leankg 0.19.1

Lightweight Knowledge Graph for AI-Assisted Development
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
use crate::db::models::CodeElement;
use crate::graph::GraphEngine;
use std::collections::{HashSet, VecDeque};

pub struct ImpactAnalyzer<'a> {
    graph: &'a GraphEngine,
}

impl<'a> ImpactAnalyzer<'a> {
    pub fn new(graph: &'a GraphEngine) -> Self {
        Self { graph }
    }

    pub fn calculate_impact_radius(
        &self,
        start_file: &str,
        depth: u32,
    ) -> Result<ImpactResult, Box<dyn std::error::Error>> {
        self.calculate_impact_radius_with_confidence(start_file, depth, 0.0)
    }

    pub fn calculate_impact_radius_with_confidence(
        &self,
        start_file: &str,
        depth: u32,
        min_confidence: f64,
    ) -> Result<ImpactResult, Box<dyn std::error::Error>> {
        self.calculate_impact_radius_with_options(
            start_file,
            depth,
            min_confidence,
            &ImpactScanOptions::default(),
        )
    }

    /// Like [`Self::calculate_impact_radius_with_confidence`] but with
    /// explicit scan options. See [`ImpactScanOptions`] for the knobs.
    pub fn calculate_impact_radius_with_options(
        &self,
        start_file: &str,
        depth: u32,
        min_confidence: f64,
        opts: &ImpactScanOptions,
    ) -> Result<ImpactResult, Box<dyn std::error::Error>> {
        let mut visited = HashSet::new();
        let mut queue = VecDeque::new();
        let mut affected_with_confidence: Vec<AffectedElementWithConfidence> = Vec::new();
        let mut seen_qualified: HashSet<String> = HashSet::new();
        let mut guard = crate::budget::BudgetGuard::for_tool("calculate_impact_radius");

        queue.push_back((start_file.to_string(), 0));
        visited.insert(start_file.to_string());

        let mut truncated = false;
        while let Some((current, current_depth)) = queue.pop_front() {
            if current_depth >= depth {
                continue;
            }
            if affected_with_confidence.len() >= opts.max_affected {
                truncated = true;
                break;
            }

            let relationships = self.graph.get_relationships(&current)?;

            for rel in relationships {
                if rel.confidence < min_confidence {
                    continue;
                }
                let target = &rel.target_qualified;
                if !visited.contains(target) {
                    visited.insert(target.clone());
                    queue.push_back((target.clone(), current_depth + 1));
                }
                if seen_qualified.insert(target.clone()) {
                    if let Ok(Some(element)) = self.graph.find_element(target) {
                        let severity = rel.severity(current_depth + 1).to_string();
                        affected_with_confidence.push(AffectedElementWithConfidence {
                            element,
                            confidence: rel.confidence,
                            severity,
                            depth: current_depth + 1,
                        });
                    }
                }
                guard.tick();
                if guard.check().is_err() {
                    truncated = true;
                    break;
                }
                if affected_with_confidence.len() >= opts.max_affected {
                    truncated = true;
                    break;
                }
            }
            if truncated {
                break;
            }

            let dependents = self.graph.get_dependents(&current)?;
            for rel in dependents {
                if rel.confidence < min_confidence {
                    continue;
                }
                let source = &rel.source_qualified;
                if !visited.contains(source) {
                    visited.insert(source.clone());
                    queue.push_back((source.clone(), current_depth + 1));
                }
                if seen_qualified.insert(source.clone()) {
                    if let Ok(Some(element)) = self.graph.find_element(source) {
                        let severity = rel.severity(current_depth + 1).to_string();
                        affected_with_confidence.push(AffectedElementWithConfidence {
                            element,
                            confidence: rel.confidence,
                            severity,
                            depth: current_depth + 1,
                        });
                    }
                }
                guard.tick();
                if guard.check().is_err() {
                    truncated = true;
                    break;
                }
                if affected_with_confidence.len() >= opts.max_affected {
                    truncated = true;
                    break;
                }
            }
            if truncated {
                break;
            }
        }

        let affected_elements: Vec<CodeElement> = affected_with_confidence
            .iter()
            .map(|a| a.element.clone())
            .collect();

        Ok(ImpactResult {
            start_file: start_file.to_string(),
            max_depth: depth,
            affected_elements,
            affected_with_confidence,
            truncated,
        })
    }
}

/// Tunable knobs for [`ImpactAnalyzer::calculate_impact_radius_with_options`].
#[derive(Debug, Clone)]
pub struct ImpactScanOptions {
    /// Hard cap on the number of affected elements returned. Defaults to
    /// 10_000 to keep memory bounded on big monorepos.
    pub max_affected: usize,
}

impl Default for ImpactScanOptions {
    fn default() -> Self {
        let max_affected = std::env::var("LEANKG_IMPACT_MAX_AFFECTED")
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(10_000);
        Self { max_affected }
    }
}

#[derive(Debug, Clone)]
pub struct AffectedElementWithConfidence {
    pub element: CodeElement,
    pub confidence: f64,
    pub severity: String,
    pub depth: u32,
}

#[derive(Debug)]
pub struct ImpactResult {
    pub start_file: String,
    pub max_depth: u32,
    pub affected_elements: Vec<CodeElement>,
    pub affected_with_confidence: Vec<AffectedElementWithConfidence>,
    /// True when the scan was aborted early because the budget /
    /// max-affected cap was reached. Callers should re-scope (smaller
    /// depth, fewer seeds, larger max_affected) and re-run.
    pub truncated: bool,
}

// ===========================================================================
// Semantic-retrieval traversal (Stage 4)
//
// Adaptive N-hop BFS from each seed node. Hops + allowed edge types + fanout
// cap depend on the seed's element_type — see `traverse_rule_for`. The
// function is feature-independent: callers pass plain `(qualified_name,
// element_type)` tuples so this module doesn't depend on the gated retrieval
// types. The retrieval pipeline + MCP handler adapt their seed list to this
// shape.
//
// See docs/plans/2026-06-30-embedding-retrieve-rerank-traverse.md §"Adaptive
// Traversal Rules".
// ====================================================================================

/// Hard ceiling on total traversed neighbors across all seeds, regardless of
/// per-seed fanout. Keeps MCP response size bounded for agents.
const GLOBAL_NEIGHBOR_CAP: usize = 60;

pub struct TraverseRule {
    pub hops: u32,
    pub edge_types: &'static [&'static str],
    pub fanout_cap: usize,
}

const WORKFLOW_EDGES: &[&str] = &[
    "has_step",
    "next_step",
    "branches_to",
    "implemented_by",
    "entry_point_of",
    "step_in_process",
    "has_failure_mode",
];

const STEP_EDGES: &[&str] = &[
    "next_step",
    "branches_to",
    "implemented_by",
    "handled_by_playbook",
    "has_failure_mode",
    "resolved_by_playbook",
];

const CONCEPT_EDGES: &[&str] = &[
    "owns_concept",
    "implements_concept",
    "exposes_endpoint",
    "reads_from",
    "writes_to",
    "documents_concept",
    "has_known_issue",
];

const ISSUE_EDGES: &[&str] = &[
    "has_known_issue",
    "resolved_by_playbook",
    "documents_concept",
];

const CODE_EDGES: &[&str] = &[
    "calls",
    "imports",
    "references",
    "tested_by",
    "documented_by",
    "implements_concept",
];

const FILE_EDGES: &[&str] = &[
    "imports",
    "references",
    "tested_by",
    "documented_by",
    "contains",
    "defines",
];

const DOC_EDGES: &[&str] = &["documented_by", "documents_concept"];

/// Element types that should never appear as traversal neighbors.
/// `unknown` is indexer noise — chain-call artifacts (iter, Ok,
/// unwrap_or, etc.) that tree-sitter extraction wrongly promotes to
/// first-class elements. `environment` is pure metadata. Both crowd
/// out real signal in `traverse_seeds` output.
const INDEXER_NOISE_TYPES: &[&str] = &["unknown", "environment"];

pub fn is_indexer_noise(element_type: &str) -> bool {
    INDEXER_NOISE_TYPES.contains(&element_type)
}

pub fn traverse_rule_for(element_type: &str) -> TraverseRule {
    match element_type {
        "workflow" => TraverseRule {
            hops: 2,
            edge_types: WORKFLOW_EDGES,
            fanout_cap: 20,
        },
        "workflow_step" | "decision_point" | "failure_mode" => TraverseRule {
            hops: 2,
            edge_types: STEP_EDGES,
            fanout_cap: 15,
        },
        "domain_entity" | "service" | "api_endpoint" | "data_store" => TraverseRule {
            hops: 1,
            edge_types: CONCEPT_EDGES,
            fanout_cap: 15,
        },
        "known_issue" | "playbook" | "team_knowledge" => TraverseRule {
            hops: 1,
            edge_types: ISSUE_EDGES,
            fanout_cap: 10,
        },
        "function" | "class" => TraverseRule {
            hops: 1,
            edge_types: CODE_EDGES,
            fanout_cap: 10,
        },
        "file" | "module" => TraverseRule {
            hops: 1,
            edge_types: FILE_EDGES,
            fanout_cap: 10,
        },
        _ => TraverseRule {
            hops: 1,
            edge_types: DOC_EDGES,
            fanout_cap: 5,
        },
    }
}

#[derive(Debug, Clone)]
pub struct TraversedNode {
    pub qualified_name: String,
    pub element_type: String,
    pub from_seed: String,
    pub via_edge: String,
    pub hop: u32,
}

#[derive(Debug, Clone)]
pub struct TraverseResult {
    pub nodes: Vec<TraversedNode>,
    pub edges: Vec<TraversedEdge>,
    pub total_neighbors: usize,
    pub capped: bool,
}

#[derive(Debug, Clone)]
pub struct TraversedEdge {
    pub source: String,
    pub target: String,
    pub rel_type: String,
}

/// Adaptive multi-hop BFS from a set of seed nodes. Returns traversed
/// neighbors (excluding the seeds themselves) plus the edges that connect
/// them. Honors per-seed-type fanout caps and the global
/// `GLOBAL_NEIGHBOR_CAP`.
pub fn traverse_seeds<I>(
    graph: &GraphEngine,
    seeds: I,
    env: Option<&str>,
) -> Result<TraverseResult, Box<dyn std::error::Error>>
where
    I: IntoIterator<Item = (String, String)>,
{
    use std::collections::{HashSet, VecDeque};

    let mut visited: HashSet<String> = HashSet::new();
    let mut nodes: Vec<TraversedNode> = Vec::new();
    let mut edges: Vec<TraversedEdge> = Vec::new();
    let mut total = 0usize;

    for (seed_qn, seed_type) in seeds {
        // Seed itself is always "visited" — we don't return it in the
        // traversed set even if a cycle would bring us back to it.
        visited.insert(seed_qn.clone());

        let rule = traverse_rule_for(&seed_type);
        let mut frontier: VecDeque<(String, u32, String, String)> = VecDeque::new();
        // (current_qn, current_hop, from_seed_qn, via_edge_into_current)
        frontier.push_back((seed_qn.clone(), 0, seed_qn.clone(), "seed".to_string()));

        let mut seed_count = 0usize;
        while let Some((current, hop, from, _via)) = frontier.pop_front() {
            if hop >= rule.hops {
                continue;
            }
            if seed_count >= rule.fanout_cap || total >= GLOBAL_NEIGHBOR_CAP {
                break;
            }

            let outgoing = graph.get_relationships(&current).unwrap_or_default();
            let incoming = graph
                .get_relationships_for_target(&current)
                .unwrap_or_default();

            for rel in outgoing.iter().chain(incoming.iter()) {
                if !rule.edge_types.contains(&rel.rel_type.as_str()) {
                    continue;
                }
                if let Some(wanted) = env {
                    if rel.env != wanted {
                        continue;
                    }
                }

                let neighbor = if rel.source_qualified == current {
                    rel.target_qualified.clone()
                } else {
                    rel.source_qualified.clone()
                };

                if visited.contains(&neighbor) {
                    continue;
                }

                let element_type = graph
                    .find_element(&neighbor)
                    .ok()
                    .flatten()
                    .map(|e| e.element_type)
                    .unwrap_or_else(|| "unknown".to_string());

                // Skip indexer noise: chain-call artifacts (iter, Ok,
                // unwrap_or, etc.) that tree-sitter extraction wrongly
                // promotes to first-class elements, plus pure-metadata
                // environment nodes. These crowd out real neighbors in
                // traversal output. Mark visited so we don't re-check.
                if is_indexer_noise(&element_type) {
                    visited.insert(neighbor);
                    continue;
                }

                visited.insert(neighbor.clone());

                edges.push(TraversedEdge {
                    source: rel.source_qualified.clone(),
                    target: rel.target_qualified.clone(),
                    rel_type: rel.rel_type.clone(),
                });

                nodes.push(TraversedNode {
                    qualified_name: neighbor.clone(),
                    element_type: element_type.clone(),
                    from_seed: from.clone(),
                    via_edge: rel.rel_type.clone(),
                    hop: hop + 1,
                });

                frontier.push_back((neighbor, hop + 1, from.clone(), rel.rel_type.clone()));

                seed_count += 1;
                total += 1;
                if total >= GLOBAL_NEIGHBOR_CAP || seed_count >= rule.fanout_cap {
                    break;
                }
            }
        }
    }

    Ok(TraverseResult {
        nodes,
        edges,
        total_neighbors: total,
        capped: total >= GLOBAL_NEIGHBOR_CAP,
    })
}

#[cfg(test)]
mod traverse_tests {
    use super::*;

    #[test]
    fn impact_scan_options_default_caps_at_10k() {
        let opts = ImpactScanOptions::default();
        assert_eq!(opts.max_affected, 10_000);
    }

    #[test]
    fn impact_scan_options_respects_env_override() {
        std::env::set_var("LEANKG_IMPACT_MAX_AFFECTED", "5");
        let opts = ImpactScanOptions::default();
        assert_eq!(opts.max_affected, 5);
        std::env::remove_var("LEANKG_IMPACT_MAX_AFFECTED");
    }

    #[test]
    fn rule_for_workflow_is_two_hops() {
        let r = traverse_rule_for("workflow");
        assert_eq!(r.hops, 2);
        assert_eq!(r.fanout_cap, 20);
        assert!(r.edge_types.contains(&"has_step"));
    }

    #[test]
    fn rule_for_function_is_one_hop() {
        let r = traverse_rule_for("function");
        assert_eq!(r.hops, 1);
        assert_eq!(r.fanout_cap, 10);
        assert!(r.edge_types.contains(&"calls"));
    }

    #[test]
    fn rule_for_unknown_type_falls_back_to_docs() {
        let r = traverse_rule_for("some-random-type");
        assert_eq!(r.hops, 1);
        assert_eq!(r.fanout_cap, 5);
        assert!(r.edge_types.contains(&"documented_by"));
    }

    // =========================================================================
    // Indexer-noise filtering tests
    //
    // `is_indexer_noise` prevents chain-call artifacts (iter, Ok, unwrap_or,
    // etc. — promoted to `unknown` element type by tree-sitter extraction)
    // and pure-metadata `environment` nodes from crowding out real signal
    // in `traverse_seeds` output.
    // =========================================================================

    #[test]
    fn is_indexer_noise_filters_unknown_type() {
        assert!(is_indexer_noise("unknown"));
    }

    #[test]
    fn is_indexer_noise_filters_environment_type() {
        assert!(is_indexer_noise("environment"));
    }

    #[test]
    fn is_indexer_noise_passes_real_code_types() {
        assert!(!is_indexer_noise("function"));
        assert!(!is_indexer_noise("class"));
        assert!(!is_indexer_noise("file"));
        assert!(!is_indexer_noise("module"));
        assert!(!is_indexer_noise("method"));
    }

    #[test]
    fn is_indexer_noise_passes_ontology_types() {
        assert!(!is_indexer_noise("workflow"));
        assert!(!is_indexer_noise("playbook"));
        assert!(!is_indexer_noise("domain_entity"));
        assert!(!is_indexer_noise("service"));
        assert!(!is_indexer_noise("known_issue"));
    }

    #[test]
    fn is_indexer_noise_passes_empty_and_arbitrary_strings() {
        // Non-noise strings (including empty) are not in the noise set.
        assert!(!is_indexer_noise(""));
        assert!(!is_indexer_noise("random_type"));
        assert!(!is_indexer_noise("cluster"));
    }

    #[test]
    fn indexer_noise_types_has_exactly_two_entries() {
        assert_eq!(INDEXER_NOISE_TYPES.len(), 2);
        assert!(INDEXER_NOISE_TYPES.contains(&"unknown"));
        assert!(INDEXER_NOISE_TYPES.contains(&"environment"));
    }

    #[test]
    fn global_neighbor_cap_is_60() {
        // Bounded MCP response size — documented contract.
        assert_eq!(GLOBAL_NEIGHBOR_CAP, 60);
    }

    // =========================================================================
    // Traverse rule edge-type coverage tests
    // =========================================================================

    #[test]
    fn rule_for_workflow_step_is_two_hops() {
        let r = traverse_rule_for("workflow_step");
        assert_eq!(r.hops, 2);
        assert!(r.fanout_cap > 0);
        assert!(r.edge_types.contains(&"next_step"));
        assert!(r.edge_types.contains(&"branches_to"));
    }

    #[test]
    fn rule_for_class_is_one_hop() {
        let r = traverse_rule_for("class");
        assert_eq!(r.hops, 1);
        assert!(r.edge_types.contains(&"calls") || r.edge_types.contains(&"imports"));
    }

    #[test]
    fn rule_for_file_is_one_hop() {
        let r = traverse_rule_for("file");
        assert_eq!(r.hops, 1);
        assert!(r.edge_types.contains(&"imports"));
        assert!(r.edge_types.contains(&"contains"));
    }

    #[test]
    fn rule_for_domain_entity_uses_concept_edges() {
        let r = traverse_rule_for("domain_entity");
        assert!(r.hops >= 1);
        assert!(
            r.edge_types.contains(&"owns_concept") || r.edge_types.contains(&"implements_concept")
        );
    }

    #[test]
    fn rule_for_known_issue_uses_issue_edges() {
        let r = traverse_rule_for("known_issue");
        assert!(r.hops >= 1);
        assert!(
            r.edge_types.contains(&"has_known_issue")
                || r.edge_types.contains(&"resolved_by_playbook")
        );
    }

    #[test]
    fn all_traverse_rules_have_positive_fanout_cap() {
        for et in &[
            "workflow",
            "workflow_step",
            "playbook",
            "playbook_step",
            "domain_entity",
            "service",
            "api_endpoint",
            "data_store",
            "known_issue",
            "function",
            "class",
            "file",
            "module",
            "method",
            "trait",
            "interface",
            "team_knowledge",
        ] {
            let r = traverse_rule_for(et);
            assert!(
                r.fanout_cap > 0,
                "fanout_cap for '{et}' should be positive, got {}",
                r.fanout_cap
            );
            assert!(
                !r.edge_types.is_empty(),
                "edge_types for '{et}' should not be empty"
            );
        }
    }
}