blastdiff 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,698 @@
1
+ """Diff-aware bidirectional symbol impact analyzer (pure core, zero I/O).
2
+
3
+ Given a clicked identifier (function, method, class, variable, or attribute)
4
+ at `(source_file, source_line)`, traces:
5
+ 1. Downstream (affected by this symbol): untouched external sites, sites
6
+ updated in this diff, and reaching test sites.
7
+ 2. Upstream (what affects this symbol): outgoing callees/dependencies for
8
+ callables (highlighting ones also modified in this diff), or write/assignment
9
+ sites for variables and attributes.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from pathlib import PurePosixPath
15
+ import time
16
+
17
+ import tree_sitter
18
+ import tree_sitter_go
19
+ import tree_sitter_javascript
20
+ import tree_sitter_python
21
+ import tree_sitter_rust
22
+ import tree_sitter_typescript
23
+
24
+ from blastdiff.core.blast_radius import is_test_path
25
+ from blastdiff.core.languages.base import analyze_file_cached, detect_language
26
+ from blastdiff.core.models import (
27
+ FileReview,
28
+ FileSymbols,
29
+ SymbolDef,
30
+ SymbolImpactReport,
31
+ SymbolOccurrence,
32
+ UpstreamDependency,
33
+ )
34
+
35
+ _BUILTIN_CALLEES: frozenset[str] = frozenset(
36
+ {
37
+ # Python builtins
38
+ "abs", "all", "any", "bool", "bytes", "callable", "chr", "dict", "dir",
39
+ "enumerate", "eval", "exec", "filter", "float", "format", "frozenset",
40
+ "getattr", "hasattr", "hash", "id", "input", "int", "isinstance",
41
+ "issubclass", "iter", "len", "list", "map", "max", "min", "next",
42
+ "object", "open", "ord", "pow", "print", "property", "range", "repr",
43
+ "reversed", "round", "set", "setattr", "slice", "sorted", "str", "sum",
44
+ "super", "tuple", "type", "vars", "zip",
45
+ "Exception", "ValueError", "TypeError", "KeyError", "RuntimeError",
46
+ "OSError", "FileNotFoundError", "AttributeError", "IndexError",
47
+ # Common container methods
48
+ "append", "extend", "get", "items", "keys", "values", "pop", "push",
49
+ "join", "split", "strip", "lstrip", "rstrip", "replace", "lower", "upper",
50
+ "startswith", "endswith", "encode", "decode", "format", "sort", "update",
51
+ "add", "remove", "discard", "clear", "copy", "items", "read", "write",
52
+ "close", "toString", "valueOf", "includes", "indexOf", "slice", "splice",
53
+ "forEach", "reduce", "find", "some", "every", "trim", "match", "test",
54
+ "log", "warn", "error", "info", "debug", "parse", "stringify", "assign",
55
+ "resolve", "reject", "then", "catch", "finally",
56
+ }
57
+ )
58
+
59
+ _MAX_OCCURRENCES_PER_BUCKET = 80
60
+ _MAX_UPSTREAM_ITEMS = 60
61
+
62
+ _PARSERS: dict[str, tree_sitter.Parser] = {}
63
+
64
+
65
+ def _get_parser(file_path: str) -> tuple[tree_sitter.Parser | None, str]:
66
+ lang = detect_language(file_path)
67
+ if lang == "python":
68
+ key = "python"
69
+ if key not in _PARSERS:
70
+ _PARSERS[key] = tree_sitter.Parser(
71
+ tree_sitter.Language(tree_sitter_python.language())
72
+ )
73
+ return _PARSERS[key], "python"
74
+ if lang == "typescript":
75
+ suffix = PurePosixPath(file_path.replace("\\", "/")).suffix.lower()
76
+ key = "tsx" if suffix == ".tsx" else "ts"
77
+ if key not in _PARSERS:
78
+ ts_lang = (
79
+ tree_sitter_typescript.language_tsx()
80
+ if key == "tsx"
81
+ else tree_sitter_typescript.language_typescript()
82
+ )
83
+ _PARSERS[key] = tree_sitter.Parser(tree_sitter.Language(ts_lang))
84
+ return _PARSERS[key], "typescript"
85
+ if lang == "javascript":
86
+ key = "js"
87
+ if key not in _PARSERS:
88
+ _PARSERS[key] = tree_sitter.Parser(
89
+ tree_sitter.Language(tree_sitter_javascript.language())
90
+ )
91
+ return _PARSERS[key], "javascript"
92
+ if lang == "go":
93
+ key = "go"
94
+ if key not in _PARSERS:
95
+ _PARSERS[key] = tree_sitter.Parser(
96
+ tree_sitter.Language(tree_sitter_go.language())
97
+ )
98
+ return _PARSERS[key], "go"
99
+ if lang == "rust":
100
+ key = "rust"
101
+ if key not in _PARSERS:
102
+ _PARSERS[key] = tree_sitter.Parser(
103
+ tree_sitter.Language(tree_sitter_rust.language())
104
+ )
105
+ return _PARSERS[key], "rust"
106
+ return None, lang
107
+
108
+
109
+ def _node_text(node: tree_sitter.Node | None, source_bytes: bytes) -> str:
110
+ if node is None:
111
+ return ""
112
+ return source_bytes[node.start_byte : node.end_byte].decode("utf-8", errors="replace")
113
+
114
+
115
+ def _enclosing_for_line(line: int, defs: list[SymbolDef]) -> SymbolDef | None:
116
+ containing = [d for d in defs if d.start_line <= line <= d.end_line]
117
+ if not containing:
118
+ return None
119
+ containing.sort(key=lambda d: (d.end_line - d.start_line, d.start_line))
120
+ return containing[0]
121
+
122
+
123
+ def _collect_diff_lines_by_file(files: list[FileReview]) -> dict[str, set[int]]:
124
+ result: dict[str, set[int]] = {}
125
+ for f in files:
126
+ lines: set[int] = set()
127
+ for hunk in f.hunks:
128
+ for dl in hunk.lines:
129
+ if dl.kind == "add" and dl.new_lineno is not None:
130
+ lines.add(dl.new_lineno)
131
+ result[f.path] = lines
132
+ return result
133
+
134
+
135
+ def _is_write_context_py(node: tree_sitter.Node) -> bool:
136
+ parent = node.parent
137
+ if parent is None:
138
+ return False
139
+ ptype = parent.type
140
+ if ptype in ("assignment", "augmented_assignment"):
141
+ left = parent.child_by_field_name("left")
142
+ return left is not None and left.start_byte <= node.start_byte and node.end_byte <= left.end_byte
143
+ if ptype in ("typed_parameter", "default_parameter", "typed_default_parameter", "parameters", "list_splat_pattern", "dictionary_splat_pattern"):
144
+ name_field = parent.child_by_field_name("name")
145
+ if name_field is not None:
146
+ return name_field.start_byte == node.start_byte and name_field.end_byte == node.end_byte
147
+ return ptype == "parameters"
148
+ if ptype == "for_statement":
149
+ left = parent.child_by_field_name("left")
150
+ return left is not None and left.start_byte <= node.start_byte and node.end_byte <= left.end_byte
151
+ if ptype == "as_pattern_target":
152
+ return True
153
+ if ptype == "attribute":
154
+ gp = parent.parent
155
+ if gp is not None and gp.type in ("assignment", "augmented_assignment"):
156
+ left = gp.child_by_field_name("left")
157
+ if left is not None and left.start_byte == parent.start_byte and left.end_byte == parent.end_byte:
158
+ attr = parent.child_by_field_name("attribute")
159
+ return attr is not None and attr.start_byte == node.start_byte
160
+ return False
161
+
162
+
163
+ def _is_write_context_ts(node: tree_sitter.Node) -> bool:
164
+ parent = node.parent
165
+ if parent is None:
166
+ return False
167
+ ptype = parent.type
168
+ if ptype in ("variable_declarator", "assignment_expression", "augmented_assignment_expression"):
169
+ target = parent.child_by_field_name("name") or parent.child_by_field_name("left")
170
+ return target is not None and target.start_byte <= node.start_byte and node.end_byte <= target.end_byte
171
+ if ptype in ("required_parameter", "optional_parameter", "formal_parameters"):
172
+ pattern = parent.child_by_field_name("pattern")
173
+ if pattern is not None:
174
+ return pattern.start_byte <= node.start_byte and node.end_byte <= pattern.end_byte
175
+ return ptype == "formal_parameters"
176
+ if ptype == "member_expression":
177
+ gp = parent.parent
178
+ if gp is not None and gp.type in ("assignment_expression", "augmented_assignment_expression"):
179
+ left = gp.child_by_field_name("left")
180
+ if left is not None and left.start_byte == parent.start_byte and left.end_byte == parent.end_byte:
181
+ prop = parent.child_by_field_name("property")
182
+ return prop is not None and prop.start_byte == node.start_byte
183
+ return False
184
+
185
+
186
+ def _classify_occurrence_role(node: tree_sitter.Node, language: str) -> str:
187
+ parent = node.parent
188
+ if parent is None:
189
+ return "read"
190
+ ptype = parent.type
191
+
192
+ if language == "python":
193
+ if ptype in ("function_definition", "class_definition"):
194
+ name_node = parent.child_by_field_name("name")
195
+ if name_node is not None and name_node.start_byte == node.start_byte:
196
+ return "definition"
197
+ if ptype in ("import_statement", "import_from_statement", "aliased_import", "dotted_name"):
198
+ cur = parent
199
+ while cur is not None:
200
+ if cur.type in ("import_statement", "import_from_statement"):
201
+ return "import"
202
+ cur = cur.parent
203
+ if ptype == "call":
204
+ fn = parent.child_by_field_name("function")
205
+ if fn is not None and fn.start_byte == node.start_byte:
206
+ return "call"
207
+ if ptype == "attribute":
208
+ attr = parent.child_by_field_name("attribute")
209
+ if attr is not None and attr.start_byte == node.start_byte:
210
+ gp = parent.parent
211
+ if gp is not None and gp.type == "call":
212
+ fn = gp.child_by_field_name("function")
213
+ if fn is not None and fn.start_byte == parent.start_byte:
214
+ return "call"
215
+ if _is_write_context_py(node):
216
+ return "write"
217
+ return "read"
218
+
219
+ # TypeScript / JavaScript
220
+ if ptype in (
221
+ "function_declaration",
222
+ "method_definition",
223
+ "class_declaration",
224
+ "interface_declaration",
225
+ "type_alias_declaration",
226
+ ):
227
+ name_node = parent.child_by_field_name("name")
228
+ if name_node is not None and name_node.start_byte == node.start_byte:
229
+ return "definition"
230
+ if ptype in ("import_specifier", "import_clause", "namespace_import", "import_statement"):
231
+ return "import"
232
+ if ptype == "call_expression":
233
+ fn = parent.child_by_field_name("function")
234
+ if fn is not None and fn.start_byte == node.start_byte:
235
+ return "call"
236
+ if ptype == "member_expression":
237
+ prop = parent.child_by_field_name("property")
238
+ if prop is not None and prop.start_byte == node.start_byte:
239
+ gp = parent.parent
240
+ if gp is not None and gp.type == "call_expression":
241
+ fn = gp.child_by_field_name("function")
242
+ if fn is not None and fn.start_byte == parent.start_byte:
243
+ return "call"
244
+ if _is_write_context_ts(node):
245
+ return "write"
246
+ return "read"
247
+
248
+
249
+ def _classify_occurrence_role_go(node: tree_sitter.Node) -> str:
250
+ parent = node.parent
251
+ if parent is None:
252
+ return "read"
253
+ ptype = parent.type
254
+ if ptype in ("function_declaration", "method_declaration", "type_spec"):
255
+ name_node = parent.child_by_field_name("name")
256
+ if name_node is not None and name_node.start_byte == node.start_byte:
257
+ return "definition"
258
+ if ptype == "import_spec":
259
+ return "import"
260
+ if ptype == "call_expression":
261
+ fn = parent.child_by_field_name("function")
262
+ if fn is not None and fn.start_byte == node.start_byte:
263
+ return "call"
264
+ if ptype == "selector_expression":
265
+ field = parent.child_by_field_name("field")
266
+ if field is not None and field.start_byte == node.start_byte:
267
+ gp = parent.parent
268
+ if gp is not None and gp.type == "call_expression":
269
+ fn = gp.child_by_field_name("function")
270
+ if fn is not None and fn.start_byte == parent.start_byte:
271
+ return "call"
272
+ if ptype in ("short_var_declaration", "assignment_statement", "var_spec", "const_spec"):
273
+ left = parent.child_by_field_name("left") or parent.child_by_field_name("name")
274
+ if left is not None and left.start_byte <= node.start_byte and node.end_byte <= left.end_byte:
275
+ return "write"
276
+ if ptype == "expression_list":
277
+ gp = parent.parent
278
+ if gp is not None and gp.type in ("short_var_declaration", "assignment_statement"):
279
+ left = gp.child_by_field_name("left")
280
+ if left is not None and left.start_byte == parent.start_byte:
281
+ return "write"
282
+ if ptype == "parameter_declaration":
283
+ name_node = parent.child_by_field_name("name")
284
+ if name_node is not None and name_node.start_byte == node.start_byte:
285
+ return "write"
286
+ return "read"
287
+
288
+
289
+ def _classify_occurrence_role_rust(node: tree_sitter.Node) -> str:
290
+ parent = node.parent
291
+ if parent is None:
292
+ return "read"
293
+ ptype = parent.type
294
+ if ptype in ("function_item", "struct_item", "enum_item", "trait_item", "type_item"):
295
+ name_node = parent.child_by_field_name("name")
296
+ if name_node is not None and name_node.start_byte == node.start_byte:
297
+ return "definition"
298
+ cur = parent
299
+ while cur is not None:
300
+ if cur.type == "use_declaration":
301
+ return "import"
302
+ if cur.type in ("block", "function_item", "source_file"):
303
+ break
304
+ cur = cur.parent
305
+ if ptype == "call_expression":
306
+ fn = parent.child_by_field_name("function")
307
+ if fn is not None and fn.start_byte == node.start_byte:
308
+ return "call"
309
+ if ptype in ("scoped_identifier", "field_expression"):
310
+ gp = parent.parent
311
+ if gp is not None and gp.type == "call_expression":
312
+ fn = gp.child_by_field_name("function")
313
+ if fn is not None and fn.start_byte == parent.start_byte:
314
+ return "call"
315
+ if ptype in ("let_declaration", "parameter"):
316
+ pat = parent.child_by_field_name("pattern")
317
+ if pat is not None and pat.start_byte <= node.start_byte and node.end_byte <= pat.end_byte:
318
+ return "write"
319
+ if ptype in ("assignment_expression", "compound_assignment_expr"):
320
+ left = parent.child_by_field_name("left")
321
+ if left is not None and left.start_byte <= node.start_byte and node.end_byte <= left.end_byte:
322
+ return "write"
323
+ return "read"
324
+
325
+
326
+ def _scan_identifier_occurrences(
327
+ file_path: str,
328
+ source: str,
329
+ symbol: str,
330
+ defs: list[SymbolDef],
331
+ diff_paths: set[str],
332
+ diff_lines: set[int],
333
+ line_range: tuple[int, int] | None = None,
334
+ ) -> tuple[list[SymbolOccurrence], bool]:
335
+ """Walk tree-sitter AST of a single file to classify every occurrence of `symbol`.
336
+
337
+ Returns `(occurrences, saw_attribute_access)`.
338
+ """
339
+ if not source or symbol not in source:
340
+ return [], False
341
+
342
+ parser, language = _get_parser(file_path)
343
+ if parser is None:
344
+ return [], False
345
+
346
+ source_bytes = source.encode("utf-8", errors="replace")
347
+ source_lines = source.splitlines()
348
+ tree = parser.parse(source_bytes)
349
+ sym_bytes = symbol.encode("utf-8")
350
+
351
+ occurrences: list[SymbolOccurrence] = []
352
+ saw_attribute = False
353
+ in_diff_file = file_path in diff_paths
354
+ is_test_file = is_test_path(file_path)
355
+
356
+ if language == "python":
357
+ ident_types = {"identifier"}
358
+ elif language == "go":
359
+ ident_types = {"identifier", "field_identifier", "type_identifier"}
360
+ elif language == "rust":
361
+ ident_types = {"identifier", "field_identifier", "type_identifier"}
362
+ else:
363
+ ident_types = {"identifier", "property_identifier", "type_identifier", "shorthand_property_identifier"}
364
+
365
+ stack: list[tree_sitter.Node] = [tree.root_node]
366
+ while stack:
367
+ node = stack.pop()
368
+ if line_range is not None:
369
+ n_start = node.start_point.row + 1
370
+ n_end = node.end_point.row + 1
371
+ if n_end < line_range[0] or n_start > line_range[1]:
372
+ continue
373
+
374
+ if node.type in ident_types:
375
+ if source_bytes[node.start_byte : node.end_byte] == sym_bytes:
376
+ lineno = node.start_point.row + 1
377
+ col = node.start_point.column + 1
378
+ if line_range is not None and not (line_range[0] <= lineno <= line_range[1]):
379
+ continue
380
+
381
+ parent = node.parent
382
+ if parent is not None:
383
+ if language == "python" and parent.type == "attribute":
384
+ attr = parent.child_by_field_name("attribute")
385
+ if attr is not None and attr.start_byte == node.start_byte:
386
+ saw_attribute = True
387
+ elif language in ("typescript", "javascript") and parent.type == "member_expression":
388
+ prop = parent.child_by_field_name("property")
389
+ if prop is not None and prop.start_byte == node.start_byte:
390
+ saw_attribute = True
391
+ elif language == "go" and parent.type == "selector_expression":
392
+ field = parent.child_by_field_name("field")
393
+ if field is not None and field.start_byte == node.start_byte:
394
+ saw_attribute = True
395
+ elif language == "rust" and parent.type == "field_expression":
396
+ field = parent.child_by_field_name("field")
397
+ if field is not None and field.start_byte == node.start_byte:
398
+ saw_attribute = True
399
+
400
+ if language == "go":
401
+ role = _classify_occurrence_role_go(node)
402
+ elif language == "rust":
403
+ role = _classify_occurrence_role_rust(node)
404
+ else:
405
+ role = _classify_occurrence_role(node, language)
406
+ enclosing_def = _enclosing_for_line(lineno, defs)
407
+ snippet = source_lines[lineno - 1].strip()[:160] if 1 <= lineno <= len(source_lines) else ""
408
+ occurrences.append(
409
+ SymbolOccurrence(
410
+ file_path=file_path,
411
+ line=lineno,
412
+ column=col,
413
+ enclosing_symbol=enclosing_def.qualified_name if enclosing_def else None,
414
+ role=role, # type: ignore[arg-type]
415
+ snippet=snippet,
416
+ in_diff=in_diff_file,
417
+ is_test=is_test_file,
418
+ line_in_diff=(lineno in diff_lines),
419
+ )
420
+ )
421
+ else:
422
+ children = node.children
423
+ if children:
424
+ stack.extend(reversed(children))
425
+
426
+ return occurrences, saw_attribute
427
+
428
+
429
+ def analyze_symbol_impact(
430
+ symbol: str,
431
+ source_file: str,
432
+ source_line: int,
433
+ files: list[FileReview],
434
+ head_sources: dict[str, str],
435
+ repo_sources: dict[str, str],
436
+ ) -> SymbolImpactReport:
437
+ """Compute diff-aware bidirectional impact for a clicked symbol in the repo."""
438
+ started = time.perf_counter()
439
+ clean_symbol = symbol.strip()
440
+ norm_source_file = source_file.replace("\\", "/")
441
+
442
+ diff_paths = {f.path for f in files}
443
+ diff_lines_by_file = _collect_diff_lines_by_file(files)
444
+
445
+ # Track symbols modified in this diff for upstream ripple detection
446
+ changed_symbol_names: set[str] = set()
447
+ changed_symbol_keys: set[tuple[str, str]] = set()
448
+ for f in files:
449
+ for sc in f.symbol_changes:
450
+ changed_symbol_names.add(sc.name)
451
+ changed_symbol_names.add(sc.name.rsplit(".", 1)[-1])
452
+ changed_symbol_keys.add((f.path, sc.name.rsplit(".", 1)[-1]))
453
+
454
+ effective_sources: dict[str, str] = {}
455
+ for p, src in repo_sources.items():
456
+ effective_sources[p.replace("\\", "/")] = src
457
+ for p, src in head_sources.items():
458
+ effective_sources[p.replace("\\", "/")] = src
459
+
460
+ # Parse FileSymbols across repo (cached by content hash)
461
+ parsed_files: dict[str, FileSymbols] = {}
462
+ defs_by_name: dict[str, list[SymbolDef]] = {}
463
+ for p, src in effective_sources.items():
464
+ syms = analyze_file_cached(p, src)
465
+ if syms is None:
466
+ continue
467
+ parsed_files[p] = syms
468
+ for d in syms.definitions:
469
+ defs_by_name.setdefault(d.name, []).append(d)
470
+
471
+ source_syms = parsed_files.get(norm_source_file)
472
+ source_defs = source_syms.definitions if source_syms else []
473
+ enclosing_def = _enclosing_for_line(source_line, source_defs)
474
+
475
+ # 1. Resolve matching callable / type definitions
476
+ matching_defs = defs_by_name.get(clean_symbol, [])
477
+ # Prefer definition in source_file, then imported files, then exported repo defs
478
+ same_file_defs = [d for d in matching_defs if d.file_path == norm_source_file]
479
+ imported_modules: set[str] = set()
480
+ if source_syms:
481
+ for imp in source_syms.imports:
482
+ if clean_symbol in imp.names:
483
+ imported_modules.add(imp.module.strip("."))
484
+ if imp.module:
485
+ imported_modules.add(imp.module.strip("."))
486
+
487
+ def _def_rank(d: SymbolDef) -> tuple[int, int, str, int]:
488
+ is_same = 0 if d.file_path == norm_source_file else 1
489
+ stem = PurePosixPath(d.file_path).stem
490
+ is_imp = 0 if any(stem in m or m in d.file_path for m in imported_modules) else 1
491
+ return (is_same, is_imp, d.file_path, d.start_line)
492
+
493
+ matching_defs_sorted = sorted(matching_defs, key=_def_rank)
494
+
495
+ # Check local occurrences in source_file to distinguish local variables vs attributes vs callables
496
+ src_text = effective_sources.get(norm_source_file, "")
497
+ src_occs, saw_attr_in_src = _scan_identifier_occurrences(
498
+ norm_source_file,
499
+ src_text,
500
+ clean_symbol,
501
+ source_defs,
502
+ diff_paths,
503
+ diff_lines_by_file.get(norm_source_file, set()),
504
+ )
505
+
506
+ clicked_is_attr = saw_attr_in_src and any(
507
+ o.line == source_line for o in src_occs
508
+ )
509
+
510
+ inferred_kind: str = "unknown"
511
+ scope: str = "repository"
512
+ primary_def: SymbolDef | None = None
513
+
514
+ if same_file_defs:
515
+ primary_def = same_file_defs[0]
516
+ inferred_kind = primary_def.kind
517
+ elif matching_defs_sorted and not clicked_is_attr:
518
+ primary_def = matching_defs_sorted[0]
519
+ inferred_kind = primary_def.kind
520
+ elif clicked_is_attr:
521
+ inferred_kind = "attribute"
522
+ scope = "repository"
523
+ else:
524
+ # Check if this identifier is written inside enclosing_def (local variable / param)
525
+ inferred_kind = "variable"
526
+ if enclosing_def is not None:
527
+ local_writes = [
528
+ o
529
+ for o in src_occs
530
+ if o.role == "write"
531
+ and enclosing_def.start_line <= o.line <= enclosing_def.end_line
532
+ ]
533
+ module_level_writes = [
534
+ o for o in src_occs if o.role == "write" and o.enclosing_symbol is None
535
+ ]
536
+ if local_writes and not module_level_writes:
537
+ scope = "local"
538
+
539
+ definitions: list[SymbolOccurrence] = []
540
+ downstream_untouched: list[SymbolOccurrence] = []
541
+ downstream_in_diff: list[SymbolOccurrence] = []
542
+ downstream_tests: list[SymbolOccurrence] = []
543
+ upstream: list[UpstreamDependency] = []
544
+
545
+ if scope == "local" and enclosing_def is not None:
546
+ # Trace exact reads (downstream) and writes (upstream) strictly inside enclosing function
547
+ local_occs, _ = _scan_identifier_occurrences(
548
+ norm_source_file,
549
+ src_text,
550
+ clean_symbol,
551
+ source_defs,
552
+ diff_paths,
553
+ diff_lines_by_file.get(norm_source_file, set()),
554
+ line_range=(enclosing_def.start_line, enclosing_def.end_line),
555
+ )
556
+ for occ in local_occs:
557
+ if occ.role == "write":
558
+ if not definitions:
559
+ definitions.append(occ.model_copy(update={"role": "definition"}))
560
+ upstream.append(
561
+ UpstreamDependency(
562
+ name=clean_symbol,
563
+ kind="write",
564
+ file_path=occ.file_path,
565
+ line=occ.line,
566
+ target_file=occ.file_path,
567
+ target_line=occ.line,
568
+ snippet=occ.snippet,
569
+ changed_in_diff=occ.line_in_diff,
570
+ )
571
+ )
572
+ elif occ.role in ("read", "call"):
573
+ if occ.is_test:
574
+ downstream_tests.append(occ)
575
+ else:
576
+ downstream_in_diff.append(occ)
577
+ else:
578
+ # Repository-wide diff-aware tracing
579
+ for d in matching_defs_sorted[:10]:
580
+ d_src = effective_sources.get(d.file_path, "")
581
+ d_lines = d_src.splitlines()
582
+ snippet = d_lines[d.start_line - 1].strip()[:160] if 1 <= d.start_line <= len(d_lines) else d.signature
583
+ definitions.append(
584
+ SymbolOccurrence(
585
+ file_path=d.file_path,
586
+ line=d.start_line,
587
+ column=1,
588
+ enclosing_symbol=d.qualified_name,
589
+ role="definition",
590
+ snippet=snippet,
591
+ in_diff=(d.file_path in diff_paths),
592
+ is_test=is_test_path(d.file_path),
593
+ line_in_diff=(d.start_line in diff_lines_by_file.get(d.file_path, set())),
594
+ )
595
+ )
596
+
597
+ is_callable_or_type = inferred_kind in ("function", "method", "class", "interface", "type")
598
+
599
+ for p, src in effective_sources.items():
600
+ if clean_symbol not in src:
601
+ continue
602
+ p_syms = parsed_files.get(p)
603
+ p_defs = p_syms.definitions if p_syms else []
604
+ occs, _ = _scan_identifier_occurrences(
605
+ p,
606
+ src,
607
+ clean_symbol,
608
+ p_defs,
609
+ diff_paths,
610
+ diff_lines_by_file.get(p, set()),
611
+ )
612
+ for occ in occs:
613
+ if occ.role == "definition":
614
+ continue
615
+ if not is_callable_or_type and occ.role == "write":
616
+ if not definitions:
617
+ definitions.append(occ.model_copy(update={"role": "definition"}))
618
+ upstream.append(
619
+ UpstreamDependency(
620
+ name=clean_symbol,
621
+ kind="write",
622
+ file_path=occ.file_path,
623
+ line=occ.line,
624
+ target_file=occ.file_path,
625
+ target_line=occ.line,
626
+ snippet=occ.snippet,
627
+ changed_in_diff=occ.line_in_diff or occ.in_diff,
628
+ )
629
+ )
630
+ continue
631
+
632
+ if occ.is_test:
633
+ downstream_tests.append(occ)
634
+ elif occ.in_diff:
635
+ downstream_in_diff.append(occ)
636
+ else:
637
+ downstream_untouched.append(occ)
638
+
639
+ # Upstream dependencies for callables/classes: outgoing calls inside primary definition
640
+ if is_callable_or_type and primary_def is not None:
641
+ def_syms = parsed_files.get(primary_def.file_path)
642
+ if def_syms is not None:
643
+ seen_callees: set[tuple[str, int]] = set()
644
+ for call in def_syms.calls:
645
+ if not (primary_def.start_line <= call.line <= primary_def.end_line):
646
+ continue
647
+ callee = call.callee_name
648
+ if not callee or callee == clean_symbol or callee in _BUILTIN_CALLEES:
649
+ continue
650
+ key = (callee, call.line)
651
+ if key in seen_callees:
652
+ continue
653
+ seen_callees.add(key)
654
+
655
+ target_defs = defs_by_name.get(callee, [])
656
+ target_def = target_defs[0] if target_defs else None
657
+ is_changed = (
658
+ callee in changed_symbol_names
659
+ or (
660
+ target_def is not None
661
+ and (target_def.file_path, callee) in changed_symbol_keys
662
+ )
663
+ )
664
+ upstream.append(
665
+ UpstreamDependency(
666
+ name=callee,
667
+ kind="call",
668
+ file_path=primary_def.file_path,
669
+ line=call.line,
670
+ target_file=target_def.file_path if target_def else None,
671
+ target_line=target_def.start_line if target_def else None,
672
+ snippet=call.snippet,
673
+ changed_in_diff=is_changed,
674
+ )
675
+ )
676
+
677
+ # Sort deterministically: changed/important first
678
+ downstream_untouched.sort(key=lambda o: (o.file_path, o.line))
679
+ downstream_in_diff.sort(key=lambda o: (not o.line_in_diff, o.file_path, o.line))
680
+ downstream_tests.sort(key=lambda o: (o.file_path, o.line))
681
+ upstream.sort(key=lambda u: (not u.changed_in_diff, u.target_file is None, u.file_path, u.line))
682
+
683
+ elapsed_ms = max(0, int((time.perf_counter() - started) * 1000))
684
+ return SymbolImpactReport(
685
+ symbol=clean_symbol,
686
+ source_file=norm_source_file,
687
+ source_line=source_line,
688
+ inferred_kind=inferred_kind, # type: ignore[arg-type]
689
+ scope=scope, # type: ignore[arg-type]
690
+ enclosing_symbol=enclosing_def.qualified_name if enclosing_def else None,
691
+ definitions=definitions[:10],
692
+ downstream_untouched=downstream_untouched[:_MAX_OCCURRENCES_PER_BUCKET],
693
+ downstream_in_diff=downstream_in_diff[:_MAX_OCCURRENCES_PER_BUCKET],
694
+ downstream_tests=downstream_tests[:_MAX_OCCURRENCES_PER_BUCKET],
695
+ upstream=upstream[:_MAX_UPSTREAM_ITEMS],
696
+ upstream_changed_in_diff_count=sum(1 for u in upstream if u.changed_in_diff),
697
+ analysis_ms=elapsed_ms,
698
+ )