loctree 0.13.0

Structural code intelligence for AI agents. Scan once, query everything.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
//! `loct occurrences <query>` handler — literal exact query scan.
//!
//! Loads (or creates) the snapshot, enumerates its files, reads each file's
//! raw bytes, and reports every literal occurrence of the queried text.
//! Identifier-like queries stay token-boundary aware; phrase/punctuation queries
//! behave as fixed strings. No AST. No fuzz. "Not found" means not found.

use std::path::{Path, PathBuf};

use super::super::super::command::{FindOptions, OccurrencesOptions};
use super::super::{DispatchResult, GlobalOptions, load_or_create_query_snapshot_for_roots};
use crate::analyzer::occurrences::{
    FileScope, OccurrenceResults, ReportOptions, ScanOptions, enrich_with_snapshot,
    scan_files_with, scan_files_with_regex, scan_files_with_scope,
};
use crate::analyzer::search::{FuzzySuggestion, literal_fuzzy_suggestions};
use crate::snapshot::Snapshot;

/// Handle the `occurrences` command directly (does not go through ParsedArgs).
pub fn handle_occurrences_command(
    opts: &OccurrencesOptions,
    global: &GlobalOptions,
) -> DispatchResult {
    let roots: Vec<PathBuf> = if opts.roots.is_empty() {
        vec![PathBuf::from(".")]
    } else {
        opts.roots.clone()
    };

    let query_global = query_global_options(global);
    let snapshot = match load_or_create_query_snapshot_for_roots(&roots, &query_global) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("[loct][error] {}", e);
            return DispatchResult::Exit(1);
        }
    };

    let base = roots.first().cloned().unwrap_or_else(|| PathBuf::from("."));
    let contents = read_snapshot_contents(&snapshot, &base);
    let borrowed = contents
        .iter()
        .map(|(p, c)| (p.as_str(), c.as_str()))
        .collect::<Vec<_>>();
    let mut results = scan_files_with(
        borrowed,
        opts.ident.trim(),
        ScanOptions {
            whole_token: opts.whole_token,
        },
    );
    enrich_with_snapshot(&mut results, &snapshot);
    results.apply_report(ReportOptions {
        group_by_file: opts.group_by_file,
        count_only: opts.count_only,
        offset: opts.offset,
        limit: opts.limit,
    });

    if global.json {
        match serde_json::to_string_pretty(&results) {
            Ok(json) => println!("{}", json),
            Err(e) => {
                eprintln!("[loct][error] Failed to serialize results: {}", e);
                return DispatchResult::Exit(1);
            }
        }
    } else {
        print_human(&results);
    }

    DispatchResult::Exit(0)
}

/// Handle `loct find --literal <query>` — literal truth mode of `find`.
///
/// Built directly on the W1-A occurrences substrate so its primary results are
/// byte-for-byte identical to `loct occurrences`. Fuzzy name-similarity
/// suggestions are computed separately and returned in their own labeled
/// section; they are NEVER promoted into the literal matches. This is what lets
/// an agent trust `--literal` absence: when the mode says literal, the answer
/// is literal, and suggestions stay behind the glass.
pub fn handle_find_literal_command(opts: &FindOptions, global: &GlobalOptions) -> DispatchResult {
    // Resolve the single literal query to scan for. `find` always scopes to `.`.
    let ident = literal_find_ident(opts);
    let ident = match ident {
        Some(id) if !id.trim().is_empty() => id,
        _ => {
            eprintln!(
                "[loct][error] 'find --literal' requires a query. Usage: loct find --literal <query>"
            );
            return DispatchResult::Exit(1);
        }
    };

    let roots = vec![PathBuf::from(".")];
    let query_global = query_global_options(global);
    let snapshot = match load_or_create_query_snapshot_for_roots(&roots, &query_global) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("[loct][error] {}", e);
            return DispatchResult::Exit(1);
        }
    };

    let base = roots.first().cloned().unwrap_or_else(|| PathBuf::from("."));
    let contents = read_snapshot_contents(&snapshot, &base);
    let borrowed = contents
        .iter()
        .map(|(p, c)| (p.as_str(), c.as_str()))
        .collect::<Vec<_>>();

    // PRIMARY: literal truth layer (identical substrate to `loct occurrences`).
    let mut literal_matches = scan_files_with_scope(
        borrowed,
        ident.trim(),
        ScanOptions {
            whole_token: opts.whole_token,
        },
        FileScope {
            file: opts.file.as_deref(),
        },
    );
    enrich_with_snapshot(&mut literal_matches, &snapshot);
    literal_matches.apply_report(ReportOptions {
        group_by_file: opts.group_by_file,
        count_only: opts.count_only,
        offset: opts.offset,
        limit: opts.limit,
    });

    // SECONDARY (strictly separate): fuzzy name-similarity hints, labeled
    // `source: "fuzzy"`. Never merged into `literal_matches`.
    let fuzzy_suggestions = literal_fuzzy_suggestions(ident.trim(), &snapshot.files);

    // A query carrying regex metacharacters could not have been evaluated as a
    // pattern by literal (exact-string) mode. Surfacing this is critical for
    // security/privacy audits: without it, `--literal` hands a confident "absence
    // is trustworthy" clean-bill for a query it never actually pattern-matched.
    let looks_like_regex = query_has_regex_metachars(ident.trim());
    let absence_trustworthy = literal_matches.total > 0 || !looks_like_regex;

    if global.json {
        let payload = serde_json::json!({
            "mode": "literal",
            "query": ident,
            "literal_matches": literal_matches,
            "fuzzy_suggestions": fuzzy_suggestions,
            "literal_trust": {
                "query_has_regex_metachars": looks_like_regex,
                "matched_as_exact_string": true,
                "absence_trustworthy": absence_trustworthy,
            },
        });
        match serde_json::to_string_pretty(&payload) {
            Ok(json) => println!("{}", json),
            Err(e) => {
                eprintln!("[loct][error] Failed to serialize results: {}", e);
                return DispatchResult::Exit(1);
            }
        }
    } else {
        print_literal_find_human(ident.trim(), &literal_matches, &fuzzy_suggestions);
    }

    DispatchResult::Exit(0)
}

/// Handle `loct find --regex <pattern>` — regex over raw file TEXT.
///
/// This is the mode `--literal` could never be: `--literal` is exact-string and,
/// on a query carrying regex metacharacters, can only report "matched as exact
/// string" (loctree-fail.md 2026-06-21 — the dangerous false-clean). `--regex`
/// actually compiles and evaluates the pattern, so a clean result is genuinely
/// trustworthy. It keeps loct's artifact-fence coverage accounting and per-hit
/// context labels (comment / string_literal / code) that the grep/sed fallback
/// cannot give — exactly where verification trust matters most.
pub fn handle_find_regex_command(opts: &FindOptions, global: &GlobalOptions) -> DispatchResult {
    let pattern = literal_find_ident(opts);
    let pattern = match pattern {
        Some(p) if !p.trim().is_empty() => p,
        _ => {
            eprintln!(
                "[loct][error] 'find --regex' requires a pattern. Usage: loct find --regex <pattern>"
            );
            return DispatchResult::Exit(1);
        }
    };

    let re = match regex::Regex::new(pattern.trim()) {
        Ok(re) => re,
        Err(e) => {
            // A failed compile is loud by design: never let a malformed pattern
            // pass as a trustworthy "0 matches".
            eprintln!(
                "[loct][error] invalid --regex pattern '{}': {}",
                pattern.trim(),
                e
            );
            return DispatchResult::Exit(1);
        }
    };

    let roots = vec![PathBuf::from(".")];
    let query_global = query_global_options(global);
    let snapshot = match load_or_create_query_snapshot_for_roots(&roots, &query_global) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("[loct][error] {}", e);
            return DispatchResult::Exit(1);
        }
    };

    let base = roots.first().cloned().unwrap_or_else(|| PathBuf::from("."));
    let contents = read_snapshot_contents(&snapshot, &base);
    let borrowed = contents
        .iter()
        .map(|(p, c)| (p.as_str(), c.as_str()))
        .collect::<Vec<_>>();

    let mut matches = scan_files_with_regex(
        borrowed,
        &re,
        FileScope {
            file: opts.file.as_deref(),
        },
    );
    // No enrich_with_snapshot: a regex pattern is not a symbol name, so symbol
    // resolution against it would be meaningless. Matches stay raw-text truth.
    matches.apply_report(ReportOptions {
        group_by_file: opts.group_by_file,
        count_only: opts.count_only,
        offset: opts.offset,
        limit: opts.limit,
    });

    if global.json {
        let payload = serde_json::json!({
            "mode": "regex",
            "query": pattern,
            "regex_matches": matches,
            "regex_trust": {
                "pattern_compiled": true,
                // The pattern WAS evaluated as a pattern, so unlike --literal a
                // clean result here is a trustworthy absence.
                "absence_trustworthy": true,
            },
        });
        match serde_json::to_string_pretty(&payload) {
            Ok(json) => println!("{}", json),
            Err(e) => {
                eprintln!("[loct][error] Failed to serialize results: {}", e);
                return DispatchResult::Exit(1);
            }
        }
    } else {
        print_regex_find_human(pattern.trim(), &matches);
    }

    DispatchResult::Exit(0)
}

/// Human render for `find --regex`. Mirrors the literal printer's structure
/// (coverage line, per-file rollup, page, per-hit role label) but labels the
/// header as regex and never prints fuzzy suggestions (there are none).
fn print_regex_find_human(pattern: &str, results: &OccurrenceResults) {
    println!(
        "Regex matches of /{}/ ({} in {} file(s)) [source: regex]",
        pattern, results.total, results.files_matched
    );
    if !results.coverage_line.is_empty() {
        println!("  {}", results.coverage_line);
    }
    if results.total == 0 {
        println!("  (not found — pattern evaluated; absence is trustworthy)");
        return;
    }
    print_file_rollup(results);
    print_page(results);
    print_role_summary(results);
    if results.slim {
        println!("  (match list suppressed — count_only/slim)");
        return;
    }
    for occ in &results.occurrences {
        println!(
            "  {}:{}:{}  [{}]  {}",
            occ.file,
            occ.line,
            occ.column,
            occ.match_role.as_str(),
            occ.context
        );
    }
}

/// Detect regex metacharacters that strongly imply the caller meant a *pattern*
/// rather than a literal string. A lone `.` is deliberately EXCLUDED: it is
/// ambiguous (IP addresses like `100.64.0.1`, filenames like `package.json`) and
/// flagging it would flood every legitimate literal query with false warnings.
/// The 2026-06-21 loctree-fail report draws exactly this line — the clean
/// `100.64.0.1` (dots only) versus the dangerous `100\.[0-9]+\.[0-9]+`
/// (backslash, character class, quantifier).
fn query_has_regex_metachars(query: &str) -> bool {
    query.chars().any(|c| {
        matches!(
            c,
            '\\' | '[' | ']' | '(' | ')' | '{' | '}' | '+' | '*' | '?' | '^' | '$' | '|'
        )
    })
}

fn query_global_options(global: &GlobalOptions) -> GlobalOptions {
    let mut scoped = global.clone();
    if !scoped.verbose {
        scoped.quiet = true;
    }
    scoped
}

/// Resolve the query for `find --literal` from a bare positional query,
/// `--symbol`, or the legacy `query` field. Literal mode takes exactly one.
fn literal_find_ident(opts: &FindOptions) -> Option<String> {
    opts.query
        .clone()
        .or_else(|| opts.queries.first().cloned())
        .or_else(|| opts.symbol.clone())
        .or_else(|| opts.similar.clone())
}

/// Read every snapshot file's content (best-effort: skip unreadable files
/// silently — a binary/deleted file is simply not a literal match site).
///
/// Shared by `occurrences` and `find --literal` so both scan the exact same
/// bytes from the exact same file set — the contract that keeps their literal
/// results identical.
fn read_snapshot_contents(snapshot: &Snapshot, base: &Path) -> Vec<(String, String)> {
    let mut contents: Vec<(String, String)> = Vec::new();
    for file in &snapshot.files {
        let resolved = resolve_path(base, &file.path);
        if let Ok(text) = std::fs::read_to_string(&resolved) {
            contents.push((file.path.clone(), text));
        }
    }
    contents
}

/// Resolve a snapshot-relative path against the scan root. Falls back to the
/// raw path if joining does not yield an existing file (e.g. already absolute).
fn resolve_path(base: &Path, rel: &str) -> PathBuf {
    let joined = base.join(rel);
    if joined.exists() {
        return joined;
    }
    let raw = PathBuf::from(rel);
    if raw.exists() {
        return raw;
    }
    joined
}

fn print_human(results: &OccurrenceResults) {
    println!(
        "Literal occurrences of '{}' ({} in {} file(s)) [source: {}]",
        results.query, results.total, results.files_matched, results.source
    );
    if !results.coverage_line.is_empty() {
        println!("  {}", results.coverage_line);
    }
    if results.total == 0 {
        println!("  (not found)");
        print_suggested_next(results);
        return;
    }
    print_file_rollup(results);
    print_page(results);
    print_role_summary(results);
    print_file_context(results);
    if results.slim {
        println!("  (occurrence list suppressed — count_only/slim)");
        print_suggested_next(results);
        return;
    }
    for occ in &results.occurrences {
        let mut suffix = String::new();
        if let Some(definition) = &occ.resolved_definition {
            suffix.push_str(&format!("  => {}", definition.symbol_id));
        }
        if let Some(enclosing) = &occ.enclosing_symbol {
            suffix.push_str(&format!("  in {}", enclosing.symbol_id));
        }
        println!(
            "  {}:{}:{}  [{}]  {}{}",
            occ.file,
            occ.line,
            occ.column,
            occ.match_role.as_str(),
            occ.context,
            suffix
        );
    }
    print_suggested_next(results);
}

/// Render the per-file occurrence rollup, when `group_by_file` populated it.
fn print_file_rollup(results: &OccurrenceResults) {
    if let Some(by_file) = &results.by_file {
        println!("  by file:");
        for fc in by_file {
            println!("    {:>5}  {}", fc.count, fc.file);
        }
    }
}

/// Render page metadata, when `limit`/`offset` pagination populated it.
fn print_page(results: &OccurrenceResults) {
    if let Some(page) = &results.page {
        match page.next_offset {
            Some(next) => println!(
                "  page: offset={}, limit={}, returned={}, next_offset={} (more available)",
                page.offset, page.limit, page.returned, next
            ),
            None => println!(
                "  page: offset={}, limit={}, returned={} (final page)",
                page.offset, page.limit, page.returned
            ),
        }
    }
}

/// Human output for `find --literal`: literal matches as the primary block,
/// then fuzzy suggestions in a clearly-labeled separate section that can never
/// be mistaken for evidence.
fn print_literal_find_human(query: &str, literal: &OccurrenceResults, fuzzy: &[FuzzySuggestion]) {
    let looks_like_regex = query_has_regex_metachars(query);
    println!(
        "=== Literal Matches ({} in {} file(s)) [source: {}] ===",
        literal.total, literal.files_matched, literal.source
    );
    if !literal.coverage_line.is_empty() {
        println!("  {}", literal.coverage_line);
    }
    if literal.total == 0 {
        if looks_like_regex {
            // NOT a trustworthy absence: the query carries regex metacharacters,
            // but `--literal` did an exact-string match and never evaluated it as
            // a pattern. Printing "absence is trustworthy" here would be a FALSE
            // CLEAN for a security/privacy audit.
            println!("  (0 exact-string matches — NOT a trustworthy absence: the query contains");
            println!("   regex metacharacters and `--literal` matches literally, so a pattern was");
            println!("   never evaluated. For a regex search use a pattern-aware tool.)");
        } else {
            println!("  (not found — literal absence is trustworthy)");
        }
    } else {
        if looks_like_regex {
            println!(
                "  (note: matched as an exact string; `--literal` does not evaluate regex metacharacters)"
            );
        }
        print_file_rollup(literal);
        print_page(literal);
        print_role_summary(literal);
        print_file_context(literal);
        if literal.slim {
            println!("  (occurrence list suppressed — count_only/slim)");
        } else {
            for occ in &literal.occurrences {
                let mut suffix = String::new();
                if let Some(definition) = &occ.resolved_definition {
                    suffix.push_str(&format!("  => {}", definition.symbol_id));
                }
                if let Some(enclosing) = &occ.enclosing_symbol {
                    suffix.push_str(&format!("  in {}", enclosing.symbol_id));
                }
                println!(
                    "  {}:{}:{}  [{}]  {}{}",
                    occ.file,
                    occ.line,
                    occ.column,
                    occ.match_role.as_str(),
                    occ.context,
                    suffix
                );
            }
        }
    }
    print_suggested_next(literal);

    // Fuzzy suggestions stay behind the glass: separate header, explicit
    // disclaimer, never folded into the literal block above.
    if !fuzzy.is_empty() {
        println!();
        println!(
            "=== Fuzzy Suggestions ({}) — NOT literal matches, hints only ===",
            fuzzy.len()
        );
        for s in fuzzy {
            match s.line {
                Some(line) => println!(
                    "  ~ {} (score {:.2}) in {}:{}  [source: {}]",
                    s.symbol, s.score, s.file, line, s.source
                ),
                None => println!(
                    "  ~ {} (score {:.2}) in {}  [source: {}]",
                    s.symbol, s.score, s.file, s.source
                ),
            }
        }
    }
}

fn print_suggested_next(results: &OccurrenceResults) {
    if results.suggested_next.is_empty() {
        return;
    }
    println!("  suggested next:");
    for suggestion in &results.suggested_next {
        println!("    {} - {}", suggestion.command, suggestion.reason);
    }
}

/// Render the definition-vs-callsite roll-up. One compact line so an agent sees
/// "is this mostly defined or mostly used here?" without walking every hit.
fn print_role_summary(results: &OccurrenceResults) {
    let Some(summary) = &results.role_summary else {
        return;
    };
    let mut parts = Vec::new();
    if summary.definitions > 0 {
        parts.push(format!("{} definition", summary.definitions));
    }
    if summary.callsites > 0 {
        parts.push(format!("{} callsite", summary.callsites));
    }
    if summary.imports > 0 {
        parts.push(format!("{} import", summary.imports));
    }
    if summary.non_code > 0 {
        parts.push(format!("{} non-code", summary.non_code));
    }
    if summary.other > 0 {
        parts.push(format!("{} other", summary.other));
    }
    if parts.is_empty() {
        return;
    }
    print!("  roles: {}", parts.join(", "));
    if !summary.definition_files.is_empty() {
        print!("  (defs in: {})", summary.definition_files.join(", "));
    }
    println!();
}

/// Render per-file importer/consumer context — the literal hit's blast radius.
fn print_file_context(results: &OccurrenceResults) {
    if results.file_context.is_empty() {
        return;
    }
    println!("  file context:");
    for ctx in &results.file_context {
        let mut line = format!(
            "    {} ({} hit{}, {})",
            ctx.file,
            ctx.hits,
            if ctx.hits == 1 { "" } else { "s" },
            ctx.scope_classification.as_str()
        );
        if !ctx.imported_by.is_empty() {
            line.push_str(&format!("  consumers: {}", ctx.imported_by.join(", ")));
        }
        if !ctx.imports.is_empty() {
            line.push_str(&format!("  deps: {}", ctx.imports.join(", ")));
        }
        if ctx.truncated {
            line.push_str("  (…truncated)");
        }
        println!("{}", line);
    }
}

#[cfg(test)]
mod tests {
    use super::query_has_regex_metachars;

    #[test]
    fn regex_metachars_flag_pattern_queries_but_not_plain_literals() {
        // Regression for the 2026-06-21 loctree-fail report: `--literal` must not
        // claim a "trustworthy absence" for a query it could only exact-match.
        // Pattern-shaped queries (the dangerous false-clean case) must flag true.
        for pattern in [
            r"100\.[0-9]+\.[0-9]+",
            r"/Users/[^/]+/",
            "foo|bar",
            "key.*path",
            "a+b",
            "(group)",
            "name$",
            "^anchor",
        ] {
            assert!(
                query_has_regex_metachars(pattern),
                "pattern-shaped query {pattern:?} must be flagged as regex-like"
            );
        }

        // Plain literals — including dotted IPs/filenames — must NOT flag, or the
        // warning floods every legitimate literal search. This is the exact line
        // the report drew: clean `100.64.0.1` vs dangerous `100\.[0-9]+`.
        for literal in [
            "100.64.0.1",
            "package.json",
            "run_agent_send_with_fallback",
            "BUNDLE_JUNK_EXCLUDES",
            "loctree-mcp",
            "--version",
        ] {
            assert!(
                !query_has_regex_metachars(literal),
                "plain literal {literal:?} must not be flagged as regex-like"
            );
        }
    }
}