knot 1.16.2

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
use std::collections::{HashMap, HashSet};
use tracing::warn;
use uuid::Uuid;

use crate::models::ResolutionEntity;

fn index_file_entities(entities: &[ResolutionEntity]) -> HashMap<&str, Vec<&ResolutionEntity>> {
    let mut file_entities: HashMap<&str, Vec<&ResolutionEntity>> = HashMap::new();
    for e in entities {
        file_entities
            .entry(e.file_path.as_str())
            .or_default()
            .push(e);
    }
    file_entities
}

fn build_file_defaults<'a>(
    entities: &'a [ResolutionEntity],
    file_entities: &HashMap<&'a str, Vec<&'a ResolutionEntity>>,
) -> HashMap<&'a str, Uuid> {
    let mut file_defaults: HashMap<&'a str, Uuid> = HashMap::new();
    for e in entities {
        if let Some(ref default_name) = e.default_export
            && let Some(ents) = file_entities.get(e.file_path.as_str())
            && let Some(target) = ents.iter().find(|en| en.name == *default_name)
        {
            file_defaults.insert(e.file_path.as_str(), target.uuid);
        }
    }
    file_defaults
}

fn resolve_entity_aliases<'a>(
    entities: &'a [ResolutionEntity],
    uuid_to_file: &HashMap<Uuid, String>,
    file_entities: &HashMap<&'a str, Vec<&'a ResolutionEntity>>,
    file_defaults: &HashMap<&'a str, Uuid>,
) -> HashMap<Uuid, Uuid> {
    let mut alias_map: HashMap<Uuid, Uuid> = HashMap::new();
    for entity in entities {
        if let Some(ref module_path) = entity.alias_module_path
            && !module_path.is_empty()
            && let Some(source_file) = uuid_to_file.get(&entity.uuid)
            && let Some(target_file) = resolve_module_path(source_file, module_path, file_entities)
            && let Some(target_entities) = file_entities.get(target_file.as_str())
        {
            let target = target_entities
                .iter()
                .find(|e| e.name == entity.name)
                .or_else(|| {
                    entity
                        .original_export_name
                        .as_ref()
                        .and_then(|original| target_entities.iter().find(|e| e.name == *original))
                })
                .or_else(|| {
                    file_defaults
                        .get(target_file.as_str())
                        .and_then(|&default_uuid| {
                            target_entities.iter().find(|e| e.uuid == default_uuid)
                        })
                });
            if let Some(t) = target {
                if entity.uuid == t.uuid {
                    warn!(
                        "Skipping self-referential alias for entity {} in {}",
                        entity.name, entity.file_path
                    );
                } else {
                    alias_map.insert(entity.uuid, t.uuid);
                }
            }
        }
    }
    alias_map
}

fn chain_terminal(
    alias_map: &mut HashMap<Uuid, Uuid>,
    current: Uuid,
    visited_order: &[Uuid],
    cycle_detected: bool,
) {
    let terminal = if cycle_detected {
        let back_edge_target = alias_map.get(&current).copied().unwrap_or(current);
        let cycle_start_idx = visited_order
            .iter()
            .position(|u| *u == back_edge_target)
            .unwrap_or(0);
        let representative = visited_order[cycle_start_idx..]
            .iter()
            .min()
            .copied()
            .unwrap_or(current);
        warn!(
            "Alias cycle detected involving {} entities; collapsing to representative {}",
            visited_order.len() - cycle_start_idx,
            representative
        );
        representative
    } else {
        current
    };
    // Path-compress the whole walk — the tail that leads into a collapsed
    // cycle included — so every node points straight at its component's
    // canonical target. Rewriting only the cycle (as this used to do) left
    // tail nodes on their original edge, so the collapsed map ended up in a
    // different shape depending on which key `collapse_alias_cycles` happened
    // to visit first (`HashMap` iteration order is randomized per process).
    //
    // The terminal keeps no entry of its own: a chain end already has none,
    // and a cycle representative is removed below because it *is* the target.
    for &member in visited_order {
        if member != terminal {
            alias_map.insert(member, terminal);
        }
    }
    alias_map.remove(&terminal);
}

fn collapse_alias_cycles(alias_map: &mut HashMap<Uuid, Uuid>) {
    // Keys are deliberately iterated in `HashMap` order rather than sorted:
    // the collapsed map must be independent of iteration order, and
    // `test_alias_map_tail_into_cycle_is_order_independent` relies on
    // `RandomState` reshuffling that order to prove it.
    let keys: Vec<Uuid> = alias_map.keys().copied().collect();
    for key in keys {
        if !alias_map.contains_key(&key) {
            continue;
        }
        let mut current = key;
        let mut visited_order: Vec<Uuid> = vec![current];
        let mut visited_set: HashSet<Uuid> = HashSet::from([current]);
        let mut cycle_detected = false;
        while let Some(&next) = alias_map.get(&current) {
            if visited_set.contains(&next) {
                cycle_detected = true;
                break;
            }
            visited_set.insert(next);
            visited_order.push(next);
            current = next;
        }
        chain_terminal(alias_map, current, &visited_order, cycle_detected);
    }
}

pub fn build_alias_map(
    entities: &[ResolutionEntity],
    uuid_to_file: &HashMap<Uuid, String>,
) -> HashMap<Uuid, Uuid> {
    let file_entities = index_file_entities(entities);
    let file_defaults = build_file_defaults(entities, &file_entities);
    let mut alias_map =
        resolve_entity_aliases(entities, uuid_to_file, &file_entities, &file_defaults);
    collapse_alias_cycles(&mut alias_map);
    alias_map
}

fn resolve_module_path(
    from_file: &str,
    module_spec: &str,
    file_entities: &HashMap<&str, Vec<&ResolutionEntity>>,
) -> Option<String> {
    use std::path::{Component, Path, PathBuf};

    let from = Path::new(from_file);
    let parent = from.parent()?;

    let mut resolved = PathBuf::new();
    for component in parent.join(module_spec).components() {
        match component {
            Component::ParentDir => {
                resolved.pop();
            }
            Component::Normal(c) => {
                resolved.push(c);
            }
            Component::CurDir => {}
            _ => {
                resolved.push(component);
            }
        }
    }

    let extensions = ["js", "ts", "tsx", "jsx"];
    let index_extensions = ["js", "ts"];

    let exact = resolved.to_string_lossy().to_string();
    if file_entities.contains_key(exact.as_str()) {
        return Some(exact);
    }
    for ext in &extensions {
        let with_ext = resolved.with_extension(ext).to_string_lossy().to_string();
        if file_entities.contains_key(with_ext.as_str()) {
            return Some(with_ext);
        }
    }
    for ext in &index_extensions {
        let index_file = resolved
            .join(format!("index.{ext}"))
            .to_string_lossy()
            .to_string();
        if file_entities.contains_key(index_file.as_str()) {
            return Some(index_file);
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::{EntityKind, ReferenceIntent, ResolutionEntity};
    use crate::pipeline::ingest::resolve::resolve_reference_intents_with_context;

    fn mock_entity_with_alias(
        name: &str,
        file: &str,
        alias_module_path: Option<&str>,
        default_export: Option<&str>,
    ) -> ResolutionEntity {
        ResolutionEntity {
            uuid: Uuid::new_v4(),
            name: name.to_string(),
            fqn: name.to_string(),
            file_path: file.to_string(),
            kind: EntityKind::Constant,
            enclosing_class: None,
            enclosing_class_fqn: None,
            signature: None,
            reference_intents: Vec::new(),
            relationships: Vec::new(),
            alias_module_path: alias_module_path.map(|s| s.to_string()),
            original_export_name: None,
            default_export: default_export.map(|s| s.to_string()),
            is_test_context: false,
            import_scope: None,
        }
    }

    fn mock_entity_with_alias_and_uuid(
        name: &str,
        file: &str,
        alias_module_path: &str,
        uuid: Uuid,
    ) -> ResolutionEntity {
        ResolutionEntity {
            uuid,
            ..mock_entity_with_alias(name, file, Some(alias_module_path), None)
        }
    }

    fn build_alias_map_for_test(entities: &[ResolutionEntity]) -> HashMap<Uuid, Uuid> {
        let uuid_to_file: HashMap<Uuid, String> = entities
            .iter()
            .map(|e| (e.uuid, e.file_path.clone()))
            .collect();
        build_alias_map(entities, &uuid_to_file)
    }

    #[test]
    fn test_alias_map_skips_self_loop() {
        let a = mock_entity_with_alias("A", "file_a.js", Some("./file_a"), None);
        let entities = vec![a];
        let map = build_alias_map_for_test(&entities);
        assert!(map.is_empty(), "Self-loop should be skipped; got {:?}", map);
    }

    #[test]
    fn test_alias_map_two_node_cycle_picks_min_uuid() {
        let a = {
            let e = mock_entity_with_alias("CycleX", "file_a.js", Some("./file_b"), None);
            ResolutionEntity {
                uuid: Uuid::parse_str("00000000-0000-0000-0000-000000000002").unwrap(),
                ..e
            }
        };
        let b = {
            let e = mock_entity_with_alias("CycleX", "file_b.js", Some("./file_a"), None);
            ResolutionEntity {
                uuid: Uuid::parse_str("00000000-0000-0000-0000-000000000001").unwrap(),
                ..e
            }
        };
        let uuid_a = a.uuid;
        let uuid_b = b.uuid;

        let entities = vec![a, b];
        let map = build_alias_map_for_test(&entities);

        assert!(!map.contains_key(&uuid_b));
        assert_eq!(map.get(&uuid_a), Some(&uuid_b));
    }

    #[test]
    fn test_alias_map_three_node_cycle() {
        let a = {
            let e = mock_entity_with_alias("CycleX", "f_a.js", Some("./f_b"), None);
            ResolutionEntity {
                uuid: Uuid::parse_str("00000000-0000-0000-0000-000000000003").unwrap(),
                ..e
            }
        };
        let b = {
            let e = mock_entity_with_alias("CycleX", "f_b.js", Some("./f_c"), None);
            ResolutionEntity {
                uuid: Uuid::parse_str("00000000-0000-0000-0000-000000000001").unwrap(),
                ..e
            }
        };
        let c = {
            let e = mock_entity_with_alias("CycleX", "f_c.js", Some("./f_a"), None);
            ResolutionEntity {
                uuid: Uuid::parse_str("00000000-0000-0000-0000-000000000002").unwrap(),
                ..e
            }
        };
        let uuid_a = a.uuid;
        let uuid_b = b.uuid;
        let uuid_c = c.uuid;

        let entities = vec![a, b, c];
        let map = build_alias_map_for_test(&entities);

        assert!(!map.contains_key(&uuid_b));
        assert_eq!(map.get(&uuid_a), Some(&uuid_b));
        assert_eq!(map.get(&uuid_c), Some(&uuid_b));
    }

    #[test]
    fn test_alias_map_long_chain_collapses() {
        let a = {
            let e = mock_entity_with_alias("Fwd", "fa.js", Some("./fb"), None);
            ResolutionEntity {
                uuid: Uuid::new_v4(),
                ..e
            }
        };
        let b = {
            let e = mock_entity_with_alias("Fwd", "fb.js", Some("./fc"), None);
            ResolutionEntity {
                uuid: Uuid::new_v4(),
                ..e
            }
        };
        let c = {
            let e = mock_entity_with_alias("Fwd", "fc.js", Some("./fd"), None);
            ResolutionEntity {
                uuid: Uuid::new_v4(),
                ..e
            }
        };
        let d = {
            let e = mock_entity_with_alias("Fwd", "fd.js", None, None);
            ResolutionEntity {
                uuid: Uuid::new_v4(),
                ..e
            }
        };
        let uuid_a = a.uuid;
        let uuid_b = b.uuid;
        let uuid_c = c.uuid;
        let uuid_d = d.uuid;

        let entities = vec![a, b, c, d];
        let map = build_alias_map_for_test(&entities);

        assert_eq!(map.get(&uuid_a), Some(&uuid_d));
        assert_eq!(map.get(&uuid_b), Some(&uuid_d));
        assert_eq!(map.get(&uuid_c), Some(&uuid_d));
        assert!(!map.contains_key(&uuid_d));
    }

    #[test]
    fn test_resolve_reference_intents_terminates_with_cyclic_aliases() {
        let a = {
            let mut e = mock_entity_with_alias("CycleR", "file_a.js", Some("./file_b"), None);
            e.uuid = Uuid::parse_str("00000000-0000-0000-0000-00000000000a").unwrap();
            e.reference_intents = vec![ReferenceIntent::ValueReference {
                value_name: "CycleR".to_string(),
                line: 1,
            }];
            e
        };
        let b = {
            let mut e = mock_entity_with_alias("CycleR", "file_b.js", Some("./file_a"), None);
            e.uuid = Uuid::parse_str("00000000-0000-0000-0000-00000000000b").unwrap();
            e.reference_intents = vec![ReferenceIntent::ValueReference {
                value_name: "CycleR".to_string(),
                line: 1,
            }];
            e
        };
        let uuid_a = a.uuid;
        let uuid_b = b.uuid;

        let mut entities = vec![a, b];
        let fqn_map: HashMap<String, Uuid> =
            entities.iter().map(|e| (e.fqn.clone(), e.uuid)).collect();
        let name_map: HashMap<String, Vec<Uuid>> =
            HashMap::from([("CycleR".to_string(), vec![uuid_a, uuid_b])]);

        resolve_reference_intents_with_context(&mut entities, fqn_map, name_map);

        let rep = std::cmp::min(uuid_a, uuid_b);
        for e in &entities {
            for (target, _) in &e.relationships {
                assert_eq!(*target, rep);
            }
        }
    }

    /// A tail that hangs off a cycle must be rewritten to the cycle's
    /// representative along with the cycle itself, otherwise the collapsed
    /// map depends on which key `collapse_alias_cycles` happened to visit
    /// first — and `HashMap` iteration order is randomized per process.
    ///
    /// Component under test: `T -> C3 -> C1 -> C2 -> C3`, so the cycle is
    /// `{C1, C2, C3}` with representative `C1` (the smallest UUID) and `T`
    /// is the tail pointing at `C3`.
    #[test]
    fn test_alias_map_tail_into_cycle_is_order_independent() {
        let uuid_t = Uuid::parse_str("00000000-0000-0000-0000-00000000000a").unwrap();
        let uuid_c1 = Uuid::parse_str("00000000-0000-0000-0000-00000000000b").unwrap();
        let uuid_c2 = Uuid::parse_str("00000000-0000-0000-0000-00000000000c").unwrap();
        let uuid_c3 = Uuid::parse_str("00000000-0000-0000-0000-00000000000d").unwrap();

        let expected: HashMap<Uuid, Uuid> =
            HashMap::from([(uuid_t, uuid_c1), (uuid_c2, uuid_c1), (uuid_c3, uuid_c1)]);

        // Each iteration builds fresh `HashMap`s, so `RandomState` reshuffles
        // the key order that `collapse_alias_cycles` walks.
        for _ in 0..64 {
            let entities = vec![
                mock_entity_with_alias_and_uuid("X", "t.js", "./c3", uuid_t),
                mock_entity_with_alias_and_uuid("X", "c1.js", "./c2", uuid_c1),
                mock_entity_with_alias_and_uuid("X", "c2.js", "./c3", uuid_c2),
                mock_entity_with_alias_and_uuid("X", "c3.js", "./c1", uuid_c3),
            ];
            let map = build_alias_map_for_test(&entities);
            assert_eq!(
                map, expected,
                "alias collapse must not depend on HashMap iteration order"
            );
            assert!(
                map.values().all(|target| !map.contains_key(target)),
                "collapsed aliases must be fully path-compressed: {map:?}"
            );
        }
    }
}