knot 1.16.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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! Stage 1 — Input: source file discovery.
//!
//! Uses the `ignore` crate to walk a directory tree while respecting
//! `.gitignore`, `.ignore`, and other standard ignore files.

use anyhow::Result;
use ignore::WalkBuilder;
use std::path::PathBuf;
use tracing::{debug, info};

/// Source-code file extensions — always indexed.
const CORE_EXTENSIONS: &[&str] = &[
    "java", "ts", "tsx", "cts", "js", "mjs", "cjs", "jsx", "kt", "kts", "py", "pyi", "pyw", "html",
    "htm", "css", "scss", "sass", "rs", "groovy", "gradle", "c", "h", "cpp", "hpp", "cc", "cxx",
    "hh", "hxx", "cs", "md", "vcl", "vtc", "vcc", "csproj",
];

/// Configuration / Kubernetes / Helm file extensions — indexed only when
/// `--include-config-files` is set.
const CONFIG_EXTENSIONS: &[&str] = &["yml", "yaml", "json", "properties", "tpl"];

/// Union of [`CORE_EXTENSIONS`] and [`CONFIG_EXTENSIONS`] — the single source
/// of truth for all supported languages across the indexing pipeline.
pub const SUPPORTED_EXTENSIONS: &[&str] = &[
    // Core
    "java",
    "ts",
    "tsx",
    "cts",
    "js",
    "mjs",
    "cjs",
    "jsx",
    "kt",
    "kts",
    "py",
    "pyi",
    "pyw",
    "html",
    "htm",
    "css",
    "scss",
    "sass",
    "rs",
    "groovy",
    "gradle",
    "c",
    "h",
    "cpp",
    "hpp",
    "cc",
    "cxx",
    "hh",
    "hxx",
    "cs",
    "md",
    "vcl",
    "vtc",
    "vcc",
    "csproj",
    // Config
    "yml",
    "yaml",
    "json",
    "properties",
    "tpl",
];

/// Lock/config file names to exclude from indexing (prevent indexing large generated files).
const EXCLUDED_NAMES: &[&str] = &[
    "package-lock.json",
    "yarn.lock",
    "pnpm-lock.yaml",
    "Cargo.lock",
    "composer.lock",
    "Gemfile.lock",
    "poetry.lock",
    "Pipfile.lock",
];

/// Maximum file size in bytes for indexing (500 KB).
/// Files larger than this are skipped to prevent indexing data dumps or generated files.
const MAX_FILE_SIZE: u64 = 500 * 1024;

/// Filenames that are always discovered, even when config files are excluded.
/// These are build-system / project-identity files, not generic configuration.
pub(crate) const BUILD_SYSTEM_NAMES: &[&str] = &[
    "Jenkinsfile",
    "pom.xml",
    "Cargo.toml",
    "package.json",
    "tsconfig.json",
    "Directory.Packages.props",
];

/// Check whether a filename (with `.json` extension) is a build-system file
/// that should always be indexed.
pub(crate) fn is_build_system_json(filename: &str) -> bool {
    filename == "package.json" || filename == "tsconfig.json"
}

/// Check whether an extension requires `--include-config-files` to be indexed.
pub(crate) fn is_config_extension(ext: &str) -> bool {
    CONFIG_EXTENSIONS.contains(&ext)
}

/// Recursively discover all supported source files under `repo_path`.
///
/// Respects `.gitignore` and other ignore files found during traversal.
/// When `include_config_files` is `false`, configuration and K8s/Helm files
/// (`.yml`, `.yaml`, `.json`, `.properties`, `.tpl`) are excluded, except for
/// build-system files like `package.json` and `tsconfig.json`.
///
/// Returns absolute [`PathBuf`]s sorted for deterministic processing order.
pub fn discover_files(repo_path: &str, include_config_files: bool) -> Result<Vec<PathBuf>> {
    use std::collections::HashSet;

    let mut files: Vec<PathBuf> = WalkBuilder::new(repo_path)
        .hidden(false)
        .git_ignore(true)
        .git_global(true)
        .git_exclude(true)
        .build()
        .filter_map(|entry| {
            let entry = entry.ok()?;
            let path = entry.path().to_path_buf();

            if !path.is_file() {
                return None;
            }

            // Exclude lock files and generated files by name
            if let Some(name) = path.file_name().and_then(|n| n.to_str())
                && EXCLUDED_NAMES.contains(&name)
            {
                debug!("Skipping excluded file: {}", name);
                return None;
            }

            // File size check — skip files > 500KB
            if let Ok(metadata) = std::fs::metadata(&path)
                && metadata.len() > MAX_FILE_SIZE
            {
                debug!(
                    "Skipping file over size limit ({} bytes): {}",
                    metadata.len(),
                    path.display()
                );
                return None;
            }

            // Match by extension first
            if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
                if CORE_EXTENSIONS.contains(&ext) {
                    return Some(path);
                }

                if is_config_extension(ext) {
                    // .json files that are build-system files are always included
                    if ext == "json" && !include_config_files {
                        if let Some(name) = path.file_name().and_then(|n| n.to_str())
                            && is_build_system_json(name)
                        {
                            return Some(path);
                        }
                        // Skip other .json files when config is disabled
                        return None;
                    }

                    // Other config extensions: only include when flag is set
                    if include_config_files {
                        return Some(path);
                    }
                    return None;
                }
            }

            // Match by filename for extensionless or non-standard files
            if let Some(name) = path.file_name().and_then(|n| n.to_str())
                && BUILD_SYSTEM_NAMES.contains(&name)
            {
                return Some(path);
            }

            None
        })
        .collect();

    // Deduplicate (some files match both extension and filename)
    let mut seen = HashSet::new();
    files.retain(|p| seen.insert(p.clone()));

    files.sort();

    info!(
        "Discovered {} source files under '{}'",
        files.len(),
        repo_path
    );

    Ok(files)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    #[test]
    fn test_discover_files_basic() {
        let dir = tempdir().unwrap();
        let repo_path = dir.path().to_str().unwrap();

        // Create supported files
        fs::write(dir.path().join("test.java"), "public class Test {}").unwrap();
        fs::write(dir.path().join("app.ts"), "export class App {}").unwrap();
        fs::write(
            dir.path().join("component.tsx"),
            "export const Comp = () => {}",
        )
        .unwrap();
        fs::write(dir.path().join("legacy.cts"), "module.exports = {}").unwrap();
        fs::write(dir.path().join("vanilla.js"), "console.log('test')").unwrap();
        fs::write(dir.path().join("module.mjs"), "export {}").unwrap();
        fs::write(dir.path().join("service.kt"), "class Service {}").unwrap();
        fs::write(dir.path().join("main.py"), "def main(): pass").unwrap();
        fs::write(dir.path().join("stub.pyi"), "def foo() -> None: ...").unwrap();
        fs::write(dir.path().join("gui.pyw"), "import tkinter").unwrap();
        fs::write(dir.path().join("readme.md"), "# Readme").unwrap();

        // Create unsupported files
        fs::write(dir.path().join("data.xml"), "<root/>").unwrap();

        // Create nested supported file
        let src_dir = dir.path().join("src");
        fs::create_dir(&src_dir).unwrap();
        fs::write(src_dir.join("utils.ts"), "export {}").unwrap();

        let files = discover_files(repo_path, true).unwrap();

        assert_eq!(files.len(), 12);

        // Verify extensions are in supported list
        for path in files {
            let ext = path.extension().unwrap().to_str().unwrap();
            assert!(SUPPORTED_EXTENSIONS.contains(&ext));
        }
    }

    #[test]
    fn test_discover_files_with_gitignore() {
        let dir = tempdir().unwrap();
        let repo_path = dir.path().to_str().unwrap();

        // Create .git directory to make WalkBuilder treat it as a repo
        fs::create_dir(dir.path().join(".git")).unwrap();

        // Create supported files
        fs::write(dir.path().join("tracked.java"), "public class Tracked {}").unwrap();
        fs::write(dir.path().join("ignored.java"), "public class Ignored {}").unwrap();

        // Create .gitignore
        fs::write(dir.path().join(".gitignore"), "ignored.java").unwrap();

        let files = discover_files(repo_path, true).unwrap();

        // Should only find tracked.java
        assert_eq!(files.len(), 1);
        assert!(files[0].to_str().unwrap().contains("tracked.java"));
    }

    #[test]
    fn test_discover_files_empty() {
        let dir = tempdir().unwrap();
        let repo_path = dir.path().to_str().unwrap();

        let files = discover_files(repo_path, true).unwrap();
        assert!(files.is_empty());
    }

    #[test]
    fn test_discover_files_config_excluded_by_default() {
        let dir = tempdir().unwrap();
        let repo_path = dir.path().to_str().unwrap();

        // Create config extension files
        fs::write(dir.path().join("config.yaml"), "key: value").unwrap();
        fs::write(dir.path().join("settings.json"), r#"{"key":"value"}"#).unwrap();
        fs::write(dir.path().join("app.properties"), "key=value").unwrap();
        fs::write(dir.path().join("template.tpl"), "{{ .Values.x }}").unwrap();

        // Create core extension file
        fs::write(dir.path().join("Main.java"), "class Main {}").unwrap();

        // With include_config_files=false, only Main.java should be found
        let files = discover_files(repo_path, false).unwrap();
        assert_eq!(files.len(), 1, "Only core files should be discovered");
        assert!(files[0].to_str().unwrap().ends_with("Main.java"));

        // With include_config_files=true, all 5 should be found
        let files = discover_files(repo_path, true).unwrap();
        assert_eq!(
            files.len(),
            5,
            "All files should be discovered when flag is on"
        );
    }

    #[test]
    fn test_discover_files_build_system_json_always_included() {
        let dir = tempdir().unwrap();
        let repo_path = dir.path().to_str().unwrap();

        // Create build-system files
        fs::write(dir.path().join("package.json"), r#"{"name":"test"}"#).unwrap();
        fs::write(dir.path().join("tsconfig.json"), "{}").unwrap();

        // Create generic JSON
        fs::write(dir.path().join("random.json"), r#"{"a":1}"#).unwrap();

        // Create core file
        fs::write(dir.path().join("Main.java"), "class Main {}").unwrap();

        // With include_config_files=false, package.json and tsconfig.json still included
        let files = discover_files(repo_path, false).unwrap();
        let filenames: Vec<&str> = files
            .iter()
            .map(|p| p.file_name().unwrap().to_str().unwrap())
            .collect();
        assert!(
            filenames.contains(&"package.json"),
            "package.json should always be included"
        );
        assert!(
            filenames.contains(&"tsconfig.json"),
            "tsconfig.json should always be included"
        );
        assert!(
            !filenames.contains(&"random.json"),
            "generic JSON should be excluded"
        );
        assert!(
            filenames.contains(&"Main.java"),
            "core file should be included"
        );

        // With include_config_files=true, all 4 should be found
        let files = discover_files(repo_path, true).unwrap();
        assert_eq!(files.len(), 4);
    }

    // ---- §11.2 / §12 B-1 discovery sync-guard tests (csproj + props) ----

    #[test]
    fn test_discover_files_csproj_always_indexed() {
        // `.csproj` is an extension entry, not a config-flag-gated one:
        // discovered even with include_config_files=false.
        let dir = tempdir().unwrap();
        let repo_path = dir.path().to_str().unwrap();

        let src = dir.path().join("src");
        fs::create_dir(&src).unwrap();
        fs::write(src.join("App.csproj"), "<Project></Project>").unwrap();
        fs::write(
            dir.path().join("Directory.Packages.props"),
            "<Project></Project>",
        )
        .unwrap();
        fs::write(src.join("Program.cs"), "class Program {}").unwrap();

        let files = discover_files(repo_path, false).unwrap();
        let filenames: Vec<&str> = files
            .iter()
            .map(|p| p.file_name().unwrap().to_str().unwrap())
            .collect();

        assert!(
            filenames.contains(&"App.csproj"),
            "App.csproj should always be discovered, got {filenames:?}"
        );
        assert!(
            filenames.contains(&"Directory.Packages.props"),
            "Directory.Packages.props should always be discovered, got {filenames:?}"
        );
        assert!(
            filenames.contains(&"Program.cs"),
            "Program.cs should be discovered, got {filenames:?}"
        );
    }

    #[test]
    fn test_discover_files_csproj_and_props_in_both_extension_and_name_paths() {
        // Sync-guard: incremental re-indexing reads `SUPPORTED_EXTENSIONS`
        // (via `is_supported_file`); fresh discovery reads `CORE_EXTENSIONS`
        // (via the extension branch). Both must admit `.csproj`, and both
        // must admit `Directory.Packages.props`. If one table is updated
        // and the other isn't, this test fails.
        assert!(CORE_EXTENSIONS.contains(&"csproj"));
        assert!(SUPPORTED_EXTENSIONS.contains(&"csproj"));
        assert!(BUILD_SYSTEM_NAMES.contains(&"Directory.Packages.props"));
    }

    #[test]
    fn test_discover_files_props_not_swept_by_extension() {
        // `Some.props` (a non-canonical filename) must NOT be discovered:
        // only the exact name `Directory.Packages.props` matches the
        // filename branch. The `props` extension is in no table.
        let dir = tempdir().unwrap();
        let repo_path = dir.path().to_str().unwrap();

        fs::write(dir.path().join("Some.props"), "<Project></Project>").unwrap();
        fs::write(
            dir.path().join("Directory.Packages.props"),
            "<Project></Project>",
        )
        .unwrap();
        fs::write(dir.path().join("Main.java"), "class Main {}").unwrap();

        let files = discover_files(repo_path, true).unwrap();
        let filenames: Vec<&str> = files
            .iter()
            .map(|p| p.file_name().unwrap().to_str().unwrap())
            .collect();

        assert!(
            !filenames.contains(&"Some.props"),
            "Some.props must NOT be discovered (props is not an extension, and \
             the name is not a build-system name), got {filenames:?}"
        );
        assert!(
            filenames.contains(&"Directory.Packages.props"),
            "exact filename match should win, got {filenames:?}"
        );
    }
}