ivygrep

github.com/bvolpato/ivygrep at commit 8cc4d45ddb. 84,921 lines of source in 138 files, and 6 documents. Here: 3,233 words, about 14 min.

Each cited line exists. Of 45 arrows, the syntax proves 33, 5 fit by name, and 7 are inferred. No second reader judged the statements. Captured 30 Nov 2026.

Answer

The parts, and who calls whomcalls that the syntax provesa link that a flow shows
Daemon to Workspace: 120 callsDaemon to Search: 67 callsCLI to Daemon: 52 callsCLI to Vectors: 26 callsCLI to Indexing: 20 callsDaemon to Indexing: 14 callsMCP to Daemon: 10 callsDaemon to Context: 1 callsWorkspace to CLI: 1 callsIndexing to Workspace: 212 callsSearch to Indexing: 63 callsIndexing to Vectors: 25 callsWeb to Workspace: 7 callsDaemon to CLI: in a flow below, and the syntax does not prove itCLI7.0kParses commands, picks thedaemon or a local run, andprints results; also the…CLI: Parses commands, picks the daemon or a local run, and prints results; also the terminal UI, doctor, hardware report, and agent setup 6,979 lines.MCP2.5kAnswers JSON-RPC requests ofcoding agents over stdioMCP: Answers JSON-RPC requests of coding agents over stdio 2,529 lines.Web4.2kServes the browser UI and itsHTTP API, and opens browsersand editorsWeb: Serves the browser UI and its HTTP API, and opens browsers and editors 4,235 lines.Daemon9.4kKeeps watchers, leases,caches, the worker queue, andgarbage collection in one…Daemon: Keeps watchers, leases, caches, the worker queue, and garbage collection in one background process 9,446 lines.Workspace3.9kResolves a directory to anindex, names its files…called by 8 of 8 partsWorkspace: Resolves a directory to an index, names its files, checks its health, walks and reads source files 3,892 lines.Indexing12kFinds changed files, splitsthem into chunks, and commitsthem to SQLite and TantivyIndexing: Finds changed files, splits them into chunks, and commits them to SQLite and Tantivy 11,566 lines.Vectors3.4kEmbeds chunks and queries,stores vectors, and admits…called by 5 of 8 partsVectors: Embeds chunks and queries, stores vectors, and admits the worker processes that build them 3,362 lines.Search16kFinds, fuses, reranks, andpresents hits for a querySearch: Finds, fuses, reranks, and presents hits for a query 15,902 lines.Context6.4kBuilds a token-bounded packof evidence for a taskContext: Builds a token-bounded pack of evidence for a task 6,418 lines.
A script counted these calls. The picture has 14 of 46 links, and this table has all, each with an example
FromToCallsExample
IndexingWorkspace212prepare_indexed_chunk → index_path_string src/indexer.rs:176
DaemonWorkspace120deadline_warning → search_deadline src/daemon.rs:140
CLIWorkspace118normalize_glob_args → parse_glob_csv src/cli.rs:376
SearchWorkspace101regex_search_with_options → new src/regex_search.rs:162
DaemonSearch67finish_daemon_search_batch → finish src/daemon.rs:119
SearchIndexing63index_prefilter_files → open_tantivy_index src/regex_search.rs:366
ContextWorkspace55context_seed_content → open src/context.rs:691
CLIDaemon52run → run_daemon src/cli.rs:567
CLISearch42run_query → select_search_workspaces src/cli.rs:1928
CLIVectors26run → admit_worker src/cli.rs:655
IndexingVectors25validate_existing_index_storage → read_count src/indexer.rs:1124
ContextIndexing23cached_seed_chunks → chunk_source src/context.rs:81
CLIIndexing20run → require_type_alias src/cli.rs:466
MCPWorkspace16serve_stdio → ensure_app_dirs src/mcp.rs:181
ContextSearch15cached_seed_chunks → new src/context.rs:56
DaemonIndexing14cached_search_context → reconcile_worktree_overlay_with_store_replacement src/daemon.rs:2926
WorkspaceDaemon14is_watcher_alive → job_status src/workspace.rs:820
VectorsWorkspace11acquire → lock_path src/indexer/enhancement.rs:19
IndexingContext10spawn_index_batch_producer → extract_file_graph_with_trees src/indexer.rs:440
MCPDaemon10cancel → request_blocking src/mcp.rs:676
WorkspaceVectors10neural_model_identity → read_identity src/workspace.rs:498
ContextDaemon9build_context_bundle_with_search_context → start src/context.rs:253
MCPSearch8execute_ivygrep_search → search_symbols_with_options src/mcp.rs:2001
SearchVectors8validate_forced_neural_workspaces → configured_neural_model_identity src/search.rs:133
WebWorkspace7open_browser → app_home src/launcher.rs:354
IndexingDaemon6remove_workspace_index_contents → read_base_ref src/indexer.rs:628
MCPIndexing6ensure_mcp_workspace_ready → workspace_is_indexed src/mcp.rs:1406
WorkspaceIndexing6has_indexed_file_below → open_sqlite_readonly src/workspace.rs:1211
DaemonVectors5create_search_model → create_model src/daemon.rs:1797
DaemonWeb5start_web_server → bind_addr src/daemon.rs:3606
MCPVectors4mcp_query_model → create_neural_model src/mcp.rs:1354
WebDaemon4respond → handle_web_request src/web.rs:286
CLIMCP3run → serve_stdio src/cli.rs:611
CLIWeb2run → open_browser src/cli.rs:604
VectorsIndexing2embed → singularize_token src/embedding.rs:691
IndexingSearch2remove_file_chunks → remove_file_graph src/indexer.rs:3499
WorkspaceSearch2list_workspaces_with_warnings → runtime_status src/workspace.rs:2034
CLIContext1run_query → build_context_bundle_with_options src/cli.rs:1997
ContextVectors1build_context_bundle_with_search_context → new src/context.rs:258
DaemonContext1handle_request_with_cancellation → build_context_bundle_with_search_context src/daemon.rs:5475
MCPCLI1execute_ivygrep_search → refuse_broad_build src/mcp.rs:1794
MCPContext1local_context_pack → build_context_bundle_with_options src/mcp.rs:2171
SearchDaemon1collect_semantic_vector_matches → start src/search.rs:4555
WebContext1build_context_pack → build_context_bundle_with_options src/web.rs:953
WorkspaceCLI1indexed_plain_ancestor → is_broad_root src/workspace.rs:1798
DaemonCLInot proveda step of a flow below

The parts

PartWhat it doesStart withQuotes
CLIParses ig commands, sends a search to the daemon or runs it here, and starts the terminal UI.run, run_query
MCPRuns the tool calls of one agent session, one at a time, in a worker thread.serve, execute_ivygrep_search
WebChecks the session and answers the HTTP API of the browser UI inside the daemon.respond, web/src/main.ts
DaemonServes requests on a local socket, watches files, and starts background work.run_daemon_inner, handle_request_with_cancellation
WorkspaceTurns a path into a root, an ID, and an index directory.Workspace.resolve, source_walker_scoped
IndexingCompares files with the last snapshot, chunks them, and commits the text stores.index_workspace_inner
VectorsCreates embedding models and admits the workers that embed chunks.EmbeddingModel, admit_worker
SearchRuns the retrieval passes for a query, fuses them, and makes hits.search_hits, SearchContext
ContextCollects evidence for a task and cuts it to the token budget.build_context_bundle_with_search_context

CLI

MCP

Web

Daemon

Workspace

Indexing

Vectors

Context

What happens when

A search from the command line

  1. CLI run_query → CLI resolve_query_workspace finds the workspace and an optional path scope. 2
    src/cli.rs:1602
    1602let (workspace, resolved_scope_filter) = resolve_query_workspace(&cli, &query_path)?;
    src/cli.rs:3190-3202
    3190pub(crate) fn resolve_query_workspace(
    3191    cli: &Cli,
    3192    path: &Path,
    3193) -> Result<(Workspace, Option<crate::workspace::WorkspaceScope>)> {
    3194    let (workspace, scope, base) = resolve_workspace_and_scope_with_base(path)?;
    3195    if !cli.all_indices
    3196        && !cli.yes
    3197        && let Some(base) = base
    3198    {
    3199        confirm_broad_build(&base, false, cli.skip_gitignore)?;
    3200    }
    3201    Ok((workspace, scope))
    3202}
  2. If the search is not over all indexes and the index is missing or unhealthy, run_query sends DaemonRequest::Index, and it lets this request start a daemon unless --no-watch is given. 7
    src/cli.rs:1655-1659
    1655if !cli.all_indices {
    1656    let first_run = matches!(initial_index_state, Some(WorkspaceIndexState::NotIndexed));
    1657    let needs_repair = matches!(initial_index_state, Some(WorkspaceIndexState::Unhealthy));
    1658    if first_run || needs_repair {
    1659        // Always show progress for first-run, even when the daemon handles it.
    src/cli.rs:1674-1689
    1674let daemon_index_request = DaemonRequest::Index {
    1675    path: workspace.root.clone(),
    1676    watch: !cli.no_watch,
    1677    skip_gitignore: cli.skip_gitignore,
    1678};
    1679
    1680// Send the index request to the daemon, but show a progress spinner
    1681// while we wait so the user knows work is happening.
    1682let ws_id = workspace.id.clone();
    1683let show_progress = std::io::stderr().is_terminal();
    1684
    1685let response_future = daemon::request::<fn(String, usize, usize)>(
    1686    &daemon_index_request,
    1687    !cli.no_watch,
    1688    None,
    1689);
    src/daemon.rs:6992-6996
    6992pub async fn request<F>(
    6993    request: &DaemonRequest,
    6994    autospawn: bool,
    6995    progress_cb: Option<F>,
    6996) -> Result<Option<DaemonResponse>>
    src/daemon.rs:7010
    7010request_unchecked(request, autospawn, progress_cb).await
    src/daemon.rs:7278-7287
    7278async fn request_unchecked_with_id<F>(
    7279    request: &DaemonRequest,
    7280    request_id: Option<uuid::Uuid>,
    7281    autospawn: bool,
    7282    mut progress_cb: Option<F>,
    7283) -> Result<Option<DaemonResponse>>
    7284where
    7285    F: FnMut(String, usize, usize) + Send,
    7286{
    7287    let Some(mut stream) = connect_to_daemon(autospawn).await else {
    src/daemon.rs:7243-7244
    7243for attempt in 0..2 {
    7244    spawn_daemon_if_missing(autospawn).await;
    src/daemon.rs:7164-7170
    7164async fn spawn_daemon_if_missing(autospawn: bool) {
    7165    if !autospawn
    7166        || crate::ipc::socket_exists()
    7167        || std::env::var_os("IVYGREP_NO_AUTOSPAWN").is_some()
    7168    {
    7169        return;
    7170    }
  3. CLI run_query → Daemon request_with_id sends DaemonRequest::Search with a new ID, after a check that the daemon is compatible. 4
    src/cli.rs:2239
    2239let search_future = daemon::request_with_id::<fn(String, usize, usize)>(
    src/daemon.rs:7022-7023
    7022ensure_compatible_daemon().await;
    7023request_unchecked_with_id(request, Some(request_id), autospawn, progress_cb).await
    src/cli.rs:2208-2210
    2208let request = DaemonRequest::Search {
    2209    path: query_path_opt.clone(),
    2210    query: query.to_string(),
    src/cli.rs:2239-2244
    2239let search_future = daemon::request_with_id::<fn(String, usize, usize)>(
    2240    &request,
    2241    uuid::Uuid::new_v4(),
    2242    false,
    2243    None,
    2244);
  4. Daemon request_unchecked_with_id ⇢ Daemon handle_client_request the client writes a JSON line to the socket, and the server races the search against a disconnect and a deadline. inferred 5
    src/daemon.rs:7295-7303
    7295let payload = serde_json::to_vec(&envelope)?;
    7296if payload.len() > MAX_DAEMON_REQUEST_BYTES {
    7297    anyhow::bail!("daemon request exceeds maximum of {MAX_DAEMON_REQUEST_BYTES} bytes");
    7298}
    7299// Timeout writes too — a zombie daemon may accept the connection
    7300// but never read from it, causing writes to eventually block.
    7301match tokio::time::timeout(DAEMON_WRITE_TIMEOUT, async {
    7302    stream.write_all(&payload).await?;
    7303    stream.write_all(b"\n").await?;
    src/daemon.rs:4032-4040
    4032let deadline = (!matches!(envelope.request, DaemonRequest::ContextPack { .. }))
    4033    .then(config::search_deadline)
    4034    .flatten();
    4035let handler = handle_request_with_cancellation(
    4036    state,
    4037    envelope.request,
    4038    cancellation.clone(),
    4039    RequestOrigin::Local,
    4040);
    src/daemon.rs:4058-4090
    4058loop {
    4059    tokio::select! {
    4060        biased;
    4061        response = &mut handler => {
    4062            drop(registration);
    4063            return if client_disconnected {
    4064                ClientRequestOutcome::Disconnected
    4065            } else {
    4066                ClientRequestOutcome::Respond(response)
    4067            };
    4068        }
    4069        peek = reader.fill_buf(), if watch_client => {
    4070            watch_client = false;
    4071            match peek {
    4072                // Pipelined bytes: the client is alive and waiting.
    4073                Ok(buffered) if !buffered.is_empty() => {}
    4074                Ok(_) | Err(_) => {
    4075                    client_disconnected = true;
    15 more lines
    src/ipc.rs:263-266
    263pub async fn connect() -> std::io::Result<IpcStream> {
    264    let path = socket_path().map_err(|e| std::io::Error::other(e.to_string()))?;
    265    IpcStream::connect(path).await
    266}
    src/daemon.rs:3976-3989
    3976let mut reader = BufReader::new(stream);
    3977loop {
    3978    // Bound the whole request line, so trickled bytes do not extend it.
    3979    // The handler below runs without this bound.
    3980    let Ok(request) =
    3981        tokio::time::timeout(idle_timeout, read_daemon_request(&mut reader)).await
    3982    else {
    3983        tracing::debug!("closing daemon connection that sent no request in time");
    3984        return Ok(());
    3985    };
    3986    let (response, keep_alive) = match request {
    3987        Ok(Some(envelope)) => {
    3988            let _in_flight = state.activity.begin();
    3989            match handle_client_request(state.clone(), envelope, &mut reader).await {
  5. Daemon handle_client_request → Daemon handle_request_with_cancellation takes the leases and then a CPU permit. 3
    src/daemon.rs:4035
    4035let handler = handle_request_with_cancellation(
    src/daemon.rs:4731-4747
    4731// Workspace leases come before the CPU permit: a search parked
    4732// behind an exclusive index lease must not pin CPU capacity.
    4733let search_leases = match state_clone
    4734    .acquire_search_leases(
    4735        &workspaces,
    4736        options.skip_gitignore,
    4737        cancellation.as_ref(),
    4738        origin,
    4739    )
    4740    .await
    4741{
    4742    Ok(Some(leases)) => leases,
    4743    Ok(None) => {
    4744        return cancelled_search_outcome(cancellation.as_ref(), workspace_warnings);
    4745    }
    4746    Err(response) => return response,
    4747};
    src/daemon.rs:4778-4785
    4778// Bound concurrent heavy search work (see #58). The permit is held
    4779// for the whole blocking task and released when it completes.
    4780let Some(permit) = state_clone
    4781    .acquire_search_permit(cancellation.as_ref())
    4782    .await
    4783else {
    4784    return cancelled_search_outcome(cancellation.as_ref(), workspace_warnings);
    4785};
  6. It returns a cached result only if no hit is dropped because its file is confirmed missing. 4
    src/daemon.rs:4864-4876
    4864if let Some(mut cached_hits) =
    4865    state_clone.cached_query_results(&cache_key, cache_revision)
    4866{
    4867    let cached_hit_count = cached_hits.len();
    4868    crate::search_service::retain_live_hits(&mut cached_hits, &workspaces);
    4869    // Cached results are already limited. Removing any hit
    4870    // requires a new search to promote live candidates.
    4871    if cached_hits.len() == cached_hit_count {
    4872        let cancelled = options.is_cancelled();
    4873        if !cancelled {
    4874            state_clone.schedule_search_enhancement(workspaces.clone(), policy);
    4875        }
    4876        return (
    src/search_service.rs:103-127
    103fn retain_live_hits_with_roots(
    104    hits: &mut Vec<SearchHit>,
    105    roots: &[(&Path, crate::workspace_file::RootHandle)],
    106) {
    107    let mut missing_paths = std::collections::HashMap::with_capacity(hits.len());
    108    let mut buffer = Vec::with_capacity(256);
    109    let keep = hits
    110        .iter()
    111        .map(|hit| {
    112            let workspace = if hit.file_path.is_absolute() {
    113                roots
    114                    .iter()
    115                    .find(|(root, _)| hit.file_path.starts_with(root))
    116            } else {
    117                roots.first()
    118            };
    119            workspace.is_none_or(|(_, files)| {
    120                !*missing_paths
    7 more lines
    src/workspace_file.rs:125-129
    125pub(crate) fn is_missing_with_buffer(&self, path: &Path, buffer: &mut Vec<u8>) -> bool {
    126    // Presence does not authorize a live read. A successful presence check
    127    // rules out confirmed absence; errors still need the contained opener,
    128    // which distinguishes deletion from an unsafe symlink or denied access.
    129    // Once opened, keep observing the pinned directory if its path changes.
    src/workspace_file.rs:150-152
    150    self.open(path)
    151        .is_err_and(|error| error.kind() == io::ErrorKind::NotFound)
    152}
  7. Daemon handle_request_with_cancellation → Search hybrid_search_with_context_and_neural_job calls search_hits, which runs literal, BM25, symbol, path, and vector passes. name match 7
    src/daemon.rs:4939
    4939match hybrid_search_with_context_and_neural_job(
    src/search_execution.rs:16-26
    16let mut warnings = Vec::new();
    17let hits = search_hits(
    18    ctx,
    19    workspace,
    20    query_text,
    21    embedding_model,
    22    options,
    23    neural_query_vector_job,
    24    &mut warnings,
    25)?;
    26Ok(SearchOutcome { hits, warnings })
    src/search_execution.rs:146-149
    146// ── Literal pass ────────────────────────────────────────────────────
    147// Always run a fast index-backed literal substring scan so exact matches
    148// surface even when tokenization splits them differently.
    149// Build a regex alternation of the original query plus snake_case/camelCase
    src/search_execution.rs:210-213
    210// ── Lexical (BM25) pass ─────────────────────────────────────────────
    211// BM25F: search across text, tokenized file path, and definition signature.
    212// Boosts on path/signature fields implement Sourcegraph-style BM25F where
    213// matches on filenames and symbol definitions count 5× more than body text.
    src/search_execution.rs:340-342
    340// Exact persisted symbol definitions provide a separate bounded rank
    341// signal. This avoids inferring every definition solely from text while
    342// keeping symbol lookup independent from the main candidate volume.
    src/search_execution.rs:405-408
    405// ── Path-match pass ──────────────────────────────────────────────────
    406// Collect chunks whose file_path contains the query as a directory/file
    407// name. This ensures "my-service" finds files under
    408// apps/my-service/ even when the code-content BM25 candidates are
    src/search_execution.rs:609
    609if embedding_model.is_some() && (has_hash_vectors || neural_model.is_some()) {
  8. Search search_hits → Search fuse_rrf_with_context adds the lexical, semantic, literal, path, and symbol votes for each chunk. name match 4
    src/search_execution.rs:827
    827let merged = fuse_rrf_with_context(
    src/search_fusion.rs:294-304
    294let mut entries: HashMap<u64, RrfEntry> = HashMap::new();
    295let mut add_entry = |chunk: IndexedChunk, score: f32, sources: SourceMask| {
    296    let vector_key = chunk.vector_key;
    297    let entry = entries.entry(vector_key).or_insert_with(|| RrfEntry {
    298        score: 0.0,
    299        chunk,
    300        sources: 0,
    301    });
    302    entry.score += score;
    303    entry.sources |= sources;
    304};
    src/search_fusion.rs:338-344
    338add_entry(
    339    chunk,
    340    LEXICAL_WEIGHT / (K + rank as f32 + 1.0)
    341        + normalize_lexical_score(lexical_score) * LEXICAL_SCORE_WEIGHT
    342        + lexical_margin,
    343    source_bit("lexical"),
    344);
    src/search_fusion.rs:409-450
    409    add_entry(
    410        chunk,
    411        direct_weight * (rank_vote + similarity_bonus),
    412        semantic_source_mask,
    413    );
    414}
    415
    416// Literal pass: verified exact substring matches get a strong boost
    417for (rank, (chunk, _)) in literal.into_iter().enumerate() {
    418    add_entry(
    419        chunk,
    420        LITERAL_WEIGHT / (K + rank as f32 + 1.0),
    421        source_bit("literal"),
    422    );
    423}
    424
    425// Path pass: chunks whose file path matches the query, ranked by their
    426// path-field BM25 score. Rank-based only — no raw-score magnitude term —
    24 more lines
  9. Search search_hits → Search rerank_hits reorders with the learned model, only for the literal or error intent, and only with five files or more. 3
    src/search_execution.rs:902
    902crate::reranker::rerank_hits(query_text, trimmed, &mut hits[..accepted_len]);
    src/reranker.rs:316-335
    316pub(crate) fn rerank_hits<T: RerankInput>(requested_query: &str, query: &str, hits: &mut [T]) {
    317    if configured_mode().0 == Mode::Deterministic {
    318        capture_skipped(requested_query, "deterministic-mode");
    319        return;
    320    }
    321    let file_count = hits
    322        .iter()
    323        .map(|hit| &hit.ranking_hit().file_path)
    324        .collect::<HashSet<_>>()
    325        .len();
    326    if file_count < 5 {
    327        capture_skipped(requested_query, "fewer-than-five-files");
    328        return;
    329    }
    330    let Ok(model) = load_model() else {
    331        capture_skipped(requested_query, "model-unavailable");
    332        return;
    333    };
    2 more lines
    src/search_execution.rs:897-905
    897if matches!(routing.intent, QueryIntent::LiteralOrError) {
    898    let accepted_len = hits
    899        .iter()
    900        .position(|hit| hit.hit.sources.iter().any(|source| source == "backfill"))
    901        .unwrap_or(hits.len());
    902    crate::reranker::rerank_hits(query_text, trimmed, &mut hits[..accepted_len]);
    903} else {
    904    crate::reranker::capture_skipped(query_text, "route-not-learned");
    905}
  10. Daemon handle_request_with_cancellation → Search retain_live_hits drops hits of missing files; if not cancelled, the handler schedules enhancement, and it caches the hits if there are also no errors. 5
    src/daemon.rs:4976
    4976crate::search_service::retain_live_hits(&mut all_hits, &workspaces);
    src/search_service.rs:78-89
    78pub(crate) fn retain_live_hits(hits: &mut Vec<SearchHit>, workspaces: &[Workspace]) {
    79    if hits.is_empty() || workspaces.is_empty() {
    80        return;
    81    }
    82    if let [workspace] = workspaces {
    83        let roots = [(
    84            workspace.root.as_path(),
    85            crate::workspace_file::RootHandle::new(&workspace.root),
    86        )];
    87        retain_live_hits_with_roots(hits, &roots);
    88        return;
    89    }
    src/search_service.rs:103-127
    103fn retain_live_hits_with_roots(
    104    hits: &mut Vec<SearchHit>,
    105    roots: &[(&Path, crate::workspace_file::RootHandle)],
    106) {
    107    let mut missing_paths = std::collections::HashMap::with_capacity(hits.len());
    108    let mut buffer = Vec::with_capacity(256);
    109    let keep = hits
    110        .iter()
    111        .map(|hit| {
    112            let workspace = if hit.file_path.is_absolute() {
    113                roots
    114                    .iter()
    115                    .find(|(root, _)| hit.file_path.starts_with(root))
    116            } else {
    117                roots.first()
    118            };
    119            workspace.is_none_or(|(_, files)| {
    120                !*missing_paths
    7 more lines
    src/workspace_file.rs:150-152
    150    self.open(path)
    151        .is_err_and(|error| error.kind() == io::ErrorKind::NotFound)
    152}
    src/daemon.rs:4979-4988
    4979let cancelled = options.is_cancelled();
    4980if !cancelled && let Some((query, completed)) = neural_query_cache_write {
    4981    state_clone.store_completed_neural_query(query, &completed, &options);
    4982}
    4983if !cancelled && all_errors.is_empty() {
    4984    state_clone.store_query_results(cache_key, &all_hits, cache_revision);
    4985}
    4986// Background hash and neural enhancement runs off the response path.
    4987if !cancelled {
    4988    state_clone.schedule_search_enhancement(workspaces.clone(), policy);

An agent asks for a context pack

  1. MCP execute_ivygrep_search → MCP ensure_mcp_workspace_ready continues at once if the workspace is indexed, its watcher is alive, and no refresh for ignored files is needed. 3
    src/mcp.rs:1800
    1800if let WorkspaceReadiness::Indexing(payload) = ensure_mcp_workspace_ready(
    src/mcp.rs:1406-1411
    1406if workspace_is_indexed(workspace)
    1407    && workspace.is_watcher_alive()
    1408    && !needs_ignored_refresh(workspace, include_ignored)?
    1409{
    1410    return Ok(WorkspaceReadiness::Ready);
    1411}
    src/mcp.rs:1386-1388
    1386/// Re-index when the caller wants ignored files but the index excludes them.
    1387fn needs_ignored_refresh(workspace: &Workspace, include_ignored: bool) -> Result<bool> {
    1388    let metadata = workspace.read_metadata()?;
  2. MCP ensure_mcp_workspace_ready ⇢ Daemon handle_request_with_cancellation sends StartIndex over the socket, and the daemon starts one run, or reports the run in flight, and answers at once. inferred 6
    src/mcp.rs:1416-1425
    1416let start_request = DaemonRequest::StartIndex {
    1417    path: workspace.root.clone(),
    1418    watch: true,
    1419    skip_gitignore: include_ignored,
    1420};
    1421let wait_started = std::time::Instant::now();
    1422match crate::daemon::request_blocking(&start_request, true)? {
    1423    Some(DaemonResponse::IndexStarted { .. }) => {
    1424        return wait_for_daemon_index(workspace, include_ignored, wait_started, cancellation);
    1425    }
    src/daemon.rs:4615-4650
    4615// Only a leader spawns work; followers (and requests whose options
    4616// differ from the in-flight run) report the existing run and let
    4617// the client poll `RuntimeStatus` until it clears.
    4618let already_running =
    4619    match state.join_or_lead_index(&workspace.id, watch, skip_gitignore) {
    4620        Some(InflightIndexSlot::Lead(lead)) => {
    4621            register_workspace_for_index(&workspace, watch, skip_gitignore);
    4622            let root = workspace.root.clone();
    4623            let arrived_at = std::time::Instant::now();
    4624            tokio::spawn(async move {
    4625                let response = run_index_request(
    4626                    state,
    4627                    workspace,
    4628                    watch,
    4629                    skip_gitignore,
    4630                    Some(lead),
    4631                    arrived_at,
    4632                    origin,
    18 more lines
    src/daemon.rs:6953-6958
    6953pub fn request_blocking(
    6954    daemon_request: &DaemonRequest,
    6955    autospawn: bool,
    6956) -> Result<Option<DaemonResponse>> {
    6957    request_blocking_with_id(daemon_request, None, autospawn)
    6958}
    src/daemon.rs:6984
    6984None => request::<fn(String, usize, usize)>(&daemon_request, autospawn, None).await,
    src/daemon.rs:7249-7250
    7249match connect_with_timeout(crate::ipc::connect(), DAEMON_CONNECT_TIMEOUT).await {
    7250    Ok(stream) => return Some(stream),
    src/ipc.rs:263-266
    263pub async fn connect() -> std::io::Result<IpcStream> {
    264    let path = socket_path().map_err(|e| std::io::Error::other(e.to_string()))?;
    265    IpcStream::connect(path).await
    266}
  3. MCP ensure_mcp_workspace_ready → MCP wait_for_daemon_index polls the status, and at the deadline (20 seconds by default) returns an indexing payload. 3
    src/mcp.rs:1424
    1424return wait_for_daemon_index(workspace, include_ignored, wait_started, cancellation);
    src/mcp.rs:1567-1576
    1567if std::time::Instant::now() >= deadline {
    1568    return Ok(WorkspaceReadiness::Indexing(indexing_status_payload(
    1569        workspace,
    1570        wait_started.elapsed(),
    1571    )));
    1572}
    1573std::thread::sleep(
    1574    poll_interval.min(deadline.saturating_duration_since(std::time::Instant::now())),
    1575);
    1576poll_interval = (poll_interval * 2).min(MCP_INDEX_POLL_MAX);
    src/config.rs:105-116
    105pub const DEFAULT_MCP_INDEX_WAIT_SECS: u64 = 20;
    106
    107/// How long an MCP tool call waits for the daemon to finish a first index
    108/// before returning an `indexing` status payload. `IVYGREP_MCP_INDEX_WAIT_SECS`
    109/// overrides the default; `0` returns immediately after enqueuing the run.
    110pub fn mcp_index_wait() -> std::time::Duration {
    111    let secs = env::var("IVYGREP_MCP_INDEX_WAIT_SECS")
    112        .ok()
    113        .and_then(|value| value.trim().parse::<u64>().ok())
    114        .unwrap_or(DEFAULT_MCP_INDEX_WAIT_SECS);
    115    std::time::Duration::from_secs(secs)
    116}
  4. MCP execute_ivygrep_search ⇢ Daemon handle_request_with_cancellation sends ContextPack over the socket, with a budget of 8,000 tokens by default. inferred 6
    src/mcp.rs:1863-1878
    1863let budget_tokens = args.budget_tokens.unwrap_or(8_000);
    1864let daemon_request = DaemonRequest::ContextPack {
    1865    path: workspace.root.clone(),
    1866    query: query.to_string(),
    1867    budget_tokens,
    1868    since: args.since.clone(),
    1869    context: search_options.context,
    1870    type_filter: args.type_filter.clone(),
    1871    include_globs: include_globs.clone(),
    1872    exclude_globs: exclude_globs.clone(),
    1873    scope_path: scope_filter.as_ref().map(|scope| scope.rel_path.clone()),
    1874    scope_is_file: scope_filter.as_ref().is_some_and(|scope| scope.is_file),
    1875    skip_gitignore: search_options.skip_gitignore,
    1876};
    1877let daemon_bundle = match cancellation.daemon_search(&daemon_request)? {
    1878    Some(DaemonResponse::ContextPack { bundle }) => Some(bundle),
    src/daemon.rs:5438-5464
    5438} => {
    5439    // The daemon builds the pack with its shared model, preview cache,
    5440    // leases, and CPU permits, so sessions do not each hold their own.
    5441    let cancellation = cancellation.unwrap_or_else(|| SearchCancellation::new(false));
    5442    let workspace = match state.resolve_workspace(&path) {
    5443        Ok(workspace) => workspace,
    5444        Err(err) => {
    5445            return DaemonResponse::Error {
    5446                message: err.to_string(),
    5447            };
    5448        }
    5449    };
    5450    let options = SearchOptions {
    5451        limit: None,
    5452        context: context.min(crate::search::MAX_SEARCH_CONTEXT_LINES),
    5453        type_filter,
    5454        include_globs,
    5455        exclude_globs,
    9 more lines
    src/mcp.rs:694
    694let response = crate::daemon::request_blocking_with_id(request, Some(search_id), false);
    src/daemon.rs:6973-6982
    6973runtime.block_on(async {
    6974    match request_id {
    6975        Some(request_id) => {
    6976            request_with_id::<fn(String, usize, usize)>(
    6977                &daemon_request,
    6978                request_id,
    6979                autospawn,
    6980                None,
    6981            )
    6982            .await
    src/daemon.rs:7249-7250
    7249match connect_with_timeout(crate::ipc::connect(), DAEMON_CONNECT_TIMEOUT).await {
    7250    Ok(stream) => return Some(stream),
    src/ipc.rs:263-266
    263pub async fn connect() -> std::io::Result<IpcStream> {
    264    let path = socket_path().map_err(|e| std::io::Error::other(e.to_string()))?;
    265    IpcStream::connect(path).await
    266}
  5. Daemon handle_request_with_cancellation → Daemon prepare_context_cancellable takes the lease, a CPU permit, and makes the workspace queryable. 4
    src/daemon.rs:5463
    5463.prepare_context_cancellable(&workspace, skip_gitignore, &cancellation, origin)
    src/daemon.rs:2581-2612
    2581let search_leases = self
    2582    .acquire_search_leases(
    2583        std::slice::from_ref(workspace),
    2584        skip_gitignore,
    2585        Some(cancellation),
    2586        origin,
    2587    )
    2588    .await
    2589    .map_err(|response| match response {
    2590        DaemonResponse::Error { message } => anyhow::anyhow!(message),
    2591        response => anyhow::anyhow!("context preparation failed: {response:?}"),
    2592    })?
    2593    .ok_or_else(|| anyhow::anyhow!("context preparation cancelled"))?;
    2594let permit = self
    2595    .acquire_search_permit(Some(cancellation))
    2596    .await
    2597    .ok_or_else(|| anyhow::anyhow!("context preparation cancelled"))?;
    2598let state = self.clone();
    14 more lines
    src/daemon.rs:2121-2137
    2121async fn acquire_search_permit(
    2122    &self,
    2123    cancellation: Option<&SearchCancellation>,
    2124) -> Option<tokio::sync::OwnedSemaphorePermit> {
    2125    let Some(cancellation) = cancellation else {
    2126        return self.acquire_cpu_permit().await;
    2127    };
    2128    if cancellation.is_cancelled() {
    2129        return None;
    2130    }
    2131    let _timer = crate::performance::StageTimer::start("foreground_cpu_wait");
    2132    tokio::select! {
    2133        biased;
    2134        () = cancellation.cancelled() => None,
    2135        permit = self.cpu_permits.clone().acquire_owned() => permit.ok(),
    2136    }
    2137}
    src/daemon.rs:2999-3006
    2999self.check_watcher_reconciliation(workspace)?;
    3000let signature = workspace_readiness_signature_with_metadata(workspace, metadata_stamp);
    3001if self.workspace_is_ready(workspace, skip_gitignore, &signature) {
    3002    return Ok(false);
    3003}
    3004
    3005let mut changed = ensure_queryable_workspace(self, workspace, skip_gitignore)?;
    3006let reconciliation_model = cached_hash_model();
  6. Daemon handle_request_with_cancellation → Context build_context_bundle_with_search_context first reconciles a stale worktree overlay. 3
    src/daemon.rs:5475
    5475let bundle = crate::context::build_context_bundle_with_search_context(
    src/context.rs:257-265
    257} else {
    258    fallback_model = HashEmbeddingModel::new(crate::EMBEDDING_DIMENSIONS);
    259    &fallback_model
    260};
    261reconcile_worktree_overlay(workspace, reconciliation_model)?;
    262
    263let input = {
    264    let _timer = crate::performance::StageTimer::start("context_input");
    265    collect_context_input(workspace, task, context_options.since, base_options)?
    src/indexer.rs:739-757
    739/// Rebuild a worktree overlay when its referenced base generation moved.
    740///
    741/// Searches call this before opening stores so stale tombstones and shadow
    742/// sets can never expose base-only files that are absent from the worktree.
    743pub fn reconcile_worktree_overlay(
    744    workspace: &Workspace,
    745    embedding_model: &dyn EmbeddingModel,
    746) -> Result<bool> {
    747    reconcile_worktree_overlay_with_store_replacement(workspace, embedding_model, &mut |_| {})
    748}
    749
    750pub(crate) fn reconcile_worktree_overlay_with_store_replacement(
    751    workspace: &Workspace,
    752    embedding_model: &dyn EmbeddingModel,
    753    before_store_replacement: &mut dyn FnMut(&Workspace),
    754) -> Result<bool> {
    755    let reset_overlay = match workspace.worktree_overlay_is_stale() {
    756        Ok(false) => return Ok(false),
    757        Ok(true) => true,
  7. Context build_context_bundle_with_search_context → Context collect_context_input turns Git changes and named paths into seeds. 5
    src/context.rs:265
    265collect_context_input(workspace, task, context_options.since, base_options)?
    src/context_input.rs:157-193
    157let (mut change_scope, seed_changes) = match collect_git_changes(&workspace.root, since)? {
    158    Some((scope, changes)) => (Some(scope), changes),
    159    None => (None, Vec::new()),
    160};
    161let mut source_paths = SourcePathMatcher::new(&workspace.root, options.skip_gitignore);
    162let mut allowed_changes = Vec::new();
    163for change in seed_changes {
    164    if path_allowed(&change.file_path) && source_paths.allows(&change.file_path)? {
    165        allowed_changes.push(change);
    166    }
    167}
    168let seed_changes = allowed_changes;
    169if let Some(scope) = &mut change_scope {
    170    scope.dirty_worktree = seed_changes.iter().any(|change| {
    171        change.sources.iter().any(|source| {
    172            matches!(
    173                source,
    174                ContextChangeSource::Staged
    19 more lines
    src/context_input.rs:194-217
    194let mut seeds = Vec::new();
    195let mut seeded_paths = BTreeSet::new();
    196for references in referenced_paths.chunk_by(|left, right| left.file_path == right.file_path) {
    197    if !workspace.root.join(&references[0].file_path).is_file() {
    198        continue;
    199    }
    200    seeded_paths.insert(references[0].file_path.clone());
    201    for (rank, reference) in seed_references(references).into_iter().enumerate() {
    202        seeds.push((
    203            rank,
    204            ContextSeed {
    205                file_path: reference.file_path.clone(),
    206                line: reference.line,
    207                git_revision: None,
    208                reason: reference.line.map_or_else(
    209                    || "mentioned in task input".to_string(),
    210                    |line| format!("mentioned at line {line} in task or stack trace"),
    211                ),
    6 more lines
    src/context_input.rs:221-227
    221for change in &seed_changes {
    222    let current_file = workspace.root.join(&change.file_path).is_file();
    223    let deleted_file = change.status == ContextChangeStatus::Deleted;
    224    if !current_file && !deleted_file || !seeded_paths.insert(change.file_path.clone()) {
    225        continue;
    226    }
    227    let sources = change
    src/context_input.rs:228-262
    228    .sources
    229    .iter()
    230    .map(|source| source.label())
    231    .collect::<Vec<_>>()
    232    .join(", ");
    233seeds.push((
    234    0,
    235    ContextSeed {
    236        file_path: change.file_path.clone(),
    237        line: None,
    238        git_revision: deleted_file.then(|| {
    239            if change.sources.iter().any(|source| {
    240                matches!(
    241                    source,
    242                    ContextChangeSource::Staged | ContextChangeSource::Worktree
    243                )
    244            }) {
    245                "HEAD".to_string()
    17 more lines
  8. Context build_context_bundle_with_search_context → Context expand_context_graph adds related files, after text search and symbol lookups gave the first candidates. 4
    src/context.rs:550
    550match expand_context_graph(workspace, search_context, &seed_paths, base_options) {
    src/context_graph.rs:2475-2483
    2475let mut edges = load_persisted_edges(workspace, search_context, &seeds)?;
    2476if edges.len() < MIN_STATIC_EDGES_BEFORE_COCHANGE {
    2477    edges.extend(recent_cochange_edges(workspace, seed_paths));
    2478}
    2479edges.sort();
    2480edges.dedup();
    2481edges.truncate(MAX_GRAPH_EDGES);
    2482
    2483let ranks = personalized_page_rank(&edges, &seeds);
    src/context.rs:386-394
    386let hits = search_task_text(search_context, workspace, &query, embedding_model, &options)?;
    387if requested_role == ContextRole::Primary {
    388    primary_hits.extend(hits.clone());
    389}
    390for (rank, hit) in hits.into_iter().enumerate() {
    391    if requested_role == ContextRole::Primary && rank > 0 && !hit_matches_task(&hit, task) {
    392        continue;
    393    }
    394    let role = classify_role(&hit, requested_role);
    src/context.rs:423-434
    423let anchor_symbols = anchor_symbols(task, &primary_hits);
    424let relationship_anchors = relationship_anchor_keys(task, &anchor_symbols);
    425let mut symbol_options = base_options.clone();
    426symbol_options.limit = Some(4);
    427symbol_options.context = 10;
    428for symbol in &anchor_symbols {
    429    match search_symbol_definitions_with_context(
    430        workspace,
    431        search_context,
    432        symbol,
    433        &symbol_options,
    434    ) {
  9. Context build_context_bundle_with_search_context → Context assemble_bundle adds items until the budget or an item limit is reached, and then removes the last items while the pack is too large. 4
    src/context.rs:622
    622let mut bundle = assemble_bundle(
    src/context.rs:1391-1395
    1391while bundle.used_tokens > bundle.budget_tokens && !bundle.items.is_empty() {
    1392    bundle.items.pop();
    1393    bundle.truncated = true;
    1394    finalize_bundle_metrics(&mut bundle);
    1395}
    src/context.rs:1301-1309
    1301for candidate in ordered {
    1302    if items.len() == MAX_ITEMS || used_tokens >= budget_tokens {
    1303        truncated = true;
    1304        break;
    1305    }
    1306    if items.len() >= TARGET_CONTEXT_ITEMS && context_roles_covered(&items, &required_roles) {
    1307        truncated = true;
    1308        break;
    1309    }
    src/context.rs:34-35
    34const MAX_ITEMS: usize = 20;
    35const TARGET_CONTEXT_ITEMS: usize = 14;

A file change reaches the index

  1. Daemon handle_watch_result → Daemon WatchEventFilter.change_for_event an ignore file of this workspace, or a new checkout over indexed files, gives a full reconciliation; other accepted paths give a set, or nothing. name match 2
    src/daemon.rs:1304
    1304Ok(event) => match event_filter.lock().change_for_event(&event) {
    src/daemon.rs:1056-1094
    1056if event.paths.iter().any(|path| {
    1057    !self
    1058        .normalize_watch_path(path)
    1059        .is_some_and(|(normalized, _)| {
    1060            crate::walker::is_ivygrep_owned_path(&self.workspace.root, &normalized)
    1061                // A nested checkout's ignore files configure that
    1062                // checkout, not this workspace.
    1063                || self
    1064                    .nested_checkouts
    1065                    .contains(&self.workspace.root, &normalized)
    1066        })
    1067        && self.is_ignore_configuration_path(path)
    1068}) {
    1069    self.refresh();
    1070    return WatchChange::FullReconciliation;
    1071}
    1072// A parent or global ignore file can change outside the watched root.
    1073// Share directory rules within this event and reload them on the next.
    21 more lines
  2. Daemon handle_watch_result → Daemon WatchControl.mark_paths_dirty merges the paths into the pending work. 2
    src/daemon.rs:1306
    1306WatchChange::Paths(paths) => control.mark_paths_dirty(paths),
    src/daemon.rs:497-506
    497let mut pending = self.pending_work.lock();
    498match &mut pending.change {
    499    WatchChange::None => pending.change = WatchChange::Paths(paths),
    500    WatchChange::Paths(existing) => existing.extend(paths),
    501    WatchChange::FullReconciliation => {}
    502}
    503self.dirty.store(true, Ordering::Relaxed);
    504self.pending_events.fetch_add(1, Ordering::Relaxed);
    505drop(pending);
    506self.notify.notify_one();
  3. Daemon WatchControl.mark_paths_dirty ⇢ Daemon spawn_watch_worker notify_one wakes the task that waits on control.notify. inferred 2
    src/daemon.rs:505-506
    505drop(pending);
    506self.notify.notify_one();
    src/daemon.rs:6156-6168
    6156loop {
    6157    control.notify.notified().await;
    6158    if !control.active.load(Ordering::Relaxed) {
    6159        break;
    6160    }
    6161
    6162    // Searches wait for startup to finish, so its updates skip the debounce.
    6163    if !control
    6164        .initial_reconciliation_pending
    6165        .load(Ordering::Relaxed)
    6166    {
    6167        wait_for_watch_quiet(&control).await;
    6168    }
  4. Daemon spawn_watch_worker → Daemon wait_for_watch_quiet waits 250 ms after one event or 750 ms after more, and at most 30 seconds. 4
    src/daemon.rs:6167
    6167wait_for_watch_quiet(&control).await;
    src/daemon.rs:6453-6465
    6453let current = control.pending_events.load(Ordering::Relaxed);
    6454let now = tokio::time::Instant::now();
    6455if current != last_seen {
    6456    last_seen = current;
    6457    last_changed = now;
    6458}
    6459
    6460let quiet_period = watch_quiet_period(current);
    6461if now.duration_since(last_changed) >= quiet_period
    6462    || now.duration_since(started) >= WATCH_MAX_DEBOUNCE
    6463{
    6464    break;
    6465}
    src/daemon.rs:47-49
    47const WATCH_SINGLE_EVENT_QUIET_PERIOD: Duration = Duration::from_millis(250);
    48const WATCH_BURST_QUIET_PERIOD: Duration = Duration::from_millis(750);
    49const WATCH_MAX_DEBOUNCE: Duration = Duration::from_secs(30);
    src/daemon.rs:6469-6475
    6469fn watch_quiet_period(pending_events: u64) -> Duration {
    6470    if pending_events <= 1 {
    6471        WATCH_SINGLE_EVENT_QUIET_PERIOD
    6472    } else {
    6473        WATCH_BURST_QUIET_PERIOD
    6474    }
    6475}
  5. The worker takes the exclusive workspace lease, and then a background CPU permit. 1
    src/daemon.rs:6255-6275
    6255            // Even a targeted update can discover damaged stores
    6256            // and replace them. Drain readers before index.lock;
    6257            // upgrading a shared lease there could deadlock an
    6258            // indexer that is waiting on that lock.
    6259            Result::<_, anyhow::Error>::Ok(lease_state.acquire_workspace_mutations(
    6260                std::slice::from_ref(&lease_workspace),
    6261            ))
    6262        })
    6263        .await
    6264        .unwrap_or_else(|join_err| Err(anyhow::anyhow!(join_err.to_string()))),
    6265    };
    6266let result = match mode_leases {
    6267    Err(err) => Err(err),
    6268    Ok(mode_leases) => {
    6269        let permit = state.acquire_background_cpu_permit().await;
    6270        let watcher_state = state.clone();
    6271        let index_control = control.clone();
    6272        tokio::task::spawn_blocking(move || {
    3 more lines
  6. Daemon spawn_watch_worker → Indexing index_workspace_with_store_replacement passes the changed paths, and a callback that releases cached readers. 4
    src/daemon.rs:6296
    6296index_workspace_with_store_replacement(
    src/indexer.rs:720-737
    720/// Index while allowing the caller to close readers immediately before a store
    721/// replacement. The caller must already exclude searches of this workspace and
    722/// its base; the index lock alone does not cover cached daemon readers.
    723pub(crate) fn index_workspace_with_store_replacement(
    724    workspace: &Workspace,
    725    embedding_model: &dyn EmbeddingModel,
    726    watcher_paths: Option<&[PathBuf]>,
    727    before_store_replacement: &mut dyn FnMut(&Workspace),
    728) -> Result<IndexingSummary> {
    729    index_workspace_with_options_and_store_replacement(
    730        workspace,
    731        embedding_model,
    732        false,
    733        watcher_paths,
    734        false,
    735        before_store_replacement,
    736    )
    737}
    src/daemon.rs:6296-6303
    6296index_workspace_with_store_replacement(
    6297    &workspace,
    6298    hash_model.as_ref(),
    6299    Some(&changed_paths),
    6300    &mut |replaced| {
    6301        watcher_state.clear_workspace_contexts(replaced)
    6302    },
    6303)?
    src/daemon.rs:3130-3147
    3130fn clear_workspace_contexts(&self, workspace: &Workspace) {
    3131    let mut affected = HashSet::from([workspace.id.clone()]);
    3132    {
    3133        let mut contexts = self.search_contexts.lock();
    3134        let keys = contexts
    3135            .iter()
    3136            .filter(|(key, cached)| {
    3137                key.workspace_id == workspace.id
    3138                    || cached.base_index_dir.as_ref() == Some(&workspace.index_dir)
    3139            })
    3140            .map(|(key, _)| {
    3141                affected.insert(key.workspace_id.clone());
    3142                key.clone()
    3143            })
    3144            .collect::<Vec<_>>();
    3145        for key in keys {
    3146            contexts.pop(&key);
    3147        }
  7. Indexing index_workspace_with_options_and_store_replacement → Indexing index_workspace_inner refreshes only those paths in the snapshot, and walks everything if that is not safe. 2
    src/indexer.rs:985
    985index_workspace_inner(
    src/indexer.rs:1460-1480
    1460let mut old = MerkleSnapshot::load(&workspace.merkle_snapshot_path())?;
    1461// Watcher events already identify changed files. Apply those directly
    1462// when safe, keeping full scans as reconciliation fallback for ignore
    1463// edits, directories, overlays, and uncertain state.
    1464let targeted = if let Some(paths) = watcher_paths.filter(|paths| !paths.is_empty())
    1465    && workspace.merkle_snapshot_path().exists()
    1466    && workspace_index_matches_skip_gitignore(workspace, skip_gitignore)
    1467{
    1468    old.refresh_paths_in_place(&workspace.root, paths, skip_gitignore)?
    1469} else {
    1470    None
    1471};
    1472let (new, d) = if let Some(diff) = targeted {
    1473    let _ = fs::write(workspace.indexing_progress_path(), "applying watcher delta");
    1474    (old, diff)
    1475} else {
    1476    let _ = fs::write(workspace.indexing_progress_path(), "scanning");
    1477    let mut new = MerkleSnapshot::build(&workspace.root, skip_gitignore)?;
    3 more lines
  8. Indexing index_workspace_inner → Indexing spawn_index_batch_producer chunks the changed files; the caller removes their old chunks unless the index is fresh, and inserts the new ones. 5
    src/indexer.rs:1786
    1786let mut producer = spawn_index_batch_producer(
    src/indexer.rs:371-380
    371let mut remaining = diff_paths.as_slice();
    372'batches: while !remaining.is_empty() {
    373    // Each batch validates the root again. Its size probes and file
    374    // reads share that walk.
    375    let files = crate::workspace_file::RootHandle::new(&root);
    376    let count = source_batch_len(&files, remaining);
    377    let (batch_paths, rest) = remaining.split_at(count);
    378    remaining = rest;
    379    let file_chunks: Result<Vec<_>> = indexing_pool().install(|| {
    380        batch_paths
    src/indexer.rs:437-439
    437let mut trees = crate::chunking::SourceTrees::default();
    438let mut chunked =
    439    chunk_source_with_metadata(rel_path, &content, &mut trees);
    src/indexer.rs:1831-1843
    1831if !is_fresh_index {
    1832    let retained_keys = indexed_chunks
    1833        .iter()
    1834        .map(|prepared| prepared.chunk.vector_key)
    1835        .collect::<HashSet<_>>();
    1836    let removed_keys = persist_or_stop!(remove_file_chunks(
    1837        &tx,
    1838        &mut writer,
    1839        &fields,
    1840        &mut vector_tombstones,
    1841        &rel_path,
    1842        Some(&retained_keys),
    1843    ));
    src/indexer.rs:1888-1898
    1888for prepared in indexed_chunks {
    1889    let indexed = &prepared.chunk;
    1890    persist_or_stop!(insert_chunk(
    1891        &mut persist_statements,
    1892        indexed,
    1893        &prepared.compressed_text,
    1894        &rel_path_string,
    1895        now_unix
    1896    ));
    1897    persist_or_stop!(writer.add_document(prepared.tantivy_doc));
    1898}
  9. Indexing index_workspace_inner → Indexing finalize_workspace_index_state raises the generation, and saves the snapshot last. 2
    src/indexer.rs:2051
    2051finalize_workspace_index_state(workspace, pending_snapshot)?;
    src/indexer.rs:2225-2242
    2225staging::test_support::check_publication(&workspace.metadata_path())?;
    2226workspace.write_metadata(&WorkspaceMetadata {
    2227    id: workspace.id.clone(),
    2228    root: workspace.root.clone(),
    2229    created_at_unix: existing.created_at_unix,
    2230    last_indexed_at_unix: Some(now),
    2231    watch_enabled: existing.watch_enabled,
    2232    skip_gitignore: existing.skip_gitignore,
    2233    // Background vector enhancement uses this lexical generation to
    2234    // detect concurrent edits and resume against the latest commit.
    2235    index_generation: existing.index_generation + 1,
    2236})?;
    2237workspace.write_index_format_version()?;
    2238
    2239// Snapshot becomes authoritative only after all stores and metadata commit.
    2240if let Some(snapshot) = pending_snapshot {
    2241    snapshot.save(&workspace.merkle_snapshot_path())?;
    2242}
  10. The worker clears the cached contexts if something changed, and it queues vector work for the workspace if background enhancement is enabled. 1
    src/daemon.rs:6328-6341
    6328if changed {
    6329    state.clear_workspace_contexts(&control.workspace);
    6330}
    6331complete_initial_watch_reconciliation(&control);
    6332if claimed_after_scan {
    6333    publish_initial_watch_readiness(&control, true);
    6334}
    6335if crate::config::background_enhancement_enabled() {
    6336    let queue = state.enhancement_queue.clone();
    6337    let edited = control.workspace.clone();
    6338    tokio::task::spawn_blocking(move || {
    6339        queue.request(edited, EnhancementPolicy::MaintainExisting);
    6340        queue.dispatch();
    6341    });

Vectors are built in the background

  1. Daemon schedule_search_enhancement → Daemon due_enhancement_workspaces drops a workspace that was tried for this mode in the last 10 seconds. 3
    src/daemon.rs:2758
    2758let due = self.due_enhancement_workspaces(workspaces, policy);
    src/daemon.rs:2784-2803
    2784let now = std::time::Instant::now();
    2785let mut triggers = self.enhancement_triggers.lock();
    2786workspaces
    2787    .into_iter()
    2788    .filter(|workspace| {
    2789        let key = EnhancementTriggerKey {
    2790            workspace_id: workspace.id.clone(),
    2791            policy,
    2792        };
    2793        let recent = triggers
    2794            .get(&key)
    2795            .is_some_and(|last| now.duration_since(*last) < ENHANCEMENT_TRIGGER_INTERVAL);
    2796        if recent {
    2797            return false;
    2798        }
    2799        triggers.put(key, now);
    2800        true
    2801    })
    2 more lines
    src/daemon.rs:103-107
    103const ENHANCEMENT_TRIGGER_INTERVAL: Duration = Duration::from_secs(10);
    104const MAX_READY_WORKSPACES: usize = 256;
    105const MAX_WATCH_POLICIES: usize = 256;
    106const MAX_SEARCH_CANCELLATION_TOMBSTONES: usize = 256;
    107const MAX_MEMORY_PROBE_LIMIT: usize = 80;
  2. Daemon schedule_search_enhancement → Daemon EnhancementQueue.request stores the workspace, if it needs work, with a recency number. name match 4
    src/daemon.rs:2765
    2765queue.request(workspace, policy);
    src/enhancement_queue.rs:177-203
    177/// Queue the work that `workspace` still needs. Reads the index, so call
    178/// it off the async runtime.
    179pub(crate) fn request(&self, workspace: Workspace, mut policy: EnhancementPolicy) {
    180    let Some(mut lane) = policy.lane(self.host.as_ref(), &workspace) else {
    181        return;
    182    };
    183    let mut state = self.state.lock();
    184    if let Some(waiting) = state.pending.get(&workspace.id)
    185        && waiting.policy > policy
    186    {
    187        // A later search does not cancel work another caller requested.
    188        policy = waiting.policy;
    189        lane = waiting.lane;
    190    }
    191    let recency = state.next_recency();
    192    state.pending.insert(
    193        workspace.id.clone(),
    194        PendingRequest {
    9 more lines
    src/enhancement_queue.rs:44-49
    44fn lane(self, host: &dyn WorkerHost, workspace: &Workspace) -> Option<WorkerLane> {
    45    match self {
    46        Self::HashOnly => host.needs_hash(workspace).then_some(WorkerLane::Hash),
    47        Self::MaintainExisting | Self::Neural => host.lane(workspace, self == Self::Neural),
    48    }
    49}
    src/enhancement_queue.rs:80-83
    80fn lane(&self, workspace: &Workspace, query_uses_neural: bool) -> Option<WorkerLane> {
    81    if !workspace.needs_search_enhancement(query_uses_neural) {
    82        return None;
    83    }
  3. Daemon schedule_search_enhancement → Daemon EnhancementQueue.dispatch visits the newest requests first, and starts a worker only in a lane (hash or neural) with a free place. name match 2
    src/daemon.rs:2767
    2767queue.dispatch();
    src/enhancement_queue.rs:232-257
    232let places = self.host.places();
    233let mut capacity = HashMap::new();
    234for lane in [WorkerLane::Hash, WorkerLane::Neural] {
    235    let mine = started.values().filter(|worker| worker.lane == lane);
    236    let free = self.host.free_places(lane);
    237    capacity.insert(lane, free.min(places.saturating_sub(mine.count())));
    238}
    239
    240let mut order = pending
    241    .iter()
    242    .map(|(id, request)| (request.recency, id.clone()))
    243    .collect::<Vec<_>>();
    244order.sort_by_key(|(recency, _)| std::cmp::Reverse(*recency));
    245for (_, id) in order {
    246    if capacity.values().all(|free| *free == 0) {
    247        break;
    248    }
    249    let request = pending.get_mut(&id).expect("request is pending");
    8 more lines
  4. Daemon EnhancementQueue.dispatch ⇢ Daemon WorkerProcesses.start calls it through the trait WorkerHost, and it picks the hash or the full trigger. inferred 3
    src/enhancement_queue.rs:286
    286if let Err(error) = self.host.start(&workspace, lane) {
    src/enhancement_queue.rs:101-105
    101fn start(&self, workspace: &Workspace, lane: WorkerLane) -> Result<()> {
    102    match lane {
    103        WorkerLane::Hash => workspace.trigger_background_hash_enhancement(),
    104        WorkerLane::Neural => workspace.trigger_background_enhancement(),
    105    }
    src/enhancement_queue.rs:71
    71impl WorkerHost for WorkerProcesses {
  5. Daemon WorkerProcesses.start → Workspace Workspace.trigger_background_enhancement calls trigger_background_enhancement_command, which creates a PID file and spawns its own executable with the hidden flag --enhance-internal. 6
    src/enhancement_queue.rs:104
    104WorkerLane::Neural => workspace.trigger_background_enhancement(),
    src/workspace.rs:1016-1018
    1016pub fn trigger_background_enhancement(&self) -> Result<()> {
    1017    self.trigger_background_enhancement_command(EnhancementMode::Full)
    1018}
    src/workspace.rs:1069-1071
    1069fn trigger_background_enhancement_command(&self, mode: EnhancementMode) -> Result<()> {
    1070    let exe = std::env::current_exe()?;
    1071    let pid_path = self.enhancing_pid_path();
    src/workspace.rs:80-85
    80impl EnhancementMode {
    81    fn command(self) -> &'static str {
    82        match self {
    83            Self::HashOnly => "--enhance-hash-internal",
    84            Self::Full => "--enhance-internal",
    85        }
    src/workspace.rs:1094-1124
    1094let lock = std::fs::OpenOptions::new()
    1095    .write(true)
    1096    .create_new(true)
    1097    .open(&pid_path);
    1098
    1099match lock {
    1100    Ok(_) => {
    1101        let mut cmd = std::process::Command::new(&exe);
    1102        cmd.arg(mode.command()).arg(&self.root);
    1103        cmd.stdin(std::process::Stdio::null());
    1104        cmd.stdout(std::process::Stdio::null());
    1105        cmd.stderr(std::process::Stdio::null());
    1106
    1107        // Keep background indexing from competing with interactive work.
    1108        #[cfg(unix)]
    1109        {
    1110            use std::os::unix::process::CommandExt;
    1111            // SAFETY: nice(2) is async-signal-safe and has no side effects
    13 more lines
    src/cli.rs:263-264
    263#[arg(long, hide = true, value_name = "PATH")]
    264pub enhance_internal: Option<PathBuf>,
  6. Workspace Workspace.trigger_background_enhancement_command ⇢ CLI run the new process sees --enhance-internal and starts an EnhancementJob record. inferred 3
    src/workspace.rs:1101-1102
    1101let mut cmd = std::process::Command::new(&exe);
    1102cmd.arg(mode.command()).arg(&self.root);
    src/cli.rs:717-728
    717if let Some(path) = &cli.enhance_internal {
    718    let workspace = Workspace::resolve(path)?;
    719    workspace.ensure_dirs()?;
    720    let job = jobs::EnhancementJob::start(&workspace, crate::indexer::WorkerLane::Neural);
    721    // Wait for a place among the running workers before opening stores.
    722    // The run starts with the hash pass, so only the guards of that pass
    723    // count here: hash vectors are built on battery too.
    724    let Some(worker_slot) = crate::indexer::admit_worker(
    725        &workspace,
    726        crate::indexer::WorkerLane::Neural,
    727        crate::indexer::WorkerStage::HashPass,
    728    )?
    src/workspace.rs:81-85
    81fn command(self) -> &'static str {
    82    match self {
    83        Self::HashOnly => "--enhance-hash-internal",
    84        Self::Full => "--enhance-internal",
    85    }
  7. CLI run → Vectors admit_worker waits until memory and load allow the pass, and until a slot lock is free. 3
    src/cli.rs:724
    724let Some(worker_slot) = crate::indexer::admit_worker(
    src/indexer/enhancement.rs:218-237
    218/// Block until this worker may run `stage`: the guards of that stage (memory
    219/// and load, for the neural pass also battery and thermal state) allow it, and
    220/// the lane has a free place. The worker has loaded no model and opened no
    221/// store yet, so a waiting worker costs a few MiB. Without this every edited
    222/// workspace got a running worker at once, and workers that a guard paused
    223/// kept their model and stores while they waited. `None` means the workspace
    224/// root vanished while the worker waited.
    225pub(crate) fn admit_worker(
    226    workspace: &Workspace,
    227    lane: WorkerLane,
    228    stage: WorkerStage,
    229) -> Result<Option<WorkerSlot>> {
    230    admit_worker_when(
    231        workspace,
    232        lane,
    233        stage,
    234        &mut check_system_constraints,
    235        GUARD_PAUSE,
    2 more lines
    src/indexer/enhancement.rs:284-295
    284if let Some(reason) = constraint(stage.tier()) {
    285    let _ = fs::write(&paused_path, &reason);
    286    std::thread::sleep(pause);
    287    continue;
    288}
    289let _ = fs::remove_file(&paused_path);
    290if let Some(slot) = try_acquire_worker_slot(lane)? {
    291    let _ = fs::remove_file(&phase_path);
    292    return Ok(Some(slot));
    293}
    294let _ = fs::write(&phase_path, QUEUED_PHASE);
    295std::thread::sleep(std::time::Duration::from_millis(500));
  8. CLI run → Indexing enhance_workspace_hash_for_job removes deleted keys, embeds the missing chunks, and saves the hash store. 6
    src/cli.rs:745
    745crate::indexer::enhance_workspace_hash_for_job(
    src/indexer.rs:2952-2958
    2952pub(crate) fn enhance_workspace_hash_for_job(
    2953    workspace: &Workspace,
    2954    hash_model: &dyn EmbeddingModel,
    2955    expected: &EnhancementSnapshot,
    2956) -> Result<usize> {
    2957    enhance_workspace_hash_with_snapshot(workspace, hash_model, Some(expected))
    2958}
    src/indexer.rs:2996-3001
    2996let mut vector_index = VectorStore::open(
    2997    &vector_path,
    2998    hash_model.dimensions(),
    2999    HASH_VECTOR_QUANTIZATION,
    3000    crate::vector_store::VectorTier::Hash,
    3001)?;
    src/indexer.rs:3019-3028
    3019let claimed_tombstones = claim_vector_tombstones(
    3020    &workspace.hash_tombstones_path(),
    3021    &workspace.hash_tombstones_processing_path(),
    3022)?;
    3023let removed_tombstones = claimed_tombstones.is_some();
    3024if let Some((_, keys)) = &claimed_tombstones {
    3025    for key in keys {
    3026        vector_index.remove(*key);
    3027    }
    3028}
    src/indexer.rs:3043-3075
    3043let process_batch = |batch: &mut Vec<(u64, String)>,
    3044                     count: &mut usize,
    3045                     store: &mut VectorStore|
    3046 -> Result<()> {
    3047    if batch.is_empty() {
    3048        return Ok(());
    3049    }
    3050    let texts = batch
    3051        .iter()
    3052        .map(|(_, text)| text.as_str())
    3053        .collect::<Vec<_>>();
    3054    let embeddings = hash_model.embed_batch(&texts);
    3055    let entries = batch.iter().map(|(key, _)| *key).zip(embeddings).collect();
    3056    indexing_pool().install(|| store.add_batch_unchecked(entries))?;
    3057    *count += batch.len();
    3058    batch.clear();
    3059    Ok(())
    3060};
    15 more lines
    src/indexer.rs:3124-3126
    3124} else if newly_processed > 0 || removed_tombstones {
    3125    vector_index.save()?;
    3126}
  9. CLI run → Vectors readmit_for_neural_pass gives up the slot and waits if the guards of the neural pass say no. 3
    src/cli.rs:754
    754crate::indexer::readmit_for_neural_pass(&workspace, worker_slot)?
    src/indexer/enhancement.rs:243-247
    243pub(crate) fn readmit_for_neural_pass(
    244    workspace: &Workspace,
    245    slot: WorkerSlot,
    246) -> Result<Option<WorkerSlot>> {
    247    readmit_for_neural_pass_when(workspace, slot, &mut check_system_constraints, GUARD_PAUSE)
    src/indexer/enhancement.rs:256-264
    256if constraint(WorkerStage::NeuralPass.tier()).is_none() {
    257    return Ok(Some(slot));
    258}
    259drop(slot);
    260admit_worker_when(
    261    workspace,
    262    WorkerLane::Neural,
    263    WorkerStage::NeuralPass,
    264    constraint,
  10. CLI run → Indexing enhance_workspace_neural_for_job saves after each 16,384 new chunks or more, and marks the generation complete only if it did not change. 4
    src/cli.rs:761
    761crate::indexer::enhance_workspace_neural_for_job(
    src/indexer.rs:3152-3158
    3152pub(crate) fn enhance_workspace_neural_for_job(
    3153    workspace: &Workspace,
    3154    neural_model: &dyn EmbeddingModel,
    3155    expected: &EnhancementSnapshot,
    3156) -> Result<usize> {
    3157    enhance_workspace_neural_with_snapshot(workspace, neural_model, Some(expected))
    3158}
    src/indexer.rs:3357-3360
    3357if newly_processed.saturating_sub(checkpointed) >= 16_384 {
    3358    vector_index.save()?;
    3359    checkpointed = newly_processed;
    3360}
    src/indexer.rs:3403-3411
    3403if workspace
    3404    .read_metadata()?
    3405    .is_some_and(|metadata| metadata.index_generation == index_generation)
    3406{
    3407    fs::write(
    3408        workspace.neural_enhanced_generation_path(),
    3409        index_generation.to_string(),
    3410    )?;
    3411}

The daemon starts, recovers, and cleans up

  1. Daemon request_unchecked_with_id → Daemon connect_to_daemon tries once with a limit of 2 seconds, and a second time only if it could remove a stale endpoint. 4
    src/daemon.rs:7287
    7287let Some(mut stream) = connect_to_daemon(autospawn).await else {
    src/daemon.rs:7240-7263
    7240async fn connect_to_daemon(autospawn: bool) -> Option<crate::ipc::IpcStream> {
    7241    // At most one stale-endpoint recovery and one retry. Every connection
    7242    // attempt has the same bound, including the first probe.
    7243    for attempt in 0..2 {
    7244        spawn_daemon_if_missing(autospawn).await;
    7245        if !crate::ipc::socket_exists() {
    7246            return None;
    7247        }
    7248
    7249        match connect_with_timeout(crate::ipc::connect(), DAEMON_CONNECT_TIMEOUT).await {
    7250            Ok(stream) => return Some(stream),
    7251            Err(DaemonConnectFailure::Io(err)) => {
    7252                warn!("daemon connection failed: {err}");
    7253            }
    7254            Err(DaemonConnectFailure::TimedOut) => {
    7255                warn!("daemon connection timed out");
    7256            }
    7257        }
    5 more lines
    src/daemon.rs:52-56
    52const DAEMON_CONNECT_TIMEOUT: Duration = Duration::from_secs(2);
    53const DAEMON_WRITE_TIMEOUT: Duration = Duration::from_secs(2);
    54const MAX_DAEMON_LOG_BYTES: u64 = 10 * 1024 * 1024;
    55const MAX_DAEMON_REQUEST_BYTES: usize = 1024 * 1024;
    56/// Client connections the daemon serves at once. Heavy work already waits for
    src/daemon.rs:7154-7162
    7154fn recover_stale_daemon_endpoint() -> bool {
    7155    match crate::ipc::cleanup_stale_socket() {
    7156        Ok(cleaned) => cleaned,
    7157        Err(err) => {
    7158            warn!("failed to inspect stale daemon endpoint: {err:#}");
    7159            false
    7160        }
    7161    }
    7162}
  2. Daemon connect_to_daemon → Daemon spawn_daemon_if_missing does nothing if a socket exists, or IVYGREP_NO_AUTOSPAWN is set, or the caller did not allow it. 2
    src/daemon.rs:7244
    7244spawn_daemon_if_missing(autospawn).await;
    src/daemon.rs:7165-7170
    7165if !autospawn
    7166    || crate::ipc::socket_exists()
    7167    || std::env::var_os("IVYGREP_NO_AUTOSPAWN").is_some()
    7168{
    7169    return;
    7170}
  3. Daemon spawn_daemon_if_missing ⇢ CLI run spawns the same executable with --daemon. inferred 3
    src/daemon.rs:7179-7189
    7179let Ok(exe) = std::env::current_exe() else {
    7180    return;
    7181};
    7182if !is_ig_executable(&exe) {
    7183    return;
    7184}
    7185
    7186let mut cmd = std::process::Command::new(exe);
    7187// Web-started daemons serve the same clients as any other daemon, so they
    7188// keep watcher restore and supervision.
    7189cmd.arg("--daemon");
    src/cli.rs:566-568
    566if cli.daemon {
    567    daemon::run_daemon().await?;
    568    return Ok(());
    src/daemon.rs:7230
    7230let _ = cmd.spawn();
  4. CLI run → Daemon run_daemon calls run_daemon_inner. 2
    src/cli.rs:567
    567daemon::run_daemon().await?;
    src/daemon.rs:3300-3302
    3300pub async fn run_daemon() -> Result<()> {
    3301    run_daemon_inner().await
    3302}
  5. Daemon run_daemon_inner → Daemon acquire_daemon_lock tries the lock 20 times, 100 ms apart, and the process exits without it. 3
    src/daemon.rs:3311
    3311let daemon_lock = match crate::ipc::acquire_daemon_lock()? {
    src/ipc.rs:40-52
    40pub fn acquire_daemon_lock() -> anyhow::Result<Option<std::fs::File>> {
    41    let file = open_daemon_lock()?;
    42    for _ in 0..20 {
    43        match fs2::FileExt::try_lock_exclusive(&file) {
    44            Ok(()) => return Ok(Some(file)),
    45            Err(e) if is_lock_contended(&e) => {
    46                std::thread::sleep(std::time::Duration::from_millis(100));
    47            }
    48            Err(e) => return Err(e.into()),
    49        }
    50    }
    51    Ok(None)
    52}
    src/daemon.rs:3311-3316
    3311let daemon_lock = match crate::ipc::acquire_daemon_lock()? {
    3312    Some(file) => Arc::new(file),
    3313    None => {
    3314        daemon_log("another ivygrep daemon is already running; exiting");
    3315        return Ok(());
    3316    }
  6. Daemon run_daemon_inner → Daemon restore_configured_watchers calls supervise_watchers now, and a supervisor task repeats it every 30 seconds. 6
    src/daemon.rs:3331
    3331tokio::task::spawn_blocking(move || restore_configured_watchers(&restore_state));
    src/daemon.rs:3667-3669
    3667fn restore_configured_watchers(state: &DaemonState) {
    3668    supervise_watchers(state);
    3669}
    src/daemon.rs:3332
    3332spawn_watcher_supervisor(state.clone());
    src/daemon.rs:3743-3751
    3743fn spawn_watcher_supervisor(state: DaemonState) {
    3744    tokio::spawn(async move {
    3745        loop {
    3746            tokio::time::sleep(WATCHER_SUPERVISOR_INTERVAL).await;
    3747            let state = state.clone();
    3748            let _ = tokio::task::spawn_blocking(move || supervise_watchers(&state)).await;
    3749        }
    3750    });
    3751}
    src/daemon.rs:3671-3677
    3671/// Registers a watcher for every enabled, indexed workspace that has none,
    3672/// honoring each workspace's retry backoff. Runs at startup and then every
    3673/// [`WATCHER_SUPERVISOR_INTERVAL`], so a watcher that failed to start (inotify
    3674/// limits, a root that was temporarily missing) comes back without anyone
    3675/// restarting the daemon.
    3676fn supervise_watchers(state: &DaemonState) {
    3677    release_watchers_for_missing_roots(state);
    src/daemon.rs:1775-1779
    1775const WATCHER_SUPERVISOR_INTERVAL: Duration = Duration::from_secs(30);
    1776
    1777#[derive(Debug, Clone)]
    1778struct WatcherRecovery {
    1779    failures: u32,
  7. Daemon supervise_watchers → Workspace list_workspace_metadata reads all registered workspaces. 2
    src/daemon.rs:3678
    3678let workspaces = match crate::workspace::list_workspace_metadata() {
    src/workspace.rs:2278-2284
    2278pub(crate) fn list_workspace_metadata() -> Result<Vec<(PathBuf, WorkspaceMetadata)>> {
    2279    let WorkspaceRegistry { entries, warnings } = workspace_registry()?;
    2280    for warning in warnings {
    2281        tracing::warn!("{warning}");
    2282    }
    2283    Ok(entries)
    2284}
  8. Daemon supervise_watchers → Daemon ensure_watcher registers a missing watcher, unless a retry delay is active. 2
    src/daemon.rs:3734
    3734if let Err(err) = ensure_watcher(state, &workspace) {
    src/daemon.rs:3830-3837
    3830fn ensure_watcher(state: &DaemonState, workspace: &Workspace) -> Result<()> {
    3831    if let Some(error) = state.watcher_backoff_error(&workspace.id) {
    3832        anyhow::bail!("{error}");
    3833    }
    3834    match register_resolved_watcher(state, workspace.clone()) {
    3835        Ok(()) => {
    3836            state.clear_watcher_failure(&workspace.id);
    3837            Ok(())
  9. Daemon run_daemon_inner → Daemon spawn_index_gc runs a pass at each interval. 2
    src/daemon.rs:3334
    3334spawn_index_gc(state.clone());
    src/daemon.rs:3756-3766
    3756fn spawn_index_gc(state: DaemonState) {
    3757    let Some(interval) = crate::index_gc::pass_interval() else {
    3758        return;
    3759    };
    3760    tokio::spawn(async move {
    3761        loop {
    3762            tokio::time::sleep(interval).await;
    3763            let state = state.clone();
    3764            let _ = tokio::task::spawn_blocking(move || collect_orphaned_indexes(&state)).await;
    3765        }
    3766    });
  10. Daemon collect_orphaned_indexes_at → Daemon remove_unused_index deletes an index whose root stayed missing, if no job and no lock uses it. 3
    src/index_gc.rs:164
    164match remove_unused_index(&workspace, holder, still_gone)? {
    src/index_gc.rs:284-317
    284// First in line: taking the daemon's lease can wait for a long search,
    285// and nothing else should be held meanwhile.
    286let _reservation = holder.reserve(workspace);
    287let job_is_active = |kind, ttl| jobs::job_status(workspace, kind, ttl).active();
    288if job_is_active(JobKind::Indexing, jobs::INDEXING_HEARTBEAT_TTL_SECS)
    289    || job_is_active(JobKind::Enhancement, jobs::ENHANCEMENT_HEARTBEAT_TTL_SECS)
    290{
    291    return Ok(Removal::InUse);
    292}
    293// Index runs hold `index.lock`; vector writers hold `enhancement.lock`.
    294let mut locks = Vec::new();
    295for name in ["index.lock", "enhancement.lock"] {
    296    let path = workspace.index_dir.join(name);
    297    if !path.exists() {
    298        continue;
    299    }
    300    let lock = fs::OpenOptions::new().write(true).open(&path)?;
    301    if fs2::FileExt::try_lock_exclusive(&lock).is_err() {
    16 more lines
    src/index_gc.rs:128-149
    128let missing_since = match read_missing_since(&marker) {
    129    Some(since) => since.min(now_unix),
    130    None => {
    131        let _ = fs::write(&marker, now_unix.to_string());
    132        now_unix
    133    }
    134};
    135let unregistered =
    136    worktree_is_unregistered(&index_dir, &metadata, &mut registered_worktrees);
    137let effective_grace = if unregistered {
    138    grace.min(DELETED_WORKTREE_GRACE)
    139} else {
    140    grace
    141};
    142let collect_after_unix = missing_since.saturating_add(effective_grace.as_secs());
    143if now_unix < collect_after_unix {
    144    report.waiting.push(WaitingIndex {
    145        root: metadata.root,
    4 more lines

State

The saved index of a workspace is in indexes/<workspace-id>/ of the app home: IVYGREP_HOME, or $XDG_DATA_HOME/ivygrep, or ~/.local/share/ivygrep. 5
src/config.rs:6-21
6pub fn app_home() -> Result<PathBuf> {
7    if let Some(path) = non_empty_env_path("IVYGREP_HOME") {
8        return Ok(path);
9    }
10
11    if let Some(xdg_data_home) = non_empty_env_path("XDG_DATA_HOME") {
12        return Ok(xdg_data_home.join("ivygrep"));
13    }
14
15    let home = dirs::home_dir().context("unable to resolve home directory")?;
16    Ok(home.join(".local/share/ivygrep"))
17}
18
19pub fn indexes_root() -> Result<PathBuf> {
20    Ok(app_home()?.join("indexes"))
21}
src/workspace.rs:395-399
395pub(crate) fn resolve_with_main_worktree_root(path: &Path) -> Result<(Self, Option<PathBuf>)> {
396    let root = detect_workspace_root(path)?;
397    let id = workspace_id(&root);
398    let index_dir = config::indexes_root()?.join(&id);

Indexes live under: docs/architecture.md, sentence 40

$IVYGREP_HOME/indexes/<workspace-id>/
docs/architecture.md, sentence 41

Without IVYGREP_HOME, ivygrep uses $XDG_DATA_HOME/ivygrep or ~/.local/share/ivygrep. docs/architecture.md, sentence 42

WhatWhereWritten byRead, replaced, or removedQuotes
Root, watch intent, generationworkspace.jsonfinalize_workspace_index_stateRead by read_metadata; removed by remove_workspace_index_contents
Chunks, symbols, file edges, statisticsmetadata.sqlite3index_workspace_innerOpened by SearchContext.load; replaced by promote
Keyword indextantivy/index_workspace_innerOpened by SearchContext.load; replaced by promote
Hash vectorsvectors.usearchHash passOpened by SearchContext.load
Neural vectors and their modelvectors_neural.usearch, neural_model.jsonNeural passThe vectors are deleted if the model identity differs, and neural_model.json is written again
Deleted vector keys.hash_tombstones, .neural_tombstonescommit_with_vector_tombstonesClaimed and removed by the vector passes
File hashesmerkle_snapshot.jsonfinalize_workspace_index_stateRead by index_workspace_inner; a file that does not parse counts as empty
Worktree overlayoverlay.sqlite3, overlay_tantivy/, overlay_vectors.usearch, base_ref.jsonindex_workspace_innerRead by SearchContext.load; checked by worktree_overlay_is_stale
Store set IDindex_incarnationIndex run; new at promotionCompared by verify_current
Unfinished publication.indexing.incompleteindex_workspace_innerForces a rebuild of a main index; removed after success
Job ledgerjob.jsonupdate_jobRead by read_job_ledger for job_status
Locks of one indexindex.lock, enhancement.lockIndex runs; vector workersTested by garbage collection
Worker places, all workspacesenhancement-slots/<lane>-<n>.lock in the app homeprobe_slotHeld by try_acquire_worker_slot
Daemon endpointdaemon.lock, daemon.sock, daemon.pid in the app homerun_daemon_innerThe socket is removed by cleanup_stale_socket, and the socket and the PID file by release_endpoint at shutdown
Daemon logdaemon.log in the app homeopen_daemon_log_fileMoved to daemon.log.1 over 10 MiB
Missing-root time.root_missing_sincecollect_orphaned_indexes_atRemoved when the root is back
Readers and results in daemon memoryDaemonStatecached_search_context_for_signature; store_query_resultsDropped by clear_workspace_contexts
Waiting enhancement requestsEnhancementQueue in daemon memoryrequestRemoved by dispatch; the oldest goes above 1,024

To change it

ToStart atThenQuotes
Add a search optionSearchOptions, as run_query fills itThe request in run_query, the handler, the MCP arguments, and build_search_request_for_path in src/web.rs
Add an MCP argumentIvygrepSearchArgssearch_tool_schema, the checks, and the daemon request
Add a daemon requestDaemonRequest and handle_request_with_cancellationProtocol versions, the client timeout, and, if it can be cancelled, is_search_request
Add a languageLANGUAGESresolve_type_alias, the grammar and query in tree_sitter_query, and INDEX_FORMAT_VERSION
Change a stored fieldcreate_tables_schema, build_schemaThe fields in open_tantivy_index, the insert of rows, and INDEX_FORMAT_VERSION
Change which files are indexedsource_walker_scopedSourcePathMatcher, the watcher filter, which shares NestedCheckouts, the targeted refresh, and SOURCE_RULES_VERSION
Change rankingfuse_rrf_with_contextCandidate limits, the rerank limit, and a relevance measurement before and after
Add an embedding profileNeuralProfileNeuralProfile.configured, create_configured_neural_model, and DenseFusionCalibration weights, which are kept only if every tuning task stays non-negative
Change worker limitsEnhancementQueue.dispatchtry_acquire_worker_slot, the guards, and both passes in run
Change the Web UIweb/src/main.ts, respondRebuild and commit web/dist; CI fails if the built files differ

Run and test

./build.sh
./test.sh --quick
./test.sh
./scripts/e2e_all.sh --binary target/release/ig
./bench.sh
cargo clippy --locked --all-targets -- -D warnings
cd web
corepack pnpm install --frozen-lockfile
corepack pnpm check
corepack pnpm build
IVYGREP_HOME=/tmp/ivygrep-diagnostics RUST_LOG=ivygrep::performance=debug ig --daemon
ig --status          # workspaces, index health, vector coverage, disk usage
ig --doctor          # diagnose index, daemon, watcher, and model
ig --doctor --fix    # repair a broken or stale index

Keep in mind

What was read, and what was not

The source, file by filecited herenot cited
CLI1 of 8 files cited, 6,979 lines

src/tui.rs 3,210 lines

src/agent.rs 1,008 lines

src/doctor.rs 685 lines

src/hardware.rs 328 lines

src/allocator.rs 88 lines

src/main.rs 62 lines

src/lib.rs 43 lines

MCP1 of 1 files cited, 2,529 lines

All files are cited.

Web3 of 16 files cited, 4,235 lines

src/launcher.rs 792 lines

web/src/app-types.ts 210 lines

web/src/render-utils.ts 169 lines

web/src/language-icons.ts 133 lines

web/src/api-client.ts 92 lines

web/src/ui-utils.ts 92 lines

web/src/clipboard-utils.ts 61 lines

web/src/workspace-status.ts 45 lines

web/src/event-source-session.ts 34 lines

web/src/file-viewer.ts 31 lines

web/playwright.config.ts 16 lines

web/vite.config.ts 10 lines

web/src/vite-env.d.ts 1 lines

Daemon6 of 7 files cited, 9,446 lines

src/performance.rs 27 lines

Workspace4 of 5 files cited, 3,892 lines

src/path_glob.rs 200 lines

Indexing6 of 10 files cited, 11,566 lines

src/text.rs 1,082 lines

src/indexer/git_state.rs 845 lines

src/indexer/compression.rs 173 lines

src/indexer/batch_budget.rs 93 lines

Vectors4 of 8 files cited, 3,362 lines

src/vector_store/portable.rs 477 lines

src/system_resources.rs 354 lines

src/vector_store/metadata.rs 287 lines

src/neural_metadata.rs 39 lines

Search7 of 17 files cited, 15,902 lines

src/regex_search.rs 1,940 lines

src/search_boolean.rs 724 lines

src/search_literal.rs 844 lines

src/search_error_text.rs 770 lines

src/search_presentation.rs 358 lines

src/search_semantic_visibility.rs 325 lines

src/search_file_cache.rs 335 lines

src/search_eligibility.rs 277 lines

src/byte_cache.rs 109 lines

src/query_aliases.rs 145 lines

Context3 of 3 files cited, 6,418 lines

All files are cited.

Set aside 3

scripts/**, benches/**, bench.sh benchmarks, evaluations, release checks, and end-to-end scripts; not part of the program

docs/** the website

packaging/**, install.sh, install.ps1, build.sh, test.sh install, build, and package scripts

Vendored code, not read 10 packages, 257,689 lines
Generated code, not read 1 file, 127 lines

web/dist/assets/index-DBmjxoBw.js

Test files 79 files, 33,895 lines

benches/indexer_bench.rs

src/indexer/enhancement_tests.rs

src/indexer/integrity_tests.rs

src/indexer/overlay_tests.rs

src/indexer/recovery_tests.rs

src/search_constraints_tests.rs

tests/agent_setup.rs

tests/cli_snapshot.rs

tests/concurrency.rs

tests/context_ignores.rs

tests/context_rust.rs

tests/daemon_ipc.rs

tests/daemon_recovery_cli.rs

tests/fixtures/python_repo/app/payments.py

tests/fixtures/rust_repo/src/lib.rs

tests/fixtures/ts_repo/src/tax.ts

tests/git_branch_switch.rs

tests/git_reuse.rs

tests/golden_queries.rs

tests/haskell_parser_safety.rs

tests/hf_hub_security.rs

tests/incremental_crud.rs

tests/index_health.rs

tests/language_retrieval.rs

tests/literal_cli.rs

tests/literal_memory.rs

tests/mcp_e2e.rs

tests/merkle_prop.rs

tests/preview_containment.rs

tests/ranking_context.rs

tests/relevance_quality.rs

tests/skip_gitignore.rs

tests/stress_harness.rs

tests/symbol_graph.rs

tests/symbol_references.rs

tests/test_agent_documentation.py

tests/test_bench_file_localization.py

tests/test_bench_linux_kernel.py

tests/test_bench_linux_relevance.py

tests/test_benchmark_guard.py

and 39 more

Other files, only counted 45

18 .html, 5 .css, 4 .snap, 3 .png, 3 .svg, 3 .jsonl, 2 .txt, 1 .editorconfig, 1 .gitattributes, 1 .gitignore, 1 .jsonc, 1 .lock, 1 LICENSE, 1 .woff2

Documents, not read 21

.github/pull_request_template.md 173 words, not about how it works

CHANGELOG.md 38,070 words, not about how it works

CODE_OF_CONDUCT.md 534 words, not about how it works

CONTRIBUTING.md 1,424 words, not about how it works

SECURITY.md 196 words, not about how it works

docs/benchmarks/cuda-validation.md 363 words, a dated or a detailed record

docs/benchmarks/native-f16-arm64-2026-09-02.md 657 words, a dated or a detailed record

docs/benchmarks/context-ab-2026-07-24.md 780 words, a dated or a detailed record

docs/benchmarks/cosqa-relevance-2026-09-02.md 688 words, a dated or a detailed record

docs/benchmarks/memory-retrieval-ab-2026-07-25.md 866 words, a dated or a detailed record

docs/benchmarks/clean-git-reuse.md 906 words, a dated or a detailed record

docs/benchmarks/runtime-coverage-2026-09-02.md 1,087 words, a dated or a detailed record

docs/benchmarks/graph-hydration.md 1,245 words, a dated or a detailed record

docs/benchmarks/opportunity-ab-2026-07-22.md 1,440 words, a dated or a detailed record

docs/benchmarks/hotpaths.md 1,404 words, a dated or a detailed record

docs/benchmarks/resource-load.md 1,225 words, a dated or a detailed record

docs/benchmarks/file-localization.md 1,655 words, a dated or a detailed record

benchmarks/public/README.md 1,423 words, a dated or a detailed record

docs/benchmarks/linux-arm64-2026-09-02.md 1,767 words, a dated or a detailed record

docs/benchmarks/opportunity-ab-2026-07-24.md 1,935 words, a dated or a detailed record

docs/benchmarks/daemon-soak.md 5,987 words, a dated or a detailed record

The documents, sentence by sentenceused here (66)left out (1,076)

Select a sentence of the brief to see its quotes. The number after it counts them. Select a mark here to read the original.

README.md 93 of 102
docs/architecture.md 746 of 801
docs/guide.md 145 of 147
packaging/crates/README.md 26 of 26
docs/releasing.md 43 of 43
plugins/ivygrep/skills/use-ivygrep/SKILL.md 23 of 23
Figures not shown 6

README.md: ivygrep logo

README.md: Latest release

README.md: CI

README.md: Security

README.md: MIT license

README.md: ig answers &quot;which thread count does it pick by default&quot; on the ripgrep source with the function default_thread_count. The keyword thread matches 201 lines in 20 files.