Skip to main content

reflex/
models.rs

1//! Core data models for Reflex
2//!
3//! These structures represent the normalized, deterministic output format
4//! that Reflex provides to AI agents and other programmatic consumers.
5
6use serde::{Deserialize, Serialize};
7use strum::{Display, EnumString};
8
9/// Represents a source code location span (line range only)
10#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
11pub struct Span {
12    /// Starting line number (1-indexed)
13    pub start_line: usize,
14    /// Ending line number (1-indexed)
15    pub end_line: usize,
16}
17
18impl Span {
19    pub fn new(start_line: usize, start_col: usize, end_line: usize, end_col: usize) -> Self {
20        // Ignore col parameters for backwards compatibility
21        let _ = (start_col, end_col);
22        Self {
23            start_line,
24            end_line,
25        }
26    }
27}
28
29/// Type of symbol found in code
30#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, EnumString, Display)]
31#[strum(serialize_all = "PascalCase")]
32pub enum SymbolKind {
33    Function,
34    Class,
35    Struct,
36    Enum,
37    Interface,
38    Trait,
39    Constant,
40    Variable,
41    Method,
42    Module,
43    Namespace,
44    Type,
45    Macro,
46    Property,
47    Event,
48    Import,
49    Export,
50    Attribute,
51    /// Catch-all for symbol kinds not yet explicitly supported.
52    /// This ensures no data loss when encountering new tree-sitter node types.
53    /// The string contains the original kind name from the parser.
54    #[strum(default)]
55    Unknown(String),
56}
57
58/// Programming language identifier
59#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
60#[serde(rename_all = "lowercase")]
61pub enum Language {
62    #[default]
63    Rust,
64    Python,
65    JavaScript,
66    TypeScript,
67    Vue,
68    Svelte,
69    Go,
70    Java,
71    PHP,
72    C,
73    Cpp,
74    CSharp,
75    Ruby,
76    Kotlin,
77    Swift,
78    Zig,
79    /// Plain-text tier: documentation, config and templates.
80    ///
81    /// Trigram-indexed only — no tree-sitter grammar, no symbol extraction, no
82    /// import extraction. Added because agents do not partition searches by file
83    /// type: a config key lives in the YAML, the Rust struct AND the spec paragraph,
84    /// and Reflex used to return the struct and a confident 0 for the rest.
85    ///
86    /// Serialises as `"text"` (the enum is `rename_all = "lowercase"`).
87    Text,
88    /// Lock files (`Cargo.lock`, `package-lock.json`, `*.lock`, …).
89    ///
90    /// Indexed since 2.0.0 in `[index] mode = "tracked"`, but excluded from every
91    /// search by default: 100k lines of pinned versions are noise for almost every
92    /// query and the one real question ("which lockfile pins serde 1.0.190?") is
93    /// asked with `include_locks: true` or `lang: "lock"`.
94    Lock,
95    /// Generated files judged by name: `*.pb.go`, `*_generated.*`, `*.generated.*`,
96    /// `*.min.js`, `*.min.css`, `*.map`. Indexed, excluded by default,
97    /// `include_generated: true` or `lang: "generated"` to widen.
98    Generated,
99    /// Never produced by [`Language::from_path`] since 2.0.0 (every path classifies
100    /// as code, `Text`, `Lock` or `Generated`); kept as the miss value of
101    /// [`Language::from_extension`] and as the forward-compatible sentinel for
102    /// readers of the `language` field.
103    Unknown,
104}
105
106/// Whether `file_name` is a dependency lock file.
107///
108/// Judged by full name: `package-lock.json` matches a text extension, and the
109/// name is the only thing that tells it apart from `settings.json`.
110pub fn is_lock_file(file_name: &str) -> bool {
111    if TEXT_FILENAME_EXCLUSIONS
112        .iter()
113        .any(|n| n.eq_ignore_ascii_case(file_name))
114    {
115        return true;
116    }
117    // `*-lock.json` and friends, beyond the names listed above.
118    file_name.ends_with("-lock.json") || file_name.ends_with(".lock")
119}
120
121/// Whether `file_name` looks like a generated file, judged by name only.
122///
123/// Content markers (`@generated` in the file head) are not read: the query engine
124/// derives a file's language from its path, so a content-based verdict at index
125/// time could not be honoured at query time.
126pub fn is_generated_name(file_name: &str) -> bool {
127    let lower = file_name.to_ascii_lowercase();
128    lower.ends_with(".pb.go")
129        || lower.ends_with(".min.js")
130        || lower.ends_with(".min.css")
131        || lower.ends_with(".map")
132        || lower.contains("_generated.")
133        || lower.contains(".generated.")
134}
135
136/// Extensions in the plain-text tier.
137///
138/// A fixed allowlist, not "everything unrecognised": an index that swallowed every
139/// binary blob and generated artefact in a repo would be slower and less useful.
140const TEXT_EXTENSIONS: &[&str] = &[
141    "md", "mdx", "txt", "yaml", "yml", "toml", "json", "proto", "html", "htm", "sh", "bash", "ini",
142    "cfg", "sql", "graphql", "bru",
143];
144
145/// Extensionless files in the plain-text tier, matched by exact name.
146///
147/// Agents grep these as readily as any `.md`; a `Makefile` target or a `Dockerfile`
148/// `COPY` line is a legitimate search hit. `Dockerfile.<variant>` is handled as a
149/// prefix in [`is_text_tier_file`].
150const TEXT_FILENAMES: &[&str] = &["Makefile", "makefile", "Dockerfile", "Justfile", "justfile"];
151
152/// Lock files, by exact name. See [`is_lock_file`] for the suffix rules.
153const TEXT_FILENAME_EXCLUSIONS: &[&str] = &[
154    "package-lock.json",
155    "npm-shrinkwrap.json",
156    "composer.lock",
157    "yarn.lock",
158    "pnpm-lock.yaml",
159    "Cargo.lock",
160    "poetry.lock",
161    "Gemfile.lock",
162    "go.sum",
163    "flake.lock",
164    "uv.lock",
165    "deno.lock",
166    "bun.lock",
167];
168
169/// Whether a file belongs in the ALLOWLIST text tier, judged by its full name.
170///
171/// This is the pre-2.0.0 rule, kept for `[index] mode = "allowlist"`. In the
172/// default `tracked` mode every non-binary, non-ignored file is text unless it is
173/// code, a lock file or a generated file.
174pub fn is_text_tier_file(file_name: &str) -> bool {
175    if is_lock_file(file_name) {
176        return false;
177    }
178    if TEXT_FILENAMES.contains(&file_name) || file_name.starts_with("Dockerfile.") {
179        return true;
180    }
181    match file_name.rsplit_once('.') {
182        Some((_, ext)) => TEXT_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str()),
183        None => false,
184    }
185}
186
187impl Language {
188    /// Classify a file by its path.
189    ///
190    /// This is the one classifier the indexer, watcher and query engine share, so a
191    /// file is either indexed, watched and searchable, or none of the three. Path
192    /// only: whether the file is binary is decided from its bytes by the indexer,
193    /// and a binary file is simply never in the index.
194    ///
195    /// * A lock file name wins (`Cargo.lock`, `package-lock.json`) → `Lock`.
196    /// * A generated name wins next (`x.pb.go`, `app.min.js`) → `Generated`.
197    /// * A recognised code extension → that language (`main.rs`, `app.mjs`).
198    /// * Everything else → `Text`: `README`, `OWNERS`, `foo.po`, `a.css`,
199    ///   `Makefile`, `.githooks/pre-commit`. Whether such a file is INDEXED is the
200    ///   `[index] mode` policy's decision (`PathPolicy::classify`).
201    pub fn from_path(path: &std::path::Path) -> Self {
202        let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
203        if is_lock_file(name) {
204            return Language::Lock;
205        }
206        if is_generated_name(name) {
207            return Language::Generated;
208        }
209        let by_ext = path
210            .extension()
211            .and_then(|e| e.to_str())
212            .map(Self::from_extension)
213            .unwrap_or(Language::Unknown);
214        match by_ext {
215            Language::Text | Language::Unknown => Language::Text,
216            code => code,
217        }
218    }
219
220    pub fn from_extension(ext: &str) -> Self {
221        match ext {
222            "rs" => Language::Rust,
223            "py" => Language::Python,
224            "js" | "mjs" | "cjs" | "jsx" => Language::JavaScript,
225            "ts" | "mts" | "cts" | "tsx" => Language::TypeScript,
226            "vue" => Language::Vue,
227            "svelte" => Language::Svelte,
228            "go" => Language::Go,
229            "java" => Language::Java,
230            "php" => Language::PHP,
231            "c" | "h" => Language::C,
232            "cpp" | "cc" | "cxx" | "hpp" | "hxx" | "C" | "H" => Language::Cpp,
233            "cs" => Language::CSharp,
234            "rb" | "rake" | "gemspec" => Language::Ruby,
235            "kt" | "kts" => Language::Kotlin,
236            "swift" => Language::Swift,
237            "zig" => Language::Zig,
238            // The text tier. Note this maps by EXTENSION only; `is_text_tier_file`
239            // additionally excludes lock files by name, and the indexer uses that.
240            ext if TEXT_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str()) => Language::Text,
241            _ => Language::Unknown,
242        }
243    }
244
245    /// Parse a language from a human-friendly name (CLI/API input)
246    ///
247    /// Accepts lowercase names and common aliases.
248    /// Returns None for unrecognized names.
249    pub fn from_name(name: &str) -> Option<Self> {
250        match name.to_lowercase().as_str() {
251            "rust" | "rs" => Some(Language::Rust),
252            "python" | "py" => Some(Language::Python),
253            "javascript" | "js" => Some(Language::JavaScript),
254            "typescript" | "ts" => Some(Language::TypeScript),
255            "vue" => Some(Language::Vue),
256            "svelte" => Some(Language::Svelte),
257            "go" => Some(Language::Go),
258            "java" => Some(Language::Java),
259            "php" => Some(Language::PHP),
260            "c" => Some(Language::C),
261            "cpp" | "c++" => Some(Language::Cpp),
262            "csharp" | "cs" | "c#" => Some(Language::CSharp),
263            "ruby" | "rb" => Some(Language::Ruby),
264            "kotlin" | "kt" => Some(Language::Kotlin),
265            "zig" => Some(Language::Zig),
266            "text" | "txt" | "plaintext" | "plain" => Some(Language::Text),
267            "lock" | "lockfile" | "lockfiles" => Some(Language::Lock),
268            "generated" | "gen" => Some(Language::Generated),
269            _ => None,
270        }
271    }
272
273    /// Human-readable list of all supported language names (for error messages)
274    pub fn supported_names_help() -> &'static str {
275        "rust (rs), python (py), javascript (js), typescript (ts), vue, svelte, \
276         go, java, php, c, cpp (c++), csharp (cs, c#), ruby (rb), kotlin (kt), zig, \
277         text (every other non-binary file: docs, config, templates, extensionless), \
278         lock (lock files, excluded by default), generated (*.pb.go, *.min.js, *.map, \
279         *_generated.*, excluded by default)"
280    }
281
282    /// Check if this language has a parser implementation
283    ///
284    /// Returns true only for languages with working Tree-sitter parsers.
285    /// This determines which files will be indexed by Reflex.
286    pub fn is_supported(&self) -> bool {
287        match self {
288            Language::Rust => true,
289            Language::TypeScript => true,
290            Language::JavaScript => true,
291            Language::Vue => true,
292            Language::Svelte => true,
293            Language::Python => true,
294            Language::Go => true,
295            Language::Java => true,
296            Language::PHP => true,
297            Language::C => true,
298            Language::Cpp => true,
299            Language::CSharp => true,
300            Language::Ruby => true,
301            Language::Kotlin => true,
302            Language::Swift => false, // Temporarily disabled - parser queries out of date with tree-sitter-swift 0.7.x grammar
303            Language::Zig => true,
304            // No tree-sitter grammar, by design.
305            Language::Text => false,
306            Language::Lock => false,
307            Language::Generated => false,
308            Language::Unknown => false,
309        }
310    }
311
312    /// Whether this is the plain-text tier.
313    pub fn is_text(&self) -> bool {
314        matches!(self, Language::Text)
315    }
316
317    /// Whether files of this language are indexed but left out of every search
318    /// unless asked for (`include_locks` / `include_generated`, or `lang`).
319    pub fn is_excluded_by_default(&self) -> bool {
320        matches!(self, Language::Lock | Language::Generated)
321    }
322
323    /// Whether this is a code language, supported or not (Swift is code without a
324    /// working grammar). Code files are assumed to be text; every other file is
325    /// sniffed for a NUL byte before it is indexed.
326    pub fn is_code(&self) -> bool {
327        !matches!(
328            self,
329            Language::Text | Language::Lock | Language::Generated | Language::Unknown
330        )
331    }
332
333    /// Whether files of this language can be in the index at all.
334    ///
335    /// Distinct from [`Self::is_supported`], which means "has a tree-sitter parser".
336    /// The text tier is indexed but never parsed, so symbol search, AST queries and
337    /// dependency analysis skip it while full-text search covers it. Whether a given
338    /// path IS indexed also depends on `[index] mode` (`PathPolicy::classify`).
339    pub fn is_indexable(&self) -> bool {
340        !matches!(self, Language::Unknown)
341    }
342}
343
344/// Which files the indexer takes, beyond the code languages.
345#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
346#[serde(rename_all = "lowercase")]
347pub enum IndexMode {
348    /// Every file not ignored by `.gitignore` / `.ignore` / `[index] exclude`,
349    /// unless a NUL byte anywhere in it says it is binary. Lock and generated
350    /// files are indexed and excluded from searches by default. This is ripgrep's
351    /// rule, and what an agent that greps expects.
352    #[default]
353    Tracked,
354    /// The pre-2.0.0 rule: code by extension plus the fixed docs/config extension
355    /// list (`is_text_tier_file`). Lock and generated files are not indexed. For
356    /// trees where the long tail of data files is not worth the index size.
357    Allowlist,
358}
359
360impl IndexMode {
361    pub fn from_name(name: &str) -> Option<Self> {
362        match name.trim().to_ascii_lowercase().as_str() {
363            "tracked" => Some(Self::Tracked),
364            "allowlist" => Some(Self::Allowlist),
365            _ => None,
366        }
367    }
368}
369
370/// Type of import/dependency
371#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
372#[serde(rename_all = "lowercase")]
373pub enum ImportType {
374    /// Internal project file
375    Internal,
376    /// External library/package
377    External,
378    /// Standard library
379    Stdlib,
380    /// Rust `mod foo;` declaration (parent→child ownership, not a usage edge)
381    #[serde(rename = "mod_decl")]
382    ModDecl,
383}
384
385/// Dependency information for API output (simplified, path-based)
386#[derive(Debug, Clone, Serialize, Deserialize)]
387pub struct DependencyInfo {
388    /// Import path as written in source (or resolved path for internal deps)
389    pub path: String,
390    /// Line number where import appears (optional)
391    #[serde(skip_serializing_if = "Option::is_none")]
392    pub line: Option<usize>,
393    /// Imported symbols (for selective imports like `from x import a, b`)
394    #[serde(skip_serializing_if = "Option::is_none")]
395    pub symbols: Option<Vec<String>>,
396    /// Every file a package import resolved to (a Go package, a C# namespace, a
397    /// JVM wildcard), in walk order; `path` is then the import as written.
398    #[serde(skip_serializing_if = "Option::is_none")]
399    pub resolved_paths: Option<Vec<String>>,
400}
401
402/// Full dependency record (internal representation with file IDs)
403#[derive(Debug, Clone)]
404pub struct Dependency {
405    /// Source file ID
406    pub file_id: i64,
407    /// Import path as written in source code
408    pub imported_path: String,
409    /// Resolved file ID (None if external or stdlib)
410    pub resolved_file_id: Option<i64>,
411    /// Package key the import resolved to (`go:<dir>`, `jvm:<package>`,
412    /// `cs:<namespace>`), when it names a package rather than one file. The graph
413    /// expands it to the files that declare membership (`package_members`).
414    pub resolved_package: Option<String>,
415    /// The member of `resolved_package` the import names (a JVM class); `None`
416    /// means the whole package.
417    pub resolved_member: Option<String>,
418    /// Import type classification
419    pub import_type: ImportType,
420    /// Line number where import appears
421    pub line_number: usize,
422    /// Imported symbols (for selective imports)
423    pub imported_symbols: Option<Vec<String>>,
424}
425
426/// A lightweight, stable reference to a code symbol for API responses
427///
428/// Prefer this over `(String, SymbolKind, Span)` tuples — tuples serialize as
429/// positional JSON arrays, making any field addition a breaking change.
430/// Named fields here are additive-safe: new optional fields can be added without
431/// shifting positions or bumping the version.
432#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
433pub struct SymbolRef {
434    /// Symbol name (e.g., function name, class name)
435    pub name: String,
436    /// Symbol kind (function, class, struct, etc.)
437    pub kind: SymbolKind,
438    /// Location span in source file
439    pub span: Span,
440}
441
442/// Helper function to skip serializing "Unknown" symbol kinds
443fn is_unknown_kind(kind: &SymbolKind) -> bool {
444    matches!(kind, SymbolKind::Unknown(_))
445}
446
447/// A search result representing a symbol or code location
448#[derive(Debug, Clone, Serialize, Deserialize)]
449pub struct SearchResult {
450    /// Absolute or relative path to the file
451    pub path: String,
452    /// Detected programming language (internal use only, not serialized to save tokens)
453    #[serde(skip)]
454    pub lang: Language,
455    /// Type of symbol found (only included for symbol searches, not text matches)
456    #[serde(skip_serializing_if = "is_unknown_kind")]
457    pub kind: SymbolKind,
458    /// Symbol name (e.g., function name, class name)
459    /// None for text/regex matches where symbol name cannot be accurately determined
460    #[serde(skip_serializing_if = "Option::is_none")]
461    pub symbol: Option<String>,
462    /// Location span in the source file
463    pub span: Span,
464    /// Code preview (few lines around the match)
465    pub preview: String,
466    /// File dependencies (only populated when --dependencies flag is used)
467    /// DEPRECATED: Use FileGroupedResult.dependencies instead for file-level grouping
468    #[serde(skip_serializing_if = "Option::is_none")]
469    pub dependencies: Option<Vec<DependencyInfo>>,
470}
471
472/// An individual match within a file (no path or dependencies)
473#[derive(Debug, Clone, Serialize, Deserialize)]
474pub struct MatchResult {
475    /// Type of symbol found (only included for symbol searches, not text matches)
476    #[serde(skip_serializing_if = "is_unknown_kind")]
477    pub kind: SymbolKind,
478    /// Symbol name (e.g., function name, class name)
479    #[serde(skip_serializing_if = "Option::is_none")]
480    pub symbol: Option<String>,
481    /// Location span in the source file
482    pub span: Span,
483    /// Code preview (few lines around the match)
484    pub preview: String,
485    /// Lines of code before the match (for context)
486    #[serde(skip_serializing_if = "Vec::is_empty")]
487    pub context_before: Vec<String>,
488    /// Lines of code after the match (for context)
489    #[serde(skip_serializing_if = "Vec::is_empty")]
490    pub context_after: Vec<String>,
491}
492
493/// File-level grouped results with dependencies at file level
494#[derive(Debug, Clone, Serialize, Deserialize)]
495pub struct FileGroupedResult {
496    /// Absolute or relative path to the file
497    pub path: String,
498    /// Detected programming language of this file (e.g. "rust", "python", "unknown")
499    pub language: Language,
500    /// File dependencies (only populated when --dependencies flag is used)
501    #[serde(skip_serializing_if = "Option::is_none")]
502    pub dependencies: Option<Vec<DependencyInfo>>,
503    /// Individual matches within this file
504    pub matches: Vec<MatchResult>,
505}
506
507impl SearchResult {
508    pub fn new(
509        path: String,
510        lang: Language,
511        kind: SymbolKind,
512        symbol: Option<String>,
513        span: Span,
514        scope: Option<String>,
515        preview: String,
516    ) -> Self {
517        // Ignore scope parameter for backwards compatibility
518        let _ = scope;
519        Self {
520            path,
521            lang,
522            kind,
523            symbol,
524            span,
525            preview,
526            dependencies: None,
527        }
528    }
529}
530
531/// Configuration for indexing behavior
532/// [`IndexConfig::lock_wait_secs`]: wait for `index.lock` until it is free. The
533/// lock is advisory and released when its holder exits, so a crash cannot leave
534/// a waiter blocked.
535pub const LOCK_WAIT_FOREVER: u64 = u64::MAX;
536
537#[derive(Debug, Clone, Serialize, Deserialize)]
538pub struct IndexConfig {
539    /// Languages to include (empty = all supported)
540    pub languages: Vec<Language>,
541    /// Glob patterns to include
542    pub include_patterns: Vec<String>,
543    /// Glob patterns to exclude
544    pub exclude_patterns: Vec<String>,
545    /// Follow symbolic links
546    pub follow_symlinks: bool,
547    /// Maximum file size to index (bytes)
548    pub max_file_size: usize,
549    /// Number of threads for parallel indexing (0 = auto, 80% of available cores)
550    pub parallel_threads: usize,
551    /// Threads for the background symbol pass (`rfx index-symbols-internal`).
552    /// `0` = auto: half the cores, at most 32. See [`resolve_symbol_thread_count`].
553    #[serde(default)]
554    pub symbol_threads: usize,
555    /// Query timeout in seconds (0 = no timeout)
556    pub query_timeout_secs: u64,
557    /// Maximum entries per trigram posting list (0 = unlimited).
558    /// High-frequency trigrams are truncated at this threshold to bound query latency.
559    pub max_posting_list_entries: usize,
560    /// How long `Indexer::index` waits for `.reflex/index.lock` when another
561    /// indexer holds it (seconds). 0 = fail immediately with `IndexLocked`;
562    /// [`LOCK_WAIT_FOREVER`] = wait until it is free. The `rfx index` CLI waits
563    /// 30 s; automatic updates wait forever (a query never answers from a stale
564    /// index because another run was busy).
565    #[serde(default, skip_serializing_if = "is_zero_u64")]
566    pub lock_wait_secs: u64,
567    /// Index documentation, config and template files alongside code.
568    ///
569    /// On by default. Covers md, mdx, txt, yaml, yml, toml, json, proto, html, htm,
570    /// sh, bash, ini, cfg, sql and graphql, trigram-indexed only — no symbols, no
571    /// AST, no dependency analysis. Lock files are always excluded.
572    ///
573    /// Set `[index] text_tier = false` for a repo with large generated JSON or
574    /// vendored documentation where the index growth is not worth it.
575    ///
576    /// `#[serde(default = ...)]` so a config file written before 1.7.2 still parses
577    /// and gets the new default.
578    #[serde(default = "default_true")]
579    pub text_tier: bool,
580    /// Which non-code files the text tier takes: every non-binary, non-hidden, non-ignored file
581    /// (`tracked`, the default since 2.0.0) or the fixed extension list
582    /// (`allowlist`, the pre-2.0.0 rule).
583    #[serde(default)]
584    pub mode: IndexMode,
585    /// Walk dot-directories and dotfiles too (`.githooks/pre-commit`, `.env.example`).
586    /// Off by default, like ripgrep without `--hidden`. `.git/` and `.reflex/` are
587    /// never walked.
588    #[serde(default)]
589    pub hidden: bool,
590    /// `[index.vendored] patterns`: gitignore rules that mark directories vendored
591    /// (`!pattern` marks one project code), checked before the built-in rules.
592    /// Vendored files are searchable but not in the import graph (`crate::vendor`).
593    #[serde(default)]
594    pub vendored_patterns: Vec<String>,
595}
596
597/// Serde default for boolean options that are on unless explicitly disabled.
598fn default_true() -> bool {
599    true
600}
601
602impl Default for IndexConfig {
603    fn default() -> Self {
604        Self {
605            languages: vec![],
606            include_patterns: vec![],
607            exclude_patterns: vec![],
608            follow_symlinks: false,
609            max_file_size: 10 * 1024 * 1024,   // 10 MB
610            parallel_threads: 0,               // 0 = auto (80% of available cores)
611            symbol_threads: 0,                 // 0 = auto (50% of available cores)
612            query_timeout_secs: 30,            // 30 seconds default timeout
613            max_posting_list_entries: 500_000, // cap at 500k to bound query latency
614            text_tier: true,                   // docs and config are searchable by default
615            mode: IndexMode::Tracked, // ripgrep defaults: not ignored, not hidden, not binary
616            hidden: false,            // dot-directories skipped, like ripgrep
617            lock_wait_secs: 0,        // fail fast when another indexer runs
618            vendored_patterns: vec![],
619        }
620    }
621}
622
623fn is_zero(v: &usize) -> bool {
624    *v == 0
625}
626fn is_zero_u64(v: &u64) -> bool {
627    *v == 0
628}
629
630/// Resolve `[performance] symbol_threads` (the background symbol pass) to a
631/// concrete thread count.
632///
633/// `REFLEX_SYMBOL_THREADS` overrides for benchmarking, then `configured` if
634/// non-zero, else half the cores (1..=32). The pass is detached from `rfx index`
635/// and runs while the user may be querying, so it takes half the machine rather
636/// than the indexer's 80%; before 2.0.0 it took 27.5%.
637pub fn resolve_symbol_thread_count(configured: usize) -> usize {
638    if let Some(n) = std::env::var("REFLEX_SYMBOL_THREADS")
639        .ok()
640        .and_then(|v| v.parse::<usize>().ok())
641        .filter(|&n| n > 0)
642    {
643        return n;
644    }
645    if configured != 0 {
646        return configured.max(1);
647    }
648    let available = std::thread::available_parallelism()
649        .map(|n| n.get())
650        .unwrap_or(4);
651    ((available as f64 * 0.5).ceil() as usize).clamp(1, 32)
652}
653
654/// Resolve `[performance] parallel_threads` to a concrete thread count.
655///
656/// `0` means automatic: 80% of the available cores, at least 1, at most
657/// `auto_cap`. A non-zero value is used as given. The indexer passes a cap of 8
658/// (write-side cache contention); query-time verification passes a higher cap.
659pub fn resolve_thread_count(configured: usize, auto_cap: usize) -> usize {
660    if configured != 0 {
661        return configured.max(1);
662    }
663    let available = std::thread::available_parallelism()
664        .map(|n| n.get())
665        .unwrap_or(4);
666    ((available as f64 * 0.8).ceil() as usize).clamp(1, auto_cap.max(1))
667}
668
669/// How a query found its candidate lines.
670///
671/// `trigram` is the normal case: the pattern's literals were looked up in the
672/// inverted index and only the lines they name were verified. `scan` means every
673/// line of every file was verified, which happens for a pattern shorter than
674/// 3 chars, a regex with no literal of 3+ chars (`\w+_id`), a non-ASCII literal
675/// under `(?i)`, or a keyword symbol query. Before 2.0.0 every `(?i)` regex
676/// scanned; since 2.0.0 its literals are looked up under all case variants.
677#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
678#[serde(rename_all = "lowercase")]
679pub enum IndexPath {
680    /// Candidates came from the trigram index.
681    #[default]
682    Trigram,
683    /// Every line was verified.
684    Scan,
685}
686
687/// Per-phase wall-clock timings for one query, in microseconds.
688///
689/// Present in a [`QueryResponse`] only when the caller asked for it
690/// (`rfx query --timing`, or `REFLEX_MCP_TIMING=1` for the MCP server).
691#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
692pub struct QueryTimings {
693    /// Whether the trigram index or a full scan produced the candidates.
694    #[serde(default)]
695    pub index_path: IndexPath,
696    /// Opening (or reusing) the index handle.
697    pub open_us: u64,
698    /// Trigram lookup and posting-list intersection.
699    pub candidates_us: u64,
700    /// Verifying candidate lines against the pattern (and any enrichment).
701    pub verify_us: u64,
702    /// Time the query waited for the freshness check after the search finished.
703    /// The check runs on its own thread alongside the search, so this is usually
704    /// near zero; `status_compute_us` is what the check itself cost.
705    pub status_us: u64,
706    /// The freshness check's own duration (git spawns, or a tree walk outside git).
707    #[serde(default)]
708    pub status_compute_us: u64,
709    /// Grouping by file, context lines, dependencies.
710    pub group_us: u64,
711    /// Whole query as seen by the engine.
712    pub total_us: u64,
713    /// Automatic updates of a stale index before the answer (0: none ran).
714    /// `total_us` includes them.
715    #[serde(default, skip_serializing_if = "is_zero_u64")]
716    pub update_us: u64,
717}
718
719/// Statistics about the index
720#[derive(Debug, Clone, Serialize, Deserialize, Default)]
721pub struct IndexStats {
722    /// Total files indexed
723    pub total_files: usize,
724    /// Index size on disk (bytes)
725    pub index_size_bytes: u64,
726    /// Last update timestamp
727    pub last_updated: String,
728    /// File count breakdown by language
729    pub files_by_language: std::collections::HashMap<String, usize>,
730    /// Line count breakdown by language
731    pub lines_by_language: std::collections::HashMap<String, usize>,
732    /// New files added since last index run (0 if not an incremental run)
733    #[serde(default, skip_serializing_if = "is_zero")]
734    pub new_files: usize,
735    /// Modified files re-indexed since last run (0 if not an incremental run)
736    #[serde(default, skip_serializing_if = "is_zero")]
737    pub modified_files: usize,
738    /// Unchanged files (same hash as last run, still re-indexed due to other changes)
739    #[serde(default, skip_serializing_if = "is_zero")]
740    pub unchanged_files: usize,
741    /// Files dropped from the index because they no longer exist on disk
742    #[serde(default, skip_serializing_if = "is_zero")]
743    pub deleted_files: usize,
744    /// Files skipped because they exceeded max_file_size
745    #[serde(default, skip_serializing_if = "is_zero")]
746    pub skipped_too_large: usize,
747    /// Total bytes of files skipped due to max_file_size
748    #[serde(default, skip_serializing_if = "is_zero_u64")]
749    pub skipped_bytes_too_large: u64,
750    /// Files skipped because a NUL byte says they are binary (ripgrep's rule)
751    #[serde(default, skip_serializing_if = "is_zero")]
752    pub skipped_binary: usize,
753    /// Raw bytes of indexed source held in content.bin (0 if unknown)
754    #[serde(default, skip_serializing_if = "is_zero_u64")]
755    pub corpus_bytes: u64,
756    /// Size of trigrams.bin on disk (0 if absent)
757    #[serde(default, skip_serializing_if = "is_zero_u64")]
758    pub trigram_index_bytes: u64,
759}
760
761/// Information about an indexed file
762#[derive(Debug, Clone, Serialize, Deserialize)]
763pub struct IndexedFile {
764    /// File path
765    pub path: String,
766    /// Detected language
767    pub language: String,
768    /// Last indexed timestamp
769    pub last_indexed: String,
770}
771
772/// Index status for query responses
773#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
774#[serde(rename_all = "snake_case")]
775pub enum IndexStatus {
776    /// Index is fresh and up-to-date
777    Fresh,
778    /// Index is stale (any issue: branch not indexed, commit changed, files modified)
779    Stale,
780}
781
782/// Warning details when index is stale
783#[derive(Debug, Clone, Serialize, Deserialize)]
784pub struct IndexWarning {
785    /// Human-readable reason why index is stale
786    pub reason: String,
787    /// Command to run to fix the issue
788    pub action_required: String,
789    /// Tracked files edited since the index was built.
790    ///
791    /// BREAKING in 1.7.2: this was a `u32` count. It is now the paths themselves,
792    /// because a count told an agent something was wrong without telling it what, so
793    /// the only safe reaction was to distrust the whole result. The list is capped;
794    /// `truncated` says when.
795    #[serde(skip_serializing_if = "Option::is_none")]
796    pub files_modified: Option<Vec<String>>,
797    /// Files present on disk but absent from the index (new or untracked).
798    #[serde(skip_serializing_if = "Option::is_none")]
799    pub files_added: Option<Vec<String>>,
800    /// Files in the index but no longer on disk. These produce ghost hits.
801    #[serde(skip_serializing_if = "Option::is_none")]
802    pub files_deleted: Option<Vec<String>>,
803    /// Total changed paths, which may exceed the lengths of the lists above.
804    #[serde(skip_serializing_if = "Option::is_none")]
805    pub changed_count: Option<usize>,
806    /// Whether the lists were cut short. Set on a fresh checkout or a huge rebase.
807    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
808    pub truncated: bool,
809    /// Additional context (git branch info, etc.)
810    #[serde(skip_serializing_if = "Option::is_none")]
811    pub details: Option<IndexWarningDetails>,
812}
813
814impl IndexWarning {
815    /// A warning with only a reason and an action, no file lists.
816    pub fn new(reason: impl Into<String>, action_required: impl Into<String>) -> Self {
817        Self {
818            reason: reason.into(),
819            action_required: action_required.into(),
820            files_modified: None,
821            files_added: None,
822            files_deleted: None,
823            changed_count: None,
824            truncated: false,
825            details: None,
826        }
827    }
828
829    /// Attach git branch/commit context.
830    pub fn with_details(mut self, details: IndexWarningDetails) -> Self {
831        self.details = Some(details);
832        self
833    }
834}
835
836/// Detailed information about index staleness
837#[derive(Debug, Clone, Serialize, Deserialize)]
838pub struct IndexWarningDetails {
839    /// Current branch (if in git repo)
840    #[serde(skip_serializing_if = "Option::is_none")]
841    pub current_branch: Option<String>,
842    /// Indexed branch (if in git repo)
843    #[serde(skip_serializing_if = "Option::is_none")]
844    pub indexed_branch: Option<String>,
845    /// Current commit SHA (if in git repo)
846    #[serde(skip_serializing_if = "Option::is_none")]
847    pub current_commit: Option<String>,
848    /// Indexed commit SHA (if in git repo)
849    #[serde(skip_serializing_if = "Option::is_none")]
850    pub indexed_commit: Option<String>,
851    /// When the index was last written (Unix seconds).
852    #[serde(default, skip_serializing_if = "Option::is_none")]
853    pub indexed_at: Option<i64>,
854    /// How the working tree was compared to the index: `"git"` (candidates from
855    /// `git status`, confirmed by fingerprint) or `"walk"` (every file stat'ed).
856    #[serde(default, skip_serializing_if = "Option::is_none")]
857    pub checked_by: Option<String>,
858}
859
860/// The full answer to `check_index_status`.
861///
862/// `details` is present even when the index is fresh, so a human can see that the
863/// indexed commit differs from HEAD without that difference being called staleness:
864/// since 2.0.0 freshness is judged by file content, not by commit.
865#[derive(Debug, Clone)]
866pub struct IndexStatusReport {
867    pub status: IndexStatus,
868    pub can_trust_results: bool,
869    pub warning: Option<IndexWarning>,
870    pub details: Option<IndexWarningDetails>,
871}
872
873/// Pagination information for query results
874#[derive(Debug, Clone, Serialize, Deserialize)]
875pub struct PaginationInfo {
876    /// Total number of results before offset/limit — **`null` whenever
877    /// `total_is_exact` is false**. A list-mode search with a `limit` stops
878    /// verifying once the page is full, and the number verified by then is not a
879    /// total; reporting it as one made agents stop paginating early (2.0.0 field
880    /// test: `total: 851` for a term with 18,752 matches). Use `approx_total` for an
881    /// estimate, or a count-mode / no-limit search for the exact number.
882    #[serde(default)]
883    pub total: Option<usize>,
884    /// Number of results in this response (after offset/limit)
885    pub count: usize,
886    /// Offset used (starting position)
887    pub offset: usize,
888    /// Limit used (max results per page)
889    #[serde(skip_serializing_if = "Option::is_none")]
890    pub limit: Option<usize>,
891    /// Whether there are more results after this page
892    pub has_more: bool,
893    /// `true` when `total` counts every match. `false` when a list-mode search
894    /// stopped verifying once the page was full: `total` is then `null` and
895    /// `approx_total` carries an estimate. Count mode, no-limit searches,
896    /// symbol/AST searches and `require_exact_total` callers are always exact.
897    #[serde(default = "default_true")]
898    pub total_is_exact: bool,
899    /// Estimated total when `total_is_exact` is false. After the page filled, a
900    /// spread sample of the remaining candidate lines was verified and the
901    /// measured hit rate scaled over the rest (see
902    /// `query::ESTIMATE_SAMPLE_FILES`). Typically within ±30% on the synthetic
903    /// corpus; wider when hits cluster in a few files. Absent when no estimate was
904    /// possible (a regex with no literal, where every line is a candidate).
905    #[serde(default, skip_serializing_if = "Option::is_none")]
906    pub approx_total: Option<usize>,
907}
908
909impl PaginationInfo {
910    /// The total, only when it is a real one.
911    pub fn exact_total(&self) -> Option<usize> {
912        if self.total_is_exact {
913            self.total
914        } else {
915            None
916        }
917    }
918
919    /// The best number available for a threshold or a log line: the exact total,
920    /// else the estimate, else the end of this page. Never show it as a total.
921    pub fn best_total(&self) -> usize {
922        self.exact_total()
923            .or(self.approx_total)
924            .unwrap_or(self.offset + self.count)
925    }
926}
927
928/// Query response with results and index status
929#[derive(Debug, Clone, Serialize, Deserialize)]
930pub struct QueryResponse {
931    /// AI-optimized instruction for how to handle these results
932    /// Only present when --ai flag is used or in MCP mode
933    /// Provides guidance to AI agents on response format and next actions
934    #[serde(skip_serializing_if = "Option::is_none")]
935    pub ai_instruction: Option<String>,
936    /// Status of the index (fresh or stale)
937    pub status: IndexStatus,
938    /// Whether the results can be trusted
939    pub can_trust_results: bool,
940    /// Warning information (only present if stale)
941    #[serde(skip_serializing_if = "Option::is_none")]
942    pub warning: Option<IndexWarning>,
943    /// Pagination information
944    pub pagination: PaginationInfo,
945    /// File-grouped search results
946    /// Results are always grouped by file path, with dependencies populated when --dependencies flag is used
947    pub results: Vec<FileGroupedResult>,
948    /// For a whole-identifier search that found nothing: how many candidate lines
949    /// contain the pattern as a substring. Lets the caller explain a zero without
950    /// running a second search. Absent whenever there were results, or when the
951    /// search was not a whole-identifier one.
952    #[serde(default, skip_serializing_if = "Option::is_none")]
953    pub substring_hint_count: Option<usize>,
954    /// Things the engine did to the query that the caller should know about.
955    ///
956    /// Today this is one message at most: a whole-identifier pattern containing
957    /// brackets was escaped and run as a regex (see
958    /// `query::prepare_literal_pattern`). Every surface — CLI, MCP, HTTP — carries it,
959    /// so a rewrite is never silent on any of them.
960    #[serde(default, skip_serializing_if = "Vec::is_empty")]
961    pub warnings: Vec<String>,
962    /// For a whole-identifier search that found nothing while substring matches
963    /// exist: a ready-to-show sentence naming the count and the switch that shows
964    /// them. Absent whenever there were results, or when the search was not a
965    /// whole-identifier one.
966    #[serde(default, skip_serializing_if = "Option::is_none")]
967    pub hint: Option<String>,
968    /// Machine-readable cause behind `hint`: `hidden` (the filter names a
969    /// dot-directory), `not_indexed` (the `file` filter names a path the index does
970    /// not hold), `lock_or_generated`, `whole_identifier`. Absent when no rule
971    /// applies, so a harness can branch without parsing prose.
972    #[serde(default, skip_serializing_if = "Option::is_none")]
973    pub excluded_reason: Option<crate::query::ExcludedReason>,
974    /// For a search that found nothing: how many candidate files were lock or
975    /// generated files, which every search leaves out unless `include_locks` /
976    /// `include_generated` (or `lang`) asks for them. The `hint` says so too.
977    #[serde(default, skip_serializing_if = "Option::is_none")]
978    pub excluded_by_default: Option<usize>,
979    /// Count-only searches: the number of files with at least one match. `results`
980    /// is empty in that mode, so this is the only place the file count lives.
981    #[serde(default, skip_serializing_if = "Option::is_none")]
982    pub file_count: Option<usize>,
983    /// Per-phase timings, only when requested.
984    #[serde(default, skip_serializing_if = "Option::is_none")]
985    pub timings: Option<QueryTimings>,
986}
987
988/// Report from cache compaction operation
989#[derive(Debug, Clone, Serialize, Deserialize)]
990pub struct CompactionReport {
991    /// Always 0 since auto-update: index runs remove deleted files (kept for JSON compatibility)
992    pub files_removed: usize,
993    /// Space saved in bytes
994    pub space_saved_bytes: u64,
995    /// Duration in milliseconds
996    pub duration_ms: u64,
997}
998
999#[cfg(test)]
1000mod tests {
1001    use super::*;
1002
1003    #[test]
1004    fn test_symbol_ref_json_shape() {
1005        let sym = SymbolRef {
1006            name: "my_function".to_string(),
1007            kind: SymbolKind::Function,
1008            span: Span {
1009                start_line: 10,
1010                end_line: 20,
1011            },
1012        };
1013        let json = serde_json::to_value(&sym).unwrap();
1014        assert_eq!(json["name"], "my_function");
1015        assert_eq!(json["kind"], "Function");
1016        assert_eq!(json["span"]["start_line"], 10);
1017        assert_eq!(json["span"]["end_line"], 20);
1018        assert!(json.as_array().is_none());
1019    }
1020
1021    #[test]
1022    fn test_symbol_ref_roundtrip() {
1023        let original = SymbolRef {
1024            name: "MyStruct".to_string(),
1025            kind: SymbolKind::Struct,
1026            span: Span {
1027                start_line: 1,
1028                end_line: 5,
1029            },
1030        };
1031        let json = serde_json::to_string(&original).unwrap();
1032        let decoded: SymbolRef = serde_json::from_str(&json).unwrap();
1033        assert_eq!(original, decoded);
1034    }
1035
1036    #[test]
1037    fn test_symbol_ref_exact_json() {
1038        let sym = SymbolRef {
1039            name: "Foo".to_string(),
1040            kind: SymbolKind::Class,
1041            span: Span {
1042                start_line: 3,
1043                end_line: 7,
1044            },
1045        };
1046        let json = serde_json::to_string(&sym).unwrap();
1047        assert_eq!(
1048            json,
1049            r#"{"name":"Foo","kind":"Class","span":{"start_line":3,"end_line":7}}"#
1050        );
1051    }
1052}