srcwalk 0.2.5

Tree-sitter indexed lookups — smart code reading for AI agents
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
use std::io::{self, IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::process;

use clap::{CommandFactory, Parser};
use clap_complete::Shell;

// mimalloc: faster than system allocator for parallel walker workloads
// where many small Strings/Vecs are allocated across rayon threads.
#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;

/// srcwalk — Tree-sitter indexed lookups, smart code reading for AI agents.
/// One tool replaces `read_file`, grep, glob, `ast_grep`, and find.
#[derive(Parser)]
#[command(name = "srcwalk", version, about)]
struct Cli {
    #[command(subcommand)]
    command: Option<Command>,

    /// File path, path:line, symbol name, glob pattern, or text to search.
    query: Option<String>,

    /// Directory to search within or resolve relative paths against.
    #[arg(long, default_value = ".")]
    scope: PathBuf,

    /// Focus line, line range, markdown heading, or symbol (e.g. "45", "45-89", "## Architecture").
    #[arg(long)]
    section: Option<String>,

    /// Max tokens in response. Reduces detail to fit.
    /// Default: 5000 when piped (non-TTY). Unlimited for interactive TTY.
    #[arg(long)]
    budget: Option<u64>,

    /// Disable default budget cap (for piped/scripted usage).
    #[arg(long)]
    no_budget: bool,

    /// Show explicit raw first page (capped at 200 lines / 5k tokens).
    #[arg(long)]
    full: bool,

    /// Treat QUERY as an exact file path. Fails fast instead of falling back to search/glob.
    #[arg(long, conflicts_with_all = ["callers", "callees", "deps", "map", "expand", "glob"])]
    path_exact: bool,

    /// Machine-readable JSON output.
    #[arg(long, conflicts_with = "map")]
    json: bool,

    /// Show source context for top N matches/callers (default: 2 when flag present).
    #[arg(long, num_args = 0..=1, default_missing_value = "2", require_equals = true)]
    expand: Option<usize>,

    /// File pattern filter (e.g. "*.rs", "!*.test.ts", "*.{go,rs}").
    #[arg(long)]
    glob: Option<String>,

    /// Find direct callers as compact facts; use --expand[=N] for source context.
    #[arg(long, conflicts_with_all = ["callees", "deps", "map", "flow", "impact"])]
    callers: bool,

    /// Filter search results or call sites with field:value qualifiers (e.g. path:foo, kind:fn; callers also support args:3 receiver:mgr; flow/detailed callees support callee:NAME).
    #[arg(long, value_name = "QUALIFIERS", conflicts_with = "map")]
    filter: Option<String>,

    /// Count direct caller call sites by field: args, caller, receiver, path, or file.
    #[arg(long, requires = "callers", value_name = "FIELD")]
    count_by: Option<String>,

    /// Show what a symbol calls (forward call graph).
    #[arg(long, conflicts_with_all = ["callers", "deps", "map", "flow", "impact"])]
    callees: bool,

    /// Show ordered call sites with args and assignment context.
    #[arg(long, requires = "callees")]
    detailed: bool,

    /// Depth for --callers/--callees BFS or --map tree. Default map: 3; BFS capped at 5.
    #[arg(long, value_name = "N")]
    depth: Option<usize>,

    /// Max callers to expand per BFS hop (hub guard). Default: 50.
    #[arg(long, value_name = "K", requires = "callers")]
    max_frontier: Option<usize>,

    /// Max total edges across all BFS hops. Default: 500.
    #[arg(long, value_name = "M", requires = "callers")]
    max_edges: Option<usize>,

    /// Comma-separated symbols to skip as BFS frontier (hub guard).
    /// Default: new,clone,from,into,to_string,drop,fmt,default.
    /// Pass empty string "" to disable.
    #[arg(long, value_name = "CSV", requires = "callers")]
    skip_hubs: Option<String>,

    /// Analyze blast-radius dependencies of a file.
    #[arg(long, conflicts_with_all = ["callers", "callees", "map", "flow", "impact"])]
    deps: bool,

    /// Summarize a known symbol's ordered calls, local resolves, and direct callers.
    #[arg(long, conflicts_with_all = ["callers", "callees", "deps", "map", "impact", "expand", "section", "full"])]
    flow: bool,

    /// Summarize definitions, name-matched callers, and receiver/file groups.
    #[arg(long, conflicts_with_all = ["callers", "callees", "deps", "map", "flow", "expand", "section", "full"])]
    impact: bool,

    /// Generate a structural codebase map.
    #[arg(long, conflicts_with_all = ["callers", "callees", "deps", "flow", "impact", "expand", "section", "full"])]
    map: bool,

    /// Include symbol names in --map output.
    #[arg(long, requires = "map")]
    symbols: bool,

    /// Max results. Default: unlimited (or 50 for interactive TTY).
    /// Applies to: symbol/content/regex/callers search and deps dependents.
    /// NOTE: multi-symbol ("A,B,C") applies the limit per-query, not total.
    #[arg(long, value_name = "N")]
    limit: Option<usize>,

    /// Skip N results (for pagination). Use with --limit.
    #[arg(long, value_name = "N", default_value = "0")]
    offset: usize,

    /// Print shell completions for the given shell.
    #[arg(long, value_name = "SHELL")]
    completions: Option<Shell>,
}

#[derive(clap::Subcommand)]
enum Command {
    /// Show the project fingerprint (languages, scale, structural overview).
    Overview,
}

/// Reset SIGPIPE to the OS default on Unix.
///
/// Rust's stdlib masks SIGPIPE to SIG_IGN at startup, which turns broken-pipe
/// into an `EPIPE` error that `println!` converts into a panic. For a CLI that
/// is routinely piped into `head`, `less`, or a truncating UI, that's the wrong
/// default: we want the process to exit silently like every other Unix tool.
#[cfg(unix)]
fn reset_sigpipe() {
    // SAFETY: setting a signal disposition is a standard, thread-safe operation
    // before any threads are spawned.
    unsafe {
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
    }
}

#[cfg(not(unix))]
fn reset_sigpipe() {}

fn main() {
    reset_sigpipe();
    configure_thread_pools();
    let cli = Cli::parse();

    // Shell completions
    if let Some(shell) = cli.completions {
        clap_complete::generate(shell, &mut Cli::command(), "srcwalk", &mut io::stdout());
        return;
    }

    // Subcommands
    if let Some(cmd) = cli.command {
        match cmd {
            Command::Overview => {
                let cwd = std::env::current_dir().unwrap_or_default();
                let output = srcwalk::overview::fingerprint(&cwd);
                if output.is_empty() {
                    eprintln!("No project fingerprint could be generated.");
                    process::exit(1);
                }
                println!("{output}");
            }
        }
        return;
    }

    let is_tty = io::stdout().is_terminal();

    // Effective budget: explicit --budget wins, --no-budget disables,
    // otherwise default 5000 tokens for piped (non-TTY) output.
    let effective_budget = if cli.no_budget {
        None
    } else if cli.budget.is_some() {
        cli.budget
    } else if !is_tty {
        Some(5_000)
    } else {
        None
    };

    // Map mode
    if cli.map {
        let cache = srcwalk::cache::OutlineCache::new();
        let scope = cli.scope.canonicalize().unwrap_or(cli.scope);
        let depth = cli.depth.unwrap_or(3);
        match srcwalk::map::generate(
            &scope,
            depth,
            effective_budget,
            &cache,
            cli.symbols,
            cli.glob.as_deref(),
        ) {
            Ok(output) => emit_output(&output, is_tty),
            Err(e) => {
                eprintln!("{e}");
                process::exit(e.exit_code());
            }
        }
        return;
    }

    // CLI mode: single query
    let query = if let Some(q) = cli.query {
        q
    } else {
        eprintln!("usage: srcwalk <query> [--scope DIR] [--section N-M] [--budget N]");
        process::exit(3);
    };

    let cache = srcwalk::cache::OutlineCache::new();
    let scope = cli.scope.canonicalize().unwrap_or(cli.scope);

    // Smart structural view by default. Use --full for a capped raw first page.
    let full = cli.full;
    let expand = cli.expand.unwrap_or(0);

    // TTY interactive mode: cap at 50 unless user set --limit or --full.
    // Piped / scripted → unlimited so grep/wc/etc. see everything.
    let effective_limit = cli.limit.or({
        if is_tty && !full {
            Some(50)
        } else {
            None
        }
    });

    // Exact file mode: read only this path; never fall back to search/glob.
    if cli.path_exact {
        let result = srcwalk::run_path_exact(
            &query,
            &scope,
            cli.section.as_deref(),
            effective_budget,
            full,
            &cache,
        );
        emit_result(result, &query, cli.json, is_tty);
        return;
    }

    if cli.filter.is_some()
        && (cli.deps || cli.map || cli.path_exact || cli.impact || (cli.callees && !cli.detailed))
    {
        eprintln!("error: --filter applies to search results, direct --callers, --flow, and --callees --detailed");
        process::exit(2);
    }

    // Lab flow mode
    if cli.flow {
        let result = srcwalk::run_flow(
            &query,
            &scope,
            effective_budget,
            &cache,
            cli.depth,
            cli.filter.as_deref(),
        );
        emit_result(result, &query, cli.json, is_tty);
        return;
    }

    // Lab impact mode
    if cli.impact {
        let result = srcwalk::run_impact(&query, &scope, effective_budget, &cache);
        emit_result(result, &query, cli.json, is_tty);
        return;
    }

    // Callers mode
    if cli.callers {
        let bfs_json = cli.json && matches!(cli.depth, Some(d) if d >= 2);
        let result = srcwalk::run_callers(
            &query,
            &scope,
            expand,
            effective_budget,
            effective_limit,
            cli.offset,
            cli.glob.as_deref(),
            &cache,
            cli.depth,
            cli.max_frontier,
            cli.max_edges,
            cli.skip_hubs.as_deref(),
            cli.filter.as_deref(),
            cli.count_by.as_deref(),
            bfs_json,
        );
        if bfs_json {
            // run_callers already returns pretty JSON; skip the generic wrapper.
            match result {
                Ok(s) => println!("{s}"),
                Err(e) => {
                    eprintln!("error: {e}");
                    process::exit(e.exit_code());
                }
            }
            return;
        }
        emit_result(result, &query, cli.json, is_tty);
        return;
    }

    // Callees mode
    if cli.callees {
        let result = srcwalk::run_callees(
            &query,
            &scope,
            effective_budget,
            &cache,
            cli.depth,
            cli.detailed,
            cli.filter.as_deref(),
        );
        emit_result(result, &query, cli.json, is_tty);
        return;
    }

    // Deps mode
    if cli.deps {
        let path = if Path::new(&query).is_absolute() {
            PathBuf::from(&query)
        } else {
            let scope_path = scope.join(&query);
            if scope_path.exists() {
                scope_path
            } else {
                let cwd_path = std::env::current_dir().unwrap_or_default().join(&query);
                if cwd_path.exists() {
                    cwd_path
                } else {
                    scope_path // fall back, let analyze_deps report the error
                }
            }
        };
        let result = srcwalk::run_deps(
            &path,
            &scope,
            effective_budget,
            &cache,
            cli.limit,
            cli.offset,
        );
        emit_result(result, &query, cli.json, is_tty);
        return;
    }

    let result = if expand > 0 {
        srcwalk::run_expanded_filtered(
            &query,
            &scope,
            cli.section.as_deref(),
            effective_budget,
            full,
            expand,
            effective_limit,
            cli.offset,
            cli.glob.as_deref(),
            cli.filter.as_deref(),
            &cache,
        )
    } else if full {
        srcwalk::run_full_filtered(
            &query,
            &scope,
            cli.section.as_deref(),
            effective_budget,
            effective_limit,
            cli.offset,
            cli.glob.as_deref(),
            cli.filter.as_deref(),
            &cache,
        )
    } else {
        srcwalk::run_filtered(
            &query,
            &scope,
            cli.section.as_deref(),
            effective_budget,
            effective_limit,
            cli.offset,
            cli.glob.as_deref(),
            cli.filter.as_deref(),
            &cache,
        )
    };

    emit_result(result, &query, cli.json, is_tty);
}

fn emit_result(
    result: Result<String, srcwalk::error::SrcwalkError>,
    query: &str,
    json: bool,
    is_tty: bool,
) {
    match result {
        Ok(output) => {
            if json {
                let json = serde_json::json!({
                    "query": query,
                    "output": output,
                });
                println!(
                    "{}",
                    serde_json::to_string_pretty(&json)
                        .expect("serde_json::Value is always serializable")
                );
            } else {
                emit_output(&output, is_tty);
            }
        }
        Err(e) => {
            eprintln!("{e}");
            process::exit(e.exit_code());
        }
    }
}

/// Write output to stdout. When TTY and output is long, pipe through $PAGER.
fn emit_output(output: &str, is_tty: bool) {
    let line_count = output.lines().count();
    let term_height = terminal_height();

    if is_tty && line_count > term_height {
        let pager = std::env::var("PAGER").unwrap_or_else(|_| "less".into());
        if let Ok(mut child) = process::Command::new(&pager)
            .arg("-R")
            .stdin(process::Stdio::piped())
            .spawn()
        {
            if let Some(ref mut stdin) = child.stdin.take() {
                let _ = stdin.write_all(output.as_bytes());
            }
            let _ = child.wait();
            return;
        }
    }

    print!("{output}");
    let _ = io::stdout().flush();
}

fn terminal_height() -> usize {
    // Try LINES env var first (set by some shells)
    if let Ok(lines) = std::env::var("LINES") {
        if let Ok(h) = lines.parse::<usize>() {
            return h;
        }
    }
    // Fallback
    24
}

/// Configure rayon global thread pool to limit CPU usage.
///
/// Defaults to min(cores / 2, 6). Override with `SRCWALK_THREADS` env var.
/// This matters for long-lived MCP sessions where back-to-back searches
/// can sustain high CPU (see #27).
fn configure_thread_pools() {
    let num_threads = std::env::var("SRCWALK_THREADS")
        .ok()
        .and_then(|v| v.parse::<usize>().ok())
        .unwrap_or_else(|| {
            std::thread::available_parallelism().map_or(4, |n| (n.get() / 2).clamp(2, 6))
        });

    rayon::ThreadPoolBuilder::new()
        .num_threads(num_threads)
        .build_global()
        .ok();
}