leankg 0.15.3

Lightweight Knowledge Graph for AI-Assisted Development
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
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Intent {
    pub query_type: String,
    pub target: Option<String>,
    pub confidence: f32,
}

pub struct IntentParser {
    patterns: Vec<IntentPattern>,
}

struct IntentPattern {
    keywords: Vec<&'static str>,
    query_type: &'static str,
    confidence: f32,
}

impl IntentParser {
    pub fn new() -> Self {
        let patterns = vec![
            IntentPattern {
                keywords: vec![
                    "context",
                    "content",
                    "read",
                    "file",
                    "show me",
                    "what's in",
                    "what is in",
                ],
                query_type: "context",
                confidence: 0.9,
            },
            IntentPattern {
                keywords: vec![
                    "impact", "affect", "changing", "change", "changes", "effects", "ripple",
                    "break",
                ],
                query_type: "impact",
                confidence: 0.85,
            },
            IntentPattern {
                keywords: vec!["depend", "import", "require", "use"],
                query_type: "dependencies",
                confidence: 0.85,
            },
            IntentPattern {
                keywords: vec!["search", "find", "look for", "where is", "locate"],
                query_type: "search",
                confidence: 0.8,
            },
            IntentPattern {
                keywords: vec!["doc", "document", "readme", "spec", "requirement"],
                query_type: "doc",
                confidence: 0.85,
            },
            IntentPattern {
                keywords: vec!["test", "spec", "unit"],
                query_type: "test",
                confidence: 0.8,
            },
            IntentPattern {
                keywords: vec!["trace", "traceability", "requirement", "user story"],
                query_type: "traceability",
                confidence: 0.85,
            },
        ];
        Self { patterns }
    }

    pub fn parse(&self, intent_str: &str) -> Intent {
        let lower = intent_str.to_lowercase();

        let mut best_match: Option<Intent> = None;
        let mut best_confidence: f32 = 0.0;

        for pattern in &self.patterns {
            let matches = pattern
                .keywords
                .iter()
                .filter(|kw| lower.contains(*kw))
                .count();

            if matches > 0 {
                let confidence =
                    pattern.confidence * (matches as f32 / pattern.keywords.len() as f32);

                if confidence > best_confidence {
                    best_confidence = confidence;
                    best_match = Some(Intent {
                        query_type: pattern.query_type.to_string(),
                        target: self.extract_target(&lower),
                        confidence,
                    });
                }
            }
        }

        best_match.unwrap_or_else(|| Intent {
            query_type: "context".to_string(),
            target: self.extract_target(&lower),
            confidence: 0.5,
        })
    }

    fn extract_target(&self, text: &str) -> Option<String> {
        let markers = ["for ", "of ", "in ", "to ", "from ", "named "];
        let file_extensions = [
            ".rs", ".md", ".go", ".ts", ".js", ".py", ".java", ".cpp", ".c", ".h", ".tsx", ".jsx",
            ".cs", ".swift", ".kt",
        ];
        let path_indicators = [
            "src/",
            "lib/",
            "bin/",
            "test/",
            "tests/",
            "benches/",
            "examples/",
            "docs/",
            "scripts/",
        ];
        // Common action words that often appear between marker and actual target
        let skip_words = [
            "the",
            "a",
            "an",
            "changing",
            "change",
            "changing",
            "update",
            "updating",
            "modifying",
            "modify",
            "editing",
            "edit",
            "removing",
            "remove",
            "adding",
            "add",
            "creating",
            "create",
            "deleting",
            "delete",
            "impact",
            "affect",
            "affected",
            "affecting",
            "file",
            "files",
        ];

        for marker in &markers {
            if let Some(pos) = text.find(marker) {
                let start = pos + marker.len();
                let rest = &text[start..];

                // Find all tokens (words) in the rest of the string
                let words: Vec<&str> = rest.split_whitespace().collect();

                // First, scan for file extensions or paths in all words after the marker
                for word in &words {
                    let cleaned = word.trim_matches(|c: char| c.is_ascii_punctuation());
                    // Check for file with extension
                    if file_extensions.iter().any(|ext| cleaned.ends_with(ext)) {
                        return Some(cleaned.to_string());
                    }
                    // Check for path-like structures (e.g., src/main.rs)
                    if path_indicators.iter().any(|p| cleaned.starts_with(p))
                        && cleaned.contains('/')
                    {
                        return Some(cleaned.to_string());
                    }
                }

                // If no file/path found, try the first word if it's not a skip word
                if let Some(first_word) = words.first() {
                    let cleaned = first_word.trim_matches(|c: char| c.is_ascii_punctuation());
                    if !cleaned.is_empty() && cleaned.len() > 1 && !skip_words.contains(&cleaned) {
                        // Check for module-like names (lowercase with underscores)
                        if cleaned.contains('_')
                            && cleaned
                                .chars()
                                .next()
                                .map(|c| c.is_lowercase())
                                .unwrap_or(false)
                        {
                            return Some(cleaned.to_string());
                        }

                        // Check for file extension in first token
                        if file_extensions.iter().any(|ext| cleaned.ends_with(ext)) {
                            return Some(cleaned.to_string());
                        }
                    }
                }

                // Try to find file extension anywhere in the remaining text
                for (i, _) in rest.char_indices() {
                    if file_extensions.iter().any(|ext| rest[i..].starts_with(ext)) {
                        let remaining = &rest[i..];
                        let word_end = remaining
                            .find(|c: char| {
                                c.is_whitespace() || c == ',' || c == '\n' || c == '"' || c == '\''
                            })
                            .map(|p| i + p)
                            .unwrap_or(rest.len());
                        let word_start = rest[..i]
                            .rfind(|c: char| {
                                c.is_whitespace() || c == ',' || c == '\n' || c == '"' || c == '\''
                            })
                            .map(|p| p + 1)
                            .unwrap_or(0);
                        let candidate = &rest[word_start..word_end];
                        if !candidate.is_empty() && candidate.len() > 1 {
                            return Some(candidate.to_string());
                        }
                    }
                }
            }
        }

        // Try to find a module-like name (lowercase with underscores, e.g., "orchestrator", "cache_module")
        // This helps when user says "show me the orchestrator module" without a marker
        let words: Vec<&str> = text.split_whitespace().collect();

        // First priority: any word with a file extension
        for word in &words {
            let cleaned = word.trim_matches(|c: char| c.is_ascii_punctuation());
            if file_extensions.iter().any(|ext| cleaned.ends_with(ext)) {
                return Some(cleaned.to_string());
            }
        }

        // Second priority: module names with underscores (e.g., "cache_module")
        for word in &words {
            let cleaned = word.trim_matches(|c: char| c.is_ascii_punctuation());
            if cleaned.len() >= 3
                && cleaned
                    .chars()
                    .next()
                    .map(|c| c.is_lowercase())
                    .unwrap_or(false)
                && cleaned.contains('_')
            {
                return Some(cleaned.to_string());
            }
        }

        // Third priority: single lowercase words that might be module names (e.g., "orchestrator")
        for word in &words {
            let cleaned = word.trim_matches(|c: char| c.is_ascii_punctuation());
            // Skip common words, look for likely module names
            if cleaned.len() >= 4
                && cleaned
                    .chars()
                    .next()
                    .map(|c| c.is_lowercase())
                    .unwrap_or(false)
                && ![
                    "the", "for", "with", "from", "this", "that", "file", "module", "show",
                ]
                .contains(&cleaned)
            {
                // Check if it looks like a module/class name (camelCase or snake_case)
                if cleaned.contains('_')
                    || (cleaned.chars().all(|c| c.is_lowercase()) && cleaned.len() > 6)
                {
                    return Some(cleaned.to_string());
                }
            }
        }

        // Try to extract identifier after function/class keywords
        let func_markers = ["function ", "class ", "struct ", "enum ", "trait ", "impl "];
        for marker in &func_markers {
            if let Some(pos) = text.find(marker) {
                let start = pos + marker.len();
                let rest = &text[start..];
                let first_token_end = rest
                    .find(|c: char| c.is_whitespace() || c == '(' || c == '{')
                    .unwrap_or(rest.len());
                let first_token = &rest[..first_token_end];
                if !first_token.is_empty() && first_token.len() > 1 {
                    return Some(first_token.to_string());
                }
            }
        }

        let words: Vec<&str> = text.split_whitespace().collect();
        if let Some(last) = words.last() {
            let cleaned = last.trim_matches(|c: char| c.is_ascii_punctuation());
            if !cleaned.is_empty() && file_extensions.iter().any(|ext| cleaned.ends_with(ext)) {
                return Some(cleaned.to_string());
            }
        }

        None
    }
}

impl Default for IntentParser {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_parse_context_intent() {
        let parser = IntentParser::new();

        let intent = parser.parse("show me context for src/main.rs");
        assert_eq!(intent.query_type, "context");
        assert_eq!(intent.target, Some("src/main.rs".to_string()));
    }

    #[test]
    fn test_parse_impact_intent() {
        let parser = IntentParser::new();

        let intent = parser.parse("what's the impact of changing lib.rs");
        assert_eq!(intent.query_type, "impact");
        assert_eq!(intent.target, Some("lib.rs".to_string()));
    }

    #[test]
    fn test_parse_dependencies_intent() {
        let parser = IntentParser::new();

        let intent = parser.parse("show dependencies of handler.rs");
        assert_eq!(intent.query_type, "dependencies");
        assert_eq!(intent.target, Some("handler.rs".to_string()));
    }

    #[test]
    fn test_parse_search_intent() {
        let parser = IntentParser::new();

        let intent = parser.parse("find function named parse_config");
        assert_eq!(intent.query_type, "search");
        assert_eq!(intent.target, Some("parse_config".to_string()));
    }

    #[test]
    fn test_parse_doc_intent() {
        let parser = IntentParser::new();

        let intent = parser.parse("get documentation for api.rs");
        assert_eq!(intent.query_type, "doc");
        assert_eq!(intent.target, Some("api.rs".to_string()));
    }

    #[test]
    fn test_parse_no_match() {
        let parser = IntentParser::new();

        let intent = parser.parse("hello world");
        assert_eq!(intent.query_type, "context");
        assert_eq!(intent.target, None);
    }

    #[test]
    fn test_extract_target_with_file() {
        let parser = IntentParser::new();

        let intent = parser.parse("analyze src/lib.rs");
        assert_eq!(intent.target, Some("src/lib.rs".to_string()));
    }

    #[test]
    fn test_extract_target_without_marker() {
        let parser = IntentParser::new();

        let intent = parser.parse("context main.rs");
        assert!(intent.target.is_some());
    }

    #[test]
    fn test_confidence_scoring() {
        let parser = IntentParser::new();

        let intent1 = parser.parse("context for file.rs");
        let intent2 = parser.parse("give me the context for the file");

        assert!(intent1.confidence >= 0.0);
        assert!(intent2.confidence >= 0.0);
    }

    #[test]
    fn test_parse_impact_intent_with_path() {
        let parser = IntentParser::new();

        // This is the specific failing case: action word "changing" between marker and path
        let intent = parser.parse("show me impact of changing src/mcp/handler.rs");
        assert_eq!(intent.query_type, "impact");
        assert_eq!(intent.target, Some("src/mcp/handler.rs".to_string()));
    }
}