pmat 3.15.0

PMAT - Zero-config AI context generation and code quality toolkit (CLI, MCP, HTTP)
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
// HybridSearchEngine implementation methods
// Contains: constructor, search dispatch, keyword/vector/hybrid search,
// result merging with RRF, filtering, and utility functions.

impl HybridSearchEngine {
    /// Create new hybrid search engine with local embeddings
    ///
    /// # Arguments
    /// * `db_path` - Vector database path
    /// * `search_root` - Root directory for keyword search
    ///
    /// # Note
    /// Uses pure Rust TF-IDF embeddings via aprender.
    /// No external API keys or internet connection required.
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
    pub async fn new(db_path: &str, search_root: &Path) -> Result<Self, String> {
        let semantic_engine = SemanticSearchEngine::new(db_path).await?;

        Ok(Self {
            semantic_engine: Arc::new(semantic_engine),
            search_root: search_root.to_path_buf(),
        })
    }

    /// Create new hybrid search engine (backward compatible - ignores api_key)
    #[deprecated(note = "Use new() without api_key - local embeddings don't require API keys")]
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
    pub async fn new_with_key(
        _api_key: &str,
        db_path: &str,
        search_root: &Path,
    ) -> Result<Self, String> {
        Self::new(db_path, search_root).await
    }

    /// Search using hybrid mode
    ///
    /// # Arguments
    /// * `query` - Search query
    ///
    /// # Returns
    /// Ranked hybrid search results
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub async fn search(
        &self,
        query: &HybridSearchQuery,
    ) -> Result<Vec<HybridSearchResult>, String> {
        if query.query.trim().is_empty() {
            return Err("Query cannot be empty".to_string());
        }

        match query.mode {
            HybridSearchMode::KeywordOnly => self.keyword_only_search(query).await,
            HybridSearchMode::VectorOnly => self.vector_only_search(query).await,
            HybridSearchMode::Hybrid => self.hybrid_search(query).await,
        }
    }

    /// Keyword-only search using ripgrep
    async fn keyword_only_search(
        &self,
        query: &HybridSearchQuery,
    ) -> Result<Vec<HybridSearchResult>, String> {
        let matches = self.keyword_search(&query.query, query.limit * 2).await?;

        let mut results: Vec<HybridSearchResult> = matches
            .into_iter()
            .enumerate()
            .map(|(rank, m)| {
                let keyword_score = Self::compute_rrf_score(rank + 1, 60);

                HybridSearchResult {
                    file_path: m.file_path.clone(),
                    chunk_name: Self::extract_chunk_name(&m.content),
                    chunk_type: "file".to_string(),
                    language: Self::detect_language(&m.file_path),
                    start_line: m.line_number,
                    end_line: m.line_number,
                    keyword_score,
                    vector_score: 0.0,
                    hybrid_score: keyword_score,
                    snippet: Self::truncate(&m.content, 200),
                }
            })
            .collect();

        // Apply filters
        results = Self::apply_filters(results, query);
        results.truncate(query.limit);

        Ok(results)
    }

    /// Vector-only search using semantic engine
    async fn vector_only_search(
        &self,
        query: &HybridSearchQuery,
    ) -> Result<Vec<HybridSearchResult>, String> {
        let semantic_query = SearchQuery {
            query: query.query.clone(),
            mode: super::SearchMode::SemanticOnly,
            language_filter: query.language_filter.clone(),
            file_pattern: query.file_pattern.clone(),
            chunk_type_filter: None,
            limit: query.limit,
        };

        let semantic_results = self.semantic_engine.search(&semantic_query).await?;

        let results = semantic_results
            .into_iter()
            .map(|r| HybridSearchResult {
                file_path: r.file_path,
                chunk_name: r.chunk_name,
                chunk_type: r.chunk_type,
                language: r.language,
                start_line: r.start_line,
                end_line: r.end_line,
                keyword_score: 0.0,
                vector_score: r.similarity_score,
                hybrid_score: r.similarity_score,
                snippet: r.snippet,
            })
            .collect();

        Ok(results)
    }

    /// Hybrid search combining keyword and vector results with RRF
    async fn hybrid_search(
        &self,
        query: &HybridSearchQuery,
    ) -> Result<Vec<HybridSearchResult>, String> {
        // Run both searches in parallel
        let keyword_matches = self.keyword_search(&query.query, query.limit * 2).await?;

        let semantic_query = SearchQuery {
            query: query.query.clone(),
            mode: super::SearchMode::SemanticOnly,
            language_filter: query.language_filter.clone(),
            file_pattern: query.file_pattern.clone(),
            chunk_type_filter: None,
            limit: query.limit * 2,
        };

        let semantic_results = self.semantic_engine.search(&semantic_query).await?;

        // Merge results using RRF
        let merged = self.merge_results(
            keyword_matches,
            semantic_results,
            (query.keyword_weight, query.vector_weight),
        );

        // Apply filters and limit
        let mut filtered = Self::apply_filters(merged, query);
        filtered.truncate(query.limit);

        Ok(filtered)
    }

    /// Keyword search using ripgrep
    async fn keyword_search(&self, query: &str, limit: usize) -> Result<Vec<KeywordMatch>, String> {
        let output = Command::new("rg")
            .arg("--line-number")
            .arg("--no-heading")
            .arg("--max-count")
            .arg(limit.to_string())
            .arg(query)
            .arg(&self.search_root)
            .output()
            .map_err(|e| format!("Failed to run ripgrep: {e}"))?;

        if !output.status.success() && !output.stdout.is_empty() {
            // ripgrep returns exit code 1 when no matches found, which is not an error
            if output.stdout.is_empty() {
                return Ok(Vec::new());
            }
        }

        let stdout = String::from_utf8_lossy(&output.stdout);
        let mut matches = Vec::new();

        for line in stdout.lines().take(limit) {
            // Format: path:line_number:content
            let parts: Vec<&str> = line.splitn(3, ':').collect();
            if parts.len() == 3 {
                if let Ok(line_num) = parts[1].parse::<usize>() {
                    matches.push(KeywordMatch {
                        file_path: parts[0].to_string(),
                        line_number: line_num,
                        content: parts[2].to_string(),
                    });
                }
            }
        }

        Ok(matches)
    }

    /// Merge keyword and vector results using RRF
    fn merge_results(
        &self,
        keyword_matches: Vec<KeywordMatch>,
        semantic_results: Vec<SearchResult>,
        weights: (f64, f64),
    ) -> Vec<HybridSearchResult> {
        let mut result_map: HashMap<String, HybridSearchResult> = HashMap::new();

        // Add keyword results with RRF scores
        for (rank, km) in keyword_matches.iter().enumerate() {
            let keyword_score = Self::compute_rrf_score(rank + 1, 60);
            let key = format!("{}:{}", km.file_path, km.line_number);

            result_map.insert(
                key,
                HybridSearchResult {
                    file_path: km.file_path.clone(),
                    chunk_name: Self::extract_chunk_name(&km.content),
                    chunk_type: "file".to_string(),
                    language: Self::detect_language(&km.file_path),
                    start_line: km.line_number,
                    end_line: km.line_number,
                    keyword_score,
                    vector_score: 0.0,
                    hybrid_score: weights.0 * keyword_score,
                    snippet: Self::truncate(&km.content, 200),
                },
            );
        }

        // Add/merge vector results with RRF scores
        for (rank, sr) in semantic_results.iter().enumerate() {
            let vector_score = Self::compute_rrf_score(rank + 1, 60);
            let key = format!("{}:{}", sr.file_path, sr.chunk_name);

            if let Some(existing) = result_map.get_mut(&key) {
                // Merge: update vector score and recalculate hybrid
                existing.vector_score = vector_score;
                existing.hybrid_score =
                    weights.0 * existing.keyword_score + weights.1 * vector_score;
            } else {
                // New entry from vector search
                result_map.insert(
                    key,
                    HybridSearchResult {
                        file_path: sr.file_path.clone(),
                        chunk_name: sr.chunk_name.clone(),
                        chunk_type: sr.chunk_type.clone(),
                        language: sr.language.clone(),
                        start_line: sr.start_line,
                        end_line: sr.end_line,
                        keyword_score: 0.0,
                        vector_score,
                        hybrid_score: weights.1 * vector_score,
                        snippet: sr.snippet.clone(),
                    },
                );
            }
        }

        // Convert to vec and sort by hybrid score
        let mut results: Vec<HybridSearchResult> = result_map.into_values().collect();
        results.sort_by(|a, b| {
            b.hybrid_score
                .partial_cmp(&a.hybrid_score)
                .expect("internal error")
        });

        results
    }

    /// Compute RRF score for a given rank
    ///
    /// # Arguments
    /// * `rank` - Position in result set (1-indexed)
    /// * `k` - Constant (typically 60)
    ///
    /// # Returns
    /// RRF score (higher is better)
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "score_range")]
    pub fn compute_rrf_score(rank: usize, k: usize) -> f64 {
        let score = 1.0 / (k as f64 + rank as f64);
        debug_assert!(score > 0.0 && score <= 1.0, "RRF score out of range: {}", score);
        score
    }

    // Kani proofs are in the module below (outside impl block)
    }

#[cfg(kani)]
mod kani_proofs {
    use super::HybridSearchEngine;

    /// Prove: RRF score is always in (0, 1] for valid inputs.
    #[kani::proof]
    fn verify_rrf_score_bounded() {
        let rank: usize = kani::any();
        let k: usize = kani::any();
        kani::assume(k > 0 && k <= 100);
        kani::assume(rank <= 10000);
        let result = HybridSearchEngine::compute_rrf_score(rank, k);
        assert!(result > 0.0, "RRF score must be positive");
        assert!(result <= 1.0, "RRF score must not exceed 1.0");
    }

    /// Prove: RRF score decreases as rank increases (higher rank = lower score).
    #[kani::proof]
    fn verify_rrf_score_monotonic_decreasing() {
        let r1: usize = kani::any();
        let r2: usize = kani::any();
        let k: usize = kani::any();
        kani::assume(r1 < r2 && r2 <= 1000);
        kani::assume(k > 0 && k <= 100);
        let s1 = HybridSearchEngine::compute_rrf_score(r1, k);
        let s2 = HybridSearchEngine::compute_rrf_score(r2, k);
        assert!(s1 > s2, "higher rank must produce lower RRF score");
    }

    /// Prove: rank 0 with k=60 (standard) gives the maximum score.
    #[kani::proof]
    fn verify_rrf_rank_zero_maximum() {
        let k: usize = kani::any();
        kani::assume(k > 0 && k <= 100);
        let result = HybridSearchEngine::compute_rrf_score(0, k);
        assert_eq!(result, 1.0 / k as f64, "rank 0 score must equal 1/k");
    }
}

impl HybridSearchEngine {
    /// Apply filters to results
    fn apply_filters(
        results: Vec<HybridSearchResult>,
        query: &HybridSearchQuery,
    ) -> Vec<HybridSearchResult> {
        results
            .into_iter()
            .filter(|r| {
                // Language filter
                if let Some(ref lang) = query.language_filter {
                    if &r.language != lang {
                        return false;
                    }
                }

                // File pattern filter
                if let Some(ref pattern) = query.file_pattern {
                    if !Self::matches_pattern(&r.file_path, pattern) {
                        return false;
                    }
                }

                true
            })
            .collect()
    }

    /// Index a directory
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
    pub async fn index_directory(&self, path: &Path) -> Result<(), String> {
        self.semantic_engine.index_directory(path).await?;
        Ok(())
    }

    /// Detect language from file path
    fn detect_language(path: &str) -> String {
        if path.ends_with(".rs") {
            "rust".to_string()
        } else if path.ends_with(".ts") || path.ends_with(".tsx") {
            "typescript".to_string()
        } else if path.ends_with(".py") {
            "python".to_string()
        } else if path.ends_with(".go") {
            "go".to_string()
        } else if path.ends_with(".c") || path.ends_with(".h") {
            "c".to_string()
        } else if path.ends_with(".cpp") || path.ends_with(".hpp") || path.ends_with(".cc") || path.ends_with(".cxx") || path.ends_with(".cu") || path.ends_with(".cuh") {
            "cpp".to_string()
        } else {
            "unknown".to_string()
        }
    }

    /// Extract chunk name from content
    fn extract_chunk_name(content: &str) -> String {
        // Simple heuristic: first word or identifier
        content
            .split_whitespace()
            .find(|s| s.chars().all(|c| c.is_alphanumeric() || c == '_'))
            .unwrap_or("unknown")
            .to_string()
    }

    /// Check if path matches pattern
    fn matches_pattern(path: &str, pattern: &str) -> bool {
        if let Some(suffix) = pattern.strip_prefix('*') {
            path.ends_with(suffix)
        } else {
            path.contains(pattern)
        }
    }

    /// Truncate string to max length
    fn truncate(s: &str, max_len: usize) -> String {
        if s.len() <= max_len {
            s.to_string()
        } else {
            format!("{}...", s.get(..max_len).unwrap_or(s))
        }
    }
}