knot 1.11.8

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
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
//! 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()
}

/// One relationship-bucket row in the callers table.
///
/// Extracted from [`format_callers_table`] to keep that function within
/// clippy's line budget; behavior unchanged (v1.8.1 repo-attribution rules
/// included).
fn add_caller_table_row(
    table: &mut Table,
    entity: &Value,
    entity_name: &str,
    label: &str,
    label_color: Color,
) {
    // 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),
    ]);
}

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),
        ("macro_calls", "Macro calls", Color::Blue),
        ("references_dom", "DOM refs", Color::Green),
        ("uses_css_class", "CSS class", Color::Green),
        ("imports_script", "Script import", Color::Green),
        ("imports_stylesheet", "Stylesheet import", Color::Green),
        ("uses_backend", "VCL backend", Color::Green),
        ("uses_probe", "VCL probe", Color::Green),
        ("uses_acl", "VCL acl", Color::Green),
        ("includes", "VCL include", Color::Green),
        ("imports_vmod", "VMOD import", Color::Green),
        ("declared_unused", "Declared unused", Color::Green),
        ("overridden_by", "Overridden by", Color::Yellow),
        ("overrides", "Overrides", Color::Cyan),
        ("dispatched_calls", "Dispatched call", Color::Blue),
    ];

    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;
            add_caller_table_row(&mut table, entity, entity_name, label, label_color);
        }
    }

    if total_refs == 0 {
        let mut no_ref_msg = callers_resolution_detail(references);
        // Markdown parity: three honest outcomes keyed on the resolution,
        // legacy wording when there is no parseable resolution block.
        let outcome = match ResolutionView::from_references(references) {
            Some(view) if view.count() > 0 || view.total_targets() > 0 => "unused",
            Some(view) if view.hidden_non_code() > 0 => "hidden_only",
            Some(_) => "not_found",
            None => "legacy",
        };
        match outcome {
            "unused" | "legacy" => no_ref_msg.push_str(&format!(
                "No references found for `{}`. This entity may be unused.\n",
                entity_name
            )),
            "hidden_only" => no_ref_msg.push_str(&format!(
                "No code entity matched `{}` — see the NOTE above; the name only hit \
                 documentation/config/build metadata.\n",
                entity_name
            )),
            _ => no_ref_msg.push_str(&format!(
                "No entity named `{}` was found in the indexed scope. Check the spelling, \
                 the repository scope (--repo), or search semantically first.\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()
        ));
    }

    // Markdown parity: the hidden-matches disclosure has to reach the table
    // output too, or CLI table readers would see a silently narrowed view.
    let hidden = view.hidden_notice(false);
    if !hidden.is_empty() {
        out.push_str(&format!("NOTE: {hidden}\n\n"));
    }

    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()
        ));
        // Same guarantee as the Markdown formatter: bucket counts are only
        // partial when the target list was truncated, and the reader must
        // know it without inferring it.
        out.push_str(&format!("{}\n", view.partial_counts_caveat()));
    }

    let hidden = view.hidden_notice(false);
    if !hidden.is_empty() {
        out.push_str(&format!("NOTE: {hidden}\n"));
    }

    out
}

pub fn format_explore_table(file_path: &str, result: &Value, include_markup: bool) -> 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);
    let (code_entities, markup_groups, markup_total) =
        crate::cli_tools::explore_file::split_markup(&arr);

    let display_entities = if include_markup {
        arr.iter().collect::<Vec<_>>()
    } else {
        code_entities
    };

    for entity in display_entities {
        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,
            "html_class" | "html_id" => Color::DarkGrey,
            _ => Color::White,
        };

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

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

    let mut out = format!(
        "Entities in `{}` ({} found)\n{}",
        file_path,
        arr.len(),
        table
    );
    if !include_markup && markup_total > 0 {
        out.push_str(&format!(
            "\nNOTE: {} markup references hidden ({} distinct). Use --include-markup to show them.\n",
            markup_total,
            markup_groups.len()
        ));
    }
    out
}

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

    /// Builds a callers-references payload with the four relationship buckets;
    /// in these tests only `calls` ever carries data.
    fn caller_references(calls: Value) -> Value {
        json!({
            "calls": calls,
            "extends": [],
            "implements": [],
            "references": []
        })
    }

    #[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 = caller_references(json!([]));
        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 = caller_references(json!([
            {"name": "caller1", "kind": "method", "file_path": "file1.java", "start_line": 10}
        ]));
        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_renders_dispatched_calls_with_bound_target() {
        let references = json!({
            "calls": [],
            "dispatched_calls": [
                {"name": "options", "kind": "method",
                 "file_path": "src/web/LookupController.java", "start_line": 12,
                 "target_fqn": "com.acme.DefaultLookupService.listOptions"}
            ]
        });
        let output = format_callers_table("LookupService.listOptions", &references);
        assert!(!output.contains("may be unused"), "got {output}");
        assert!(output.contains("Dispatched call"), "got {output}");
        assert!(
            output.contains("com.acme.DefaultLookupService.listOptions"),
            "got {output}"
        );
        assert!(output.contains("options"), "got {output}");
    }

    #[test]
    fn callers_table_labels_caller_repo() {
        let references = caller_references(json!([
            {
                "name": "caller1", "kind": "method",
                "file_path": "file1.java", "start_line": 10,
                "repo_name": "alpha", "target_repo_name": "alpha"
            }
        ]));
        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 = caller_references(json!([
            {
                "name": "caller1", "kind": "method",
                "file_path": "file1.java", "start_line": 10,
                "target_fqn": "beta::SharedUtil::work",
                "repo_name": "alpha", "target_repo_name": "beta"
            }
        ]));
        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 = caller_references(json!([
            {
                "name": "caller1", "kind": "method",
                "file_path": "file1.java", "start_line": 10,
                "repo_name": "alpha", "target_repo_name": "alpha"
            }
        ]));
        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 callers_table_truncated_resolution_states_shown_vs_total() {
        // The truncated header must state the true pre-truncation total, not
        // the shown count, and must carry the partial-counts caveat. The
        // v1.10.0 bug: `total_targets` was never emitted, so this shape never
        // reached the formatter in production.
        let mut references = caller_references(
            json!([{"name": "caller1", "kind": "method", "file_path": "f.rs", "start_line": 1}]),
        );
        references["resolution"] = json!({
            "query": "delete",
            "tier": "exact_name",
            "truncated": true,
            "total_targets": 112,
            "targets": [{}]
        });
        let output = format_callers_table("delete", &references);
        assert!(
            output.contains("Truncated — 112 targets matched; showing first 1 by FQN."),
            "got {output}"
        );
        assert!(
            output
                .contains("Counts below are partial — they cover only the 1 of 112 targets shown."),
            "got {output}"
        );
    }

    #[test]
    fn callers_table_complete_resolution_has_no_partial_counts_caveat() {
        let mut references = caller_references(
            json!([{"name": "caller1", "kind": "method", "file_path": "f.rs", "start_line": 1}]),
        );
        references["resolution"] = json!({
            "query": "MyEntity",
            "tier": "exact_name",
            "truncated": false,
            "total_targets": 1,
            "targets": [{}]
        });
        let output = format_callers_table("MyEntity", &references);
        assert!(!output.contains("Counts below are partial"), "got {output}");
    }

    #[test]
    fn test_format_explore_table_empty() {
        let entities = json!([]);
        let output = format_explore_table("test.java", &entities, false);
        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, false);
        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, false);
        assert!(output.contains("myMethod"));
        assert!(output.contains("This is a method"));
    }
}