Skip to main content

reflex/
indexer.rs

1//! Indexing engine for parsing source code
2//!
3//! The indexer scans the project directory, parses source files using Tree-sitter,
4//! and builds the symbol/token cache for fast querying.
5
6use anyhow::{Context, Result};
7use ignore::WalkBuilder;
8use indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle};
9use rayon::prelude::*;
10use std::collections::HashMap;
11use std::path::{Path, PathBuf};
12use std::sync::atomic::{AtomicU64, Ordering};
13use std::sync::{Arc, Mutex};
14use std::time::Instant;
15
16use crate::cache::{CacheManager, WALK_SEQ_GAP};
17use crate::content_store::ContentWriter;
18use crate::models::{IndexConfig, IndexMode, IndexStats, Language};
19#[cfg(unix)]
20use crate::output;
21use crate::parsers::c::CDependencyExtractor;
22use crate::parsers::cpp::CppDependencyExtractor;
23use crate::parsers::csharp::CSharpDependencyExtractor;
24use crate::parsers::go::GoDependencyExtractor;
25use crate::parsers::java::JavaDependencyExtractor;
26use crate::parsers::kotlin::KotlinDependencyExtractor;
27use crate::parsers::php::PhpDependencyExtractor;
28use crate::parsers::python::PythonDependencyExtractor;
29use crate::parsers::ruby::RubyDependencyExtractor;
30use crate::parsers::rust::RustDependencyExtractor;
31use crate::parsers::svelte::SvelteDependencyExtractor;
32use crate::parsers::typescript::TypeScriptDependencyExtractor;
33use crate::parsers::vue::VueDependencyExtractor;
34use crate::parsers::zig::ZigDependencyExtractor;
35use crate::parsers::{DependencyExtractor, ExportInfo, ImportInfo};
36use crate::trigram_build::{TrigramIndexBuilder, TrigramRun};
37
38/// Progress callback type: (current_file_count, total_file_count, status_message)
39/// Uses Arc to allow cloning for multi-threaded progress updates
40pub type ProgressCallback = Arc<dyn Fn(usize, usize, String) + Send + Sync>;
41
42/// Result of processing a single file (used for parallel processing)
43struct FileProcessingResult {
44    hash: String,
45    content: String,
46    language: Language,
47    line_count: usize,
48    /// On-disk size and mtime, taken BEFORE the read so a write that lands
49    /// between the two is caught by the next status check, not hidden by it.
50    size: u64,
51    mtime_ns: i64,
52    /// Imports, re-exports and package memberships, when they were extracted
53    /// this run.
54    imports: Option<Extracted>,
55    /// The file's trigram postings, extracted in the pool (no file id yet).
56    trigram_run: TrigramRun,
57}
58
59/// `statistics` key of the resolver config digest the dependency rows were
60/// resolved with (see [`crate::dependency_resolve::ResolverConfigs::digest`]).
61const RESOLVER_DIGEST_KEY: &str = "resolver_config_digest";
62
63/// `statistics` key of the manifest generation meta.db's rows go with. A manifest
64/// of another generation means a run stopped between the two commits.
65pub const INDEX_GENERATION_KEY: &str = "index_generation";
66
67/// File in `.reflex/` whose mtime is an index run's start (see `run_marker`).
68const RUN_MARKER: &str = ".index-run";
69
70/// What a run found for one discovered file, compared with its `files` row.
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72enum FileStatus {
73    /// Same size and mtime as stored: not read.
74    Unchanged,
75    /// Different stat, same bytes (a `touch`, or an edit reverted).
76    Touched,
77    /// Different bytes.
78    Modified,
79    /// No row.
80    Added,
81}
82
83/// One file the build read, in walk order.
84struct IndexedFile {
85    /// Position in the discovery lists.
86    index: usize,
87    hash: String,
88    language: Language,
89    line_count: usize,
90    size: u64,
91    mtime_ns: i64,
92    /// Imports, re-exports and package memberships, when they were extracted
93    /// this run.
94    imports: Option<Extracted>,
95}
96
97/// One added or modified file a delta update reads.
98struct Rewrite {
99    rel: String,
100    /// Size from the walk's stat (the merge-limit check before any read).
101    size: u64,
102    walk_seq: i64,
103}
104
105/// The dirty flags a change set records: the rewritten paths that are dirty, the
106/// touched rows `(id, size, mtime_ns, dirty)`, the rows whose flag flips, and the
107/// branch's flag.
108struct DirtyFlags {
109    rewrites: std::collections::HashSet<String>,
110    touched: Vec<(i64, u64, i64, bool)>,
111    flips: Vec<(i64, bool)>,
112    git_dirty: bool,
113}
114
115/// A delta update's change set (see `Indexer::publish_delta`): `rfx index` builds
116/// it from a full walk, `update_paths` from the named paths. Rows and store
117/// entries it does not name stay as they are.
118struct DeltaChanges<'a> {
119    root: &'a Path,
120    /// Added and modified files, in walk order.
121    rewrites: Vec<Rewrite>,
122    /// Rows of files gone from the index: `(path, id)`.
123    deleted: Vec<(String, i64)>,
124    /// Rows whose walk position moved: `(id, walk_seq)`.
125    walk_moves: Vec<(i64, i64)>,
126    /// The dirty flags, asked for only when meta.db is written (a library update's
127    /// `git status` runs while the stores are written).
128    dirty: Box<dyn FnOnce() -> DirtyFlags + 'a>,
129    /// The rows of the rewritten paths that have one.
130    stored: HashMap<String, crate::meta_update::StoredFile>,
131    /// Re-sync every branch row (the branch may not be the one last synced);
132    /// otherwise only the rewritten rows are set.
133    sync_all_branch_rows: bool,
134    /// Return the statistics `rfx index` prints (per-language counts: a scan of
135    /// every row); otherwise the counts and sizes only.
136    full_stats: bool,
137    /// Files in the index after the update (unreadable rewrites not subtracted).
138    live_files: usize,
139    /// (new, modified, unchanged) of the files not rewritten, against the branch's
140    /// own hashes.
141    breakdown_rest: (usize, usize, usize),
142    /// The branch's own hashes of the rewritten paths.
143    branch_hashes: HashMap<String, String>,
144    branch: &'a str,
145    commit: Option<&'a str>,
146    resolver_configs: &'a crate::dependency_resolve::ResolverConfigs,
147    run_start: std::time::SystemTime,
148    generation: u64,
149    pool: &'a rayon::ThreadPool,
150    deleted_file_count: usize,
151    /// (too large, bytes too large, binary)
152    skipped: (usize, u64, usize),
153}
154
155/// What `Indexer::process_file` reads from the run.
156struct ProcessCtx<'a> {
157    root: &'a Path,
158    rels: &'a [String],
159    stored: &'a HashMap<String, crate::meta_update::StoredFile>,
160    run_start: std::time::SystemTime,
161    full_deps: bool,
162    tsconfigs: &'a HashMap<PathBuf, crate::parsers::tsconfig::PathAliasMap>,
163}
164
165/// Inputs of `Indexer::refresh_unchanged`.
166struct RefreshUnchanged<'a> {
167    rels: &'a [String],
168    metas: &'a [Option<crate::cache::FileStat>],
169    status: &'a [FileStatus],
170    /// Each walked path's row (every one has a row: nothing was added).
171    rows: &'a [Option<&'a crate::meta_update::StoredFile>],
172    existing_hashes: &'a BranchHashes<'a>,
173    dirty_paths: &'a std::collections::HashSet<String>,
174    branch: &'a str,
175    /// The branch's rows already name every file (the last run synced them).
176    in_sync: bool,
177    commit: Option<&'a str>,
178    /// `Some(dirty)` inside git.
179    git_dirty: Option<bool>,
180    run_start: std::time::SystemTime,
181    /// (too large, bytes too large, binary)
182    skipped: (usize, u64, usize),
183}
184
185/// Inputs of `Indexer::refresh_named`.
186struct RefreshNamed<'a> {
187    touched: &'a [(i64, u64, i64, bool)],
188    flips: &'a [(i64, bool)],
189    walk_moves: &'a [(i64, i64)],
190    branch: &'a str,
191    commit: Option<&'a str>,
192    git_dirty: bool,
193    live_files: usize,
194    /// (too large, bytes too large, binary)
195    skipped: (usize, u64, usize),
196}
197
198/// Inputs of `Indexer::write_meta`.
199struct MetaWrite<'a> {
200    root: &'a Path,
201    rels: &'a [String],
202    /// Discovery indices of the files in the new snapshot, in walk order.
203    present: &'a [usize],
204    /// Files read this run, in walk order (a subset of `present`).
205    written: &'a [IndexedFile],
206    metas: &'a [Option<crate::cache::FileStat>],
207    run_start: std::time::SystemTime,
208    stored: &'a HashMap<String, crate::meta_update::StoredFile>,
209    status: &'a [FileStatus],
210    dirty_paths: &'a std::collections::HashSet<String>,
211    branch: &'a str,
212    commit: Option<&'a str>,
213    resolver_configs: &'a crate::dependency_resolve::ResolverConfigs,
214    full_deps: bool,
215    /// Generation of the manifest these rows go with.
216    generation: u64,
217}
218
219/// (new, modified, unchanged) of `(path, hash)` pairs against a branch's hashes.
220/// The branch's own hash of each path: its `file_branches` rows, or, for the
221/// branch the last run synced, the `files` rows themselves (the same values,
222/// without loading them).
223enum BranchHashes<'a> {
224    Synced(&'a HashMap<String, crate::meta_update::StoredFile>),
225    Loaded(HashMap<String, String>),
226}
227
228impl BranchHashes<'_> {
229    fn get(&self, path: &str) -> Option<&str> {
230        match self {
231            Self::Synced(stored) => stored.get(path).map(|row| row.hash.as_str()),
232            Self::Loaded(hashes) => hashes.get(path).map(String::as_str),
233        }
234    }
235}
236
237fn breakdown<'a>(
238    files: impl Iterator<Item = (&'a str, &'a str)>,
239    existing_hashes: &BranchHashes<'_>,
240) -> (usize, usize, usize) {
241    let (mut new, mut modified, mut unchanged) = (0, 0, 0);
242    for (path, hash) in files {
243        match existing_hashes.get(path) {
244            None => new += 1,
245            Some(old) if old != hash => modified += 1,
246            _ => unchanged += 1,
247        }
248    }
249    (new, modified, unchanged)
250}
251
252/// Set `files.vendored` from `rules` for the rows in `ids`, or for every row
253/// (`None`: the rules may have changed). Returns how many rows changed.
254fn refresh_vendored(
255    tx: &rusqlite::Connection,
256    rules: &crate::vendor::VendorRules,
257    ids: Option<&[i64]>,
258) -> Result<usize> {
259    let mut changed: Vec<(i64, bool)> = Vec::new();
260    {
261        let mut visit = |id: i64, path: &str, old: bool| {
262            let new = rules.is_vendored(path, crate::models::Language::from_path(Path::new(path)));
263            if new != old {
264                changed.push((id, new));
265            }
266        };
267        match ids {
268            None => {
269                let mut stmt = tx.prepare("SELECT id, path, vendored FROM files")?;
270                let rows = stmt.query_map([], |r| {
271                    Ok((
272                        r.get::<_, i64>(0)?,
273                        r.get::<_, String>(1)?,
274                        r.get::<_, bool>(2)?,
275                    ))
276                })?;
277                for row in rows {
278                    let (id, path, old) = row?;
279                    visit(id, &path, old);
280                }
281            }
282            Some(ids) => {
283                let mut stmt = tx.prepare("SELECT path, vendored FROM files WHERE id = ?")?;
284                for &id in ids {
285                    let (path, old): (String, bool) =
286                        stmt.query_row([id], |r| Ok((r.get(0)?, r.get(1)?)))?;
287                    visit(id, &path, old);
288                }
289            }
290        }
291    }
292    let mut stmt = tx.prepare("UPDATE files SET vendored = ? WHERE id = ?")?;
293    for (id, vendored) in &changed {
294        stmt.execute(rusqlite::params![vendored, id])?;
295    }
296    Ok(changed.len())
297}
298
299/// Resolve again every stored import (other than External/Stdlib) and every
300/// export of the files not in `skip`, updating the rows whose target changed.
301/// Package-keyed rows are skipped: their key depends on the import and the
302/// module config only, and which files a package holds is `package_members`.
303/// Returns how many rows changed.
304fn reresolve(
305    tx: &rusqlite::Connection,
306    ctx: &crate::dependency_resolve::ResolverContext<'_>,
307    resolver: &crate::dependency::PathResolver,
308    skip: &std::collections::HashSet<i64>,
309) -> Result<usize> {
310    let mut changed: Vec<(i64, Option<i64>)> = Vec::new();
311    {
312        let mut stmt = tx.prepare(
313            "SELECT d.id, d.file_id, f.path, d.imported_path, d.resolved_file_id
314             FROM file_dependencies d JOIN files f ON f.id = d.file_id
315             WHERE d.import_type NOT IN ('external', 'stdlib')
316               AND d.resolved_package IS NULL",
317        )?;
318        let rows = stmt.query_map([], |r| {
319            Ok((
320                r.get::<_, i64>(0)?,
321                r.get::<_, i64>(1)?,
322                r.get::<_, String>(2)?,
323                r.get::<_, String>(3)?,
324                r.get::<_, Option<i64>>(4)?,
325            ))
326        })?;
327        for row in rows {
328            let (id, file_id, path, imported_path, old) = row?;
329            if skip.contains(&file_id) {
330                continue;
331            }
332            // Resolution reads only the imported path (the stored type is already
333            // the reclassified one, and External/Stdlib rows are skipped above).
334            let import = ImportInfo {
335                imported_path,
336                import_type: crate::models::ImportType::Internal,
337                line_number: 0,
338                imported_symbols: None,
339            };
340            let new = ctx.resolve_import(&path, &import, resolver);
341            if new != old {
342                changed.push((id, new));
343            }
344        }
345    }
346    let mut stmt = tx.prepare("UPDATE file_dependencies SET resolved_file_id = ? WHERE id = ?")?;
347    for (id, new) in &changed {
348        stmt.execute(rusqlite::params![new, id])?;
349    }
350    let mut total = changed.len();
351
352    let mut changed: Vec<(i64, Option<i64>)> = Vec::new();
353    {
354        let mut stmt = tx.prepare(
355            "SELECT e.id, e.file_id, f.path, e.source_path, e.resolved_source_id
356             FROM file_exports e JOIN files f ON f.id = e.file_id",
357        )?;
358        let rows = stmt.query_map([], |r| {
359            Ok((
360                r.get::<_, i64>(0)?,
361                r.get::<_, i64>(1)?,
362                r.get::<_, String>(2)?,
363                r.get::<_, String>(3)?,
364                r.get::<_, Option<i64>>(4)?,
365            ))
366        })?;
367        for row in rows {
368            let (id, file_id, path, source_path, old) = row?;
369            if skip.contains(&file_id) {
370                continue;
371            }
372            let export = ExportInfo {
373                exported_symbol: None,
374                source_path,
375                line_number: 0,
376            };
377            let new = ctx.resolve_export(&path, &export, resolver);
378            if new != old {
379                changed.push((id, new));
380            }
381        }
382    }
383    let mut stmt = tx.prepare("UPDATE file_exports SET resolved_source_id = ? WHERE id = ?")?;
384    for (id, new) in &changed {
385        stmt.execute(rusqlite::params![new, id])?;
386    }
387    total += changed.len();
388    Ok(total)
389}
390
391/// What import extraction yields for one file: its imports, its re-exports, and
392/// the `(package key, member)` rows its content declares (`package_members`).
393type Extracted = (Vec<ImportInfo>, Vec<ExportInfo>, Vec<(String, String)>);
394
395/// Imports, re-exports and declared package memberships of one file, by
396/// language. `path_str` is the path as walked (for the nearest tsconfig).
397fn extract_imports(
398    language: Language,
399    content: &str,
400    path_str: &str,
401    root: &Path,
402    tsconfigs: &HashMap<PathBuf, crate::parsers::tsconfig::PathAliasMap>,
403) -> Extracted {
404    // Extract dependencies and exports for supported languages
405    let mut parsed_exports: Vec<ExportInfo> = Vec::new();
406    let mut declared_namespaces: Vec<(String, String)> = Vec::new();
407    let dependencies = match language {
408        Language::Rust => match RustDependencyExtractor::extract_dependencies(content) {
409            Ok(deps) => deps,
410            Err(e) => {
411                log::warn!("Failed to extract dependencies from {}: {}", path_str, e);
412                Vec::new()
413            }
414        },
415        Language::Python => match PythonDependencyExtractor::extract_dependencies(content) {
416            Ok(deps) => deps,
417            Err(e) => {
418                log::warn!("Failed to extract dependencies from {}: {}", path_str, e);
419                Vec::new()
420            }
421        },
422        Language::TypeScript | Language::JavaScript => {
423            // Find nearest tsconfig for path alias resolution. One parse
424            // yields both the imports and the re-exports.
425            let alias_map =
426                crate::dependency_resolve::find_nearest_tsconfig(path_str, root, tsconfigs);
427            match TypeScriptDependencyExtractor::extract_dependencies_and_exports(
428                content, alias_map,
429            ) {
430                Ok((deps, exports)) => {
431                    parsed_exports = exports;
432                    deps
433                }
434                Err(e) => {
435                    log::warn!("Failed to extract dependencies from {}: {}", path_str, e);
436                    Vec::new()
437                }
438            }
439        }
440        Language::Go => match GoDependencyExtractor::extract_dependencies(content) {
441            Ok(deps) => deps,
442            Err(e) => {
443                log::warn!("Failed to extract dependencies from {}: {}", path_str, e);
444                Vec::new()
445            }
446        },
447        Language::Java => match JavaDependencyExtractor::extract_dependencies(content) {
448            Ok(deps) => deps,
449            Err(e) => {
450                log::warn!("Failed to extract dependencies from {}: {}", path_str, e);
451                Vec::new()
452            }
453        },
454        Language::C => match CDependencyExtractor::extract_dependencies(content) {
455            Ok(deps) => deps,
456            Err(e) => {
457                log::warn!("Failed to extract dependencies from {}: {}", path_str, e);
458                Vec::new()
459            }
460        },
461        Language::Cpp => match CppDependencyExtractor::extract_dependencies(content) {
462            Ok(deps) => deps,
463            Err(e) => {
464                log::warn!("Failed to extract dependencies from {}: {}", path_str, e);
465                Vec::new()
466            }
467        },
468        Language::CSharp => {
469            match CSharpDependencyExtractor::extract_dependencies_and_members(content) {
470                Ok((deps, members)) => {
471                    declared_namespaces = members;
472                    deps
473                }
474                Err(e) => {
475                    log::warn!("Failed to extract dependencies from {}: {}", path_str, e);
476                    Vec::new()
477                }
478            }
479        }
480        Language::PHP => match PhpDependencyExtractor::extract_dependencies(content) {
481            Ok(deps) => deps,
482            Err(e) => {
483                log::warn!("Failed to extract dependencies from {}: {}", path_str, e);
484                Vec::new()
485            }
486        },
487        Language::Ruby => match RubyDependencyExtractor::extract_dependencies(content) {
488            Ok(deps) => deps,
489            Err(e) => {
490                log::warn!("Failed to extract dependencies from {}: {}", path_str, e);
491                Vec::new()
492            }
493        },
494        Language::Kotlin => match KotlinDependencyExtractor::extract_dependencies(content) {
495            Ok(deps) => deps,
496            Err(e) => {
497                log::warn!("Failed to extract dependencies from {}: {}", path_str, e);
498                Vec::new()
499            }
500        },
501        Language::Zig => match ZigDependencyExtractor::extract_dependencies(content) {
502            Ok(deps) => deps,
503            Err(e) => {
504                log::warn!("Failed to extract dependencies from {}: {}", path_str, e);
505                Vec::new()
506            }
507        },
508        Language::Vue => {
509            // Find nearest tsconfig for path alias resolution. One parse
510            // per script block yields both the imports and the re-exports.
511            let alias_map =
512                crate::dependency_resolve::find_nearest_tsconfig(path_str, root, tsconfigs);
513            match VueDependencyExtractor::extract_dependencies_and_exports(content, alias_map) {
514                Ok((deps, exports)) => {
515                    parsed_exports = exports;
516                    deps
517                }
518                Err(e) => {
519                    log::warn!("Failed to extract dependencies from {}: {}", path_str, e);
520                    Vec::new()
521                }
522            }
523        }
524        Language::Svelte => match SvelteDependencyExtractor::extract_dependencies(content) {
525            Ok(deps) => deps,
526            Err(e) => {
527                log::warn!("Failed to extract dependencies from {}: {}", path_str, e);
528                Vec::new()
529            }
530        },
531        // Other languages not yet implemented
532        _ => Vec::new(),
533    };
534
535    // Exports (barrel re-export tracking) came out of the same parse as the
536    // dependencies above; only TypeScript/JavaScript/Vue have them.
537    let members = match language {
538        Language::Java | Language::Kotlin => {
539            crate::parsers::java::jvm_package_members(path_str, content)
540        }
541        Language::CSharp => declared_namespaces,
542        _ => Vec::new(),
543    };
544    (dependencies, parsed_exports, members)
545}
546
547/// Manages the indexing process
548pub struct Indexer {
549    cache: CacheManager,
550    config: IndexConfig,
551    /// `(max_files, max_bytes)` per batch; `None` = defaults / env overrides.
552    batch_limits: Option<(usize, u64)>,
553    /// `(max_files, max_bytes)` of the delta before it is merged into a new base;
554    /// `None` = [`DELTA_MAX_FILES`] and [`DELTA_MAX_CORPUS_PERCENT`] of the corpus.
555    merge_limits: Option<(usize, u64)>,
556    /// `(max_files, max_bytes)` of the recent segment before it is folded into the
557    /// delta; `None` = [`RECENT_MAX_FILES`] and the merge byte limit over
558    /// [`RECENT_BYTES_DIVISOR`].
559    recent_limits: Option<(usize, u64)>,
560    /// Crash tests: the write point at which the process aborts.
561    abort_at: Option<String>,
562    /// The rule-file record the current `index` run saw, when it differs from
563    /// the stored one: written after the run succeeds.
564    rules_pending: std::sync::Mutex<Option<String>>,
565}
566
567/// The path resolver of this process's last delta publish: `(meta.db, publish id,
568/// resolver)`. The next publish over that manifest patches it with its added and
569/// deleted paths instead of loading every path; any other publish (another process,
570/// a full build, a cleared cache) has another publish id, and the next one loads
571/// again.
572static RESOLVER_CACHE: Mutex<Option<(PathBuf, u64, crate::dependency::PathResolver)>> =
573    Mutex::new(None);
574
575/// Files the recent segment may hold before an update folds it into the delta.
576pub const RECENT_MAX_FILES: usize = 256;
577/// The recent segment's text limit: the delta's (merge) limit divided by this.
578pub const RECENT_BYTES_DIVISOR: u64 = 16;
579
580/// Exit code of a process stopped by `Indexer::set_abort_point`.
581#[doc(hidden)]
582pub const ABORT_EXIT_CODE: i32 = 86;
583
584/// Files the delta may hold before an update merges it into a new base.
585pub const DELTA_MAX_FILES: usize = 2000;
586/// Text bytes the delta may hold, as a percentage of the live corpus, before an
587/// update merges it into a new base.
588pub const DELTA_MAX_CORPUS_PERCENT: u64 = 5;
589
590/// Default cap on files per batch.
591pub const BATCH_MAX_FILES: usize = 5000;
592/// Default cap on bytes of text per batch. Bounds the per-batch memory of the
593/// read pool (file contents) and of the trigram build (postings), whatever the
594/// file count: a 9,000-file tree of large files no longer builds one giant
595/// in-memory index.
596pub const BATCH_MAX_BYTES: u64 = 48 << 20;
597
598/// Cut `sizes` (in file order) into consecutive batches of at most `max_files`
599/// files and, past the first file of a batch, at most `max_bytes` bytes.
600pub fn plan_batches(
601    sizes: &[u64],
602    max_files: usize,
603    max_bytes: u64,
604) -> Vec<std::ops::Range<usize>> {
605    let max_files = max_files.max(1);
606    let mut batches = Vec::new();
607    let mut start = 0usize;
608    let mut bytes = 0u64;
609    for (i, &size) in sizes.iter().enumerate() {
610        let count = i - start;
611        if count > 0 && (count >= max_files || bytes.saturating_add(size) > max_bytes) {
612            batches.push(start..i);
613            start = i;
614            bytes = 0;
615        }
616        bytes = bytes.saturating_add(size);
617    }
618    if start < sizes.len() {
619        batches.push(start..sizes.len());
620    }
621    batches
622}
623
624/// The `[index] include.patterns` / `exclude.patterns` policy, compiled once.
625///
626/// Built on `ignore::overrides::Override`, so the patterns follow gitignore rules
627/// exactly as the walker applies them: a pattern containing `/` is anchored at the
628/// workspace root, a bare name matches at any depth, `*` does not cross `/`.
629/// Includes are whitelist globs, excludes are `!`-prefixed. With only includes,
630/// non-matching *files* are dropped but directories are still walked, so
631/// `include = ["src/**/*.rs"]` works without listing `src/`.
632///
633/// The same policy must answer "would Reflex index this path?" everywhere: the
634/// walker, the working-tree freshness check and the watcher. If they disagree, an
635/// edit to an excluded file marks the index permanently stale.
636#[derive(Clone, Debug)]
637pub struct PathPolicy {
638    overrides: Option<ignore::overrides::Override>,
639    /// `[index] text_tier`.
640    text_tier: bool,
641    /// `[index] languages`; empty = every supported language.
642    languages: Vec<Language>,
643    /// `[index] mode`.
644    mode: IndexMode,
645    /// `[index] hidden`.
646    hidden: bool,
647}
648
649impl Default for PathPolicy {
650    fn default() -> Self {
651        Self {
652            overrides: None,
653            text_tier: true,
654            languages: Vec::new(),
655            mode: IndexMode::Tracked,
656            hidden: false,
657        }
658    }
659}
660
661impl PathPolicy {
662    /// Compile the policy from an index config. No patterns → a policy that admits
663    /// every path the language rules allow. An invalid pattern is logged and skipped.
664    pub fn from_config(root: &Path, config: &IndexConfig) -> Self {
665        let mut policy = Self {
666            overrides: None,
667            text_tier: config.text_tier,
668            languages: config.languages.clone(),
669            mode: config.mode,
670            hidden: config.hidden,
671        };
672        if config.include_patterns.is_empty() && config.exclude_patterns.is_empty() {
673            return policy;
674        }
675        let mut builder = ignore::overrides::OverrideBuilder::new(root);
676        for pat in &config.include_patterns {
677            if let Err(e) = builder.add(pat) {
678                log::warn!("Invalid [index] include pattern '{}': {}", pat, e);
679            }
680        }
681        for pat in &config.exclude_patterns {
682            let negated = format!("!{}", pat.trim_start_matches('!'));
683            if let Err(e) = builder.add(&negated) {
684                log::warn!("Invalid [index] exclude pattern '{}': {}", pat, e);
685            }
686        }
687        match builder.build() {
688            Ok(ov) => policy.overrides = Some(ov),
689            Err(e) => log::warn!("Failed to build [index] include/exclude policy: {}", e),
690        }
691        policy
692    }
693
694    /// The language a file at `path` would be indexed as, or `None` when the
695    /// policy would not index it (excluded by pattern, tier off, parser not
696    /// wanted). Path only: no filesystem access, so it is the same answer for the
697    /// walker, the freshness check and the watcher.
698    pub fn classify(&self, path: &Path) -> Option<Language> {
699        if !self.admits(path, false) {
700            return None;
701        }
702        let lang = Language::from_path(path);
703        let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
704
705        match lang {
706            // Indexed only in tracked mode, and excluded from searches by default.
707            Language::Lock | Language::Generated => {
708                (self.mode == IndexMode::Tracked).then_some(lang)
709            }
710            // The plain-text tier: docs, config, templates and, in tracked mode,
711            // every other non-binary file. Deliberately NOT subject to `languages`.
712            // That option means "which PARSERS do I care about"; a user with
713            // languages = ["rust"] would otherwise lose the text tier silently,
714            // which is the very bug this tier exists to fix. `text_tier = false`
715            // is the way to turn it off.
716            Language::Text => {
717                if !self.text_tier {
718                    return None;
719                }
720                match self.mode {
721                    IndexMode::Tracked => Some(lang),
722                    IndexMode::Allowlist => crate::models::is_text_tier_file(name).then_some(lang),
723                }
724            }
725            Language::Unknown => None,
726            // Code without a working grammar (Swift): in tracked mode it is still a
727            // text file an agent greps, so it is indexed; symbol queries skip it.
728            code if !code.is_supported() => {
729                (self.mode == IndexMode::Tracked && self.text_tier).then_some(code)
730            }
731            code => {
732                if !self.languages.is_empty() && !self.languages.contains(&code) {
733                    log::debug!(
734                        "Skipping {} ({:?} not in configured languages)",
735                        path.display(),
736                        code
737                    );
738                    return None;
739                }
740                Some(code)
741            }
742        }
743    }
744
745    /// Whether a workspace-RELATIVE path is under a directory the walker would
746    /// descend into. With `hidden = false` (the default, like ripgrep) no dot
747    /// segment is; with `hidden = true` only `.git/` and `.reflex/` are skipped.
748    ///
749    /// Relative paths only: an absolute path's own ancestors (`/tmp/.cache/…`) are
750    /// none of the walker's business.
751    pub fn hidden_ok(&self, rel: &Path) -> bool {
752        rel.components()
753            .filter_map(|c| c.as_os_str().to_str())
754            .all(|seg| {
755                if seg == "." || seg == ".." {
756                    return true;
757                }
758                if seg == ".git" || seg == crate::cache::CACHE_DIR {
759                    return false;
760                }
761                self.hidden || !is_hidden_segment(seg)
762            })
763    }
764
765    /// `[index] hidden`.
766    pub fn hidden(&self) -> bool {
767        self.hidden
768    }
769
770    /// Whether the policy admits this path. Directories are always admitted (the
771    /// walker descends; files decide), unless an exclude names them.
772    pub fn admits(&self, path: &Path, is_dir: bool) -> bool {
773        match &self.overrides {
774            None => true,
775            Some(ov) => !ov.matched(path, is_dir).is_ignore(),
776        }
777    }
778
779    /// The walker-side view of the policy.
780    pub fn overrides(&self) -> Option<&ignore::overrides::Override> {
781        self.overrides.as_ref()
782    }
783}
784
785/// A walk before the binary check (see `Indexer::walk_candidates`).
786#[derive(Debug, Default)]
787struct Walked {
788    found: Discovered,
789    /// Per entry of `found`: whether its type is not code (so it is sniffed).
790    non_code: Vec<bool>,
791}
792
793/// What one directory walk found.
794#[derive(Debug, Default)]
795struct Discovered {
796    /// Each file relative to the root, with forward slashes: the path the stores
797    /// and meta.db use. The walker's own path is `root.join(rel)`.
798    rels: Vec<String>,
799    /// On-disk size of each entry of `files` (0 when unknown); drives batching.
800    sizes: Vec<u64>,
801    /// The `stat` of each entry of `files`, taken during the walk.
802    metas: Vec<Option<crate::cache::FileStat>>,
803    skipped_too_large: usize,
804    skipped_bytes_too_large: u64,
805    skipped_binary: usize,
806}
807
808/// The paths a library update names, relative to the root (`/`-separated): the
809/// walk goes down through their ancestors and into them, and nowhere else.
810#[derive(Debug, Default)]
811struct Targets {
812    /// Each named path (a file or a directory).
813    exact: std::collections::HashSet<String>,
814    /// Every proper ancestor directory of a named path.
815    ancestors: std::collections::HashSet<String>,
816}
817
818impl Targets {
819    fn new(paths: &[String]) -> Self {
820        let mut out = Self::default();
821        for p in paths {
822            let mut end = p.len();
823            while let Some(slash) = p[..end].rfind('/') {
824                out.ancestors.insert(p[..slash].to_string());
825                end = slash;
826            }
827            out.exact.insert(p.clone());
828        }
829        out
830    }
831
832    /// Whether `rel` is a named path or lies under one.
833    fn covers(&self, rel: &str) -> bool {
834        if self.exact.contains(rel) {
835            return true;
836        }
837        let mut end = rel.len();
838        while let Some(slash) = rel[..end].rfind('/') {
839            if self.exact.contains(&rel[..slash]) {
840                return true;
841            }
842            end = slash;
843        }
844        false
845    }
846
847    /// Whether the walk enters `rel`: the root, an ancestor of a named path, or a
848    /// path a named path covers.
849    fn admits(&self, rel: &str) -> bool {
850        rel.is_empty() || self.ancestors.contains(rel) || self.covers(rel)
851    }
852}
853
854/// Walk positions for the files a library update rewrites (`rewrites`, in walk
855/// order; each with its row when it has one), found by probing `files` in
856/// `walk_seq` order with the walk-order comparator. A rewritten file keeps its
857/// position while its neighbours still bracket it; a new or moved one gets a
858/// value between the rows that now bracket it. Rows in `skip` (deleted) are left
859/// out. `None` when a comparison cannot be made or a gap has no room: the caller
860/// then runs a full index, which renumbers.
861fn place_rewrites(
862    conn: &rusqlite::Connection,
863    walk: &mut crate::walk_order::WalkOrder<'_>,
864    rewrites: &[(&str, Option<&crate::meta_update::StoredFile>)],
865    skip: &std::collections::HashSet<i64>,
866) -> Result<Option<HashMap<String, i64>>> {
867    use crate::meta_update::row_near_seq;
868    use std::cmp::Ordering::{Greater, Less};
869    let mut skip = skip.clone();
870    let mut kept: HashMap<&str, i64> = HashMap::new();
871    // Rows whose neighbours no longer bracket them are placed anew; a row moved
872    // out can change another's neighbours, so check again until nothing moves.
873    let mut moved: std::collections::HashSet<&str> = std::collections::HashSet::new();
874    for _ in 0..4 {
875        kept.clear();
876        let mut changed = false;
877        for (path, row) in rewrites {
878            let Some(row) = row else { continue };
879            if moved.contains(path) {
880                continue;
881            }
882            let before = row_near_seq(conn, row.walk_seq, true, &skip)?;
883            let after = row_near_seq(conn, row.walk_seq + 1, false, &skip)?;
884            let fits = before
885                .as_ref()
886                .is_none_or(|(_, p, _)| walk.cmp(p, path) == Some(Less))
887                && after
888                    .as_ref()
889                    .is_none_or(|(_, p, _)| walk.cmp(path, p) == Some(Less));
890            if fits {
891                kept.insert(path, row.walk_seq);
892            } else {
893                moved.insert(path);
894                skip.insert(row.id);
895                changed = true;
896            }
897        }
898        if !changed {
899            break;
900        }
901    }
902
903    let bounds: (Option<i64>, Option<i64>) =
904        conn.query_row("SELECT MIN(walk_seq), MAX(walk_seq) FROM files", [], |r| {
905            Ok((r.get(0)?, r.get(1)?))
906        })?;
907    // Each file to place, with the positions of the rows that bracket it.
908    let mut gaps: Vec<(&str, Option<i64>, Option<i64>)> = Vec::new();
909    for (path, row) in rewrites {
910        if row.is_some() && !moved.contains(path) {
911            continue;
912        }
913        let (before, after) = match bounds {
914            (Some(min), Some(max)) => {
915                // The smallest position whose first row comes after `path`.
916                let (mut lo, mut hi) = (min, max + 1);
917                while lo < hi {
918                    let mid = lo + (hi - lo) / 2;
919                    let after_path = match row_near_seq(conn, mid, false, &skip)? {
920                        None => true,
921                        Some((_, q, _)) => match walk.cmp(&q, path) {
922                            Some(Greater) => true,
923                            Some(Less) => false,
924                            _ => return Ok(None),
925                        },
926                    };
927                    if after_path {
928                        hi = mid;
929                    } else {
930                        lo = mid + 1;
931                    }
932                }
933                (
934                    row_near_seq(conn, lo, true, &skip)?.map(|r| r.2),
935                    row_near_seq(conn, lo, false, &skip)?.map(|r| r.2),
936                )
937            }
938            _ => (None, None),
939        };
940        gaps.push((path, before, after));
941    }
942    let mut out: HashMap<String, i64> = kept
943        .into_iter()
944        .map(|(p, seq)| (p.to_string(), seq))
945        .collect();
946    // Files that share a gap are spread over it, in walk order.
947    let mut i = 0;
948    while i < gaps.len() {
949        let (_, before, after) = gaps[i];
950        let mut j = i;
951        while j < gaps.len() && (gaps[j].1, gaps[j].2) == (before, after) {
952            j += 1;
953        }
954        let k = (j - i) as i64;
955        for (n, (path, _, _)) in gaps[i..j].iter().enumerate() {
956            let n = n as i64;
957            let seq = match (before, after) {
958                (Some(a), Some(b)) => {
959                    let step = (b - a) / (k + 1);
960                    if step < 1 {
961                        return Ok(None);
962                    }
963                    a.checked_add(step * (n + 1))
964                }
965                (Some(a), None) => a.checked_add(WALK_SEQ_GAP * (n + 1)),
966                (None, Some(b)) => b.checked_sub(WALK_SEQ_GAP * (k - n)),
967                (None, None) => Some(WALK_SEQ_GAP * n),
968            };
969            let Some(seq) = seq else { return Ok(None) };
970            out.insert(path.to_string(), seq);
971        }
972        i = j;
973    }
974    Ok(Some(out))
975}
976
977/// `file_path` relative to `root` with forward slashes (a path that is not under
978/// `root` loses a leading `./`): the path the stores and meta.db use, the same
979/// on every OS.
980fn normalize_rel(root: &Path, file_path: &Path) -> String {
981    match file_path.strip_prefix(root) {
982        Ok(rel) => rel.to_string_lossy().replace('\\', "/"),
983        Err(_) => file_path
984            .to_string_lossy()
985            .trim_start_matches("./")
986            .replace('\\', "/"),
987    }
988}
989
990/// A path segment the walker treats as hidden: a dot-name other than `.` / `..`.
991/// Shared by the walker policy, the freshness check and the zero-result hint.
992pub fn is_hidden_segment(seg: &str) -> bool {
993    seg.len() > 1 && seg.starts_with('.') && seg != ".."
994}
995
996/// ripgrep's binary rule: a NUL byte anywhere in the file.
997///
998/// Not "in the first 8 KB": a protobuf blob on the Kubernetes checkout
999/// (`swagger.pb`, 4109 word matches) carries its first NUL past that point, and
1000/// ripgrep still skips it. The indexer holds the whole file in memory when it
1001/// asks, so the full scan is free; `memchr` makes it a few GB/s.
1002pub fn is_binary(bytes: &[u8]) -> bool {
1003    memchr::memchr(0, bytes).is_some()
1004}
1005
1006/// [`is_binary`] on the file at `path`. A file that cannot be read is not called
1007/// binary here; the read that follows reports the error. Callers apply this only
1008/// to non-code files under `max_file_size`.
1009pub fn looks_binary(path: &Path) -> bool {
1010    match std::fs::read(path) {
1011        Ok(bytes) => is_binary(&bytes),
1012        Err(_) => false,
1013    }
1014}
1015
1016/// Phase timings of one run, logged as one line.
1017struct Laps {
1018    last: Instant,
1019    line: String,
1020}
1021
1022impl Laps {
1023    fn new() -> Self {
1024        Self {
1025            last: Instant::now(),
1026            line: String::new(),
1027        }
1028    }
1029
1030    fn lap(&mut self, name: &str) {
1031        use std::fmt::Write;
1032        let _ = write!(
1033            self.line,
1034            " {}={:.1}",
1035            name,
1036            self.last.elapsed().as_secs_f64() * 1000.0
1037        );
1038        self.last = Instant::now();
1039    }
1040}
1041
1042/// What `Indexer::update_paths` does with one named path.
1043enum Named {
1044    /// Nothing indexed can depend on it (outside the tree, `.git/`, `.reflex/`).
1045    Skip,
1046    /// It needs a full run: an ignore file, the project config, a resolver config,
1047    /// the root itself, or a path that leaves the root.
1048    Full,
1049    /// A path under the root, relative and `/`-separated.
1050    Path(String),
1051}
1052
1053fn classify_named(root: &Path, abs_root: &Path, path: &Path) -> Named {
1054    let rel = if path.is_absolute() {
1055        match path
1056            .strip_prefix(root)
1057            .or_else(|_| path.strip_prefix(abs_root))
1058        {
1059            Ok(rel) => rel,
1060            Err(_) => return Named::Skip,
1061        }
1062    } else {
1063        path
1064    };
1065    let mut parts: Vec<String> = Vec::new();
1066    for component in rel.components() {
1067        match component {
1068            std::path::Component::Normal(s) => parts.push(s.to_string_lossy().into_owned()),
1069            std::path::Component::CurDir => {}
1070            _ => return Named::Full,
1071        }
1072    }
1073    let Some(name) = parts.last() else {
1074        return Named::Full;
1075    };
1076    if parts[0] == ".git" {
1077        return Named::Skip;
1078    }
1079    if parts[0] == crate::cache::CACHE_DIR {
1080        return if parts.len() == 2 && parts[1] == "config.toml" {
1081            Named::Full
1082        } else {
1083            Named::Skip
1084        };
1085    }
1086    if is_ignore_file_name(name) || crate::dependency_resolve::is_resolver_config_name(name) {
1087        return Named::Full;
1088    }
1089    Named::Path(parts.join("/"))
1090}
1091
1092/// `statistics` key: the rule files an index run saw, as a JSON map from path
1093/// (relative to the root) to the blake3 of its bytes (`""` when absent). The rule
1094/// files decide WHICH files are indexed, so a change to one makes the index stale
1095/// although no indexed file changed. Older binaries ignore the key.
1096pub(crate) const RULE_FILES_KEY: &str = "rule_files";
1097
1098/// Rule files compared on every freshness check: Reflex's config and the root's
1099/// ignore files. Nested ignore files are compared when git lists them.
1100pub(crate) const FIXED_RULE_FILES: [&str; 4] =
1101    [".reflex/config.toml", ".gitignore", ".ignore", ".rgignore"];
1102
1103/// Whether `name` is an ignore file the walker reads in every directory.
1104pub(crate) fn is_ignore_file_name(name: &str) -> bool {
1105    matches!(name, ".gitignore" | ".ignore" | ".rgignore")
1106}
1107
1108/// Whether the path `rel` (relative, `/`-separated) is a rule file.
1109pub(crate) fn is_rule_file(rel: &str) -> bool {
1110    rel == FIXED_RULE_FILES[0] || is_ignore_file_name(rel.rsplit('/').next().unwrap_or(rel))
1111}
1112
1113/// The blake3 of the rule file at `rel`, or `""` when it cannot be read.
1114pub(crate) fn rule_file_hash(root: &Path, rel: &str) -> String {
1115    match std::fs::read(root.join(rel)) {
1116        Ok(bytes) => blake3::hash(&bytes).to_hex().to_string(),
1117        Err(_) => String::new(),
1118    }
1119}
1120
1121/// The rule-file record of an index run over `root`: the fixed files, and every
1122/// ignore file in `dirty` (the paths `git status` listed).
1123fn rule_files_record<'a>(root: &Path, dirty: impl IntoIterator<Item = &'a String>) -> String {
1124    let mut record: std::collections::BTreeMap<String, String> = FIXED_RULE_FILES
1125        .iter()
1126        .map(|rel| (rel.to_string(), rule_file_hash(root, rel)))
1127        .collect();
1128    for rel in dirty {
1129        if is_rule_file(rel) {
1130            record.insert(rel.clone(), rule_file_hash(root, rel));
1131        }
1132    }
1133    serde_json::to_string(&record).unwrap_or_default()
1134}
1135
1136/// Whether a directory holds a file named like a resolver config at any depth (no
1137/// ignore rules: a superset of what the config walk would find).
1138fn holds_resolver_config(dir: &Path) -> bool {
1139    ignore::WalkBuilder::new(dir)
1140        .standard_filters(false)
1141        .build()
1142        .flatten()
1143        .any(|e| {
1144            e.file_name()
1145                .to_str()
1146                .is_some_and(crate::dependency_resolve::is_resolver_config_name)
1147        })
1148}
1149
1150/// Drops the shared query handles for a workspace when an index run ends,
1151/// on every exit path including errors and panics.
1152struct InvalidateOnDrop(std::path::PathBuf);
1153
1154impl Drop for InvalidateOnDrop {
1155    fn drop(&mut self) {
1156        crate::query::invalidate_caches(&self.0);
1157    }
1158}
1159
1160impl Indexer {
1161    /// Create a new indexer with the given cache manager and config
1162    pub fn new(cache: CacheManager, config: IndexConfig) -> Self {
1163        Self {
1164            cache,
1165            config,
1166            batch_limits: None,
1167            merge_limits: None,
1168            recent_limits: None,
1169            abort_at: None,
1170            rules_pending: std::sync::Mutex::new(None),
1171        }
1172    }
1173
1174    /// Override the per-batch limits (files, bytes). For tests that need to
1175    /// exercise multi-batch builds on small trees; production reads
1176    /// `REFLEX_INDEX_BATCH_FILES` / `REFLEX_INDEX_BATCH_BYTES` or the defaults.
1177    #[doc(hidden)]
1178    pub fn set_batch_limits(&mut self, max_files: usize, max_bytes: u64) {
1179        self.batch_limits = Some((max_files, max_bytes));
1180    }
1181
1182    /// Override the delta's merge limits (files, text bytes). For tests: a small
1183    /// tree would otherwise merge on every update under the 5 % rule.
1184    #[doc(hidden)]
1185    pub fn set_merge_limits(&mut self, max_files: usize, max_bytes: u64) {
1186        self.merge_limits = Some((max_files, max_bytes));
1187    }
1188
1189    /// Abort the process at a named write point, to test crash safety. A delta
1190    /// publish has `delta-files` (stores written), `unlinked` (fixed names
1191    /// removed), `manifest` (published) and `meta` (meta.db committed); a full
1192    /// build has `base-files`, `base-manifest` and `base-meta`.
1193    #[doc(hidden)]
1194    pub fn set_abort_point(&mut self, point: &str) {
1195        self.abort_at = Some(point.to_string());
1196    }
1197
1198    fn abort_point(&self, point: &str) {
1199        if self.abort_at.as_deref() == Some(point) {
1200            // No destructor, no later write: what a killed process leaves.
1201            std::process::exit(ABORT_EXIT_CODE);
1202        }
1203    }
1204
1205    /// Override the recent segment's limits (files, text bytes) before it is
1206    /// folded into the delta. For tests.
1207    #[doc(hidden)]
1208    pub fn set_recent_limits(&mut self, max_files: usize, max_bytes: u64) {
1209        self.recent_limits = Some((max_files, max_bytes));
1210    }
1211
1212    fn recent_limits(&self, max_files: usize, max_bytes: u64) -> (usize, u64) {
1213        self.recent_limits.unwrap_or((
1214            RECENT_MAX_FILES.min(max_files),
1215            max_bytes / RECENT_BYTES_DIVISOR,
1216        ))
1217    }
1218
1219    fn merge_limits(&self, live_corpus_bytes: u64) -> (usize, u64) {
1220        self.merge_limits.unwrap_or((
1221            DELTA_MAX_FILES,
1222            live_corpus_bytes * DELTA_MAX_CORPUS_PERCENT / 100,
1223        ))
1224    }
1225
1226    fn batch_limits(&self) -> (usize, u64) {
1227        if let Some(limits) = self.batch_limits {
1228            return limits;
1229        }
1230        let files = std::env::var("REFLEX_INDEX_BATCH_FILES")
1231            .ok()
1232            .and_then(|v| v.parse::<usize>().ok())
1233            .filter(|&n| n > 0)
1234            .unwrap_or(BATCH_MAX_FILES);
1235        let bytes = std::env::var("REFLEX_INDEX_BATCH_BYTES")
1236            .ok()
1237            .and_then(|v| v.parse::<u64>().ok())
1238            .filter(|&n| n > 0)
1239            .unwrap_or(BATCH_MAX_BYTES);
1240        (files, bytes)
1241    }
1242
1243    /// The `[index] include/exclude` policy for a workspace root.
1244    pub fn path_policy(&self, root: &Path) -> PathPolicy {
1245        PathPolicy::from_config(root, &self.config)
1246    }
1247
1248    /// Build or update the index for the given root directory
1249    pub fn index(&self, root: impl AsRef<Path>, show_progress: bool) -> Result<IndexStats> {
1250        self.index_with_callback(root, show_progress, None)
1251    }
1252
1253    /// Bring the index up to date with changes to `paths` alone, without walking
1254    /// the tree: for a caller that already knows what changed (a file watcher, an
1255    /// editor). `paths` are files or directories, absolute or relative to `root`,
1256    /// that were added, modified or deleted; a rename names both paths.
1257    ///
1258    /// When every changed path is named, the index then holds what
1259    /// [`Indexer::index`] would build. The run falls back to [`Indexer::index`]
1260    /// when the change cannot be applied alone: an ignore file, `.reflex/config.toml`
1261    /// or a resolver config (`go.mod`, `tsconfig.json`, ...) is involved, the branch
1262    /// changed, the delta would pass its merge limits, or the index is not one an
1263    /// update can start from.
1264    pub fn update_paths(&self, root: impl AsRef<Path>, paths: &[PathBuf]) -> Result<IndexStats> {
1265        let root = root.as_ref();
1266        match self.try_update_paths(root, paths)? {
1267            Some(stats) => Ok(stats),
1268            None => {
1269                log::info!("update_paths: the change needs a full index run");
1270                self.index(root, false)
1271            }
1272        }
1273    }
1274
1275    /// [`Self::update_paths`] without the fallback: `None` when a full run is
1276    /// needed (nothing was written). For tests that check which path ran.
1277    #[doc(hidden)]
1278    pub fn try_update_paths(&self, root: &Path, paths: &[PathBuf]) -> Result<Option<IndexStats>> {
1279        let started = Instant::now();
1280        let mut laps = Laps::new();
1281        let cache_dir = self.cache.path().to_path_buf();
1282        if !cache_dir.join(crate::cache::META_DB).exists() {
1283            return Ok(None);
1284        }
1285        let abs_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
1286        let mut named: Vec<String> = Vec::new();
1287        for path in paths {
1288            match classify_named(root, &abs_root, path) {
1289                Named::Skip => {}
1290                Named::Full => return Ok(None),
1291                Named::Path(rel) => named.push(rel),
1292            }
1293        }
1294        named.sort();
1295        named.dedup();
1296
1297        // `git status` of the named paths runs while the rest is prepared.
1298        let in_git = crate::git::is_git_repo(root);
1299        let spawn_status = |specs: Vec<String>| {
1300            let root = root.to_path_buf();
1301            std::thread::spawn(move || {
1302                if specs.len() > 1000 {
1303                    crate::git::changed_paths(&root)
1304                } else {
1305                    let refs: Vec<&str> = specs.iter().map(String::as_str).collect();
1306                    crate::git::changed_paths_in(&root, &refs)
1307                }
1308            })
1309        };
1310        let mut status_jobs = Vec::new();
1311        if in_git && !named.is_empty() {
1312            status_jobs.push(spawn_status(named.clone()));
1313        }
1314
1315        // The start of a run, as in `index_with_callback`.
1316        let _index_lock = crate::atomic_write::IndexLock::acquire_with_timeout(
1317            &cache_dir,
1318            std::time::Duration::from_secs(self.config.lock_wait_secs),
1319        )?;
1320        crate::atomic_write::remove_stale_tmp(&cache_dir);
1321        crate::query::invalidate_caches(root);
1322        let _invalidate_on_exit = InvalidateOnDrop(root.to_path_buf());
1323        self.yield_to_symbol_pass(&cache_dir)?;
1324        laps.lap("lock");
1325        self.cache.assert_writable(false)?;
1326        if !self.cache.check_schema_hash().unwrap_or(false)
1327            || !self.cache.check_extraction_hash().unwrap_or(false)
1328        {
1329            return Ok(None);
1330        }
1331        let run_start = self.run_marker(&cache_dir);
1332        laps.lap("checks");
1333
1334        let conn = crate::cache::open_meta_db(cache_dir.join(crate::cache::META_DB))?;
1335        let file_count = crate::meta_update::count_files(&conn)?;
1336        let stored_digest = crate::meta_update::get_statistic(&conn, RESOLVER_DIGEST_KEY)?;
1337        let meta_generation = crate::meta_update::get_statistic(&conn, INDEX_GENERATION_KEY)?
1338            .and_then(|g| g.parse::<u64>().ok());
1339        let synced_branch =
1340            crate::meta_update::get_statistic(&conn, crate::meta_update::SYNCED_BRANCH_KEY)?;
1341        let (Some(generation), Ok(indexed)) =
1342            (meta_generation, CacheManager::latest_branch_info_on(&conn))
1343        else {
1344            return Ok(None);
1345        };
1346        if !self.stores_intact(file_count, meta_generation) {
1347            return Ok(None);
1348        }
1349        let generation = generation + 1;
1350        laps.lap("snapshot");
1351
1352        // The resolver configs the last walk found, unchanged since.
1353        let Some(resolver_configs) = crate::dependency_resolve::ResolverConfigs::from_saved_list(
1354            root,
1355            &cache_dir,
1356            &self.config.vendored_patterns,
1357        ) else {
1358            return Ok(None);
1359        };
1360        if stored_digest.as_deref() != Some(resolver_configs.digest.as_str()) {
1361            return Ok(None);
1362        }
1363        laps.lap("configs");
1364
1365        // Git: still the branch last indexed; a HEAD that moved adds what it changed.
1366        let (branch, commit) = if in_git {
1367            let Ok((commit, branch)) = crate::git::head_commit_and_branch(root) else {
1368                return Ok(None);
1369            };
1370            (branch, Some(commit))
1371        } else {
1372            ("_default".to_string(), None)
1373        };
1374        // Only the branch whose rows the last run synced (its rows are then
1375        // updated one by one).
1376        if synced_branch.as_deref() != Some(branch.as_str()) || branch != indexed.branch {
1377            return Ok(None);
1378        }
1379        if let Some(commit) = &commit
1380            && *commit != indexed.commit_sha
1381        {
1382            let Ok(moved) = crate::git::diff_names(root, &indexed.commit_sha, commit) else {
1383                return Ok(None);
1384            };
1385            let mut extra: Vec<String> = Vec::new();
1386            for path in moved {
1387                match classify_named(root, &abs_root, Path::new(&path)) {
1388                    Named::Skip => {}
1389                    Named::Full => return Ok(None),
1390                    Named::Path(rel) => {
1391                        if named.binary_search(&rel).is_err() {
1392                            extra.push(rel);
1393                        }
1394                    }
1395                }
1396            }
1397            if !extra.is_empty() {
1398                status_jobs.push(spawn_status(extra.clone()));
1399                named.extend(extra);
1400                named.sort();
1401                named.dedup();
1402            }
1403        }
1404        if resolver_configs.lists_any_under(root, &named)
1405            || named.iter().any(|rel| {
1406                let dir = root.join(rel);
1407                dir.is_dir() && holds_resolver_config(&dir)
1408            })
1409        {
1410            return Ok(None);
1411        }
1412        let targets = Arc::new(Targets::new(&named));
1413        laps.lap("git");
1414
1415        // The rows at and under the named paths, and those paths as a full walk
1416        // would see them now.
1417        let stored = crate::meta_update::load_rows_under(&conn, &named)?;
1418        let Discovered {
1419            rels: found_rels,
1420            metas: found_metas,
1421            skipped_too_large,
1422            skipped_bytes_too_large,
1423            skipped_binary,
1424            ..
1425        } = self.discover_files_in(root, &stored, Some(Arc::clone(&targets)))?;
1426        let found: HashMap<&str, usize> = found_rels
1427            .iter()
1428            .enumerate()
1429            .map(|(i, rel)| (rel.as_str(), i))
1430            .collect();
1431        laps.lap("walk");
1432
1433        // What changed, by the rules of a full run.
1434        let num_threads = crate::models::resolve_thread_count(self.config.parallel_threads, 32);
1435        let pool = rayon::ThreadPoolBuilder::new()
1436            .num_threads(num_threads)
1437            .build()
1438            .context("Failed to create thread pool")?;
1439        let to_hash: Vec<usize> = (0..found_rels.len())
1440            .filter(|&i| {
1441                stored.get(&found_rels[i]).is_some_and(|row| {
1442                    !found_metas[i]
1443                        .as_ref()
1444                        .is_some_and(|md| row.stat_matches(md))
1445                })
1446            })
1447            .collect();
1448        let hashed: Vec<(usize, Option<String>)> = pool.install(|| {
1449            to_hash
1450                .par_iter()
1451                .map(|&i| {
1452                    let hash = std::fs::read(root.join(&found_rels[i]))
1453                        .ok()
1454                        .map(|b| self.hash_content(&b));
1455                    (i, hash)
1456                })
1457                .collect()
1458        });
1459        let mut found_status: Vec<FileStatus> = found_rels
1460            .iter()
1461            .map(|rel| {
1462                if stored.contains_key(rel) {
1463                    FileStatus::Unchanged
1464                } else {
1465                    FileStatus::Added
1466                }
1467            })
1468            .collect();
1469        for (i, hash) in hashed {
1470            found_status[i] = match hash {
1471                Some(h) if h == stored[&found_rels[i]].hash => FileStatus::Touched,
1472                _ => FileStatus::Modified,
1473            };
1474        }
1475        let rewritten =
1476            |i: usize| matches!(found_status[i], FileStatus::Added | FileStatus::Modified);
1477        // Indexed paths at or under a named path that the walk no longer yields.
1478        let deleted: Vec<&str> = {
1479            let mut d: Vec<&str> = stored
1480                .keys()
1481                .map(String::as_str)
1482                .filter(|p| !found.contains_key(p))
1483                .collect();
1484            d.sort_unstable();
1485            d
1486        };
1487        laps.lap("hash");
1488
1489        // Walk positions of the rewritten files.
1490        let to_place: Vec<(&str, Option<&crate::meta_update::StoredFile>)> = (0..found_rels.len())
1491            .filter(|&i| rewritten(i))
1492            .map(|i| (found_rels[i].as_str(), stored.get(&found_rels[i])))
1493            .collect();
1494        let deleted_ids: std::collections::HashSet<i64> =
1495            deleted.iter().map(|p| stored[*p].id).collect();
1496        let mut walk_order = crate::walk_order::WalkOrder::new(root);
1497        let Some(seq_of) = place_rewrites(&conn, &mut walk_order, &to_place, &deleted_ids)? else {
1498            return Ok(None);
1499        };
1500        drop(conn);
1501        let added = found_status
1502            .iter()
1503            .filter(|s| **s == FileStatus::Added)
1504            .count();
1505        let live_files = file_count - deleted.len() + added;
1506        laps.lap("order");
1507
1508        let mut rewrites = Vec::new();
1509        let mut rewrite_rows = HashMap::new();
1510        for (i, rel) in found_rels.iter().enumerate() {
1511            if rewritten(i) {
1512                rewrites.push(Rewrite {
1513                    rel: rel.clone(),
1514                    size: found_metas[i].as_ref().map_or(0, |md| md.size()),
1515                    walk_seq: seq_of[rel],
1516                });
1517                if let Some(row) = stored.get(rel) {
1518                    rewrite_rows.insert(rel.clone(), row.clone());
1519                }
1520            }
1521        }
1522        // Dirty flags of the named paths as `git status` lists them now (every other
1523        // row keeps the flag it has), joined only when meta.db is written. If git
1524        // fails, every named path counts as dirty: a superset is safe for freshness.
1525        let dirty_job = || -> DirtyFlags {
1526            let mut now_dirty: std::collections::HashSet<String> = std::collections::HashSet::new();
1527            let mut ok = true;
1528            for job in status_jobs {
1529                match job.join() {
1530                    Ok(Ok(paths)) => now_dirty.extend(paths),
1531                    _ => ok = false,
1532                }
1533            }
1534            let is_dirty = |rel: &str| !ok || now_dirty.contains(rel);
1535            let mut flags = DirtyFlags {
1536                rewrites: std::collections::HashSet::new(),
1537                touched: Vec::new(),
1538                flips: Vec::new(),
1539                git_dirty: in_git && (indexed.is_dirty || !ok || !now_dirty.is_empty()),
1540            };
1541            for (i, rel) in found_rels.iter().enumerate() {
1542                let dirty = is_dirty(rel);
1543                if rewritten(i) {
1544                    if dirty {
1545                        flags.rewrites.insert(rel.clone());
1546                    }
1547                } else if let Some(row) = stored.get(rel) {
1548                    if found_status[i] == FileStatus::Touched {
1549                        let (size, mtime) = found_metas[i]
1550                            .as_ref()
1551                            .map(|md| (md.size(), md.recorded_mtime_ns(run_start)))
1552                            .unwrap_or((0, 0));
1553                        flags.touched.push((row.id, size, mtime, dirty));
1554                    } else if dirty != row.dirty {
1555                        flags.flips.push((row.id, dirty));
1556                    }
1557                }
1558            }
1559            flags
1560        };
1561        // The branch's own hashes of the rewritten paths; every other file's row
1562        // matches its hash (the last run on this branch synced them all).
1563        let branch_hashes: HashMap<String, String> = {
1564            let conn = crate::cache::open_meta_db(cache_dir.join(crate::cache::META_DB))?;
1565            let mut stmt = conn.prepare(
1566                "SELECT fb.hash FROM file_branches fb
1567                 JOIN files f ON f.id = fb.file_id
1568                 JOIN branches b ON b.id = fb.branch_id
1569                 WHERE b.name = ? AND f.path = ?",
1570            )?;
1571            let mut out = HashMap::new();
1572            for r in &rewrites {
1573                let hash: Option<String> = rusqlite::OptionalExtension::optional(
1574                    stmt.query_row(rusqlite::params![branch, r.rel], |row| row.get(0)),
1575                )?;
1576                if let Some(hash) = hash {
1577                    out.insert(r.rel.clone(), hash);
1578                }
1579            }
1580            out
1581        };
1582        let skipped = (skipped_too_large, skipped_bytes_too_large, skipped_binary);
1583        let rewritten_count = rewrites.len();
1584        laps.lap("change_set");
1585
1586        let result = if deleted.is_empty() && rewrites.is_empty() {
1587            let flags = dirty_job();
1588            self.refresh_named(RefreshNamed {
1589                touched: &flags.touched,
1590                flips: &flags.flips,
1591                walk_moves: &[],
1592                branch: &branch,
1593                commit: commit.as_deref(),
1594                git_dirty: flags.git_dirty,
1595                live_files,
1596                skipped,
1597            })
1598            .map(Some)
1599        } else {
1600            let deleted_file_count = deleted.iter().filter(|p| !root.join(p).exists()).count();
1601            self.publish_delta(DeltaChanges {
1602                root,
1603                rewrites,
1604                deleted: deleted
1605                    .iter()
1606                    .map(|p| (p.to_string(), stored[*p].id))
1607                    .collect(),
1608                walk_moves: Vec::new(),
1609                dirty: Box::new(dirty_job),
1610                stored: rewrite_rows,
1611                sync_all_branch_rows: false,
1612                full_stats: false,
1613                live_files,
1614                breakdown_rest: (0, 0, live_files - rewritten_count),
1615                branch_hashes,
1616                branch: &branch,
1617                commit: commit.as_deref(),
1618                resolver_configs: &resolver_configs,
1619                run_start,
1620                generation,
1621                pool: &pool,
1622                deleted_file_count,
1623                skipped,
1624            })
1625        };
1626        laps.lap("publish");
1627        log::info!(
1628            "update_paths: {} named paths, {} rewritten, {} deleted in {} ms;{}",
1629            named.len(),
1630            rewritten_count,
1631            deleted.len(),
1632            started.elapsed().as_millis(),
1633            laps.line
1634        );
1635        result
1636    }
1637
1638    /// How long to wait for a running symbol pass to yield the database.
1639    ///
1640    /// One batch is 128 files, so a pass normally yields in well under a second.
1641    /// 10s covers a slow batch without making the caller wait out a whole pass.
1642    const SYMBOL_PASS_YIELD_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
1643
1644    /// Wait for the detached background symbol pass to release `meta.db`.
1645    ///
1646    /// The pass (`rfx index-symbols-internal`) runs for minutes on a large repo and
1647    /// holds a SQLite write lock the whole time, but takes its own `indexing.lock`
1648    /// rather than the workspace `index.lock`. In 1.7.0 that meant every
1649    /// `index_project` and `rfx index` during the window failed with a raw
1650    /// `Failed to begin meta.db schema transaction: database is locked`.
1651    ///
1652    /// Asks the pass to stop at its next batch, then waits briefly. If it does not
1653    /// yield, returns [`ReflexError::SymbolIndexingInProgress`], which names the pid
1654    /// and the progress — never SQLite's error text.
1655    fn yield_to_symbol_pass(&self, cache_dir: &Path) -> Result<()> {
1656        use crate::background_indexer::BackgroundIndexer;
1657
1658        let Some(holder) = BackgroundIndexer::lock_holder(cache_dir) else {
1659            // Nothing running (or the lock was stale and has just been reaped).
1660            BackgroundIndexer::clear_cancel(cache_dir);
1661            return Ok(());
1662        };
1663
1664        log::info!(
1665            "Symbol indexing is running (pid {}); asking it to yield",
1666            holder.pid
1667        );
1668        let _ = BackgroundIndexer::request_cancel(cache_dir);
1669
1670        let deadline = std::time::Instant::now() + Self::SYMBOL_PASS_YIELD_TIMEOUT;
1671        // A pass that has nothing left to do exits within milliseconds: poll fast
1672        // first, then every 100 ms.
1673        let mut pause = std::time::Duration::from_millis(5);
1674        while std::time::Instant::now() < deadline {
1675            if !BackgroundIndexer::is_running(cache_dir) {
1676                BackgroundIndexer::clear_cancel(cache_dir);
1677                log::info!("Symbol indexing yielded; continuing");
1678                return Ok(());
1679            }
1680            std::thread::sleep(pause);
1681            pause = (pause * 2).min(std::time::Duration::from_millis(100));
1682        }
1683
1684        // It did not yield. Report what it is doing, then leave it alone.
1685        BackgroundIndexer::clear_cancel(cache_dir);
1686        let status = BackgroundIndexer::get_status(cache_dir).ok().flatten();
1687        Err(crate::errors::ReflexError::SymbolIndexingInProgress {
1688            pid: holder.pid,
1689            started_at: holder.started_clock(),
1690            processed: status.as_ref().map(|s| s.processed_files).unwrap_or(0),
1691            total: status.as_ref().map(|s| s.total_files).unwrap_or(0),
1692        }
1693        .into())
1694    }
1695
1696    /// Build or update the index with progress callback support
1697    pub fn index_with_callback(
1698        &self,
1699        root: impl AsRef<Path>,
1700        show_progress: bool,
1701        progress_callback: Option<ProgressCallback>,
1702    ) -> Result<IndexStats> {
1703        let root = root.as_ref();
1704        let stats = self.index_run(root, show_progress, progress_callback)?;
1705        // The rule files this run indexed under, once its index is published. A
1706        // crash before this write leaves the old record: the next check reports
1707        // the rules as changed and the next run writes it.
1708        let pending = self
1709            .rules_pending
1710            .lock()
1711            .unwrap_or_else(|e| e.into_inner())
1712            .take();
1713        if let Some(record) = pending {
1714            let conn = crate::cache::open_meta_db(self.cache.path().join(crate::cache::META_DB))?;
1715            crate::meta_update::set_statistic(
1716                &conn,
1717                RULE_FILES_KEY,
1718                &record,
1719                chrono::Utc::now().timestamp(),
1720            )?;
1721            crate::query::invalidate_caches(root);
1722        }
1723        Ok(stats)
1724    }
1725
1726    fn index_run(
1727        &self,
1728        root: &Path,
1729        show_progress: bool,
1730        progress_callback: Option<ProgressCallback>,
1731    ) -> Result<IndexStats> {
1732        log::info!("Indexing directory: {:?}", root);
1733        let mut laps = Laps::new();
1734
1735        // Exclusive workspace lock for the whole run. Two indexers streaming
1736        // into the same content.bin/trigrams.bin is how a reader ends up with a
1737        // short file. The OS drops the lock if this process dies.
1738        let cache_dir = self.cache.path().to_path_buf();
1739        let _index_lock = crate::atomic_write::IndexLock::acquire_with_timeout(
1740            &cache_dir,
1741            std::time::Duration::from_secs(self.config.lock_wait_secs),
1742        )?;
1743        // A previous indexer that died mid-write leaves `*.tmp` behind.
1744        crate::atomic_write::remove_stale_tmp(&cache_dir);
1745
1746        // Any open handle on the stores about to be rewritten is dropped now, and
1747        // again on every exit path below, so a query in this process never reads a
1748        // mix of old and new files and never keeps a memo of a stale verdict.
1749        crate::query::invalidate_caches(root);
1750        let _invalidate_on_exit = InvalidateOnDrop(root.to_path_buf());
1751
1752        // The detached symbol pass holds meta.db but NOT this lock, so acquiring
1753        // `index.lock` above proves nothing about SQLite. Yield to it here, before
1754        // `cache.init()` runs `BEGIN IMMEDIATE`, so a waiting agent sees progress
1755        // instead of `database is locked: Error code 5`.
1756        self.yield_to_symbol_pass(&cache_dir)?;
1757        laps.lap("lock");
1758
1759        // Configure thread pool for parallel processing.
1760        // 0 = auto (80% of available cores, up to 32 — the query pool's rule).
1761        // The pool reads, hashes, extracts imports and trigrams; the only serial
1762        // work left is streaming file bytes into content.bin. Peak memory is set
1763        // by the batch byte budget, not by the thread count.
1764        let num_threads = crate::models::resolve_thread_count(self.config.parallel_threads, 32);
1765
1766        log::info!(
1767            "Using {} threads for parallel indexing (out of {} available)",
1768            num_threads,
1769            std::thread::available_parallelism()
1770                .map(|n| n.get())
1771                .unwrap_or(4)
1772        );
1773
1774        // Refuse to write a cache another Reflex build owns.
1775        //
1776        // A `force` rebuild clears `.reflex/` first, so there is no meta.db left to
1777        // conflict with and this passes — taking ownership is exactly what force
1778        // means. Checked before `init()`, which is itself a write.
1779        self.cache.assert_writable(false)?;
1780
1781        // Whether the cache was last completed by a binary with this cache schema.
1782        // Read BEFORE `init()`: a cache from other code must be rebuilt in full, and
1783        // a new cache has nothing to reuse either way.
1784        let schema_ok = self.cache.check_schema_hash().unwrap_or(false);
1785        let extraction_ok = self.cache.check_extraction_hash().unwrap_or(false);
1786
1787        // Ensure cache is initialized. A cache this binary completed a run on has
1788        // every table: only `config.toml` may need recreating.
1789        if schema_ok && extraction_ok {
1790            self.cache.ensure_config()?;
1791        } else {
1792            self.cache.init()?;
1793        }
1794
1795        // Extraction code (parsers, resolution) changed since this cache was last
1796        // written: stored symbols are from other code, and every file's imports
1797        // are extracted again below.
1798        if !schema_ok || !extraction_ok {
1799            match self.cache.clear_symbol_cache() {
1800                Ok(n) if n > 0 => {
1801                    log::info!("Cleared {} symbol cache rows written by other code", n)
1802                }
1803                Ok(_) => {}
1804                Err(e) => log::warn!("Failed to clear the symbol cache: {}", e),
1805            }
1806        }
1807
1808        // Files modified at or after this run began record an unknown mtime (0), so
1809        // a write racing the read is caught by hash on the next check. The threshold
1810        // is the mtime of a file written now, on the same (coarse) clock that stamps
1811        // the files: a write in the same tick as a read could otherwise carry an
1812        // mtime just below a process-clock `run_start` and be trusted forever.
1813        let run_start = self.run_marker(&cache_dir);
1814
1815        laps.lap("init");
1816
1817        let pool = rayon::ThreadPoolBuilder::new()
1818            .num_threads(num_threads)
1819            .build()
1820            .context("Failed to create thread pool")?;
1821
1822        // Step 1: walk the tree. In parallel, load what meta.db holds (one row per
1823        // path of the last indexed tree), ask git for the branch and the dirty
1824        // paths, and find the resolver configs (each is its own walk or subprocess).
1825        let meta_path = cache_dir.join(crate::cache::META_DB);
1826        let phase_start = Instant::now();
1827        let (git_state, resolver_configs, meta_read, walked) = std::thread::scope(|scope| {
1828            let git = scope.spawn(|| {
1829                let t = Instant::now();
1830                let r = crate::git::get_git_state_optional(root);
1831                (r, t.elapsed().as_millis())
1832            });
1833            let configs = scope.spawn(|| {
1834                let t = Instant::now();
1835                let r = crate::dependency_resolve::ResolverConfigs::discover(
1836                    root,
1837                    &self.config.vendored_patterns,
1838                );
1839                (r, t.elapsed().as_millis())
1840            });
1841            // Available disk space (a `df` subprocess), now that the cache exists.
1842            let disk = scope.spawn(|| self.check_disk_space(root));
1843            let meta_read = scope.spawn(|| -> Result<_> {
1844                let t = Instant::now();
1845                let conn = crate::cache::open_meta_db(&meta_path)?;
1846                let rows = crate::meta_update::load_stored_files(&conn)?;
1847                log::debug!("meta.db rows read in {} ms", t.elapsed().as_millis());
1848                Ok((
1849                    rows,
1850                    crate::meta_update::get_statistic(&conn, RESOLVER_DIGEST_KEY)?,
1851                    crate::meta_update::get_statistic(&conn, INDEX_GENERATION_KEY)?
1852                        .and_then(|g| g.parse::<u64>().ok()),
1853                    crate::meta_update::get_statistic(
1854                        &conn,
1855                        crate::meta_update::SYNCED_BRANCH_KEY,
1856                    )?,
1857                    crate::meta_update::get_statistic(&conn, RULE_FILES_KEY)?,
1858                ))
1859            });
1860            let t = Instant::now();
1861            let walked = self.walk_candidates(root, None);
1862            let walk_ms = t.elapsed().as_millis();
1863            let (git, configs) = (git.join(), configs.join());
1864            log::info!(
1865                "discovery phase: walk {} ms, git {} ms, resolver configs {} ms",
1866                walk_ms,
1867                git.as_ref().map_or(0, |g| g.1),
1868                configs.as_ref().map_or(0, |c| c.1)
1869            );
1870            let disk = disk
1871                .join()
1872                .unwrap_or_else(|_| Err(anyhow::anyhow!("disk space check panicked")));
1873            (
1874                git.map(|g| g.0),
1875                configs.map(|c| c.0),
1876                meta_read.join(),
1877                walked.and_then(|w| disk.map(|()| w)),
1878            )
1879        });
1880        let (stored, stored_digest, meta_generation, synced_branch, stored_rules) =
1881            meta_read.map_err(|_| anyhow::anyhow!("meta.db read thread panicked"))??;
1882        // A non-code file is text only when it holds no NUL byte; one whose stat
1883        // matches its row was checked when it was indexed.
1884        let discovered = walked.map(|w| Self::drop_binaries(root, w, &stored, Some(&pool)));
1885        // The snapshot currently published, and the generation the next publish takes.
1886        let prev_manifest = crate::snapshot::read_manifest(&cache_dir).ok().flatten();
1887        let generation = prev_manifest
1888            .as_ref()
1889            .map(|m| m.generation)
1890            .max(meta_generation)
1891            .unwrap_or(0)
1892            + 1;
1893        let git_state = git_state.map_err(|_| anyhow::anyhow!("git state thread panicked"))??;
1894        let resolver_configs =
1895            resolver_configs.map_err(|_| anyhow::anyhow!("resolver config walk panicked"))?;
1896        // For `update_paths`, which parses the same configs without walking.
1897        if let Err(e) = resolver_configs.save_list(root, &cache_dir) {
1898            log::warn!("Failed to save the resolver config list: {:#}", e);
1899        }
1900        let Discovered {
1901            rels,
1902            sizes,
1903            metas,
1904            skipped_too_large,
1905            skipped_bytes_too_large,
1906            skipped_binary,
1907        } = discovered?;
1908        let total_files = rels.len();
1909        laps.lap("discover");
1910        log::info!(
1911            "Discovered {} files to index ({} skipped: too large, {} binary) in {} ms",
1912            total_files,
1913            skipped_too_large,
1914            skipped_binary,
1915            phase_start.elapsed().as_millis()
1916        );
1917
1918        let branch = git_state
1919            .as_ref()
1920            .map(|s| s.branch.clone())
1921            .unwrap_or_else(|| "_default".to_string());
1922        if let Some(ref state) = git_state {
1923            log::info!(
1924                "Git state: branch='{}', commit='{}', dirty={}",
1925                state.branch,
1926                state.commit,
1927                state.dirty
1928            );
1929        } else {
1930            log::info!("Not a git repository, using default branch");
1931        }
1932        let commit = git_state.as_ref().map(|s| s.commit.clone());
1933        let dirty_paths: std::collections::HashSet<String> = git_state
1934            .as_ref()
1935            .map(|s| s.dirty_paths.clone())
1936            .unwrap_or_default();
1937        let rules = rule_files_record(root, &dirty_paths);
1938        *self.rules_pending.lock().unwrap_or_else(|e| e.into_inner()) =
1939            (stored_rules.as_deref() != Some(rules.as_str())).then_some(rules);
1940
1941        // The branch's own hashes: the basis of the "new / modified / unchanged"
1942        // breakdown, as before stable ids.
1943        let in_sync = synced_branch.as_deref() == Some(branch.as_str());
1944        let existing_hashes = if in_sync {
1945            BranchHashes::Synced(&stored)
1946        } else {
1947            BranchHashes::Loaded(self.cache.load_hashes_for_branch(&branch)?)
1948        };
1949        laps.lap("branch_hashes");
1950
1951        // Step 2: what changed. A file whose (size, mtime) match its row is
1952        // unchanged without being read; the others are read and hashed.
1953        let classify_start = Instant::now();
1954        // Each walked path's row, looked up once.
1955        let rows_of: Vec<Option<&crate::meta_update::StoredFile>> =
1956            rels.iter().map(|rel| stored.get(rel)).collect();
1957        let to_hash: Vec<usize> = (0..total_files)
1958            .filter(|&i| {
1959                rows_of[i]
1960                    .is_some_and(|row| !metas[i].as_ref().is_some_and(|md| row.stat_matches(md)))
1961            })
1962            .collect();
1963        let hashed: Vec<(usize, Option<String>)> = pool.install(|| {
1964            to_hash
1965                .par_iter()
1966                .map(|&i| {
1967                    (
1968                        i,
1969                        std::fs::read(root.join(&rels[i]))
1970                            .ok()
1971                            .map(|b| self.hash_content(&b)),
1972                    )
1973                })
1974                .collect()
1975        });
1976        let mut status: Vec<FileStatus> = rows_of
1977            .iter()
1978            .map(|row| {
1979                if row.is_some() {
1980                    FileStatus::Unchanged
1981                } else {
1982                    FileStatus::Added
1983                }
1984            })
1985            .collect();
1986        for (i, hash) in hashed {
1987            status[i] = match (hash, rows_of[i]) {
1988                (Some(h), Some(row)) if h == row.hash => FileStatus::Touched,
1989                _ => FileStatus::Modified,
1990            };
1991        }
1992        // Every stored path was walked (the usual case) when as many walked paths
1993        // have a row as there are rows: nothing is gone.
1994        let walked_with_row = status.iter().filter(|s| **s != FileStatus::Added).count();
1995        let gone: Vec<&String> = if walked_with_row == stored.len() {
1996            Vec::new()
1997        } else {
1998            let discovered_set: std::collections::HashSet<&str> =
1999                rels.iter().map(String::as_str).collect();
2000            stored
2001                .keys()
2002                .filter(|p| !discovered_set.contains(p.as_str()))
2003                .collect()
2004        };
2005        // Counted as "deleted" only when the file is gone from disk (a file that is
2006        // merely no longer indexable was never counted), as before.
2007        let deleted_file_count = gone.iter().filter(|p| !root.join(p).exists()).count();
2008        let added = status.iter().filter(|s| **s == FileStatus::Added).count();
2009        let modified = status
2010            .iter()
2011            .filter(|s| **s == FileStatus::Modified)
2012            .count();
2013        log::info!(
2014            "phase classify: {} added, {} modified, {} touched, {} gone; {} files hashed in {} ms",
2015            added,
2016            modified,
2017            status.iter().filter(|s| **s == FileStatus::Touched).count(),
2018            gone.len(),
2019            to_hash.len(),
2020            classify_start.elapsed().as_millis()
2021        );
2022
2023        // Every dependency row is rewritten when the extraction code, the schema or
2024        // any resolver config (go.mod, tsconfig.json, ...) changed.
2025        let full_deps = !schema_ok
2026            || !extraction_ok
2027            || stored_digest.as_deref() != Some(resolver_configs.digest.as_str());
2028        let content_changed = added > 0 || modified > 0 || !gone.is_empty();
2029        laps.lap("classify");
2030        let stores_ok = schema_ok && self.stores_intact(stored.len(), meta_generation);
2031        laps.lap("snapshot");
2032
2033        if !content_changed && !full_deps && stores_ok {
2034            log::info!("No files changed - skipping index rebuild");
2035            log::info!("index run phases:{}", laps.line);
2036            return self.refresh_unchanged(RefreshUnchanged {
2037                rels: &rels,
2038                metas: &metas,
2039                status: &status,
2040                rows: &rows_of,
2041                existing_hashes: &existing_hashes,
2042                dirty_paths: &dirty_paths,
2043                branch: &branch,
2044                in_sync,
2045                commit: commit.as_deref(),
2046                git_dirty: git_state.as_ref().map(|s| s.dirty),
2047                run_start,
2048                skipped: (skipped_too_large, skipped_bytes_too_large, skipped_binary),
2049            });
2050        }
2051        if content_changed && !full_deps && stores_ok {
2052            // The change set from the whole walk: walk positions planned over every
2053            // file, dirty flags from `git status`.
2054            let seqs = crate::meta_update::plan_walk_seq(
2055                &rels
2056                    .iter()
2057                    .map(|rel| stored.get(rel).map(|s| s.walk_seq))
2058                    .collect::<Vec<_>>(),
2059            );
2060            let mut rewrites = Vec::new();
2061            let mut dirty_rewrites = std::collections::HashSet::new();
2062            let mut rewrite_rows = HashMap::new();
2063            let mut branch_hashes = HashMap::new();
2064            let (mut touched, mut walk_moves, mut flips) = (Vec::new(), Vec::new(), Vec::new());
2065            let mut rest: Vec<(&str, &str)> = Vec::new();
2066            for i in 0..total_files {
2067                let rel = &rels[i];
2068                let dirty = dirty_paths.contains(rel);
2069                match (status[i], stored.get(rel)) {
2070                    (FileStatus::Added | FileStatus::Modified, row) => {
2071                        rewrites.push(Rewrite {
2072                            rel: rel.clone(),
2073                            size: sizes[i],
2074                            walk_seq: seqs[i],
2075                        });
2076                        if dirty {
2077                            dirty_rewrites.insert(rel.clone());
2078                        }
2079                        if let Some(row) = row {
2080                            rewrite_rows.insert(rel.clone(), row.clone());
2081                        }
2082                        if let Some(h) = existing_hashes.get(rel) {
2083                            branch_hashes.insert(rel.clone(), h.to_string());
2084                        }
2085                    }
2086                    (_, Some(row)) => {
2087                        if seqs[i] != row.walk_seq {
2088                            walk_moves.push((row.id, seqs[i]));
2089                        }
2090                        if status[i] == FileStatus::Touched {
2091                            let (size, mtime) = metas[i]
2092                                .as_ref()
2093                                .map(|md| (md.size(), md.recorded_mtime_ns(run_start)))
2094                                .unwrap_or((0, 0));
2095                            touched.push((row.id, size, mtime, dirty));
2096                        } else if dirty != row.dirty {
2097                            flips.push((row.id, dirty));
2098                        }
2099                        rest.push((rel.as_str(), row.hash.as_str()));
2100                    }
2101                    (_, None) => unreachable!("an unchanged file has a row"),
2102                }
2103            }
2104            let git_dirty = git_state.as_ref().map(|s| s.dirty).unwrap_or(false);
2105            let changes = DeltaChanges {
2106                root,
2107                rewrites,
2108                deleted: gone.iter().map(|p| ((*p).clone(), stored[*p].id)).collect(),
2109                walk_moves,
2110                dirty: Box::new(move || DirtyFlags {
2111                    rewrites: dirty_rewrites,
2112                    touched,
2113                    flips,
2114                    git_dirty,
2115                }),
2116                stored: rewrite_rows,
2117                sync_all_branch_rows: !in_sync,
2118                full_stats: true,
2119                live_files: total_files,
2120                breakdown_rest: breakdown(rest.into_iter(), &existing_hashes),
2121                branch_hashes,
2122                branch: &branch,
2123                commit: commit.as_deref(),
2124                resolver_configs: &resolver_configs,
2125                run_start,
2126                generation,
2127                pool: &pool,
2128                deleted_file_count,
2129                skipped: (skipped_too_large, skipped_bytes_too_large, skipped_binary),
2130            };
2131            match self.publish_delta(changes)? {
2132                Some(stats) => return Ok(stats),
2133                None => log::info!("The delta would pass its limits - building a new base"),
2134            }
2135        }
2136        if full_deps {
2137            log::info!(
2138                "Resolver configs, extraction code or schema changed - re-extracting every file's imports"
2139            );
2140        }
2141
2142        // Step 3: Build trigram index + content store from every file (the stores
2143        // are rewritten in full). Imports are extracted only where they may have
2144        // changed.
2145        let mut files_indexed = 0;
2146        let mut indexed: Vec<IndexedFile> = Vec::with_capacity(total_files);
2147
2148        // Initialize trigram builder and content store. The builder spills each
2149        // batch to `<cache>/trigram_temp/` only when there is more than one batch;
2150        // a single batch stays in memory and the directory is never created.
2151        let mut trigram_builder = TrigramIndexBuilder::new(self.cache.path().join("trigram_temp"));
2152        let mut content_writer = ContentWriter::new();
2153
2154        // Initialize content writer to start streaming writes immediately
2155        let (content_name, trigrams_name, plan_name) = crate::snapshot::base_file_names(generation);
2156        let content_path = cache_dir.join(&content_name);
2157        content_writer
2158            .init(content_path.clone())
2159            .context("Failed to initialize content writer")?;
2160
2161        // Create progress bar (only if requested via --progress flag)
2162        let pb = if show_progress {
2163            let pb = ProgressBar::new(total_files as u64);
2164            pb.set_draw_target(ProgressDrawTarget::stderr());
2165            pb.set_style(
2166                ProgressStyle::default_bar()
2167                    .template("[{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} files ({percent}%) {msg}")
2168                    .unwrap()
2169                    .progress_chars("=>-")
2170            );
2171            // Force updates every 100ms to ensure progress is visible
2172            pb.enable_steady_tick(std::time::Duration::from_millis(100));
2173            pb
2174        } else {
2175            ProgressBar::hidden()
2176        };
2177
2178        // Atomic counter for thread-safe progress updates
2179        let progress_counter = Arc::new(AtomicU64::new(0));
2180        // Shared status message for progress callback
2181        let progress_status = Arc::new(Mutex::new("Indexing files...".to_string()));
2182
2183        let batch_phase_start = Instant::now();
2184        let mut pool_ms = 0u128;
2185        let mut flush_ms = 0u128;
2186
2187        // A merge: when the published stores match meta.db, a file whose bytes
2188        // are unchanged takes its text from them instead of the disk. Same text,
2189        // same order, same builder: the new base is byte-identical to a build
2190        // that reads every file.
2191        let merge_source: Option<(crate::snapshot::IndexSnapshot, HashMap<String, u32>)> =
2192            if stores_ok {
2193                crate::snapshot::IndexSnapshot::open(&cache_dir)
2194                    .ok()
2195                    .map(|snapshot| {
2196                        let ids = snapshot
2197                            .live_ids()
2198                            .filter_map(|id| {
2199                                Some((snapshot.get_file_path(id)?.to_str()?.to_string(), id))
2200                            })
2201                            .collect();
2202                        (snapshot, ids)
2203                    })
2204            } else {
2205                None
2206            };
2207        let from_snapshot = std::sync::atomic::AtomicUsize::new(0);
2208
2209        // Spawn a background thread to update progress bar and call callback during parallel processing
2210        let counter_for_thread = Arc::clone(&progress_counter);
2211        let status_for_thread = Arc::clone(&progress_status);
2212        let pb_clone = pb.clone();
2213        let callback_for_thread = progress_callback.clone();
2214        let total_files_for_thread = total_files;
2215        let progress_thread = if show_progress || callback_for_thread.is_some() {
2216            Some(std::thread::spawn(move || {
2217                loop {
2218                    let count = counter_for_thread.load(Ordering::Relaxed);
2219                    pb_clone.set_position(count);
2220
2221                    // Call progress callback if provided
2222                    if let Some(ref callback) = callback_for_thread {
2223                        let status = status_for_thread.lock().unwrap().clone();
2224                        callback(count as usize, total_files_for_thread, status);
2225                    }
2226
2227                    if count >= total_files_for_thread as u64 {
2228                        break;
2229                    }
2230                    std::thread::sleep(std::time::Duration::from_millis(50));
2231                }
2232            }))
2233        } else {
2234            None
2235        };
2236
2237        // Process files in batches to bound memory: a batch holds at most
2238        // `max_files` files and about `max_bytes` bytes of text, so the pool's
2239        // in-flight contents and the trigram build's postings stay bounded on
2240        // any tree.
2241        let (max_files, max_bytes) = self.batch_limits();
2242        let batches = plan_batches(&sizes, max_files, max_bytes);
2243        let num_batches = batches.len();
2244        let spill_to_disk = num_batches > 1;
2245        log::info!(
2246            "Processing {} files in {} batches (<= {} files, ~{} MB each)",
2247            total_files,
2248            num_batches,
2249            max_files,
2250            max_bytes >> 20
2251        );
2252
2253        for (batch_idx, batch_range) in batches.into_iter().enumerate() {
2254            let batch_start = batch_range.start;
2255            let batch_len = batch_range.len();
2256            log::info!(
2257                "Processing batch {}/{} ({} files)",
2258                batch_idx + 1,
2259                num_batches,
2260                batch_len
2261            );
2262            let pool_start = Instant::now();
2263
2264            // Process files in parallel using rayon with custom thread pool.
2265            // `map_init` gives each worker one reusable trigram sort buffer.
2266            let counter_clone = Arc::clone(&progress_counter);
2267            let tsconfigs = &resolver_configs.tsconfigs;
2268            let ctx = ProcessCtx {
2269                root,
2270                rels: &rels,
2271                stored: &stored,
2272                run_start,
2273                full_deps,
2274                tsconfigs,
2275            };
2276            let results: Vec<Option<FileProcessingResult>> = pool.install(|| {
2277                batch_range
2278                    .into_par_iter()
2279                    .map_init(Vec::<u64>::new, |trigram_scratch, i| {
2280                        let reused = match &merge_source {
2281                            Some((snapshot, ids))
2282                                if matches!(
2283                                    status[i],
2284                                    FileStatus::Unchanged | FileStatus::Touched
2285                                ) =>
2286                            {
2287                                ids.get(&rels[i]).and_then(|&id| {
2288                                    self.reuse_file(
2289                                        &ctx,
2290                                        snapshot,
2291                                        id,
2292                                        i,
2293                                        &metas[i],
2294                                        trigram_scratch,
2295                                    )
2296                                })
2297                            }
2298                            _ => None,
2299                        };
2300                        let result = match reused {
2301                            Some(r) => {
2302                                from_snapshot.fetch_add(1, Ordering::Relaxed);
2303                                Some(r)
2304                            }
2305                            None => self.process_file(&ctx, i, trigram_scratch),
2306                        };
2307                        counter_clone.fetch_add(1, Ordering::Relaxed);
2308                        result
2309                    })
2310                    .collect()
2311            });
2312            pool_ms += pool_start.elapsed().as_millis();
2313            // A merge copied this batch's text out of the old stores: let their pages
2314            // go, or the whole old base ends up resident by the last batch.
2315            if let Some((snapshot, _)) = &merge_source {
2316                snapshot.release_pages();
2317            }
2318
2319            // Process batch results immediately (streaming approach to minimize memory)
2320            for (offset, result) in results.into_iter().enumerate() {
2321                let Some(result) = result else { continue };
2322                let i = batch_start + offset;
2323                // The normalized (forward-slash, relative) path everywhere, so the
2324                // trigram index and content store agree with the database and the
2325                // downstream filters, regardless of host separator.
2326                let normalized_pathbuf = PathBuf::from(&rels[i]);
2327
2328                // Register the file with the trigram builder (assigns file_id in
2329                // discovery order) and hand it the postings extracted in the pool.
2330                let _file_id =
2331                    trigram_builder.add_file(normalized_pathbuf.clone(), result.trigram_run);
2332
2333                // Add to content store
2334                content_writer.add_file(normalized_pathbuf, &result.content);
2335
2336                files_indexed += 1;
2337                indexed.push(IndexedFile {
2338                    index: i,
2339                    hash: result.hash,
2340                    language: result.language,
2341                    line_count: result.line_count,
2342                    size: result.size,
2343                    mtime_ns: result.mtime_ns,
2344                    imports: result.imports,
2345                });
2346            }
2347
2348            // Build this batch's posting lists (sharded, parallel) into a partial.
2349            let flush_msg = format!(
2350                "Building trigram batch {}/{}...",
2351                batch_idx + 1,
2352                num_batches
2353            );
2354            if show_progress {
2355                pb.set_message(flush_msg.clone());
2356            }
2357            *progress_status.lock().unwrap() = flush_msg;
2358            let flush_start = Instant::now();
2359            trigram_builder
2360                .flush_batch(&pool, spill_to_disk)
2361                .context("Failed to build trigram batch")?;
2362            flush_ms += flush_start.elapsed().as_millis();
2363        }
2364        log::info!(
2365            "phase read+extract: {} ms in pool, {} ms building trigram batches, {} ms total; {} files from the published stores",
2366            pool_ms,
2367            flush_ms,
2368            batch_phase_start.elapsed().as_millis(),
2369            from_snapshot.load(Ordering::Relaxed)
2370        );
2371        drop(merge_source);
2372
2373        // Wait for progress thread to finish
2374        if let Some(thread) = progress_thread {
2375            let _ = thread.join();
2376        }
2377
2378        // Update progress bar to final count
2379        if show_progress {
2380            let final_count = progress_counter.load(Ordering::Relaxed);
2381            pb.set_position(final_count);
2382        }
2383
2384        // Update progress bar message for post-processing
2385        *progress_status.lock().unwrap() = "Writing file metadata to database...".to_string();
2386        if show_progress {
2387            pb.set_message("Writing file metadata to database...".to_string());
2388        }
2389
2390        // Breakdown against the branch's own hashes (unchanged since stable ids).
2391        let (new_file_count, modified_file_count, unchanged_file_count) = breakdown(
2392            indexed
2393                .iter()
2394                .map(|f| (rels[f.index].as_str(), f.hash.as_str())),
2395            &existing_hashes,
2396        );
2397
2398        log::info!("Indexed {} files", files_indexed);
2399
2400        // Step 4: Write trigram index.
2401        // Crash-safe write: the builder streams into `trigrams.<g>.bin.tmp`, syncs,
2402        // then renames it into place (see `atomic_write`). Nothing names the new
2403        // files until the manifest below does, so a crash leaves the previous
2404        // snapshot as it was.
2405        *progress_status.lock().unwrap() = "Writing trigram index...".to_string();
2406        if show_progress {
2407            pb.set_message("Writing trigram index...".to_string());
2408        }
2409        let trigrams_path = cache_dir.join(&trigrams_name);
2410        let write_start = Instant::now();
2411        trigram_builder
2412            .write_with_plan(&pool, &trigrams_path, Some(&cache_dir.join(&plan_name)))
2413            .context("Failed to write trigram index")?;
2414        log::info!(
2415            "phase trigram write: {} trigrams, {} files, {} ms",
2416            trigram_builder.trigram_count(),
2417            trigram_builder.file_count(),
2418            write_start.elapsed().as_millis()
2419        );
2420
2421        // Step 5: Finalize content store (already been writing incrementally)
2422        *progress_status.lock().unwrap() = "Finalizing content store...".to_string();
2423        if show_progress {
2424            pb.set_message("Finalizing content store...".to_string());
2425        }
2426        content_writer
2427            .finalize_if_needed()
2428            .context("Failed to finalize content store")?;
2429        log::info!(
2430            "Wrote {} files ({} bytes) to {}",
2431            content_writer.file_count(),
2432            content_writer.content_size(),
2433            content_name
2434        );
2435
2436        // Step 6: Publish. The manifest rename is the commit point of the stores;
2437        // meta.db follows in one transaction that records the same generation.
2438        // A crash between the two leaves a manifest ahead of meta.db: the changed
2439        // files read as stale (their rows are older than the stores), and the next
2440        // run sees the generations differ and rebuilds.
2441        let manifest = crate::snapshot::Manifest::for_base(
2442            generation,
2443            crate::snapshot::SegmentFiles {
2444                content: content_name.clone(),
2445                trigrams: trigrams_name.clone(),
2446                plan: Some(plan_name.clone()),
2447                files: content_writer.file_count() as u64,
2448                content_bytes: std::fs::metadata(&content_path)?.len(),
2449                trigrams_bytes: std::fs::metadata(&trigrams_path)?.len(),
2450            },
2451            trigram_builder.trigram_count() as u64,
2452            content_writer.content_size() as u64,
2453        );
2454        self.abort_point("base-files");
2455        crate::snapshot::write_manifest(&cache_dir, &manifest)?;
2456        crate::snapshot::link_fixed_names(&cache_dir, &manifest);
2457        self.abort_point("base-manifest");
2458
2459        let meta_start = Instant::now();
2460        let present: Vec<usize> = indexed.iter().map(|f| f.index).collect();
2461        self.write_meta(MetaWrite {
2462            root,
2463            rels: &rels,
2464            present: &present,
2465            written: &indexed,
2466            metas: &metas,
2467            run_start,
2468            stored: &stored,
2469            status: &status,
2470            dirty_paths: &dirty_paths,
2471            branch: &branch,
2472            commit: commit.as_deref(),
2473            resolver_configs: &resolver_configs,
2474            full_deps,
2475            generation,
2476        })?;
2477        self.abort_point("base-meta");
2478
2479        // Update branch metadata
2480        self.cache.update_branch_metadata(
2481            &branch,
2482            commit.as_deref(),
2483            indexed.len(),
2484            git_state.as_ref().map(|s| s.dirty).unwrap_or(false),
2485        )?;
2486
2487        // Force WAL checkpoint to ensure background processes see all committed data
2488        // This is critical when spawning background symbol indexer immediately after
2489        self.cache
2490            .checkpoint_wal()
2491            .context("Failed to checkpoint WAL")?;
2492        log::info!(
2493            "phase meta.db (files, branches, dependencies, exports): {} ms",
2494            meta_start.elapsed().as_millis()
2495        );
2496
2497        // Readers in this process reopen; files no manifest names any more go.
2498        crate::query::invalidate_caches(root);
2499        crate::snapshot::remove_unreferenced(&cache_dir, &manifest, prev_manifest.as_ref());
2500
2501        // Step 7: Update SQLite statistics from database totals (branch-aware)
2502        *progress_status.lock().unwrap() = "Updating statistics...".to_string();
2503        if show_progress {
2504            pb.set_message("Updating statistics...".to_string());
2505        }
2506        // Update stats for current branch only
2507        self.cache.update_stats(&branch)?;
2508
2509        // Update schema hash to mark cache as compatible with current binary
2510        self.cache.update_schema_hash()?;
2511        self.cache.update_extraction_hash()?;
2512
2513        pb.finish_with_message("Indexing complete");
2514
2515        // Return stats with incremental breakdown (the branch's rows were synced
2516        // above: count from `files` alone).
2517        let mut stats = self.cache.stats_synced()?;
2518        stats.new_files = new_file_count;
2519        stats.modified_files = modified_file_count;
2520        stats.deleted_files = deleted_file_count;
2521        stats.unchanged_files = unchanged_file_count;
2522        stats.skipped_too_large = skipped_too_large;
2523        stats.skipped_bytes_too_large = skipped_bytes_too_large;
2524        stats.skipped_binary = skipped_binary;
2525        log::info!(
2526            "Indexing complete: {} files (new={}, modified={}, unchanged={})",
2527            stats.total_files,
2528            new_file_count,
2529            modified_file_count,
2530            unchanged_file_count
2531        );
2532
2533        Ok(stats)
2534    }
2535
2536    /// Apply a change set as a delta on the published base: the rewritten files
2537    /// are read, the delta is rebuilt from them and the previous delta's files the
2538    /// change set leaves alone, and the base files they supersede (or that are
2539    /// gone) are tombstoned. `meta.db` changes only the rows the change set names,
2540    /// in one transaction. `Ok(None)` when the delta would pass its limits (nothing
2541    /// is written): the caller then builds a new base (a merge).
2542    fn publish_delta(&self, c: DeltaChanges<'_>) -> Result<Option<IndexStats>> {
2543        use crate::snapshot::{IndexSnapshot, Manifest, SegmentFiles};
2544        use rusqlite::OptionalExtension;
2545        let cache_dir = self.cache.path().to_path_buf();
2546        let snapshot = IndexSnapshot::open(&cache_dir)?;
2547        let Some(prev) = snapshot.manifest().cloned() else {
2548            return Ok(None);
2549        };
2550        let base_len = snapshot.base_len();
2551        let delta_start = Instant::now();
2552        let mut laps = Laps::new();
2553
2554        let rels: Vec<String> = c.rewrites.iter().map(|r| r.rel.clone()).collect();
2555        let delta_len = snapshot.delta_len();
2556        // Ids below this are base and delta files, tombstoned in place; the recent
2557        // segment above them is rebuilt.
2558        let stable_end = base_len + delta_len;
2559
2560        // Store entries that go: every rewritten and every deleted path.
2561        let gone: std::collections::HashSet<String> = rels
2562            .iter()
2563            .cloned()
2564            .chain(c.deleted.iter().map(|(p, _)| p.clone()))
2565            .collect();
2566        let path_of = |id: u32| -> Option<&str> { snapshot.get_file_path(id)?.to_str() };
2567        let (mut new_dead_base, mut new_dead_delta) = (Vec::new(), Vec::new());
2568        for id in 0..stable_end {
2569            if path_of(id).is_some_and(|p| gone.contains(p)) {
2570                if id < base_len {
2571                    new_dead_base.push(id);
2572                } else {
2573                    new_dead_delta.push(id);
2574                }
2575            }
2576        }
2577        let kept_in = |range: std::ops::Range<u32>| -> Vec<(String, u32)> {
2578            range
2579                .filter_map(|id| {
2580                    let p = path_of(id)?;
2581                    (!gone.contains(p)).then(|| (p.to_string(), id))
2582                })
2583                .collect()
2584        };
2585        let delta_kept = kept_in(base_len..stable_end);
2586        let recent_kept = kept_in(stable_end..snapshot.id_bound());
2587
2588        // The limits, from stat sizes and entry-table lengths, before anything is
2589        // read (a merge reads the files itself).
2590        let len_of = |kept: &[(String, u32)]| -> u64 {
2591            kept.iter()
2592                .map(|(_, id)| snapshot.file_len(*id).unwrap_or(0))
2593                .sum()
2594        };
2595        let rewrite_bytes: u64 = c.rewrites.iter().map(|r| r.size).sum();
2596        let (delta_kept_bytes, recent_kept_bytes) = (len_of(&delta_kept), len_of(&recent_kept));
2597        let (max_files, max_bytes) = self.merge_limits(prev.live_corpus_bytes);
2598        let all_files = c.rewrites.len() + delta_kept.len() + recent_kept.len();
2599        let all_bytes = rewrite_bytes + delta_kept_bytes + recent_kept_bytes;
2600        if all_files > max_files || all_bytes > max_bytes {
2601            log::info!(
2602                "Delta of {} files / ~{} bytes passes its limits ({} files / {} bytes)",
2603                all_files,
2604                all_bytes,
2605                max_files,
2606                max_bytes
2607            );
2608            return Ok(None);
2609        }
2610        // The recent segment is rebuilt by every update; past its own limits it is
2611        // folded, with the delta's live files, into a new delta.
2612        let (recent_max_files, recent_max_bytes) = self.recent_limits(max_files, max_bytes);
2613        let fold = c.rewrites.len() + recent_kept.len() > recent_max_files
2614            || rewrite_bytes + recent_kept_bytes > recent_max_bytes;
2615
2616        // Read the rewritten files.
2617        let ctx = ProcessCtx {
2618            root: c.root,
2619            rels: &rels,
2620            stored: &c.stored,
2621            run_start: c.run_start,
2622            full_deps: false,
2623            tsconfigs: &c.resolver_configs.tsconfigs,
2624        };
2625        let mut read: Vec<Option<FileProcessingResult>> = c.pool.install(|| {
2626            (0..rels.len())
2627                .into_par_iter()
2628                .map_init(Vec::<u64>::new, |scratch, i| {
2629                    self.process_file(&ctx, i, scratch)
2630                })
2631                .collect()
2632        });
2633        laps.lap("read");
2634
2635        // An unreadable file is gone, as in a full run: its row goes too.
2636        let mut deleted = c.deleted;
2637        let mut live_files = c.live_files;
2638        for (k, r) in read.iter().enumerate() {
2639            if r.is_none() {
2640                live_files -= 1;
2641                if let Some(row) = c.stored.get(&rels[k]) {
2642                    deleted.push((rels[k].clone(), row.id));
2643                }
2644            }
2645        }
2646
2647        // The new segment: the read files and the kept ones, in walk order.
2648        enum Source {
2649            Fresh(usize),
2650            Old(u32),
2651        }
2652        let kept: Vec<(String, u32)> = if fold {
2653            delta_kept.into_iter().chain(recent_kept).collect()
2654        } else {
2655            recent_kept
2656        };
2657        let kept_seqs: HashMap<String, i64> = if kept.is_empty() {
2658            HashMap::new()
2659        } else {
2660            let conn = crate::cache::open_meta_db(cache_dir.join(crate::cache::META_DB))?;
2661            let mut stmt = conn.prepare("SELECT walk_seq FROM files WHERE path = ?")?;
2662            let mut out = HashMap::new();
2663            for (p, _) in &kept {
2664                if let Some(seq) = stmt.query_row([p], |r| r.get::<_, i64>(0)).optional()? {
2665                    out.insert(p.clone(), seq);
2666                }
2667            }
2668            out
2669        };
2670        let mut entries: Vec<(i64, String, Source)> = Vec::new();
2671        for (k, r) in read.iter().enumerate() {
2672            if r.is_some() {
2673                entries.push((c.rewrites[k].walk_seq, rels[k].clone(), Source::Fresh(k)));
2674            }
2675        }
2676        for (p, id) in kept {
2677            let seq = kept_seqs.get(&p).copied().unwrap_or(i64::MAX);
2678            entries.push((seq, p, Source::Old(id)));
2679        }
2680        entries.sort_by_key(|(seq, _, _)| *seq);
2681        let mut segment_bytes = 0u64;
2682        for (_, _, src) in &entries {
2683            segment_bytes += match src {
2684                Source::Fresh(k) => read[*k].as_ref().map_or(0, |f| f.content.len() as u64),
2685                Source::Old(id) => snapshot.file_len(*id).unwrap_or(0),
2686            };
2687        }
2688        let (stable_files, stable_bytes) = if fold {
2689            (0, 0)
2690        } else {
2691            (
2692                snapshot.delta_len() as usize
2693                    - new_dead_delta.len()
2694                    - (0..delta_len)
2695                        .filter(|&k| snapshot.is_dead(base_len + k))
2696                        .count(),
2697                delta_kept_bytes,
2698            )
2699        };
2700        if entries.len() + stable_files > max_files || segment_bytes + stable_bytes > max_bytes {
2701            log::info!(
2702                "Delta of {} files / {} bytes passes its limits after reading",
2703                entries.len() + stable_files,
2704                segment_bytes + stable_bytes
2705            );
2706            return Ok(None);
2707        }
2708
2709        // Tombstones, and the planning sizes of the postings they remove.
2710        let mut tombstones: Vec<u32> = if fold {
2711            // A new delta: only base ids stay tombstoned.
2712            prev.tombstones
2713                .iter()
2714                .copied()
2715                .filter(|&id| id < base_len)
2716                .chain(new_dead_base.iter().copied())
2717                .collect()
2718        } else {
2719            prev.tombstones
2720                .iter()
2721                .copied()
2722                .chain(new_dead_base.iter().copied())
2723                .chain(new_dead_delta.iter().copied())
2724                .collect()
2725        };
2726        tombstones.sort_unstable();
2727        tombstones.dedup();
2728        let sizes_of = |ids: &[u32]| -> Vec<Vec<(crate::trigram::Trigram, u32)>> {
2729            c.pool.install(|| {
2730                ids.par_iter()
2731                    .map_init(Vec::<u64>::new, |scratch, &id| {
2732                        let content = snapshot.get_file_content(id).unwrap_or("");
2733                        let run = crate::trigram_build::extract_trigram_run(content, scratch);
2734                        crate::trigram_build::run_plan_sizes(&run)
2735                    })
2736                    .collect()
2737            })
2738        };
2739        let carried = |plan: Option<&crate::snapshot::TombPlan>| {
2740            plan.map(|t| t.entries().map(|(t, n)| (t, n as u64)).collect())
2741                .unwrap_or_default()
2742        };
2743        type TombMap = std::collections::BTreeMap<crate::trigram::Trigram, u64>;
2744        let mut touched_trigrams: Vec<crate::trigram::Trigram> = Vec::new();
2745        let mut tomb: TombMap = carried(snapshot.tomb());
2746        for sizes in sizes_of(&new_dead_base) {
2747            for (t, n) in sizes {
2748                *tomb.entry(t).or_default() += n as u64;
2749                touched_trigrams.push(t);
2750            }
2751        }
2752        let mut tomb_delta: TombMap = if fold {
2753            TombMap::new()
2754        } else {
2755            carried(snapshot.tomb_delta())
2756        };
2757        for sizes in sizes_of(&new_dead_delta) {
2758            for (t, n) in sizes {
2759                if !fold {
2760                    *tomb_delta.entry(t).or_default() += n as u64;
2761                }
2762                touched_trigrams.push(t);
2763            }
2764        }
2765        laps.lap("tombstones");
2766
2767        // Write the new segment (generation files: nothing names them yet).
2768        let (delta_content, delta_trigrams, delta_plan, tomb_name) =
2769            crate::snapshot::delta_file_names(c.generation);
2770        let (recent_content, recent_trigrams, recent_plan, tomb_delta_name) =
2771            crate::snapshot::recent_file_names(c.generation);
2772        let (seg_content, seg_trigrams, seg_plan) = if fold {
2773            (delta_content, delta_trigrams, delta_plan)
2774        } else {
2775            (recent_content, recent_trigrams, recent_plan)
2776        };
2777        let segment = if entries.is_empty() {
2778            None
2779        } else {
2780            let runs: Vec<Option<TrigramRun>> = c.pool.install(|| {
2781                entries
2782                    .par_iter()
2783                    .map_init(Vec::<u64>::new, |scratch, (_, _, src)| match src {
2784                        Source::Fresh(_) => None,
2785                        Source::Old(id) => Some(crate::trigram_build::extract_trigram_run(
2786                            snapshot.get_file_content(*id).unwrap_or(""),
2787                            scratch,
2788                        )),
2789                    })
2790                    .collect()
2791            });
2792            let mut builder = TrigramIndexBuilder::new(cache_dir.join("trigram_temp"));
2793            let mut writer = ContentWriter::new();
2794            let content_path = cache_dir.join(&seg_content);
2795            writer
2796                .init(content_path.clone())
2797                .context("Failed to initialize the delta content store")?;
2798            for ((_, rel, src), run) in entries.iter().zip(runs) {
2799                let path = PathBuf::from(rel);
2800                match src {
2801                    Source::Fresh(k) => {
2802                        let f = read[*k].as_mut().expect("read file");
2803                        let run = std::mem::take(&mut f.trigram_run);
2804                        builder.add_file(path.clone(), run);
2805                        writer.add_file(path, &f.content);
2806                    }
2807                    Source::Old(id) => {
2808                        builder.add_file(path.clone(), run.expect("kept file run"));
2809                        writer.add_file(path, snapshot.get_file_content(*id)?);
2810                    }
2811                }
2812            }
2813            let trigrams_path = cache_dir.join(&seg_trigrams);
2814            builder
2815                .write_with_plan(c.pool, &trigrams_path, Some(&cache_dir.join(&seg_plan)))
2816                .context("Failed to write the delta trigram index")?;
2817            writer
2818                .finalize_if_needed()
2819                .context("Failed to finalize the delta content store")?;
2820            Some(SegmentFiles {
2821                content: seg_content.clone(),
2822                trigrams: seg_trigrams.clone(),
2823                plan: Some(seg_plan.clone()),
2824                files: writer.file_count() as u64,
2825                content_bytes: std::fs::metadata(&content_path)?.len(),
2826                trigrams_bytes: std::fs::metadata(&trigrams_path)?.len(),
2827            })
2828        };
2829        let write_tomb = |map: &TombMap, name: String| -> Result<String> {
2830            let entries: Vec<(crate::trigram::Trigram, u32)> = map
2831                .iter()
2832                .map(|(&t, &n)| (t, n.min(u32::MAX as u64) as u32))
2833                .collect();
2834            crate::snapshot::write_tomb_file(&cache_dir.join(&name), &entries)?;
2835            Ok(name)
2836        };
2837        let tomb_file = if tombstones.iter().any(|&id| id < base_len) {
2838            Some(write_tomb(&tomb, tomb_name)?)
2839        } else {
2840            None
2841        };
2842        let tomb_delta_file = if tombstones.iter().any(|&id| id >= base_len) {
2843            Some(write_tomb(&tomb_delta, tomb_delta_name)?)
2844        } else {
2845            None
2846        };
2847        let (delta_files, recent_files) = if fold {
2848            (segment, None)
2849        } else {
2850            (prev.delta.clone(), segment)
2851        };
2852        laps.lap("write");
2853
2854        // The live trigram count, kept up to date from the trigrams this update
2855        // touches: those of tombstoned files, of the replaced and the new segment.
2856        let segment_index =
2857            |files: &Option<SegmentFiles>| -> Result<Option<crate::trigram::TrigramIndex>> {
2858                let Some(f) = files else { return Ok(None) };
2859                let mut index = crate::trigram::TrigramIndex::load(cache_dir.join(&f.trigrams))?;
2860                if let Some(plan) = &f.plan {
2861                    index.attach_plan(cache_dir.join(plan))?;
2862                }
2863                Ok(Some(index))
2864            };
2865        let new_segment = segment_index(if fold { &delta_files } else { &recent_files })?;
2866        if let Some(recent) = snapshot.recent() {
2867            touched_trigrams.extend(recent.trigrams.trigrams());
2868        }
2869        if fold && let Some(delta) = snapshot.delta() {
2870            touched_trigrams.extend(delta.trigrams.trigrams());
2871        }
2872        if let Some(index) = &new_segment {
2873            touched_trigrams.extend(index.trigrams());
2874        }
2875        touched_trigrams.sort_unstable();
2876        touched_trigrams.dedup();
2877        let plan_in = |index: Option<&crate::trigram::TrigramIndex>, t| -> i64 {
2878            index
2879                .and_then(|i| i.list_part(t))
2880                .map_or(0, |(_, plan)| plan as i64)
2881        };
2882        let old_delta = snapshot.delta().map(|d| &d.trigrams);
2883        let (new_delta, new_recent) = if fold {
2884            (new_segment.as_ref(), None)
2885        } else {
2886            (old_delta, new_segment.as_ref())
2887        };
2888        let mut live_trigrams = prev.live_trigrams as i64;
2889        for &t in &touched_trigrams {
2890            let was = snapshot.live_plan(t) > 0;
2891            let now = plan_in(Some(&snapshot.base().trigrams), t)
2892                + plan_in(new_delta, t)
2893                + plan_in(new_recent, t)
2894                - tomb.get(&t).copied().unwrap_or(0) as i64
2895                - tomb_delta.get(&t).copied().unwrap_or(0) as i64
2896                > 0;
2897            live_trigrams += now as i64 - was as i64;
2898        }
2899        let dead_set: std::collections::HashSet<u32> = tombstones.iter().copied().collect();
2900        // Lengths come from the entry table: reading the content would page in (and
2901        // UTF-8 check) the whole base on every update.
2902        let mut live_corpus = segment_bytes;
2903        let stable_bound = if fold { base_len } else { stable_end };
2904        for id in 0..stable_bound {
2905            if !dead_set.contains(&id) {
2906                live_corpus += snapshot.file_len(id).unwrap_or(0);
2907            }
2908        }
2909        laps.lap("live");
2910
2911        // Publish: fixed names first (an older binary must not read the base alone
2912        // once it is incomplete), then the manifest, then meta.db.
2913        let manifest = Manifest {
2914            format: 0,
2915            generation: c.generation,
2916            base: prev.base.clone(),
2917            delta: delta_files,
2918            recent: recent_files,
2919            tombstones,
2920            tomb: tomb_file,
2921            tomb_delta: tomb_delta_file,
2922            live_trigrams: live_trigrams.max(0) as u64,
2923            publish_id: 0,
2924            live_corpus_bytes: live_corpus,
2925            checksum: String::new(),
2926        }
2927        .sealed();
2928        self.abort_point("delta-files");
2929        if !manifest.base_only() {
2930            crate::snapshot::unlink_fixed_names(&cache_dir);
2931        }
2932        self.abort_point("unlinked");
2933        crate::snapshot::write_manifest(&cache_dir, &manifest)?;
2934        crate::snapshot::link_fixed_names(&cache_dir, &manifest);
2935        self.abort_point("manifest");
2936        log::info!(
2937            "phase delta: {} delta + {} recent files ({} read{}), {} tombstones, {} ms",
2938            manifest.delta.as_ref().map_or(0, |d| d.files),
2939            manifest.recent.as_ref().map_or(0, |d| d.files),
2940            read.iter().filter(|r| r.is_some()).count(),
2941            if fold {
2942                ", folded into a new delta"
2943            } else {
2944                ""
2945            },
2946            manifest.tombstones.len(),
2947            delta_start.elapsed().as_millis()
2948        );
2949        laps.lap("manifest");
2950
2951        // meta.db: the named rows, their dependencies, the statistics and the
2952        // branch row, in one transaction.
2953        let meta_start = Instant::now();
2954        let now = chrono::Utc::now().timestamp();
2955        let flags = (c.dirty)();
2956        laps.lap("dirty");
2957        let mut rows: Vec<crate::cache::FileRow> = Vec::new();
2958        let mut row_k: Vec<usize> = Vec::new();
2959        for (k, r) in read.iter().enumerate() {
2960            if let Some(f) = r {
2961                rows.push(crate::cache::FileRow {
2962                    path: rels[k].clone(),
2963                    hash: f.hash.clone(),
2964                    language: format!("{:?}", f.language),
2965                    line_count: f.line_count,
2966                    size: f.size,
2967                    mtime_ns: f.mtime_ns,
2968                    dirty: flags.rewrites.contains(&rels[k]),
2969                    walk_seq: c.rewrites[k].walk_seq,
2970                });
2971                row_k.push(k);
2972            }
2973        }
2974        let paths_changed =
2975            !deleted.is_empty() || rows.iter().any(|r| !c.stored.contains_key(&r.path));
2976        let mut conn = crate::cache::open_meta_db(cache_dir.join(crate::cache::META_DB))?;
2977        let tx = conn
2978            .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
2979            .context("Failed to begin meta.db transaction")?;
2980        let deleted_ids: Vec<i64> = deleted.iter().map(|(_, id)| *id).collect();
2981        crate::meta_update::delete_files(&tx, &deleted_ids)?;
2982        let ids = crate::meta_update::upsert_files(&tx, &rows, now)?;
2983        crate::meta_update::set_walk_seqs(&tx, &c.walk_moves)?;
2984        crate::meta_update::refresh_stats(&tx, &flags.touched)?;
2985        crate::meta_update::set_dirty_flags(&tx, &flags.flips)?;
2986        let branch_id = self
2987            .cache
2988            .get_or_create_branch_id(&tx, c.branch, c.commit)?;
2989        if c.sync_all_branch_rows {
2990            crate::meta_update::sync_branch_rows(&tx, branch_id, c.branch, now)?;
2991        } else {
2992            let branch_rows: Vec<(i64, &str)> = ids
2993                .iter()
2994                .zip(&rows)
2995                .map(|(id, row)| (*id, row.hash.as_str()))
2996                .collect();
2997            crate::meta_update::set_branch_rows(&tx, branch_id, &branch_rows, now)?;
2998        }
2999        log::info!(
3000            "meta.db: {} rows written, {} deleted, {} moved, {} touched, {} dirty flags",
3001            rows.len(),
3002            deleted_ids.len(),
3003            c.walk_moves.len(),
3004            flags.touched.len(),
3005            flags.flips.len()
3006        );
3007        laps.lap("rows");
3008
3009        // The resolver this process kept from the previous publish, patched with this
3010        // one's paths, or every path loaded again.
3011        let meta_path = cache_dir.join(crate::cache::META_DB);
3012        let cached = RESOLVER_CACHE
3013            .lock()
3014            .ok()
3015            .and_then(|mut slot| slot.take())
3016            .filter(|(path, publish, _)| {
3017                *path == meta_path && prev.publish_id != 0 && *publish == prev.publish_id
3018            })
3019            .map(|(_, _, resolver)| resolver);
3020        let resolver = match cached {
3021            Some(mut resolver) => {
3022                for (path, _) in &deleted {
3023                    resolver.remove(path);
3024                }
3025                for (row, id) in rows.iter().zip(&ids) {
3026                    resolver.insert(*id, &row.path);
3027                }
3028                resolver
3029            }
3030            None => crate::dependency::PathResolver::from_conn(&tx)
3031                .context("Failed to load file paths for dependency resolution")?,
3032        };
3033        laps.lap("resolver");
3034        let ctx = crate::dependency_resolve::ResolverContext::new(c.root, c.resolver_configs);
3035        let mut writer = crate::dependency::DependencyWriter::new(&tx);
3036        let mut resolved_here: std::collections::HashSet<i64> = std::collections::HashSet::new();
3037        for (&k, &file_id) in row_k.iter().zip(&ids) {
3038            let Some((imports, exports, declared)) =
3039                read[k].as_ref().and_then(|f| f.imports.as_ref())
3040            else {
3041                continue;
3042            };
3043            let rel = &rels[k];
3044            resolved_here.insert(file_id);
3045            let deps = ctx.resolve_file_imports(file_id, rel, imports.clone(), &resolver);
3046            writer.replace_dependencies(file_id, &deps)?;
3047            writer.replace_members(
3048                file_id,
3049                &crate::dependency_resolve::package_members(rel, declared),
3050            )?;
3051            writer.clear_exports(file_id)?;
3052            for export in exports {
3053                let resolved = ctx.resolve_export(rel, export, &resolver);
3054                writer.insert_export(
3055                    file_id,
3056                    export.exported_symbol.as_deref(),
3057                    &export.source_path,
3058                    resolved,
3059                    export.line_number,
3060                )?;
3061            }
3062        }
3063        let (deps_written, exports_written) = writer.counts();
3064        // An added or removed path can change how an unchanged file's imports
3065        // resolve (suffix matches, ambiguity, the first of several candidates).
3066        let reresolved = if paths_changed {
3067            reresolve(&tx, &ctx, &resolver, &resolved_here)?
3068        } else {
3069            0
3070        };
3071        refresh_vendored(&tx, &c.resolver_configs.vendor, Some(&ids))?;
3072        laps.lap("deps");
3073
3074        crate::meta_update::set_statistic(
3075            &tx,
3076            RESOLVER_DIGEST_KEY,
3077            &c.resolver_configs.digest,
3078            now,
3079        )?;
3080        crate::meta_update::set_statistic(
3081            &tx,
3082            INDEX_GENERATION_KEY,
3083            &c.generation.to_string(),
3084            now,
3085        )?;
3086        CacheManager::update_branch_metadata_on(
3087            &tx,
3088            c.branch,
3089            c.commit,
3090            live_files,
3091            flags.git_dirty,
3092        )?;
3093        // Every file has its branch row now: the count is the file count.
3094        CacheManager::set_total_files_on(&tx, live_files, now)?;
3095        CacheManager::update_schema_hash_on(&tx)?;
3096        CacheManager::update_extraction_hash_on(&tx)?;
3097        laps.lap("stamps");
3098        tx.commit()?;
3099        self.abort_point("meta");
3100        if let Ok(mut slot) = RESOLVER_CACHE.lock() {
3101            *slot = Some((meta_path, manifest.publish_id, resolver));
3102        }
3103        laps.lap("commit");
3104        self.cache
3105            .checkpoint_wal()
3106            .context("Failed to checkpoint WAL")?;
3107        log::info!(
3108            "dependencies: {} rows, {} exports written; {} rows re-resolved",
3109            deps_written,
3110            exports_written,
3111            reresolved
3112        );
3113        log::info!(
3114            "phase meta.db (files, branches, dependencies, exports): {} ms",
3115            meta_start.elapsed().as_millis()
3116        );
3117
3118        crate::query::invalidate_caches(c.root);
3119        drop(snapshot);
3120        crate::snapshot::remove_unreferenced(&cache_dir, &manifest, Some(&prev));
3121        laps.lap("cleanup");
3122
3123        let (mut new_files, mut modified_files, mut unchanged_files) = c.breakdown_rest;
3124        for (k, r) in read.iter().enumerate() {
3125            if let Some(f) = r {
3126                match c.branch_hashes.get(&rels[k]) {
3127                    None => new_files += 1,
3128                    Some(old) if *old != f.hash => modified_files += 1,
3129                    _ => unchanged_files += 1,
3130                }
3131            }
3132        }
3133        let mut stats = if c.full_stats {
3134            // The branch's rows name every file now: count from `files` alone.
3135            self.cache.stats_synced()?
3136        } else {
3137            self.light_stats(live_files, now)
3138        };
3139        laps.lap("stats");
3140        log::info!("delta update phases:{}", laps.line);
3141        stats.new_files = new_files;
3142        stats.modified_files = modified_files;
3143        stats.deleted_files = c.deleted_file_count;
3144        stats.unchanged_files = unchanged_files;
3145        stats.skipped_too_large = c.skipped.0;
3146        stats.skipped_bytes_too_large = c.skipped.1;
3147        stats.skipped_binary = c.skipped.2;
3148        Ok(Some(stats))
3149    }
3150
3151    /// [`Self::process_file`] for a file whose bytes are the ones the published
3152    /// stores hold (`id` there): the text comes from the stores, the hash from its
3153    /// row, and a touched file's stat from the walk. `None` when the stores cannot
3154    /// give it (the caller reads the file).
3155    fn reuse_file(
3156        &self,
3157        ctx: &ProcessCtx<'_>,
3158        snapshot: &crate::snapshot::IndexSnapshot,
3159        id: u32,
3160        i: usize,
3161        meta: &Option<crate::cache::FileStat>,
3162        trigram_scratch: &mut Vec<u64>,
3163    ) -> Option<FileProcessingResult> {
3164        let row = ctx.stored.get(&ctx.rels[i])?;
3165        let content = snapshot.get_file_content(id).ok()?.to_string();
3166        let file_path = &ctx.root.join(&ctx.rels[i]);
3167        let (size, mtime_ns) = match meta {
3168            Some(md) if !row.stat_matches(md) => (md.size(), md.recorded_mtime_ns(ctx.run_start)),
3169            _ => (row.size, row.mtime_ns),
3170        };
3171        let language = Language::from_path(file_path);
3172        let line_count = content.lines().count();
3173        let trigram_run = crate::trigram_build::extract_trigram_run(&content, trigram_scratch);
3174        let imports = ctx.full_deps.then(|| {
3175            let path_str = file_path.to_string_lossy().to_string();
3176            extract_imports(language, &content, &path_str, ctx.root, ctx.tsconfigs)
3177        });
3178        Some(FileProcessingResult {
3179            hash: row.hash.clone(),
3180            content,
3181            language,
3182            line_count,
3183            size,
3184            mtime_ns,
3185            imports,
3186            trigram_run,
3187        })
3188    }
3189
3190    /// Read one discovered file: stat, bytes, hash, text, trigram run, and imports
3191    /// when they may have changed. `None` when it cannot be read.
3192    fn process_file(
3193        &self,
3194        ctx: &ProcessCtx<'_>,
3195        i: usize,
3196        trigram_scratch: &mut Vec<u64>,
3197    ) -> Option<FileProcessingResult> {
3198        let file_path = &ctx.root.join(&ctx.rels[i]);
3199        let path_str = file_path.to_string_lossy().to_string();
3200
3201        // Stat BEFORE the read. If the file changes between the two, the recorded
3202        // (size, mtime) is older than the bytes, so the next check re-hashes it
3203        // rather than trusting a stat that matches.
3204        let (size, mtime_ns) = std::fs::metadata(file_path)
3205            .map(|md| {
3206                (
3207                    md.len(),
3208                    crate::cache::recorded_mtime_ns(&md, ctx.run_start),
3209                )
3210            })
3211            .unwrap_or((0, 0));
3212
3213        // Read file content once (used for hashing, trigrams, and parsing). The
3214        // hash is of the RAW bytes, so the freshness check can hash a file on disk
3215        // and compare. Invalid UTF-8 (a Latin-1 `.po`, an old doc) is decoded
3216        // lossily rather than dropped: ripgrep searches those bytes, and an agent
3217        // expects the same.
3218        let bytes = match std::fs::read(file_path) {
3219            Ok(b) => b,
3220            Err(e) => {
3221                log::warn!("Failed to read {}: {}", path_str, e);
3222                return None;
3223            }
3224        };
3225        let hash = self.hash_content(&bytes);
3226        let content = match String::from_utf8(bytes) {
3227            Ok(s) => s,
3228            Err(e) => String::from_utf8_lossy(e.as_bytes()).into_owned(),
3229        };
3230
3231        // Detect language
3232        let language = Language::from_path(file_path);
3233
3234        // Count lines in the file
3235        let line_count = content.lines().count();
3236
3237        // Trigram postings, sorted, without a file id (assigned serially).
3238        let trigram_run = crate::trigram_build::extract_trigram_run(&content, trigram_scratch);
3239
3240        // Imports and re-exports: for every file when they are all rewritten, else
3241        // for files whose bytes changed (including a file that changed again since
3242        // it was classified).
3243        let unchanged = ctx
3244            .stored
3245            .get(&ctx.rels[i])
3246            .is_some_and(|row| row.hash == hash);
3247        let imports = (ctx.full_deps || !unchanged)
3248            .then(|| extract_imports(language, &content, &path_str, ctx.root, ctx.tsconfigs));
3249
3250        Some(FileProcessingResult {
3251            hash,
3252            content,
3253            language,
3254            line_count,
3255            size,
3256            mtime_ns,
3257            imports,
3258            trigram_run,
3259        })
3260    }
3261
3262    /// Write the marker whose mtime is this run's race threshold; returns it (or the
3263    /// process clock when the marker cannot be written or read).
3264    fn run_marker(&self, cache_dir: &Path) -> std::time::SystemTime {
3265        let marker = cache_dir.join(RUN_MARKER);
3266        std::fs::write(&marker, b"")
3267            .and_then(|_| std::fs::metadata(&marker))
3268            .and_then(|md| md.modified())
3269            .unwrap_or_else(|_| std::time::SystemTime::now())
3270    }
3271
3272    /// Whether the published snapshot is complete, holds `expected` files (the rows
3273    /// of the last indexed tree) and is the one meta.db's rows go with.
3274    fn stores_intact(&self, expected: usize, meta_generation: Option<u64>) -> bool {
3275        // A manifest, headers and sizes: not the stores themselves (a run that
3276        // changes nothing must not page in their path tables). Whatever opens them
3277        // next validates them in full.
3278        match crate::snapshot::check_published(self.cache.path()) {
3279            Ok(None) => {
3280                log::info!("Index written before the manifest - rebuilding");
3281                false
3282            }
3283            Ok(Some(manifest)) => {
3284                if Some(manifest.generation) != meta_generation {
3285                    log::warn!(
3286                        "Manifest generation {} but meta.db rows are generation {:?} (a run stopped between the two) - rebuilding",
3287                        manifest.generation,
3288                        meta_generation
3289                    );
3290                    false
3291                } else if manifest.live_files() as usize != expected {
3292                    log::warn!(
3293                        "Stores hold {} files but meta.db lists {} - rebuilding",
3294                        manifest.live_files(),
3295                        expected
3296                    );
3297                    false
3298                } else {
3299                    true
3300                }
3301            }
3302            Err(e) => {
3303                log::warn!("Index stores unusable ({:#}) - rebuilding", e);
3304                false
3305            }
3306        }
3307    }
3308
3309    /// Nothing to write to the stores: bring meta.db up to date (fingerprints of
3310    /// touched files, dirty flags, walk positions, this branch's rows, the branch
3311    /// metadata and the statistics timestamp) and report.
3312    /// The statistics of a library update: counts and sizes, without the
3313    /// per-language maps (they scan every row).
3314    fn light_stats(&self, total_files: usize, now: i64) -> IndexStats {
3315        let (index_size_bytes, trigram_index_bytes, corpus_bytes) = self.cache.store_sizes();
3316        IndexStats {
3317            total_files,
3318            index_size_bytes,
3319            last_updated: chrono::DateTime::from_timestamp(now, 0)
3320                .unwrap_or_else(chrono::Utc::now)
3321                .to_rfc3339(),
3322            corpus_bytes,
3323            trigram_index_bytes,
3324            ..Default::default()
3325        }
3326    }
3327
3328    /// A library update that changed no content: the named rows' stats, flags and
3329    /// positions, the branch row and the statistics (what `refresh_unchanged`
3330    /// does for a whole walk).
3331    fn refresh_named(&self, r: RefreshNamed<'_>) -> Result<IndexStats> {
3332        let mut conn = crate::cache::open_meta_db(self.cache.path().join(crate::cache::META_DB))?;
3333        let tx = conn
3334            .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
3335            .context("Failed to begin meta.db transaction")?;
3336        crate::meta_update::set_walk_seqs(&tx, r.walk_moves)?;
3337        crate::meta_update::refresh_stats(&tx, r.touched)?;
3338        crate::meta_update::set_dirty_flags(&tx, r.flips)?;
3339        if r.commit.is_some() {
3340            CacheManager::update_branch_metadata_on(
3341                &tx,
3342                r.branch,
3343                r.commit,
3344                r.live_files,
3345                r.git_dirty,
3346            )?;
3347        }
3348        CacheManager::update_stats_on(&tx, r.branch)?;
3349        tx.commit()?;
3350        let mut stats = self.light_stats(r.live_files, chrono::Utc::now().timestamp());
3351        stats.new_files = 0;
3352        stats.modified_files = 0;
3353        stats.deleted_files = 0;
3354        stats.unchanged_files = r.live_files;
3355        stats.skipped_too_large = r.skipped.0;
3356        stats.skipped_bytes_too_large = r.skipped.1;
3357        stats.skipped_binary = r.skipped.2;
3358        Ok(stats)
3359    }
3360
3361    fn refresh_unchanged(&self, r: RefreshUnchanged<'_>) -> Result<IndexStats> {
3362        let mut laps = Laps::new();
3363        let now = chrono::Utc::now().timestamp();
3364        let rows: Vec<&crate::meta_update::StoredFile> = r
3365            .rows
3366            .iter()
3367            .map(|row| row.expect("nothing was added: every file has a row"))
3368            .collect();
3369        let seqs = crate::meta_update::plan_walk_seq(
3370            &rows
3371                .iter()
3372                .map(|row| Some(row.walk_seq))
3373                .collect::<Vec<_>>(),
3374        );
3375        let mut walk = Vec::new();
3376        let mut flips = Vec::new();
3377        let mut touched = Vec::new();
3378        let no_dirty = r.dirty_paths.is_empty();
3379        for (i, rel) in r.rels.iter().enumerate() {
3380            let row = rows[i];
3381            let dirty = !no_dirty && r.dirty_paths.contains(rel);
3382            if seqs[i] != row.walk_seq {
3383                walk.push((row.id, seqs[i]));
3384            }
3385            if r.status[i] == FileStatus::Touched {
3386                let (size, mtime) = r.metas[i]
3387                    .as_ref()
3388                    .map(|md| (md.size(), md.recorded_mtime_ns(r.run_start)))
3389                    .unwrap_or((0, 0));
3390                touched.push((row.id, size, mtime, dirty));
3391            } else if dirty != row.dirty {
3392                flips.push((row.id, dirty));
3393            }
3394        }
3395
3396        laps.lap("plan");
3397        let mut conn = crate::cache::open_meta_db(self.cache.path().join(crate::cache::META_DB))?;
3398        let tx = conn
3399            .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
3400            .context("Failed to begin meta.db transaction")?;
3401        crate::meta_update::set_walk_seqs(&tx, &walk)?;
3402        crate::meta_update::refresh_stats(&tx, &touched)?;
3403        crate::meta_update::set_dirty_flags(&tx, &flips)?;
3404        let branch_id = self
3405            .cache
3406            .get_or_create_branch_id(&tx, r.branch, r.commit)?;
3407        laps.lap("rows");
3408        if !r.in_sync {
3409            crate::meta_update::sync_branch_rows(&tx, branch_id, r.branch, now)?;
3410        }
3411        laps.lap("branch_rows");
3412
3413        // The CONTENT is current, but the recorded commit may not be: committing
3414        // already-indexed files moves HEAD without changing a single hash.
3415        // Skipping the metadata update left `commit_sha` behind forever, so
3416        // freshness reported `stale` on a perfectly current index until some
3417        // unrelated edit happened to force a rebuild.
3418        if let Some(git_dirty) = r.git_dirty {
3419            CacheManager::update_branch_metadata_on(
3420                &tx,
3421                r.branch,
3422                r.commit,
3423                r.rels.len(),
3424                git_dirty,
3425            )?;
3426        }
3427        // Every file has its branch row now: the count is the file count.
3428        CacheManager::set_total_files_on(&tx, r.rels.len(), now)?;
3429        tx.commit()?;
3430        laps.lap("commit");
3431
3432        // On the synced branch every file's branch hash is its row's: all unchanged.
3433        let (new_files, modified_files, unchanged_files) = if r.in_sync {
3434            (0, 0, rows.len())
3435        } else {
3436            breakdown(
3437                r.rels
3438                    .iter()
3439                    .zip(&rows)
3440                    .map(|(rel, row)| (rel.as_str(), row.hash.as_str())),
3441                r.existing_hashes,
3442            )
3443        };
3444        // Nothing changed: the statistics are the rows' (what `stats_synced` would
3445        // count from `files`), without a query.
3446        let mut files_by_language: HashMap<String, usize> = HashMap::new();
3447        let mut lines_by_language: HashMap<String, usize> = HashMap::new();
3448        for row in &rows {
3449            match files_by_language.get_mut(&row.language) {
3450                Some(n) => *n += 1,
3451                None => {
3452                    files_by_language.insert(row.language.clone(), 1);
3453                }
3454            }
3455            match lines_by_language.get_mut(&row.language) {
3456                Some(n) => *n += row.line_count,
3457                None => {
3458                    lines_by_language.insert(row.language.clone(), row.line_count);
3459                }
3460            }
3461        }
3462        let (index_size_bytes, trigram_index_bytes, corpus_bytes) = self.cache.store_sizes();
3463        let mut stats = IndexStats {
3464            total_files: r.rels.len(),
3465            index_size_bytes,
3466            last_updated: chrono::DateTime::from_timestamp(now, 0)
3467                .unwrap_or_else(chrono::Utc::now)
3468                .to_rfc3339(),
3469            files_by_language,
3470            lines_by_language,
3471            corpus_bytes,
3472            trigram_index_bytes,
3473            ..Default::default()
3474        };
3475        laps.lap("stats");
3476        log::info!("refresh phases:{}", laps.line);
3477        stats.new_files = new_files;
3478        stats.modified_files = modified_files;
3479        stats.unchanged_files = unchanged_files;
3480        stats.deleted_files = 0;
3481        stats.skipped_too_large = r.skipped.0;
3482        stats.skipped_bytes_too_large = r.skipped.1;
3483        stats.skipped_binary = r.skipped.2;
3484        Ok(stats)
3485    }
3486
3487    /// One meta.db transaction for a run that rewrote the stores: the rows of
3488    /// files whose bytes, fingerprint, dirty flag or walk position changed, the
3489    /// deletions, this branch's rows, and the dependency and export rows (every
3490    /// file's when `full_deps`, else the changed files', plus re-resolution of the
3491    /// rest when files were added or removed).
3492    fn write_meta(&self, w: MetaWrite<'_>) -> Result<()> {
3493        let now = chrono::Utc::now().timestamp();
3494        let mut laps = Laps::new();
3495        let seqs = crate::meta_update::plan_walk_seq(
3496            &w.present
3497                .iter()
3498                .map(|&i| w.stored.get(&w.rels[i]).map(|s| s.walk_seq))
3499                .collect::<Vec<_>>(),
3500        );
3501        let written: HashMap<usize, &IndexedFile> =
3502            w.written.iter().map(|f| (f.index, f)).collect();
3503
3504        let mut rows: Vec<crate::cache::FileRow> = Vec::new();
3505        let mut row_files: Vec<usize> = Vec::new(); // discovery index of each row
3506        let mut walk = Vec::new();
3507        let mut flips = Vec::new();
3508        let mut touched = Vec::new();
3509        for (k, &i) in w.present.iter().enumerate() {
3510            let rel = &w.rels[i];
3511            let dirty = w.dirty_paths.contains(rel);
3512            let stored = w.stored.get(rel);
3513            match written.get(&i) {
3514                Some(f)
3515                    if !(w.status[i] == FileStatus::Unchanged
3516                        && stored.is_some_and(|row| row.hash == f.hash)) =>
3517                {
3518                    rows.push(crate::cache::FileRow {
3519                        path: rel.clone(),
3520                        hash: f.hash.clone(),
3521                        language: format!("{:?}", f.language),
3522                        line_count: f.line_count,
3523                        size: f.size,
3524                        mtime_ns: f.mtime_ns,
3525                        dirty,
3526                        walk_seq: seqs[k],
3527                    });
3528                    row_files.push(i);
3529                }
3530                _ => {
3531                    // Not read this run (or read with the bytes and fingerprint
3532                    // stored): only the walk position, the fingerprint of a touched
3533                    // file and the dirty flag can move.
3534                    let Some(row) = stored else { continue };
3535                    if seqs[k] != row.walk_seq {
3536                        walk.push((row.id, seqs[k]));
3537                    }
3538                    if w.status[i] == FileStatus::Touched && !written.contains_key(&i) {
3539                        let (size, mtime) = w.metas[i]
3540                            .as_ref()
3541                            .map(|md| (md.size(), md.recorded_mtime_ns(w.run_start)))
3542                            .unwrap_or((0, 0));
3543                        touched.push((row.id, size, mtime, dirty));
3544                    } else if dirty != row.dirty {
3545                        flips.push((row.id, dirty));
3546                    }
3547                }
3548            }
3549        }
3550        let present: std::collections::HashSet<&str> =
3551            w.present.iter().map(|&i| w.rels[i].as_str()).collect();
3552        let deleted: Vec<i64> = w
3553            .stored
3554            .iter()
3555            .filter(|(p, _)| !present.contains(p.as_str()))
3556            .map(|(_, row)| row.id)
3557            .collect();
3558        let paths_changed = !deleted.is_empty()
3559            || w.present
3560                .iter()
3561                .any(|&i| !w.stored.contains_key(&w.rels[i]));
3562
3563        laps.lap("plan");
3564        let mut conn = crate::cache::open_meta_db(self.cache.path().join(crate::cache::META_DB))?;
3565        let tx = conn
3566            .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
3567            .context("Failed to begin meta.db transaction")?;
3568
3569        crate::meta_update::delete_files(&tx, &deleted)?;
3570        let new_ids = crate::meta_update::upsert_files(&tx, &rows, now)?;
3571        crate::meta_update::set_walk_seqs(&tx, &walk)?;
3572        crate::meta_update::refresh_stats(&tx, &touched)?;
3573        crate::meta_update::set_dirty_flags(&tx, &flips)?;
3574        laps.lap("rows");
3575        let branch_id = self
3576            .cache
3577            .get_or_create_branch_id(&tx, w.branch, w.commit)?;
3578        crate::meta_update::sync_branch_rows(&tx, branch_id, w.branch, now)?;
3579        laps.lap("branch_rows");
3580        log::info!(
3581            "meta.db: {} rows written, {} deleted, {} moved, {} touched, {} dirty flags",
3582            rows.len(),
3583            deleted.len(),
3584            walk.len(),
3585            touched.len(),
3586            flips.len()
3587        );
3588
3589        // id of every file read this run, by discovery index.
3590        let mut ids: HashMap<usize, i64> = w
3591            .written
3592            .iter()
3593            .filter_map(|f| w.stored.get(&w.rels[f.index]).map(|s| (f.index, s.id)))
3594            .collect();
3595        for (i, id) in row_files.iter().zip(new_ids) {
3596            ids.insert(*i, id);
3597        }
3598
3599        let resolver = crate::dependency::PathResolver::from_conn(&tx)
3600            .context("Failed to load file paths for dependency resolution")?;
3601        laps.lap("resolver");
3602        let ctx = crate::dependency_resolve::ResolverContext::new(w.root, w.resolver_configs);
3603        let mut writer = crate::dependency::DependencyWriter::new(&tx);
3604        if w.full_deps {
3605            writer.clear_all()?;
3606        }
3607        // In walk order: the row order a full build produces.
3608        let mut resolved_here: std::collections::HashSet<i64> = std::collections::HashSet::new();
3609        for f in w.written {
3610            let Some((imports, exports, declared)) = &f.imports else {
3611                continue;
3612            };
3613            let rel = &w.rels[f.index];
3614            let file_id = ids[&f.index];
3615            resolved_here.insert(file_id);
3616            let deps = ctx.resolve_file_imports(file_id, rel, imports.clone(), &resolver);
3617            writer.replace_dependencies(file_id, &deps)?;
3618            writer.replace_members(
3619                file_id,
3620                &crate::dependency_resolve::package_members(rel, declared),
3621            )?;
3622            if !w.full_deps {
3623                writer.clear_exports(file_id)?;
3624            }
3625            for export in exports {
3626                let resolved = ctx.resolve_export(rel, export, &resolver);
3627                writer.insert_export(
3628                    file_id,
3629                    export.exported_symbol.as_deref(),
3630                    &export.source_path,
3631                    resolved,
3632                    export.line_number,
3633                )?;
3634            }
3635        }
3636        let (deps_written, exports_written) = writer.counts();
3637        laps.lap("deps");
3638
3639        // An added or removed path can change how an unchanged file's imports
3640        // resolve (suffix matches, ambiguity, the first of several candidates).
3641        let mut reresolved = 0usize;
3642        if !w.full_deps && paths_changed {
3643            reresolved = reresolve(&tx, &ctx, &resolver, &resolved_here)?;
3644        }
3645        let written_ids: Vec<i64> = ids.values().copied().collect();
3646        refresh_vendored(
3647            &tx,
3648            &w.resolver_configs.vendor,
3649            (!w.full_deps).then_some(written_ids.as_slice()),
3650        )?;
3651
3652        crate::meta_update::set_statistic(
3653            &tx,
3654            RESOLVER_DIGEST_KEY,
3655            &w.resolver_configs.digest,
3656            now,
3657        )?;
3658        crate::meta_update::set_statistic(
3659            &tx,
3660            INDEX_GENERATION_KEY,
3661            &w.generation.to_string(),
3662            now,
3663        )?;
3664        laps.lap("reresolve");
3665        tx.commit()?;
3666        laps.lap("commit");
3667        log::info!("meta.db write phases:{}", laps.line);
3668        log::info!(
3669            "dependencies: {} rows, {} exports written; {} rows re-resolved",
3670            deps_written,
3671            exports_written,
3672            reresolved
3673        );
3674        Ok(())
3675    }
3676
3677    /// Discover all indexable files in the directory tree.
3678    ///
3679    /// `stored` is meta.db's view of the last indexed tree: a non-code file whose
3680    /// stat matches its row was sniffed for NUL bytes when it was indexed and is
3681    /// not read again.
3682    #[cfg(test)]
3683    fn discover_files(
3684        &self,
3685        root: &Path,
3686        stored: &HashMap<String, crate::meta_update::StoredFile>,
3687    ) -> Result<Discovered> {
3688        self.discover_files_in(root, stored, None)
3689    }
3690
3691    /// [`Self::discover_files`] limited to `targets` (all files when `None`): the
3692    /// same walker and rules, entering only the named paths and their ancestors, so
3693    /// every ignore file on the way applies exactly as in a full walk.
3694    fn discover_files_in(
3695        &self,
3696        root: &Path,
3697        stored: &HashMap<String, crate::meta_update::StoredFile>,
3698        targets: Option<Arc<Targets>>,
3699    ) -> Result<Discovered> {
3700        let walked = self.walk_candidates(root, targets)?;
3701        Ok(Self::drop_binaries(root, walked, stored, None))
3702    }
3703
3704    /// The walk half of discovery: every file the walker and the path policy admit,
3705    /// under the size limit, with its stat, in walk order. Non-code files are only
3706    /// marked: [`Self::drop_binaries`] decides, once the stored rows are known.
3707    fn walk_candidates(&self, root: &Path, targets: Option<Arc<Targets>>) -> Result<Walked> {
3708        let mut out = Walked::default();
3709
3710        let policy = self.path_policy(root);
3711        let walker = Self::targeted_walk_builder(root, &self.config, &policy, targets).build();
3712
3713        for entry in walker {
3714            let entry = entry?;
3715            let path = entry.path();
3716
3717            // Only process files (not directories)
3718            if !entry.file_type().map(|ft| ft.is_file()).unwrap_or(false) {
3719                continue;
3720            }
3721
3722            // Check extension / language eligibility first (cheap)
3723            let Some(lang) = policy.classify(path) else {
3724                continue;
3725            };
3726
3727            // Check file size separately so we can report skipped counts
3728            let mut size = 0u64;
3729            let metadata = std::fs::metadata(path).ok();
3730            if let Some(metadata) = &metadata {
3731                size = metadata.len();
3732                if size > self.config.max_file_size as u64 {
3733                    log::debug!("Skipping {} (too large: {} bytes)", path.display(), size);
3734                    out.found.skipped_too_large += 1;
3735                    out.found.skipped_bytes_too_large += size;
3736                    continue;
3737                }
3738            }
3739
3740            out.found.rels.push(normalize_rel(root, path));
3741            out.found.sizes.push(size);
3742            out.found
3743                .metas
3744                .push(metadata.as_ref().map(crate::cache::FileStat::of));
3745            out.non_code.push(!lang.is_code());
3746        }
3747
3748        Ok(out)
3749    }
3750
3751    /// The binary half of discovery. A code extension is trusted to be text.
3752    /// Anything else in the tracked tier (`image.png`, `OWNERS`, `data.bin`) is
3753    /// sniffed: ripgrep's rule, a NUL byte anywhere means binary, and a binary file
3754    /// is never in the index. Only the long tail pays the read (from the page
3755    /// cache, since the main pass reads it again a moment later), and not a file
3756    /// that is unchanged since it was indexed. Order is kept.
3757    fn drop_binaries(
3758        root: &Path,
3759        walked: Walked,
3760        stored: &HashMap<String, crate::meta_update::StoredFile>,
3761        pool: Option<&rayon::ThreadPool>,
3762    ) -> Discovered {
3763        let Walked {
3764            found: mut out,
3765            non_code,
3766        } = walked;
3767        let to_sniff: Vec<usize> = (0..out.rels.len())
3768            .filter(|&i| {
3769                non_code[i]
3770                    && !stored
3771                        .get(&out.rels[i])
3772                        .zip(out.metas[i].as_ref())
3773                        .is_some_and(|(row, md)| row.stat_matches(md))
3774            })
3775            .collect();
3776        let sniff = |i: &usize| looks_binary(&root.join(&out.rels[*i]));
3777        let binary: Vec<bool> = match pool {
3778            Some(pool) => pool.install(|| to_sniff.par_iter().map(sniff).collect()),
3779            None => to_sniff.iter().map(sniff).collect(),
3780        };
3781        let dropped: std::collections::HashSet<usize> = to_sniff
3782            .iter()
3783            .zip(binary)
3784            .filter_map(|(&i, b)| b.then_some(i))
3785            .collect();
3786        if dropped.is_empty() {
3787            return out;
3788        }
3789        for &i in &dropped {
3790            log::debug!("Skipping {} (binary)", out.rels[i]);
3791        }
3792        out.skipped_binary += dropped.len();
3793        fn keep<T>(v: &mut Vec<T>, dropped: &std::collections::HashSet<usize>) {
3794            let mut i = 0;
3795            v.retain(|_| {
3796                let k = !dropped.contains(&i);
3797                i += 1;
3798                k
3799            });
3800        }
3801        keep(&mut out.rels, &dropped);
3802        keep(&mut out.sizes, &dropped);
3803        keep(&mut out.metas, &dropped);
3804        out
3805    }
3806
3807    /// The directory walker every tree pass shares: the indexer, and the freshness
3808    /// check outside git (which has no `git status` to name candidates and must
3809    /// walk). One builder so the two can never disagree about what is in the tree.
3810    /// [`Indexer::walk_builder`], entering only `targets` and their ancestors when
3811    /// given.
3812    fn targeted_walk_builder(
3813        root: &Path,
3814        config: &IndexConfig,
3815        policy: &PathPolicy,
3816        targets: Option<Arc<Targets>>,
3817    ) -> WalkBuilder {
3818        let mut builder = Self::walk_builder(root, config, policy);
3819        if let Some(targets) = targets {
3820            // Replaces the walker's own entry filter, so repeat it.
3821            let hidden = policy.hidden();
3822            let root_buf = root.to_path_buf();
3823            builder.filter_entry(move |e| {
3824                if hidden {
3825                    let name = e.file_name();
3826                    if name == ".git" || name == crate::cache::CACHE_DIR {
3827                        return false;
3828                    }
3829                }
3830                let rel = normalize_rel(&root_buf, e.path());
3831                targets.admits(&rel)
3832            });
3833        }
3834        builder
3835    }
3836
3837    /// Which of the files `rels` (relative, `/`-separated) the walk reaches: the
3838    /// ignore files and the include/exclude patterns applied exactly as an index
3839    /// run applies them. Walks only the ancestors of `rels`.
3840    pub(crate) fn walked_among(
3841        root: &Path,
3842        config: &IndexConfig,
3843        policy: &PathPolicy,
3844        rels: &[String],
3845    ) -> std::collections::HashSet<String> {
3846        let targets = Arc::new(Targets::new(rels));
3847        let walker =
3848            Self::targeted_walk_builder(root, config, policy, Some(Arc::clone(&targets))).build();
3849        walker
3850            .flatten()
3851            .filter(|e| e.file_type().is_some_and(|t| t.is_file()))
3852            .map(|e| normalize_rel(root, e.path()))
3853            .filter(|rel| targets.exact.contains(rel))
3854            .collect()
3855    }
3856
3857    pub fn walk_builder(root: &Path, config: &IndexConfig, policy: &PathPolicy) -> WalkBuilder {
3858        // WalkBuilder from ignore crate automatically respects:
3859        // - .gitignore (when in a git repo)
3860        // - .ignore files
3861        // - Hidden files (can be configured)
3862        let mut builder = WalkBuilder::new(root);
3863        builder
3864            .follow_links(config.follow_symlinks)
3865            .hidden(!policy.hidden())
3866            .git_ignore(true) // Explicitly enable gitignore support (enabled by default, but be explicit)
3867            .git_global(false) // Don't use global gitignore
3868            .git_exclude(false); // Don't use .git/info/exclude
3869        if policy.hidden() {
3870            // Dot-directories are walked, but never the repository's own and never
3871            // Reflex's own cache: indexing `.reflex/content.bin` into content.bin
3872            // is a loop, and `.git/objects` is binary noise by the thousand.
3873            builder.filter_entry(|e| {
3874                let name = e.file_name();
3875                name != ".git" && name != crate::cache::CACHE_DIR
3876            });
3877        }
3878        // `[index] include.patterns` / `exclude.patterns`, gitignore semantics.
3879        if let Some(ov) = policy.overrides() {
3880            builder.overrides(ov.clone());
3881        }
3882        builder
3883    }
3884
3885    /// Whether a path is one Reflex would index, judged by extension alone.
3886    ///
3887    /// Public so freshness checking can ask the same question the walker asks. If the
3888    /// two ever disagree, editing a file Reflex does not index (a README, anything
3889    /// under `target/`) would mark the index permanently stale — a cure worse than
3890    /// the disease.
3891    ///
3892    /// Judges extension only: no filesystem access, no size check, no `.gitignore`
3893    /// (git's own output is already filtered by that). Cheap enough to call per path
3894    /// in a `git status` listing.
3895    pub fn is_indexable_path(path: &Path) -> bool {
3896        Self::is_indexable_path_with(path, None)
3897    }
3898
3899    /// [`Self::is_indexable_path`] under an `[index]` policy.
3900    ///
3901    /// The freshness check must apply the same policy as the walker: a file the
3902    /// config excludes is not indexed, so editing it must not report staleness.
3903    pub fn is_indexable_path_with(path: &Path, policy: Option<&PathPolicy>) -> bool {
3904        let default_policy;
3905        let policy = match policy {
3906            Some(p) => p,
3907            None => {
3908                default_policy = PathPolicy::default();
3909                &default_policy
3910            }
3911        };
3912        // Mirror the walker's hidden rule. Without this, Reflex's OWN
3913        // `.reflex/config.toml` counts as an indexable change the moment the text
3914        // tier claims `.toml`, and the index reports itself permanently stale.
3915        policy.hidden_ok(path) && policy.classify(path).is_some()
3916    }
3917
3918    /// Check if a file's language/extension is eligible for indexing (without size check).
3919    fn should_index_lang(&self, path: &Path) -> bool {
3920        PathPolicy::from_config(Path::new("."), &self.config)
3921            .classify(path)
3922            .is_some()
3923    }
3924
3925    /// Check if a file should be indexed based on config (language + size).
3926    #[allow(dead_code)]
3927    fn should_index(&self, path: &Path) -> bool {
3928        if !self.should_index_lang(path) {
3929            return false;
3930        }
3931
3932        // Check file size limits
3933        if let Ok(metadata) = std::fs::metadata(path)
3934            && metadata.len() > self.config.max_file_size as u64
3935        {
3936            log::debug!(
3937                "Skipping {} (too large: {} bytes)",
3938                path.display(),
3939                metadata.len()
3940            );
3941            return false;
3942        }
3943
3944        // `[index] include/exclude` patterns are applied by the walker
3945        // (`discover_files`) and by `is_indexable_path_with`; this per-file check
3946        // has no root to anchor them against.
3947        true
3948    }
3949
3950    /// Compute blake3 hash from file contents for change detection
3951    fn hash_content(&self, content: &[u8]) -> String {
3952        let hash = blake3::hash(content);
3953        hash.to_hex().to_string()
3954    }
3955
3956    /// Check available disk space before indexing
3957    ///
3958    /// Ensures there's enough free space to create the index. Warns if disk space is low.
3959    /// This prevents partial index writes and confusing error messages.
3960    #[cfg_attr(not(unix), allow(unused_variables))]
3961    fn check_disk_space(&self, root: &Path) -> Result<()> {
3962        // Get available space on the filesystem containing the cache directory
3963        let cache_path = self.cache.path();
3964
3965        // Use statvfs on Unix systems
3966        #[cfg(unix)]
3967        {
3968            // On Linux, we can use statvfs to get available space
3969            // For now, we'll use a simple heuristic: warn if we can't write a test file
3970            let test_file = cache_path.join(".space_check");
3971            match std::fs::write(&test_file, b"test") {
3972                Ok(_) => {
3973                    let _ = std::fs::remove_file(&test_file);
3974
3975                    // Try to estimate available space using df command
3976                    if let Ok(output) = std::process::Command::new("df")
3977                        .arg("-k")
3978                        .arg(cache_path.parent().unwrap_or(root))
3979                        .output()
3980                        && let Ok(df_output) = String::from_utf8(output.stdout)
3981                    {
3982                        // Parse df output to get available KB
3983                        if let Some(line) = df_output.lines().nth(1) {
3984                            let parts: Vec<&str> = line.split_whitespace().collect();
3985                            if parts.len() >= 4
3986                                && let Ok(available_kb) = parts[3].parse::<u64>()
3987                            {
3988                                let available_mb = available_kb / 1024;
3989
3990                                // Warn if less than 100MB available
3991                                if available_mb < 100 {
3992                                    log::warn!(
3993                                        "Low disk space: only {}MB available. Indexing may fail.",
3994                                        available_mb
3995                                    );
3996                                    output::warn(&format!(
3997                                        "Low disk space ({}MB available). Consider freeing up space.",
3998                                        available_mb
3999                                    ));
4000                                } else {
4001                                    log::debug!("Available disk space: {}MB", available_mb);
4002                                }
4003                            }
4004                        }
4005                    }
4006
4007                    Ok(())
4008                }
4009                Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
4010                    anyhow::bail!(
4011                        "Permission denied writing to cache directory: {}. Check file permissions.",
4012                        cache_path.display()
4013                    )
4014                }
4015                Err(e) => {
4016                    // If we can't write, it might be a disk space issue
4017                    log::warn!(
4018                        "Failed to write test file (possible disk space issue): {}",
4019                        e
4020                    );
4021                    Err(e).context(
4022                        "Failed to verify disk space - indexing may fail due to insufficient space",
4023                    )
4024                }
4025            }
4026        }
4027
4028        #[cfg(not(unix))]
4029        {
4030            // On Windows, try to write a test file
4031            let test_file = cache_path.join(".space_check");
4032            match std::fs::write(&test_file, b"test") {
4033                Ok(_) => {
4034                    let _ = std::fs::remove_file(&test_file);
4035                    Ok(())
4036                }
4037                Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
4038                    anyhow::bail!(
4039                        "Permission denied writing to cache directory: {}. Check file permissions.",
4040                        cache_path.display()
4041                    )
4042                }
4043                Err(e) => {
4044                    log::warn!(
4045                        "Failed to write test file (possible disk space issue): {}",
4046                        e
4047                    );
4048                    Err(e).context(
4049                        "Failed to verify disk space - indexing may fail due to insufficient space",
4050                    )
4051                }
4052            }
4053        }
4054    }
4055}
4056
4057#[cfg(test)]
4058mod tests {
4059    use super::*;
4060    use std::fs;
4061    use tempfile::TempDir;
4062
4063    #[test]
4064    fn test_indexer_creation() {
4065        let temp = TempDir::new().unwrap();
4066        let cache = CacheManager::new(temp.path());
4067        let config = IndexConfig::default();
4068        let indexer = Indexer::new(cache, config);
4069
4070        assert!(indexer.cache.path().ends_with(".reflex"));
4071    }
4072
4073    #[test]
4074    fn test_hash_content() {
4075        let temp = TempDir::new().unwrap();
4076        let cache = CacheManager::new(temp.path());
4077        let config = IndexConfig::default();
4078        let indexer = Indexer::new(cache, config);
4079
4080        let content1 = b"hello world";
4081        let content2 = b"hello world";
4082        let content3 = b"different content";
4083
4084        let hash1 = indexer.hash_content(content1);
4085        let hash2 = indexer.hash_content(content2);
4086        let hash3 = indexer.hash_content(content3);
4087
4088        // Same content should produce same hash
4089        assert_eq!(hash1, hash2);
4090
4091        // Different content should produce different hash
4092        assert_ne!(hash1, hash3);
4093
4094        // Hash should be hex string
4095        assert_eq!(hash1.len(), 64); // blake3 hash is 32 bytes = 64 hex chars
4096    }
4097
4098    #[test]
4099    fn test_should_index_rust_file() {
4100        let temp = TempDir::new().unwrap();
4101        let cache = CacheManager::new(temp.path());
4102        let config = IndexConfig::default();
4103        let indexer = Indexer::new(cache, config);
4104
4105        // Create a small Rust file
4106        let rust_file = temp.path().join("test.rs");
4107        fs::write(&rust_file, "fn main() {}").unwrap();
4108
4109        assert!(indexer.should_index(&rust_file));
4110    }
4111
4112    #[test]
4113    fn test_should_index_unsupported_extension() {
4114        let temp = TempDir::new().unwrap();
4115        let cache = CacheManager::new(temp.path());
4116        let config = IndexConfig::default();
4117        let indexer = Indexer::new(cache, config);
4118
4119        // Tracked mode (the default) takes every file by path; whether a file is
4120        // binary is decided from its bytes in `discover_files`, not here.
4121        let unsupported_file = temp.path().join("test.xyz");
4122        fs::write(&unsupported_file, "mystery format").unwrap();
4123        assert!(indexer.should_index(&unsupported_file));
4124
4125        // Allowlist mode keeps the pre-2.0.0 rule.
4126        let allowlist = Indexer::new(
4127            CacheManager::new(temp.path()),
4128            IndexConfig {
4129                mode: IndexMode::Allowlist,
4130                ..Default::default()
4131            },
4132        );
4133        assert!(!allowlist.should_index(&unsupported_file));
4134        let binary_file = temp.path().join("logo.png");
4135        fs::write(&binary_file, "not really a png").unwrap();
4136        assert!(!allowlist.should_index(&binary_file));
4137    }
4138
4139    #[test]
4140    fn test_binary_sniff() {
4141        assert!(!is_binary(b"plain text\n"));
4142        assert!(is_binary(b"\x89PNG\r\n\x1a\n\0\0"));
4143        // Anywhere, not just the first 8 KB: ripgrep skips such a file too.
4144        let mut late = vec![b'a'; 64 * 1024];
4145        late.push(0);
4146        assert!(is_binary(&late));
4147    }
4148
4149    #[test]
4150    fn test_should_index_text_tier() {
4151        let temp = TempDir::new().unwrap();
4152        let indexer = Indexer::new(CacheManager::new(temp.path()), IndexConfig::default());
4153
4154        for name in [
4155            "notes.md",
4156            "config.yaml",
4157            "data.json",
4158            "api.proto",
4159            "run.sh",
4160        ] {
4161            let path = temp.path().join(name);
4162            fs::write(&path, "realm_marker").unwrap();
4163            assert!(indexer.should_index(&path), "{name} should be indexed");
4164        }
4165
4166        // Lock files are indexed in tracked mode (and left out of searches unless
4167        // asked for); allowlist mode never indexes them.
4168        let lock = temp.path().join("package-lock.json");
4169        fs::write(&lock, "{}").unwrap();
4170        assert!(indexer.should_index(&lock));
4171        let allowlist = Indexer::new(
4172            CacheManager::new(temp.path()),
4173            IndexConfig {
4174                mode: IndexMode::Allowlist,
4175                ..Default::default()
4176            },
4177        );
4178        assert!(!allowlist.should_index(&lock));
4179    }
4180
4181    #[test]
4182    fn test_text_tier_can_be_disabled() {
4183        let temp = TempDir::new().unwrap();
4184        let indexer = Indexer::new(
4185            CacheManager::new(temp.path()),
4186            IndexConfig {
4187                text_tier: false,
4188                ..Default::default()
4189            },
4190        );
4191
4192        let md = temp.path().join("notes.md");
4193        fs::write(&md, "text").unwrap();
4194        assert!(!indexer.should_index(&md));
4195
4196        let rs = temp.path().join("main.rs");
4197        fs::write(&rs, "fn main() {}").unwrap();
4198        assert!(indexer.should_index(&rs), "code is unaffected");
4199    }
4200
4201    #[test]
4202    fn test_should_index_no_extension() {
4203        let temp = TempDir::new().unwrap();
4204        let cache = CacheManager::new(temp.path());
4205        let config = IndexConfig::default();
4206        let indexer = Indexer::new(cache, config);
4207
4208        // Tracked mode: every extensionless text file. Allowlist mode: only the
4209        // names on the list (`Makefile`), not `README`.
4210        let makefile = temp.path().join("Makefile");
4211        fs::write(&makefile, "all:\n\techo hello").unwrap();
4212        assert!(indexer.should_index(&makefile));
4213
4214        let readme = temp.path().join("README");
4215        fs::write(&readme, "hello").unwrap();
4216        assert!(indexer.should_index(&readme));
4217
4218        let allowlist = Indexer::new(
4219            CacheManager::new(temp.path()),
4220            IndexConfig {
4221                mode: IndexMode::Allowlist,
4222                ..Default::default()
4223            },
4224        );
4225        assert!(allowlist.should_index(&makefile));
4226        assert!(!allowlist.should_index(&readme));
4227    }
4228
4229    #[test]
4230    fn test_should_index_size_limit() {
4231        let temp = TempDir::new().unwrap();
4232        let cache = CacheManager::new(temp.path());
4233
4234        // Config with 100 byte size limit
4235        let config = IndexConfig {
4236            max_file_size: 100,
4237            ..Default::default()
4238        };
4239
4240        let indexer = Indexer::new(cache, config);
4241
4242        // Create small file (should be indexed)
4243        let small_file = temp.path().join("small.rs");
4244        fs::write(&small_file, "fn main() {}").unwrap();
4245        assert!(indexer.should_index(&small_file));
4246
4247        // Create large file (should be skipped)
4248        let large_file = temp.path().join("large.rs");
4249        let large_content = "a".repeat(150);
4250        fs::write(&large_file, large_content).unwrap();
4251        assert!(!indexer.should_index(&large_file));
4252    }
4253
4254    #[test]
4255    fn test_discover_files_empty_dir() {
4256        let temp = TempDir::new().unwrap();
4257        let cache = CacheManager::new(temp.path());
4258        let config = IndexConfig::default();
4259        let indexer = Indexer::new(cache, config);
4260
4261        let files = indexer
4262            .discover_files(temp.path(), &HashMap::new())
4263            .unwrap()
4264            .rels
4265            .iter()
4266            .map(std::path::PathBuf::from)
4267            .collect::<Vec<_>>();
4268        assert_eq!(files.len(), 0);
4269    }
4270
4271    #[test]
4272    fn test_discover_files_single_file() {
4273        let temp = TempDir::new().unwrap();
4274        let cache = CacheManager::new(temp.path());
4275        let config = IndexConfig::default();
4276        let indexer = Indexer::new(cache, config);
4277
4278        // Create a Rust file
4279        let rust_file = temp.path().join("main.rs");
4280        fs::write(&rust_file, "fn main() {}").unwrap();
4281
4282        let files = indexer
4283            .discover_files(temp.path(), &HashMap::new())
4284            .unwrap()
4285            .rels
4286            .iter()
4287            .map(std::path::PathBuf::from)
4288            .collect::<Vec<_>>();
4289        assert_eq!(files.len(), 1);
4290        assert!(files[0].ends_with("main.rs"));
4291    }
4292
4293    #[test]
4294    fn test_discover_files_multiple_languages() {
4295        let temp = TempDir::new().unwrap();
4296        let cache = CacheManager::new(temp.path());
4297        let config = IndexConfig::default();
4298        let indexer = Indexer::new(cache, config);
4299
4300        // Create files of different languages
4301        fs::write(temp.path().join("main.rs"), "fn main() {}").unwrap();
4302        fs::write(temp.path().join("script.py"), "print('hello')").unwrap();
4303        fs::write(temp.path().join("app.js"), "console.log('hi')").unwrap();
4304        // Since 1.7.2 markdown IS indexed, in the plain-text tier.
4305        fs::write(temp.path().join("README.md"), "# Project").unwrap();
4306        // Since 2.0.0 (tracked mode) every non-binary file is indexed, whatever
4307        // its extension; a binary one is sniffed out.
4308        fs::write(temp.path().join("mystery.xyz"), "?").unwrap();
4309        fs::write(temp.path().join("blob.bin"), b"\0\x01\x02").unwrap();
4310
4311        let found = indexer
4312            .discover_files(temp.path(), &HashMap::new())
4313            .unwrap();
4314        assert_eq!(found.rels.len(), 5, "3 code files, the markdown, the .xyz");
4315        assert_eq!(found.skipped_binary, 1);
4316    }
4317
4318    #[test]
4319    fn test_discover_files_subdirectories() {
4320        let temp = TempDir::new().unwrap();
4321        let cache = CacheManager::new(temp.path());
4322        let config = IndexConfig::default();
4323        let indexer = Indexer::new(cache, config);
4324
4325        // Create nested directory structure
4326        let src_dir = temp.path().join("src");
4327        fs::create_dir(&src_dir).unwrap();
4328        fs::write(src_dir.join("main.rs"), "fn main() {}").unwrap();
4329        fs::write(src_dir.join("lib.rs"), "pub mod test {}").unwrap();
4330
4331        let tests_dir = temp.path().join("tests");
4332        fs::create_dir(&tests_dir).unwrap();
4333        fs::write(tests_dir.join("test.rs"), "#[test] fn test() {}").unwrap();
4334
4335        let files = indexer
4336            .discover_files(temp.path(), &HashMap::new())
4337            .unwrap()
4338            .rels
4339            .iter()
4340            .map(std::path::PathBuf::from)
4341            .collect::<Vec<_>>();
4342        assert_eq!(files.len(), 3);
4343    }
4344
4345    #[test]
4346    fn test_discover_files_respects_gitignore() {
4347        let temp = TempDir::new().unwrap();
4348
4349        // Initialize git repo (required for .gitignore to work with WalkBuilder)
4350        std::process::Command::new("git")
4351            .arg("init")
4352            .current_dir(temp.path())
4353            .output()
4354            .expect("Failed to initialize git repo");
4355
4356        let cache = CacheManager::new(temp.path());
4357        let config = IndexConfig::default();
4358        let indexer = Indexer::new(cache, config);
4359
4360        // Create .gitignore - use "ignored/" pattern to ignore the directory
4361        // Note: WalkBuilder respects .gitignore ONLY in git repositories
4362        fs::write(temp.path().join(".gitignore"), "ignored/\n").unwrap();
4363
4364        // Create files
4365        fs::write(temp.path().join("included.rs"), "fn main() {}").unwrap();
4366        fs::write(temp.path().join("also_included.py"), "print('hi')").unwrap();
4367
4368        let ignored_dir = temp.path().join("ignored");
4369        fs::create_dir(&ignored_dir).unwrap();
4370        fs::write(ignored_dir.join("excluded.rs"), "fn test() {}").unwrap();
4371
4372        let files = indexer
4373            .discover_files(temp.path(), &HashMap::new())
4374            .unwrap()
4375            .rels
4376            .iter()
4377            .map(std::path::PathBuf::from)
4378            .collect::<Vec<_>>();
4379
4380        // Verify the expected files are found
4381        assert!(
4382            files.iter().any(|f| f.ends_with("included.rs")),
4383            "Should find included.rs"
4384        );
4385        assert!(
4386            files.iter().any(|f| f.ends_with("also_included.py")),
4387            "Should find also_included.py"
4388        );
4389
4390        // Verify excluded.rs in ignored/ directory is NOT found
4391        // This is the key test - gitignore should filter it out
4392        assert!(
4393            !files.iter().any(|f| {
4394                let path_str = f.to_string_lossy();
4395                path_str.contains("ignored") && f.ends_with("excluded.rs")
4396            }),
4397            "Should NOT find excluded.rs in ignored/ directory (gitignore pattern)"
4398        );
4399
4400        // Should find exactly 2 files (included.rs and also_included.py)
4401        // .gitignore file itself has no supported language extension, so it won't be indexed
4402        assert_eq!(
4403            files.len(),
4404            2,
4405            "Should find exactly 2 files (not including .gitignore or ignored/excluded.rs)"
4406        );
4407    }
4408
4409    #[test]
4410    fn test_index_empty_directory() {
4411        let temp = TempDir::new().unwrap();
4412        let cache = CacheManager::new(temp.path());
4413        let config = IndexConfig::default();
4414        let indexer = Indexer::new(cache, config);
4415
4416        let stats = indexer.index(temp.path(), false).unwrap();
4417
4418        assert_eq!(stats.total_files, 0);
4419    }
4420
4421    #[test]
4422    fn test_index_single_rust_file() {
4423        let temp = TempDir::new().unwrap();
4424        let project_root = temp.path().join("project");
4425        fs::create_dir(&project_root).unwrap();
4426
4427        let cache = CacheManager::new(&project_root);
4428        let config = IndexConfig::default();
4429        let indexer = Indexer::new(cache, config);
4430
4431        // Create a Rust file
4432        fs::write(
4433            project_root.join("main.rs"),
4434            "fn main() { println!(\"Hello\"); }",
4435        )
4436        .unwrap();
4437
4438        let stats = indexer.index(&project_root, false).unwrap();
4439
4440        assert_eq!(stats.total_files, 1);
4441        assert!(stats.files_by_language.contains_key("Rust"));
4442    }
4443
4444    #[test]
4445    fn test_index_multiple_files() {
4446        let temp = TempDir::new().unwrap();
4447        let project_root = temp.path().join("project");
4448        fs::create_dir(&project_root).unwrap();
4449
4450        let cache = CacheManager::new(&project_root);
4451        let config = IndexConfig::default();
4452        let indexer = Indexer::new(cache, config);
4453
4454        // Create multiple files
4455        fs::write(project_root.join("main.rs"), "fn main() {}").unwrap();
4456        fs::write(project_root.join("lib.rs"), "pub fn test() {}").unwrap();
4457        fs::write(project_root.join("script.py"), "def main(): pass").unwrap();
4458
4459        let stats = indexer.index(&project_root, false).unwrap();
4460
4461        assert_eq!(stats.total_files, 3);
4462        assert_eq!(stats.files_by_language.get("Rust"), Some(&2));
4463        assert_eq!(stats.files_by_language.get("Python"), Some(&1));
4464    }
4465
4466    #[test]
4467    fn test_index_creates_trigram_index() {
4468        let temp = TempDir::new().unwrap();
4469        let project_root = temp.path().join("project");
4470        fs::create_dir(&project_root).unwrap();
4471
4472        let cache = CacheManager::new(&project_root);
4473        let config = IndexConfig::default();
4474        let indexer = Indexer::new(cache, config);
4475
4476        fs::write(project_root.join("main.rs"), "fn main() {}").unwrap();
4477
4478        indexer.index(&project_root, false).unwrap();
4479
4480        // Verify trigrams.bin was created
4481        let trigrams_path = project_root.join(".reflex/trigrams.bin");
4482        assert!(trigrams_path.exists());
4483    }
4484
4485    #[test]
4486    fn test_index_creates_content_store() {
4487        let temp = TempDir::new().unwrap();
4488        let project_root = temp.path().join("project");
4489        fs::create_dir(&project_root).unwrap();
4490
4491        let cache = CacheManager::new(&project_root);
4492        let config = IndexConfig::default();
4493        let indexer = Indexer::new(cache, config);
4494
4495        fs::write(project_root.join("main.rs"), "fn main() {}").unwrap();
4496
4497        indexer.index(&project_root, false).unwrap();
4498
4499        // Verify content.bin was created
4500        let content_path = project_root.join(".reflex/content.bin");
4501        assert!(content_path.exists());
4502    }
4503
4504    #[test]
4505    fn test_index_incremental_no_changes() {
4506        let temp = TempDir::new().unwrap();
4507        let project_root = temp.path().join("project");
4508        fs::create_dir(&project_root).unwrap();
4509
4510        let cache = CacheManager::new(&project_root);
4511        let config = IndexConfig::default();
4512        let indexer = Indexer::new(cache, config);
4513
4514        fs::write(project_root.join("main.rs"), "fn main() {}").unwrap();
4515
4516        // First index
4517        let stats1 = indexer.index(&project_root, false).unwrap();
4518        assert_eq!(stats1.total_files, 1);
4519
4520        // Second index without changes
4521        let stats2 = indexer.index(&project_root, false).unwrap();
4522        assert_eq!(stats2.total_files, 1);
4523    }
4524
4525    #[test]
4526    fn test_index_incremental_with_changes() {
4527        let temp = TempDir::new().unwrap();
4528        let project_root = temp.path().join("project");
4529        fs::create_dir(&project_root).unwrap();
4530
4531        let cache = CacheManager::new(&project_root);
4532        let config = IndexConfig::default();
4533        let indexer = Indexer::new(cache, config);
4534
4535        let main_path = project_root.join("main.rs");
4536        fs::write(&main_path, "fn main() {}").unwrap();
4537
4538        // First index
4539        indexer.index(&project_root, false).unwrap();
4540
4541        // Modify file
4542        fs::write(&main_path, "fn main() { println!(\"changed\"); }").unwrap();
4543
4544        // Second index should detect change
4545        let stats = indexer.index(&project_root, false).unwrap();
4546        assert_eq!(stats.total_files, 1);
4547    }
4548
4549    #[test]
4550    fn test_index_incremental_new_file() {
4551        let temp = TempDir::new().unwrap();
4552        let project_root = temp.path().join("project");
4553        fs::create_dir(&project_root).unwrap();
4554
4555        let cache = CacheManager::new(&project_root);
4556        let config = IndexConfig::default();
4557        let indexer = Indexer::new(cache, config);
4558
4559        fs::write(project_root.join("main.rs"), "fn main() {}").unwrap();
4560
4561        // First index
4562        let stats1 = indexer.index(&project_root, false).unwrap();
4563        assert_eq!(stats1.total_files, 1);
4564
4565        // Add new file
4566        fs::write(project_root.join("lib.rs"), "pub fn test() {}").unwrap();
4567
4568        // Second index should include new file
4569        let stats2 = indexer.index(&project_root, false).unwrap();
4570        assert_eq!(stats2.total_files, 2);
4571    }
4572
4573    #[test]
4574    fn test_index_parallel_threads_config() {
4575        let temp = TempDir::new().unwrap();
4576        let project_root = temp.path().join("project");
4577        fs::create_dir(&project_root).unwrap();
4578
4579        let cache = CacheManager::new(&project_root);
4580
4581        // Test with explicit thread count
4582        let config = IndexConfig {
4583            parallel_threads: 2,
4584            ..Default::default()
4585        };
4586
4587        let indexer = Indexer::new(cache, config);
4588
4589        fs::write(project_root.join("main.rs"), "fn main() {}").unwrap();
4590
4591        let stats = indexer.index(&project_root, false).unwrap();
4592        assert_eq!(stats.total_files, 1);
4593    }
4594
4595    #[test]
4596    fn test_index_parallel_threads_auto() {
4597        let temp = TempDir::new().unwrap();
4598        let project_root = temp.path().join("project");
4599        fs::create_dir(&project_root).unwrap();
4600
4601        let cache = CacheManager::new(&project_root);
4602
4603        // Test with auto thread count (0 = auto)
4604        let config = IndexConfig {
4605            parallel_threads: 0,
4606            ..Default::default()
4607        };
4608
4609        let indexer = Indexer::new(cache, config);
4610
4611        fs::write(project_root.join("main.rs"), "fn main() {}").unwrap();
4612
4613        let stats = indexer.index(&project_root, false).unwrap();
4614        assert_eq!(stats.total_files, 1);
4615    }
4616
4617    #[test]
4618    fn test_index_respects_size_limit() {
4619        let temp = TempDir::new().unwrap();
4620        let project_root = temp.path().join("project");
4621        fs::create_dir(&project_root).unwrap();
4622
4623        let cache = CacheManager::new(&project_root);
4624
4625        // Very small size limit
4626        let config = IndexConfig {
4627            max_file_size: 50,
4628            ..Default::default()
4629        };
4630
4631        let indexer = Indexer::new(cache, config);
4632
4633        // Small file (should be indexed)
4634        fs::write(project_root.join("small.rs"), "fn a() {}").unwrap();
4635
4636        // Large file (should be skipped)
4637        let large_content = "fn main() {}\n".repeat(10);
4638        fs::write(project_root.join("large.rs"), large_content).unwrap();
4639
4640        let stats = indexer.index(&project_root, false).unwrap();
4641
4642        // Only small file should be indexed
4643        assert_eq!(stats.total_files, 1);
4644    }
4645
4646    #[test]
4647    fn test_index_mixed_languages() {
4648        let temp = TempDir::new().unwrap();
4649        let project_root = temp.path().join("project");
4650        fs::create_dir(&project_root).unwrap();
4651
4652        let cache = CacheManager::new(&project_root);
4653        let config = IndexConfig::default();
4654        let indexer = Indexer::new(cache, config);
4655
4656        // Create files in multiple languages
4657        fs::write(project_root.join("main.rs"), "fn main() {}").unwrap();
4658        fs::write(project_root.join("test.py"), "def test(): pass").unwrap();
4659        fs::write(project_root.join("app.js"), "function main() {}").unwrap();
4660        fs::write(project_root.join("lib.go"), "func main() {}").unwrap();
4661
4662        let stats = indexer.index(&project_root, false).unwrap();
4663
4664        assert_eq!(stats.total_files, 4);
4665        assert!(stats.files_by_language.contains_key("Rust"));
4666        assert!(stats.files_by_language.contains_key("Python"));
4667        assert!(stats.files_by_language.contains_key("JavaScript"));
4668        assert!(stats.files_by_language.contains_key("Go"));
4669    }
4670
4671    #[test]
4672    fn test_index_updates_cache_stats() {
4673        let temp = TempDir::new().unwrap();
4674        let project_root = temp.path().join("project");
4675        fs::create_dir(&project_root).unwrap();
4676
4677        let cache = CacheManager::new(&project_root);
4678        let config = IndexConfig::default();
4679        let indexer = Indexer::new(cache, config);
4680
4681        fs::write(project_root.join("main.rs"), "fn main() {}").unwrap();
4682
4683        indexer.index(&project_root, false).unwrap();
4684
4685        // Verify cache stats were updated
4686        let cache = CacheManager::new(&project_root);
4687        let stats = cache.stats().unwrap();
4688
4689        assert_eq!(stats.total_files, 1);
4690        assert!(stats.index_size_bytes > 0);
4691    }
4692}