diff --git a/README.md b/README.md index 76221321..9442b4aa 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ Coding agents burn context fast in unfamiliar repositories: running broad text searches, opening half-related files, and chasing call chains one file at a time. Vera gives an agent (or a developer in a terminal) direct paths to the relevant symbols. Ask what a piece of code does, where a type is defined, or who calls a function, and Vera returns ranked functions, classes, and call sites with file paths and line ranges. -Vera ships as a single native binary and keeps each project's index in `.vera/` with no background daemon or database server. Indexing, storage, keyword search, and code-aware ranking always run on your machine; embeddings run either locally on any CPU (`potion-code-16M-v2`, offline after one download) or through an OpenAI-compatible API such as Qwen3 embeddings plus reranking. +Vera ships as a single native binary and keeps each project's index in `.vera/` with no database server. CLI searches run as one-shot commands by default; optionally, `vera daemon` keeps search models and open index stores resident for reuse across calls. Indexing, storage, keyword search, and code-aware ranking always run on your machine; embeddings run either locally on any CPU (`potion-code-16M-v2`, offline after one download) or through an OpenAI-compatible API such as Qwen3 embeddings plus reranking. ![vera search demo](docs/assets/vera-demo.gif) diff --git a/crates/vera-cli/src/cli.rs b/crates/vera-cli/src/cli.rs index 7c8d5c1a..e165f274 100644 --- a/crates/vera-cli/src/cli.rs +++ b/crates/vera-cli/src/cli.rs @@ -73,6 +73,17 @@ pub enum Commands { vera mcp # Start MCP server on stdio")] Mcp, + /// Run a persistent local search server for `vera search` commands. + #[command(long_about = "Run a persistent local search server.\n\n\ + The daemon keeps search models and open index stores resident so \ + repeated `vera search` invocations can reuse them. In another \ + terminal, use `vera search` normally; it connects to the daemon \ + when available and otherwise performs the search locally.\n\n\ + The daemon runs in the foreground. Stop it with Ctrl-C.\n\n\ + Example:\n \ + vera daemon")] + Daemon, + /// Start the Vera HTTP API server for remote embedding and reranking. #[command(long_about = "Start the Vera HTTP API server.\n\n\ Loads the embedding model at startup and keeps it (using the \ @@ -308,17 +319,23 @@ pub enum Commands { Discovers source files (respecting .gitignore), parses them with \ tree-sitter for 61 languages, creates searchable chunks at symbol \ boundaries, generates embeddings using the current Vera mode, and \ - stores everything in a local `.vera/` index directory.\n\n\ + stores everything in a local `.vera/` index directory. If index \ + data already exists, Vera refuses to replace it unless you pass \ + `--replace`.\n\n\ Use `vera setup` for Vera's built-in local models, or `vera setup \ --api` for an OpenAI-compatible endpoint.\n\n\ Examples:\n \ vera index . # Index current directory\n \ vera index /path/to/repo # Index a specific repo\n \ + vera index . --replace # Replace an existing index\n \ vera index . --dry-run # Estimate work without writing an index\n \ vera index . --json # Output summary as JSON")] Index { /// Path to the directory to index. path: String, + /// Replace an existing index. + #[arg(long)] + replace: bool, /// Build a keyword (BM25) index without embeddings. #[arg(long)] full_text_only: bool, diff --git a/crates/vera-cli/src/commands/daemon.rs b/crates/vera-cli/src/commands/daemon.rs new file mode 100644 index 00000000..38b5ae99 --- /dev/null +++ b/crates/vera-cli/src/commands/daemon.rs @@ -0,0 +1,453 @@ +//! Persistent local search daemon and its private CLI protocol. + +#[cfg(not(unix))] +use anyhow::Result; + +type SearchOutcomeResult = anyhow::Result<( + Vec, + vera_core::retrieval::search_service::SearchTimings, +)>; +type SearchOutcomes = Vec; + +#[cfg(unix)] +mod local { + use std::collections::HashSet; + use std::fs; + use std::os::unix::fs::PermissionsExt; + use std::os::unix::net::{UnixListener as StdUnixListener, UnixStream}; + use std::path::PathBuf; + use std::sync::Arc; + + use anyhow::{Context, Result, bail}; + use serde::{Deserialize, Serialize}; + use vera_core::config::{InferenceBackend, VeraConfig}; + use vera_core::retrieval::cross_index::{IndexSearch, search_indexes}; + use vera_core::retrieval::search_service::{SearchContext, SearchTimings}; + use vera_core::types::{SearchFilters, SearchResult, SearchScope}; + + #[path = "daemon_transport.rs"] + mod transport; + + use transport::{ + SocketGuard, acquire_daemon_lock, daemon_socket_path, existing_socket_path, + read_async_frame, read_frame, remove_stale_socket, write_async_frame, write_frame, + }; + + const PROTOCOL_VERSION: u32 = 1; + + #[derive(Serialize, Deserialize)] + struct SearchRequest { + protocol_version: u32, + indexes: Vec, + queries: Vec, + intent: Option, + config: VeraConfig, + backend: InferenceBackend, + result_limit: usize, + deep: bool, + } + + #[derive(Serialize, Deserialize)] + struct SearchIndexRequest { + index_dir: PathBuf, + filters: SearchFiltersRequest, + } + + #[derive(Serialize, Deserialize)] + struct SearchFiltersRequest { + language: Option, + path_glob: Vec, + exact_paths: Option>, + symbol_type: Option, + scope: Option, + include_generated: Option, + } + + impl From<&SearchFilters> for SearchFiltersRequest { + fn from(filters: &SearchFilters) -> Self { + let mut exact_paths = filters + .exact_paths + .as_ref() + .map(|paths| paths.iter().cloned().collect::>()); + if let Some(paths) = &mut exact_paths { + paths.sort(); + } + Self { + language: filters.language.clone(), + path_glob: filters.path_glob.clone(), + exact_paths, + symbol_type: filters.symbol_type.clone(), + scope: filters.scope, + include_generated: filters.include_generated, + } + } + } + + impl From for SearchFilters { + fn from(filters: SearchFiltersRequest) -> Self { + Self { + language: filters.language, + path_glob: filters.path_glob, + exact_paths: filters + .exact_paths + .map(|paths| Arc::new(paths.into_iter().collect::>())), + symbol_type: filters.symbol_type, + scope: filters.scope, + include_generated: filters.include_generated, + } + } + } + + #[derive(Serialize, Deserialize)] + struct DaemonResponse { + protocol_version: u32, + body: ResponseBody, + } + + #[derive(Serialize, Deserialize)] + #[serde(tag = "kind", rename_all = "snake_case")] + enum ResponseBody { + Search { outcomes: Vec }, + Error { message: String }, + } + + #[derive(Serialize, Deserialize)] + #[serde(tag = "status", rename_all = "snake_case")] + enum SearchOutcome { + Success { + results: Vec, + timings: SearchTimings, + }, + Error { + message: String, + }, + } + + struct CachedContext { + key: String, + context: Arc, + } + + struct DaemonState { + context: Option, + keyword_context: Arc, + } + + impl DaemonState { + fn new() -> Self { + Self { + context: None, + keyword_context: Arc::new(SearchContext::bm25_only()), + } + } + + async fn search_context( + &mut self, + config: &VeraConfig, + backend: InferenceBackend, + ) -> Result> { + let key = format!("{backend}|{}", serde_json::to_string(config)?); + if let Some(cached) = self.context.as_ref().filter(|cached| cached.key == key) { + return Ok(Arc::clone(&cached.context)); + } + + let context = Arc::new(SearchContext::new(config, backend).await); + self.context = Some(CachedContext { + key, + context: Arc::clone(&context), + }); + Ok(context) + } + } + + /// Try the daemon before constructing any per-command search context. + /// + /// `None` means no daemon is listening and the caller should use its + /// existing local search path. Once connected, protocol/search errors are + /// returned to the user rather than retried locally. + pub(crate) fn try_search( + config: &VeraConfig, + backend: InferenceBackend, + indexes: &[(PathBuf, PathBuf, SearchFilters)], + queries: &[String], + intent: Option<&str>, + result_limit: usize, + deep: bool, + ) -> Result> { + let Some(socket_path) = existing_socket_path() else { + eprintln!("vera: local"); + return Ok(None); + }; + let mut stream = match UnixStream::connect(&socket_path) { + Ok(stream) => stream, + Err(error) + if matches!( + error.kind(), + std::io::ErrorKind::NotFound | std::io::ErrorKind::ConnectionRefused + ) => + { + eprintln!("vera: local"); + return Ok(None); + } + Err(error) => { + return Err(error).with_context(|| { + format!( + "failed to connect to Vera daemon at {}", + socket_path.display() + ) + }); + } + }; + eprintln!("vera: daemon"); + + let request = SearchRequest { + protocol_version: PROTOCOL_VERSION, + indexes: indexes + .iter() + .map(|(_, index_dir, filters)| SearchIndexRequest { + index_dir: index_dir.clone(), + filters: SearchFiltersRequest::from(filters), + }) + .collect(), + queries: queries.to_vec(), + intent: intent.map(str::to_owned), + config: config.clone(), + backend, + result_limit, + deep, + }; + write_frame(&mut stream, &request)?; + let response: DaemonResponse = read_frame(&mut stream)?; + if response.protocol_version != PROTOCOL_VERSION { + bail!( + "Vera daemon protocol mismatch (client {}, server {}). Restart the daemon with the current Vera version.", + PROTOCOL_VERSION, + response.protocol_version + ); + } + + match response.body { + ResponseBody::Search { outcomes } => Ok(Some( + outcomes + .into_iter() + .map(|outcome| match outcome { + SearchOutcome::Success { results, timings } => Ok((results, timings)), + SearchOutcome::Error { message } => Err(anyhow::anyhow!(message)), + }) + .collect(), + )), + ResponseBody::Error { message } => Err(anyhow::anyhow!("Vera daemon: {message}")), + } + } + + pub(crate) fn run() -> Result<()> { + let socket_path = daemon_socket_path()?; + let _lock = acquire_daemon_lock(&socket_path)?; + remove_stale_socket(&socket_path)?; + + let listener = StdUnixListener::bind(&socket_path) + .with_context(|| format!("failed to bind daemon socket {}", socket_path.display()))?; + fs::set_permissions(&socket_path, fs::Permissions::from_mode(0o600)) + .with_context(|| format!("failed to secure daemon socket {}", socket_path.display()))?; + listener.set_nonblocking(true)?; + let _socket_guard = SocketGuard(socket_path.clone()); + + eprintln!( + "Vera search daemon listening at {}. Press Ctrl-C to stop.", + socket_path.display() + ); + + let runtime = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .context("failed to create daemon runtime")?; + runtime.block_on(async move { + let listener = tokio::net::UnixListener::from_std(listener) + .context("failed to initialize daemon listener")?; + let mut state = DaemonState::new(); + let shutdown = tokio::signal::ctrl_c(); + tokio::pin!(shutdown); + + loop { + tokio::select! { + signal = &mut shutdown => { + signal.context("failed to listen for Ctrl-C")?; + break; + } + accepted = listener.accept() => { + match accepted { + Ok((stream, _)) => { + if let Err(error) = handle_client(stream, &mut state).await { + tracing::warn!(%error, "daemon request failed"); + } + } + Err(error) => tracing::warn!(%error, "failed to accept daemon connection"), + } + } + } + } + Ok(()) + }) + } + + async fn handle_client( + mut stream: tokio::net::UnixStream, + state: &mut DaemonState, + ) -> Result<()> { + let request: SearchRequest = read_async_frame(&mut stream).await?; + eprintln!( + "search request: queries={}, indexes={}", + request.queries.len(), + request.indexes.len() + ); + let response = process_search(state, request).await; + write_async_frame(&mut stream, &response).await + } + + async fn process_search(state: &mut DaemonState, request: SearchRequest) -> DaemonResponse { + if request.protocol_version != PROTOCOL_VERSION { + return error_response(format!( + "protocol mismatch (client {}, server {})", + request.protocol_version, PROTOCOL_VERSION + )); + } + if request.indexes.is_empty() { + return error_response("search request contains no indexes"); + } + + let mut prepared = Vec::with_capacity(request.indexes.len()); + let mut outcomes = std::iter::repeat_with(|| None) + .take(request.indexes.len()) + .collect::>>(); + for (index, request_index) in request.indexes.into_iter().enumerate() { + match vera_core::indexing::is_full_text_only(&request_index.index_dir) { + Ok(full_text_only) => prepared.push(( + index, + request_index.index_dir, + SearchFilters::from(request_index.filters), + full_text_only, + )), + Err(error) if index == 0 => return error_response(format!("{error:#}")), + Err(error) => { + outcomes[index] = Some(SearchOutcome::Error { + message: format!("{error:#}"), + }); + } + } + } + + let context = if prepared + .iter() + .any(|(_, _, _, full_text_only)| !full_text_only) + { + match state.search_context(&request.config, request.backend).await { + Ok(context) => context, + Err(error) => return error_response(format!("{error:#}")), + } + } else { + Arc::clone(&state.keyword_context) + }; + + let index_searches = prepared + .iter() + .map(|(_, index_dir, filters, _)| IndexSearch { + context: &context, + index_dir, + filters, + }) + .collect::>(); + let search_results = match search_indexes( + &index_searches, + &request.queries, + request.intent.as_deref(), + &request.config, + request.result_limit, + request.deep, + ) + .await + { + Ok(results) => results, + Err(error) => return error_response(format!("{error:#}")), + }; + for ((original_index, _, _, _), result) in prepared.into_iter().zip(search_results) { + outcomes[original_index] = Some(match result { + Ok((results, timings)) => SearchOutcome::Success { results, timings }, + Err(error) => SearchOutcome::Error { + message: format!("{error:#}"), + }, + }); + } + + DaemonResponse { + protocol_version: PROTOCOL_VERSION, + body: ResponseBody::Search { + outcomes: outcomes + .into_iter() + .map(|outcome| outcome.expect("every index has a search outcome")) + .collect(), + }, + } + } + + fn error_response(message: impl Into) -> DaemonResponse { + DaemonResponse { + protocol_version: PROTOCOL_VERSION, + body: ResponseBody::Error { + message: message.into(), + }, + } + } + + #[cfg(test)] + mod tests { + use super::*; + + #[test] + fn search_filters_wire_round_trip_preserves_exact_paths() { + let filters = SearchFilters { + language: Some("rust".into()), + path_glob: vec!["src/**".into()], + exact_paths: Some(Arc::new(HashSet::from([ + "src/main.rs".into(), + "src/lib.rs".into(), + ]))), + symbol_type: Some("function".into()), + scope: Some(SearchScope::Source), + include_generated: Some(false), + }; + + let restored = SearchFilters::from(SearchFiltersRequest::from(&filters)); + assert_eq!(restored.language, filters.language); + assert_eq!(restored.path_glob, filters.path_glob); + assert_eq!(restored.exact_paths, filters.exact_paths); + assert_eq!(restored.symbol_type, filters.symbol_type); + assert_eq!(restored.scope, filters.scope); + assert_eq!(restored.include_generated, filters.include_generated); + } + } +} + +#[cfg(unix)] +pub(crate) use local::{run, try_search}; + +#[cfg(not(unix))] +pub(crate) fn run() -> Result<()> { + anyhow::bail!("`vera daemon` is currently supported on Unix platforms only") +} + +#[cfg(not(unix))] +pub(crate) fn try_search( + _config: &vera_core::config::VeraConfig, + _backend: vera_core::config::InferenceBackend, + _indexes: &[( + std::path::PathBuf, + std::path::PathBuf, + vera_core::types::SearchFilters, + )], + _queries: &[String], + _intent: Option<&str>, + _result_limit: usize, + _deep: bool, +) -> Result> { + Ok(None) +} diff --git a/crates/vera-cli/src/commands/daemon/local/daemon_transport.rs b/crates/vera-cli/src/commands/daemon/local/daemon_transport.rs new file mode 100644 index 00000000..6b2ec395 --- /dev/null +++ b/crates/vera-cli/src/commands/daemon/local/daemon_transport.rs @@ -0,0 +1,168 @@ +//! Unix socket setup, peer framing, and the daemon singleton lock. + +use std::fs::{self, File, OpenOptions}; +use std::io::{Read, Write}; +use std::os::fd::AsRawFd; +use std::os::unix::fs::{FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt}; +use std::os::unix::net::UnixStream; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result, bail}; +use serde::{Deserialize, Serialize}; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; + +const MAX_FRAME_SIZE: usize = 64 * 1024 * 1024; + +pub(super) fn existing_socket_path() -> Option { + let path = daemon_dir().ok()?.join("daemon.sock"); + let metadata = fs::symlink_metadata(&path).ok()?; + metadata.file_type().is_socket().then_some(path) +} + +pub(super) fn daemon_socket_path() -> Result { + let directory = daemon_dir()?; + fs::create_dir_all(&directory) + .with_context(|| format!("failed to create daemon directory {}", directory.display()))?; + let metadata = fs::symlink_metadata(&directory) + .with_context(|| format!("failed to inspect daemon directory {}", directory.display()))?; + // SAFETY: getuid has no preconditions and only reads the current process uid. + let current_uid = unsafe { libc::getuid() }; + if !metadata.is_dir() || metadata.uid() != current_uid { + bail!( + "daemon directory {} must be a directory owned by the current user", + directory.display() + ); + } + fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)) + .with_context(|| format!("failed to secure daemon directory {}", directory.display()))?; + + let path = directory.join("daemon.sock"); + if path.as_os_str().as_encoded_bytes().len() >= 100 { + bail!( + "daemon socket path is too long: {}. Set XDG_RUNTIME_DIR to a shorter private directory.", + path.display() + ); + } + Ok(path) +} + +pub(super) fn acquire_daemon_lock(socket_path: &Path) -> Result { + let lock_path = socket_path.with_extension("lock"); + let lock = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .mode(0o600) + .open(&lock_path) + .with_context(|| format!("failed to open daemon lock {}", lock_path.display()))?; + // SAFETY: `lock` owns a valid file descriptor for the lock file and the + // nonblocking exclusive lock is released automatically when it is dropped. + let result = unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }; + if result == -1 { + let error = std::io::Error::last_os_error(); + if error.kind() == std::io::ErrorKind::WouldBlock { + bail!("Vera daemon is already running"); + } + return Err(error).context("failed to acquire daemon lock"); + } + Ok(lock) +} + +pub(super) fn remove_stale_socket(socket_path: &Path) -> Result<()> { + match fs::symlink_metadata(socket_path) { + Ok(metadata) if metadata.file_type().is_socket() => { + fs::remove_file(socket_path).with_context(|| { + format!( + "failed to remove stale daemon socket {}", + socket_path.display() + ) + })?; + } + Ok(_) => bail!( + "refusing to replace non-socket daemon path {}", + socket_path.display() + ), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => { + return Err(error).with_context(|| { + format!("failed to inspect daemon socket {}", socket_path.display()) + }); + } + } + Ok(()) +} + +pub(super) struct SocketGuard(pub(super) PathBuf); + +impl Drop for SocketGuard { + fn drop(&mut self) { + if let Err(error) = fs::remove_file(&self.0) + && error.kind() != std::io::ErrorKind::NotFound + { + tracing::warn!(path = %self.0.display(), %error, "failed to remove daemon socket"); + } + } +} + +pub(super) fn write_frame(stream: &mut UnixStream, value: &impl Serialize) -> Result<()> { + let payload = serde_json::to_vec(value).context("failed to encode daemon request")?; + if payload.len() > MAX_FRAME_SIZE { + bail!("daemon request exceeds the {MAX_FRAME_SIZE}-byte limit"); + } + let length = u32::try_from(payload.len()).context("daemon request is too large")?; + stream.write_all(&length.to_be_bytes())?; + stream.write_all(&payload)?; + stream.flush()?; + Ok(()) +} + +pub(super) fn read_frame Deserialize<'de>>(stream: &mut UnixStream) -> Result { + let mut length = [0_u8; 4]; + stream.read_exact(&mut length)?; + let length = u32::from_be_bytes(length) as usize; + if length > MAX_FRAME_SIZE { + bail!("daemon response exceeds the {MAX_FRAME_SIZE}-byte limit"); + } + let mut payload = vec![0; length]; + stream.read_exact(&mut payload)?; + serde_json::from_slice(&payload).context("failed to decode daemon response") +} + +pub(super) async fn read_async_frame Deserialize<'de>>( + stream: &mut (impl AsyncRead + Unpin), +) -> Result { + let mut length = [0_u8; 4]; + stream.read_exact(&mut length).await?; + let length = u32::from_be_bytes(length) as usize; + if length > MAX_FRAME_SIZE { + bail!("daemon request exceeds the {MAX_FRAME_SIZE}-byte limit"); + } + let mut payload = vec![0; length]; + stream.read_exact(&mut payload).await?; + serde_json::from_slice(&payload).context("failed to decode daemon request") +} + +pub(super) async fn write_async_frame( + stream: &mut (impl AsyncWrite + Unpin), + value: &impl Serialize, +) -> Result<()> { + let payload = serde_json::to_vec(value).context("failed to encode daemon response")?; + if payload.len() > MAX_FRAME_SIZE { + bail!("daemon response exceeds the {MAX_FRAME_SIZE}-byte limit"); + } + let length = u32::try_from(payload.len()).context("daemon response is too large")?; + stream.write_all(&length.to_be_bytes()).await?; + stream.write_all(&payload).await?; + stream.flush().await?; + Ok(()) +} + +fn daemon_dir() -> Result { + let base = std::env::var_os("XDG_RUNTIME_DIR") + .filter(|value| !value.is_empty()) + .map(PathBuf::from) + .or_else(dirs::cache_dir) + .context("could not determine a local runtime directory")?; + Ok(base.join("vera")) +} diff --git a/crates/vera-cli/src/commands/index.rs b/crates/vera-cli/src/commands/index.rs index 70982623..ac19f6be 100644 --- a/crates/vera-cli/src/commands/index.rs +++ b/crates/vera-cli/src/commands/index.rs @@ -18,6 +18,7 @@ use crate::state; pub struct CommandOptions { pub backend: InferenceBackend, + pub replace: bool, pub exclude: Vec, pub no_ignore: bool, pub no_default_excludes: bool, @@ -32,6 +33,7 @@ impl CommandOptions { pub fn new(backend: InferenceBackend) -> Self { Self { backend, + replace: false, exclude: Vec::new(), no_ignore: false, no_default_excludes: false, @@ -71,6 +73,7 @@ pub fn execute( ) -> anyhow::Result> { let CommandOptions { backend, + replace, exclude, no_ignore, no_default_excludes, @@ -94,6 +97,16 @@ pub fn execute( Hint: vera index expects a directory path, not a file." ); } + let repo_root = repo_path + .canonicalize() + .with_context(|| format!("failed to resolve path: {path}"))?; + let index_dir = vera_core::indexing::index_dir(&repo_root); + if !dry_run && !replace && index_dir.exists() { + bail!( + "index data already exists at {}. Refusing to replace it; pass `--replace` to rebuild this index.", + index_dir.display() + ); + } let rt = tokio::runtime::Runtime::new() .map_err(|e| anyhow::anyhow!("failed to create async runtime: {e}"))?; @@ -145,7 +158,7 @@ pub fn execute( let tracker = std::sync::Mutex::new(vera_core::indexing::progress::HonestProgressTracker::new()); let task = rt.handle().spawn(async move { - vera_core::indexing::pipeline::index_repository_with_progress_and_cancellation( + vera_core::indexing::index_repository_with_progress_and_cancellation_with_replace( &task_repo_path, provider.as_deref(), &config, @@ -156,6 +169,7 @@ pub fn execute( progress_reporter.observe(display, tracker.fixed_total()); }, &task_cancellation, + replace, ) .await }); @@ -234,13 +248,14 @@ pub fn execute( let task_repo_path = repo_path.to_path_buf(); let signal = wait_for_interrupt(rt.handle())?; let task = rt.handle().spawn(async move { - vera_core::indexing::pipeline::index_repository_with_progress_and_cancellation( + vera_core::indexing::index_repository_with_progress_and_cancellation_with_replace( &task_repo_path, provider.as_deref(), &config, &model_name, on_progress, &task_cancellation, + replace, ) .await }); diff --git a/crates/vera-cli/src/commands/mod.rs b/crates/vera-cli/src/commands/mod.rs index e32885f7..4782c0d7 100644 --- a/crates/vera-cli/src/commands/mod.rs +++ b/crates/vera-cli/src/commands/mod.rs @@ -5,6 +5,7 @@ pub mod agent; pub mod config; +pub mod daemon; pub mod doctor; pub mod explain_path; pub mod grep; diff --git a/crates/vera-cli/src/commands/search.rs b/crates/vera-cli/src/commands/search.rs index cffad49b..20819dbe 100644 --- a/crates/vera-cli/src/commands/search.rs +++ b/crates/vera-cli/src/commands/search.rs @@ -88,53 +88,92 @@ pub fn run( Err(err) => eprintln!("warning: skipped {}: {err}", root.display()), } } - let (rt, modes, embedded, prepared) = timing::timed("setup", || -> anyhow::Result<_> { - let rt = tokio::runtime::Runtime::new() - .map_err(|e| anyhow::anyhow!("failed to create async runtime: {e}"))?; - let mut modes = Vec::new(); - let mut ready = Vec::new(); - for (i, (root, index, repo_filters)) in prepared.into_iter().enumerate() { - match vera_core::indexing::is_full_text_only(&index) { - Ok(mode) => { - modes.push(mode); - ready.push((root, index, repo_filters)); - } - Err(err) if i == 0 => return Err(err), - Err(err) => eprintln!("warning: skipped {}: {err}", root.display()), - } - } - let embedded = if modes.contains(&false) { - Some(rt.block_on(SearchContext::new(&config, backend))) - } else { - None - }; - Ok((rt, modes, embedded, ready)) - })?; - let keyword = SearchContext::bm25_only(); - let indexes: Vec<_> = prepared - .iter() - .zip(&modes) - .map(|((_, index_dir, filters), keyword_only)| IndexSearch { - context: if *keyword_only { - &keyword - } else { - embedded - .as_ref() - .expect("embedded context initialized for semantic indexes") - }, - index_dir, - filters, - }) - .collect(); - let search_start = Instant::now(); - let outcomes = rt.block_on(search_indexes( - &indexes, + let daemon_start = Instant::now(); + let daemon_outcomes = crate::commands::daemon::try_search( + &config, + backend, + &prepared, &queries, intent, - &config, result_limit, deep, - ))?; + )?; + let (outcomes, search_elapsed) = if let Some(outcomes) = daemon_outcomes { + (outcomes, daemon_start.elapsed()) + } else { + let (rt, modes, embedded, setup_errors) = + timing::timed("setup", || -> anyhow::Result<_> { + let rt = tokio::runtime::Runtime::new() + .map_err(|e| anyhow::anyhow!("failed to create async runtime: {e}"))?; + let mut modes = Vec::with_capacity(prepared.len()); + let mut setup_errors = Vec::with_capacity(prepared.len()); + for (i, (_, index, _)) in prepared.iter().enumerate() { + match vera_core::indexing::is_full_text_only(index) { + Ok(mode) => { + modes.push(Some(mode)); + setup_errors.push(None); + } + Err(err) if i == 0 => return Err(err), + Err(err) => { + modes.push(None); + setup_errors.push(Some(format!("{err:#}"))); + } + } + } + let embedded = if modes.contains(&Some(false)) { + Some(rt.block_on(SearchContext::new(&config, backend))) + } else { + None + }; + Ok((rt, modes, embedded, setup_errors)) + })?; + let keyword = SearchContext::bm25_only(); + let valid_indexes: Vec<_> = prepared + .iter() + .zip(&modes) + .filter_map(|((_, index_dir, filters), mode)| { + mode.map(|keyword_only| IndexSearch { + context: if keyword_only { + &keyword + } else { + embedded + .as_ref() + .expect("embedded context initialized for semantic indexes") + }, + index_dir, + filters, + }) + }) + .collect(); + let searched_indexes: Vec<_> = modes + .iter() + .enumerate() + .filter_map(|(index, mode)| mode.is_some().then_some(index)) + .collect(); + let search_start = Instant::now(); + let searched_outcomes = rt.block_on(search_indexes( + &valid_indexes, + &queries, + intent, + &config, + result_limit, + deep, + ))?; + let mut outcomes: Vec<_> = setup_errors + .into_iter() + .map(|error| error.map_or_else(|| None, |message| Some(Err(anyhow::anyhow!(message))))) + .collect(); + for (index, outcome) in searched_indexes.into_iter().zip(searched_outcomes) { + outcomes[index] = Some(outcome); + } + ( + outcomes + .into_iter() + .map(|outcome| outcome.expect("every prepared index has a search outcome")) + .collect(), + search_start.elapsed(), + ) + }; let mut timings = SearchTimings::default(); let mut lists = Vec::with_capacity(outcomes.len()); let mut searched = Vec::new(); @@ -153,7 +192,7 @@ pub fn run( } } } - timings.total = Some(search_start.elapsed()); + timings.total = Some(search_elapsed); let cross_mode = searched.len() > 1; let merged = merge_results(lists, result_limit); let roots: Vec<_> = prepared.iter().map(|(root, _, _)| root.clone()).collect(); diff --git a/crates/vera-cli/src/main.rs b/crates/vera-cli/src/main.rs index 7d6a93dd..1ced9a0a 100644 --- a/crates/vera-cli/src/main.rs +++ b/crates/vera-cli/src/main.rs @@ -63,7 +63,10 @@ fn main() { } }; #[cfg(unix)] - if !matches!(cli.command, Commands::Mcp | Commands::Serve { .. }) { + if !matches!( + cli.command, + Commands::Mcp | Commands::Daemon | Commands::Serve { .. } + ) { // Let `vera stats | head` end quietly, as other CLI tools do, instead of // panicking on a closed stdout. Servers keep Rust's default so a client // that disconnects mid-write cannot kill them. @@ -110,6 +113,7 @@ fn main() { let show_nudges = !matches!( cli.command, Commands::Mcp + | Commands::Daemon | Commands::Serve { .. } | Commands::Agent { .. } | Commands::Uninstall @@ -123,6 +127,10 @@ fn main() { commands::mcp::run(); Ok(()) } + Commands::Daemon => { + tracing::info!("starting local search daemon"); + commands::daemon::run() + } Commands::Serve { port, host, @@ -211,6 +219,7 @@ fn main() { } Commands::Index { path, + replace, full_text_only, dry_run, backend, @@ -227,6 +236,7 @@ fn main() { cli.json, commands::index::CommandOptions { backend: backend.resolve(), + replace, exclude, no_ignore, no_default_excludes, diff --git a/crates/vera-cli/tests/daemon.rs b/crates/vera-cli/tests/daemon.rs new file mode 100644 index 00000000..393a1abd --- /dev/null +++ b/crates/vera-cli/tests/daemon.rs @@ -0,0 +1,148 @@ +#![cfg(unix)] + +use std::fs; +use std::io::Read; +use std::os::unix::fs::FileTypeExt; +use std::path::Path; +use std::process::{Child, Command, Stdio}; +use std::thread; +use std::time::{Duration, Instant}; + +struct RunningDaemon(Child); + +impl RunningDaemon { + fn stop(&mut self) { + if self.0.try_wait().expect("check daemon status").is_none() { + // SAFETY: the child PID is valid while the Child is running. + let result = unsafe { libc::kill(self.0.id() as i32, libc::SIGINT) }; + assert_eq!(result, 0, "send Ctrl-C to daemon"); + let status = self.0.wait().expect("wait for daemon shutdown"); + assert!(status.success(), "daemon exited with {status}"); + } + } +} + +impl Drop for RunningDaemon { + fn drop(&mut self) { + if self.0.try_wait().ok().flatten().is_none() { + self.0.kill().expect("kill test daemon"); + self.0.wait().expect("reap test daemon"); + } + } +} + +fn assert_search(binary: &Path, home: &Path, runtime: &Path, repo: &Path, expected_mode: &str) { + let output = Command::new(binary) + .arg("-C") + .arg(repo) + .args(["search", "persistent_daemon_marker", "--json"]) + .env("HOME", home) + .env("XDG_RUNTIME_DIR", runtime) + .output() + .expect("run vera search"); + assert!( + output.status.success(), + "search failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert!( + String::from_utf8_lossy(&output.stderr).contains(expected_mode), + "search stderr did not indicate {expected_mode:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + let results: serde_json::Value = + serde_json::from_slice(&output.stdout).expect("parse JSON search results"); + assert!( + results.to_string().contains("persistent_daemon_marker"), + "search did not return the indexed marker: {results}" + ); +} + +#[test] +fn cli_search_uses_daemon_and_falls_back_when_it_is_absent() { + let temp = tempfile::tempdir().expect("create temporary test directory"); + let repo = temp.path().join("repo"); + let runtime = temp.path().join("runtime"); + let home = temp.path().join("home"); + fs::create_dir_all(&repo).unwrap(); + fs::create_dir_all(&runtime).unwrap(); + fs::create_dir_all(&home).unwrap(); + fs::write( + repo.join("marker.rs"), + "pub fn persistent_daemon_marker() {}\n", + ) + .unwrap(); + let binary = Path::new(env!("CARGO_BIN_EXE_vera")); + + let index = Command::new(binary) + .arg("index") + .arg(&repo) + .args(["--full-text-only", "--no-progress", "--json"]) + .env("HOME", &home) + .env("XDG_RUNTIME_DIR", &runtime) + .output() + .expect("index test repository"); + assert!( + index.status.success(), + "index failed: {}", + String::from_utf8_lossy(&index.stderr) + ); + + assert_search(binary, &home, &runtime, &repo, "vera: local"); + + let mut daemon = RunningDaemon( + Command::new(binary) + .arg("daemon") + .env("HOME", &home) + .env("XDG_RUNTIME_DIR", &runtime) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() + .expect("start daemon"), + ); + let socket_path = runtime.join("vera/daemon.sock"); + let deadline = Instant::now() + Duration::from_secs(10); + while Instant::now() < deadline { + if fs::symlink_metadata(&socket_path).is_ok_and(|metadata| metadata.file_type().is_socket()) + { + break; + } + if daemon.0.try_wait().expect("check daemon status").is_some() { + let mut stderr = String::new(); + if let Some(mut pipe) = daemon.0.stderr.take() { + let _ = pipe.read_to_string(&mut stderr); + } + panic!("daemon exited before listening: {stderr}"); + } + thread::sleep(Duration::from_millis(25)); + } + assert!( + fs::symlink_metadata(&socket_path).is_ok_and(|metadata| metadata.file_type().is_socket()), + "daemon socket did not appear" + ); + + assert_search(binary, &home, &runtime, &repo, "vera: daemon"); + assert_search(binary, &home, &runtime, &repo, "vera: daemon"); + daemon.stop(); + let mut daemon_logs = String::new(); + daemon + .0 + .stderr + .as_mut() + .expect("capture daemon logs") + .read_to_string(&mut daemon_logs) + .expect("read daemon logs"); + assert!( + daemon_logs + .matches("search request: queries=1, indexes=1") + .count() + >= 2, + "daemon should log both incoming searches: {daemon_logs}" + ); + assert!( + !socket_path.exists(), + "daemon socket should be removed after shutdown" + ); + + assert_search(binary, &home, &runtime, &repo, "vera: local"); +} diff --git a/crates/vera-cli/tests/full_text_only.rs b/crates/vera-cli/tests/full_text_only.rs index 1ecc51a2..e7cf477a 100644 --- a/crates/vera-cli/tests/full_text_only.rs +++ b/crates/vera-cli/tests/full_text_only.rs @@ -108,7 +108,7 @@ fn full_text_only_commands_need_no_embedding_configuration() { assert!(!repo.join(".vera/vectors.db").exists()); let stats = run(&["stats"]); assert!(String::from_utf8_lossy(&stats.stdout).contains("full-text only")); - let summary = run(&["index", ".", "--full-text-only"]); + let summary = run(&["index", ".", "--full-text-only", "--replace"]); let summary = String::from_utf8_lossy(&summary.stdout); assert!(summary.contains("full-text only")); assert!(!summary.contains("Embeddings generated")); diff --git a/crates/vera-cli/tests/index_replace.rs b/crates/vera-cli/tests/index_replace.rs new file mode 100644 index 00000000..4bfd4612 --- /dev/null +++ b/crates/vera-cli/tests/index_replace.rs @@ -0,0 +1,67 @@ +use std::path::Path; +use std::process::{Command, Output}; + +use tempfile::TempDir; + +fn run(repo: &Path, temp: &TempDir, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_vera")) + .current_dir(repo) + .env_clear() + .env("PATH", std::env::var_os("PATH").unwrap_or_default()) + .env("HOME", temp.path().join("home")) + .env("VERA_HOME", temp.path().join("vera-home")) + .env("TMPDIR", temp.path()) + .env("VERA_NO_UPDATE_CHECK", "1") + .env("VERA_BACKEND", "api") + .args(args) + .output() + .unwrap() +} + +#[test] +fn existing_index_requires_replace_and_dry_run_does_not_replace() { + let temp = tempfile::tempdir().unwrap(); + let repo = temp.path().join("repo"); + std::fs::create_dir_all(&repo).unwrap(); + std::fs::write(repo.join("main.rs"), "pub fn indexed() {}\n").unwrap(); + + let initial = run(&repo, &temp, &["index", ".", "--full-text-only", "--json"]); + assert!( + initial.status.success(), + "{}", + String::from_utf8_lossy(&initial.stderr) + ); + + let sentinel = repo.join(".vera/sentinel"); + std::fs::write(&sentinel, "preserve until explicit replace").unwrap(); + let dry_run = run( + &repo, + &temp, + &["index", ".", "--full-text-only", "--dry-run", "--json"], + ); + assert!( + dry_run.status.success(), + "{}", + String::from_utf8_lossy(&dry_run.stderr) + ); + assert!(sentinel.exists()); + + let refused = run(&repo, &temp, &["index", ".", "--full-text-only", "--json"]); + assert!(!refused.status.success()); + let stderr = String::from_utf8_lossy(&refused.stderr); + assert!(stderr.contains("Refusing to replace it"), "{stderr}"); + assert!(stderr.contains("--replace"), "{stderr}"); + assert!(sentinel.exists()); + + let replaced = run( + &repo, + &temp, + &["index", ".", "--full-text-only", "--replace", "--json"], + ); + assert!( + replaced.status.success(), + "{}", + String::from_utf8_lossy(&replaced.stderr) + ); + assert!(!sentinel.exists()); +} diff --git a/crates/vera-core/src/indexing/mod.rs b/crates/vera-core/src/indexing/mod.rs index 67f601e3..cf681b67 100644 --- a/crates/vera-core/src/indexing/mod.rs +++ b/crates/vera-core/src/indexing/mod.rs @@ -24,7 +24,8 @@ pub use estimate::{IndexEstimate, estimate_index}; pub use freshness::{IndexFreshness, detect_staleness}; pub use pipeline::{ FULL_TEXT_ONLY_MODE, FileError, INDEX_MODE_KEY, IndexProgress, IndexSummary, index_dir, - index_repository, index_repository_with_progress, is_full_text_only, + index_repository, index_repository_with_progress, + index_repository_with_progress_and_cancellation_with_replace, is_full_text_only, }; pub use update::{ UpdateOptions, UpdateProgress, UpdateSummary, content_hash, update_repository, diff --git a/crates/vera-core/src/indexing/pipeline.rs b/crates/vera-core/src/indexing/pipeline.rs index 034d27f1..9ae2fcf5 100644 --- a/crates/vera-core/src/indexing/pipeline.rs +++ b/crates/vera-core/src/indexing/pipeline.rs @@ -248,7 +248,33 @@ where P: EmbeddingProvider, F: Fn(IndexProgress) + Send + Sync, { - index_repository_with_progress_and_cancellation_with_window_target( + index_repository_with_progress_and_cancellation_with_replace( + repo_path, + provider, + config, + model_name, + on_progress, + cancellation, + true, + ) + .await +} + +/// Index a repository, refusing to replace existing index data unless opted in. +pub async fn index_repository_with_progress_and_cancellation_with_replace( + repo_path: &Path, + provider: Option<&P>, + config: &VeraConfig, + model_name: &str, + on_progress: F, + cancellation: &CancellationToken, + replace_existing: bool, +) -> Result +where + P: EmbeddingProvider, + F: Fn(IndexProgress) + Send + Sync, +{ + index_repository_with_progress_and_cancellation_with_window_target_and_replace( repo_path, provider, config, @@ -256,12 +282,14 @@ where on_progress, cancellation, WINDOW_CHUNK_TARGET, + replace_existing, ) .await } /// Run the full-index pipeline with an explicit chunk-window target. /// Production uses `WINDOW_CHUNK_TARGET`; tests lower it to exercise staging windows. +#[cfg(test)] pub(crate) async fn index_repository_with_progress_and_cancellation_with_window_target( repo_path: &Path, provider: Option<&P>, @@ -271,6 +299,33 @@ pub(crate) async fn index_repository_with_progress_and_cancellation_with_window_ cancellation: &CancellationToken, window_chunk_target: usize, ) -> Result +where + P: EmbeddingProvider, + F: Fn(IndexProgress) + Send + Sync, +{ + index_repository_with_progress_and_cancellation_with_window_target_and_replace( + repo_path, + provider, + config, + model_name, + on_progress, + cancellation, + window_chunk_target, + true, + ) + .await +} + +async fn index_repository_with_progress_and_cancellation_with_window_target_and_replace( + repo_path: &Path, + provider: Option<&P>, + config: &VeraConfig, + model_name: &str, + on_progress: F, + cancellation: &CancellationToken, + window_chunk_target: usize, + replace_existing: bool, +) -> Result where P: EmbeddingProvider, F: Fn(IndexProgress) + Send + Sync, @@ -306,6 +361,12 @@ where let _index_lock = crate::indexing::lock::IndexLock::acquire_blocking_for_index_dir(&idx_dir) .context("failed to acquire index lock")?; recover_index_directories(&idx_dir).context("failed to recover index directories")?; + if idx_dir.exists() && !replace_existing { + bail!( + "index data already exists at {}. Refusing to replace it; pass `--replace` to rebuild this index.", + idx_dir.display() + ); + } let checkpoint = provider .and_then(|provider| EmbeddingCheckpoint::for_provider(&idx_dir, provider, model_name)); diff --git a/crates/vera-core/src/indexing/pipeline_tests.rs b/crates/vera-core/src/indexing/pipeline_tests.rs index e7d54a7f..96fa5ba8 100644 --- a/crates/vera-core/src/indexing/pipeline_tests.rs +++ b/crates/vera-core/src/indexing/pipeline_tests.rs @@ -445,6 +445,33 @@ async fn failed_window_keeps_live_index_and_cleans_staging() { assert!(!sibling_index_dir(&idx_dir, "old").exists()); } +#[tokio::test] +async fn index_without_replace_refuses_existing_index_data() { + let dir = TempDir::new().unwrap(); + let idx_dir = index_dir(dir.path()); + fs::create_dir_all(&idx_dir).unwrap(); + fs::write(idx_dir.join("sentinel"), "previous index").unwrap(); + + let provider = MockProvider::new(8); + let error = index_repository_with_progress_and_cancellation_with_replace( + dir.path(), + Some(&provider), + &default_config(), + "mock-model", + |_| {}, + &CancellationToken::new(), + false, + ) + .await + .unwrap_err(); + + assert!(error.to_string().contains("Refusing to replace it")); + assert_eq!( + fs::read_to_string(idx_dir.join("sentinel")).unwrap(), + "previous index" + ); +} + #[test] fn stale_staging_and_old_index_are_recovered_on_startup() { let dir = TempDir::new().unwrap(); diff --git a/crates/vera-core/src/retrieval/reranker.rs b/crates/vera-core/src/retrieval/reranker.rs index 6ac39ebe..02a1a791 100644 --- a/crates/vera-core/src/retrieval/reranker.rs +++ b/crates/vera-core/src/retrieval/reranker.rs @@ -12,8 +12,9 @@ use std::collections::HashSet; use std::time::Duration; +use serde::{Deserialize, Serialize}; + use anyhow::{Context, Result}; -use serde::Deserialize; use tokio_util::sync::CancellationToken; use tracing::{debug, warn}; @@ -31,7 +32,8 @@ use crate::types::SearchResult; pub const RERANKER_INSTRUCTION_FIELD: &str = "instruction"; /// Reranking diagnostics for one search or an aggregated request. -#[derive(Debug, Clone, Default, PartialEq, Eq)] +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "status", content = "reason", rename_all = "snake_case")] pub enum RerankOutcome { #[default] NotAttempted, diff --git a/crates/vera-core/src/retrieval/search_service.rs b/crates/vera-core/src/retrieval/search_service.rs index bdba115f..bab95dc3 100644 --- a/crates/vera-core/src/retrieval/search_service.rs +++ b/crates/vera-core/src/retrieval/search_service.rs @@ -9,6 +9,7 @@ use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use anyhow::Result; +use serde::{Deserialize, Serialize}; use tokio::sync::OnceCell; use tracing::warn; @@ -24,7 +25,7 @@ use crate::retrieval::{RerankOutcome, apply_filters, search_bm25_with_stores_and use crate::types::{SearchFilters, SearchResult}; /// Timing data for each stage of the search pipeline. -#[derive(Debug, Default)] +#[derive(Debug, Default, Serialize, Deserialize)] pub struct SearchTimings { pub rerank_outcome: RerankOutcome, /// Why semantic search was skipped or failed, leaving BM25-only results. diff --git a/docs/features.md b/docs/features.md index c7495124..ca3e3c01 100644 --- a/docs/features.md +++ b/docs/features.md @@ -44,6 +44,16 @@ vera search "config" --intent "find where database connection strings are loaded `--intent` adds your goal to a short or ambiguous query so ranking can aim at what you need. +### Reuse search state across CLI calls + +For repeated searches, start the foreground daemon in one terminal: + +```bash +vera daemon +``` + +In another terminal, keep using `vera search` normally. It connects to the local daemon when available, reusing loaded models and open index stores; if no daemon is running, search uses the usual one-shot CLI path. Stop the daemon with Ctrl-C. This currently uses a Unix-domain socket and is supported on Unix platforms. + ### Deep search ```bash @@ -131,6 +141,13 @@ Regex search over indexed files, with the same filters and git scopes as `vera s ## Indexing +`vera index` refuses to replace existing index data by default. To deliberately +rebuild an existing index, pass `--replace`: + +```bash +vera index . --replace +``` + ### Dry run ```bash @@ -147,7 +164,7 @@ vera index . --full-text-only Build a keyword (BM25) index without configuring or loading an embedding model. Grep, structural queries, references, and overview work exactly as with an embedded index. Search ranks by keyword match only, so queries that describe behavior in plain words find less than they would with embeddings. `vera update` and watch mode keep the index keyword-only. -Run `vera index .` without the flag to rebuild with embeddings. +Run `vera index . --replace` to rebuild an existing keyword-only index with embeddings. ### Symbol-aware chunks diff --git a/docs/llama-cpp-setup.md b/docs/llama-cpp-setup.md index c08a45ca..6822e555 100644 --- a/docs/llama-cpp-setup.md +++ b/docs/llama-cpp-setup.md @@ -114,7 +114,7 @@ export VERA_COMPLETION_MAX_TOKENS=16384 export VERA_COMPLETION_TIMEOUT_SECS=120 ``` -After changing `indexing.max_chunk_bytes`, run `vera index .` so every file is chunked with the new limit. +After changing `indexing.max_chunk_bytes`, run `vera index . --replace` so every file is chunked with the new limit. ## 7. Use it from an MCP client diff --git a/docs/migration-v2.md b/docs/migration-v2.md index 6b840686..97ba806c 100644 --- a/docs/migration-v2.md +++ b/docs/migration-v2.md @@ -36,10 +36,10 @@ vera config set embedding.timeout_secs 60 ## Indexing and search behavior -- Saved `embedding.query_prefix` and `embedding.document_prefix` values now reach API requests; earlier versions ignored them. If you saved a prefix, rebuild with `vera index` so stored vectors match new queries. +- Saved `embedding.query_prefix` and `embedding.document_prefix` values now reach API requests; earlier versions ignored them. If you saved a prefix, rebuild with `vera index . --replace` so stored vectors match new queries. - Saved `indexing.no_ignore`, `indexing.no_default_excludes`, and `indexing.extra_excludes` now apply when the matching flags are not given; earlier versions reset them on every run. `--exclude` now adds to saved globs instead of replacing them. - A failed API `vera index` leaves `/.vera.resume/` so the next run can reuse finished embeddings. -- An index left half-written by an interrupted `vera update` is refused until `vera update` or `vera index` repairs it. +- An index left half-written by an interrupted `vera update` is refused until `vera update` or `vera index . --replace` repairs it. - Index and update summaries gain request, retry, timeout, and phase-time fields; existing fields are unchanged. Slow runs print progress to stderr even when stderr is not a terminal. `--no-progress` turns this off. - When `retrieval.reranking_enabled` is true but no reranker is configured, or the reranker cannot start, search prints `reranker unavailable` on stderr and returns unreranked results. - Error messages from embedding, reranker, and completion APIs no longer include endpoint URLs. diff --git a/docs/models.md b/docs/models.md index f6791423..bf90088e 100644 --- a/docs/models.md +++ b/docs/models.md @@ -191,7 +191,7 @@ vera setup --onnx-jina-cuda \ ## Changing models -The index records which embedding model built it, including every `--embedding-*` setting, so changing the model, pooling, or a prefix requires a rebuild with `vera index .`. +The index records which embedding model built it, including every `--embedding-*` setting, so changing the model, pooling, or a prefix requires a rebuild with `vera index . --replace`. If two model names produce identical embeddings (the same model behind two endpoints, for example), declare them as aliases to skip the rebuild. Set `embedding.model_aliases` or export `VERA_EMBEDDING_MODEL_ALIASES`: groups separated by semicolons, names within a group separated by commas, at least two names per group. diff --git a/docs/supported-languages.md b/docs/supported-languages.md index a1fe4f95..62236193 100644 --- a/docs/supported-languages.md +++ b/docs/supported-languages.md @@ -157,5 +157,5 @@ not expand macros, select build configurations, or replace compiler-based analysis. Other errors remain visible. Indexed content and line numbers always come from the original source, including annotations and linkage guards. -Rebuild existing indexes with `vera index .` after upgrading to pick up parser +Rebuild existing indexes with `vera index . --replace` after upgrading to pick up parser changes in unchanged files. `vera update .` alone skips unchanged source files. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 29ae3f89..89d9c578 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -58,7 +58,7 @@ For linked git worktrees, see [automatic worktree indexes](features.md#linked-wo the index at ... is incomplete because an update stopped before it finished writing ``` -A `vera update` was interrupted. Vera refuses to read the partial index. Run `vera update .` to repair it or `vera index .` to rebuild. +A `vera update` was interrupted. Vera refuses to read the partial index. Run `vera update .` to repair it or `vera index . --replace` to rebuild. ### `.vera/` shows up in git @@ -111,7 +111,7 @@ The [query guide](query-guide.md) has more examples. A stderr warning ending in `using BM25-only search` or `falling back to BM25-only results`, or `warning: semantic search unavailable (...)` in an MCP result, means vector search did not run and results come from keyword matching alone. The message gives the cause: - The embedding endpoint failed, for example an expired key or a provider outage. See [API mode](#api-mode). -- The index was built with a different embedding model or document prefix than the active one, or with more dimensions than the active model returns. Rebuild with `vera index .`. +- The index was built with a different embedding model or document prefix than the active one, or with more dimensions than the active model returns. Rebuild with `vera index . --replace`. - The index has no stored vectors, for example because `.vera/vectors.db` was deleted. Run `vera update .` to re-embed the missing files. ### Reranker unavailable @@ -152,7 +152,7 @@ Error messages never contain the endpoint URL or keys. They name the underlying Vera retries connection errors, 408, 429, and 5xx responses with backoff, honoring `Retry-After` up to 60 seconds. A 400 response containing `Unable to process`, which some providers send when overloaded, is retried the same way. Other 4xx responses, including authentication errors, fail immediately. When indexing fails, stderr ends with request, retry, and timeout counts followed by the error. -Run `vera index .` again. An API build resumes from the embeddings it already received. +Run `vera index . --replace` again. An API build resumes from the embeddings it already received. ### Rate limits and quota errors @@ -172,7 +172,7 @@ Vera already caps known provider limits, such as 100 inputs per request for Gemi ### The index uses a different embedding model -If the active model name differs from the one stored in the index, rebuild with `vera index .`. If the two names are the same model, declare them as aliases instead; see [Changing models](models.md#changing-models). +If the active model name differs from the one stored in the index, rebuild with `vera index . --replace`. If the two names are the same model, declare them as aliases instead; see [Changing models](models.md#changing-models). ## Local GPU and ONNX backends diff --git a/skills/vera/SKILL.md b/skills/vera/SKILL.md index 20e319f9..afb14cea 100644 --- a/skills/vera/SKILL.md +++ b/skills/vera/SKILL.md @@ -34,6 +34,10 @@ Use the following in indexed repositories. Without an index, follow [Recovery](# Narrow callers or callees with `vera references make_config --path 'src/**/*.rs'`; repeat `--path` to include several patterns, just as with search. +## Reuse search state across CLI calls + +For repeated searches, optionally start `vera daemon` in a foreground terminal. It keeps search models and open index stores resident; other `vera search` commands connect to it automatically, or run normally when no daemon is available. Stop it with Ctrl-C. The daemon currently uses a Unix-domain socket and is supported on Unix platforms. + ## Search well - Search behavior, not nouns: `"JWT expiry handling"`, not `"auth"` or `"utils"`. @@ -59,11 +63,12 @@ Narrow callers or callees with `vera references make_config --path 'src/**/*.rs' ## Recovery -If you will work in a code repository without an index, run `vera index .` from its root. A first index can take several minutes: use a long shell timeout or run it in the background, and use rg until it finishes. An interrupted API-mode run reuses its finished embeddings. Otherwise, or without shell access, use your usual search tools. +If you will work in a code repository without an index, run `vera index .` from its root. A first index can take several minutes: use a long shell timeout or run it in the background, and use rg until it finishes. An interrupted API-mode run reuses its finished embeddings. If index data already exists, `vera index` stops rather than replacing it; use `vera index . --replace` only when a deliberate full rebuild is needed. For ordinary source changes, prefer `vera update .`. Otherwise, or without shell access, use your usual search tools. | Symptom | Fix | |---------|-----| | `no index found` | Follow the indexing and fallback guidance above | +| `index data already exists` | Use `vera index . --replace` only for an intentional full rebuild; use `vera update .` for normal changes | | `no indexed file matches ` | Use a root-relative `--path`; stderr suggests a wildcard directory form when one applies | | Stale results after edits | `vera update .` (or `vera watch .`); works from any subdirectory | | A file is missing from results | `vera explain-path path/to/file` |