knot 1.8.1

Codebase Graph + Vector RAG Indexer for Java, TypeScript, JavaScript, Kotlin, Rust, Python, Groovy, C/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
//! Table output formatters for CLI.
//!
//! Formats search results, callers, and file entities as ASCII tables
//! using the comfy-table crate for human-readable console output.

use comfy_table::{Cell, CellAlignment, Color, ContentArrangement, Table};
use serde_json::Value;

use crate::cli_tools::resolution::ResolutionView;
use crate::cli_tools::{json_entities_array, json_line_number, json_target_name};

pub fn format_search_table(results: &Value) -> String {
    let mut table = Table::new();
    table.set_content_arrangement(ContentArrangement::DynamicFullWidth);
    table.set_header(vec![
        Cell::new("Kind")
            .set_alignment(CellAlignment::Center)
            .fg(Color::Cyan),
        Cell::new("Name").fg(Color::Green),
        Cell::new("File").fg(Color::White),
        Cell::new("Line")
            .set_alignment(CellAlignment::Right)
            .fg(Color::Yellow),
    ]);

    if let Some(arr) = results.as_array() {
        for entity in arr {
            let kind = entity.get("kind").and_then(|v| v.as_str()).unwrap_or("-");
            let name = entity.get("name").and_then(|v| v.as_str()).unwrap_or("-");
            let file = entity
                .get("file_path")
                .and_then(|v| v.as_str())
                .unwrap_or("-");
            let line = json_line_number(entity);
            let kind_color = match kind {
                "class" | "python_class" => Color::Yellow,
                "interface" => Color::Cyan,
                "method" | "function" | "python_method" | "python_function" => Color::Blue,
                "variable" | "field" => Color::Magenta,
                _ => Color::White,
            };

            let name_cell = match entity.get("repo_name").and_then(|v| v.as_str()) {
                Some(repo) => Cell::new(format!("{name} (repo: {repo})")),
                None => Cell::new(name),
            };

            table.add_row(vec![
                Cell::new(kind).fg(kind_color),
                name_cell,
                Cell::new(file),
                Cell::new(line).set_alignment(CellAlignment::Right),
            ]);
        }
    }

    if table.row_iter().count() == 0 {
        return "No matching code found for your query.".to_string();
    }

    table.to_string()
}

pub fn format_callers_table(entity_name: &str, references: &Value) -> String {
    let mut table = Table::new();
    table.set_content_arrangement(ContentArrangement::DynamicFullWidth);
    table.set_header(vec![
        Cell::new("Relationship")
            .set_alignment(CellAlignment::Center)
            .fg(Color::Cyan),
        Cell::new("Target").fg(Color::Magenta),
        Cell::new("Caller").fg(Color::Green),
        Cell::new("File").fg(Color::White),
        Cell::new("Line")
            .set_alignment(CellAlignment::Right)
            .fg(Color::Yellow),
    ]);

    let mut total_refs = 0;

    let rel_types = [
        ("calls", "Calls", Color::Blue),
        ("extends", "Extends", Color::Yellow),
        ("implements", "Implements", Color::Cyan),
        ("references", "References", Color::Magenta),
    ];

    for (key, label, label_color) in rel_types {
        let Some(arr) = references.get(key).and_then(|v| v.as_array()) else {
            continue;
        };
        for entity in arr {
            total_refs += 1;
            // Prefer target_fqn when available (qualified identifiers
            // disambiguate homonyms like `WidgetA::new` vs `WidgetB::new`).
            let target = json_target_name(entity, entity_name);
            let caller_name = entity.get("name").and_then(|v| v.as_str()).unwrap_or("-");
            let caller_repo = entity
                .get("repo_name")
                .and_then(|v| v.as_str())
                .filter(|s| !s.is_empty());
            let caller = match caller_repo {
                Some(repo) => format!("{caller_name} (repo: {repo})"),
                None => caller_name.to_string(),
            };
            // Reference repo attribution (v1.8.1), rule R3: the
            // Target column repeats once per row, so it is labeled only for
            // genuine cross-repo references to avoid doubling the noise.
            let target_repo = entity
                .get("target_repo_name")
                .and_then(|v| v.as_str())
                .filter(|s| !s.is_empty());
            let target_cell = match target_repo {
                Some(target_repo) if Some(target_repo) != caller_repo => {
                    format!("{target} (repo: {target_repo})")
                }
                _ => target,
            };
            let file = entity
                .get("file_path")
                .and_then(|v| v.as_str())
                .unwrap_or("-");
            let line = json_line_number(entity);

            table.add_row(vec![
                Cell::new(label).fg(label_color),
                Cell::new(target_cell).fg(Color::Magenta),
                Cell::new(caller),
                Cell::new(file),
                Cell::new(line).set_alignment(CellAlignment::Right),
            ]);
        }
    }

    if total_refs == 0 {
        let mut no_ref_msg = callers_resolution_detail(references);
        no_ref_msg.push_str(&format!(
            "No references found for `{}`. This entity may be unused.\n",
            entity_name
        ));
        return no_ref_msg;
    }

    let header = callers_resolution_header(entity_name, references, total_refs);
    header + &table.to_string()
}

/// Verbose resolution block shown when no references were found: the target
/// list is the only useful signal left, so it is spelled out in full.
fn callers_resolution_detail(references: &Value) -> String {
    let Some(view) = ResolutionView::from_references(references) else {
        return String::new();
    };

    let mut out = format!("{}:\n", view.summary());
    out.push_str(&view.target_bullets());
    out.push('\n');

    if view.is_fuzzy() {
        out.push_str(&format!(
            "WARNING: Fuzzy match — no entity matched `{}` exactly.\n\n",
            view.query()
        ));
    }

    out
}

/// One-line resolution header shown above the caller table.
fn callers_resolution_header(entity_name: &str, references: &Value, total_refs: usize) -> String {
    let Some(view) = ResolutionView::from_references(references) else {
        return format!("References to `{}` ({} total)\n", entity_name, total_refs);
    };

    let mut out = format!("{} ({} references total)\n", view.summary(), total_refs);

    if view.is_fuzzy() {
        out.push_str(&format!(
            "WARNING: Fuzzy match — no entity matched `{}` exactly.\n",
            view.query()
        ));
    }

    if view.is_truncated() {
        out.push_str(&format!(
            "Truncated — {} targets matched; showing first {} by FQN.\n",
            view.total_targets(),
            view.count()
        ));
    }

    out
}

pub fn format_explore_table(file_path: &str, result: &Value) -> String {
    let mut table = Table::new();
    table.set_content_arrangement(ContentArrangement::DynamicFullWidth);
    table.set_header(vec![
        Cell::new("Type")
            .set_alignment(CellAlignment::Center)
            .fg(Color::Cyan),
        Cell::new("Name").fg(Color::Green),
        Cell::new("Line")
            .set_alignment(CellAlignment::Right)
            .fg(Color::Yellow),
        Cell::new("Signature / Doc").fg(Color::White),
    ]);

    let arr = json_entities_array(result);

    for entity in &arr {
        let kind = entity.get("kind").and_then(|v| v.as_str()).unwrap_or("-");
        let name = entity.get("name").and_then(|v| v.as_str()).unwrap_or("-");
        let line = json_line_number(entity);

        let sig_or_doc = entity
            .get("signature")
            .and_then(|v| v.as_str())
            .filter(|s| !s.is_empty())
            .map(|s| s.to_string())
            .or_else(|| {
                entity
                    .get("docstring")
                    .and_then(|v| v.as_str())
                    .filter(|s| !s.trim().is_empty())
                    .map(|s| s.lines().next().unwrap_or("").to_string())
            })
            .unwrap_or_else(|| "-".to_string());

        let kind_color = match kind {
            "class" | "python_class" => Color::Yellow,
            "interface" => Color::Cyan,
            "method" | "function" | "python_method" | "python_function" => Color::Blue,
            "variable" | "field" => Color::Magenta,
            _ => Color::White,
        };

        table.add_row(vec![
            Cell::new(kind).fg(kind_color),
            Cell::new(name),
            Cell::new(line).set_alignment(CellAlignment::Right),
            Cell::new(sig_or_doc),
        ]);
    }

    if table.row_iter().count() == 0 {
        return format!("No entities found in `{}`.\n", file_path);
    }

    let count = arr.len();
    let header = format!("Entities in `{}` ({} found)\n", file_path, count);
    header + &table.to_string()
}

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

    #[test]
    fn test_format_search_table_empty() {
        let results = json!([]);
        let output = format_search_table(&results);
        assert!(output.contains("No matching code found"));
    }

    #[test]
    fn test_format_search_table_with_results() {
        let results = json!([
            {
                "name": "MyClass",
                "kind": "class",
                "file_path": "src/main.java",
                "start_line": 10
            }
        ]);
        let output = format_search_table(&results);
        assert!(output.contains("MyClass"));
        assert!(output.contains("class"));
        assert!(output.contains("src/main.java"));
        assert!(output.contains("10"));
    }

    #[test]
    fn test_format_search_table_multiple_results() {
        let results = json!([
            {"name": "Class1", "kind": "class", "file_path": "file1.java", "start_line": 1},
            {"name": "Class2", "kind": "interface", "file_path": "file2.java", "start_line": 20}
        ]);
        let output = format_search_table(&results);
        assert!(output.contains("Class1"));
        assert!(output.contains("Class2"));
    }

    #[test]
    fn test_format_callers_table_empty() {
        let references = json!({
            "calls": [],
            "extends": [],
            "implements": [],
            "references": []
        });
        let output = format_callers_table("MyEntity", &references);
        assert!(output.contains("No references found"));
        assert!(output.contains("MyEntity"));
    }

    #[test]
    fn test_format_callers_table_with_references() {
        let references = json!({
            "calls": [
                {"name": "caller1", "kind": "method", "file_path": "file1.java", "start_line": 10}
            ],
            "extends": [],
            "implements": [],
            "references": []
        });
        let output = format_callers_table("MyEntity", &references);
        assert!(output.contains("References to `MyEntity`"));
        assert!(output.contains("caller1"));
        assert!(output.contains("Calls"));
    }

    #[test]
    fn callers_table_labels_caller_repo() {
        let references = json!({
            "calls": [
                {
                    "name": "caller1", "kind": "method",
                    "file_path": "file1.java", "start_line": 10,
                    "repo_name": "alpha", "target_repo_name": "alpha"
                }
            ],
            "extends": [],
            "implements": [],
            "references": []
        });
        let output = format_callers_table("MyEntity", &references);
        assert!(output.contains("caller1 (repo: alpha)"), "got {output}");
    }

    #[test]
    fn callers_table_labels_target_repo_when_different() {
        let references = json!({
            "calls": [
                {
                    "name": "caller1", "kind": "method",
                    "file_path": "file1.java", "start_line": 10,
                    "target_fqn": "beta::SharedUtil::work",
                    "repo_name": "alpha", "target_repo_name": "beta"
                }
            ],
            "extends": [],
            "implements": [],
            "references": []
        });
        let output = format_callers_table("MyEntity", &references);
        assert!(
            output.contains("beta::SharedUtil::work (repo: beta)"),
            "got {output}"
        );
    }

    #[test]
    fn callers_table_omits_target_label_when_same_repo() {
        let references = json!({
            "calls": [
                {
                    "name": "caller1", "kind": "method",
                    "file_path": "file1.java", "start_line": 10,
                    "repo_name": "alpha", "target_repo_name": "alpha"
                }
            ],
            "extends": [],
            "implements": [],
            "references": []
        });
        let output = format_callers_table("MyEntity", &references);
        // Rule R3: intra-repo reference — the Target cell stays bare.
        assert!(!output.contains("MyEntity (repo:"), "got {output}");
    }

    #[test]
    fn test_format_explore_table_empty() {
        let entities = json!([]);
        let output = format_explore_table("test.java", &entities);
        assert!(output.contains("No entities found"));
    }

    #[test]
    fn test_format_explore_table_with_entities() {
        let entities = json!([
            {
                "name": "MyClass",
                "kind": "class",
                "start_line": 10,
                "signature": "public class MyClass"
            }
        ]);
        let output = format_explore_table("test.java", &entities);
        assert!(output.contains("Entities in `test.java`"));
        assert!(output.contains("MyClass"));
        assert!(output.contains("class"));
    }

    #[test]
    fn test_format_explore_table_with_docstring() {
        let entities = json!([
            {
                "name": "myMethod",
                "kind": "method",
                "start_line": 20,
                "docstring": "This is a method"
            }
        ]);
        let output = format_explore_table("test.java", &entities);
        assert!(output.contains("myMethod"));
        assert!(output.contains("This is a method"));
    }
}