harn-hostlib 0.10.132

Opt-in code-intelligence and deterministic-tool host builtins for the Harn VM
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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
//! Typed symbol graph layered on top of the flat code index.
//!
//! Nodes are typed by [`NodeKind`] (Function, Type, Field, EnumCase,
//! Module, Import, CallSite, Macro) and edges by [`EdgeKind`] (Calls,
//! Refs, Imports, Contains, Overrides). The graph is built lazily from the AST symbol
//! extractor and the existing import [`super::DepGraph`]; it does not
//! duplicate the trigram or word indexes.
//!
//! [`SymbolGraph::rebuild_file`] re-parses a single file and replaces the
//! node + edge slice belonging to that file. Both forward and reverse
//! adjacency lists are kept so the Cypher executor in [`super::cypher`]
//! can traverse `<-[:EDGE]-` patterns without rescanning.

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

use tree_sitter::{Node as TsNode, Tree};

use crate::ast::{api as ast_api, Language, Symbol, SymbolKind};
use crate::ResolvedHarnReference;

use super::file_table::FileId;

/// Typed node identifier. Stable across `rebuild_file` calls that don't
/// touch the file (id assignment is per-file deterministic — see
/// [`SymbolGraph::rebuild_file`]).
pub type NodeId = u32;

/// Coarse typed node kinds defined in issue #2434.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NodeKind {
    /// Functions, methods, free-standing closures with names.
    Function,
    /// Classes, structs, enums, interfaces, protocols, type aliases.
    Type,
    /// Struct/class/interface fields and properties.
    Field,
    /// Individual enum cases / variants.
    EnumCase,
    /// One per indexed file; acts as the container for top-level decls.
    Module,
    /// One per raw import string surfaced by the import extractor.
    Import,
    /// One per `f(...)` call expression matched in source.
    CallSite,
    /// Macro definitions (reserved for language-specific extraction).
    Macro,
}

impl NodeKind {
    /// Label-case wire form used by Cypher and the JSON projection.
    pub fn as_str(self) -> &'static str {
        match self {
            NodeKind::Function => "Function",
            NodeKind::Type => "Type",
            NodeKind::Field => "Field",
            NodeKind::EnumCase => "EnumCase",
            NodeKind::Module => "Module",
            NodeKind::Import => "Import",
            NodeKind::CallSite => "CallSite",
            NodeKind::Macro => "Macro",
        }
    }

    /// Every kind, so an exhaustiveness test can enumerate them.
    pub const ALL: [NodeKind; 8] = [
        NodeKind::Function,
        NodeKind::Type,
        NodeKind::Field,
        NodeKind::EnumCase,
        NodeKind::Module,
        NodeKind::Import,
        NodeKind::CallSite,
        NodeKind::Macro,
    ];

    /// Whether a node of this kind can be named from another file by a
    /// bare identifier, and is therefore a legitimate target for the
    /// `REFS` name heuristic.
    ///
    /// Two kinds are excluded for different reasons, and both exclusions
    /// are load-bearing:
    ///
    /// - [`NodeKind::CallSite`] is a *use*, not a declaration. Pointing a
    ///   REFS edge at one asserts that module A references a call
    ///   expression inside module B, which is not a fact anybody wants.
    ///   It is also where essentially all the edges came from: on a
    ///   7,038-file workspace, call sites absorbed 80.9M of 87.0M REFS
    ///   edges, because a name like `assert` has 32,343 call sites and
    ///   seven actual declarations.
    /// - [`NodeKind::Field`] and [`NodeKind::EnumCase`] are scoped to
    ///   their container. A module that happens to contain the word
    ///   `path` is not referencing all 469 struct fields named `path`.
    ///
    /// [`NodeKind::Import`] is excluded because its name is a raw import
    /// string, which never word-matches.
    pub fn is_name_addressable(self) -> bool {
        matches!(
            self,
            NodeKind::Function | NodeKind::Type | NodeKind::Macro | NodeKind::Module
        )
    }

    /// Parse a case-sensitive Cypher label.
    pub fn parse(label: &str) -> Option<Self> {
        match label {
            "Function" => Some(NodeKind::Function),
            "Type" => Some(NodeKind::Type),
            "Field" => Some(NodeKind::Field),
            "EnumCase" => Some(NodeKind::EnumCase),
            "Module" => Some(NodeKind::Module),
            "Import" => Some(NodeKind::Import),
            "CallSite" => Some(NodeKind::CallSite),
            "Macro" => Some(NodeKind::Macro),
            _ => None,
        }
    }
}

/// Coarse typed edge kinds defined in issue #2434.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EdgeKind {
    /// CallSite → Function. A call expression resolving to a function.
    Calls,
    /// Module → any. Name-heuristic for languages without a resolver.
    /// Harn files do not emit these; they use ModuleGraph instead.
    Refs,
    /// Module → Module (resolved) or Module → Import (unresolved).
    Imports,
    /// Container → child. Module-to-decl or Type-to-method.
    Contains,
    /// Method → method. Reserved for explicit overrides.
    Overrides,
}

impl EdgeKind {
    /// Wire form (uppercase, matches Cypher convention).
    pub fn as_str(self) -> &'static str {
        match self {
            EdgeKind::Calls => "CALLS",
            EdgeKind::Refs => "REFS",
            EdgeKind::Imports => "IMPORTS",
            EdgeKind::Contains => "CONTAINS",
            EdgeKind::Overrides => "OVERRIDES",
        }
    }

    /// Parse an edge label, accepting both forward (`CALLS`) and inverse
    /// (`CALLED_BY`) spellings. Returns `(kind, reversed)` so the executor
    /// flips direction during traversal.
    pub fn parse_with_direction(label: &str) -> Option<(Self, bool)> {
        if let Some(kind) = forward_match(label) {
            return Some((kind, false));
        }
        match label {
            "CALLED_BY" => Some((EdgeKind::Calls, true)),
            "REFERENCED_BY" => Some((EdgeKind::Refs, true)),
            "IMPORTED_BY" => Some((EdgeKind::Imports, true)),
            "CONTAINED_BY" => Some((EdgeKind::Contains, true)),
            "OVERRIDDEN_BY" => Some((EdgeKind::Overrides, true)),
            _ => None,
        }
    }
}

fn forward_match(label: &str) -> Option<EdgeKind> {
    match label {
        "CALLS" => Some(EdgeKind::Calls),
        "REFS" => Some(EdgeKind::Refs),
        "IMPORTS" => Some(EdgeKind::Imports),
        "CONTAINS" => Some(EdgeKind::Contains),
        "OVERRIDES" => Some(EdgeKind::Overrides),
        _ => None,
    }
}

/// One typed node in the symbol graph. `line` is 1-based to match the
/// rest of the host-builtin wire format; `path` is workspace-relative.
#[derive(Debug, Clone)]
pub struct Node {
    /// Stable graph-local id assigned at construction.
    pub id: NodeId,
    /// Typed kind ([`NodeKind`]).
    pub kind: NodeKind,
    /// Display name (function/type identifier, module basename, or
    /// raw import string for [`NodeKind::Import`]).
    pub name: String,
    /// Owning file id from the flat code index.
    pub file_id: FileId,
    /// Workspace-relative path of the owning file.
    pub path: String,
    /// 1-based start line within the file.
    pub line: u32,
    /// Single-line signature/preview.
    pub signature: String,
    /// Enclosing container name (class/struct/module), if any.
    pub container: Option<String>,
    /// Normalized declaration access level when known.
    pub access_level: Option<String>,
    /// Tree-sitter language name (e.g. `"rust"`, `"typescript"`).
    pub language: String,
}

/// One directed edge.
#[derive(Debug, Clone, Copy)]
pub struct Edge {
    /// Source node id.
    pub from: NodeId,
    /// Destination node id.
    pub to: NodeId,
    /// Typed edge kind ([`EdgeKind`]).
    pub kind: EdgeKind,
}

/// Result of [`SymbolGraph::rebuild_file`]. Exposes the flat symbol list
/// produced by the tree-sitter parse so callers can populate sibling
/// indexes (e.g. `IndexedFile::symbols`) without re-parsing.
#[derive(Debug, Clone, Default)]
pub struct RebuildOutcome {
    /// Number of nodes installed for this file, including the Module
    /// node. Matches the previous `usize` return value.
    pub node_count: usize,
    /// Flat symbol list extracted from the parse. Empty when the
    /// grammar didn't recognise the source.
    pub symbols: Vec<Symbol>,
}

/// Typed symbol graph for a single workspace.
#[derive(Debug, Default, Clone)]
pub struct SymbolGraph {
    nodes: HashMap<NodeId, Node>,
    by_file: HashMap<FileId, Vec<NodeId>>,
    by_name: HashMap<String, Vec<NodeId>>,
    out_edges: HashMap<NodeId, Vec<Edge>>,
    in_edges: HashMap<NodeId, Vec<Edge>>,
    next_id: NodeId,
}

impl SymbolGraph {
    /// Construct an empty graph.
    pub fn new() -> Self {
        Self {
            next_id: 1,
            ..Self::default()
        }
    }

    /// Total node count.
    pub fn node_count(&self) -> usize {
        self.nodes.len()
    }

    /// Total edge count.
    pub fn edge_count(&self) -> usize {
        self.out_edges.values().map(Vec::len).sum()
    }

    /// Borrow a node by id.
    pub fn node(&self, id: NodeId) -> Option<&Node> {
        self.nodes.get(&id)
    }

    /// Iterate every node (order is unspecified).
    pub fn iter_nodes(&self) -> impl Iterator<Item = &Node> {
        self.nodes.values()
    }

    /// All node ids of a specific kind. Used by the Cypher executor's
    /// label-driven scan.
    pub fn nodes_of_kind(&self, kind: NodeKind) -> Vec<NodeId> {
        let mut out: Vec<NodeId> = self
            .nodes
            .values()
            .filter(|n| n.kind == kind)
            .map(|n| n.id)
            .collect();
        out.sort_unstable();
        out
    }

    /// Every node id, sorted. Used as the unfiltered scan when the
    /// Cypher pattern has no label predicate.
    pub fn all_node_ids(&self) -> Vec<NodeId> {
        let mut out: Vec<NodeId> = self.nodes.keys().copied().collect();
        out.sort_unstable();
        out
    }

    /// All nodes matching `name` (case-sensitive). Empty when no match.
    pub fn nodes_named(&self, name: &str) -> &[NodeId] {
        match self.by_name.get(name) {
            Some(v) => v.as_slice(),
            None => &[],
        }
    }

    /// Outgoing edges from `id`.
    pub fn outgoing(&self, id: NodeId) -> &[Edge] {
        self.out_edges.get(&id).map(Vec::as_slice).unwrap_or(&[])
    }

    /// Incoming edges to `id`.
    pub fn incoming(&self, id: NodeId) -> &[Edge] {
        self.in_edges.get(&id).map(Vec::as_slice).unwrap_or(&[])
    }

    /// File ids that own at least one node in this graph.
    pub fn file_ids(&self) -> Vec<FileId> {
        let mut out: Vec<FileId> = self.by_file.keys().copied().collect();
        out.sort_unstable();
        out
    }

    /// Drop every node + edge owned by `file_id`.
    pub fn remove_file(&mut self, file_id: FileId) {
        let Some(node_ids) = self.by_file.remove(&file_id) else {
            return;
        };
        for id in node_ids {
            self.drop_node(id);
        }
    }

    fn drop_node(&mut self, id: NodeId) {
        let Some(node) = self.nodes.remove(&id) else {
            return;
        };
        if let Some(bucket) = self.by_name.get_mut(&node.name) {
            bucket.retain(|n| *n != id);
            if bucket.is_empty() {
                self.by_name.remove(&node.name);
            }
        }
        if let Some(outs) = self.out_edges.remove(&id) {
            for e in outs {
                if let Some(bucket) = self.in_edges.get_mut(&e.to) {
                    bucket.retain(|edge| edge.from != id);
                }
            }
        }
        if let Some(ins) = self.in_edges.remove(&id) {
            for e in ins {
                if let Some(bucket) = self.out_edges.get_mut(&e.from) {
                    bucket.retain(|edge| edge.to != id);
                }
            }
        }
    }

    /// Replace every node + edge belonging to `file_id` with the freshly
    /// parsed set derived from `source`. Returns the count of nodes
    /// installed (including the per-file Module node) along with the
    /// flat symbol list that was extracted from the parse — callers
    /// (notably [`super::IndexState`]) reuse the symbol list to populate
    /// `IndexedFile::symbols` without re-parsing.
    ///
    /// `imported_files` is this file's **resolved** import set, which
    /// scopes call resolution. The caller owns import resolution and must
    /// have run it for `file_id` already;
    /// [`super::IndexState`] does, at all three sites that reach here.
    /// Pass an empty slice to mean "this file imports nothing", which is
    /// the honest answer for a language or file with no import syntax —
    /// not "resolve against everything".
    pub fn rebuild_file(
        &mut self,
        file_id: FileId,
        path: &str,
        language: Language,
        source: &str,
        import_strings: &[String],
        imported_files: &[FileId],
    ) -> RebuildOutcome {
        self.remove_file(file_id);
        let module_id = self.add_module_for_file(file_id, path, &language);

        // Parse once and reuse the tree for both symbol extraction and
        // the call-site sweep. Falling back to empty results when the
        // grammar is unhappy keeps one bad file from poisoning the
        // wider rebuild.
        let (tree, symbols) = match ast_api::parse_with_symbols(source, language) {
            Ok((t, s)) => (Some(t), s),
            Err(err) => {
                tracing::debug!(
                    "code_index: tree-sitter parse failed for `{path}`: {err}; \
                     symbol graph slice will be Module-only"
                );
                (None, Vec::new())
            }
        };

        // Functions / Types / Modules + CONTAINS edges. Nested decls
        // point at a previously-emitted container symbol when one
        // exists, otherwise at the file's Module node.
        let mut container_ids: HashMap<String, NodeId> = HashMap::new();
        for sym in &symbols {
            let Some(kind) = map_symbol_kind(sym.kind) else {
                continue;
            };
            let id = self.add_node(Node {
                id: 0,
                kind,
                name: sym.name.clone(),
                file_id,
                path: path.to_string(),
                line: sym.start_row.saturating_add(1),
                signature: sym.signature.clone(),
                container: sym.container.clone(),
                access_level: sym.access_level.clone(),
                language: language.name().to_string(),
            });
            if matches!(kind, NodeKind::Type | NodeKind::Module) {
                container_ids.insert(sym.name.clone(), id);
            }
            let parent_id = sym
                .container
                .as_deref()
                .and_then(|c| container_ids.get(c).copied())
                .unwrap_or(module_id);
            self.add_edge(parent_id, id, EdgeKind::Contains);
        }

        // CallSite nodes + CALLS edges. Targets are resolved against
        // the global by-name index, so cross-file calls become callable
        // once every file has been ingested at least once.
        if let Some(tree) = tree.as_ref() {
            // A Swift target or Go package can put hundreds of files in
            // scope, so the membership test is a set lookup rather than
            // a scan of the import list per candidate per call site.
            let visible: HashSet<FileId> = imported_files.iter().copied().collect();
            for (callee_name, line) in extract_call_sites_from_tree(tree, source) {
                let call_id = self.add_node(Node {
                    id: 0,
                    kind: NodeKind::CallSite,
                    name: callee_name.clone(),
                    file_id,
                    path: path.to_string(),
                    line,
                    signature: format!("{callee_name}(…)"),
                    container: None,
                    access_level: None,
                    language: language.name().to_string(),
                });
                self.add_edge(module_id, call_id, EdgeKind::Contains);
                let targets = self.resolve_call_targets(&callee_name, file_id, &visible);
                for t in targets {
                    self.add_edge(call_id, t, EdgeKind::Calls);
                }
            }
        }

        // Import nodes — one per raw import string. IMPORTS edge from
        // the file's Module to the Import marker. A second resolution
        // pass in [`Self::link_imports`] adds Module→Module edges once
        // every file has been ingested.
        for raw in import_strings {
            let imp_id = self.add_node(Node {
                id: 0,
                kind: NodeKind::Import,
                name: raw.clone(),
                file_id,
                path: path.to_string(),
                line: 1,
                signature: format!("import {raw}"),
                container: None,
                access_level: None,
                language: language.name().to_string(),
            });
            self.add_edge(module_id, imp_id, EdgeKind::Imports);
        }

        // REFS: name-heuristic only for languages without a resolver.
        // Harn answers from ModuleGraph (`definition_of`); a word match
        // here would collapse a local `run` with an imported `run`.
        if language.name() != "harn" {
            for target in self.collect_cross_file_refs(source, file_id) {
                self.add_edge(module_id, target, EdgeKind::Refs);
            }
        }

        let node_count = self.by_file.get(&file_id).map(Vec::len).unwrap_or_default();
        RebuildOutcome {
            node_count,
            symbols,
        }
    }

    /// Resolve every IMPORTS edge whose target is currently an `Import`
    /// marker to the corresponding Module-to-Module edge, using the
    /// resolution table from the flat dep graph. Add-only: the marker
    /// edges remain so the Import nodes still anchor the raw strings.
    pub fn link_imports(&mut self, resolved: &HashMap<FileId, Vec<FileId>>) {
        for (src_file, targets) in resolved {
            let Some(src_module) = self.module_node_for_file(*src_file) else {
                continue;
            };
            for tgt_file in targets {
                let Some(tgt_module) = self.module_node_for_file(*tgt_file) else {
                    continue;
                };
                // Idempotent add: `link_imports` re-runs over the WHOLE
                // workspace after every per-file reindex, but `rebuild_file`
                // only clears the reindexed file's edges. Without this guard,
                // every reindex appends another copy of every still-valid
                // Module→Module edge, growing the graph without bound and
                // returning duplicate rows from IMPORTS/IMPORTED_BY traversals.
                let already_linked = self.out_edges.get(&src_module).is_some_and(|edges| {
                    edges
                        .iter()
                        .any(|e| e.to == tgt_module && e.kind == EdgeKind::Imports)
                });
                if !already_linked {
                    self.add_edge(src_module, tgt_module, EdgeKind::Imports);
                }
            }
        }
    }

    /// Replace every resolver-backed Harn `REFS` edge with `references`.
    ///
    /// The projection is path-qualified, so same-named declarations in
    /// separate modules remain distinct. Clearing first is intentional:
    /// rebuilds, editor reindexes, and branch overlays must remove stale
    /// answers rather than accumulate them.
    pub fn replace_harn_references(&mut self, references: &[ResolvedHarnReference]) {
        let harn_modules: BTreeSet<NodeId> = self
            .nodes
            .values()
            .filter(|node| node.kind == NodeKind::Module && node.language == "harn")
            .map(|node| node.id)
            .collect();
        for module in &harn_modules {
            if let Some(edges) = self.out_edges.get_mut(module) {
                let removed: Vec<Edge> = edges
                    .iter()
                    .copied()
                    .filter(|edge| edge.kind == EdgeKind::Refs)
                    .collect();
                edges.retain(|edge| edge.kind != EdgeKind::Refs);
                for edge in removed {
                    if let Some(incoming) = self.in_edges.get_mut(&edge.to) {
                        incoming.retain(|candidate| {
                            !(candidate.from == edge.from
                                && candidate.to == edge.to
                                && candidate.kind == EdgeKind::Refs)
                        });
                    }
                }
            }
        }

        for reference in references {
            let Some(from) = self
                .nodes
                .values()
                .find(|node| {
                    node.kind == NodeKind::Module
                        && node.language == "harn"
                        && node.path == reference.from_path
                })
                .map(|node| node.id)
            else {
                continue;
            };
            let targets: Vec<NodeId> = self
                .nodes
                .values()
                .filter(|node| {
                    node.path == reference.to_path
                        && node.name == reference.to_name
                        && node.kind != NodeKind::Module
                })
                .map(|node| node.id)
                .collect();
            for target in targets {
                let duplicate = self
                    .outgoing(from)
                    .iter()
                    .any(|edge| edge.kind == EdgeKind::Refs && edge.to == target);
                if !duplicate {
                    self.add_edge(from, target, EdgeKind::Refs);
                }
            }
        }
    }

    /// Find the Module node owned by `file_id`, if one exists.
    pub fn module_node_for_file(&self, file_id: FileId) -> Option<NodeId> {
        let ids = self.by_file.get(&file_id)?;
        ids.iter().copied().find(|id| {
            self.nodes
                .get(id)
                .is_some_and(|n| matches!(n.kind, NodeKind::Module))
        })
    }

    /// Walk `source` once, collecting node ids whose name appears as a
    /// word in the file *and* who live in a different file. Each target
    /// id appears at most once.
    fn collect_cross_file_refs(&self, source: &str, this_file: FileId) -> BTreeSet<NodeId> {
        let mut out: BTreeSet<NodeId> = BTreeSet::new();
        if self.by_name.is_empty() {
            return out;
        }
        let mut word = String::with_capacity(32);
        for ch in source.chars() {
            if ch.is_alphanumeric() || ch == '_' {
                word.push(ch);
            } else if !word.is_empty() {
                self.absorb_word_refs(&word, this_file, &mut out);
                word.clear();
            }
        }
        if !word.is_empty() {
            self.absorb_word_refs(&word, this_file, &mut out);
        }
        out
    }

    /// Which functions a call to `callee_name` in `file_id` can be
    /// reaching, in order of confidence.
    ///
    /// The old rule was "every function with this name, anywhere". On a
    /// 7,038-file workspace that made a call to `assert` link to all
    /// seven unrelated functions of that name, so six of every seven
    /// edges were wrong and one function node collected 32,887 callers
    /// (#8107).
    ///
    /// The replacement never guesses between candidates it cannot
    /// distinguish:
    ///
    /// 1. **Same file.** A local definition shadows anything imported,
    ///    so if the file defines the name itself, that is the call.
    /// 2. **Imported files.** Otherwise the call can only reach what
    ///    this file actually imports. All matching declarations in the
    ///    resolved import set are returned, because a genuine ambiguity
    ///    across two imports is a fact about the code, not a guess.
    /// 3. **Exactly one declaration workspace-wide.** A unique name is
    ///    unambiguous whether or not the import resolver saw the edge,
    ///    which keeps recall for implicit visibility — a sibling module
    ///    in the same crate, a global, a language with no import syntax.
    /// 4. **Otherwise, nothing.** Several candidates and no import
    ///    linking any of them is precisely the case where an edge would
    ///    be invented rather than found.
    fn resolve_call_targets(
        &self,
        callee_name: &str,
        file_id: FileId,
        visible: &HashSet<FileId>,
    ) -> Vec<NodeId> {
        let named: Vec<NodeId> = self
            .nodes_named(callee_name)
            .iter()
            .copied()
            .filter(|nid| {
                self.nodes
                    .get(nid)
                    .is_some_and(|n| n.kind == NodeKind::Function)
            })
            .collect();
        if named.is_empty() {
            return named;
        }

        let local: Vec<NodeId> = named
            .iter()
            .copied()
            .filter(|nid| self.nodes.get(nid).is_some_and(|n| n.file_id == file_id))
            .collect();
        if !local.is_empty() {
            return local;
        }

        let imported: Vec<NodeId> = named
            .iter()
            .copied()
            .filter(|nid| {
                self.nodes
                    .get(nid)
                    .is_some_and(|n| visible.contains(&n.file_id))
            })
            .collect();
        if !imported.is_empty() {
            return imported;
        }

        if named.len() == 1 {
            return named;
        }
        Vec::new()
    }

    /// Add every cross-file declaration named `word` to `bag`.
    ///
    /// `by_name` indexes every node, including call sites, because the
    /// CALLS resolver and the Cypher executor both need that. The REFS
    /// heuristic is narrower: it wants declarations a bare identifier in
    /// another file could actually be naming, so it filters to
    /// [`NodeKind::is_name_addressable`].
    fn absorb_word_refs(&self, word: &str, this_file: FileId, bag: &mut BTreeSet<NodeId>) {
        if word.len() < 3 {
            return;
        }
        let Some(ids) = self.by_name.get(word) else {
            return;
        };
        for nid in ids {
            let Some(node) = self.nodes.get(nid) else {
                continue;
            };
            if node.file_id == this_file || !node.kind.is_name_addressable() {
                continue;
            }
            bag.insert(*nid);
        }
    }

    fn add_module_for_file(&mut self, file_id: FileId, path: &str, language: &Language) -> NodeId {
        let name = module_name_from_path(path);
        self.add_node(Node {
            id: 0,
            kind: NodeKind::Module,
            name,
            file_id,
            path: path.to_string(),
            line: 1,
            signature: format!("module {path}"),
            container: None,
            access_level: None,
            language: language.name().to_string(),
        })
    }

    fn add_node(&mut self, mut node: Node) -> NodeId {
        let id = self.next_id;
        self.next_id = self.next_id.checked_add(1).expect("NodeId overflow");
        node.id = id;
        self.by_file.entry(node.file_id).or_default().push(id);
        self.by_name.entry(node.name.clone()).or_default().push(id);
        self.nodes.insert(id, node);
        id
    }

    fn add_edge(&mut self, from: NodeId, to: NodeId, kind: EdgeKind) {
        let edge = Edge { from, to, kind };
        self.out_edges.entry(from).or_default().push(edge);
        self.in_edges.entry(to).or_default().push(edge);
    }
}

/// Derive a coarse module name from a workspace-relative path (basename
/// without extension). Used to make Module-node queries human-readable.
pub fn module_name_from_path(path: &str) -> String {
    let stem = path.rsplit_once('/').map(|(_, name)| name).unwrap_or(path);
    let base = stem.rsplit_once('.').map(|(name, _)| name).unwrap_or(stem);
    base.to_string()
}

fn map_symbol_kind(kind: SymbolKind) -> Option<NodeKind> {
    match kind {
        SymbolKind::Function | SymbolKind::Method => Some(NodeKind::Function),
        SymbolKind::Field => Some(NodeKind::Field),
        SymbolKind::EnumCase => Some(NodeKind::EnumCase),
        SymbolKind::Class
        | SymbolKind::Struct
        | SymbolKind::Enum
        | SymbolKind::Interface
        | SymbolKind::Protocol
        | SymbolKind::Type => Some(NodeKind::Type),
        SymbolKind::Module => Some(NodeKind::Module),
        SymbolKind::Variable | SymbolKind::Other => None,
    }
}

/// Sweep an already-parsed tree for `call_expression`-like nodes. The
/// set of node kinds we accept covers the major tree-sitter grammars
/// wired into `harn-hostlib`. Returns `(callee_name, 1-based line)`
/// pairs.
fn extract_call_sites_from_tree(tree: &Tree, source: &str) -> Vec<(String, u32)> {
    let mut out: Vec<(String, u32)> = Vec::new();
    let mut cursor = tree.root_node().walk();
    let mut stack: Vec<TsNode<'_>> = vec![tree.root_node()];
    while let Some(node) = stack.pop() {
        if is_call_kind(node.kind()) {
            if let Some(name) = call_callee_name(node, source) {
                let line = node.start_position().row as u32 + 1;
                out.push((name, line));
            }
        }
        for child in node.children(&mut cursor) {
            stack.push(child);
        }
    }
    out
}

fn is_call_kind(kind: &str) -> bool {
    matches!(
        kind,
        "call_expression"
            | "call"
            | "function_call"
            | "method_invocation"
            | "method_call_expression"
            | "invocation_expression"
            | "function_call_expression"
            | "macro_invocation"
    )
}

fn call_callee_name(node: TsNode<'_>, source: &str) -> Option<String> {
    let callee = node
        .child_by_field_name("function")
        .or_else(|| node.child_by_field_name("name"))
        .or_else(|| node.child_by_field_name("method"))
        .or_else(|| node.child(0u32))?;
    #[expect(
        clippy::string_slice,
        reason = "tree-sitter node byte ranges lie on char boundaries of the parsed source"
    )]
    let text = &source[callee.start_byte()..callee.end_byte()];
    let last = text.rsplit_once(['.', ':', '!']);
    let raw = last.map(|(_, name)| name).unwrap_or(text);
    let trimmed = raw.trim();
    let plain: String = trimmed
        .chars()
        .take_while(|c| c.is_alphanumeric() || *c == '_')
        .collect();
    if plain.is_empty() {
        None
    } else {
        Some(plain)
    }
}

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

    #[test]
    fn add_and_remove_round_trip() {
        let mut g = SymbolGraph::new();
        let outcome = g.rebuild_file(1, "src/a.rs", Language::Rust, "fn foo() {}\n", &[], &[]);
        assert!(
            outcome.node_count >= 2,
            "module + function expected, got {}",
            outcome.node_count
        );
        assert!(
            outcome.symbols.iter().any(|s| s.name == "foo"),
            "rebuild_file should surface the parsed `foo` symbol"
        );
        assert!(!g.nodes_named("foo").is_empty());
        g.remove_file(1);
        assert_eq!(g.node_count(), 0);
        assert!(g.nodes_named("foo").is_empty());
    }

    #[test]
    fn rebuild_file_emits_function_module_and_call_nodes() {
        let mut g = SymbolGraph::new();
        let src = "fn alpha() {}\nfn beta() { alpha(); }\n";
        let outcome = g.rebuild_file(7, "src/x.rs", Language::Rust, src, &[], &[]);
        assert!(
            outcome.node_count >= 3,
            "expected module + 2 functions, got {}",
            outcome.node_count
        );
        let alpha_funcs: Vec<_> = g
            .iter_nodes()
            .filter(|n| n.kind == NodeKind::Function && n.name == "alpha")
            .collect();
        assert_eq!(alpha_funcs.len(), 1);
        let beta_funcs: Vec<_> = g
            .iter_nodes()
            .filter(|n| n.kind == NodeKind::Function && n.name == "beta")
            .collect();
        assert_eq!(beta_funcs.len(), 1);
        let beta_calls: Vec<_> = g
            .iter_nodes()
            .filter(|n| n.kind == NodeKind::CallSite && n.name == "alpha")
            .collect();
        assert!(!beta_calls.is_empty(), "expected a CallSite for alpha()");
    }

    #[test]
    fn rebuild_file_emits_fields_and_enum_cases() {
        let mut g = SymbolGraph::new();
        let src = "pub struct Greeter {\n    pub name: String,\n}\n\nenum Color {\n    Red,\n}\n";
        g.rebuild_file(9, "src/lib.rs", Language::Rust, src, &[], &[]);

        let field = g
            .iter_nodes()
            .find(|n| n.kind == NodeKind::Field && n.name == "name")
            .expect("expected public field node");
        assert_eq!(field.container.as_deref(), Some("Greeter"));
        assert_eq!(field.access_level.as_deref(), Some("public"));

        let case = g
            .iter_nodes()
            .find(|n| n.kind == NodeKind::EnumCase && n.name == "Red")
            .expect("expected enum case node");
        assert_eq!(case.container.as_deref(), Some("Color"));

        let color = g
            .iter_nodes()
            .find(|n| n.kind == NodeKind::Type && n.name == "Color")
            .expect("expected enum type node");
        assert!(
            g.outgoing(color.id)
                .iter()
                .any(|edge| edge.kind == EdgeKind::Contains && edge.to == case.id),
            "enum type should contain its case"
        );
    }

    #[test]
    fn called_by_inverse_label_resolves() {
        let (kind, reversed) = EdgeKind::parse_with_direction("CALLED_BY").unwrap();
        assert_eq!(kind, EdgeKind::Calls);
        assert!(reversed);
        let (kind, reversed) = EdgeKind::parse_with_direction("CALLS").unwrap();
        assert_eq!(kind, EdgeKind::Calls);
        assert!(!reversed);
    }

    /// The `REFS` name heuristic must point only at declarations another
    /// file could name. Before this was enforced, a call site was a legal
    /// target, so a workspace with N call sites of a popular name grew
    /// REFS quadratically: 80.9M of 87.0M edges on a real 7,038-file
    /// workspace pointed at call sites (#8081).
    #[test]
    fn refs_never_point_at_a_call_site() {
        let mut g = SymbolGraph::new();
        // One declaration of `helper`, in its own file.
        g.rebuild_file(
            1,
            "src/decl.rs",
            Language::Rust,
            "pub fn helper() -> i32 { 1 }\n",
            &[],
            &[],
        );
        // A file full of calls to it. Each call is a CallSite node named
        // `helper`, and each is a candidate REFS target under the old rule.
        g.rebuild_file(
            2,
            "src/uses.rs",
            Language::Rust,
            "fn a() { helper(); helper(); helper(); }\n",
            &[],
            &[],
        );
        // A third file that merely mentions the word.
        g.rebuild_file(
            3,
            "src/mentions.rs",
            Language::Rust,
            "fn b() { let _ = \"helper\"; helper(); }\n",
            &[],
            &[],
        );

        // Positive control: the heuristic still fires. The mentioning
        // module reaches the real declaration.
        let decl = *g
            .nodes_named("helper")
            .iter()
            .find(|id| g.node(**id).is_some_and(|n| n.kind == NodeKind::Function))
            .expect("the function declaration exists");
        let mentions_mod = g.module_node_for_file(3).unwrap();
        assert!(
            g.outgoing(mentions_mod)
                .iter()
                .any(|e| e.kind == EdgeKind::Refs && e.to == decl),
            "a module naming a cross-file function must still get a REFS edge"
        );

        // The property: no REFS edge anywhere lands on a non-addressable
        // node. Asserted over the whole graph, not just the one module,
        // so a future kind cannot quietly re-enter through another path.
        let call_sites = g
            .iter_nodes()
            .filter(|n| n.kind == NodeKind::CallSite)
            .count();
        assert!(
            call_sites >= 4,
            "fixture must contain call sites to exclude"
        );
        for id in g.all_node_ids() {
            for edge in g.outgoing(id) {
                if edge.kind != EdgeKind::Refs {
                    continue;
                }
                let target = g.node(edge.to).expect("edge target exists");
                assert!(
                    target.kind.is_name_addressable(),
                    "REFS edge points at a {} node named `{}`, which no bare \
                     identifier in another file can be naming",
                    target.kind.as_str(),
                    target.name
                );
            }
        }
    }

    /// A field name is scoped to its container, so a module that merely
    /// contains the same word is not referencing it.
    #[test]
    fn refs_never_point_at_a_field_or_enum_case() {
        let mut g = SymbolGraph::new();
        g.rebuild_file(
            1,
            "src/model.rs",
            Language::Rust,
            "pub struct Doc { pub path: String }\npub enum Mode { Fastpath }\n",
            &[],
            &[],
        );
        g.rebuild_file(
            2,
            "src/other.rs",
            Language::Rust,
            "fn go() { let path = 1; let Fastpath = 2; }\n",
            &[],
            &[],
        );
        assert!(
            g.iter_nodes().any(|n| n.kind == NodeKind::Field),
            "fixture must declare a field to exclude"
        );
        let other_mod = g.module_node_for_file(2).unwrap();
        for edge in g.outgoing(other_mod) {
            if edge.kind != EdgeKind::Refs {
                continue;
            }
            let target = g.node(edge.to).unwrap();
            assert!(
                target.kind.is_name_addressable(),
                "REFS edge points at a container-scoped {} named `{}`",
                target.kind.as_str(),
                target.name
            );
        }
    }

    /// Every kind is classified deliberately. A kind added later fails
    /// this test until someone decides which side it belongs on, rather
    /// than defaulting into the heuristic and re-opening #8081.
    #[test]
    fn every_node_kind_has_a_deliberate_addressability_verdict() {
        for kind in NodeKind::ALL {
            let expected = match kind {
                NodeKind::Function | NodeKind::Type | NodeKind::Macro | NodeKind::Module => true,
                NodeKind::Field | NodeKind::EnumCase | NodeKind::CallSite | NodeKind::Import => {
                    false
                }
            };
            assert_eq!(
                kind.is_name_addressable(),
                expected,
                "{} changed sides; decide deliberately and update #8081's reasoning",
                kind.as_str()
            );
        }
    }

    /// A call must not link to an identically-named function the caller
    /// neither defines nor imports. Before this, every function sharing
    /// the callee's name was a target, so on a 7,038-file workspace one
    /// function node collected 32,887 callers and six of every seven
    /// edges were wrong (#8107).
    #[test]
    fn a_call_does_not_reach_an_unimported_same_named_function() {
        let mut g = SymbolGraph::new();
        // Three unrelated files each declaring `assert`, plus a caller
        // that imports exactly one of them.
        g.rebuild_file(1, "a.rs", Language::Rust, "pub fn assert() {}\n", &[], &[]);
        g.rebuild_file(2, "b.rs", Language::Rust, "pub fn assert() {}\n", &[], &[]);
        g.rebuild_file(3, "c.rs", Language::Rust, "pub fn assert() {}\n", &[], &[]);
        g.rebuild_file(
            4,
            "caller.rs",
            Language::Rust,
            "use crate::b::assert;\nfn go() { assert(); }\n",
            &["crate::b".into()],
            &[2],
        );

        let call = *g
            .nodes_named("assert")
            .iter()
            .find(|id| g.node(**id).is_some_and(|n| n.kind == NodeKind::CallSite))
            .expect("the call site exists");
        let targets: Vec<&str> = g
            .outgoing(call)
            .iter()
            .filter(|e| e.kind == EdgeKind::Calls)
            .filter_map(|e| g.node(e.to))
            .map(|n| n.path.as_str())
            .collect();
        assert_eq!(
            targets,
            vec!["b.rs"],
            "a call must reach only the declaration its file imports"
        );

        // The negative control is the whole point: the other two
        // declarations must have gained no caller at all.
        for path in ["a.rs", "c.rs"] {
            let decl = *g
                .nodes_named("assert")
                .iter()
                .find(|id| {
                    g.node(**id)
                        .is_some_and(|n| n.kind == NodeKind::Function && n.path == path)
                })
                .expect("declaration exists");
            assert!(
                g.incoming(decl).iter().all(|e| e.kind != EdgeKind::Calls),
                "{path} was never imported by the caller and must have no CALLS edge"
            );
        }
    }

    /// A definition in the calling file wins over anything imported,
    /// because that is what the language does.
    #[test]
    fn a_local_definition_shadows_an_imported_one() {
        let mut g = SymbolGraph::new();
        g.rebuild_file(
            1,
            "dep.rs",
            Language::Rust,
            "pub fn helper() {}\n",
            &[],
            &[],
        );
        g.rebuild_file(
            2,
            "local.rs",
            Language::Rust,
            "use crate::dep::helper;\nfn helper() {}\nfn go() { helper(); }\n",
            &["crate::dep".into()],
            &[1],
        );

        let call = *g
            .nodes_named("helper")
            .iter()
            .find(|id| g.node(**id).is_some_and(|n| n.kind == NodeKind::CallSite))
            .expect("call site");
        let targets: Vec<&str> = g
            .outgoing(call)
            .iter()
            .filter(|e| e.kind == EdgeKind::Calls)
            .filter_map(|e| g.node(e.to))
            .map(|n| n.path.as_str())
            .collect();
        assert_eq!(targets, vec!["local.rs"]);
    }

    /// Recall guard. A name with exactly one declaration anywhere is
    /// unambiguous, so it still resolves even when no import edge was
    /// recorded — a sibling module in the same crate, a global, or a
    /// language with no import syntax. Without this the fix would trade
    /// one silent wrongness for another.
    #[test]
    fn a_unique_name_resolves_without_an_import_edge() {
        let mut g = SymbolGraph::new();
        g.rebuild_file(
            1,
            "only.rs",
            Language::Rust,
            "pub fn one_of_a_kind() {}\n",
            &[],
            &[],
        );
        g.rebuild_file(
            2,
            "caller.rs",
            Language::Rust,
            "fn go() { one_of_a_kind(); }\n",
            &[],
            &[],
        );

        let call = *g
            .nodes_named("one_of_a_kind")
            .iter()
            .find(|id| g.node(**id).is_some_and(|n| n.kind == NodeKind::CallSite))
            .expect("call site");
        let targets: Vec<&str> = g
            .outgoing(call)
            .iter()
            .filter(|e| e.kind == EdgeKind::Calls)
            .filter_map(|e| g.node(e.to))
            .map(|n| n.path.as_str())
            .collect();
        assert_eq!(
            targets,
            vec!["only.rs"],
            "an unambiguous name must still resolve across files"
        );
    }

    /// Ambiguous and unimportable is the one case where the old code
    /// invented edges. It must now produce none rather than guess.
    #[test]
    fn an_ambiguous_unimported_call_produces_no_edge() {
        let mut g = SymbolGraph::new();
        g.rebuild_file(1, "a.rs", Language::Rust, "pub fn run() {}\n", &[], &[]);
        g.rebuild_file(2, "b.rs", Language::Rust, "pub fn run() {}\n", &[], &[]);
        g.rebuild_file(
            3,
            "caller.rs",
            Language::Rust,
            "fn go() { run(); }\n",
            &[],
            &[],
        );

        let call = *g
            .nodes_named("run")
            .iter()
            .find(|id| g.node(**id).is_some_and(|n| n.kind == NodeKind::CallSite))
            .expect("call site");
        let calls: Vec<_> = g
            .outgoing(call)
            .iter()
            .filter(|e| e.kind == EdgeKind::Calls)
            .collect();
        assert!(
            calls.is_empty(),
            "two candidates and no import is a guess, not a resolution; got {} edges",
            calls.len()
        );
    }

    #[test]
    fn link_imports_creates_module_to_module_edges() {
        let mut g = SymbolGraph::new();
        g.rebuild_file(
            1,
            "src/a.ts",
            Language::TypeScript,
            "import { x } from \"./b\";\n",
            &["./b".into()],
            &[],
        );
        g.rebuild_file(
            2,
            "src/b.ts",
            Language::TypeScript,
            "export const x = 1;\n",
            &[],
            &[],
        );
        let mut resolved: HashMap<FileId, Vec<FileId>> = HashMap::new();
        resolved.insert(1, vec![2]);
        g.link_imports(&resolved);
        let a_mod = g.module_node_for_file(1).unwrap();
        let b_mod = g.module_node_for_file(2).unwrap();
        let edge_exists = g
            .outgoing(a_mod)
            .iter()
            .any(|e| e.kind == EdgeKind::Imports && e.to == b_mod);
        assert!(edge_exists, "expected Module→Module IMPORTS edge");
    }

    #[test]
    fn link_imports_is_idempotent_across_repeated_relinks() {
        let mut g = SymbolGraph::new();
        g.rebuild_file(
            1,
            "src/a.ts",
            Language::TypeScript,
            "import { x } from \"./b\";\n",
            &["./b".into()],
            &[],
        );
        g.rebuild_file(
            2,
            "src/b.ts",
            Language::TypeScript,
            "export const x = 1;\n",
            &[],
            &[],
        );
        let mut resolved: HashMap<FileId, Vec<FileId>> = HashMap::new();
        resolved.insert(1, vec![2]);
        // `link_imports` re-runs over the whole workspace after every per-file
        // reindex, so relinking three times must not accumulate duplicate
        // Module→Module IMPORTS edges.
        g.link_imports(&resolved);
        g.link_imports(&resolved);
        g.link_imports(&resolved);
        let a_mod = g.module_node_for_file(1).unwrap();
        let b_mod = g.module_node_for_file(2).unwrap();
        let module_import_edges = g
            .outgoing(a_mod)
            .iter()
            .filter(|e| e.kind == EdgeKind::Imports && e.to == b_mod)
            .count();
        assert_eq!(
            module_import_edges, 1,
            "Module→Module IMPORTS edge must not duplicate across relinks"
        );
    }

    #[test]
    fn harn_reference_projection_replaces_stale_edges_and_keeps_names_separate() {
        let mut graph = SymbolGraph::new();
        graph.rebuild_file(1, "a.harn", Language::Harn, "fn run() { 1 }", &[], &[]);
        graph.rebuild_file(2, "b.harn", Language::Harn, "fn run() { 2 }", &[], &[]);
        graph.rebuild_file(
            3,
            "use.harn",
            Language::Harn,
            "fn use_it() { run() }",
            &[],
            &[],
        );
        graph.replace_harn_references(&[ResolvedHarnReference {
            from_path: "use.harn".into(),
            to_path: "a.harn".into(),
            to_name: "run".into(),
        }]);
        let module = graph.module_node_for_file(3).unwrap();
        let target_path = |graph: &SymbolGraph| {
            graph
                .outgoing(module)
                .iter()
                .filter(|edge| edge.kind == EdgeKind::Refs)
                .map(|edge| graph.node(edge.to).unwrap().path.clone())
                .collect::<Vec<_>>()
        };
        assert_eq!(target_path(&graph), vec!["a.harn"]);

        graph.replace_harn_references(&[ResolvedHarnReference {
            from_path: "use.harn".into(),
            to_path: "b.harn".into(),
            to_name: "run".into(),
        }]);
        assert_eq!(target_path(&graph), vec!["b.harn"]);
    }
}