trusty-search 0.3.20

Machine-wide hybrid code search service: BM25 + vector + KG, zero cold-start, MCP server
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
use regex::Regex;
use std::sync::OnceLock;

#[derive(Debug, Clone, PartialEq)]
pub enum QueryIntent {
    Definition, // BM25-heavy: alpha=0.3, beta=0.7
    Usage,      // KG-first: alpha=0.5, beta=0.5, use_kg_first=true
    Conceptual, // vector-heavy: alpha=0.8, beta=0.2
    BugDebt,    // BM25-only: alpha=0.1, beta=0.9
    Unknown,    // balanced: alpha=0.6, beta=0.4
}

impl QueryIntent {
    pub fn weights(&self) -> (f32, f32, bool) {
        // returns (alpha_vector, beta_bm25, use_kg_first)
        match self {
            QueryIntent::Definition => (0.3, 0.7, false),
            QueryIntent::Usage => (0.5, 0.5, true),
            QueryIntent::Conceptual => (0.8, 0.2, false),
            QueryIntent::BugDebt => (0.1, 0.9, false),
            QueryIntent::Unknown => (0.6, 0.4, false),
        }
    }
}

pub struct QueryClassifier;

static DEFINITION_RE: OnceLock<Regex> = OnceLock::new();
static USAGE_RE: OnceLock<Regex> = OnceLock::new();
static CONCEPTUAL_RE: OnceLock<Regex> = OnceLock::new();
static BUG_DEBT_RE: OnceLock<Regex> = OnceLock::new();
// Entity-relationship keyword patterns (issue #21). Matched alongside the
// existing intent regexes; a hit overrides the default to bias the query
// toward the routing best-suited for that entity relationship.
static ENTITY_DEF_RE: OnceLock<Regex> = OnceLock::new();
static ENTITY_USAGE_RE: OnceLock<Regex> = OnceLock::new();
static ENTITY_BUG_RE: OnceLock<Regex> = OnceLock::new();
// Domain-term definition patterns (issue #88): PascalCase identifiers followed
// by structural keywords, and standalone structural vocabulary words.
static DOMAIN_DEF_RE: OnceLock<Regex> = OnceLock::new();
// Extended bug/debt vocabulary (issue #88).
static EXTENDED_BUG_RE: OnceLock<Regex> = OnceLock::new();
// Long natural-language conceptual queries (issue #88): ≥6 words, no code tokens.
static LONG_NL_RE: OnceLock<Regex> = OnceLock::new();

impl QueryClassifier {
    /// Classify a query string into a `QueryIntent` for routing weight selection.
    ///
    /// Why: different query shapes benefit from different BM25/vector balance;
    /// classifying up-front lets the search pipeline pick optimal weights without
    /// per-result heuristics.
    /// What: applies a priority-ordered chain of regex patterns; the first match
    /// wins. Entity-relationship keywords (issue #21) and domain-term definitions
    /// (issue #88) are checked before the generic structural patterns.
    /// Test: see the `#[cfg(test)]` module below for representative examples per intent.
    pub fn classify(query: &str) -> QueryIntent {
        let def_re = DEFINITION_RE.get_or_init(|| {
            Regex::new(
                r"(?i)\b(fn |struct |impl |trait |enum |type |def |class |function |define)\b",
            )
            .unwrap()
        });
        let usage_re = USAGE_RE.get_or_init(|| {
            Regex::new(r"(?i)\b(where is|callers of|who calls|uses of|usages|called by)\b").unwrap()
        });
        let conceptual_re = CONCEPTUAL_RE.get_or_init(|| {
            Regex::new(r"(?i)\b(how does|what is|explain|overview|architecture|design|why)\b")
                .unwrap()
        });
        let bug_re = BUG_DEBT_RE.get_or_init(|| {
            Regex::new(r"(?i)\b(TODO|FIXME|HACK|panic!|unwrap\(\)|bug|error|crash|fail)\b").unwrap()
        });
        // Entity-relationship keyword regexes (issue #21).
        let entity_def_re = ENTITY_DEF_RE
            .get_or_init(|| Regex::new(r"(?i)\b(implements|derives from|aliased as)\b").unwrap());
        let entity_usage_re =
            ENTITY_USAGE_RE.get_or_init(|| Regex::new(r"(?i)\b(tested by|co-occurs)\b").unwrap());
        let entity_bug_re =
            ENTITY_BUG_RE.get_or_init(|| Regex::new(r"(?i)\b(raises|documented by)\b").unwrap());

        // Domain-term definition patterns (issue #88).
        //
        // Pattern A: a standalone structural/schema keyword used as a noun
        //   → "definition", "interface", "schema", "enum", "model" as a whole word.
        // Pattern B: a PascalCase identifier immediately followed by a structural
        //   keyword → "RoomType definition", "Hotel struct", "UserRole enum".
        let domain_def_re = DOMAIN_DEF_RE.get_or_init(|| {
            Regex::new(
                r"(?x)
                # Pattern A — standalone structural vocabulary word
                (?i)\b(definition|interface|schema|model)\b
                |
                # Pattern B — PascalCase identifier + structural keyword
                \b[A-Z][a-zA-Z0-9]+\s+(?i)(definition|struct|class|interface|type|schema|enum|trait|model)\b
                ",
            )
            .unwrap()
        });

        // Extended bug/debt vocabulary (issue #88).
        let extended_bug_re = EXTENDED_BUG_RE.get_or_init(|| {
            Regex::new(
                r"(?i)\b(error\s+handling|deprecated|legacy|missing\s+validation|hardcoded)\b",
            )
            .unwrap()
        });

        // Long natural-language conceptual query (issue #88): ≥6 whitespace-
        // separated tokens with no code punctuation (`(`, `:`, `_`, `.`).
        let long_nl_re = LONG_NL_RE.get_or_init(|| {
            // A "code token" is any character in: ( ) : _ .
            // We match queries that have ≥6 word characters separated by spaces and
            // contain none of the above punctuation.
            Regex::new(r"^[^():_.]+(?:\s+[^():_.]+){5,}$").unwrap()
        });

        // Priority chain — most-specific patterns first.

        // Entity-keyword hits take precedence over generic patterns (issue #21).
        if entity_usage_re.is_match(query) {
            return QueryIntent::Usage;
        }
        if entity_def_re.is_match(query) {
            return QueryIntent::Definition;
        }
        if entity_bug_re.is_match(query) {
            return QueryIntent::BugDebt;
        }

        // Domain-term definition patterns (issue #88) evaluated before the
        // generic `def_re` so "enum" / "interface" etc. are not missed.
        if domain_def_re.is_match(query) {
            return QueryIntent::Definition;
        }

        // Extended bug/debt vocabulary (issue #88).
        if extended_bug_re.is_match(query) {
            return QueryIntent::BugDebt;
        }

        if usage_re.is_match(query) {
            return QueryIntent::Usage;
        }
        if def_re.is_match(query) {
            return QueryIntent::Definition;
        }
        if conceptual_re.is_match(query) {
            return QueryIntent::Conceptual;
        }
        if bug_re.is_match(query) {
            return QueryIntent::BugDebt;
        }

        // Long natural-language query with no code tokens → Conceptual (issue #88).
        // Checked after all keyword patterns so that long queries containing
        // code tokens still fall through to the generic patterns.
        let trimmed = query.trim();
        if long_nl_re.is_match(trimmed) {
            return QueryIntent::Conceptual;
        }

        QueryIntent::Unknown
    }
}

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

    #[test]
    fn test_definition_intent() {
        assert_eq!(
            QueryClassifier::classify("fn search_hybrid"),
            QueryIntent::Definition
        );
        assert_eq!(
            QueryClassifier::classify("struct CodeIndexer"),
            QueryIntent::Definition
        );
    }

    #[test]
    fn test_usage_intent() {
        assert_eq!(
            QueryClassifier::classify("callers of search_hybrid"),
            QueryIntent::Usage
        );
        assert_eq!(
            QueryClassifier::classify("where is CodeIndexer used"),
            QueryIntent::Usage
        );
    }

    #[test]
    fn test_conceptual_intent() {
        assert_eq!(
            QueryClassifier::classify("how does the search work"),
            QueryIntent::Conceptual
        );
        assert_eq!(
            QueryClassifier::classify("what is BM25"),
            QueryIntent::Conceptual
        );
    }

    #[test]
    fn test_bug_debt_intent() {
        assert_eq!(
            QueryClassifier::classify("TODO items in search"),
            QueryIntent::BugDebt
        );
        assert_eq!(
            QueryClassifier::classify("FIXME authentication"),
            QueryIntent::BugDebt
        );
    }

    #[test]
    fn test_usage_beats_definition() {
        assert_eq!(
            QueryClassifier::classify("callers of fn search_hybrid"),
            QueryIntent::Usage
        );
    }

    #[test]
    fn test_entity_implements_is_definition() {
        assert_eq!(
            QueryClassifier::classify("which types implements Embedder"),
            QueryIntent::Definition
        );
    }

    #[test]
    fn test_entity_derives_from_is_definition() {
        assert_eq!(
            QueryClassifier::classify("structs that derives from Default"),
            QueryIntent::Definition
        );
    }

    #[test]
    fn test_entity_aliased_as_is_definition() {
        assert_eq!(
            QueryClassifier::classify("Result aliased as anyhow::Result"),
            QueryIntent::Definition
        );
    }

    #[test]
    fn test_entity_tested_by_is_usage() {
        assert_eq!(
            QueryClassifier::classify("authenticate tested by login_test"),
            QueryIntent::Usage
        );
    }

    #[test]
    fn test_entity_co_occurs_is_usage() {
        assert_eq!(
            QueryClassifier::classify("symbols that co-occurs in test fixtures"),
            QueryIntent::Usage
        );
    }

    #[test]
    fn test_entity_raises_is_bug_debt() {
        assert_eq!(
            QueryClassifier::classify("functions that raises ConfigError"),
            QueryIntent::BugDebt
        );
    }

    #[test]
    fn test_entity_documented_by_is_bug_debt() {
        assert_eq!(
            QueryClassifier::classify("ParseError documented by docs/errors.md"),
            QueryIntent::BugDebt
        );
    }

    // ── Domain-term definition tests (issue #88) ────────────────────────────

    #[test]
    fn test_domain_word_definition_is_definition() {
        assert_eq!(
            QueryClassifier::classify("RoomType definition"),
            QueryIntent::Definition
        );
    }

    #[test]
    fn test_domain_pascal_struct_is_definition() {
        assert_eq!(
            QueryClassifier::classify("Hotel struct"),
            QueryIntent::Definition
        );
    }

    #[test]
    fn test_domain_pascal_interface_is_definition() {
        assert_eq!(
            QueryClassifier::classify("BookingRepository interface"),
            QueryIntent::Definition
        );
    }

    #[test]
    fn test_domain_pascal_enum_is_definition() {
        assert_eq!(
            QueryClassifier::classify("UserRole enum"),
            QueryIntent::Definition
        );
    }

    #[test]
    fn test_standalone_schema_is_definition() {
        assert_eq!(
            QueryClassifier::classify("schema for reservations"),
            QueryIntent::Definition
        );
    }

    #[test]
    fn test_standalone_interface_is_definition() {
        assert_eq!(
            QueryClassifier::classify("interface for payment processor"),
            QueryIntent::Definition
        );
    }

    #[test]
    fn test_standalone_model_is_definition() {
        assert_eq!(
            QueryClassifier::classify("model for user accounts"),
            QueryIntent::Definition
        );
    }

    #[test]
    fn test_domain_pascal_type_is_definition() {
        assert_eq!(
            QueryClassifier::classify("ReservationStatus type"),
            QueryIntent::Definition
        );
    }

    // ── Extended BugDebt tests (issue #88) ──────────────────────────────────

    #[test]
    fn test_error_handling_is_bug_debt() {
        assert_eq!(
            QueryClassifier::classify("error handling in payment flow"),
            QueryIntent::BugDebt
        );
    }

    #[test]
    fn test_deprecated_is_bug_debt() {
        assert_eq!(
            QueryClassifier::classify("deprecated authentication methods"),
            QueryIntent::BugDebt
        );
    }

    #[test]
    fn test_legacy_is_bug_debt() {
        assert_eq!(
            QueryClassifier::classify("legacy session management code"),
            QueryIntent::BugDebt
        );
    }

    #[test]
    fn test_missing_validation_is_bug_debt() {
        assert_eq!(
            QueryClassifier::classify("missing validation in user input"),
            QueryIntent::BugDebt
        );
    }

    #[test]
    fn test_hardcoded_is_bug_debt() {
        assert_eq!(
            QueryClassifier::classify("hardcoded connection strings"),
            QueryIntent::BugDebt
        );
    }

    // ── Long natural-language conceptual tests (issue #88) ──────────────────

    #[test]
    fn test_long_nl_query_is_conceptual() {
        assert_eq!(
            QueryClassifier::classify("how the reservation system handles overbooking scenarios"),
            QueryIntent::Conceptual
        );
    }

    #[test]
    fn test_long_nl_query_without_code_tokens_is_conceptual() {
        assert_eq!(
            QueryClassifier::classify("what happens when a payment method expires"),
            QueryIntent::Conceptual
        );
    }

    #[test]
    fn test_long_query_with_code_token_not_long_nl_conceptual() {
        // Contains `_` so the long-NL path should NOT fire. The query may still
        // be classified Conceptual via "how does" in the generic pattern — that
        // is correct behaviour. This test verifies that the long-NL path requires
        // no code tokens by using a query that has no other conceptual keywords.
        let result =
            QueryClassifier::classify("the payment_processor retries failed attempts five times");
        // Contains `_` → long-NL rule is suppressed; no other keyword match → Unknown
        assert_eq!(result, QueryIntent::Unknown);
    }

    #[test]
    fn test_short_nl_query_not_forced_conceptual() {
        // Only 3 words — should not match the ≥6-word pattern
        let result = QueryClassifier::classify("reservation booking flow");
        // May be Unknown, not forced to Conceptual
        assert_ne!(result, QueryIntent::Conceptual);
    }
}