Skip to main content

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