Skip to main content

reference_query/cli/
mod.rs

1//! Command-line surface. Search is the default action: `rq <query>`.
2
3use std::collections::HashSet;
4use std::io::{IsTerminal, Write};
5use std::path::PathBuf;
6use std::process::ExitCode;
7use std::time::Duration;
8
9use clap::{CommandFactory, Parser};
10use clap_complete::Shell;
11
12use crate::store::Store;
13
14/// Search is the default action (`rq <query>`). Operations are flags rather
15/// than subcommands so no word is reserved — `rq index`, `rq status`, and
16/// `rq record` all search for those symbols. This also matches the rg/fd feel.
17#[derive(Parser)]
18#[command(
19    name = "rq",
20    version,
21    about = "Ranked definition lookup — the one place a symbol is defined, first.",
22    long_about = "rq finds where a symbol is defined and ranks the one you most \
23likely meant to the top — not every match.\n\n\
24Search is the default action; operations are flags, not subcommands, so every \
25word (including \"index\", \"status\", \"record\") stays searchable. Ranking favors \
26your current repo and recently-active files, and learns from the results you open \
27(see RECORDING below). Run `rq <query> --explain` to see the score behind each result.",
28    after_help = "EXAMPLES:\n  \
29rq thing                  search for a definition named or like \"thing\"\n  \
30rq wibble --explain       same, plus the score behind each result\n  \
31rq thing --json           machine-readable results (for editors/agents)\n  \
32rq thing --no-record      search without recording it (speculative/agent queries)\n  \
33rq thing --no-wait        answer now from the committed index; don't block on a rebuild\n  \
34rq thing --wait 2s        ...or wait up to a bounded time for the index to warm\n  \
35rq thing app/web          restrict to a directory (rg-style)\n  \
36rq perform -k method      restrict to a symbol kind (c/mod/m/f/s/e/t)\n  \
37rq class Widget           a leading kind keyword is shorthand for -k\n  \
38rq --symbols FILE         outline a file's definitions, in line order\n  \
39rq thing -x rust          restrict to a language (ruby/rust/go/python/ts/js)\n  \
40rq 'Foo::Bar'             qualify by scope — the surest way past an ambiguous name\n  \
41rq 'Foo#bar'              ...and by owner, for a method\n  \
42rq 'refund*proc'          wildcards: * (any run), ? (one char) — quote them\n  \
43rq -o thing               open the best match in your editor (and record it)\n  \
44rq --index                index the current repository\n  \
45rq --status               show indexing coverage\n  \
46rq --usage                show how rq has been called (by caller and flags)\n  \
47rq --drop                 remove this repo's index (opposite of --index)\n\n\
48SHORT FLAGS (easy to misread):\n  \
49-j = --json (not jobs; --jobs is long-only)   -l = --limit (not lang)   -x = --lang\n\n\
50RECORDING (editor/shell hook):\n  \
51rq --record --file <path> --line <n> <query>\n  \
52Tells rq which result you opened for a query, so ranking learns. Pass --no-record \
53to a search to skip this. Editors and the script/rq-open wrapper call --record for you.\n\n\
54The index is a SQLite file at $RQ_DB (default ~/.local/share/rq/rq.db); it warms \
55automatically on the first search in a git repo. On a large, cold repo a search \
56keeps indexing until it can answer rather than reporting a premature \"no \
57matches\" (an interactive run shows progress and stops on Ctrl-C). Exit codes: 0 \
58= matched, 1 = no match, 2 = no match yet (index still warming — try again)."
59)]
60struct Cli {
61    /// Search query. With --drop, the repo path/identity to drop; with --record,
62    /// the query the selection was made for.
63    //
64    // `Other` keeps shells from offering filenames here: a search query isn't a
65    // path. The path-valued operations (--index, --symbols) carry their own
66    // value with a path hint instead, so completion is scoped to them.
67    #[arg(value_name = "TARGET", value_hint = clap::ValueHint::Other)]
68    target: Option<String>,
69
70    /// Directories to restrict results to (rg-style; same as repeated --path).
71    #[arg(value_name = "PATH")]
72    dirs: Vec<String>,
73
74    /// Show the score breakdown for each result.
75    #[arg(short = 'e', long)]
76    explain: bool,
77
78    /// Don't let this invocation teach ranking or count as usage — suppresses
79    /// recording the result you open, select, or `--show`, and keeps the call
80    /// out of `--usage`. For benchmark and CI loops, whose repeated queries
81    /// would otherwise dominate both.
82    #[arg(long)]
83    no_record: bool,
84
85    /// Answer immediately from the committed index — never block waiting on a
86    /// background (re)index. For agents/scripts: a query issued mid-rebuild
87    /// returns at once (a miss reports `warming`, exit 2, so a caller can retry)
88    /// instead of blocking up to the wait budget. Shorthand for `--wait 0`;
89    /// leftover warming still detaches to a background child.
90    #[arg(long = "no-wait")]
91    no_wait: bool,
92
93    /// How long a query may wait for the index to warm before answering with
94    /// whatever's committed: a duration like `50ms`, `2s`, `1m`, or a bare number
95    /// of seconds. `0` doesn't wait at all (same as `--no-wait`). Overrides
96    /// `RQ_WAIT_BUDGET_MS` for this call (default 1 minute).
97    #[arg(long, value_name = "DUR", value_parser = parse_wait, conflicts_with = "no_wait")]
98    wait: Option<Duration>,
99
100    /// Open the best match in your editor and record the pick, so ranking learns.
101    /// On a terminal with several matches, prompts to choose. Launcher: `RQ_OPEN`
102    /// (a template with `{file}`/`{line}`/`{}` = path:line), else VS Code
103    /// (`code`), else `$VISUAL`/`$EDITOR`, else prints the resolved path:line.
104    #[arg(short = 'o', long, conflicts_with_all = ["index", "status", "record", "json", "ndjson"])]
105    open: bool,
106
107    /// Print the definition's source, not just its location — but only when the
108    /// top match is confident; otherwise falls back to the ranked list. Pipe to a
109    /// pager (`rq --show foo | less`). JSON adds a `body` field.
110    #[arg(long, conflicts_with_all = ["open", "index", "status", "record", "symbols", "drop"])]
111    show: bool,
112
113    /// Emit results as a JSON array (for editors and scripts).
114    #[arg(short = 'j', long)]
115    json: bool,
116
117    /// Emit results as newline-delimited JSON, one object per line.
118    #[arg(short = 'J', long, conflicts_with = "json")]
119    ndjson: bool,
120
121    /// Restrict results to files under this repo-relative directory (repeatable).
122    #[arg(short = 'p', long, value_name = "DIR")]
123    path: Vec<String>,
124
125    /// Maximum number of results to show; `0` shows every match.
126    #[arg(short = 'l', long, value_name = "N", default_value_t = DEFAULT_LIMIT)]
127    limit: usize,
128
129    /// Restrict to symbol kinds: class, module, method, function, struct, enum,
130    /// trait (shortcuts: c, mod, m, f, s, e, t; `interface` = trait, `type` =
131    /// struct). Repeatable or comma-separated.
132    #[arg(short = 'k', long, value_name = "KIND", value_delimiter = ',')]
133    kind: Vec<String>,
134
135    /// Restrict to languages: ruby, rust, go, python, typescript, javascript.
136    /// Prefix-matched, so `r` means ruby+rust and `p` means python; aliases rb,
137    /// rs, golang, ts, tsx, js, jsx. Repeatable or comma-separated.
138    #[arg(short = 'x', long = "lang", value_name = "LANG", value_delimiter = ',')]
139    lang: Vec<String>,
140
141    /// Search every indexed repository, not just the current one. By default a
142    /// search inside a repo returns only that repo's definitions.
143    #[arg(short = 'a', long = "all-repos")]
144    all_repos: bool,
145
146    /// Index a repository (PATH, or the current directory).
147    #[arg(long, value_name = "PATH", num_args = 0..=1, value_hint = clap::ValueHint::AnyPath, conflicts_with_all = ["status", "record"])]
148    index: Option<Option<String>>,
149
150    /// Show indexing coverage per known repository.
151    #[arg(long, conflicts_with_all = ["index", "record"])]
152    status: bool,
153
154    /// Show how rq has been used: searches per day, by caller and flags.
155    #[arg(long, conflicts_with_all = ["index", "record", "status"])]
156    usage: bool,
157
158    /// List the symbols defined in FILE, in line order — a structural outline,
159    /// not a ranked search. Honors -k/-x to filter by kind/language.
160    #[arg(long, value_name = "FILE", value_hint = clap::ValueHint::FilePath, conflicts_with_all = ["index", "status", "record", "drop", "open"])]
161    symbols: Option<String>,
162
163    /// Drop a repository's index — the opposite of --index. Removes its symbols,
164    /// files, coverage, and learned ranking. TARGET is the repo's path (or the
165    /// current repo); a known identity string (as shown by --status) also works.
166    #[arg(long, conflicts_with_all = ["index", "status", "record", "open"])]
167    drop: bool,
168
169    /// Record an interaction (editor/shell hook): the result opened for a query.
170    /// Requires --file.
171    #[arg(long, requires = "file", conflicts_with_all = ["index", "status"])]
172    record: bool,
173
174    /// (--record) File that was opened/selected.
175    #[arg(long)]
176    file: Option<String>,
177
178    /// (--record) Line landed on (attributes the selection to a definition).
179    #[arg(long)]
180    line: Option<i64>,
181
182    /// (--record) Event kind (select or open).
183    #[arg(long, default_value = "select")]
184    event: String,
185
186    /// Finish warming a repository's index in the background — the target a
187    /// search re-execs after printing results, detached, so the shell never
188    /// waits on it. Single-flighted per repo; safe to run by hand.
189    #[arg(long, hide = true, value_name = "PATH", num_args = 0..=1, value_hint = clap::ValueHint::AnyPath, conflicts_with_all = ["index", "status", "record", "drop", "symbols", "open", "show"])]
190    warm: Option<Option<String>>,
191
192    /// Print a shell completion script (bash, zsh, fish, elvish, powershell).
193    #[arg(long, value_name = "SHELL")]
194    completions: Option<Shell>,
195
196    /// Trace what rq decides (root, coverage, warming, reconcile) to stderr —
197    /// for debugging. `RQ_LOG=1` does the same for an installed binary.
198    #[arg(short = 'v', long)]
199    verbose: bool,
200
201    /// Report where a search spent its time, phase by phase, to stderr — as
202    /// JSON alongside --json, so a baseline can be stored and diffed.
203    /// `RQ_PROFILE=1` does the same for an installed binary.
204    #[arg(long)]
205    profile: bool,
206
207    /// Parse worker threads the background indexer uses (0 = auto). (`-j` is
208    /// taken by `--json`, so this is `--jobs` only.) `RQ_JOBS` works too.
209    #[arg(long, value_name = "N", default_value_t = 0)]
210    jobs: usize,
211}
212
213/// Parse arguments and dispatch. Returns the process exit code.
214pub fn run() -> ExitCode {
215    let cli = Cli::parse();
216    crate::trace::enable_from(cli.verbose);
217    crate::profile::enable_from(cli.profile);
218    crate::index::set_parse_jobs(cli.jobs);
219
220    if let Some(shell) = cli.completions {
221        clap_complete::generate(shell, &mut Cli::command(), "rq", &mut std::io::stdout());
222        return ExitCode::SUCCESS;
223    }
224    if let Some(path) = &cli.index {
225        // index PATH (else cwd); with --path, seed only those subtrees
226        let out = output_format(&cli);
227        return cmd_index(path.as_deref().map(PathBuf::from), &cli.path, out);
228    }
229    if let Some(path) = &cli.warm {
230        return cmd_warm(path.as_deref());
231    }
232    if cli.status {
233        return cmd_status(output_format(&cli));
234    }
235    if cli.usage {
236        return cmd_usage(output_format(&cli));
237    }
238    if cli.drop {
239        let out = output_format(&cli);
240        return cmd_drop(cli.target, out);
241    }
242    if cli.record {
243        // a typo'd --event would otherwise record silently and never roll up
244        if !matches!(cli.event.as_str(), "select" | "open") {
245            return fail(format_args!(
246                "rq --record: unknown --event {:?} (expected select or open)",
247                cli.event
248            ));
249        }
250        // clap guarantees --file is present via `requires`
251        let file = cli.file.expect("--record requires --file");
252        return cmd_record(&cli.event, cli.target.as_deref(), &file, cli.line);
253    }
254    let out = output_format(&cli);
255    if cli.target.as_deref().is_some_and(|t| t.trim().is_empty()) {
256        return fail(format_args!("rq: empty query"));
257    }
258    // Reject an unknown --kind/--lang rather than filtering everything away: a
259    // typo used to come back as `no_match`, exit 1 — the one code a script is
260    // meant to trust as "this symbol does not exist".
261    let mut kinds: Vec<String> = Vec::new();
262    for k in &cli.kind {
263        match canonical_kind(k) {
264            Some(c) => kinds.push(c.to_string()),
265            None => {
266                return fail(format_args!(
267                    "rq: unknown --kind {k:?} (class, module, method, function, struct, enum, trait)"
268                ));
269            }
270        }
271    }
272    // a language token can expand to several tags (`r` → ruby + rust)
273    let mut langs: Vec<String> = Vec::new();
274    for x in &cli.lang {
275        let matched = canonical_langs(x);
276        if matched.is_empty() {
277            return fail(format_args!(
278                "rq: unknown --lang {x:?} ({})",
279                crate::lang::languages().join(", ")
280            ));
281        }
282        langs.extend(matched);
283    }
284    if let Some(file) = &cli.symbols {
285        return cmd_symbols(file, &kinds, &langs, out);
286    }
287    // path filters: trailing positionals (rg-style) plus any --path flags
288    let mut paths = cli.path.clone();
289    match cli.target {
290        Some(target) => {
291            // A leading kind keyword (`rq class Foo`) is shorthand for `-k`; skip
292            // it when the user gave an explicit `-k`, so the two never conflict.
293            let query = if cli.kind.is_empty() {
294                let (kw, query, dirs) = split_kind_keyword(target, cli.dirs.clone());
295                if let Some(k) = kw {
296                    kinds.push(k.to_string());
297                }
298                paths.extend(dirs);
299                query
300            } else {
301                paths.extend(cli.dirs.clone());
302                target
303            };
304            let mut session = match Session::open() {
305                Ok(s) => s,
306                Err(code) => return code,
307            };
308            cmd_search(
309                &mut session,
310                &SearchArgs {
311                    query: &query,
312                    explain: cli.explain,
313                    out,
314                    paths: &paths,
315                    kinds: &kinds,
316                    langs: &langs,
317                    want: requested_limit(cli.limit),
318                    no_record: cli.no_record,
319                    no_wait: cli.no_wait,
320                    wait: cli.wait,
321                    open: cli.open,
322                    all_repos: cli.all_repos,
323                    show: cli.show,
324                    batch: false,
325                },
326            )
327        }
328        // No query, but a pipe on stdin: each line is one, all sharing this
329        // run's store, repo resolution and warm.
330        None if !std::io::stdin().is_terminal() => cmd_batch(&cli, out, &paths, &kinds, &langs),
331        // bare `rq` (or just flags like --explain with no query): show help
332        None => {
333            let _ = Cli::command().print_long_help();
334            ExitCode::SUCCESS
335        }
336    }
337}
338
339/// How results are rendered.
340#[derive(Clone, Copy, PartialEq)]
341enum Output {
342    Text,
343    Json,
344    Ndjson,
345}
346
347fn output_format(cli: &Cli) -> Output {
348    if cli.ndjson {
349        Output::Ndjson
350    } else if cli.json {
351        Output::Json
352    } else {
353        Output::Text
354    }
355}
356
357/// Results shown when `--limit` isn't given.
358const DEFAULT_LIMIT: usize = 10;
359
360/// Minimum headroom to rank before a `--path` filter (so filtered-in results
361/// aren't lost to the cutoff).
362const PATH_HEADROOM: usize = 200;
363
364/// `--limit 0` means unlimited: every ranked hit, bounded only by how many
365/// candidates recall returned.
366fn requested_limit(limit: usize) -> usize {
367    if limit == 0 { usize::MAX } else { limit }
368}
369
370/// Count one search for `--usage`. Observability only: `search` rows are
371/// invisible to the rollup that feeds ranking, so this can never move a result.
372fn record_usage(
373    store: &mut Store,
374    args: &SearchArgs,
375    repository_id: Option<i64>,
376    results: usize,
377    status: &str,
378    coverage: Option<&str>,
379) {
380    if args.no_record {
381        return;
382    }
383    let _ = store.record_search(&crate::store::SearchRecord {
384        query: &args.query.to_ascii_lowercase(),
385        repository_id,
386        results,
387        source: &crate::origin::detect(),
388        flags: &flag_summary(args),
389        status,
390        coverage: coverage.unwrap_or("none"),
391    });
392}
393
394/// The call's flags as a canonical, comma-joined string, for usage counts.
395/// A fixed vocabulary in a fixed order, so the same call always produces the
396/// same string and the counter table stays small — values are never included,
397/// only which knobs were reached for.
398fn flag_summary(args: &SearchArgs) -> String {
399    let mut on: Vec<&str> = Vec::new();
400    match args.out {
401        Output::Json => on.push("json"),
402        Output::Ndjson => on.push("ndjson"),
403        Output::Text => {}
404    }
405    for (present, name) in [
406        (args.explain, "explain"),
407        (args.show, "show"),
408        (args.open, "open"),
409        (args.all_repos, "all-repos"),
410        (args.no_wait, "no-wait"),
411        (args.batch, "batch"),
412        (!args.paths.is_empty(), "path"),
413        (!args.kinds.is_empty(), "kind"),
414        (!args.langs.is_empty(), "lang"),
415        (args.want != DEFAULT_LIMIT, "limit"),
416    ] {
417        if present {
418            on.push(name);
419        }
420    }
421    on.join(",")
422}
423
424/// How often the search re-checks the index while a cold repo warms on the
425/// background thread. Each poll runs a full read query against the DB the
426/// indexer is actively writing, so polling too fast steals CPU and read-lock
427/// churn from the warm; 100 ms keeps that pressure low while staying
428/// imperceptible (an early answer or completion appears within a frame, and the
429/// progress line only redraws every `PROGRESS_REDRAW` anyway).
430const POLL_INTERVAL: Duration = Duration::from_millis(100);
431
432/// How long a cold-repo query may wait silently before we tell the user we're
433/// indexing — short enough to explain the pause, long enough that a repo which
434/// indexes quickly never flashes a message.
435const HEADS_UP_DELAY: Duration = Duration::from_millis(500);
436
437/// Minimum gap between progress-line redraws once the heads-up is showing — keeps
438/// the line from flickering (and the count query off the hot path) while still
439/// feeling live.
440const PROGRESS_REDRAW: Duration = Duration::from_millis(120);
441
442/// Everything `rq <query>` needs, bundled from the parsed CLI flags.
443struct SearchArgs<'a> {
444    query: &'a str,
445    explain: bool,
446    out: Output,
447    paths: &'a [String],
448    kinds: &'a [String],
449    langs: &'a [String],
450    /// Number of results to show (`--limit`).
451    want: usize,
452    no_record: bool,
453    /// Answer from the committed index without blocking on a (re)index (`--no-wait`).
454    no_wait: bool,
455    /// Cap on how long to wait for the index to warm (`--wait`); `None` = the
456    /// default/`RQ_WAIT_BUDGET_MS` budget.
457    wait: Option<Duration>,
458    open: bool,
459    all_repos: bool,
460    /// One of several queries sharing a run, so each row says which query it
461    /// answers — a single stream serving many questions is otherwise
462    /// unattributable.
463    batch: bool,
464    show: bool,
465}
466
467/// Default action: search the index and print ranked results.
468/// Everything a search needs that doesn't depend on the query: the open store,
469/// the repo it's rooted in, the branch's changed files, and who that repo is.
470///
471/// Split out because it's the expensive half — opening the store, resolving the
472/// root, reading branch files, resolving identity — and none of it varies per
473/// query. One search builds one and drops it; a caller answering many can build
474/// it once. Deliberately *not* holding the warm decision: that one is entangled
475/// with the query (the indexer path-prioritises toward it) and belongs to a
476/// single search.
477struct Session {
478    store: Store,
479    cwd: Option<PathBuf>,
480    cwd_is_git: bool,
481    root: Option<PathBuf>,
482    active_paths: Vec<String>,
483    branch_refresh: Option<BranchRefresh>,
484    identity: Option<String>,
485    coverage: Option<String>,
486}
487
488impl Session {
489    /// Resolve the search context, or the exit code to fail with.
490    fn open() -> std::result::Result<Session, ExitCode> {
491        let open_span = crate::profile::span("store open");
492        let store = match open_store() {
493            Ok(s) => s,
494            Err(e) => return Err(fail(format_args!("rq: cannot open database: {e}"))),
495        };
496        drop(open_span);
497        let git_span = crate::profile::span("setup: git root");
498        let cwd = std::env::current_dir().ok();
499        let cwd_is_git = cwd.as_deref().is_some_and(crate::index::is_git_repo);
500
501        // Index relative to the repo ROOT, not wherever the search happens to run.
502        // Paths and the stored checkout root must be repo-root-relative and stable, or
503        // a search from a subdirectory would re-key the same repo under subdir-relative
504        // paths — and the deletion reconcile / staleness revalidation would then forget
505        // everything indexed from the root. Outside git, the root is just the cwd.
506        let root = cwd
507            .as_deref()
508            .map(|c| crate::index::repo_root(c).unwrap_or_else(|| c.to_path_buf()));
509        drop(git_span);
510
511        // Files you're changing on this feature branch (and their directory
512        // neighbors): the branch ranking boost, and the warm pass's priority set.
513        let mut branch_span = crate::profile::span("setup: branch files");
514        let (active_paths, branch_refresh) = match &root {
515            Some(c) if cwd_is_git => cached_branch_files(&store, c),
516            _ => (Vec::new(), None),
517        };
518        branch_span.note(|| {
519            let how = if branch_refresh.is_some() {
520                "cached, refreshing alongside"
521            } else {
522                "cached"
523            };
524            format!("{} changed, {how}", active_paths.len())
525        });
526        drop(branch_span);
527
528        // Resolve identity from the repo root, cache-first: looked up by checkout root
529        // (no `git remote` fork), falling back to git only the first time we see a
530        // repo. Computed even for non-git dirs so an explicitly `--index`ed one is
531        // still recognized as the current repo below.
532        let mut identity_span = crate::profile::span("setup: identity");
533        let identity = root.as_deref().map(|c| resolve_identity(&store, c));
534        let coverage = identity
535            .as_deref()
536            .and_then(|id| store.coverage_status(id).ok())
537            .flatten();
538        identity_span.note(|| coverage.as_deref().unwrap_or("unknown").to_string());
539        drop(identity_span);
540        Ok(Session {
541            store,
542            cwd,
543            cwd_is_git,
544            root,
545            active_paths,
546            branch_refresh,
547            identity,
548            coverage,
549        })
550    }
551}
552
553/// Answer a stream of queries, one per line on stdin, in a single run.
554///
555/// Everything a query doesn't vary — the store, the repo, its identity, the
556/// branch's changed files — is resolved once and reused, which on a large repo
557/// is most of what a single lookup costs. Agents and scripts do runs of
558/// lookups; this is that shape.
559///
560/// A cold repo warms **once, up front, until complete** rather than answering
561/// each line from whatever happens to be indexed. Block-until-*answered*
562/// doesn't generalise to queries we haven't read yet — you can't prioritise
563/// toward them — so block-until-*complete* is the batch-shaped equivalent, and
564/// it keeps this file's own rule that correctness beats the first query's
565/// latency. `--no-wait` opts out, exactly as it does for one query, and any
566/// line the index can't yet answer says so with `status: "warming"`.
567fn cmd_batch(
568    cli: &Cli,
569    out: Output,
570    paths: &[String],
571    kinds: &[String],
572    langs: &[String],
573) -> ExitCode {
574    if out == Output::Json {
575        return fail(format_args!(
576            "rq: --json can't frame a stream of queries — use --ndjson (-J), \
577             where each line carries the query it answers"
578        ));
579    }
580    if cli.open || cli.show {
581        return fail(format_args!(
582            "rq: --open and --show act on a single result, not a stream of queries"
583        ));
584    }
585
586    use std::io::BufRead;
587    let queries: Vec<String> = std::io::stdin()
588        .lock()
589        .lines()
590        .map_while(std::result::Result::ok)
591        .map(|l| l.trim().to_string())
592        .filter(|l| !l.is_empty())
593        .collect();
594    // Nothing on stdin isn't a batch — it's a bare invocation that happens to
595    // run without a terminal (a script, a test harness, stdin from /dev/null).
596    // Treat it the way `rq` with no arguments is always treated.
597    if queries.is_empty() {
598        let _ = Cli::command().print_long_help();
599        return ExitCode::SUCCESS;
600    }
601
602    let mut session = match Session::open() {
603        Ok(s) => s,
604        Err(code) => return code,
605    };
606
607    // Warm to completion before answering anything, so a cold repo doesn't
608    // return a page of misses that only mean "not indexed yet".
609    if !cli.no_wait
610        && session.coverage.as_deref() != Some("complete")
611        && let Some(root) = session.root.clone()
612    {
613        {
614            let budget = cli.wait.unwrap_or_else(wait_budget);
615            crate::trace!(
616                "batch: warming {} queries' worth of index first",
617                queries.len()
618            );
619            let active = session.active_paths.clone();
620            let _ = crate::index::index_budgeted(&mut session.store, &root, &active, budget, None);
621            session.coverage = session
622                .identity
623                .as_deref()
624                .and_then(|id| session.store.coverage_status(id).ok())
625                .flatten();
626        }
627    }
628
629    let mut worst = ExitCode::SUCCESS;
630    let mut any_hit = false;
631    for query in &queries {
632        let code = cmd_search(
633            &mut session,
634            &SearchArgs {
635                query,
636                explain: cli.explain,
637                out,
638                paths,
639                kinds,
640                langs,
641                want: requested_limit(cli.limit),
642                no_record: cli.no_record,
643                // The warm happened above, once. Per-query warming would undo
644                // the point of batching, and block-until-answered is meaningless
645                // when the queries were all read up front.
646                no_wait: true,
647                wait: cli.wait,
648                open: false,
649                all_repos: cli.all_repos,
650                show: false,
651                batch: true,
652            },
653        );
654        if code == ExitCode::SUCCESS {
655            any_hit = true;
656        } else {
657            worst = code;
658        }
659    }
660    // The batch ran; per-line `status` carries each query's outcome. Only a
661    // wholly fruitless batch reports failure, mirroring one query's contract.
662    if any_hit { ExitCode::SUCCESS } else { worst }
663}
664
665fn cmd_search(session: &mut Session, args: &SearchArgs) -> ExitCode {
666    let &SearchArgs {
667        query,
668        out,
669        want,
670        no_record,
671        no_wait,
672        wait,
673        open,
674        all_repos,
675        show,
676        ..
677    } = args;
678    // `--wait DUR` overrides the wait budget for this call; `--wait 0` (or
679    // `--no-wait`) means don't block or warm in-process at all.
680    let wait_budget = wait.unwrap_or_else(wait_budget);
681    let no_wait = no_wait || wait_budget.is_zero();
682    // post-filters (--path, --kind, --lang) need headroom before the cutoff so a
683    // filtered-in result isn't lost to the top-N truncation
684    let limit = if args.paths.is_empty() && args.kinds.is_empty() && args.langs.is_empty() {
685        want
686    } else {
687        want.saturating_mul(20).max(PATH_HEADROOM)
688    };
689    let _timer = crate::trace::Timer::start("search done");
690    let profile_started = std::time::Instant::now();
691    let t_setup = std::time::Instant::now();
692    // Brackets the warm decision as well as the session, so it outlives both.
693    let setup_span = crate::profile::span("setup");
694    // Borrowed field-by-field so the body reads the same as when it owned them,
695    // while the session itself outlives this call and can answer again.
696    let Session {
697        store,
698        cwd,
699        cwd_is_git,
700        root,
701        active_paths,
702        branch_refresh,
703        identity,
704        coverage,
705    } = session;
706    let cwd_is_git = *cwd_is_git;
707
708    // Opportunistic indexing (Layer 5), time-bounded so the first query in a
709    // large repo never blocks on a full walk. We may warm a git work tree (safe
710    // to auto-discover) *or* any dir we already track — one earns tracking by
711    // being explicitly `--index`ed, which opts a non-git dir in. We never warm
712    // an unknown non-git dir (don't walk a random directory). A subtree index
713    // (`--index --path …`) is a seed, not a fence: coverage stays `warming`, so
714    // warming continues over the rest of the repo from here.
715    let known = coverage.is_some();
716    let warming_ok = cwd_is_git || known;
717    if crate::trace::enabled() {
718        crate::trace!(
719            "query {query:?}: root={} identity={} coverage={} warming_ok={warming_ok} active={}",
720            root.as_deref().map_or("?".into(), crate::trace::abbrev),
721            identity.as_deref().unwrap_or("none"),
722            coverage.as_deref().unwrap_or("none"),
723            active_paths.len(),
724        );
725    }
726    let repo_span = crate::profile::span("setup: repo state");
727    let current = identity
728        .as_deref()
729        .and_then(|id| store.repository_id(id).ok().flatten());
730    // Default: scope results to the current repo (when it's indexed) so a search
731    // never leaks another repo's definitions. `--all-repos` searches everything.
732    let only_repo = if all_repos { None } else { current };
733    let active = crate::search::ActiveFiles::new(active_paths.clone());
734
735    drop(repo_span);
736    let warm_span = crate::profile::span("setup: warm decision");
737
738    // Warm the index on a background thread (its own connection — WAL lets it
739    // write while we read) whenever there's work: a not-yet-complete repo, or a
740    // complete one changed since it was indexed. The search below reads whatever
741    // it has committed so far. With detach on (the default), this in-process
742    // warm only serves *this* answer — leftover work goes to a detached child
743    // after results print, so the shell never waits on it.
744    let warm_budget = if warm_detach_enabled() {
745        answer_warm_budget()
746    } else {
747        answer_warm_budget() + deferred_warm_budget()
748    };
749    let was_warming = coverage.as_deref() != Some("complete");
750
751    // On a complete repo the only question left is whether the worktree moved
752    // since it was indexed — and answering it forks `git status`, which on a
753    // large worktree is most of a query's cost. It decides nothing this answer
754    // depends on: with `was_warming` false, `block` and `polling` below are
755    // false too, the search reads the committed index, and `revalidate_top`
756    // guarantees the freshness of what we print. So start it alongside the
757    // search and collect it in `settle_warm` once results are out.
758    //
759    // A still-warming repo never ran this check at all — the `||` short-circuit
760    // saw to that — so its path here is unchanged.
761    let indexed_head = (!was_warming)
762        .then(|| current.and_then(|id| store.indexed_head(id).ok().flatten()))
763        .flatten();
764    // Whether the worktree moved is a property of the repo, not of the query,
765    // so a batch asks once (up front) instead of forking `git status` per line.
766    let staleness = (!was_warming && warming_ok && !args.batch)
767        .then(|| root.clone())
768        .flatten()
769        .map(|c| std::thread::spawn(move || worktree_changed(&c, indexed_head.as_deref())));
770    // Only a repo that's still warming warms *before* the answer now; a
771    // complete-but-edited one is reindexed by `settle_warm` afterwards.
772    let want_warm = warming_ok && was_warming && root.is_some();
773
774    // Block-until-answered on a cold/partial repo. A bounded warm exists so a
775    // query never hangs, but on a *huge, cold* repo it can expire before the
776    // symbol is indexed — turning a real hit into a false "no matches". Since
777    // correctness beats the first query's latency (and once warm the repo answers
778    // fast), we keep indexing until the answer appears or the repo is fully
779    // indexed — for humans *and* programs alike. Small/medium repos finish inside
780    // the normal budget and are unaffected; only a genuinely large cold repo
781    // waits, and only once.
782    // `--no-wait`: a scripted/agent caller that would rather answer from the
783    // committed index right now than block up to the wait budget while a
784    // background rebuild rewrites the index. It suppresses the block-until-answered
785    // escalation *and* the in-process warm (no lock contention, no join) — leftover
786    // warming still detaches below, so the index keeps improving for next time.
787    let block = want_warm && was_warming && !no_wait;
788    // A human at a plain-text terminal also gets a live progress heads-up and a
789    // graceful Ctrl-C; piped/`--json` callers (agents, scripts) block silently and
790    // are bounded by a wait budget instead, since there's nothing to draw to and
791    // no one to interrupt.
792    let progress_ui = block && show_progress(out, stderr_interactive());
793    let indexer_budget = if block { wait_budget } else { warm_budget };
794    if progress_ui {
795        install_interrupt_handler();
796    }
797
798    // `warm_done` lets the poll stop the instant the indexer finishes — so a miss
799    // on a small repo returns as soon as it's indexed, not at the deadline.
800    let warm_done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
801    let indexer = (want_warm && root.is_some() && !no_wait).then(|| {
802        crate::trace!(
803            "background warm ({indexer_budget:?}, block={block}, progress_ui={progress_ui}, {} jobs)",
804            crate::index::parse_jobs()
805        );
806        let root = root.clone().expect("checked");
807        let active = active_paths.clone();
808        let q = query.to_string();
809        let warm_done = std::sync::Arc::clone(&warm_done);
810        std::thread::spawn(move || {
811            if let Ok(mut idx) = open_store() {
812                // path-prioritize toward the query so the relevant file indexes first
813                let _ = if block {
814                    // the abort flag (`INTERRUPTED`) lets a Ctrl-C, a wait timeout,
815                    // or an early answer stop the pass without losing committed work
816                    crate::index::index_budgeted_cancellable(
817                        &mut idx,
818                        &root,
819                        &active,
820                        indexer_budget,
821                        Some(&q),
822                        &INTERRUPTED,
823                    )
824                } else {
825                    crate::index::index_budgeted(&mut idx, &root, &active, indexer_budget, Some(&q))
826                };
827            }
828            warm_done.store(true, std::sync::atomic::Ordering::Relaxed);
829        })
830    });
831
832    // Poll while a cold/partial repo warms. Don't print the first hit off a sparse
833    // index — a fuzzy or path match can be wrong once more is indexed. Hold until a
834    // *high-confidence* (exact or prefix name) match appears; otherwise keep
835    // building until the index is complete (a "no matches" is then trustworthy), a
836    // wait deadline passes, or — interactively — Ctrl-C. A human sees a progress
837    // line once the pause is noticeable.
838    crate::trace!(
839        "setup (open + repo detect + warm decision): {} ms",
840        t_setup.elapsed().as_millis()
841    );
842    let poll_start = std::time::Instant::now();
843    // Deadline: an interactive block waits unbounded (Ctrl-C escapes); a
844    // programmatic block waits out the wait budget; a non-block (complete repo)
845    // keeps the original fast answer budget.
846    let deadline = if progress_ui {
847        None
848    } else if block {
849        Some(poll_start + wait_budget)
850    } else {
851        Some(poll_start + answer_warm_budget())
852    };
853    drop(warm_span);
854    let polling = indexer.is_some() && was_warming;
855    // Everything before the first search: resolving the repo root, checking
856    // coverage, deciding whether to warm. It runs on every query, so it counts
857    // toward the first-answer budget even though no searching happened yet.
858    drop(setup_span);
859    let mut query_span = crate::profile::span("query");
860    let label = repo_label(root.as_deref());
861    let mut drew_progress = false;
862    let mut last_draw = poll_start;
863    // Rank one deeper than asked: confidence is a comparison against the
864    // runner-up, so normalizing over the returned window made `-l 1` read 1.0
865    // every time — and that reading is what gates `--show`.
866    let rank_limit = limit.max(2);
867    let mut total;
868    let mut hits = loop {
869        match crate::search::search(store, query, current, only_repo, &active, rank_limit) {
870            Ok(m) => {
871                total = m.total;
872                let h = m.hits;
873                let confident = h.first().is_some_and(|hit| {
874                    hit.features
875                        .iter()
876                        .any(|f| matches!(f.name, "exact" | "prefix"))
877                });
878                let warm_finished = warm_done.load(std::sync::atomic::Ordering::Relaxed);
879                let stopped = INTERRUPTED.load(std::sync::atomic::Ordering::Relaxed);
880                let timed_out = deadline.is_some_and(|d| std::time::Instant::now() >= d);
881                if !polling || confident || warm_finished || stopped || timed_out {
882                    break h;
883                }
884                if progress_ui
885                    && poll_start.elapsed() >= HEADS_UP_DELAY
886                    && last_draw.elapsed() >= PROGRESS_REDRAW
887                {
888                    draw_progress(store, identity.as_deref(), &label);
889                    drew_progress = true;
890                    last_draw = std::time::Instant::now();
891                }
892            }
893            Err(e) => {
894                if let Some(h) = indexer {
895                    let _ = h.join();
896                }
897                return fail(format_args!("rq: {e}"));
898            }
899        }
900        std::thread::sleep(POLL_INTERVAL);
901    };
902    query_span.note(|| {
903        if polling {
904            "polled a warming index".to_string()
905        } else {
906            String::new()
907        }
908    });
909    drop(query_span);
910    if drew_progress {
911        clear_progress();
912    }
913    // Captured before we self-cancel below, so it reflects only a *user's* Ctrl-C.
914    let interrupted = INTERRUPTED.load(std::sync::atomic::Ordering::Relaxed);
915
916    // Staleness: revalidate the files behind the top hits; re-rank once if changed.
917    if !hits.is_empty()
918        && revalidate_top(store, &hits)
919        && let Ok(m) = crate::search::search(store, query, current, only_repo, &active, rank_limit)
920    {
921        total = m.total;
922        hits = m.hits;
923    }
924
925    // Untracked non-git dir — nothing persisted, no warmer running — so scan it
926    // live in-memory (substring, then fuzzy) and blend with whatever the index
927    // gave. The only non-persisting scan left.
928    if !hits.iter().any(strong)
929        && indexer.is_none()
930        && coverage.is_none()
931        && let Some(root) = &root
932    {
933        let tail = live_fallback(root, query, rank_limit);
934        hits = crate::search::merge(hits, tail, rank_limit);
935        total = total.max(hits.len());
936    }
937
938    apply_gates(query, &mut hits);
939    apply_post_filters(args, cwd.as_deref(), root.as_deref(), &mut hits);
940    // A filtered search reports what survived the filter — that's the set the
941    // caller asked about.
942    if !args.paths.is_empty() || !args.kinds.is_empty() || !args.langs.is_empty() {
943        total = hits.len();
944    }
945
946    if hits.is_empty() {
947        // Stop a still-running block so the join is prompt, then settle coverage.
948        if block {
949            INTERRUPTED.store(true, std::sync::atomic::Ordering::Relaxed);
950        }
951        if let Some(h) = indexer {
952            let _ = h.join();
953        }
954        // A miss against a *complete* index is definitive (the symbol isn't
955        // there); against a still-warming one it's only "not yet". Distinguish
956        // them so a caller — agent or script — isn't misled into thinking the
957        // symbol is absent when the index simply hasn't reached it. `--no-wait`
958        // returns without blocking, so its miss is judged the same way — an
959        // incomplete index yields `warming` (exit 2, "retry"), not a false absence.
960        let mut incomplete = (block || no_wait)
961            && identity
962                .as_deref()
963                .and_then(|id| store.coverage_status(id).ok().flatten())
964                .as_deref()
965                != Some("complete");
966        // a "not yet" miss leaves work behind — reindex an edited worktree and
967        // let a detached child keep warming, so the retry lands on a better
968        // index. This is the path a just-added symbol takes, so it has to do
969        // the same settling the render path does.
970        // A worktree that has moved since we indexed it makes this miss
971        // provisional, not definitive: the symbol may be in an edit the
972        // detached warm hasn't caught up with. Say "warming" (exit 2, retry)
973        // rather than "no match" (exit 1, absent) — a just-added symbol is
974        // exactly this case, and a confident no is the wrong answer to it.
975        incomplete |= settle_warm(
976            store,
977            staleness,
978            was_warming,
979            warming_ok,
980            root.as_deref(),
981            active_paths,
982            query,
983            warm_budget,
984            no_wait,
985            identity.as_deref(),
986        );
987        // Recorded here rather than above the branch: whether this was a
988        // definitive miss or a not-ready one is only known now, and counting
989        // them as one number overstates how often rq truly finds nothing.
990        record_usage(
991            store,
992            args,
993            current,
994            0,
995            if incomplete { "warming" } else { "miss" },
996            coverage.as_deref(),
997        );
998        return no_match_code(out, query, interrupted, incomplete);
999    }
1000
1001    // The hit path's single count, above the --show/--open/list forks so it
1002    // covers all three.
1003    record_usage(store, args, current, hits.len(), "hit", coverage.as_deref());
1004
1005    // Confidence first, while the runner-up is still in hand, then cut to the
1006    // window the caller asked for — `--show`'s gate reads this, so measuring it
1007    // over an already-truncated list made `-l 1` unconditionally confident.
1008    attach_confidence(&mut hits);
1009    hits.truncate(want);
1010    let total = total.max(hits.len());
1011    for hit in &mut hits {
1012        hit.total = total;
1013        if args.explain {
1014            hit.explain = Some(
1015                hit.features
1016                    .iter()
1017                    .map(|f| (f.name.to_string(), f.value))
1018                    .collect(),
1019            );
1020        }
1021    }
1022
1023    // Attach each result's definition line (e.g. `def perform(refund)`) — shown
1024    // in text output and carried in JSON. Cheap: only the displayed results.
1025    for hit in &mut hits {
1026        hit.signature = read_signature(
1027            store,
1028            &hit.repo_identity,
1029            &hit.file,
1030            hit.line,
1031            cwd.as_deref(),
1032        );
1033    }
1034
1035    // --show: print the top hit's full source when confident; otherwise fall
1036    // through to the normal ranked list (rq won't dump a body it isn't sure of).
1037    if show
1038        && let Some(code) = show_top_definition(
1039            store,
1040            &mut hits,
1041            query,
1042            out,
1043            cwd.as_deref(),
1044            current,
1045            no_record,
1046        )
1047    {
1048        return code;
1049    }
1050
1051    // --open: pick the best match (prompting on a TTY with several), record the
1052    // pick so ranking learns, and hand off to the editor. Returns before the
1053    // normal print / warm-join — opening should be snappy, and a launcher `exec`s.
1054    if open {
1055        return finish_open(store, &hits, query, current, root.as_deref(), no_record);
1056    }
1057
1058    if let Some(code) = render_hits(args, &hits) {
1059        return code;
1060    }
1061
1062    // Report before the deferred maintenance below, so the total covers
1063    // getting answers out rather than the bookkeeping that follows them.
1064    if crate::profile::enabled() {
1065        let total = profile_started.elapsed();
1066        if args.out == Output::Text {
1067            for line in crate::profile::report(total) {
1068                eprintln!("{line}");
1069            }
1070        } else {
1071            // stdout stays exactly the results, so the profile can be captured
1072            // separately and diffed.
1073            eprintln!("{}", crate::profile::json(total));
1074        }
1075    }
1076
1077    // Collect the refresh started back at setup. It ran alongside the search
1078    // rather than after it, so by now it has usually finished — and it only
1079    // ever feeds the *next* query, never this one's ranking, so waiting on it
1080    // can't reorder what was just printed.
1081    // Taken, not borrowed: the refresh is one-shot, and a session answering
1082    // several queries must not re-store a result it already consumed.
1083    if let Some(refresh) = branch_refresh.take() {
1084        refresh.store(store);
1085    }
1086
1087    // Results are out — now the cheap deferred work, amortized across
1088    // interactions: roll the `open`/`select` picks that teach ranking into
1089    // `selection_stats`, and prune the raw log. The `search` row written above
1090    // is skipped by the rollup — it counts usage, it doesn't teach.
1091    deferred_maintenance(store);
1092
1093    // Results are out; stop the in-process warm (it persists as it goes, so a
1094    // cut pass keeps everything parsed) and join it — then hand whatever's left
1095    // to a detached child, which finishes coverage with a budget no foreground
1096    // query could afford. The shell only ever waits on the answer.
1097    if block {
1098        INTERRUPTED.store(true, std::sync::atomic::Ordering::Relaxed);
1099    }
1100    if let Some(h) = indexer {
1101        let _ = h.join();
1102    }
1103    let _ = settle_warm(
1104        store,
1105        staleness,
1106        was_warming,
1107        warming_ok,
1108        root.as_deref(),
1109        active_paths,
1110        query,
1111        warm_budget,
1112        no_wait,
1113        identity.as_deref(),
1114    );
1115
1116    ExitCode::SUCCESS
1117}
1118
1119/// Re-exec a detached warm child when this query's warming didn't finish the
1120/// job. No-op when detach is off, nothing was warming, or coverage completed.
1121fn maybe_detach_warm(
1122    store: &Store,
1123    want_warm: bool,
1124    changed: bool,
1125    root: Option<&std::path::Path>,
1126    identity: Option<&str>,
1127) {
1128    if !warm_detach_enabled() || !want_warm {
1129        return;
1130    }
1131    let (Some(root), Some(id)) = (root, identity) else {
1132        return;
1133    };
1134    // Coverage measures breadth, not freshness — an edit never demotes it. So
1135    // "complete" alone isn't done; it's done only if the worktree also hasn't
1136    // moved since we indexed it.
1137    if !changed && store.coverage_status(id).ok().flatten().as_deref() == Some("complete") {
1138        return; // the in-process pass finished the job
1139    }
1140    spawn_detached_warm(root);
1141}
1142
1143/// Spawn `rq --warm <root>` fully detached: null stdio and its own process
1144/// group, so it survives this process and a later Ctrl-C in the terminal
1145/// can't reach it. The child nices itself and is single-flighted per repo.
1146fn spawn_detached_warm(root: &std::path::Path) {
1147    use std::os::unix::process::CommandExt;
1148    let Ok(exe) = std::env::current_exe() else {
1149        return;
1150    };
1151    let mut cmd = std::process::Command::new(exe);
1152    cmd.arg("--warm")
1153        .arg(root)
1154        .stdin(std::process::Stdio::null())
1155        .stdout(std::process::Stdio::null())
1156        .stderr(std::process::Stdio::null())
1157        .process_group(0);
1158    match cmd.spawn() {
1159        Ok(child) => crate::trace!(
1160            "background warm (detached): pid {} for {}",
1161            child.id(),
1162            crate::trace::abbrev(root)
1163        ),
1164        Err(e) => crate::trace!("detached warm failed to spawn: {e}"),
1165    }
1166}
1167
1168/// How long a warm lock is trusted without a liveness hit — past this, a
1169/// stamp is a crashed warmer's leftover and a new child takes over.
1170const WARM_LOCK_TTL_SECS: i64 = 600;
1171
1172/// `rq --warm [PATH]`: the detached child a search re-execs after printing —
1173/// finishes warming the repo's index in the background. Niced so it stays out
1174/// of the foreground's way; single-flighted per repo so a burst of queries
1175/// runs at most one warmer. Safe (and boring) to run by hand.
1176fn cmd_warm(path: Option<&str>) -> ExitCode {
1177    // Stay out of the way: drop scheduling priority, and throttle disk I/O on
1178    // macOS. Best-effort — a failure just means a less-polite warm.
1179    #[cfg(target_os = "macos")]
1180    unsafe extern "C" {
1181        // <sys/resource.h>; not in the libc crate. Args below:
1182        // IOPOL_TYPE_DISK=0, IOPOL_SCOPE_PROCESS=0, IOPOL_THROTTLE=3.
1183        fn setiopolicy_np(
1184            iotype: libc::c_int,
1185            scope: libc::c_int,
1186            policy: libc::c_int,
1187        ) -> libc::c_int;
1188    }
1189    unsafe {
1190        libc::nice(10);
1191        #[cfg(target_os = "macos")]
1192        setiopolicy_np(0, 0, 3);
1193    }
1194    let mut store = match open_store() {
1195        Ok(s) => s,
1196        Err(_) => return ExitCode::FAILURE,
1197    };
1198    let start = path
1199        .map(PathBuf::from)
1200        .or_else(|| std::env::current_dir().ok())
1201        .unwrap_or_else(|| PathBuf::from("."));
1202    let root = crate::index::repo_root(&start).unwrap_or(start);
1203    let identity = resolve_identity(&store, &root);
1204
1205    // Single-flight: if another live rq is already warming this repo, bow out.
1206    // A dead pid or a stale stamp is a crashed warmer — take over.
1207    if let Ok(Some((pid, ts))) = store.warm_lock(&identity)
1208        && pid != std::process::id()
1209        && unsafe { libc::kill(pid as libc::pid_t, 0) } == 0
1210        && now_secs() - ts < WARM_LOCK_TTL_SECS
1211    {
1212        return ExitCode::SUCCESS;
1213    }
1214    let _ = store.set_warm_lock(&identity, std::process::id());
1215
1216    // Sweep until coverage completes, the budget runs out, or a pass stops
1217    // making progress (each pass converges — mtime-skips what's done).
1218    let deadline = std::time::Instant::now() + warm_bg_budget();
1219    let active = crate::index::branch_changed_files(&root);
1220    loop {
1221        let remaining = deadline.saturating_duration_since(std::time::Instant::now());
1222        if remaining.is_zero() {
1223            break;
1224        }
1225        let stats = match crate::index::index_budgeted(&mut store, &root, &active, remaining, None)
1226        {
1227            Ok(s) => s,
1228            Err(_) => break,
1229        };
1230        if store.coverage_status(&identity).ok().flatten().as_deref() == Some("complete")
1231            || stats.files_indexed == 0
1232        {
1233            break;
1234        }
1235    }
1236    let _ = store.clear_warm_lock(&identity);
1237    ExitCode::SUCCESS
1238}
1239
1240fn now_secs() -> i64 {
1241    std::time::SystemTime::now()
1242        .duration_since(std::time::UNIX_EPOCH)
1243        .map(|d| d.as_secs() as i64)
1244        .unwrap_or(0)
1245}
1246
1247/// Live in-memory scan of an untracked (non-git, never-indexed) dir: substring
1248/// pre-filtered first, then the unfiltered fuzzy retry. Persists nothing.
1249fn live_fallback(root: &std::path::Path, query: &str, limit: usize) -> Vec<crate::search::Hit> {
1250    crate::trace!("empty → live (in-memory) scan of an untracked dir");
1251    let deadline = std::time::Instant::now() + live_fallback_budget();
1252    let h = crate::search::live_search(root, query, limit, &HashSet::new(), Some(deadline), true);
1253    if !h.is_empty() {
1254        return h;
1255    }
1256    crate::search::live_search(root, query, limit, &HashSet::new(), Some(deadline), false)
1257}
1258
1259/// A high-confidence name match: exact or prefix (not fuzzy/path-only).
1260fn strong(h: &crate::search::Hit) -> bool {
1261    h.features
1262        .iter()
1263        .any(|f| matches!(f.name, "exact" | "prefix"))
1264}
1265
1266/// The result-quality gates, in order:
1267/// - relevance: when the query lands a real name match (exact or prefix), drop
1268///   the scattered fuzzy / path-only near-matches — they're noise next to a
1269///   solid hit, and rq favors fewer, better results. A purely-fuzzy query (no
1270///   exact/prefix anywhere) keeps its matches.
1271/// - scope: a qualified query (`Foo::Bar#baz`) that lands inside the named
1272///   scope keeps only the in-scope results; if none match, the others stay
1273///   (the definition may live elsewhere).
1274fn apply_gates(query: &str, hits: &mut Vec<crate::search::Hit>) {
1275    if hits.iter().any(strong) {
1276        hits.retain(strong);
1277    }
1278    crate::search::apply_scope_gate(query, hits);
1279}
1280
1281/// Post-filters: keep only results under a `--path` dir, of a `--kind`, and/or
1282/// in a `--lang`, then trim to the requested count.
1283fn apply_post_filters(
1284    args: &SearchArgs,
1285    cwd: Option<&std::path::Path>,
1286    root: Option<&std::path::Path>,
1287    hits: &mut Vec<crate::search::Hit>,
1288) {
1289    if !args.paths.is_empty() {
1290        // --path values may be absolute or cwd-relative; stored files are
1291        // repo-root-relative, so normalize before prefix-matching or an
1292        // absolute path would silently filter everything out.
1293        let here = cwd.map_or_else(|| PathBuf::from("."), PathBuf::from);
1294        let base = root.map_or_else(|| here.clone(), PathBuf::from);
1295        let norm: Vec<String> = args
1296            .paths
1297            .iter()
1298            .map(|p| repo_relative(&base, &here, p))
1299            .collect();
1300        hits.retain(|h| under_any(&h.file, &norm));
1301    }
1302    if !args.kinds.is_empty() {
1303        hits.retain(|h| args.kinds.iter().any(|k| k == &h.kind));
1304    }
1305    if !args.langs.is_empty() {
1306        hits.retain(|h| args.langs.iter().any(|l| l == &h.language));
1307    }
1308    // Deliberately not truncated to `want` here: confidence is measured against
1309    // the runner-up, so the final cut happens after it's assigned.
1310    if !args.paths.is_empty() || !args.kinds.is_empty() || !args.langs.is_empty() {
1311        hits.truncate(args.want.max(2));
1312    }
1313}
1314
1315/// Report a miss and pick its exit code. Structured callers get a reason, not
1316/// a bare `[]`/empty: `warming` (retry — index incomplete), `interrupted` (a
1317/// stopped block), or `no_match` (definitive). Text keeps its human message.
1318/// Exit 2 = indeterminate (index incomplete), 1 = a definitive miss — both
1319/// non-zero, so `rq … && …` still reads as "found something".
1320fn no_match_code(out: Output, query: &str, interrupted: bool, incomplete: bool) -> ExitCode {
1321    let status = if interrupted {
1322        "interrupted"
1323    } else if incomplete {
1324        "warming"
1325    } else {
1326        "no_match"
1327    };
1328    match out {
1329        Output::Json | Output::Ndjson => {
1330            let obj = serde_json::json!({ "status": status, "query": query });
1331            let _ = emit_json(out, &obj); // the exit code below carries the miss
1332        }
1333        Output::Text if interrupted => {
1334            eprintln!("rq: indexing interrupted — run again to finish")
1335        }
1336        Output::Text if incomplete => eprintln!(
1337            "rq: still indexing — no match for {query:?} yet (run again, or `rq --index` to finish)"
1338        ),
1339        Output::Text => eprintln!("no matches for {query:?}"),
1340    }
1341    if incomplete {
1342        ExitCode::from(2)
1343    } else {
1344        ExitCode::FAILURE
1345    }
1346}
1347
1348/// Normalized confidence per hit: match quality scaled by dominance over the
1349/// other results (needs the whole ranked set). "Best other" is the top score —
1350/// or the runner-up, for the top hit itself.
1351fn attach_confidence(hits: &mut [crate::search::Hit]) {
1352    let (top, second) = hits.iter().fold((None::<f64>, None::<f64>), |(t, s), h| {
1353        if t.is_none_or(|t| h.score > t) {
1354            (Some(h.score), t)
1355        } else if s.is_none_or(|s| h.score > s) {
1356            (t, Some(h.score))
1357        } else {
1358            (t, s)
1359        }
1360    });
1361    for hit in hits.iter_mut() {
1362        let best_other = if Some(hit.score) == top { second } else { top };
1363        hit.confidence = crate::search::confidence(
1364            hit.score,
1365            crate::search::match_quality(&hit.features),
1366            best_other,
1367        );
1368    }
1369}
1370
1371/// Print the ranked results (JSON array, NDJSON lines, or highlighted text).
1372/// `Some(exit)` on a serialization failure, `None` on success.
1373fn render_hits(args: &SearchArgs, hits: &[crate::search::Hit]) -> Option<ExitCode> {
1374    // Time to the first printed result, not to the last: rq streams, and the
1375    // sub-50 ms budget is about the first answer. A change that speeds the
1376    // total while delaying this one is a regression.
1377    let render_span = crate::profile::span("render");
1378    if args.batch {
1379        // One stream, many questions: tag each row with the query it answers,
1380        // the same way `no_match_code` already tags a miss.
1381        #[derive(serde::Serialize)]
1382        struct Tagged<'a> {
1383            query: &'a str,
1384            #[serde(flatten)]
1385            hit: &'a crate::search::Hit,
1386        }
1387        let rows: Vec<Tagged> = hits
1388            .iter()
1389            .map(|hit| Tagged {
1390                query: args.query,
1391                hit,
1392            })
1393            .collect();
1394        if let Some(code) = emit_rows(args.out, &rows) {
1395            return Some(code);
1396        }
1397    } else if let Some(code) = emit_rows(args.out, hits) {
1398        return Some(code);
1399    }
1400    if args.out != Output::Text {
1401        return None;
1402    }
1403    drop(render_span);
1404    let color = match_color();
1405    let c = color.as_deref();
1406    let query = args.query;
1407    if args.show {
1408        // fell through from --show: no single confident match to print
1409        let total = hits.first().map_or(hits.len(), |h| h.total);
1410        eprintln!(
1411            "rq: no single confident match for {query:?} — {} of {total} candidates below; narrow the query to --show one",
1412            hits.len()
1413        );
1414    }
1415    for hit in hits {
1416        // highlight the chars the query matched — in the name, the
1417        // filename, and the definition line (great for fuzzy matches)
1418        let name = hl(&hit.name, query, c);
1419        let qualified = match &hit.parent {
1420            Some(p) => format!("{name} · {p}"),
1421            None => name,
1422        };
1423        println!(
1424            "{}:{}  {} {}",
1425            hl_path(&hit.file, query, c),
1426            hit.line,
1427            hit.kind,
1428            qualified
1429        );
1430        if let Some(sig) = &hit.signature {
1431            println!("    {}", hl(sig, query, c));
1432        }
1433        if args.explain {
1434            let parts: Vec<String> = hit
1435                .features
1436                .iter()
1437                .map(|f| format!("{} {:.0}", f.name, f.value))
1438                .collect();
1439            println!(
1440                "    confidence {:.2} · score {:.0} = {}",
1441                hit.confidence,
1442                hit.score,
1443                parts.join(" + ")
1444            );
1445        }
1446    }
1447    None
1448}
1449
1450/// Pick a hit for `--open`: the top match, unless we're on an interactive
1451/// terminal with several — then print a short numbered menu and read a choice
1452/// (empty = the top match). `None` means abort (EOF or unparseable input).
1453fn choose_hit(hits: &[crate::search::Hit]) -> Option<&crate::search::Hit> {
1454    use std::io::{IsTerminal, Write};
1455    if hits.len() == 1 || !std::io::stdin().is_terminal() || !std::io::stderr().is_terminal() {
1456        return hits.first();
1457    }
1458    let mut err = std::io::stderr();
1459    let _ = writeln!(err, "rq: {} matches — pick one (enter = 1):", hits.len());
1460    for (i, h) in hits.iter().enumerate() {
1461        let _ = writeln!(
1462            err,
1463            "  {}. {}:{}  {} {}",
1464            i + 1,
1465            h.file,
1466            h.line,
1467            h.kind,
1468            h.name
1469        );
1470    }
1471    let _ = write!(err, "rq> ");
1472    let _ = err.flush();
1473    let mut line = String::new();
1474    if std::io::stdin().read_line(&mut line).unwrap_or(0) == 0 {
1475        return None; // Ctrl-D
1476    }
1477    parse_choice(&line, hits.len()).and_then(|i| hits.get(i))
1478}
1479
1480/// Resolve a menu reply to a 0-based index: blank → 0 (the top match), `N` → N-1
1481/// when in range, anything else → `None` (abort). Pure, so it's unit-tested.
1482fn parse_choice(input: &str, n: usize) -> Option<usize> {
1483    let s = input.trim();
1484    if s.is_empty() {
1485        return Some(0);
1486    }
1487    let i = s.parse::<usize>().ok()?.checked_sub(1)?;
1488    (i < n).then_some(i)
1489}
1490
1491/// `--open`: choose a hit, record it as a selection so ranking learns, then hand
1492/// off to the editor. The launcher `exec`s (replacing this process), so the shell
1493/// waits on the editor — not on rq's background warm.
1494fn finish_open(
1495    store: &mut Store,
1496    hits: &[crate::search::Hit],
1497    query: &str,
1498    current: Option<i64>,
1499    root: Option<&std::path::Path>,
1500    no_record: bool,
1501) -> ExitCode {
1502    let Some(hit) = choose_hit(hits) else {
1503        return ExitCode::SUCCESS; // aborted at the prompt
1504    };
1505
1506    // Record the pick — same signal as `rq --record`. The hit's path is already
1507    // repo-relative, which is what the selection rollup keys off.
1508    if !no_record {
1509        let _ = store.record_event(
1510            "select",
1511            Some(&query.to_ascii_lowercase()),
1512            current,
1513            Some(&hit.file),
1514            Some(hit.line),
1515            None,
1516        );
1517        deferred_maintenance(store);
1518    }
1519
1520    // Results are repo-root-relative, so resolve against the root — the bare path
1521    // wouldn't open from a subdirectory.
1522    let target = match root {
1523        Some(r) => r.join(&hit.file),
1524        None => PathBuf::from(&hit.file),
1525    };
1526    launch_editor(&target, hit.line)
1527}
1528
1529/// Launch the editor on `file:line`, resolving the command in order: `RQ_OPEN`
1530/// template → VS Code (`code`) → `$VISUAL`/`$EDITOR` → print the location. The
1531/// chosen command replaces this process via `exec`.
1532fn launch_editor(file: &std::path::Path, line: i64) -> ExitCode {
1533    use std::os::unix::process::CommandExt;
1534    let loc = format!("{}:{}", file.display(), line);
1535    match open_command(file, line, &loc) {
1536        Some((prog, args)) => {
1537            // exec returns only on failure
1538            let err = std::process::Command::new(&prog).args(&args).exec();
1539            fail(format_args!("rq --open: cannot run {prog}: {err}"))
1540        }
1541        None => {
1542            println!("{loc}");
1543            ExitCode::SUCCESS
1544        }
1545    }
1546}
1547
1548/// Resolve the editor command + args. `None` → no launcher configured (the
1549/// caller prints the location). `RQ_OPEN` is split on whitespace (no shell) with
1550/// `{file}` / `{line}` / `{}` (= `path:line`) substituted per token.
1551fn open_command(file: &std::path::Path, line: i64, loc: &str) -> Option<(String, Vec<String>)> {
1552    let fstr = file.to_string_lossy().into_owned();
1553
1554    if let Some(t) = std::env::var_os("RQ_OPEN") {
1555        let t = t.to_string_lossy();
1556        let mut parts = t.split_whitespace().map(|p| {
1557            p.replace("{file}", &fstr)
1558                .replace("{line}", &line.to_string())
1559                .replace("{}", loc)
1560        });
1561        if let Some(prog) = parts.next() {
1562            return Some((prog, parts.collect()));
1563        }
1564    }
1565
1566    if on_path("code") {
1567        return Some(("code".into(), vec!["--goto".into(), loc.into()]));
1568    }
1569
1570    if let Some(ed) = std::env::var_os("VISUAL").or_else(|| std::env::var_os("EDITOR")) {
1571        let ed = ed.to_string_lossy().into_owned();
1572        let l = ed.to_ascii_lowercase();
1573        // line-aware launch for the common terminal editors; others just get the file
1574        if ["vim", "nvim", "vi", "nano", "emacs", "kak", "micro"]
1575            .iter()
1576            .any(|e| l.contains(e))
1577        {
1578            return Some((ed, vec![format!("+{line}"), fstr]));
1579        }
1580        return Some((ed, vec![fstr]));
1581    }
1582
1583    None
1584}
1585
1586/// Whether `prog` resolves on `PATH` (a regular file; symlinks followed).
1587fn on_path(prog: &str) -> bool {
1588    std::env::var_os("PATH")
1589        .is_some_and(|paths| std::env::split_paths(&paths).any(|dir| dir.join(prog).is_file()))
1590}
1591
1592/// Whether a complete repo is provably unchanged since its last index — same
1593/// HEAD and a clean work tree — so the deferred re-walk can be skipped. The git
1594/// HEAD + dirty check is cheap (~tens of ms) and authoritative at any size, so
1595/// it gates warming for small and large repos alike: a clean, fully-indexed repo
1596/// has nothing to warm, and re-walking it on every query just to discover that
1597/// wasted a full sweep (~hundreds of ms) per search. Conservative: any
1598/// uncertainty (not complete, non-git / no recorded head, git hiccup) returns
1599/// false, so we warm.
1600/// Seconds since the epoch.
1601fn unix_now() -> i64 {
1602    std::time::SystemTime::now()
1603        .duration_since(std::time::UNIX_EPOCH)
1604        .map(|d| d.as_secs() as i64)
1605        .unwrap_or(0)
1606}
1607
1608/// How long a branch-file list is served before it's refreshed. A commit or a
1609/// checkout is caught by the stamp; a bare working-tree edit touches neither
1610/// `.git/HEAD` nor `.git/index`, so only elapsed time catches that — short
1611/// enough that a burst of searches shares one computation and the edit you just
1612/// made is reflected on the next search.
1613const BRANCH_FILES_TTL_SECS: i64 = 15;
1614
1615/// A branch-file recomputation running alongside the search. The git work
1616/// happens on the thread; the store write waits for the main thread, since a
1617/// SQLite connection isn't shared.
1618struct BranchRefresh {
1619    handle: std::thread::JoinHandle<Vec<String>>,
1620    identity: String,
1621    stamp: String,
1622}
1623
1624impl BranchRefresh {
1625    /// Wait for the recomputation and store it for the next query.
1626    fn store(self, store: &Store) {
1627        let Ok(files) = self.handle.join() else {
1628            return;
1629        };
1630        let _ = store.branch_files_set(&self.identity, &self.stamp, unix_now(), &files);
1631    }
1632}
1633
1634/// The branch-changed file list, served from the store when it's still good.
1635/// Returns the list, plus a recomputation to collect after results print when
1636/// the stored one has aged out.
1637///
1638/// The list feeds a *ranking boost*, so serving a slightly old one costs a
1639/// little ranking quality, while recomputing it first would cost every search
1640/// the git diff behind it — which is O(tracked files). So the stored list is
1641/// served immediately and the refresh runs concurrently with the search rather
1642/// than after it, which usually hides its cost entirely. It feeds only the next
1643/// query, so nothing about this run's ranking depends on how the race lands.
1644///
1645/// The first search in a repo has nothing to serve and computes inline; that's
1646/// once per repo, like the first index.
1647fn cached_branch_files(
1648    store: &Store,
1649    root: &std::path::Path,
1650) -> (Vec<String>, Option<BranchRefresh>) {
1651    let identity = resolve_identity(store, root);
1652    let stamp = crate::index::branch_files_stamp(root);
1653    let cached = store.branch_files_get(&identity).ok().flatten();
1654    let now = unix_now();
1655
1656    if let (Some((cached_stamp, at, files)), Some(stamp)) = (&cached, &stamp) {
1657        if cached_stamp == stamp && now.saturating_sub(*at) < BRANCH_FILES_TTL_SECS {
1658            return (files.clone(), None);
1659        }
1660        let owned_root = root.to_path_buf();
1661        let refresh = BranchRefresh {
1662            handle: std::thread::spawn(move || crate::index::branch_changed_files(&owned_root)),
1663            identity,
1664            stamp: stamp.clone(),
1665        };
1666        return (files.clone(), Some(refresh));
1667    }
1668
1669    // Nothing cached (or nowhere to cache it, e.g. a worktree): compute inline.
1670    let files = crate::index::branch_changed_files(root);
1671    if let Some(stamp) = stamp {
1672        let _ = store.branch_files_set(&identity, &stamp, now, &files);
1673    }
1674    (files, None)
1675}
1676
1677/// Whether the worktree has moved since it was indexed — a different HEAD, or
1678/// uncommitted edits. Split out from the store read so this half can run on its
1679/// own thread: `is_dirty` forks `git status`, which on a large worktree costs
1680/// more than the search it was gating (measured: 12.6ms of a 16.8ms query on a
1681/// 6k-file repo, against 0.1ms on a 54-file one).
1682///
1683/// `None` for `indexed_head` means we never recorded one, which counts as
1684/// changed — there's nothing to compare against, so assume work is due.
1685fn worktree_changed(cwd: &std::path::Path, indexed_head: Option<&str>) -> bool {
1686    let Some(head) = indexed_head else {
1687        return true;
1688    };
1689    crate::index::git_head(cwd).as_deref() != Some(head) || crate::index::is_dirty(cwd)
1690}
1691
1692/// Settle warming once the answer is out: collect the staleness check started
1693/// back at setup, reindex if the worktree moved, and hand any remainder to a
1694/// detached child.
1695///
1696/// Called from *both* exits. The miss path matters as much as the render one —
1697/// a symbol added a moment ago is precisely a miss, and reindexing before we
1698/// exit is what makes the immediate retry hit.
1699#[allow(clippy::too_many_arguments)]
1700fn settle_warm(
1701    store: &Store,
1702    staleness: Option<std::thread::JoinHandle<bool>>,
1703    was_warming: bool,
1704    warming_ok: bool,
1705    root: Option<&std::path::Path>,
1706    active: &[String],
1707    query: &str,
1708    budget: Duration,
1709    no_wait: bool,
1710    identity: Option<&str>,
1711) -> bool {
1712    // A panicked check counts as changed: warming needlessly costs a little
1713    // time, skipping it wrongly serves a stale index.
1714    let changed = staleness.is_some_and(|h| h.join().unwrap_or(true));
1715    // Reindexing an edited worktree means sweeping every file to find the few
1716    // that moved — ~32ms on a 3000-file repo, and it was paid on *every* query
1717    // for as long as anything stayed uncommitted, which is exactly while you're
1718    // working. The shell shouldn't wait for that: hand it to the detached
1719    // child, which is what "the shell never waits on it" already promises
1720    // everywhere else.
1721    //
1722    // With detach off (the harness pins it so no child races a test's cleanup)
1723    // there's nobody to hand it to, so do it here as before.
1724    if changed
1725        && !no_wait
1726        && !warm_detach_enabled()
1727        && let Some(r) = root
1728        && let Ok(mut idx) = open_store()
1729    {
1730        crate::trace!("background warm (deferred, {budget:?}): worktree changed since index");
1731        let _ = crate::index::index_budgeted(&mut idx, r, active, budget, Some(query));
1732    }
1733    maybe_detach_warm(
1734        store,
1735        warming_ok && (was_warming || changed),
1736        changed,
1737        root,
1738        identity,
1739    );
1740    // Report only that work was *deferred*, which is what makes a miss
1741    // provisional. When the reindex ran inline just above (detach off), the
1742    // index is as current as we can make it and a miss is definitive.
1743    changed && warm_detach_enabled()
1744}
1745
1746/// Inline warm budget on the search path. A *cap*, not a fixed delay:
1747/// `index_budgeted` returns the moment a full sweep finishes, so small/medium
1748/// repos index completely and pay only their real cost. The cap only bites a
1749/// genuinely huge, never-indexed repo — where a bigger budget buys a much better
1750/// first answer (a tiny budget can return nothing, since a git repo has no
1751/// live-scan fallback). 500 ms is a one-time cold-cache cost, trivial next to
1752/// scanning a large tree from scratch; the deferred pass and later queries fill
1753/// in the rest.
1754fn answer_warm_budget() -> Duration {
1755    env_budget("RQ_ANSWER_BUDGET_MS", 500)
1756}
1757
1758/// Deferred warm budget, spent after results are printed: larger, to make real
1759/// progress on coverage per query while keeping each invocation snappy.
1760fn deferred_warm_budget() -> Duration {
1761    env_budget("RQ_DEFERRED_BUDGET_MS", 250)
1762}
1763
1764/// Bound for the git-repo live-scan fallback (index empty, still warming): enough
1765/// to surface a result the warm hasn't reached, without an unbounded walk.
1766fn live_fallback_budget() -> Duration {
1767    env_budget("RQ_FALLBACK_BUDGET_MS", 250)
1768}
1769
1770/// Budget for the *detached* warm child — generous, because nothing waits on
1771/// it: the shell got its results and the child runs niced in the background.
1772fn warm_bg_budget() -> Duration {
1773    env_budget("RQ_WARM_BUDGET_MS", 20_000)
1774}
1775
1776/// Whether a search hands leftover warming to a detached child (default) or
1777/// finishes it in-process before exiting (`RQ_WARM_DETACH=0` — used by the
1778/// test harness for hermetic runs, and handy for debugging).
1779fn warm_detach_enabled() -> bool {
1780    std::env::var("RQ_WARM_DETACH").map_or(true, |v| v != "0")
1781}
1782
1783/// How long a query may block indexing a cold repo before giving up with an
1784/// honest "still indexing" rather than a false miss. A generous backstop, not the
1785/// real cost: `index_budgeted` returns the moment the sweep completes, so any
1786/// normal repo finishes well under it, and an interactive run isn't bounded by it
1787/// at all (Ctrl-C escapes). It mainly bounds a programmatic caller on a
1788/// pathologically huge repo — where the partial index still persists for the next
1789/// query. `RQ_WAIT_BUDGET_MS=0` makes a programmatic caller non-blocking again —
1790/// it answers immediately from whatever's already indexed.
1791fn wait_budget() -> Duration {
1792    env_budget("RQ_WAIT_BUDGET_MS", 60_000)
1793}
1794
1795/// Parse a `--wait` value into a duration: `<n>ms`, `<n>s`, `<n>m`, or a bare
1796/// `<n>` (seconds). Fractions are allowed (`1.5s`); `0` (any unit) means "don't
1797/// wait". A `clap` value parser, so an invalid duration is rejected at parse
1798/// time with a usage error.
1799fn parse_wait(s: &str) -> std::result::Result<Duration, String> {
1800    let s = s.trim();
1801    let bad = || format!("invalid duration {s:?} — use e.g. 50ms, 2s, 1m, or 0");
1802    // check "ms" before "s" so the "s" arm doesn't swallow it
1803    let (num, unit_ms) = if let Some(n) = s.strip_suffix("ms") {
1804        (n, 1.0)
1805    } else if let Some(n) = s.strip_suffix('s') {
1806        (n, 1_000.0)
1807    } else if let Some(n) = s.strip_suffix('m') {
1808        (n, 60_000.0)
1809    } else {
1810        // a bare number is seconds
1811        (s, 1_000.0)
1812    };
1813    let val: f64 = num.trim().parse().map_err(|_| bad())?;
1814    if !val.is_finite() || val < 0.0 {
1815        return Err(bad());
1816    }
1817    Ok(Duration::from_millis((val * unit_ms).round() as u64))
1818}
1819
1820/// Set by the SIGINT handler during an interactive cold-start escalation. The
1821/// poll loop and the running index pass watch it, so Ctrl-C stops the wait
1822/// promptly and prints the best partial results instead of killing the process.
1823static INTERRUPTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
1824
1825extern "C" fn on_sigint(_: libc::c_int) {
1826    // Async-signal-safe: a lone relaxed atomic store — no allocation, no locks.
1827    INTERRUPTED.store(true, std::sync::atomic::Ordering::Relaxed);
1828}
1829
1830/// Install the SIGINT handler once. Scoped to the escalation path: a normal fast
1831/// query keeps the default behavior (Ctrl-C kills it outright).
1832fn install_interrupt_handler() {
1833    static ONCE: std::sync::Once = std::sync::Once::new();
1834    ONCE.call_once(|| unsafe {
1835        let mut action: libc::sigaction = std::mem::zeroed();
1836        action.sa_sigaction = on_sigint as *const () as usize;
1837        libc::sigemptyset(&mut action.sa_mask);
1838        libc::sigaction(libc::SIGINT, &action, std::ptr::null_mut());
1839    });
1840}
1841
1842/// Is a human watching stderr? True for a real terminal; `RQ_ASSUME_INTERACTIVE`
1843/// forces it on so the progress/Ctrl-C path is exercisable under test (where
1844/// stderr is a pipe), mirroring the `RQ_*_BUDGET_MS` testing knobs.
1845fn stderr_interactive() -> bool {
1846    std::io::stderr().is_terminal() || std::env::var_os("RQ_ASSUME_INTERACTIVE").is_some()
1847}
1848
1849/// Whether to show the live "indexing…" progress heads-up and handle Ctrl-C
1850/// gracefully while a cold repo blocks — a human watching a plain-text terminal.
1851/// Piped / `--json` / `--ndjson` callers block silently instead (no line to draw,
1852/// no one to interrupt); the *decision to block* is the same for both.
1853fn show_progress(out: Output, interactive: bool) -> bool {
1854    interactive && matches!(out, Output::Text)
1855}
1856
1857/// A short, friendly name for the repo being indexed — its directory name, for
1858/// the progress line.
1859fn repo_label(root: Option<&std::path::Path>) -> String {
1860    root.and_then(|r| r.file_name())
1861        .map(|n| n.to_string_lossy().into_owned())
1862        .unwrap_or_else(|| "repo".into())
1863}
1864
1865/// Redraw the in-place "indexing…" progress line on stderr (kept off stdout so
1866/// piped/`--json` output stays clean). The file count comes from the index the
1867/// background pass is filling, so it climbs as warming proceeds.
1868fn draw_progress(store: &Store, identity: Option<&str>, label: &str) {
1869    let files = identity
1870        .and_then(|id| store.repository_id(id).ok().flatten())
1871        .and_then(|rid| store.repo_totals(rid).ok())
1872        .map_or(0, |(f, _)| f);
1873    eprint!("\r\x1b[Krq: indexing {label}… {files} files");
1874    let _ = std::io::stderr().flush();
1875}
1876
1877/// Erase the progress line so results print to a clean terminal.
1878fn clear_progress() {
1879    eprint!("\r\x1b[K");
1880    let _ = std::io::stderr().flush();
1881}
1882
1883/// Read a budget (milliseconds) from an env var, else the default. The env knobs
1884/// exist mainly for testing — a tiny budget reproduces large-repo warming
1885/// behavior on a small repo.
1886fn env_budget(var: &str, default_ms: u64) -> Duration {
1887    let ms = std::env::var(var)
1888        .ok()
1889        .and_then(|v| v.parse().ok())
1890        .unwrap_or(default_ms);
1891    Duration::from_millis(ms)
1892}
1893
1894/// How many events to roll up per interaction. Bounded so the deferred pass
1895/// after a command stays quick.
1896const AGGREGATE_BATCH: usize = 256;
1897
1898/// Recent raw events to retain after rollup (enough for repeat detection); the
1899/// rest, once aggregated, are pruned to keep the log from growing unbounded.
1900const KEEP_RECENT_EVENTS: i64 = 200;
1901
1902/// The bounded background work run after a user interaction, once results are
1903/// out: roll new events into the learning rollup, then prune the raw log.
1904fn deferred_maintenance(store: &mut Store) {
1905    let _ = store.aggregate_events(AGGREGATE_BATCH);
1906    let _ = store.prune_events(KEEP_RECENT_EVENTS);
1907}
1908
1909/// Hook entry point: record that `file` was opened/selected for `query`, then
1910/// amortize a chunk of event aggregation.
1911fn cmd_record(kind: &str, query: Option<&str>, file: &str, line: Option<i64>) -> ExitCode {
1912    let mut store = match open_store() {
1913        Ok(s) => s,
1914        Err(e) => return fail(format_args!("rq: cannot open database: {e}")),
1915    };
1916    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
1917    let identity = crate::index::detect_identity(&cwd).to_string();
1918    let repo_id = store.repository_id(&identity).ok().flatten();
1919
1920    // Store the path repo-relative so the rollup can resolve it against indexed
1921    // files.
1922    let rel = match repo_id.and_then(|id| store.checkout_root(id).ok().flatten()) {
1923        Some(root) => repo_relative(std::path::Path::new(&root), &cwd, file),
1924        None => file.to_string(),
1925    };
1926    let query_norm = query.map(|q| q.to_ascii_lowercase());
1927
1928    if let Err(e) = store.record_event(kind, query_norm.as_deref(), repo_id, Some(&rel), line, None)
1929    {
1930        return fail(format_args!("rq record: {e}"));
1931    }
1932    deferred_maintenance(&mut store);
1933    ExitCode::SUCCESS
1934}
1935
1936/// Candidate on-disk roots that may hold a hit's file, most-current first: every
1937/// checkout root recorded for the repo (newest first), then the cwd (for live
1938/// results, and as a fallback when the stored root is stale — a moved repo keeps
1939/// its old checkout row, and reading from that path fails). Callers read from the
1940/// first candidate that actually has the file.
1941fn hit_file_roots(
1942    store: &Store,
1943    repo_identity: &str,
1944    cwd: Option<&std::path::Path>,
1945) -> Vec<PathBuf> {
1946    let mut roots: Vec<PathBuf> = store
1947        .repository_id(repo_identity)
1948        .ok()
1949        .flatten()
1950        .map(|id| store.checkout_roots(id).unwrap_or_default())
1951        .unwrap_or_default()
1952        .into_iter()
1953        .map(PathBuf::from)
1954        .collect();
1955    if let Some(c) = cwd {
1956        let c = c.to_path_buf();
1957        if !roots.contains(&c) {
1958            roots.push(c);
1959        }
1960    }
1961    roots
1962}
1963
1964/// The definition's source line (trimmed) for a hit — read from the first
1965/// candidate root that has the file (see [`hit_file_roots`]). Best-effort.
1966fn read_signature(
1967    store: &Store,
1968    repo_identity: &str,
1969    file: &str,
1970    line: i64,
1971    cwd: Option<&std::path::Path>,
1972) -> Option<String> {
1973    hit_file_roots(store, repo_identity, cwd)
1974        .into_iter()
1975        .find_map(|root| signature_in(&std::fs::read_to_string(root.join(file)).ok()?, line))
1976}
1977
1978/// Confidence at or above which `--show` prints a body instead of a list. Exact
1979/// (1.0) and a unique prefix (0.9) clear it; a fuzzy or tied match does not — so
1980/// `--show` never prints a definition it isn't sure about.
1981const SHOW_CONFIDENCE: f64 = 0.85;
1982
1983/// `--show`: if the top hit is confident, read and print its full source span
1984/// and return the exit code; otherwise return `None` to fall through to the
1985/// ranked list. Emits a single object in JSON/NDJSON (with a `body` field).
1986///
1987/// Printing the body *is* the selection — the caller asked for one definition
1988/// and consumed exactly this one — so it records the same signal `--open` does,
1989/// no follow-up call needed. Unlike a ranked list, there was no choice left to
1990/// the caller, and unlike a bare search, rq observed what was taken.
1991fn show_top_definition(
1992    store: &mut Store,
1993    hits: &mut [crate::search::Hit],
1994    query: &str,
1995    out: Output,
1996    cwd: Option<&std::path::Path>,
1997    current: Option<i64>,
1998    no_record: bool,
1999) -> Option<ExitCode> {
2000    let top = hits.first()?;
2001    if top.confidence < SHOW_CONFIDENCE {
2002        return None; // ambiguous / weak — let the caller list candidates
2003    }
2004    let end = top.end_line.unwrap_or(top.line);
2005    let body = read_span(store, &top.repo_identity, &top.file, top.line, end, cwd);
2006    hits[0].body = body;
2007    let top = &hits[0];
2008    let shown = (top.file.clone(), top.line);
2009    let code = match out {
2010        Output::Json | Output::Ndjson => {
2011            // fail loudly on a serialize error, like every other JSON path
2012            emit_json(out, top)
2013        }
2014        Output::Text => {
2015            let color = match_color();
2016            let c = color.as_deref();
2017            let name = hl(&top.name, query, c);
2018            let qualified = match &top.parent {
2019                Some(p) => format!("{name} · {p}"),
2020                None => name,
2021            };
2022            println!(
2023                "{}:{}  {} {}",
2024                hl_path(&top.file, query, c),
2025                top.line,
2026                top.kind,
2027                qualified
2028            );
2029            match (&top.body, &top.signature) {
2030                (Some(body), _) => println!("{body}"),
2031                // end_line unknown (pre-v4 row) → at least the definition line
2032                (None, Some(sig)) => println!("{sig}"),
2033                (None, None) => {}
2034            }
2035            ExitCode::SUCCESS
2036        }
2037    };
2038
2039    // After the output, like every other post-interaction write.
2040    if !no_record {
2041        let (file, line) = shown;
2042        let _ = store.record_event(
2043            "select",
2044            Some(&query.to_ascii_lowercase()),
2045            current,
2046            Some(&file),
2047            Some(line),
2048            None,
2049        );
2050        deferred_maintenance(store);
2051    }
2052    Some(code)
2053}
2054
2055/// The source span `start..=end` (1-based, inclusive) of a hit — the full
2056/// definition body for `--show`. Best-effort, mirroring [`read_signature`].
2057fn read_span(
2058    store: &Store,
2059    repo_identity: &str,
2060    file: &str,
2061    start: i64,
2062    end: i64,
2063    cwd: Option<&std::path::Path>,
2064) -> Option<String> {
2065    hit_file_roots(store, repo_identity, cwd)
2066        .into_iter()
2067        .find_map(|root| span_in(&std::fs::read_to_string(root.join(file)).ok()?, start, end))
2068}
2069
2070/// Lines `start..=end` (1-based, inclusive) of already-read `content`, joined —
2071/// clamped to the file's bounds. `None` if `start` is past the end.
2072fn span_in(content: &str, start: i64, end: i64) -> Option<String> {
2073    let s = usize::try_from(start).ok()?.checked_sub(1)?;
2074    let lines: Vec<&str> = content.lines().collect();
2075    if s >= lines.len() {
2076        return None;
2077    }
2078    let e = usize::try_from(end).ok()?.clamp(s + 1, lines.len());
2079    Some(lines[s..e].join("\n"))
2080}
2081
2082/// The trimmed source line `line` (1-based) of already-read `content`, if
2083/// non-empty — a symbol's definition line. Splitting this out lets `--symbols`
2084/// read one file once instead of re-reading it per symbol.
2085fn signature_in(content: &str, line: i64) -> Option<String> {
2086    let idx = usize::try_from(line).ok()?.checked_sub(1)?;
2087    let l = content.lines().nth(idx)?.trim();
2088    (!l.is_empty()).then(|| l.to_string())
2089}
2090
2091/// One symbol in `rq --symbols` output. Same field names as a search hit
2092/// (`repo`, `signature`) for agent consistency, but no score/features — an
2093/// outline is structural, not ranked.
2094#[derive(serde::Serialize)]
2095struct SymbolOut {
2096    name: String,
2097    kind: String,
2098    language: String,
2099    file: String,
2100    line: i64,
2101    #[serde(skip_serializing_if = "Option::is_none")]
2102    end_line: Option<i64>,
2103    #[serde(skip_serializing_if = "Option::is_none")]
2104    parent: Option<String>,
2105    #[serde(skip_serializing_if = "Option::is_none")]
2106    visibility: Option<String>,
2107    repo: String,
2108    #[serde(skip_serializing_if = "Option::is_none")]
2109    signature: Option<String>,
2110}
2111
2112/// `rq --symbols <file>`: list a file's symbols in line order — a structural
2113/// outline, not a ranked search. Warms the file's repo if it's cold/incomplete or
2114/// changed (same gate as search), then reads straight from the index. Honors
2115/// --kind/--lang filters and --json/--ndjson.
2116fn cmd_symbols(file_arg: &str, kinds: &[String], langs: &[String], out: Output) -> ExitCode {
2117    let mut store = match open_store() {
2118        Ok(s) => s,
2119        Err(e) => return fail(format_args!("rq: cannot open database: {e}")),
2120    };
2121    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
2122    let root = crate::index::repo_root(&cwd).unwrap_or_else(|| cwd.clone());
2123    let rel = repo_relative(&root, &cwd, file_arg);
2124
2125    let identity = resolve_identity(&store, &root);
2126    let coverage = store.coverage_status(&identity).ok().flatten();
2127    let warming_ok = crate::index::is_git_repo(&root) || coverage.is_some();
2128    let current = store.repository_id(&identity).ok().flatten();
2129    // Listing a file's symbols warms synchronously — there's no answer to get
2130    // out of the way of here, so the staleness fork is paid inline as before.
2131    let indexed_head = current.and_then(|id| store.indexed_head(id).ok().flatten());
2132    let needs_warm = warming_ok
2133        && (coverage.as_deref() != Some("complete")
2134            || worktree_changed(&root, indexed_head.as_deref()));
2135    if needs_warm {
2136        // Path-prioritize the warm toward the requested file so it indexes first.
2137        let budget = answer_warm_budget() + deferred_warm_budget();
2138        let _ = crate::index::index_budgeted(&mut store, &root, &[], budget, Some(&rel));
2139    }
2140
2141    let Some(repo_id) = store.repository_id(&identity).ok().flatten() else {
2142        return emit_symbols(out, &[]); // unknown / un-indexed repo → nothing
2143    };
2144    let mut rows = match store.symbols_in_file(repo_id, &rel) {
2145        Ok(r) => r,
2146        Err(e) => return fail(format_args!("rq: {e}")),
2147    };
2148    if !kinds.is_empty() {
2149        rows.retain(|r| kinds.iter().any(|k| k == &r.kind));
2150    }
2151    if !langs.is_empty() {
2152        rows.retain(|r| langs.iter().any(|l| l == &r.language));
2153    }
2154
2155    // Read the source once for signatures (every row is the same file), from
2156    // the first root that actually has it (see `hit_file_roots` — a moved repo
2157    // keeps a stale checkout row, so the first-recorded root can be dead).
2158    let content = hit_file_roots(&store, &identity, Some(&root))
2159        .iter()
2160        .find_map(|r| std::fs::read_to_string(r.join(&rel)).ok());
2161    let syms: Vec<SymbolOut> = rows
2162        .into_iter()
2163        .map(|r| SymbolOut {
2164            signature: content.as_deref().and_then(|c| signature_in(c, r.line)),
2165            name: r.name,
2166            kind: r.kind,
2167            language: r.language,
2168            file: r.file,
2169            line: r.line,
2170            end_line: r.end_line,
2171            parent: r.parent,
2172            visibility: r.visibility,
2173            repo: r.repo_identity,
2174        })
2175        .collect();
2176    emit_symbols(out, &syms)
2177}
2178
2179/// Render the outline. Exit 0 if any symbols, non-zero if none — rq's exit-code
2180/// convention, matching how search reports an empty result per format.
2181fn emit_symbols(out: Output, syms: &[SymbolOut]) -> ExitCode {
2182    if syms.is_empty() {
2183        match out {
2184            Output::Json | Output::Ndjson => {
2185                let obj = serde_json::json!({ "status": "no_match" });
2186                let _ = emit_json(out, &obj); // exit code below carries the miss
2187            }
2188            Output::Text => eprintln!("no symbols"),
2189        }
2190        return ExitCode::FAILURE;
2191    }
2192    if let Some(code) = emit_rows(out, syms) {
2193        return code;
2194    }
2195    match out {
2196        Output::Json | Output::Ndjson => {}
2197        Output::Text => {
2198            for s in syms {
2199                let qualified = match &s.parent {
2200                    Some(p) => format!("{} · {p}", s.name),
2201                    None => s.name.clone(),
2202                };
2203                println!("{}:{}  {} {}", s.file, s.line, s.kind, qualified);
2204                if let Some(sig) = &s.signature {
2205                    println!("    {sig}");
2206                }
2207            }
2208        }
2209    }
2210    ExitCode::SUCCESS
2211}
2212
2213/// A leading positional that names a symbol kind — the shorthand behind
2214/// `rq class Foo` and `rq method zoom`. Only the full, unambiguous keyword forms
2215/// count (never the single-letter `-k` shortcuts, which are far likelier to be a
2216/// real query). Returns the canonical kind, so it filters exactly like `--kind`.
2217fn keyword_kind(token: &str) -> Option<&'static str> {
2218    match token.to_ascii_lowercase().as_str() {
2219        "class" => Some("class"),
2220        "module" => Some("module"),
2221        "method" => Some("method"),
2222        "function" | "fn" => Some("function"),
2223        "struct" | "type" => Some("struct"),
2224        "enum" => Some("enum"),
2225        "trait" | "interface" => Some("trait"),
2226        _ => None,
2227    }
2228}
2229
2230/// Peel a leading kind keyword off the query, so `rq class Foo` (or the quoted
2231/// `rq 'class Foo'`) means `-k class` + query `Foo`. The keyword must be followed
2232/// by a real query token — a bare `rq class` stays a search for a symbol literally
2233/// named `class`. Returns `(kind, query, trailing_path_dirs)`; the trailing dirs
2234/// are the rg-style positionals left after the query is consumed.
2235fn split_kind_keyword(
2236    target: String,
2237    dirs: Vec<String>,
2238) -> (Option<&'static str>, String, Vec<String>) {
2239    // Quoted form: the whole thing is one arg (`"class Foo"`), so peel the first
2240    // whitespace-separated word and keep the remainder as the query.
2241    if let Some((head, rest)) = target.split_once(char::is_whitespace) {
2242        let rest = rest.trim();
2243        if let Some(k) = keyword_kind(head)
2244            && !rest.is_empty()
2245        {
2246            return (Some(k), rest.to_string(), dirs);
2247        }
2248    } else if let Some(k) = keyword_kind(&target)
2249        && let Some((query, extra)) = dirs.split_first()
2250    {
2251        // Unquoted form: `rq class Foo` — the next positional is the query.
2252        return (Some(k), query.clone(), extra.to_vec());
2253    }
2254    (None, target, dirs)
2255}
2256
2257/// Normalize a `--kind` value (name or shortcut) to a canonical symbol kind.
2258/// Unknown values pass through lowercased (so they simply match nothing).
2259fn canonical_kind(s: &str) -> Option<&'static str> {
2260    Some(match s.to_ascii_lowercase().as_str() {
2261        "c" | "class" => "class",
2262        "m" | "method" => "method",
2263        "f" | "fn" | "func" | "function" => "function",
2264        "mod" | "module" => "module",
2265        "s" | "struct" | "type" => "struct",
2266        "e" | "enum" => "enum",
2267        "t" | "trait" | "interface" => "trait",
2268        _ => return None,
2269    })
2270}
2271
2272/// Expand a `--lang` value to the language tag(s) it selects: a **prefix** of any
2273/// known language name (so `r` → ruby+rust, `p`/`py` → python, `g` → go,
2274/// `t` → typescript, `j` → javascript), plus a few non-prefix aliases
2275/// (`rb`→ruby, `rs`→rust, `golang`→go, `ts`/`tsx`→typescript,
2276/// `js`/`jsx`→javascript). An unknown value passes through lowercased so it
2277/// simply matches nothing.
2278fn canonical_langs(s: &str) -> Vec<String> {
2279    let t = s.to_ascii_lowercase();
2280    let alias = match t.as_str() {
2281        "rb" => Some("ruby"),
2282        "rs" => Some("rust"),
2283        "golang" => Some("go"),
2284        "ts" | "tsx" => Some("typescript"),
2285        "js" | "jsx" => Some("javascript"),
2286        _ => None,
2287    };
2288    let matched: Vec<String> = crate::lang::languages()
2289        .into_iter()
2290        .filter(|lang| alias == Some(*lang) || lang.starts_with(&t))
2291        .map(str::to_string)
2292        .collect();
2293    matched
2294}
2295
2296/// The ANSI SGR code for highlighting matches, or `None` to disable color.
2297/// Off unless stdout is a terminal; honors `NO_COLOR`; takes the match style
2298/// from `GREP_COLORS` (`mt`/`ms`) when set, else grep's default bold red.
2299fn match_color() -> Option<String> {
2300    if std::env::var_os("NO_COLOR").is_some() || !std::io::stdout().is_terminal() {
2301        return None;
2302    }
2303    let style = std::env::var("GREP_COLORS").ok().and_then(|gc| {
2304        gc.split(':').find_map(|e| {
2305            e.strip_prefix("mt=")
2306                .or_else(|| e.strip_prefix("ms="))
2307                .filter(|v| !v.is_empty())
2308                .map(str::to_string)
2309        })
2310    });
2311    Some(style.unwrap_or_else(|| "1;31".to_string()))
2312}
2313
2314/// Highlight the chars of `text` that `query` matched (no-op when `color` is
2315/// `None`, e.g. piped output).
2316fn hl(text: &str, query: &str, color: Option<&str>) -> String {
2317    match color {
2318        Some(c) => highlight(text, &crate::search::match_positions(query, text), c),
2319        None => text.to_string(),
2320    }
2321}
2322
2323/// Like [`hl`], but only over a path's filename — so matched chars light up in
2324/// `payrolls_controller.rb`, not scattered across the directory parts.
2325fn hl_path(path: &str, query: &str, color: Option<&str>) -> String {
2326    let Some(c) = color else {
2327        return path.to_string();
2328    };
2329    let base_byte = path.rfind('/').map(|b| b + 1).unwrap_or(0);
2330    let base_start = path[..base_byte].chars().count();
2331    // align on the filename *stem* (drop the extension), the same string the
2332    // scorer matched — so the query can't straggle into `.rb` instead of lighting
2333    // up the logical name (`employees_controller`)
2334    let stem = crate::search::path_stem(path);
2335    let positions: Vec<usize> = crate::search::match_positions(query, stem)
2336        .into_iter()
2337        .map(|p| p + base_start)
2338        .collect();
2339    highlight(path, &positions, c)
2340}
2341
2342/// Wrap the matched character positions of `text` in an ANSI color run.
2343/// Consecutive matched chars share one escape sequence.
2344fn highlight(text: &str, positions: &[usize], color: &str) -> String {
2345    if positions.is_empty() {
2346        return text.to_string();
2347    }
2348    let matched: std::collections::HashSet<usize> = positions.iter().copied().collect();
2349    let mut out = String::new();
2350    let mut on = false;
2351    for (i, c) in text.chars().enumerate() {
2352        match (matched.contains(&i), on) {
2353            (true, false) => {
2354                out.push_str("\x1b[");
2355                out.push_str(color);
2356                out.push('m');
2357                on = true;
2358            }
2359            (false, true) => {
2360                out.push_str("\x1b[0m");
2361                on = false;
2362            }
2363            _ => {}
2364        }
2365        out.push(c);
2366    }
2367    if on {
2368        out.push_str("\x1b[0m");
2369    }
2370    out
2371}
2372
2373/// Whether a repo-relative `file` sits under one of the `--path` directories
2374/// (prefix match on a path boundary). `app/services` matches
2375/// `app/services/refund.rb` but not `app/services_old/x.rb`.
2376fn under_any(file: &str, paths: &[String]) -> bool {
2377    paths.iter().any(|p| {
2378        let p = p.trim_start_matches("./").trim_end_matches('/');
2379        p.is_empty() || file == p || file.starts_with(&format!("{p}/"))
2380    })
2381}
2382
2383/// Resolve a possibly-absolute or cwd-relative path to a repo-relative one.
2384fn repo_relative(root: &std::path::Path, cwd: &std::path::Path, file: &str) -> String {
2385    let p = std::path::Path::new(file);
2386    let abs = if p.is_absolute() {
2387        p.to_path_buf()
2388    } else {
2389        cwd.join(p)
2390    };
2391    let abs = abs.canonicalize().unwrap_or(abs);
2392    abs.strip_prefix(root)
2393        .map(|r| r.to_string_lossy().into_owned())
2394        .unwrap_or_else(|_| file.to_string())
2395}
2396
2397/// Revalidate the files behind the top hits against disk, refreshing any that
2398/// changed and forgetting any that were deleted. Returns true if anything
2399/// changed (so the caller re-runs the search).
2400fn revalidate_top(store: &mut Store, hits: &[crate::search::Hit]) -> bool {
2401    use std::collections::HashSet;
2402    let mut seen = HashSet::new();
2403    let mut changed = false;
2404    for hit in hits {
2405        if !seen.insert((hit.repo_identity.clone(), hit.file.clone())) {
2406            continue;
2407        }
2408        let Some(repo_id) = store.repository_id(&hit.repo_identity).ok().flatten() else {
2409            continue;
2410        };
2411        let Some(root) = store.checkout_root(repo_id).ok().flatten() else {
2412            continue;
2413        };
2414        if let Ok(crate::index::Refresh::Updated) =
2415            crate::index::refresh_file(store, repo_id, std::path::Path::new(&root), &hit.file)
2416        {
2417            changed = true;
2418        }
2419    }
2420    changed
2421}
2422
2423/// The repository's normalized identity for `cwd`, cache-first: look it up by
2424/// the canonical cwd (the checkout root indexing records), so a known repo (git
2425/// or explicitly `--index`ed) costs no `git` fork. On a cache miss, a non-git
2426/// dir resolves to its `local:` path directly (still no fork); only a git work
2427/// tree we haven't seen yet pays a `git remote` call.
2428fn resolve_identity(store: &Store, cwd: &std::path::Path) -> String {
2429    if let Ok(canon) = cwd.canonicalize() {
2430        if let Ok(Some(identity)) = store.identity_for_root(&canon.to_string_lossy()) {
2431            return identity;
2432        }
2433        if crate::index::repo_root(cwd).is_none() {
2434            return crate::core::RepoIdentity::local(&canon.to_string_lossy()).to_string();
2435        }
2436    }
2437    crate::index::detect_identity(cwd).to_string()
2438}
2439
2440fn cmd_index(path: Option<PathBuf>, subdirs: &[String], out: Output) -> ExitCode {
2441    let explicit = path.is_some();
2442    let target = path.unwrap_or_else(|| PathBuf::from("."));
2443    // Normalize to the repo root: the index is repo-root-relative, so indexing
2444    // from a subdirectory must still key off the root (a subdir-relative index
2445    // would mismatch a later search and get reconciled away). `--path` scopes a
2446    // subset; outside git the target is used as-is.
2447    let root = crate::index::repo_root(&target).unwrap_or_else(|| target.clone());
2448    // An explicit TARGET *inside* the repo scopes the index to that subtree — the
2449    // user pointed at a subdir, not the whole repo, and shouldn't pay to walk
2450    // everything. Folded in alongside any `--path` subdirs. (A bare `rq --index`
2451    // with no target still walks the whole repo.)
2452    let mut subdirs = subdirs.to_vec();
2453    if explicit
2454        && let (Ok(t), Ok(r)) = (target.canonicalize(), root.canonicalize())
2455        && t != r
2456        && let Ok(rel) = t.strip_prefix(&r)
2457        && !rel.as_os_str().is_empty()
2458    {
2459        subdirs.push(rel.to_string_lossy().into_owned());
2460    }
2461    let mut store = match open_store() {
2462        Ok(s) => s,
2463        Err(e) => return fail(format_args!("rq: cannot open database: {e}")),
2464    };
2465    let identity = crate::index::detect_identity(&root).to_string();
2466    match crate::index::index_under(&mut store, &root, &subdirs) {
2467        Ok(stats) => {
2468            let subtree = !subdirs.is_empty();
2469            // distinguish this run's incremental work from the index totals
2470            let totals = store
2471                .repository_id(&identity)
2472                .ok()
2473                .flatten()
2474                .and_then(|id| store.repo_totals(id).ok());
2475            match out {
2476                Output::Json | Output::Ndjson => {
2477                    let (files, symbols) = match totals {
2478                        Some((f, s)) => (Some(f), Some(s)),
2479                        None => (None, None),
2480                    };
2481                    return emit_json(
2482                        out,
2483                        &serde_json::json!({
2484                            "repo": identity,
2485                            "scope": if subtree { "subtree" } else { "full" },
2486                            "files_added": stats.files_indexed,
2487                            "symbols_added": stats.symbols,
2488                            "files": files,
2489                            "symbols": symbols,
2490                        }),
2491                    );
2492                }
2493                Output::Text => {
2494                    let scope = if subtree { " (subtree seed)" } else { "" };
2495                    match totals {
2496                        Some((files, symbols)) => println!(
2497                            "{} file(s)/{} symbol(s) added this run; index{scope} now {files} files, {symbols} symbols",
2498                            stats.files_indexed, stats.symbols
2499                        ),
2500                        None => println!(
2501                            "{} file(s)/{} symbol(s) added this run{scope}",
2502                            stats.files_indexed, stats.symbols
2503                        ),
2504                    }
2505                }
2506            }
2507            ExitCode::SUCCESS
2508        }
2509        Err(e) => fail(format_args!("rq --index: {e}")),
2510    }
2511}
2512
2513fn cmd_drop(target: Option<String>, out: Output) -> ExitCode {
2514    let mut store = match open_store() {
2515        Ok(s) => s,
2516        Err(e) => return fail(format_args!("rq: cannot open database: {e}")),
2517    };
2518
2519    // Resolve the repo to drop: TARGET as a path (→ repo root → identity, like
2520    // --index), falling back to TARGET as a literal identity string — so cruft
2521    // shown by --status can be dropped by name even if the checkout is gone.
2522    let path = PathBuf::from(target.clone().unwrap_or_else(|| ".".to_string()));
2523    let root = crate::index::repo_root(&path).unwrap_or(path);
2524    let from_path = crate::index::detect_identity(&root).to_string();
2525    let resolved = match store.repository_id(&from_path) {
2526        Ok(Some(id)) => Some((from_path.clone(), id)),
2527        Ok(None) => target.as_deref().and_then(|s| {
2528            store
2529                .repository_id(s)
2530                .ok()
2531                .flatten()
2532                .map(|id| (s.to_string(), id))
2533        }),
2534        Err(e) => return fail(format_args!("rq --drop: {e}")),
2535    };
2536
2537    let Some((identity, repo_id)) = resolved else {
2538        // nothing to drop — idempotent. `dropped: false` lets a script tell.
2539        return match out {
2540            Output::Text => {
2541                println!("not indexed: {from_path}");
2542                ExitCode::SUCCESS
2543            }
2544            _ => emit_json(
2545                out,
2546                &serde_json::json!({"repo": from_path, "files": 0, "symbols": 0, "dropped": false}),
2547            ),
2548        };
2549    };
2550
2551    let (files, symbols) = store.repo_totals(repo_id).unwrap_or((0, 0));
2552    match store.drop_repository(repo_id) {
2553        Ok(()) => match out {
2554            Output::Text => {
2555                println!("dropped {identity} ({files} file(s), {symbols} symbol(s))");
2556                ExitCode::SUCCESS
2557            }
2558            _ => emit_json(
2559                out,
2560                &serde_json::json!({"repo": identity, "files": files, "symbols": symbols, "dropped": true}),
2561            ),
2562        },
2563        Err(e) => fail(format_args!("rq --drop: {e}")),
2564    }
2565}
2566
2567/// Print a single value as JSON: `--json` pretty, `--ndjson` compact one-liner.
2568/// Used by the single-object operations (`--index`, `--drop`) and the
2569/// no-match status objects; [`emit_rows`] is the multi-row twin.
2570fn emit_json<T: serde::Serialize>(out: Output, value: &T) -> ExitCode {
2571    let rendered = if out == Output::Json {
2572        serde_json::to_string_pretty(value)
2573    } else {
2574        serde_json::to_string(value)
2575    };
2576    match rendered {
2577        Ok(s) => {
2578            println!("{s}");
2579            ExitCode::SUCCESS
2580        }
2581        Err(e) => fail(format_args!("rq: {e}")),
2582    }
2583}
2584
2585/// Print a row set as structured output: `--json` one pretty array, `--ndjson`
2586/// one compact object per line. Returns `Some(exit)` on a serialization
2587/// failure, `None` on success (Text output is the caller's business).
2588fn emit_rows<T: serde::Serialize>(out: Output, rows: &[T]) -> Option<ExitCode> {
2589    match out {
2590        Output::Json => match serde_json::to_string_pretty(rows) {
2591            Ok(s) => println!("{s}"),
2592            Err(e) => return Some(fail(format_args!("rq: {e}"))),
2593        },
2594        Output::Ndjson => {
2595            for r in rows {
2596                match serde_json::to_string(r) {
2597                    Ok(line) => println!("{line}"),
2598                    Err(e) => return Some(fail(format_args!("rq: {e}"))),
2599                }
2600            }
2601        }
2602        Output::Text => {}
2603    }
2604    None
2605}
2606
2607fn cmd_status(out: Output) -> ExitCode {
2608    let store = match open_store() {
2609        Ok(s) => s,
2610        Err(e) => return fail(format_args!("rq: cannot open database: {e}")),
2611    };
2612    let rows = match store.coverage_overview() {
2613        Ok(rows) => rows,
2614        Err(e) => return fail(format_args!("rq --status: {e}")),
2615    };
2616    if let Some(code) = emit_rows(out, &rows) {
2617        return code;
2618    }
2619    match out {
2620        Output::Json | Output::Ndjson => {}
2621        Output::Text if rows.is_empty() => {
2622            println!("no repositories indexed yet (try `rq --index`)");
2623        }
2624        Output::Text => {
2625            for r in &rows {
2626                println!(
2627                    "{:<10} {:>6} files  {:>7} symbols  {}",
2628                    r.status, r.files, r.symbols, r.identity
2629                );
2630            }
2631        }
2632    }
2633    ExitCode::SUCCESS
2634}
2635
2636/// `--usage`: how rq has actually been called, by day, caller, and flag set.
2637/// Reads `usage_daily`, which outlives the pruned raw event log.
2638fn cmd_usage(out: Output) -> ExitCode {
2639    let store = match open_store() {
2640        Ok(s) => s,
2641        Err(e) => return fail(format_args!("rq: cannot open database: {e}")),
2642    };
2643    let rows = match store.usage_overview() {
2644        Ok(rows) => rows,
2645        Err(e) => return fail(format_args!("rq --usage: {e}")),
2646    };
2647    if let Some(code) = emit_rows(out, &rows) {
2648        return code;
2649    }
2650    match out {
2651        Output::Json | Output::Ndjson => {}
2652        Output::Text if rows.is_empty() => {
2653            println!("no usage recorded yet");
2654        }
2655        Output::Text => {
2656            // Columns of bare numbers need naming; `--status` gets away without
2657            // a header because its columns carry their own units.
2658            println!(
2659                "{:<10}  {:<16} {:>6} {:>7} {:>8}  flags",
2660                "day", "caller", "found", "missed", "warming"
2661            );
2662            for r in &rows {
2663                let flags = if r.flags.is_empty() { "-" } else { &r.flags };
2664                println!(
2665                    "{:<10}  {:<16} {:>6} {:>7} {:>8}  {}",
2666                    r.day,
2667                    r.source,
2668                    r.searches - r.misses - r.warming,
2669                    r.misses,
2670                    r.warming,
2671                    flags
2672                );
2673            }
2674            let searches: i64 = rows.iter().map(|r| r.searches).sum();
2675            let misses: i64 = rows.iter().map(|r| r.misses).sum();
2676            let warming: i64 = rows.iter().map(|r| r.warming).sum();
2677            let complete: i64 = rows.iter().map(|r| r.on_complete).sum();
2678            let plural = if searches == 1 { "search" } else { "searches" };
2679            // Counts, not a percentage: these totals are often small enough
2680            // that a percentage would read as more evidence than there is.
2681            println!(
2682                "{searches} {plural} · {misses} missed · {warming} asked too early · {complete} on a complete index"
2683            );
2684        }
2685    }
2686    // Nothing recorded is the "nothing happened" case, like an empty --status.
2687    if rows.is_empty() {
2688        return ExitCode::from(1);
2689    }
2690    ExitCode::SUCCESS
2691}
2692
2693/// Open the rq database, honoring `RQ_DB` and creating parent dirs.
2694fn open_store() -> Result<Store, Box<dyn std::error::Error>> {
2695    let path = db_path()?;
2696    if let Some(parent) = path.parent() {
2697        std::fs::create_dir_all(parent)?;
2698    }
2699    Ok(Store::open(&path)?)
2700}
2701
2702/// Resolve the database path: `$RQ_DB`, else `$HOME/.local/share/rq/rq.db`.
2703fn db_path() -> Result<PathBuf, Box<dyn std::error::Error>> {
2704    if let Ok(p) = std::env::var("RQ_DB") {
2705        return Ok(PathBuf::from(p));
2706    }
2707    let home = std::env::var("HOME")?;
2708    Ok(PathBuf::from(home).join(".local/share/rq/rq.db"))
2709}
2710
2711fn fail(args: std::fmt::Arguments) -> ExitCode {
2712    eprintln!("{args}");
2713    ExitCode::FAILURE
2714}
2715
2716#[cfg(test)]
2717mod tests {
2718    use super::*;
2719
2720    #[test]
2721    fn open_menu_choice_parsing() {
2722        // blank reply takes the top match; a valid number maps to its index
2723        assert_eq!(parse_choice("\n", 5), Some(0));
2724        assert_eq!(parse_choice("  ", 5), Some(0));
2725        assert_eq!(parse_choice("3", 5), Some(2));
2726        assert_eq!(parse_choice("5", 5), Some(4));
2727        // out of range, zero, or non-numeric aborts
2728        assert_eq!(parse_choice("6", 5), None);
2729        assert_eq!(parse_choice("0", 5), None);
2730        assert_eq!(parse_choice("q", 5), None);
2731    }
2732
2733    #[test]
2734    fn wait_duration_parsing() {
2735        use std::time::Duration;
2736        // units: ms / s / m, and a bare number is seconds
2737        assert_eq!(parse_wait("50ms"), Ok(Duration::from_millis(50)));
2738        assert_eq!(parse_wait("2s"), Ok(Duration::from_secs(2)));
2739        assert_eq!(parse_wait("1m"), Ok(Duration::from_secs(60)));
2740        assert_eq!(parse_wait("250"), Ok(Duration::from_secs(250)));
2741        // fractions and zero
2742        assert_eq!(parse_wait("1.5s"), Ok(Duration::from_millis(1500)));
2743        assert_eq!(parse_wait("0"), Ok(Duration::ZERO));
2744        assert!(parse_wait("0s").unwrap().is_zero());
2745        // surrounding whitespace is tolerated
2746        assert_eq!(parse_wait(" 2s "), Ok(Duration::from_secs(2)));
2747        // garbage, empty, and negatives are rejected (a usage error at parse time)
2748        assert!(parse_wait("2x").is_err());
2749        assert!(parse_wait("").is_err());
2750        assert!(parse_wait("s").is_err());
2751        assert!(parse_wait("-1s").is_err());
2752    }
2753
2754    #[test]
2755    fn leading_kind_keyword_becomes_a_kind_filter() {
2756        let d = |s: &[&str]| s.iter().map(|x| x.to_string()).collect::<Vec<_>>();
2757        // unquoted: `rq class Widget` — keyword + next positional is the query
2758        assert_eq!(
2759            split_kind_keyword("class".into(), d(&["Widget"])),
2760            (Some("class"), "Widget".into(), vec![])
2761        );
2762        // quoted: `rq 'method zoom'` — one arg, peel the first word
2763        assert_eq!(
2764            split_kind_keyword("method zoom".into(), vec![]),
2765            (Some("method"), "zoom".into(), vec![])
2766        );
2767        // `fn` is an alias for function; composes with a qualifier tail
2768        assert_eq!(
2769            split_kind_keyword("fn".into(), d(&["Foo::run"])),
2770            (Some("function"), "Foo::run".into(), vec![])
2771        );
2772        // extra positionals after the query stay as rg-style path dirs
2773        assert_eq!(
2774            split_kind_keyword("struct".into(), d(&["Gadget", "src"])),
2775            (Some("struct"), "Gadget".into(), d(&["src"]))
2776        );
2777    }
2778
2779    #[test]
2780    fn a_bare_or_non_keyword_query_is_left_alone() {
2781        let d = |s: &[&str]| s.iter().map(|x| x.to_string()).collect::<Vec<_>>();
2782        // a keyword with no following query token is a search for that literal name
2783        assert_eq!(
2784            split_kind_keyword("class".into(), vec![]),
2785            (None, "class".into(), vec![])
2786        );
2787        // an ordinary query is untouched, trailing dirs preserved
2788        assert_eq!(
2789            split_kind_keyword("Widget".into(), d(&["app"])),
2790            (None, "Widget".into(), d(&["app"]))
2791        );
2792        // single-letter `-k` shortcuts are NOT keywords here (too query-like)
2793        assert_eq!(
2794            split_kind_keyword("c".into(), d(&["Foo"])),
2795            (None, "c".into(), d(&["Foo"]))
2796        );
2797    }
2798
2799    #[test]
2800    fn a_language_selects_by_prefix_or_alias() {
2801        // a prefix can name more than one language
2802        assert_eq!(canonical_langs("r"), ["ruby", "rust"]);
2803        assert_eq!(canonical_langs("t"), ["typescript"]);
2804        // the names people actually type aren't prefixes of the tag
2805        assert_eq!(canonical_langs("ts"), ["typescript"]);
2806        assert_eq!(canonical_langs("jsx"), ["javascript"]);
2807        assert_eq!(canonical_langs("rb"), ["ruby"]);
2808        // an unknown value matches nothing, so the caller can reject it rather
2809        // than silently filtering every result away
2810        assert!(canonical_langs("COBOL").is_empty());
2811    }
2812
2813    #[test]
2814    fn a_kind_normalizes_language_specific_spellings() {
2815        assert_eq!(canonical_kind("f"), Some("function"));
2816        // TypeScript's spellings land on the shared model's kinds
2817        assert_eq!(canonical_kind("interface"), Some("trait"));
2818        assert_eq!(canonical_kind("type"), Some("struct"));
2819        assert_eq!(canonical_kind("banana"), None);
2820        // …and work as the leading-keyword shorthand too
2821        let d = |s: &[&str]| s.iter().map(|x| x.to_string()).collect::<Vec<_>>();
2822        assert_eq!(
2823            split_kind_keyword("interface".into(), d(&["Renderer"])),
2824            (Some("trait"), "Renderer".into(), vec![])
2825        );
2826    }
2827
2828    #[test]
2829    fn highlight_wraps_matched_runs() {
2830        assert_eq!(
2831            highlight("FooThing", &[0, 1, 2], "1;31"),
2832            "\u{1b}[1;31mFoo\u{1b}[0mThing"
2833        );
2834        // scattered matches get separate runs
2835        assert_eq!(
2836            highlight("FooThing", &[0, 3], "1"),
2837            "\u{1b}[1mF\u{1b}[0moo\u{1b}[1mT\u{1b}[0mhing"
2838        );
2839        // nothing matched → unchanged
2840        assert_eq!(highlight("FooThing", &[], "1;31"), "FooThing");
2841    }
2842
2843    #[test]
2844    fn progress_ui_only_for_an_interactive_text_terminal() {
2845        // a person at a terminal, plain text → live progress + graceful Ctrl-C
2846        assert!(show_progress(Output::Text, true));
2847
2848        // machine-readable output blocks silently (no progress line to corrupt it)
2849        assert!(!show_progress(Output::Json, true));
2850        assert!(!show_progress(Output::Ndjson, true));
2851
2852        // not a terminal (a script/agent/pipe) — block, but without the UI
2853        assert!(!show_progress(Output::Text, false));
2854    }
2855
2856    #[test]
2857    fn repo_label_uses_the_directory_name() {
2858        assert_eq!(
2859            repo_label(Some(std::path::Path::new("/src/widgets"))),
2860            "widgets"
2861        );
2862        assert_eq!(repo_label(None), "repo");
2863    }
2864
2865    #[test]
2866    fn hl_path_highlights_the_stem_not_the_extension() {
2867        // matching `employeescontroller`, the highlight covers the logical name in
2868        // the stem and never straggles into `.rb`
2869        let out = hl_path(
2870            "app/employees_controller.rb",
2871            "employeescontroller",
2872            Some("1;31"),
2873        );
2874        assert!(
2875            out.starts_with("app/\u{1b}[1;31memployees"),
2876            "stem highlighted: {out:?}"
2877        );
2878        assert!(
2879            out.ends_with("controller\u{1b}[0m.rb"),
2880            "`.rb` left un-highlighted: {out:?}"
2881        );
2882    }
2883}