reflex-search 0.3.2

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

Thank you for your interest in contributing to Reflex! We welcome contributions that help make Reflex faster, more accurate, and easier to use.

## Project Philosophy

Reflex is built around three core principles:

1. **Speed**: Extremely fast queries on large codebases through efficient trigram indexing
2. **Accuracy**: Complete coverage with deterministic results (no probabilistic ranking)
3. **Simplicity**: Clean architecture that's easy to understand, extend, and maintain

When contributing, please keep these principles in mind.

---

## Getting Started

### Prerequisites

- **Rust**: Version 1.75 or later (edition 2024)

### Development Setup

1. **Clone the repository:**

```bash
git clone https://github.com/reflex-search/reflex.git
cd reflex
```

2. **Build the project:**

```bash
cargo build --release
```

3. **Run tests:**

```bash
cargo test
```

4. **Run with debug logging:**

```bash
RUST_LOG=debug cargo run -- query "pattern"
```

5. **Generate documentation:**

```bash
cargo doc --open
```

---

## Project Structure

```
reflex/
├── src/
│   ├── lib.rs              # Library root (public API)
│   ├── main.rs             # CLI entry point
│   ├── cli.rs              # Command-line interface
│   ├── cache.rs            # Cache management (SQLite, file I/O)
│   ├── indexer.rs          # Indexing logic (trigram extraction)
│   ├── query.rs            # Query engine (search execution)
│   ├── trigram.rs          # Trigram algorithm (inverted index)
│   ├── content_store.rs    # Memory-mapped content storage
│   ├── regex_trigrams.rs   # Regex optimization
│   ├── ast_query.rs        # AST pattern matching
│   ├── formatter.rs        # Output formatting
│   ├── watcher.rs          # File watcher (auto-reindex)
│   ├── mcp.rs              # MCP server (AI integration)
│   ├── git.rs              # Git integration
│   ├── models.rs           # Data structures and types
│   └── parsers/            # Language-specific parsers
│       ├── mod.rs          # Parser factory
│       ├── rust.rs         # Rust parser
│       ├── typescript.rs   # TypeScript/JavaScript parser
│       ├── python.rs       # Python parser
│       ├── go.rs           # Go parser
│       ├── java.rs         # Java parser
│       ├── c.rs            # C parser
│       ├── cpp.rs          # C++ parser
│       ├── php.rs          # PHP parser
│       ├── csharp.rs       # C# parser
│       ├── ruby.rs         # Ruby parser
│       ├── kotlin.rs       # Kotlin parser
│       ├── zig.rs          # Zig parser
│       ├── vue.rs          # Vue parser
│       └── svelte.rs       # Svelte parser
├── tests/
│   ├── integration_test.rs     # End-to-end workflow tests
│   └── performance_test.rs     # Performance benchmarks
├── .context/
│   └── TODO.md             # Task tracking and roadmap
├── ARCHITECTURE.md         # System design documentation
├── CLAUDE.md               # Development workflow guide
├── README.md               # User documentation
├── API.md                  # HTTP API reference
└── Cargo.toml              # Rust package configuration
```

---

## Development Workflow

### Making Changes

1. **Create a branch** for your feature or bugfix:

```bash
git checkout -b feature/your-feature-name
# or
git checkout -b fix/issue-description
```

2. **Make your changes** following our [Code Style]#code-style guidelines

3. **Write tests** for new functionality (see [Testing]#testing)

4. **Run the test suite:**

```bash
cargo test
```

5. **Run linters:**

```bash
cargo fmt --check  # Check formatting
cargo clippy -- -D warnings  # Run linter
```

6. **Update documentation** if adding new features or changing behavior

7. **Commit your changes** using [Conventional Commits]#conventional-commits

8. **Push to your fork and create a Pull Request**

### Pull Request Process

1. **Open a PR** with a clear title and description
2. **Link related issues** (e.g., "Fixes #123")
3. **Wait for CI checks** to pass (tests, linting, formatting)
4. **Respond to review feedback** and make requested changes
5. **Squash commits** if requested before merge

**PR Checklist:**

- [ ] Tests pass locally (`cargo test`)
- [ ] Code is formatted (`cargo fmt`)
- [ ] No clippy warnings (`cargo clippy`)
- [ ] Documentation updated (if applicable)
- [ ] Commit messages follow Conventional Commits format
- [ ] PR description explains what/why (not just how)

---

## Code Style

### Rust Style Guidelines

Reflex follows **standard Rust conventions**:

- Use `rustfmt` for code formatting (run `cargo fmt` before committing)
- Use `clippy` for linting (address all warnings: `cargo clippy -- -D warnings`)
- Follow [Rust API Guidelines]https://rust-lang.github.io/api-guidelines/

### Naming Conventions

- **Modules**: `snake_case` (e.g., `query_engine`, `ast_parser`)
- **Structs/Enums**: `PascalCase` (e.g., `QueryEngine`, `SymbolKind`)
- **Functions/Methods**: `snake_case` (e.g., `extract_symbols`, `parse_file`)
- **Constants**: `SCREAMING_SNAKE_CASE` (e.g., `DEFAULT_TIMEOUT`, `MAX_FILE_SIZE`)

### Documentation

- **Public API**: All public items must have rustdoc comments
- **Modules**: Start with `//!` module-level docs
- **Functions**: Use `///` doc comments with examples for complex functions
- **Examples**: Include code examples in doc comments when helpful

```rust
/// Parse source code into an abstract syntax tree.
///
/// # Arguments
///
/// * `source` - Source code string
/// * `language` - Programming language
///
/// # Returns
///
/// Returns a `Tree` on success, or an error if parsing fails.
///
/// # Examples
///
/// ```
/// let tree = parse_tree("fn main() {}", Language::Rust)?;
/// ```
pub fn parse_tree(source: &str, language: Language) -> Result<Tree> {
    // ...
}
```

### Error Handling

- Use `anyhow::Result` for functions that return errors
- Use `anyhow::bail!()` for early returns with error messages
- Add context to errors using `.context()` or `.with_context()`

```rust
use anyhow::{Context, Result};

fn read_file(path: &Path) -> Result<String> {
    std::fs::read_to_string(path)
        .with_context(|| format!("Failed to read file: {}", path.display()))
}
```

---

## Testing

Reflex has **comprehensive tests** across three categories:

### Unit Tests

Located in `#[cfg(test)]` modules within source files:

```bash
# Run all unit tests
cargo test --lib

# Run tests for a specific module
cargo test --lib cache::tests

# Run with output visible
cargo test -- --nocapture
```

**Writing Unit Tests:**

```rust
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_trigram_extraction() {
        let text = "hello world";
        let trigrams = extract_trigrams(text);
        assert_eq!(trigrams, vec!["hel", "ell", "llo"]);
    }
}
```

### Integration Tests

Located in `tests/` directory:

```bash
# Run integration tests
cargo test --test integration_test

# Run specific integration test
cargo test --test integration_test test_full_workflow
```

**Integration tests** verify end-to-end workflows (index → query → verify).

### Performance Tests

Located in `tests/performance_test.rs`:

```bash
# Run performance tests
cargo test --test performance_test --release

# Skip slow tests during development
cargo test --test performance_test --release -- --skip large
```

**Performance tests** ensure queries remain under target latencies.

### Test Coverage Goals

- **New features**: Must include tests covering typical and edge cases
- **Bug fixes**: Add a regression test that would have caught the bug
- **Parsers**: Each language parser needs 8-15 tests covering all symbol types
- **Core modules**: Aim for >80% code coverage on critical paths

---

## Conventional Commits

Reflex uses **Conventional Commits** for automatic changelog generation and version bumping.

### Commit Message Format

```
<type>(<scope>): <description>

[optional body]

[optional footer(s)]
```

### Commit Types

- `feat:` - New feature (triggers MINOR version bump)
- `fix:` - Bug fix (triggers PATCH version bump)
- `docs:` - Documentation only changes
- `refactor:` - Code refactoring (no functional changes)
- `perf:` - Performance improvements
- `test:` - Adding or updating tests
- `chore:` - Maintenance tasks (dependencies, build, etc.)
- `BREAKING CHANGE:` - Breaking change (triggers MAJOR version bump)

### Examples

```bash
# Feature: Adds timeout support
git commit -m "feat(query): add --timeout flag for query timeout control"

# Bug fix: Fixes crash
git commit -m "fix(indexer): handle empty files without panic"

# Breaking change: Removes deprecated API
git commit -m "feat(api): remove deprecated /search endpoint

BREAKING CHANGE: The /search endpoint has been removed.
Use /query instead."

# Documentation
git commit -m "docs(readme): add examples for AST pattern matching"

# Refactoring
git commit -m "refactor(trigram): simplify posting list intersection"

# Performance
git commit -m "perf(query): optimize symbol lookup with hash map"

# Tests
git commit -m "test(parser): add tests for PHP enum parsing"

# Chore
git commit -m "chore(deps): update tree-sitter to 0.24.1"
```

### Validation

Install `cocogitto` for local commit validation:

```bash
cargo install cocogitto

# Validate commits
cog check

# Create a conventional commit interactively
cog commit
```

---

## Adding New Language Support

Reflex supports 14+ languages through Tree-sitter parsers. Here's how to add a new language:

### 1. Add Tree-sitter Grammar Dependency

Edit `Cargo.toml`:

```toml
[dependencies]
tree-sitter-yourLanguage = "0.23"
```

### 2. Update Language Enum

In `src/models.rs`, add your language to the `Language` enum:

```rust
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Language {
    Rust,
    Python,
    // ... existing languages
    YourLanguage,  // Add here
}
```

### 3. Create Parser Module

Create `src/parsers/your_language.rs`:

```rust
use tree_sitter::{Node, Parser, Query, QueryCursor};
use crate::models::{Symbol, SymbolKind, Span};

/// Extract symbols from YourLanguage source code
pub fn extract_symbols(source: &str) -> Vec<Symbol> {
    let mut parser = Parser::new();
    parser.set_language(&tree_sitter_your_language::language())
        .expect("Failed to load YourLanguage grammar");

    let tree = match parser.parse(source, None) {
        Some(tree) => tree,
        None => return Vec::new(),
    };

    let mut symbols = Vec::new();
    let root = tree.root_node();

    // Extract functions
    symbols.extend(extract_functions(source, root));

    // Extract classes
    symbols.extend(extract_classes(source, root));

    // Extract other symbol types...

    symbols
}

fn extract_functions(source: &str, root: Node) -> Vec<Symbol> {
    // Use Tree-sitter query to find function nodes
    let query_str = "(function_declaration name: (identifier) @name)";
    let query = Query::new(&tree_sitter_your_language::language(), query_str)
        .expect("Invalid query");

    let mut cursor = QueryCursor::new();
    let matches = cursor.matches(&query, root, source.as_bytes());

    let mut functions = Vec::new();
    for m in matches {
        for capture in m.captures {
            let node = capture.node;
            let name = node.utf8_text(source.as_bytes()).unwrap_or("");

            functions.push(Symbol {
                name: name.to_string(),
                kind: SymbolKind::Function,
                span: Span {
                    start_line: node.start_position().row + 1,
                    start_col: node.start_position().column + 1,
                    end_line: node.end_position().row + 1,
                    end_col: node.end_position().column + 1,
                },
                scope: None,
            });
        }
    }

    functions
}
```

### 4. Register in Parser Factory

In `src/parsers/mod.rs`, add your parser:

```rust
pub mod your_language;

pub fn parse_file(source: &str, language: Language) -> Vec<Symbol> {
    match language {
        Language::Rust => rust::extract_symbols(source),
        Language::Python => python::extract_symbols(source),
        // ... existing parsers
        Language::YourLanguage => your_language::extract_symbols(source),
        _ => Vec::new(),
    }
}
```

### 5. Update File Extensions

In `src/indexer.rs`, map file extensions to your language:

```rust
fn detect_language(path: &Path) -> Option<Language> {
    match path.extension()?.to_str()? {
        "rs" => Some(Language::Rust),
        "py" => Some(Language::Python),
        // ... existing extensions
        "yourlang" | "yl" => Some(Language::YourLanguage),
        _ => None,
    }
}
```

### 6. Add Tests

Create comprehensive tests in `src/parsers/your_language.rs`:

```rust
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_extract_functions() {
        let source = r#"
            function hello() {
                console.log("Hello");
            }
        "#;

        let symbols = extract_symbols(source);
        assert_eq!(symbols.len(), 1);
        assert_eq!(symbols[0].name, "hello");
        assert_eq!(symbols[0].kind, SymbolKind::Function);
    }

    // Add more tests for classes, methods, etc.
}
```

### 7. Update Documentation

- Add your language to `README.md` (Supported Languages table)
- Add your language to `CLAUDE.md` (Supported Languages section)
- Update `API.md` (Supported Languages table)

### Resources

- **Tree-sitter Documentation**: https://tree-sitter.github.io/tree-sitter/
- **Tree-sitter Playground**: https://tree-sitter.github.io/tree-sitter/playground
- **Reflex Architecture Guide**: See [ARCHITECTURE.md]ARCHITECTURE.md#extension-guide

---

## Debugging Tips

### Enable Debug Logging

```bash
# All debug output
RUST_LOG=debug rfx query "pattern"

# Specific module
RUST_LOG=reflex::query=debug rfx query "pattern"

# Trace level (very verbose)
RUST_LOG=trace rfx query "pattern"
```

### Profile Performance

```bash
# Build with profiling enabled
cargo build --release --features profiling

# Run with profiler (Linux)
perf record --call-graph=dwarf ./target/release/rfx query "pattern"
perf report
```

### Inspect Cache Files

```bash
# View SQLite metadata
sqlite3 .reflex/meta.db ".schema"
sqlite3 .reflex/meta.db "SELECT * FROM files LIMIT 10;"

# View file hashes
cat .reflex/hashes.json | jq '.'
```

### Run Single Test with Output

```bash
cargo test test_name -- --nocapture --test-threads=1
```

---

## Release Process

Reflex uses **automated releases** via [release-plz](https://release-plz.ieni.dev/):

1. **Make changes** and commit using Conventional Commits
2. **Push to `main`** branch
3. **GitHub Action** automatically:
   - Analyzes commits
   - Determines next version
   - Updates `Cargo.toml` and `CHANGELOG.md`
   - Opens release PR
4. **Merge release PR** to create tag and GitHub Release

**Manual releases** are discouraged. See [CLAUDE.md Release Management](CLAUDE.md#release-management) for details.

---

## Getting Help

- **Documentation**: Start with [README.md]README.md and [ARCHITECTURE.md]ARCHITECTURE.md
- **Issues**: Check existing [GitHub Issues]https://github.com/reflex-search/reflex/issues
- **Discussions**: Open a [GitHub Discussion]https://github.com/reflex-search/reflex/discussions for questions
- **Context**: Read [CLAUDE.md]CLAUDE.md for project philosophy and workflow

---

## Code of Conduct

We expect all contributors to:

- Be respectful and constructive in discussions
- Focus on technical merit and project goals
- Help create a welcoming environment for all skill levels
- Report unacceptable behavior to the maintainers

---

## License

By contributing to Reflex, you agree that your contributions will be licensed under the MIT License.

See [LICENSE](LICENSE) for details.

---

## Recognition

Contributors will be recognized in:

- GitHub contributor list
- Release notes for significant contributions
- CHANGELOG.md for feature additions

Thank you for contributing to Reflex! 🚀