knot 1.6.2

Codebase Graph + Vector RAG Indexer for Java, TypeScript, JavaScript, Kotlin, Rust, Python, Groovy, C/C++, Build Systems, and HTML/CSS codebases
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
636
637
638
639
640
641
642
643
//! Core explore_file logic shared between CLI and MCP
//!
//! Lists all code entities (classes, methods, interfaces, functions)
//! within a specific source file, organized by type.

use std::path::{Path, PathBuf};
use std::sync::Arc;

use crate::db::graph::{GraphDb, QueryExt};

use crate::cli_tools::json_entities_array;

use crate::cli_tools::append_signature_if_present;

use crate::cli_tools::format_file_line;

/// Normalize caller-supplied input to the canonical form used in the index.
///
/// Implements §4 of `docs/specs/relative_file_paths.md`:
///
/// 1. POSIX separators and no leading `./`.
/// 2. EXACT — caller already supplied the stored form (no further work).
/// 3. LOCAL-ROOT — if the input exists on disk and lives under one of the
///    known local roots (`KNOT_REPO_PATH` first, then CWD), strip the root
///    and retry as a relative path.
/// 4. SUFFIX — for the `find_files` fallback: a path-boundary
///    `ENDS WITH '/' + suffix` query lets callers pass either `Cargo.toml`
///    or `path/to/Cargo.toml` and still hit a stored entity.
pub fn normalize_explore_input(input: &str, repo_root: Option<&Path>) -> String {
    let mut normalized = input.replace('\\', "/");
    if normalized.starts_with("./") {
        normalized.drain(..2);
    }
    if let Some(root) = repo_root
        && let Some(root_str) = root.to_str()
    {
        let root_norm = root_str
            .replace('\\', "/")
            .trim_end_matches('/')
            .to_string();
        let root_with_slash = format!("{root_norm}/");
        if let Some(stripped) = normalized.strip_prefix(&root_with_slash) {
            return stripped.to_string();
        }
        if normalized == root_norm {
            return String::new();
        }
    }
    normalized
}

/// Resolve `input` to the canonical repo-relative form by consulting the
/// local filesystem when the caller passed a path that exists on disk
/// (e.g. an absolute path from a developer's checkout).
///
/// `cwd` and `repo_root` are passed in for testability. Pass
/// `std::env::current_dir().ok()` and `std::env::var("KNOT_REPO_PATH").ok()`
/// from production code.
pub fn resolve_explore_input(input: &str, cwd: Option<&Path>, repo_root: Option<&Path>) -> String {
    let mut candidate = normalize_explore_input(input, repo_root);
    let input_path = Path::new(input);

    if input_path.exists()
        && let Ok(canonical) = std::fs::canonicalize(input_path)
    {
        let roots: [Option<&Path>; 2] = [repo_root, cwd];
        for root in roots.iter().flatten() {
            if let Ok(rel) = canonical.strip_prefix(root) {
                let s = rel.to_string_lossy().replace('\\', "/");
                candidate = s.trim_start_matches("./").to_string();
                break;
            }
        }
    }
    candidate
}

/// Build the suffix query fragment used by the SUFFIX fallback of
/// `run_explore_file`. Exposed for unit tests in §10.1.
pub fn ends_with_suffix_query(suffix: &str) -> String {
    format!("ENDS WITH '/{suffix}'")
}

/// Main explore_file function called by both CLI and MCP.
pub async fn run_explore_file(
    file_path: &str,
    repo_name: Option<&str>,
    graph_db: &Arc<GraphDb>,
) -> anyhow::Result<(String, serde_json::Value)> {
    let cwd = std::env::current_dir().ok();
    let repo_root = std::env::var("KNOT_REPO_PATH").ok().map(PathBuf::from);
    let normalized_path = resolve_explore_input(file_path, cwd.as_deref(), repo_root.as_deref());

    let entities = graph_db
        .get_file_entities(&normalized_path, repo_name)
        .await?;
    let outgoing_refs = graph_db
        .get_file_outgoing_references(&normalized_path, repo_name)
        .await
        .unwrap_or_else(|_| serde_json::json!([]));

    // §4 step 6 — DISAMBIGUATE: if the exact match produced nothing, fall
    // back to a suffix search. This handles the `transition period`
    // (relative query against an old absolute index) and the common case
    // of a bare-filename query like `src/lib.rs` from any CWD.
    if entities.as_array().is_none_or(|a| a.is_empty())
        && outgoing_refs.as_array().is_none_or(|a| a.is_empty())
        && !normalized_path.is_empty()
    {
        let suffix = ends_with_suffix_query(&normalized_path);
        if let Ok(candidates) = graph_db.find_files_by_suffix(&suffix, repo_name).await
            && candidates.as_array().is_some_and(|a| !a.is_empty())
        {
            return Ok((
                normalized_path,
                serde_json::json!({
                    "entities": entities,
                    "outgoing_references": outgoing_refs,
                    "ambiguous_path_candidates": candidates,
                }),
            ));
        }
    }

    let result = serde_json::json!({
        "entities": entities,
        "outgoing_references": outgoing_refs,
    });

    Ok((normalized_path, result))
}

pub fn format_file_entities(file_path: &str, result: &serde_json::Value) -> String {
    let mut output = format!("# Entities in {}\n\n", format_file_line(file_path, None));

    let entities = json_entities_array(result);

    let outgoing_refs = result
        .as_object()
        .and_then(|obj| obj.get("outgoing_references"))
        .and_then(|v| v.as_array())
        .cloned()
        .unwrap_or_default();

    if entities.is_empty() && outgoing_refs.is_empty() {
        output.push_str("No entities found in this file.\n");
        return output;
    }

    if !entities.is_empty() {
        output.push_str(&format!("Found {} entity/entities:\n\n", entities.len()));
        append_entity_groups(&mut output, &entities);
    }

    append_outgoing_references(&mut output, &outgoing_refs);

    output
}

/// One bucket in the entity grouping table — collects every JSON `kind`
/// that maps to a given Markdown section header.
struct KindBucket {
    header: &'static str,
    kinds: &'static [&'static str],
}

/// Ordered table of every recognised entity kind and the Markdown section
/// header it should appear under. Ordering determines the section order
/// in the rendered output.
const KIND_BUCKETS: &[KindBucket] = &[
    KindBucket {
        header: "Classes",
        kinds: &["class", "kotlin_class"],
    },
    KindBucket {
        header: "Interfaces",
        kinds: &["interface", "kotlin_interface"],
    },
    KindBucket {
        header: "Objects (Singletons)",
        kinds: &["kotlin_object"],
    },
    KindBucket {
        header: "Companion Objects",
        kinds: &["kotlin_companion"],
    },
    KindBucket {
        header: "Methods",
        kinds: &["method", "kotlin_method"],
    },
    KindBucket {
        header: "Functions",
        kinds: &["function", "kotlin_function"],
    },
    KindBucket {
        header: "Properties",
        kinds: &["kotlin_property"],
    },
    KindBucket {
        header: "Python Classes",
        kinds: &["python_class"],
    },
    KindBucket {
        header: "Python Constants",
        kinds: &["python_constant"],
    },
    KindBucket {
        header: "Python Functions",
        kinds: &["python_function"],
    },
    KindBucket {
        header: "Python Methods",
        kinds: &["python_method"],
    },
    KindBucket {
        header: "Python Modules",
        kinds: &["python_module"],
    },
    KindBucket {
        header: "Structs (Rust)",
        kinds: &["rust_struct"],
    },
    KindBucket {
        header: "Enums (Rust)",
        kinds: &["rust_enum"],
    },
    KindBucket {
        header: "Unions (Rust)",
        kinds: &["rust_union"],
    },
    KindBucket {
        header: "Traits (Rust)",
        kinds: &["rust_trait"],
    },
    KindBucket {
        header: "Impl Blocks (Rust)",
        kinds: &["rust_impl"],
    },
    KindBucket {
        header: "Functions (Rust)",
        kinds: &["rust_function"],
    },
    KindBucket {
        header: "Methods (Rust)",
        kinds: &["rust_method"],
    },
    KindBucket {
        header: "Macros (Rust)",
        kinds: &["rust_macro_def", "rust_macro_invoke"],
    },
    KindBucket {
        header: "Type Aliases (Rust)",
        kinds: &["rust_type_alias"],
    },
    KindBucket {
        header: "Constants (Rust)",
        kinds: &["rust_constant"],
    },
    KindBucket {
        header: "Statics (Rust)",
        kinds: &["rust_static"],
    },
    KindBucket {
        header: "Modules (Rust)",
        kinds: &["rust_module"],
    },
    KindBucket {
        header: "Dependencies",
        kinds: &["build_dependency"],
    },
    KindBucket {
        header: "Plugins",
        kinds: &["build_plugin"],
    },
    KindBucket {
        header: "Tasks",
        kinds: &["build_task"],
    },
    KindBucket {
        header: "Pipeline Stages",
        kinds: &["pipeline_stage"],
    },
    KindBucket {
        header: "Pipeline Steps",
        kinds: &["pipeline_step"],
    },
    KindBucket {
        header: "Classes (Groovy)",
        kinds: &["groovy_class"],
    },
    KindBucket {
        header: "Interfaces (Groovy)",
        kinds: &["groovy_interface"],
    },
    KindBucket {
        header: "Traits (Groovy)",
        kinds: &["groovy_trait"],
    },
    KindBucket {
        header: "Enums (Groovy)",
        kinds: &["groovy_enum"],
    },
    KindBucket {
        header: "Methods (Groovy)",
        kinds: &["groovy_method"],
    },
    KindBucket {
        header: "Functions (Groovy)",
        kinds: &["groovy_function"],
    },
    KindBucket {
        header: "Properties (Groovy)",
        kinds: &["groovy_property"],
    },
    KindBucket {
        header: "Cargo Package",
        kinds: &["cargo_package"],
    },
    KindBucket {
        header: "Cargo Features",
        kinds: &["cargo_feature"],
    },
    KindBucket {
        header: "Workspace Members",
        kinds: &["workspace_member"],
    },
    KindBucket {
        header: "Configuration Properties",
        kinds: &["config_property"],
    },
    KindBucket {
        header: "Kubernetes Resources",
        kinds: &[
            "k8s_deployment",
            "k8s_service",
            "k8s_configmap",
            "k8s_secret",
            "k8s_ingress",
            "k8s_namespace",
            "k8s_resource",
        ],
    },
    KindBucket {
        header: "Helm Chart",
        kinds: &["helm_chart"],
    },
    KindBucket {
        header: "Helm Values",
        kinds: &["helm_value"],
    },
    KindBucket {
        header: "Template Variables",
        kinds: &["helm_template_var"],
    },
];

const OTHERS_HEADER: &str = "Other Entities";

/// Group `entities` by [`KIND_BUCKETS`] and append a Markdown section per
/// non-empty bucket (plus a final `Other Entities` bucket for any kinds
/// not present in the table).
fn append_entity_groups(output: &mut String, entities: &[serde_json::Value]) {
    let mut buckets: Vec<Vec<&serde_json::Value>> = vec![Vec::new(); KIND_BUCKETS.len()];
    let mut others: Vec<&serde_json::Value> = Vec::new();

    for entity in entities {
        let kind = entity.get("kind").and_then(|v| v.as_str()).unwrap_or("");
        match KIND_BUCKETS.iter().position(|b| b.kinds.contains(&kind)) {
            Some(idx) => buckets[idx].push(entity),
            None => others.push(entity),
        }
    }

    for (bucket, items) in KIND_BUCKETS.iter().zip(buckets) {
        if items.is_empty() {
            continue;
        }
        output.push_str(&format!("## {}\n\n", bucket.header));
        for entity in items {
            output.push_str(&format_entity_summary(entity));
        }
    }

    if !others.is_empty() {
        output.push_str(&format!("## {OTHERS_HEADER}\n\n"));
        for entity in others {
            output.push_str(&format_entity_summary(entity));
        }
    }
}

/// Append the "Imports / Referenced Types" section, deduplicating on
/// `(name, kind, file_path)`.
fn append_outgoing_references(output: &mut String, outgoing_refs: &[serde_json::Value]) {
    if outgoing_refs.is_empty() {
        return;
    }

    output.push_str("## Imports / Referenced Types\n\n");
    let mut seen = std::collections::HashSet::new();
    for entry in outgoing_refs {
        let name = entry.get("name").and_then(|v| v.as_str()).unwrap_or("");
        let kind = entry.get("kind").and_then(|v| v.as_str()).unwrap_or("");
        let fp = entry
            .get("file_path")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        let line_num = entry.get("line").and_then(|v| v.as_i64()).unwrap_or(0);

        let key = format!("{}:{}:{}", name, kind, fp);
        if !seen.insert(key) {
            continue;
        }
        if line_num > 0 && !fp.is_empty() {
            output.push_str(&format!("- {} ({}) — {}:{}\n", name, kind, fp, line_num));
        } else {
            output.push_str(&format!("- {} ({})\n", name, kind));
        }
    }
    output.push('\n');
}

/// Format entity summary as Markdown
fn format_entity_summary(entity: &serde_json::Value) -> String {
    let mut output = String::new();

    if let Some(name) = entity.get("name").and_then(|v| v.as_str()) {
        output.push_str(&format!("- **`{}`**", name));

        if let Some(start_line) = entity.get("start_line").and_then(|v| v.as_i64()) {
            output.push_str(&format!(" (line {})", start_line));
        }

        output.push('\n');

        if let Some(decorators_array) = entity.get("decorators").and_then(|v| v.as_array())
            && !decorators_array.is_empty()
        {
            let decorator_strs: Vec<String> = decorators_array
                .iter()
                .filter_map(|v| v.as_str())
                .map(|s| s.to_string())
                .collect();
            if !decorator_strs.is_empty() {
                output.push_str(&format!("  - Decorators: {}\n", decorator_strs.join(", ")));
            }
        }

        append_signature_if_present(&mut output, entity);

        if let Some(docstring) = entity
            .get("docstring")
            .and_then(|v| v.as_str())
            .filter(|s| !s.trim().is_empty())
        {
            let doc_preview = docstring.lines().next().unwrap_or("");
            output.push_str(&format!("  - Doc: {}\n", doc_preview));
        }

        output.push('\n');
    }

    output
}

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

    #[test]
    fn test_format_file_entities_empty() {
        let entities = json!([]);
        let formatted = format_file_entities("src/main.java", &entities);
        assert!(formatted.contains("No entities found in this file"));
    }

    #[test]
    fn test_format_file_entities_single_class() {
        let entities = json!([
            {
                "name": "MyClass",
                "kind": "class",
                "start_line": 10,
                "signature": "public class MyClass"
            }
        ]);
        let formatted = format_file_entities("src/main.java", &entities);
        assert!(formatted.contains("## Classes"));
        assert!(formatted.contains("MyClass"));
        assert!(formatted.contains("(line 10)"));
        assert!(formatted.contains("public class MyClass"));
    }

    #[test]
    fn test_format_file_entities_multiple_classes() {
        let entities = json!([
            {
                "name": "Class1",
                "kind": "class",
                "start_line": 10
            },
            {
                "name": "Class2",
                "kind": "class",
                "start_line": 50
            }
        ]);
        let formatted = format_file_entities("src/main.java", &entities);
        assert!(formatted.contains("Found 2 entity/entities"));
        assert!(formatted.contains("Class1"));
        assert!(formatted.contains("Class2"));
    }

    #[test]
    fn test_format_file_entities_groups_by_kind() {
        let entities = json!([
            {"name": "MyClass", "kind": "class"},
            {"name": "MyInterface", "kind": "interface"},
            {"name": "myMethod", "kind": "method"},
            {"name": "myFunction", "kind": "function"}
        ]);
        let formatted = format_file_entities("src/main.java", &entities);
        assert!(formatted.contains("## Classes"));
        assert!(formatted.contains("## Interfaces"));
        assert!(formatted.contains("## Methods"));
        assert!(formatted.contains("## Functions"));
    }

    #[test]
    fn test_format_entity_summary_with_signature() {
        let entity = json!({
            "name": "myMethod",
            "kind": "method",
            "start_line": 20,
            "signature": "public void myMethod(String param)"
        });
        let formatted = format_entity_summary(&entity);
        assert!(formatted.contains("myMethod"));
        assert!(formatted.contains("(line 20)"));
        assert!(formatted.contains("public void myMethod(String param)"));
    }

    #[test]
    fn test_format_entity_summary_with_docstring() {
        let entity = json!({
            "name": "myMethod",
            "kind": "method",
            "docstring": "First line of doc\nSecond line of doc"
        });
        let formatted = format_entity_summary(&entity);
        assert!(formatted.contains("myMethod"));
        assert!(formatted.contains("First line of doc"));
        assert!(!formatted.contains("Second line of doc"));
    }

    #[test]
    fn test_format_entity_summary_ignores_whitespace_docstring() {
        let entity = json!({
            "name": "myMethod",
            "kind": "method",
            "docstring": "   \n  \t"
        });
        let formatted = format_entity_summary(&entity);
        assert!(!formatted.contains("- Doc:"));
    }

    #[test]
    fn test_format_entity_summary_without_optional_fields() {
        let entity = json!({
            "name": "MyClass",
            "kind": "class"
        });
        let formatted = format_entity_summary(&entity);
        assert!(formatted.contains("MyClass"));
        assert!(!formatted.contains("(line"));
        assert!(!formatted.contains("Signature:"));
    }

    #[test]
    fn test_format_file_entities_unknown_kind() {
        let entities = json!([
            {
                "name": "UnknownEntity",
                "kind": "unknown_kind"
            }
        ]);
        let formatted = format_file_entities("src/main.java", &entities);
        // Unknown kinds fall into the "Other Entities" bucket so they remain visible.
        assert!(formatted.contains("UnknownEntity"));
        assert!(formatted.contains("Found 1 entity/entities"));
        assert!(formatted.contains("## Other Entities"));
    }

    #[test]
    fn test_format_file_entities_displays_file_path() {
        let entities = json!([
            {"name": "MyClass", "kind": "class"}
        ]);
        let formatted = format_file_entities("src/main/java/MyClass.java", &entities);
        assert!(formatted.contains("src/main/java/MyClass.java"));
    }

    // ---- §10.1 unit tests for input normalization ----

    #[test]
    fn test_normalize_input_strips_dot_slash_and_backslashes() {
        let root = Path::new("/repo");
        let result = normalize_explore_input("./src\\lib.rs", Some(root));
        assert_eq!(result, "src/lib.rs");
    }

    #[test]
    fn test_normalize_input_passthrough_when_no_root() {
        let result = normalize_explore_input("src/lib.rs", None);
        assert_eq!(result, "src/lib.rs");
    }

    #[test]
    fn test_normalize_input_strips_known_absolute_root() {
        let root = Path::new("/home/user/myrepo");
        let result = normalize_explore_input("/home/user/myrepo/src/lib.rs", Some(root));
        assert_eq!(result, "src/lib.rs");
    }

    #[test]
    fn test_normalize_absolute_unknown_root_passthrough() {
        // Path under no known root must be passed through verbatim
        // (after backslash/dot-slash normalization) — the SUFFIX fallback
        // in `run_explore_file` is what eventually matches it.
        let root = Path::new("/home/user/myrepo");
        let result = normalize_explore_input("/elsewhere/src/lib.rs", Some(root));
        assert_eq!(result, "/elsewhere/src/lib.rs");
    }

    #[test]
    fn test_ends_with_suffix_query_uses_path_boundary() {
        // Spec §4 step 5: the '/' guard prevents `bar/baz.rs` matching
        // `foobar/baz.rs`.
        let fragment = ends_with_suffix_query("src/lib.rs");
        assert_eq!(fragment, "ENDS WITH '/src/lib.rs'");
    }
}