codenexus 0.3.4

A queryable code knowledge graph tool built on LadybugDB and tree-sitter
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
// Copyright (c) 2026 Kirky.X. All rights reserved.
// SPDX-License-Identifier: MIT

//! #include tracking graph for C++ scope-aware call resolution.
//!
//! [`IncludesGraph`] stores the directed `#include` relationships between
//! files (File A `#include`s File B → edge A → B) and supports transitive
//! closure queries ("which files are reachable from File A via #include
//! chains?").
//!
//! # Purpose
//!
//! BUG-C4 (reverted in v0.2.2): C++ free functions had `is_exported=false`
//! because [`ProjectSymbolTable::lookup_exported`] returned ALL same-name
//! functions across the entire project, causing massive over-resolution
//! (fmt CALLS 1,852 → 5,002, +54%). The fix requires scoping cross-file
//! resolution by the `#include` graph: a function in File B is only a
//! valid resolution target for a call in File A if A `#include`s B
//! (directly or transitively).
//!
//! # Design
//!
//! - Storage: `HashMap<String, HashSet<String>>` (file → directly included files)
//! - `reachable_from(start)`: BFS transitive closure, includes `start` itself
//!   (a file is always "reachable" from itself for scope purposes)
//! - `contains(from, to)`: direct edge check (no transitive closure)
//!
//! The graph is populated during [`ResolvePhase`] (see `phases.rs`) from
//! `EdgeType::Includes` edges and passed to [`CallResolver`] for
//! `lookup_exported_in_scope` filtering.
//!
//! [`ProjectSymbolTable::lookup_exported`]: crate::resolve::symbol_table::ProjectSymbolTable::lookup_exported
//! [`ResolvePhase`]: crate::index::phases::ResolvePhase
//! [`CallResolver`]: crate::resolve::calls::CallResolver

use std::collections::{HashMap, HashSet};

/// Directed graph of `#include` relationships between files.
///
/// Stores File A → File B edges where A `#include`s B. Supports transitive
/// closure queries via [`reachable_from`](Self::reachable_from).
///
/// # Examples
///
/// ```
/// use codenexus::resolve::includes_graph::IncludesGraph;
///
/// let mut graph = IncludesGraph::new();
/// graph.add_include("main.cpp", "foo.h");
/// graph.add_include("foo.h", "bar.h");
///
/// // Transitive closure: main.cpp reaches foo.h and bar.h (and itself).
/// let reachable = graph.reachable_from("main.cpp");
/// assert!(reachable.contains("main.cpp"));
/// assert!(reachable.contains("foo.h"));
/// assert!(reachable.contains("bar.h"));
///
/// // Direct edge check.
/// assert!(graph.contains("main.cpp", "foo.h"));
/// assert!(!graph.contains("foo.h", "main.cpp")); // directed, not symmetric
/// ```
#[derive(Debug, Clone, Default)]
pub struct IncludesGraph {
    /// Adjacency list: source file → set of directly included files.
    edges: HashMap<String, HashSet<String>>,
}

impl IncludesGraph {
    /// Creates an empty `IncludesGraph`.
    #[must_use]
    pub fn new() -> Self {
        Self {
            edges: HashMap::new(),
        }
    }

    /// Adds a directed `#include` edge: `from_file` includes `to_file`.
    ///
    /// Duplicate edges are silently collapsed (idempotent — `HashSet` dedup).
    /// Self-edges (`from == to`) are ignored (a file cannot `#include` itself
    /// in valid C++; if encountered, it's a parse artifact, not a real edge).
    pub fn add_include(&mut self, from_file: &str, to_file: &str) {
        if from_file == to_file {
            return;
        }
        self.edges
            .entry(from_file.to_string())
            .or_default()
            .insert(to_file.to_string());
    }

    /// Returns all files reachable from `start` via `#include` chains
    /// (transitive closure), **including `start` itself**.
    ///
    /// A file is always considered reachable from itself for scope purposes:
    /// a function defined in the same file as the caller is always a valid
    /// resolution target, regardless of `#include` relationships.
    ///
    /// # Algorithm
    ///
    /// BFS over the adjacency list. Avoids infinite loops on cycles
    /// (e.g. `a.h ↔ b.h` mutual includes) by tracking visited nodes.
    ///
    /// # Returns
    ///
    /// `HashSet<&str>` with lifetimes tied to `&self`. Empty set if `start`
    /// has no outgoing edges AND is not a key in `edges` (still returns
    /// `{start}` because a file always reaches itself).
    ///
    /// For hot-path callers that invoke this repeatedly, prefer
    /// [`fill_reachable_from`](Self::fill_reachable_from) to reuse a buffer
    /// and avoid per-call allocation.
    pub fn reachable_from<'a>(&'a self, start: &'a str) -> HashSet<&'a str> {
        let mut out = HashSet::new();
        self.fill_reachable_from(start, &mut out);
        out
    }

    /// Fills `out` with all files reachable from `start` via `#include` chains
    /// (transitive closure), **including `start` itself**.
    ///
    /// This is the zero-allocation variant of
    /// [`reachable_from`](Self::reachable_from): it writes into a
    /// caller-provided buffer instead of allocating a new `HashSet` on each
    /// call. Callers that invoke this in a hot loop (e.g.
    /// `lookup_exported_in_scope` during call resolution) can reuse the same
    /// buffer across calls to avoid repeated allocations.
    ///
    /// # Algorithm
    ///
    /// BFS over the adjacency list, identical to `reachable_from`. Clears
    /// `out` before populating to ensure correctness across repeated calls
    /// with the same buffer.
    pub fn fill_reachable_from<'a>(&'a self, start: &'a str, out: &mut HashSet<&'a str>) {
        out.clear();
        out.insert(start);
        let mut queue: Vec<&str> = vec![start];
        while let Some(current) = queue.pop() {
            if let Some(neighbors) = self.edges.get(current) {
                for next in neighbors {
                    let next: &str = next;
                    if out.insert(next) {
                        queue.push(next);
                    }
                }
            }
        }
    }

    /// Returns `true` if `from` directly includes `to` (no transitive closure).
    ///
    /// For transitive reachability, use [`reachable_from`](Self::reachable_from).
    pub fn contains(&self, from: &str, to: &str) -> bool {
        self.edges
            .get(from)
            .is_some_and(|neighbors| neighbors.contains(to))
    }

    /// Returns `true` if `file` has any direct outgoing `#include` edges.
    ///
    /// Used by `CallResolver` to decide whether to use scope-aware lookup
    /// (`lookup_exported_in_scope`) or fall back to global exported lookup
    /// (`lookup_exported`). A file with no outgoing #include edges uses
    /// the global path to preserve backward compatibility for non-C++ files.
    #[must_use]
    pub fn has_outgoing_edges(&self, file: &str) -> bool {
        self.edges
            .get(file)
            .is_some_and(|neighbors| !neighbors.is_empty())
    }

    /// Returns the number of direct `#include` edges in the graph.
    #[must_use]
    pub fn edge_count(&self) -> usize {
        self.edges.values().map(SetCount::len).sum()
    }

    /// Returns `true` if the graph has no edges.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.edges.values().all(|s| s.is_empty())
    }
}

/// Trait alias to access `HashSet::len` without importing the type name.
/// Kept private to avoid leaking implementation detail.
trait SetCount {
    fn len(&self) -> usize;
}

impl<T, S> SetCount for HashSet<T, S> {
    fn len(&self) -> usize {
        HashSet::len(self)
    }
}

/// Resolves a C++ `#include` path to a concrete file path in the project.
///
/// Given the `#include` directive's `source_file` (e.g. `"foo.h"`,
/// `"fmt/format.h"`), the file issuing the include (`calling_file`), and the
/// list of all files in the project, returns the matched file path or `None`.
///
/// # Resolution strategy (deterministic — Rule 5)
///
/// 1. **Suffix match with boundary check**: `source_file` is matched as a
///    suffix of each file path in `all_files`, with a path boundary check
///    (so `"format.h"` matches `"include/fmt/format.h"` but not
///    `"xformat.h"`).
/// 2. **Same-directory preference**: when multiple files match, prefer the
///    one in the same directory as `calling_file` (standard C++
///    `#include "..."` behavior). Among same-directory matches, the shortest
///    path wins (most specific).
/// 3. **Shortest-path fallback**: when no same-directory match exists, the
///    shortest matching path wins (closest to project root).
/// 4. **No match → `None`**: system headers (`<iostream>`), external libs,
///    and missing files return `None`.
///
/// # Note on `ImportInfo::source_file`
///
/// The parse phase (`cpp.rs::extract_include`) already strips `<>`/`"`
/// wrappers from `#include` directives, so `source_file` is a clean path
/// like `"foo.h"` or `"fmt/format.h"`, not `"<foo.h>"` or `"\"foo.h\""`.
///
/// # Relationship to `imports.rs::resolve_include_suffix`
///
/// This function is intentionally separate from
/// `ImportResolver::resolve_include_suffix` (in `imports.rs`) despite
/// similar logic:
/// - Different input: `&[String]` (file paths) vs `HashMap<String, String>`
///   (file path → node id)
/// - Different output: file path vs node id
/// - Different concern: `IncludesGraph` construction (scope filtering) vs
///   `IMPORTS` edge construction (graph persistence)
/// - Decoupling: `IncludesGraph` should not depend on `ImportResolver`
///   internals
///
/// # Arguments
///
/// * `source_file` - The `#include` path (e.g. `"foo.h"`, `"fmt/format.h"`).
/// * `calling_file` - The file issuing the `#include` (e.g. `"src/main.cpp"`).
/// * `all_files` - All file paths in the project (e.g. from `parse.results`).
///
/// # Returns
///
/// The matched file path (owned `String`), or `None` if no match.
///
/// # Examples
///
/// ```
/// use codenexus::resolve::includes_graph::resolve_include;
///
/// // Same-directory preference: src/foo.h wins over include/foo.h.
/// let all = vec!["src/foo.h".to_string(), "include/foo.h".to_string()];
/// assert_eq!(
///     resolve_include("foo.h", "src/main.cpp", &all),
///     Some("src/foo.h".to_string())
/// );
///
/// // No same-directory match: falls back to any project file.
/// let all = vec!["include/bar.h".to_string()];
/// assert_eq!(
///     resolve_include("bar.h", "src/main.cpp", &all),
///     Some("include/bar.h".to_string())
/// );
///
/// // System header: no match in project files.
/// let all = vec!["src/main.cpp".to_string()];
/// assert_eq!(resolve_include("iostream", "src/main.cpp", &all), None);
/// ```
pub fn resolve_include(
    source_file: &str,
    calling_file: &str,
    all_files: &[String],
) -> Option<String> {
    let path_norm = source_file.replace('\\', "/");
    let calling_dir = calling_file
        .rsplit_once('/')
        .map(|(dir, _)| dir)
        .unwrap_or("");

    let mut same_dir: Option<&String> = None;
    let mut other: Option<&String> = None;

    for file in all_files {
        let file_norm = file.replace('\\', "/");
        if file_norm.ends_with(path_norm.as_str()) {
            let prefix_len = file_norm.len() - path_norm.len();
            // Boundary check: prefix must be empty or end with '/' (so
            // "format.h" matches "include/fmt/format.h" but not "xformat.h").
            if prefix_len == 0 || file_norm.as_bytes()[prefix_len - 1] == b'/' {
                let file_dir = file_norm.rsplit_once('/').map(|(dir, _)| dir).unwrap_or("");
                if file_dir == calling_dir {
                    // Same directory — pick shortest path for determinism.
                    if same_dir.as_ref().is_none_or(|s| s.len() > file.len()) {
                        same_dir = Some(file);
                    }
                } else {
                    // Other directory — pick shortest path (closest to root).
                    if other.as_ref().is_none_or(|s| s.len() > file.len()) {
                        other = Some(file);
                    }
                }
            }
        }
    }

    same_dir.or(other).cloned()
}

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

    // --- new() / empty graph ---

    #[test]
    fn new_creates_empty_graph() {
        let graph = IncludesGraph::new();
        assert!(graph.is_empty());
        assert_eq!(graph.edge_count(), 0);
    }

    #[test]
    fn default_creates_empty_graph() {
        let graph = IncludesGraph::default();
        assert!(graph.is_empty());
    }

    // --- add_include + contains (direct edges) ---

    #[test]
    fn add_include_creates_direct_edge() {
        let mut graph = IncludesGraph::new();
        graph.add_include("a.cpp", "b.h");
        assert!(graph.contains("a.cpp", "b.h"));
    }

    #[test]
    fn includes_graph_contains_direct() {
        // Spec Red test: add_include("a","b") → contains("a","b")==true
        // and contains("b","a")==false (directed, not symmetric).
        let mut graph = IncludesGraph::new();
        graph.add_include("a", "b");
        assert!(graph.contains("a", "b"));
        assert!(
            !graph.contains("b", "a"),
            "edge is directed: b→a should not exist"
        );
    }

    #[test]
    fn contains_returns_false_for_missing_from() {
        let graph = IncludesGraph::new();
        assert!(!graph.contains("nonexistent", "b.h"));
    }

    #[test]
    fn contains_returns_false_for_missing_to() {
        let mut graph = IncludesGraph::new();
        graph.add_include("a", "b");
        assert!(!graph.contains("a", "c"));
    }

    #[test]
    fn has_outgoing_edges_true_for_file_with_includes() {
        let mut graph = IncludesGraph::new();
        graph.add_include("main.cpp", "foo.h");
        assert!(graph.has_outgoing_edges("main.cpp"));
    }

    #[test]
    fn has_outgoing_edges_false_for_file_without_includes() {
        let mut graph = IncludesGraph::new();
        graph.add_include("main.cpp", "foo.h");
        // foo.h has no outgoing edges (only incoming)
        assert!(!graph.has_outgoing_edges("foo.h"));
    }

    #[test]
    fn has_outgoing_edges_false_for_unknown_file() {
        let graph = IncludesGraph::new();
        assert!(!graph.has_outgoing_edges("nonexistent.cpp"));
    }

    #[test]
    fn has_outgoing_edges_false_for_empty_graph() {
        let graph = IncludesGraph::new();
        assert!(!graph.has_outgoing_edges("any.cpp"));
    }

    #[test]
    fn add_include_is_idempotent() {
        let mut graph = IncludesGraph::new();
        graph.add_include("a", "b");
        graph.add_include("a", "b");
        assert_eq!(graph.edge_count(), 1, "duplicate edge should collapse");
    }

    #[test]
    fn add_include_ignores_self_edge() {
        let mut graph = IncludesGraph::new();
        graph.add_include("a", "a");
        assert!(!graph.contains("a", "a"), "self-edge should be ignored");
        assert!(graph.is_empty());
    }

    #[test]
    fn add_include_multiple_targets() {
        let mut graph = IncludesGraph::new();
        graph.add_include("main.cpp", "foo.h");
        graph.add_include("main.cpp", "bar.h");
        graph.add_include("main.cpp", "baz.h");
        assert_eq!(graph.edge_count(), 3);
        assert!(graph.contains("main.cpp", "foo.h"));
        assert!(graph.contains("main.cpp", "bar.h"));
        assert!(graph.contains("main.cpp", "baz.h"));
    }

    // --- reachable_from (transitive closure) ---

    #[test]
    fn includes_graph_reachable_transitive() {
        // Spec Red test: a→b, b→c → reachable_from("a") contains a/b/c.
        let mut graph = IncludesGraph::new();
        graph.add_include("a", "b");
        graph.add_include("b", "c");
        let reachable = graph.reachable_from("a");
        assert!(
            reachable.contains("a"),
            "start node should be reachable from itself"
        );
        assert!(
            reachable.contains("b"),
            "direct neighbor should be reachable"
        );
        assert!(
            reachable.contains("c"),
            "transitive neighbor should be reachable"
        );
        assert_eq!(reachable.len(), 3);
    }

    #[test]
    fn reachable_from_includes_start_itself() {
        // A file is always reachable from itself (scope includes same-file).
        let graph = IncludesGraph::new();
        let reachable = graph.reachable_from("lonely.cpp");
        assert_eq!(reachable.len(), 1);
        assert!(reachable.contains("lonely.cpp"));
    }

    #[test]
    fn reachable_from_no_outgoing_edges() {
        let mut graph = IncludesGraph::new();
        graph.add_include("a", "b");
        // "b" has no outgoing edges, but reachable_from("b") should still
        // include "b" itself.
        let reachable = graph.reachable_from("b");
        assert_eq!(reachable.len(), 1);
        assert!(reachable.contains("b"));
    }

    #[test]
    fn reachable_from_handles_cycle() {
        // Mutual includes: a↔b. BFS must terminate (visited set prevents loop).
        let mut graph = IncludesGraph::new();
        graph.add_include("a", "b");
        graph.add_include("b", "a");
        let reachable_from_a = graph.reachable_from("a");
        assert!(reachable_from_a.contains("a"));
        assert!(reachable_from_a.contains("b"));
        assert_eq!(reachable_from_a.len(), 2);

        let reachable_from_b = graph.reachable_from("b");
        assert!(reachable_from_b.contains("a"));
        assert!(reachable_from_b.contains("b"));
        assert_eq!(reachable_from_b.len(), 2);
    }

    #[test]
    fn reachable_from_diamond_shape() {
        // Diamond: a→b, a→c, b→d, c→d. d reachable from a via two paths.
        let mut graph = IncludesGraph::new();
        graph.add_include("a", "b");
        graph.add_include("a", "c");
        graph.add_include("b", "d");
        graph.add_include("c", "d");
        let reachable = graph.reachable_from("a");
        assert!(reachable.contains("a"));
        assert!(reachable.contains("b"));
        assert!(reachable.contains("c"));
        assert!(reachable.contains("d"));
        assert_eq!(reachable.len(), 4, "d should appear once despite two paths");
    }

    #[test]
    fn reachable_from_deep_chain() {
        // Deep chain: a→b→c→d→e. All reachable from a.
        let mut graph = IncludesGraph::new();
        graph.add_include("a", "b");
        graph.add_include("b", "c");
        graph.add_include("c", "d");
        graph.add_include("d", "e");
        let reachable = graph.reachable_from("a");
        assert_eq!(reachable.len(), 5);
        for file in &["a", "b", "c", "d", "e"] {
            assert!(reachable.contains(file), "{file} should be reachable");
        }
    }

    #[test]
    fn reachable_from_disconnected_components() {
        // Two disconnected subgraphs: a→b and c→d. reachable_from("a") should
        // NOT include c or d.
        let mut graph = IncludesGraph::new();
        graph.add_include("a", "b");
        graph.add_include("c", "d");
        let reachable_from_a = graph.reachable_from("a");
        assert!(reachable_from_a.contains("a"));
        assert!(reachable_from_a.contains("b"));
        assert!(
            !reachable_from_a.contains("c"),
            "disconnected node should not be reachable"
        );
        assert!(
            !reachable_from_a.contains("d"),
            "disconnected node should not be reachable"
        );
    }

    // --- fill_reachable_from (zero-allocation variant) ---

    #[test]
    fn fill_reachable_from_reuses_buffer() {
        // Graph: a→b→c. fill_reachable_from("a", &mut buf) should fill buf
        // with a/b/c. Then fill_reachable_from("b", &mut buf) should clear
        // and fill with b/c only (verifying clear works).
        let mut graph = IncludesGraph::new();
        graph.add_include("a", "b");
        graph.add_include("b", "c");

        let mut buf: HashSet<&str> = HashSet::new();

        // First call: from "a" → {a, b, c}
        graph.fill_reachable_from("a", &mut buf);
        assert!(buf.contains("a"), "start node should be in buffer");
        assert!(buf.contains("b"), "direct neighbor should be in buffer");
        assert!(buf.contains("c"), "transitive neighbor should be in buffer");
        assert_eq!(buf.len(), 3);

        // Second call: from "b" → {b, c} (a must be cleared)
        graph.fill_reachable_from("b", &mut buf);
        assert!(buf.contains("b"), "start node should be in buffer");
        assert!(buf.contains("c"), "transitive neighbor should be in buffer");
        assert!(
            !buf.contains("a"),
            "stale entry from previous call must be cleared"
        );
        assert_eq!(
            buf.len(),
            2,
            "buffer should only contain b and c after clear+fill"
        );
    }

    #[test]
    fn fill_reachable_from_matches_reachable_from() {
        // fill_reachable_from and reachable_from must produce identical results.
        let mut graph = IncludesGraph::new();
        graph.add_include("main.cpp", "a.h");
        graph.add_include("a.h", "b.h");
        graph.add_include("b.h", "c.h");
        graph.add_include("main.cpp", "c.h"); // diamond

        let expected = graph.reachable_from("main.cpp");
        let mut buf = HashSet::new();
        graph.fill_reachable_from("main.cpp", &mut buf);
        assert_eq!(
            expected, buf,
            "fill_reachable_from must match reachable_from output"
        );
    }

    // --- edge_count / is_empty ---

    #[test]
    fn edge_count_counts_all_direct_edges() {
        let mut graph = IncludesGraph::new();
        graph.add_include("a", "b");
        graph.add_include("a", "c");
        graph.add_include("b", "c");
        assert_eq!(graph.edge_count(), 3);
    }

    #[test]
    fn is_empty_true_for_new_graph() {
        let graph = IncludesGraph::new();
        assert!(graph.is_empty());
    }

    #[test]
    fn is_empty_false_after_add_edge() {
        let mut graph = IncludesGraph::new();
        graph.add_include("a", "b");
        assert!(!graph.is_empty());
    }

    #[test]
    fn is_empty_true_when_only_self_edges_attempted() {
        let mut graph = IncludesGraph::new();
        graph.add_include("a", "a"); // self-edge ignored
        assert!(graph.is_empty());
    }

    // --- resolve_include (basename matching) ---

    fn make_files(paths: &[&str]) -> Vec<String> {
        paths.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn resolve_include_quoted_prefers_same_dir() {
        // Spec Red test: resolve_include("foo.h", "src/main.cpp",
        // &["src/foo.h", "include/foo.h"]) returns "src/foo.h" (same dir).
        let all = make_files(&["src/foo.h", "include/foo.h"]);
        let result = resolve_include("foo.h", "src/main.cpp", &all);
        assert_eq!(result, Some("src/foo.h".to_string()));
    }

    #[test]
    fn resolve_include_angled_matches_anywhere() {
        // Spec Red test: resolve_include("bar.h", "src/main.cpp",
        // &["include/bar.h"]) returns "include/bar.h" (no same-dir match,
        // falls back to any project file).
        let all = make_files(&["include/bar.h"]);
        let result = resolve_include("bar.h", "src/main.cpp", &all);
        assert_eq!(result, Some("include/bar.h".to_string()));
    }

    #[test]
    fn resolve_include_no_match_returns_none() {
        // Spec Red test: <iostream> (system header) → None.
        let all = make_files(&["src/main.cpp", "src/foo.h"]);
        let result = resolve_include("iostream", "src/main.cpp", &all);
        assert_eq!(result, None);
    }

    #[test]
    fn resolve_include_partial_path_matches() {
        // C++ #include "fmt/format.h" → include/fmt/format.h
        // (partial path suffix match with boundary check).
        let all = make_files(&["src/main.cpp", "include/fmt/format.h"]);
        let result = resolve_include("fmt/format.h", "src/main.cpp", &all);
        assert_eq!(result, Some("include/fmt/format.h".to_string()));
    }

    #[test]
    fn resolve_include_boundary_check_rejects_partial_filename() {
        // "format.h" should NOT match "xformat.h" (no path boundary).
        let all = make_files(&["src/xformat.h"]);
        let result = resolve_include("format.h", "src/main.cpp", &all);
        assert_eq!(
            result, None,
            "xformat.h should not match format.h (no boundary)"
        );
    }

    #[test]
    fn resolve_include_exact_match_returns_file() {
        // source_file exactly equals a file path → match (prefix_len == 0).
        let all = make_files(&["foo.h", "src/main.cpp"]);
        let result = resolve_include("foo.h", "src/main.cpp", &all);
        assert_eq!(result, Some("foo.h".to_string()));
    }

    #[test]
    fn resolve_include_same_dir_picks_shortest_path() {
        // When multiple same-directory files match, pick the shortest
        // (most specific) for determinism.
        let all = make_files(&["src/a/b.h", "src/b.h"]);
        // Both match "b.h" and are in "src" directory relative to
        // calling_file "src/main.cpp". Wait — "src/a/b.h" is in "src/a",
        // not "src". Let me fix the test.
        // Actually: calling_dir = "src", "src/a/b.h" dir = "src/a",
        // "src/b.h" dir = "src". So only "src/b.h" is same-dir.
        let result = resolve_include("b.h", "src/main.cpp", &all);
        assert_eq!(result, Some("src/b.h".to_string()));
    }

    #[test]
    fn resolve_include_other_dir_picks_shortest_path() {
        // When no same-directory match, pick the shortest matching path
        // (closest to project root) for determinism.
        let all = make_files(&["include/fmt/format.h", "vendor/deep/fmt/format.h"]);
        let result = resolve_include("fmt/format.h", "src/main.cpp", &all);
        assert_eq!(
            result,
            Some("include/fmt/format.h".to_string()),
            "shorter path should win when no same-dir match"
        );
    }

    #[test]
    fn resolve_include_empty_source_returns_none() {
        let all = make_files(&["src/main.cpp"]);
        let result = resolve_include("", "src/main.cpp", &all);
        // Empty source_file would match every file (all end with ""), but
        // boundary check requires prefix_len == 0 or boundary '/'. For
        // "src/main.cpp" with empty path_norm, prefix_len = 13, and byte
        // at [12] is 'c' (not '/'), so no match. Returns None.
        // Actually: "" ends_with "" is true for all strings. prefix_len =
        // file.len(). boundary check: file.as_bytes()[file.len()-1] is
        // 'p' (not '/'), so rejected. All files rejected → None.
        assert_eq!(result, None, "empty source_file should not match anything");
    }

    #[test]
    fn resolve_include_empty_all_files_returns_none() {
        let all: Vec<String> = vec![];
        let result = resolve_include("foo.h", "src/main.cpp", &all);
        assert_eq!(result, None);
    }

    #[test]
    fn resolve_include_handles_backslash_paths() {
        // Windows-style paths: backslashes converted to forward slashes.
        let all = make_files(&["src\\foo.h"]);
        let result = resolve_include("foo.h", "src\\main.cpp", &all);
        assert_eq!(result, Some("src\\foo.h".to_string()));
    }

    #[test]
    fn resolve_include_calling_file_in_root_no_dir() {
        // calling_file has no '/' → calling_dir = "". Files in root
        // (no '/') have file_dir = "" → match as same_dir.
        let all = make_files(&["foo.h", "src/foo.h"]);
        let result = resolve_include("foo.h", "main.cpp", &all);
        assert_eq!(
            result,
            Some("foo.h".to_string()),
            "root-level file preferred when caller is in root"
        );
    }
}