reflex/cli/mod.rs
1//! CLI argument parsing and command router
2
3use crate::cache::CacheManager;
4use anyhow::Result;
5use clap::{CommandFactory, Parser, Subcommand};
6use std::path::PathBuf;
7
8mod ask;
9mod deps;
10mod index;
11mod llm;
12mod misc;
13mod pulse;
14mod query;
15mod serve;
16mod snapshot;
17mod watch;
18
19pub use self::query::truncate_preview;
20
21/// Reflex: Local-first, structure-aware code search for AI agents
22#[derive(Parser, Debug)]
23#[command(
24 name = "rfx",
25 version,
26 about = "A fast, deterministic code search engine built for AI",
27 long_about = "Reflex is a local-first, structure-aware code search engine that returns \
28 structured results (symbols, spans, scopes) with sub-100ms latency. \
29 Designed for AI coding agents and automation."
30)]
31pub struct Cli {
32 /// Enable verbose logging (can be repeated for more verbosity)
33 #[arg(short, long, action = clap::ArgAction::Count)]
34 pub verbose: u8,
35
36 /// Answer from the index as it is: do not update a stale index or build a
37 /// missing one first (every command that reads the index does by default)
38 #[arg(long, global = true)]
39 pub no_update: bool,
40
41 #[command(subcommand)]
42 pub command: Option<Command>,
43}
44
45#[derive(Subcommand, Debug)]
46pub enum IndexSubcommand {
47 /// Show background symbol indexing status
48 Status,
49
50 /// Compact the cache by removing deleted files
51 ///
52 /// Removes files from the cache that no longer exist on disk and reclaims
53 /// disk space using SQLite VACUUM. This operation is also performed automatically
54 /// in the background every 24 hours during normal usage.
55 ///
56 /// Examples:
57 /// rfx index compact # Show compaction results
58 /// rfx index compact --json # JSON output
59 Compact {
60 /// Output format as JSON
61 #[arg(long)]
62 json: bool,
63
64 /// Pretty-print JSON output (only with --json)
65 #[arg(long)]
66 pretty: bool,
67 },
68}
69
70#[derive(Subcommand, Debug)]
71pub enum Command {
72 /// Build or update the local code index
73 Index {
74 /// Directory to index (defaults to current directory)
75 #[arg(value_name = "PATH", default_value = ".")]
76 path: PathBuf,
77
78 /// Force a full rebuild even when no file changed
79 #[arg(short, long)]
80 force: bool,
81
82 /// Languages to include (empty = all)
83 #[arg(short, long, value_delimiter = ',')]
84 languages: Vec<String>,
85
86 /// Suppress all output (no progress bar, no summary)
87 #[arg(short, long)]
88 quiet: bool,
89
90 /// Subcommand (status, compact)
91 #[command(subcommand)]
92 command: Option<IndexSubcommand>,
93 },
94
95 /// Query the code index
96 ///
97 /// If no pattern is provided, launches interactive mode (TUI).
98 ///
99 /// Search modes:
100 /// - Default: Word-boundary matching (precise, finds complete identifiers)
101 /// Example: rfx query "Error" → finds "Error" but not "NetworkError"
102 /// Example: rfx query "test" → finds "test" but not "test_helper"
103 ///
104 /// - Symbol search: Word-boundary for text, exact match for symbols
105 /// Example: rfx query "parse" --symbols → finds only "parse" function/class
106 /// Example: rfx query "parse" --kind function → finds only "parse" functions
107 ///
108 /// - Substring search: Expansive matching (opt-in with --contains)
109 /// Example: rfx query "mb" --contains → finds "mb", "kmb_dai_ops", "symbol", etc.
110 ///
111 /// - Regex search: Pattern-controlled matching (opt-in with --regex)
112 /// Example: rfx query "^mb_.*" --regex → finds "mb_init", "mb_start", etc.
113 ///
114 /// Patterns starting with `-` (clap reads them as flags): put them after `--`
115 /// or use --pattern:
116 /// rfx query -- '-> Result<'
117 /// rfx query --pattern '-> Result<'
118 ///
119 /// Interactive mode:
120 /// - Launch with: rfx query
121 /// - Search, filter, and navigate code results in a live TUI
122 /// - Press '?' for help, 'q' to quit
123 Query {
124 /// Search pattern (omit to launch interactive mode)
125 pattern: Option<String>,
126
127 /// Search pattern, as a named flag: for patterns that start with `-`
128 /// (`--pattern '-> Result<'`), so agents never have to reach for `--`
129 #[arg(
130 long = "pattern",
131 value_name = "PATTERN",
132 conflicts_with = "pattern",
133 allow_hyphen_values = true
134 )]
135 pattern_flag: Option<String>,
136
137 /// Search symbol definitions only (functions, classes, etc.)
138 #[arg(short, long)]
139 symbols: bool,
140
141 /// Filter by language
142 /// Supported: rust, python, javascript, typescript, vue, svelte, go, java, php, c, c++, c#, ruby, kotlin, zig
143 #[arg(short, long)]
144 lang: Option<String>,
145
146 /// Filter by symbol kind (implies --symbols)
147 /// Supported: function, class, struct, enum, interface, trait, constant, variable, method, module, namespace, type, macro, property, event, import, export, attribute
148 #[arg(short, long)]
149 kind: Option<String>,
150
151 /// Use AST pattern matching (SLOW: 500ms-2s+, scans all files)
152 ///
153 /// WARNING: AST queries bypass trigram optimization and scan the entire codebase.
154 /// In 95% of cases, use --symbols instead which is 10-100x faster.
155 ///
156 /// When --ast is set, the pattern parameter is interpreted as a Tree-sitter
157 /// S-expression query instead of text search.
158 ///
159 /// RECOMMENDED: Always use --glob to limit scope for better performance.
160 ///
161 /// Examples:
162 /// Fast (2-50ms): rfx query "fetch" --symbols --kind function --lang python
163 /// Slow (500ms-2s): rfx query "(function_definition) @fn" --ast --lang python
164 /// Faster with glob: rfx query "(class_declaration) @class" --ast --lang typescript --glob "src/**/*.ts"
165 #[arg(long)]
166 ast: bool,
167
168 /// Use regex pattern matching
169 ///
170 /// Enables standard regex syntax in the search pattern:
171 /// | for alternation (OR) - NO backslash needed
172 /// . matches any character
173 /// .* matches zero or more characters
174 /// ^ anchors to start of line
175 /// $ anchors to end of line
176 ///
177 /// Examples:
178 /// --regex "belongsTo|hasMany" Match belongsTo OR hasMany
179 /// --regex "^import.*from" Lines starting with import...from
180 /// --regex "fn.*test" Functions containing 'test'
181 ///
182 /// Note: Cannot be combined with --contains (mutually exclusive)
183 #[arg(short = 'r', long)]
184 regex: bool,
185
186 /// Output format as JSON
187 #[arg(long)]
188 json: bool,
189
190 /// Pretty-print JSON output (only with --json)
191 /// By default, JSON is minified to reduce token usage
192 #[arg(long)]
193 pretty: bool,
194
195 /// Print per-phase timings (open, candidates, verify, status, group) to stderr;
196 /// with --json they are included as a `timings` object
197 #[arg(long)]
198 timing: bool,
199
200 /// AI-optimized mode: returns JSON with ai_instruction field
201 /// Implies --json (minified by default, use --pretty for formatted output)
202 /// Provides context-aware guidance to AI agents on response format and next actions
203 #[arg(long)]
204 ai: bool,
205
206 /// Maximum number of results
207 #[arg(short = 'n', long)]
208 limit: Option<usize>,
209
210 /// Pagination offset (skip first N results after sorting)
211 /// Use with --limit for pagination: --offset 0 --limit 10, then --offset 10 --limit 10
212 #[arg(short = 'o', long)]
213 offset: Option<usize>,
214
215 /// Show full symbol definition (entire function/class body)
216 /// Only applicable to symbol searches
217 #[arg(long)]
218 expand: bool,
219
220 /// Filter by file path (supports substring matching)
221 /// Example: --file math.rs or --file helpers/
222 #[arg(short = 'f', long)]
223 file: Option<String>,
224
225 /// Exact symbol name match (no substring matching)
226 /// Only applicable to symbol searches
227 #[arg(long)]
228 exact: bool,
229
230 /// Use substring matching for both text and symbols (expansive search)
231 ///
232 /// Default behavior uses word-boundary matching for precision:
233 /// "Error" matches "Error" but not "NetworkError"
234 ///
235 /// With --contains, enables substring matching (expansive):
236 /// "Error" matches "Error", "NetworkError", "error_handler", etc.
237 ///
238 /// Use cases:
239 /// - Finding partial matches: --contains "partial"
240 /// - When you're unsure of exact names
241 /// - Exploratory searches
242 ///
243 /// Note: Cannot be combined with --regex or --exact (mutually exclusive)
244 #[arg(long)]
245 contains: bool,
246
247 /// Match letters regardless of case (like `rg -i`)
248 ///
249 /// Works with the default whole-identifier search, with --contains and
250 /// with --regex. The literals are still looked up in the trigram index
251 /// under every case variant, so the query costs about the same as a
252 /// case-sensitive one.
253 #[arg(short = 'i', long)]
254 ignore_case: bool,
255
256 /// Also search lock files (Cargo.lock, package-lock.json, *.lock, go.sum)
257 ///
258 /// Lock files are indexed but left out of every search unless asked for.
259 /// `--lang lock` selects them alone.
260 #[arg(long)]
261 include_locks: bool,
262
263 /// Also search generated files (*.pb.go, *.min.js, *.map, *_generated.*)
264 ///
265 /// Judged by name; indexed but left out of every search unless asked for.
266 /// `--lang generated` selects them alone.
267 #[arg(long)]
268 include_generated: bool,
269
270 /// Only show count and timing, not the actual results
271 #[arg(short, long)]
272 count: bool,
273
274 /// Query timeout in seconds (0 = no timeout, default: 30)
275 #[arg(short = 't', long, default_value = "30")]
276 timeout: u64,
277
278 /// Use plain text output (disable colors and syntax highlighting)
279 #[arg(long)]
280 plain: bool,
281
282 /// Include files matching glob pattern (can be repeated)
283 ///
284 /// Patterns follow gitignore rules (like ripgrep -g):
285 /// a pattern containing / is anchored at the index root
286 /// a bare name (*.rs, Makefile) matches at any depth
287 /// ** = recursive match (all subdirectories)
288 /// * = single level match (never crosses /)
289 ///
290 /// Examples:
291 /// --glob src/**/*.rs All .rs files under src/ at the root only
292 /// --glob **/src/**/*.rs All .rs files under any src/ directory
293 /// --glob app/Models/*.php PHP files directly in Models/ (not subdirs)
294 /// --glob tests/**/*_test.go All test files under tests/
295 ///
296 /// Tip: Use --file for simple substring matching instead:
297 /// --file User.php Simpler than --glob **/User.php
298 #[arg(short = 'g', long)]
299 glob: Vec<String>,
300
301 /// Exclude files matching glob pattern (can be repeated)
302 ///
303 /// Same syntax as --glob (** for recursive, * for single level)
304 ///
305 /// Examples:
306 /// --exclude target/** Exclude all files under target/
307 /// --exclude **/*.gen.rs Exclude generated Rust files
308 /// --exclude node_modules/** Exclude npm dependencies
309 #[arg(short = 'x', long)]
310 exclude: Vec<String>,
311
312 /// Return only unique file paths (no line numbers or content)
313 /// Compatible with --json to output ["path1", "path2", ...]
314 #[arg(short = 'p', long)]
315 paths: bool,
316
317 /// Disable smart preview truncation (show full lines)
318 /// By default, previews are truncated to ~100 chars to reduce token usage
319 #[arg(long)]
320 no_truncate: bool,
321
322 /// Number of context lines to show before and after each match (max: 10)
323 /// Example: -C 3 shows 3 lines before and after each match
324 #[arg(short = 'C', long, value_name = "N")]
325 context: Option<usize>,
326
327 /// Return all results (no limit)
328 #[arg(short = 'a', long)]
329 all: bool,
330
331 /// Force execution of potentially expensive queries
332 /// Bypasses broad query detection that prevents queries with:
333 /// • Short patterns (< 3 characters)
334 /// • High candidate counts (> 5,000 files for symbol/AST queries)
335 /// • AST queries without --glob restrictions
336 #[arg(long)]
337 force: bool,
338
339 /// Include dependency information (imports) in results
340 /// Currently only available for Rust files
341 #[arg(long)]
342 dependencies: bool,
343 },
344
345 /// Start a local HTTP API server
346 Serve {
347 /// Port to listen on
348 #[arg(short, long, default_value = "7878")]
349 port: u16,
350
351 /// Host to bind to
352 #[arg(long, default_value = "127.0.0.1")]
353 host: String,
354 },
355
356 /// Show index statistics and cache information
357 Stats {
358 /// Output format as JSON
359 #[arg(long)]
360 json: bool,
361
362 /// Pretty-print JSON output (only with --json)
363 #[arg(long)]
364 pretty: bool,
365 },
366
367 /// Clear the local cache
368 Clear {
369 /// Skip confirmation prompt
370 #[arg(short, long)]
371 yes: bool,
372 },
373
374 /// List all indexed files
375 ListFiles {
376 /// Output format as JSON
377 #[arg(long)]
378 json: bool,
379
380 /// Pretty-print JSON output (only with --json)
381 #[arg(long)]
382 pretty: bool,
383
384 /// Filter by language (e.g. rust, python, typescript)
385 #[arg(short, long)]
386 lang: Option<String>,
387
388 /// Include files matching glob pattern (can be repeated)
389 /// Example: --glob "src/**/*.rs"
390 #[arg(short = 'g', long)]
391 glob: Vec<String>,
392 },
393
394 /// Watch for file changes and auto-reindex
395 ///
396 /// Continuously monitors the workspace for changes and automatically
397 /// reindexes after the debounce period. Useful for IDE integrations and
398 /// keeping the index always fresh during active development.
399 ///
400 /// The debounce timer resets on every file change, batching rapid edits
401 /// (e.g., multi-file refactors, format-on-save) into a single reindex.
402 Watch {
403 /// Directory to watch (defaults to current directory)
404 #[arg(value_name = "PATH", default_value = ".")]
405 path: PathBuf,
406
407 /// Debounce duration in milliseconds (default: 15000 = 15s)
408 /// Waits this long after the last change before reindexing
409 /// Valid range: 5000-30000 (5-30 seconds)
410 #[arg(short, long, default_value = "15000")]
411 debounce: u64,
412
413 /// Suppress output (only log errors)
414 #[arg(short, long)]
415 quiet: bool,
416 },
417
418 /// Start MCP server for AI agent integration
419 ///
420 /// Runs Reflex as a Model Context Protocol (MCP) server using stdio transport.
421 /// This command is automatically invoked by MCP clients like Claude Code and
422 /// should not be run manually.
423 ///
424 /// Register with Claude Code: `claude mcp add --scope user reflex -- rfx mcp`
425 /// Equivalent JSON (`.mcp.json` or another client's MCP config):
426 /// {
427 /// "mcpServers": {
428 /// "reflex": {
429 /// "type": "stdio",
430 /// "command": "rfx",
431 /// "args": ["mcp"]
432 /// }
433 /// }
434 /// }
435 Mcp,
436
437 /// Analyze codebase structure and dependencies
438 ///
439 /// Perform graph-wide dependency analysis to understand code architecture.
440 /// By default, shows a summary report with counts. Use specific flags for
441 /// detailed results.
442 ///
443 /// Examples:
444 /// rfx analyze # Summary report
445 /// rfx analyze --circular # Find cycles
446 /// rfx analyze --hotspots # Most-imported files
447 /// rfx analyze --hotspots --min-dependents 5 # Filter by minimum
448 /// rfx analyze --unused # Orphaned files
449 /// rfx analyze --islands # Disconnected components
450 /// rfx analyze --hotspots --count # Just show count
451 /// rfx analyze --circular --glob "src/**" # Limit to src/
452 Analyze {
453 /// Show circular dependencies
454 #[arg(long)]
455 circular: bool,
456
457 /// Show most-imported files (hotspots)
458 #[arg(long)]
459 hotspots: bool,
460
461 /// Minimum number of dependents for hotspots (default: 2)
462 #[arg(long, default_value = "2", requires = "hotspots")]
463 min_dependents: usize,
464
465 /// Show unused/orphaned files
466 #[arg(long)]
467 unused: bool,
468
469 /// Show disconnected components (islands)
470 #[arg(long)]
471 islands: bool,
472
473 /// Minimum island size (default: 2)
474 #[arg(long, default_value = "2", requires = "islands")]
475 min_island_size: usize,
476
477 /// Maximum island size (default: 500 or 50% of total files)
478 #[arg(long, requires = "islands")]
479 max_island_size: Option<usize>,
480
481 /// Output format: tree (default), table
482 #[arg(short = 'f', long, default_value = "tree")]
483 format: String,
484
485 /// Output as JSON
486 #[arg(long)]
487 json: bool,
488
489 /// Pretty-print JSON output
490 #[arg(long)]
491 pretty: bool,
492
493 /// Only show count and timing, not the actual results
494 #[arg(short, long)]
495 count: bool,
496
497 /// Return all results (no limit)
498 /// Equivalent to --limit 0, convenience flag for unlimited results
499 #[arg(short = 'a', long)]
500 all: bool,
501
502 /// Use plain text output (disable colors and syntax highlighting)
503 #[arg(long)]
504 plain: bool,
505
506 /// Include files matching glob pattern (can be repeated)
507 /// Example: --glob "src/**/*.rs" --glob "tests/**/*.rs"
508 #[arg(short = 'g', long)]
509 glob: Vec<String>,
510
511 /// Exclude files matching glob pattern (can be repeated)
512 /// Example: --exclude "target/**" --exclude "*.gen.rs"
513 #[arg(short = 'x', long)]
514 exclude: Vec<String>,
515
516 /// Force execution of potentially expensive queries
517 /// Bypasses broad query detection
518 #[arg(long)]
519 force: bool,
520
521 /// Maximum number of results
522 #[arg(short = 'n', long)]
523 limit: Option<usize>,
524
525 /// Pagination offset
526 #[arg(short = 'o', long)]
527 offset: Option<usize>,
528
529 /// Sort order for results: asc (ascending) or desc (descending)
530 /// Applies to --hotspots (by import_count), --islands (by size), --circular (by cycle length)
531 /// Default: desc (most important first)
532 #[arg(long)]
533 sort: Option<String>,
534 },
535
536 /// Analyze dependencies for a specific file
537 ///
538 /// Show dependencies and dependents for a single file.
539 /// For graph-wide analysis, use 'rfx analyze' instead.
540 ///
541 /// Examples:
542 /// rfx deps src/main.rs # Show dependencies
543 /// rfx deps src/config.rs --reverse # Show dependents
544 /// rfx deps src/api.rs --depth 3 # Transitive deps
545 Deps {
546 /// File path to analyze
547 file: PathBuf,
548
549 /// Show files that depend on this file (reverse lookup)
550 #[arg(short, long)]
551 reverse: bool,
552
553 /// Traversal depth for transitive dependencies (default: 1)
554 #[arg(short, long, default_value = "1")]
555 depth: usize,
556
557 /// Output format: tree (default), table
558 #[arg(short = 'f', long, default_value = "tree")]
559 format: String,
560
561 /// Output as JSON
562 #[arg(long)]
563 json: bool,
564
565 /// Pretty-print JSON output
566 #[arg(long)]
567 pretty: bool,
568 },
569
570 /// Ask a natural language question and generate search queries
571 ///
572 /// Uses an LLM to translate natural language questions into `rfx query` commands.
573 /// Requires API key configuration for one of: OpenAI, Anthropic, or OpenRouter.
574 ///
575 /// If no question is provided, launches interactive chat mode by default.
576 ///
577 /// Configuration:
578 /// 1. Run interactive setup wizard (recommended):
579 /// rfx ask --configure
580 ///
581 /// 2. OR set API key via environment variable:
582 /// - OPENAI_API_KEY, ANTHROPIC_API_KEY, or OPENROUTER_API_KEY
583 ///
584 /// 3. Optional: Configure provider in ~/.reflex/config.toml:
585 /// [semantic]
586 /// provider = "openai" # or anthropic, openrouter
587 /// model = "gpt-5.1-mini" # optional, defaults to provider default
588 ///
589 /// Examples:
590 /// rfx ask --configure # Interactive setup wizard
591 /// rfx ask # Launch interactive chat (default)
592 /// rfx ask "Find all TODOs in Rust files"
593 /// rfx ask "Where is the main function defined?" --execute
594 /// rfx ask "Show me error handling code" --provider openrouter
595 Ask {
596 /// Natural language question
597 question: Option<String>,
598
599 /// Execute queries immediately without confirmation
600 #[arg(short, long)]
601 execute: bool,
602
603 /// Override configured LLM provider (openai, anthropic, openrouter, openai-compatible)
604 #[arg(short, long)]
605 provider: Option<String>,
606
607 /// Output format as JSON
608 #[arg(long)]
609 json: bool,
610
611 /// Pretty-print JSON output (only with --json)
612 #[arg(long)]
613 pretty: bool,
614
615 /// Additional context to inject into prompt (e.g., from `rfx context`)
616 #[arg(long)]
617 additional_context: Option<String>,
618
619 /// Launch interactive configuration wizard to set up AI provider and API key
620 #[arg(long)]
621 configure: bool,
622
623 /// Enable agentic mode (multi-step reasoning with context gathering)
624 #[arg(long)]
625 agentic: bool,
626
627 /// Maximum iterations for query refinement in agentic mode (default: 2)
628 #[arg(long, default_value = "2")]
629 max_iterations: usize,
630
631 /// Skip result evaluation in agentic mode
632 #[arg(long)]
633 no_eval: bool,
634
635 /// Show LLM reasoning blocks at each phase (agentic mode only)
636 #[arg(long)]
637 show_reasoning: bool,
638
639 /// Verbose output: show tool results and details (agentic mode only)
640 #[arg(long)]
641 verbose: bool,
642
643 /// Quiet mode: suppress progress output (agentic mode only)
644 #[arg(long)]
645 quiet: bool,
646
647 /// Generate a conversational answer based on search results
648 #[arg(long)]
649 answer: bool,
650
651 /// Launch interactive chat mode (TUI) with conversation history
652 #[arg(short = 'i', long)]
653 interactive: bool,
654
655 /// Debug mode: output full LLM prompts and retain terminal history
656 #[arg(long)]
657 debug: bool,
658 },
659
660 /// Generate codebase context for AI prompts
661 ///
662 /// Provides structural and organizational context about the project to help
663 /// LLMs understand project layout. Use with `rfx ask --additional-context`.
664 ///
665 /// By default (no flags), shows all context types. Use individual flags to
666 /// select specific context types.
667 ///
668 /// Examples:
669 /// rfx context # Full context (all types)
670 /// rfx context --path services/backend # Full context for monorepo subdirectory
671 /// rfx context --framework --entry-points # Specific context types only
672 /// rfx context --structure --depth 5 # Deep directory tree
673 ///
674 /// # Use with semantic queries
675 /// rfx ask "find auth" --additional-context "$(rfx context --framework)"
676 Context {
677 /// Show directory structure (enabled by default)
678 #[arg(long)]
679 structure: bool,
680
681 /// Focus on specific directory path
682 #[arg(short, long)]
683 path: Option<String>,
684
685 /// Show file type distribution (enabled by default)
686 #[arg(long)]
687 file_types: bool,
688
689 /// Detect project type (CLI/library/webapp/monorepo)
690 #[arg(long)]
691 project_type: bool,
692
693 /// Detect frameworks and conventions
694 #[arg(long)]
695 framework: bool,
696
697 /// Show entry point files
698 #[arg(long)]
699 entry_points: bool,
700
701 /// Show test organization pattern
702 #[arg(long)]
703 test_layout: bool,
704
705 /// List important configuration files
706 #[arg(long)]
707 config_files: bool,
708
709 /// Tree depth for --structure (default: 1)
710 #[arg(long, default_value = "1")]
711 depth: usize,
712
713 /// Output as JSON
714 #[arg(long)]
715 json: bool,
716 },
717
718 /// Internal command: Run background symbol indexing (hidden from help)
719 #[command(hide = true)]
720 IndexSymbolsInternal {
721 /// Cache directory path
722 cache_dir: PathBuf,
723 },
724
725 /// Take and manage codebase snapshots for structural tracking
726 ///
727 /// Snapshots capture the structural state of the index (files, dependencies,
728 /// metrics) for diffing and historical analysis.
729 ///
730 /// With no subcommand, creates a new snapshot.
731 ///
732 /// Examples:
733 /// rfx snapshot # Create a new snapshot
734 /// rfx snapshot list # List available snapshots
735 /// rfx snapshot diff # Diff latest vs previous
736 /// rfx snapshot gc # Run retention policy
737 Snapshot {
738 #[command(subcommand)]
739 command: Option<SnapshotSubcommand>,
740 },
741
742 /// Generate a documentation site from the index (plus changelog, map, glossary)
743 ///
744 /// Pulse turns the index into a docs site: a Docs tab for users (guides, API and
745 /// CLI reference, changelog) and an Internals tab for contributors. `generate`
746 /// builds it with Astro/Starlight into plain static HTML.
747 ///
748 /// Examples:
749 /// rfx pulse generate --no-llm # Full static site in ./pulse-site
750 /// rfx pulse serve # Preview it
751 /// rfx pulse changelog --no-llm # Structural-only changelog
752 /// rfx pulse map # Architecture map (mermaid)
753 Pulse {
754 #[command(subcommand)]
755 command: PulseSubcommand,
756 },
757
758 /// Manage LLM provider configuration (shared by `ask` and `pulse`)
759 ///
760 /// Examples:
761 /// rfx llm config # Launch interactive setup wizard
762 /// rfx llm status # Show current LLM configuration
763 Llm {
764 #[command(subcommand)]
765 command: LlmSubcommand,
766 },
767}
768
769#[derive(Subcommand, Debug)]
770pub enum SnapshotSubcommand {
771 /// Compare two snapshots
772 ///
773 /// Defaults to latest vs previous snapshot.
774 Diff {
775 /// Baseline snapshot ID (defaults to second-most-recent)
776 #[arg(long)]
777 baseline: Option<String>,
778
779 /// Current snapshot ID (defaults to most recent)
780 #[arg(long)]
781 current: Option<String>,
782
783 /// Output as JSON
784 #[arg(long)]
785 json: bool,
786
787 /// Pretty-print JSON output
788 #[arg(long)]
789 pretty: bool,
790 },
791
792 /// List available snapshots
793 List {
794 /// Output as JSON
795 #[arg(long)]
796 json: bool,
797
798 /// Pretty-print JSON output
799 #[arg(long)]
800 pretty: bool,
801 },
802
803 /// Run snapshot garbage collection
804 Gc {
805 /// Output as JSON
806 #[arg(long)]
807 json: bool,
808 },
809}
810
811/// LLM writing options for `rfx pulse generate`.
812#[derive(clap::Args, Debug, Clone)]
813pub struct PulseLlmArgs {
814 /// LLM writing: `on` (call on cache misses), `off`, or `cache-only` (never call;
815 /// use cached answers, e.g. in CI jobs without secrets)
816 #[arg(long, value_name = "MODE", default_value = "on")]
817 pub llm: String,
818
819 /// Skip LLM narration (same as `--llm off`)
820 #[arg(long)]
821 pub no_llm: bool,
822
823 /// Ignore cached LLM answers. Bare flag = all; or a comma list of kinds
824 /// (overview, modules, architecture, guides, timeline, glossary, changelog)
825 /// and task-id globs (e.g. `module:src/pulse*`)
826 #[arg(long, value_name = "SCOPES", num_args = 0..=1, default_missing_value = "all")]
827 pub force_renarrate: Option<String>,
828
829 /// Print the LLM plan (tasks, cache hits, estimated tokens) and exit without
830 /// calling the provider or writing the site
831 #[arg(long)]
832 pub dry_run: bool,
833
834 /// Stop planning LLM calls once estimated input+output tokens reach this cap;
835 /// the rest are deferred to later runs (default: [pulse.write] max_llm_tokens)
836 #[arg(long, value_name = "TOKENS")]
837 pub max_llm_tokens: Option<u64>,
838
839 /// Model for Pulse only (default: [pulse.write] model, then the `rfx ask` model)
840 #[arg(long, value_name = "MODEL")]
841 pub llm_model: Option<String>,
842
843 /// LLM answer cache directory (default: .reflex/pulse/write-cache)
844 #[arg(long, value_name = "DIR")]
845 pub llm_cache_dir: Option<PathBuf>,
846
847 /// Keep cache entries that this run did not use
848 #[arg(long)]
849 pub no_prune: bool,
850
851 /// Maximum concurrent LLM requests (default: [pulse.write] concurrency, 4)
852 #[arg(long)]
853 pub concurrency: Option<usize>,
854
855 /// Print every LLM sentence the grounding gate dropped, and why
856 #[arg(long)]
857 pub explain: bool,
858}
859
860impl PulseLlmArgs {
861 pub fn to_options(&self) -> anyhow::Result<crate::pulse::write::WriteOptions> {
862 use crate::pulse::write::{ForceScope, LlmMode, WriteOptions};
863 let mode = if self.no_llm {
864 LlmMode::Off
865 } else {
866 self.llm.parse::<LlmMode>().map_err(anyhow::Error::msg)?
867 };
868 Ok(WriteOptions {
869 mode,
870 force: self
871 .force_renarrate
872 .as_deref()
873 .map(ForceScope::parse)
874 .unwrap_or_default(),
875 dry_run: self.dry_run,
876 concurrency: self.concurrency,
877 max_llm_tokens: self.max_llm_tokens,
878 cache_dir: self.llm_cache_dir.clone(),
879 no_prune: self.no_prune,
880 model: self.llm_model.clone(),
881 explain: self.explain,
882 })
883 }
884}
885
886#[derive(Subcommand, Debug)]
887pub enum PulseRuntimeCommand {
888 /// Print the runtime id (a cache key for CI)
889 Key,
890 /// Show Node, the runtime directory and whether a prebuilt runtime exists
891 Status,
892 /// Install the runtime now (prebuilt download, else `npm ci`)
893 Install,
894}
895
896#[derive(Subcommand, Debug)]
897pub enum PulseSubcommand {
898 /// Generate a product-level changelog from recent commits
899 Changelog {
900 /// Number of recent commits to include (default: 20)
901 #[arg(long, default_value = "20")]
902 count: usize,
903
904 /// Skip LLM narration (structural content only)
905 #[arg(long)]
906 no_llm: bool,
907
908 /// Output as JSON
909 #[arg(long)]
910 json: bool,
911
912 /// Pretty-print JSON output
913 #[arg(long)]
914 pretty: bool,
915 },
916
917 /// Export an architecture map
918 Map {
919 /// Output format (mermaid, d2)
920 #[arg(short, long, default_value = "mermaid")]
921 format: String,
922
923 /// Output file (prints to stdout if not set)
924 #[arg(short, long)]
925 output: Option<PathBuf>,
926
927 /// Zoom level: repo (default) or module path
928 #[arg(short, long)]
929 zoom: Option<String>,
930 },
931
932 /// Generate the documentation site (static HTML)
933 ///
934 /// Builds the Docs Model from the index, optionally fills narrative sections
935 /// with a grounded LLM pass, renders every page to HTML and lays the site out
936 /// with Astro/Starlight. Needs Node 22.12+; the site runtime is downloaded once
937 /// (see `rfx pulse runtime status`). --base-url sets the host and path prefix.
938 Generate {
939 /// Output directory for the static site (plain HTML, ready for any CDN)
940 #[arg(short, long, default_value = "pulse-site")]
941 output: PathBuf,
942
943 /// Where the site is served from: `/`, `/docs/`, or `https://host/sub/`
944 #[arg(long, default_value = "/")]
945 base_url: String,
946
947 /// Site title
948 #[arg(long)]
949 title: Option<String>,
950
951 /// Deprecated: the site's sections are no longer selectable (ignored)
952 #[arg(long, hide = true)]
953 include: Option<String>,
954
955 /// Replace the output directory even if rfx pulse did not create it
956 #[arg(long)]
957 clean: bool,
958
959 #[command(flatten)]
960 llm: PulseLlmArgs,
961
962 /// Maximum directory depth for module discovery (1=top-level only, 2=default)
963 #[arg(long, default_value = "2")]
964 depth: u8,
965
966 /// Minimum file count for a module to be included
967 #[arg(long, default_value = "1")]
968 min_files: usize,
969
970 /// Write the site project (template + page bundle) but do not install the
971 /// runtime or build HTML; prints where the project is
972 #[arg(long)]
973 no_build: bool,
974
975 /// Never download or install anything (the runtime must already be installed)
976 #[arg(long)]
977 offline: bool,
978
979 /// Show the full `astro build` output
980 #[arg(long)]
981 verbose_build: bool,
982 },
983
984 /// Serve a generated site locally (under its base path)
985 Serve {
986 /// Directory containing the generated site
987 #[arg(short, long, default_value = "pulse-site")]
988 output: PathBuf,
989
990 /// Port to serve on
991 #[arg(short, long, default_value = "1111")]
992 port: u16,
993
994 /// Address to bind (loopback by default)
995 #[arg(long, default_value = "127.0.0.1")]
996 host: String,
997
998 /// Do not open a browser
999 #[arg(long)]
1000 no_open: bool,
1001 },
1002
1003 /// Inspect or install the site runtime (Astro/Starlight packages)
1004 Runtime {
1005 #[command(subcommand)]
1006 command: PulseRuntimeCommand,
1007 },
1008
1009 /// Build the Docs Model (tabs, pages, facts) without rendering it
1010 ///
1011 /// Prints a summary, or the full model with --json. The model is what the site
1012 /// renderer consumes; its JSON is deterministic, so it diffs well.
1013 Model {
1014 /// Print the full model as JSON
1015 #[arg(long)]
1016 json: bool,
1017
1018 /// Site title
1019 #[arg(long)]
1020 title: Option<String>,
1021
1022 /// Maximum directory depth for module discovery (1=top-level only, 2=default)
1023 #[arg(long, default_value = "2")]
1024 depth: u8,
1025
1026 /// Minimum source files for a module to be included
1027 #[arg(long, default_value = "1")]
1028 min_files: usize,
1029 },
1030
1031 /// Generate cross-cutting symbol glossary
1032 Glossary {
1033 /// Skip LLM concept generation (structural evidence only)
1034 #[arg(long)]
1035 no_llm: bool,
1036
1037 /// Output as JSON
1038 #[arg(long)]
1039 json: bool,
1040 },
1041}
1042
1043#[derive(Subcommand, Debug)]
1044pub enum LlmSubcommand {
1045 /// Launch interactive configuration wizard for AI provider and API key
1046 Config,
1047 /// Show current LLM configuration status
1048 Status,
1049}
1050
1051/// Format a byte count into a human-readable string (B, KB, MB, GB, TB).
1052fn format_bytes(bytes: u64) -> String {
1053 const KB: u64 = 1024;
1054 const MB: u64 = KB * 1024;
1055 const GB: u64 = MB * 1024;
1056 const TB: u64 = GB * 1024;
1057
1058 if bytes >= TB {
1059 format!("{:.2} TB", bytes as f64 / TB as f64)
1060 } else if bytes >= GB {
1061 format!("{:.2} GB", bytes as f64 / GB as f64)
1062 } else if bytes >= MB {
1063 format!("{:.2} MB", bytes as f64 / MB as f64)
1064 } else if bytes >= KB {
1065 format!("{:.2} KB", bytes as f64 / KB as f64)
1066 } else if bytes > 0 {
1067 format!("{} bytes", bytes)
1068 } else {
1069 "< 1 KB".to_string()
1070 }
1071}
1072
1073/// The query engine every command searches with: it updates a stale index (and
1074/// builds a missing one) before it answers, unless `--no-update` was given.
1075pub(crate) fn engine(cache: CacheManager, no_update: bool) -> crate::query::QueryEngine {
1076 let engine = crate::query::QueryEngine::new(cache);
1077 if no_update {
1078 engine
1079 } else {
1080 engine.with_update(crate::auto_update::UpdateOptions::cli())
1081 }
1082}
1083
1084/// Commands that read the index without the query engine's own update.
1085fn reads_index_first(command: &Command) -> bool {
1086 match command {
1087 Command::Stats { .. }
1088 | Command::ListFiles { .. }
1089 | Command::Analyze { .. }
1090 | Command::Deps { .. }
1091 | Command::Ask { .. }
1092 | Command::Context { .. } => true,
1093 Command::Snapshot { command } => {
1094 matches!(command, None | Some(SnapshotSubcommand::Diff { .. }))
1095 }
1096 Command::Pulse { command } => matches!(
1097 command,
1098 PulseSubcommand::Changelog { .. }
1099 | PulseSubcommand::Map { .. }
1100 | PulseSubcommand::Generate { .. }
1101 | PulseSubcommand::Model { .. }
1102 | PulseSubcommand::Glossary { .. }
1103 ),
1104 _ => false,
1105 }
1106}
1107
1108/// Update the index of `cache` before a command reads it. A build that fails
1109/// fails the command; an update that cannot run is a warning.
1110fn update_before(cache: &CacheManager) -> Result<()> {
1111 use crate::auto_update::{UpdateOptions, Updated, update_if_stale};
1112 if let Updated::Skipped(reason) = update_if_stale(cache, &UpdateOptions::cli())? {
1113 crate::output::warn(&format!("⚠️ Index not updated: {reason}"));
1114 }
1115 Ok(())
1116}
1117
1118/// Try to run background cache compaction if needed
1119///
1120/// Checks if 24+ hours have passed since last compaction.
1121/// If yes, spawns a non-blocking background thread to compact the cache.
1122/// Main command continues immediately without waiting for compaction.
1123///
1124/// Compaction is skipped for commands that don't need it:
1125/// - Clear (will delete the cache anyway)
1126/// - Index (rewrites meta.db itself; compaction would wait on its lock)
1127/// - Mcp (long-running server process)
1128/// - Watch (long-running watcher process)
1129/// - Serve (long-running HTTP server)
1130fn try_background_compact(cache: &CacheManager, command: &Command) {
1131 // Skip compaction for certain commands
1132 match command {
1133 Command::Clear { .. } => {
1134 log::debug!("Skipping compaction for Clear command");
1135 return;
1136 }
1137 Command::Watch { .. } => {
1138 log::debug!("Skipping compaction for Watch command");
1139 return;
1140 }
1141 Command::Serve { .. } => {
1142 log::debug!("Skipping compaction for Serve command");
1143 return;
1144 }
1145 // An index run rewrites meta.db itself and prunes deleted files; a
1146 // compaction racing it would only wait on its lock.
1147 Command::Index { .. } => {
1148 log::debug!("Skipping compaction for Index command");
1149 return;
1150 }
1151 _ => {}
1152 }
1153
1154 // Check if compaction should run
1155 let should_compact = match cache.should_compact() {
1156 Ok(true) => true,
1157 Ok(false) => {
1158 log::debug!("Compaction not needed yet (last run <24h ago)");
1159 return;
1160 }
1161 Err(e) => {
1162 log::warn!("Failed to check compaction status: {}", e);
1163 return;
1164 }
1165 };
1166
1167 if !should_compact {
1168 return;
1169 }
1170
1171 log::info!("Starting background cache compaction...");
1172
1173 // Clone cache path for background thread
1174 let cache_path = cache.path().to_path_buf();
1175
1176 // Spawn background thread for compaction
1177 std::thread::spawn(move || {
1178 let cache = CacheManager::new(
1179 cache_path
1180 .parent()
1181 .expect("Cache should have parent directory"),
1182 );
1183
1184 // Never alongside an index run: skip when `index.lock` is held, and hold it
1185 // for the compaction.
1186 let _lock = match crate::atomic_write::IndexLock::try_acquire(cache.path()) {
1187 Ok(Some(lock)) => lock,
1188 Ok(None) => {
1189 log::debug!("Skipping background compaction: an index run holds the lock");
1190 return;
1191 }
1192 Err(e) => {
1193 log::debug!("Skipping background compaction: {}", e);
1194 return;
1195 }
1196 };
1197
1198 match cache.compact() {
1199 Ok(report) => {
1200 log::info!(
1201 "Background compaction completed: {} files removed, {:.2} MB saved, took {}ms",
1202 report.files_removed,
1203 report.space_saved_bytes as f64 / 1_048_576.0,
1204 report.duration_ms
1205 );
1206 }
1207 Err(e) => {
1208 log::warn!("Background compaction failed: {}", e);
1209 }
1210 }
1211 });
1212
1213 log::debug!("Background compaction thread spawned - main command continuing");
1214}
1215
1216impl Cli {
1217 /// Execute the CLI command
1218 pub fn execute(self) -> Result<()> {
1219 // Setup logging based on verbosity
1220 let log_level = match self.verbose {
1221 0 => "warn", // Default: only warnings and errors
1222 1 => "info", // -v: show info messages
1223 2 => "debug", // -vv: show debug messages
1224 _ => "trace", // -vvv: show trace messages
1225 };
1226 env_logger::Builder::from_env(env_logger::Env::default().default_filter_or(log_level))
1227 .init();
1228
1229 // Try background compaction (non-blocking) before command execution
1230 if let Some(ref command) = self.command {
1231 // Use current directory as default cache location
1232 let cache = CacheManager::new(".");
1233 try_background_compact(&cache, command);
1234 }
1235
1236 // A command that reads the index brings it up to date first. Searches do it
1237 // inside the query engine, alongside the search, so a fresh index adds no
1238 // wait; the other readers do it here.
1239 let no_update = self.no_update;
1240 if !no_update && self.command.as_ref().is_some_and(reads_index_first) {
1241 update_before(&CacheManager::new("."))?;
1242 }
1243
1244 // Execute the subcommand, or show help if no command provided
1245 match self.command {
1246 None => {
1247 // No subcommand: show help
1248 Cli::command().print_help()?;
1249 println!(); // Add newline after help
1250 Ok(())
1251 }
1252 Some(Command::Index {
1253 path,
1254 force,
1255 languages,
1256 quiet,
1257 command,
1258 }) => {
1259 match command {
1260 None => {
1261 // Default: run index build
1262 index::handle_index_build(&path, &force, &languages, &quiet)
1263 }
1264 Some(IndexSubcommand::Status) => index::handle_index_status(),
1265 Some(IndexSubcommand::Compact { json, pretty }) => {
1266 index::handle_index_compact(&json, &pretty)
1267 }
1268 }
1269 }
1270 Some(Command::Query {
1271 pattern,
1272 pattern_flag,
1273 symbols,
1274 lang,
1275 kind,
1276 ast,
1277 regex,
1278 json,
1279 pretty,
1280 timing,
1281 ai,
1282 limit,
1283 offset,
1284 expand,
1285 file,
1286 exact,
1287 contains,
1288 ignore_case,
1289 include_locks,
1290 include_generated,
1291 count,
1292 timeout,
1293 plain,
1294 glob,
1295 exclude,
1296 paths,
1297 no_truncate,
1298 context,
1299 all,
1300 force,
1301 dependencies,
1302 }) => {
1303 // If no pattern provided, launch interactive mode (REF-68: require TTY)
1304 match pattern.or(pattern_flag) {
1305 None => {
1306 use crossterm::tty::IsTty;
1307 if !std::io::stdin().is_tty() {
1308 eprintln!("error: interactive mode requires a terminal (TTY).");
1309 eprintln!("Use 'rfx query <pattern>' for non-interactive search.");
1310 std::process::exit(1);
1311 }
1312 query::handle_interactive(no_update)
1313 }
1314 Some(pattern) => query::handle_query(
1315 pattern,
1316 symbols,
1317 lang,
1318 kind,
1319 ast,
1320 regex,
1321 json,
1322 pretty,
1323 timing,
1324 ai,
1325 limit,
1326 offset,
1327 expand,
1328 file,
1329 exact,
1330 contains,
1331 ignore_case,
1332 include_locks,
1333 include_generated,
1334 count,
1335 timeout,
1336 plain,
1337 glob,
1338 exclude,
1339 paths,
1340 no_truncate,
1341 context,
1342 all,
1343 force,
1344 dependencies,
1345 no_update,
1346 ),
1347 }
1348 }
1349 Some(Command::Serve { port, host }) => serve::handle_serve(port, host, no_update),
1350 Some(Command::Stats { json, pretty }) => misc::handle_stats(json, pretty),
1351 Some(Command::Clear { yes }) => misc::handle_clear(yes),
1352 Some(Command::ListFiles {
1353 json,
1354 pretty,
1355 lang,
1356 glob,
1357 }) => misc::handle_list_files(json, pretty, lang, glob),
1358 Some(Command::Watch {
1359 path,
1360 debounce,
1361 quiet,
1362 }) => watch::handle_watch(path, debounce, quiet),
1363 Some(Command::Mcp) => misc::handle_mcp(no_update),
1364 Some(Command::Analyze {
1365 circular,
1366 hotspots,
1367 min_dependents,
1368 unused,
1369 islands,
1370 min_island_size,
1371 max_island_size,
1372 format,
1373 json,
1374 pretty,
1375 count,
1376 all,
1377 plain,
1378 glob,
1379 exclude,
1380 force,
1381 limit,
1382 offset,
1383 sort,
1384 }) => deps::handle_analyze(
1385 circular,
1386 hotspots,
1387 min_dependents,
1388 unused,
1389 islands,
1390 min_island_size,
1391 max_island_size,
1392 format,
1393 json,
1394 pretty,
1395 count,
1396 all,
1397 plain,
1398 glob,
1399 exclude,
1400 force,
1401 limit,
1402 offset,
1403 sort,
1404 ),
1405 Some(Command::Deps {
1406 file,
1407 reverse,
1408 depth,
1409 format,
1410 json,
1411 pretty,
1412 }) => deps::handle_deps(file, reverse, depth, format, json, pretty),
1413 Some(Command::Ask {
1414 question,
1415 execute,
1416 provider,
1417 json,
1418 pretty,
1419 additional_context,
1420 configure,
1421 agentic,
1422 max_iterations,
1423 no_eval,
1424 show_reasoning,
1425 verbose,
1426 quiet,
1427 answer,
1428 interactive,
1429 debug,
1430 }) => ask::handle_ask(
1431 question,
1432 execute,
1433 provider,
1434 json,
1435 pretty,
1436 additional_context,
1437 configure,
1438 agentic,
1439 max_iterations,
1440 no_eval,
1441 show_reasoning,
1442 verbose,
1443 quiet,
1444 answer,
1445 interactive,
1446 debug,
1447 ),
1448 Some(Command::Context {
1449 structure,
1450 path,
1451 file_types,
1452 project_type,
1453 framework,
1454 entry_points,
1455 test_layout,
1456 config_files,
1457 depth,
1458 json,
1459 }) => misc::handle_context(
1460 structure,
1461 path,
1462 file_types,
1463 project_type,
1464 framework,
1465 entry_points,
1466 test_layout,
1467 config_files,
1468 depth,
1469 json,
1470 ),
1471 Some(Command::IndexSymbolsInternal { cache_dir }) => {
1472 index::handle_index_symbols_internal(cache_dir)
1473 }
1474 Some(Command::Snapshot { command }) => match command {
1475 None => snapshot::handle_snapshot_create(),
1476 Some(SnapshotSubcommand::List { json, pretty }) => {
1477 snapshot::handle_snapshot_list(json, pretty)
1478 }
1479 Some(SnapshotSubcommand::Diff {
1480 baseline,
1481 current,
1482 json,
1483 pretty,
1484 }) => snapshot::handle_snapshot_diff(baseline, current, json, pretty),
1485 Some(SnapshotSubcommand::Gc { json }) => snapshot::handle_snapshot_gc(json),
1486 },
1487 Some(Command::Pulse { command }) => match command {
1488 PulseSubcommand::Changelog {
1489 count,
1490 no_llm,
1491 json,
1492 pretty,
1493 } => pulse::handle_pulse_changelog(count, no_llm, json, pretty),
1494 PulseSubcommand::Map {
1495 format,
1496 output,
1497 zoom,
1498 } => pulse::handle_pulse_map(format, output, zoom),
1499 PulseSubcommand::Generate {
1500 output,
1501 base_url,
1502 title,
1503 include,
1504 clean,
1505 llm,
1506 depth,
1507 min_files,
1508 no_build,
1509 offline,
1510 verbose_build,
1511 } => pulse::handle_pulse_generate(pulse::GenerateArgs {
1512 output,
1513 base_url,
1514 title,
1515 include,
1516 clean,
1517 write: llm.to_options()?,
1518 depth,
1519 min_files,
1520 no_build,
1521 offline,
1522 verbose_build,
1523 }),
1524 PulseSubcommand::Serve {
1525 output,
1526 port,
1527 host,
1528 no_open,
1529 } => crate::pulse::serve::serve(&output, &host, port, !no_open),
1530 PulseSubcommand::Runtime { command } => pulse::handle_pulse_runtime(command),
1531 PulseSubcommand::Model {
1532 json,
1533 title,
1534 depth,
1535 min_files,
1536 } => pulse::handle_pulse_model(json, title, depth, min_files),
1537 PulseSubcommand::Glossary { no_llm, json } => {
1538 pulse::handle_pulse_glossary(no_llm, json)
1539 }
1540 },
1541 Some(Command::Llm { command }) => match command {
1542 LlmSubcommand::Config => llm::handle_llm_config(),
1543 LlmSubcommand::Status => llm::handle_llm_status(),
1544 },
1545 }
1546 }
1547}