tokensafe 2.6.1 → 2.7.0

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.
@@ -1,29 +1,68 @@
1
1
  """
2
2
  TokenSafe Graph Engine: Dependency-Aware Graph Analysis & Skeletonization.
3
- Builds a zero-LLM deterministic code graph (AST-based) for Python, TypeScript, and Go.
3
+ Builds a zero-LLM deterministic code graph for Python, TypeScript/JavaScript, Go,
4
+ Rust, Java, C#, C/C++, PHP, Kotlin, and Swift.
5
+
6
+ Uses the optional Tree-sitter backend when available (`src.treesitter_backend`)
7
+ and falls back seamlessly to the Python standard library `ast` and `BraceLexer`
8
+ state-machine parsers with zero extra required runtime dependencies.
9
+
4
10
  Powers:
5
- 1. Graph-Guided Skeletonization (target + 1-hop full, 2-hop signature, 0-hop pruned).
6
- 2. God Nodes Detection (architectural hubs via Degree Centrality).
11
+ 1. Graph-Guided Skeletonization (target + 1-hop full/signature, 0-hop isolated).
12
+ 2. God Nodes Detection (architectural hubs via import- & call-aware centrality).
7
13
  3. API Surface Map Generation (tokensafe-out/API_SURFACE.md).
8
- 4. Subtree Cache Invalidation & Instant Retrieval via incremental mtime tracking.
14
+ 4. Incremental `(mtime, size)` scanning & optional persistent disk cache.
9
15
  """
10
16
 
11
- import os
12
17
  import ast
13
- import re
18
+ import hashlib
14
19
  import json
20
+ import os
21
+ import re
15
22
  import stat
23
+ import tempfile
16
24
  import time
17
25
  from typing import Dict, Set, List, Optional, Tuple, Any
18
26
 
27
+ from src.paths import resolve_data_dir
28
+
19
29
  IGNORED_DIRS = {
20
30
  ".git", ".hg", ".svn", "node_modules", "dist", "build", "venv", ".venv",
21
31
  "__pycache__", ".idea", ".vscode", "data", "coverage", ".pytest_cache",
22
32
  "Library", "Applications", "Pictures", "Movies", "Music", "Downloads",
23
- ".cache", ".npm", ".bun", ".rustup", ".cargo", ".local", ".system_generated"
33
+ ".cache", ".npm", ".bun", ".rustup", ".cargo", ".local", ".system_generated",
34
+ "target", "tokensafe-out",
35
+ }
36
+
37
+ SUPPORTED_EXTS = {
38
+ ".py", ".ts", ".js", ".tsx", ".jsx", ".mjs", ".cjs",
39
+ ".go", ".rs", ".java", ".cs",
40
+ ".c", ".cpp", ".cc", ".cxx", ".h", ".hpp",
41
+ ".php", ".kt", ".kts", ".swift",
42
+ }
43
+
44
+ _SKIP_CALLS = {
45
+ "if", "else", "for", "while", "do", "switch", "case", "catch", "try",
46
+ "return", "throw", "yield", "await", "sizeof", "typeof", "instanceof",
47
+ "new", "delete", "import", "export", "require", "print", "len", "str",
48
+ "int", "float", "bool", "list", "dict", "set", "tuple", "range",
49
+ "div", "span", "button", "input", "label", "form", "svg", "path",
50
+ "true", "false", "null", "undefined", "None", "True", "False",
24
51
  }
25
52
 
26
- SUPPORTED_EXTS = {".py", ".ts", ".js", ".tsx", ".jsx", ".go"}
53
+ _CACHE_SCHEMA_VERSION = 2
54
+
55
+
56
+ def _is_test_file(rel_path: str) -> bool:
57
+ norm = rel_path.replace("\\", "/").lower()
58
+ base = os.path.basename(norm)
59
+ parts = norm.split("/")
60
+ if any(p in ("test", "tests", "__tests__", "spec", "specs") for p in parts[:-1]):
61
+ return True
62
+ return (
63
+ base.startswith("test_")
64
+ or base.endswith(("_test.py", "_test.go", ".test.ts", ".test.tsx", ".test.js", ".test.jsx", ".spec.ts", ".spec.tsx", ".spec.js"))
65
+ )
27
66
 
28
67
  class CodeSymbol:
29
68
  """Represents a structural code entity (file, class, or function)."""
@@ -57,21 +96,124 @@ class CodeSymbol:
57
96
  "signature": self.signature
58
97
  }
59
98
 
99
+ @classmethod
100
+ def from_dict(cls, data: Dict[str, Any]) -> "CodeSymbol":
101
+ return cls(
102
+ name=data.get("name", ""),
103
+ kind=data.get("kind", "function"),
104
+ file_path=data.get("file_path", ""),
105
+ line_start=int(data.get("line_start", 0)),
106
+ line_end=int(data.get("line_end", 0)),
107
+ signature=data.get("signature", ""),
108
+ )
109
+
110
+
60
111
  class CodeGraph:
61
112
  """
62
113
  Deterministic In-Memory Knowledge Graph of a software repository.
63
- Nodes: File and Symbol identifiers.
64
- Edges: Directed dependencies (CALLS, IMPORTS, CONTAINS).
114
+ Nodes: File (`file:...`), Module (`mod:...`), Symbol (`rel_path::qual_name`), Call (`call:...`).
115
+ Edges: Directed dependencies (`CALLS`, `IMPORTS`, `CONTAINS`, resolved `file -> file`).
65
116
  """
66
117
 
67
- def __init__(self, root_dir: str = "."):
118
+ def __init__(self, root_dir: str = ".", use_disk_cache: bool = False):
68
119
  self.root_dir = os.path.abspath(root_dir)
120
+ self.use_disk_cache = use_disk_cache
69
121
  self.symbols: Dict[str, CodeSymbol] = {}
70
- self.file_symbols: Dict[str, List[str]] = {} # file_rel_path -> [symbol_keys]
71
- self.edges: Dict[str, Set[str]] = {} # caller/importer -> set(callees/imported)
72
- self.rev_edges: Dict[str, Set[str]] = {} # callee/imported -> set(callers/importers)
73
- self.file_mtimes: Dict[str, float] = {} # file_rel_path -> mtime
122
+ self.file_symbols: Dict[str, List[str]] = {} # file_rel_path -> [symbol_keys]
123
+ self.edges: Dict[str, Set[str]] = {} # caller/importer -> set(callees/imported)
124
+ self.rev_edges: Dict[str, Set[str]] = {} # callee/imported -> set(callers/importers)
125
+ self.file_mtimes: Dict[str, float] = {} # file_rel_path -> mtime
126
+ self.file_stats: Dict[str, Tuple[float, int]] = {} # file_rel_path -> (mtime, size)
127
+ self.file_imports: Dict[str, Set[str]] = {} # file_rel_path -> raw imported modules
74
128
  self.last_scanned: float = 0.0
129
+ self.backend: str = self._detect_backend()
130
+
131
+ if self.use_disk_cache and os.environ.get("TOKENSAFE_GRAPH_DISK_CACHE", "1") != "0":
132
+ self._load_disk_cache()
133
+
134
+ @staticmethod
135
+ def _detect_backend() -> str:
136
+ try:
137
+ from src.treesitter_backend import TreeSitterBackend
138
+ if TreeSitterBackend.is_available():
139
+ return "treesitter"
140
+ except Exception:
141
+ pass
142
+ return "stdlib"
143
+
144
+ def _cache_path(self) -> str:
145
+ cache_dir = os.path.join(resolve_data_dir(), "graph_cache")
146
+ key = hashlib.md5(self.root_dir.encode("utf-8")).hexdigest()[:12]
147
+ return os.path.join(cache_dir, f"{key}.json")
148
+
149
+ def _load_disk_cache(self) -> bool:
150
+ path = self._cache_path()
151
+ if not os.path.exists(path):
152
+ return False
153
+ try:
154
+ with open(path, "r", encoding="utf-8") as f:
155
+ data = json.load(f)
156
+ if (
157
+ data.get("version") != _CACHE_SCHEMA_VERSION
158
+ or data.get("root_dir") != self.root_dir
159
+ or data.get("backend") != self.backend
160
+ ):
161
+ return False
162
+
163
+ self.symbols = {k: CodeSymbol.from_dict(v) for k, v in data.get("symbols", {}).items()}
164
+ self.file_symbols = {k: list(v) for k, v in data.get("file_symbols", {}).items()}
165
+ self.edges = {k: set(v) for k, v in data.get("edges", {}).items()}
166
+ self.rev_edges = {k: set(v) for k, v in data.get("rev_edges", {}).items()}
167
+ self.file_stats = {
168
+ k: (float(v[0]), int(v[1]))
169
+ for k, v in data.get("file_stats", {}).items()
170
+ if isinstance(v, (list, tuple)) and len(v) == 2
171
+ }
172
+ self.file_mtimes = {k: v[0] for k, v in self.file_stats.items()}
173
+ self.file_imports = {k: set(v) for k, v in data.get("file_imports", {}).items()}
174
+ self.last_scanned = float(data.get("last_scanned", 0.0))
175
+ return True
176
+ except Exception:
177
+ self.symbols.clear()
178
+ self.file_symbols.clear()
179
+ self.edges.clear()
180
+ self.rev_edges.clear()
181
+ self.file_stats.clear()
182
+ self.file_mtimes.clear()
183
+ self.file_imports.clear()
184
+ return False
185
+
186
+ def _save_disk_cache(self) -> None:
187
+ if not self.use_disk_cache or os.environ.get("TOKENSAFE_GRAPH_DISK_CACHE", "1") == "0":
188
+ return
189
+ path = self._cache_path()
190
+ cache_dir = os.path.dirname(path)
191
+ try:
192
+ os.makedirs(cache_dir, exist_ok=True)
193
+ payload = {
194
+ "version": _CACHE_SCHEMA_VERSION,
195
+ "root_dir": self.root_dir,
196
+ "backend": self.backend,
197
+ "last_scanned": self.last_scanned,
198
+ "file_stats": {k: [v[0], v[1]] for k, v in self.file_stats.items()},
199
+ "file_symbols": self.file_symbols,
200
+ "file_imports": {k: sorted(v) for k, v in self.file_imports.items()},
201
+ "symbols": {k: v.to_dict() for k, v in self.symbols.items()},
202
+ "edges": {k: sorted(v) for k, v in self.edges.items()},
203
+ "rev_edges": {k: sorted(v) for k, v in self.rev_edges.items()},
204
+ }
205
+ fd, tmp_path = tempfile.mkstemp(prefix="graph_", suffix=".tmp", dir=cache_dir)
206
+ try:
207
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
208
+ json.dump(payload, f)
209
+ os.replace(tmp_path, path)
210
+ except Exception:
211
+ try:
212
+ os.unlink(tmp_path)
213
+ except OSError:
214
+ pass
215
+ except OSError:
216
+ pass
75
217
 
76
218
  def add_edge(self, source: str, target: str):
77
219
  if not source or not target or source == target:
@@ -84,15 +226,26 @@ class CodeGraph:
84
226
  self.rev_edges[target] = set()
85
227
  self.rev_edges[target].add(source)
86
228
 
229
+ def _remove_edge(self, source: str, target: str):
230
+ if source in self.edges:
231
+ self.edges[source].discard(target)
232
+ if target in self.rev_edges:
233
+ self.rev_edges[target].discard(source)
234
+
87
235
  def scan(self, force: bool = False) -> int:
88
236
  """
89
237
  Fast incremental scan of the workspace.
90
- Parses modified files only; returns number of files re-indexed.
238
+ Parses modified files only (checked via `(mtime, size)`); returns number of files re-indexed.
91
239
  """
92
240
  system_roots = {"/", "/Users", "/home", "/root", os.path.expanduser("~")}
93
241
  if self.root_dir in system_roots:
94
242
  return 0
95
243
 
244
+ current_backend = self._detect_backend()
245
+ if current_backend != self.backend:
246
+ self.backend = current_backend
247
+ force = True
248
+
96
249
  reindexed = 0
97
250
  current_files = set()
98
251
 
@@ -106,27 +259,47 @@ class CodeGraph:
106
259
  current_files.add(rel_path)
107
260
 
108
261
  try:
109
- mtime = os.path.getmtime(full_path)
262
+ st = os.stat(full_path)
263
+ if not stat.S_ISREG(st.st_mode) or st.st_size > 2 * 1024 * 1024:
264
+ continue
265
+ sig = (st.st_mtime, st.st_size)
110
266
  except OSError:
111
267
  continue
112
268
 
113
- if force or rel_path not in self.file_mtimes or self.file_mtimes[rel_path] < mtime:
269
+ prev_sig = self.file_stats.get(rel_path)
270
+ prev_mtime = self.file_mtimes.get(rel_path)
271
+ changed = (
272
+ force
273
+ or prev_sig is None
274
+ or prev_sig != sig
275
+ or prev_mtime is None
276
+ or prev_mtime < st.st_mtime
277
+ )
278
+ if changed:
114
279
  self._index_file(full_path, rel_path)
115
- self.file_mtimes[rel_path] = mtime
280
+ self.file_stats[rel_path] = sig
281
+ self.file_mtimes[rel_path] = st.st_mtime
116
282
  reindexed += 1
117
283
 
118
284
  # Purge removed files
119
- deleted = set(self.file_mtimes.keys()) - current_files
285
+ deleted = (set(self.file_stats.keys()) | set(self.file_mtimes.keys())) - current_files
120
286
  for del_path in deleted:
121
287
  self._purge_file(del_path)
288
+ self.file_stats.pop(del_path, None)
122
289
  self.file_mtimes.pop(del_path, None)
123
290
 
291
+ if reindexed > 0 or deleted or force:
292
+ self._resolve_local_imports()
293
+
124
294
  self.last_scanned = time.time()
295
+ if reindexed > 0 or deleted:
296
+ self._save_disk_cache()
125
297
  return reindexed
126
298
 
127
299
  def _purge_file(self, rel_path: str):
128
- """Removes symbols and edges belonging to a file."""
300
+ """Removes symbols, imports, and edges belonging to a file."""
129
301
  sym_keys = self.file_symbols.pop(rel_path, [])
302
+ self.file_imports.pop(rel_path, None)
130
303
  for k in sym_keys:
131
304
  self.symbols.pop(k, None)
132
305
  targets = self.edges.pop(k, set())
@@ -140,11 +313,15 @@ class CodeGraph:
140
313
 
141
314
  # File-level node
142
315
  file_node = f"file:{rel_path}"
143
- self.edges.pop(file_node, None)
144
- self.rev_edges.pop(file_node, None)
316
+ for t in self.edges.pop(file_node, set()):
317
+ if t in self.rev_edges:
318
+ self.rev_edges[t].discard(file_node)
319
+ for s in self.rev_edges.pop(file_node, set()):
320
+ if s in self.edges:
321
+ self.edges[s].discard(file_node)
145
322
 
146
323
  def _index_file(self, full_path: str, rel_path: str):
147
- """Indexes a single code file using standard AST or regex tokenizers."""
324
+ """Indexes a single code file using Tree-sitter (if available) or stdlib parsers."""
148
325
  self._purge_file(rel_path)
149
326
  try:
150
327
  st = os.stat(full_path)
@@ -157,15 +334,58 @@ class CodeGraph:
157
334
 
158
335
  file_node = f"file:{rel_path}"
159
336
  self.file_symbols[rel_path] = []
337
+ self.file_imports[rel_path] = set()
160
338
 
161
339
  _, ext = os.path.splitext(full_path)
162
340
  ext = ext.lower()
163
341
 
342
+ if self._try_index_treesitter(content, rel_path, file_node, ext):
343
+ return
344
+
164
345
  if ext == ".py":
165
346
  self._parse_python(content, rel_path, file_node)
166
- elif ext in (".ts", ".js", ".tsx", ".jsx", ".go"):
347
+ elif ext in SUPPORTED_EXTS:
167
348
  self._parse_braces(content, rel_path, file_node, ext)
168
349
 
350
+ def _register_symbol(self, rel_path: str, file_node: str, symbol: CodeSymbol, sym_key: str):
351
+ self.symbols[sym_key] = symbol
352
+ if sym_key not in self.file_symbols[rel_path]:
353
+ self.file_symbols[rel_path].append(sym_key)
354
+ self.add_edge(file_node, sym_key)
355
+
356
+ def _try_index_treesitter(self, code: str, rel_path: str, file_node: str, ext: str) -> bool:
357
+ if self.backend != "treesitter":
358
+ return False
359
+ try:
360
+ from src.treesitter_backend import TreeSitterBackend
361
+ data = TreeSitterBackend.extract_graph_data(code, ext, rel_path)
362
+ except Exception:
363
+ return False
364
+ if data is None:
365
+ return False
366
+
367
+ for mod in data.get("imports", []):
368
+ self.file_imports[rel_path].add(mod)
369
+ self.add_edge(file_node, f"mod:{mod}")
370
+ for sym in data.get("imported_symbols", []):
371
+ self.add_edge(file_node, f"sym:{sym}")
372
+
373
+ for item in data.get("symbols", []):
374
+ symbol = CodeSymbol(
375
+ name=item["name"],
376
+ kind=item["kind"],
377
+ file_path=rel_path,
378
+ line_start=item["line_start"],
379
+ line_end=item["line_end"],
380
+ signature=item["signature"],
381
+ )
382
+ self._register_symbol(rel_path, file_node, symbol, item["sym_key"])
383
+
384
+ for caller_key, callee_name in data.get("calls", []):
385
+ self.add_edge(caller_key, f"call:{callee_name}")
386
+
387
+ return True
388
+
169
389
  def _parse_python(self, code: str, rel_path: str, file_node: str):
170
390
  try:
171
391
  tree = ast.parse(code)
@@ -174,154 +394,433 @@ class CodeGraph:
174
394
 
175
395
  lines = code.splitlines()
176
396
 
177
- for node in ast.walk(tree):
178
- if isinstance(node, (ast.Import, ast.ImportFrom)):
179
- # Record imports
180
- if isinstance(node, ast.Import):
181
- for alias in node.names:
397
+ def walk_py(node: ast.AST, class_name: Optional[str] = None, fn_key: Optional[str] = None):
398
+ for child in ast.iter_child_nodes(node):
399
+ if isinstance(child, ast.Import):
400
+ for alias in child.names:
401
+ self.file_imports[rel_path].add(alias.name)
182
402
  self.add_edge(file_node, f"mod:{alias.name}")
183
- elif isinstance(node, ast.ImportFrom) and node.module:
184
- self.add_edge(file_node, f"mod:{node.module}")
185
- for alias in node.names:
186
- self.add_edge(file_node, f"sym:{alias.name}")
187
-
188
- elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
189
- kind = "class" if isinstance(node, ast.ClassDef) else "function"
190
- start = getattr(node, "lineno", 1)
191
- end = getattr(node, "end_lineno", start)
192
- sym_key = f"{rel_path}::{node.name}"
193
- sig = lines[start - 1].strip() if 0 < start <= len(lines) else node.name
403
+ elif isinstance(child, ast.ImportFrom):
404
+ mod_prefix = "." * (child.level or 0)
405
+ mod_name = f"{mod_prefix}{child.module or ''}"
406
+ if mod_name:
407
+ self.file_imports[rel_path].add(mod_name)
408
+ self.add_edge(file_node, f"mod:{mod_name}")
409
+ for alias in child.names:
410
+ if alias.name != "*":
411
+ self.add_edge(file_node, f"sym:{alias.name}")
412
+ elif isinstance(child, ast.ClassDef):
413
+ start = getattr(child, "lineno", 1)
414
+ end = getattr(child, "end_lineno", start)
415
+ qual = f"{class_name}::{child.name}" if class_name else child.name
416
+ sym_key = f"{rel_path}::{qual}"
417
+ sig = lines[start - 1].strip() if 0 < start <= len(lines) else child.name
418
+ symbol = CodeSymbol(
419
+ name=child.name,
420
+ kind="class",
421
+ file_path=rel_path,
422
+ line_start=start,
423
+ line_end=end,
424
+ signature=sig,
425
+ )
426
+ self._register_symbol(rel_path, file_node, symbol, sym_key)
427
+ walk_py(child, class_name=qual, fn_key=None)
428
+ elif isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
429
+ start = getattr(child, "lineno", 1)
430
+ end = getattr(child, "end_lineno", start)
431
+ qual = f"{class_name}::{child.name}" if class_name else child.name
432
+ sym_key = f"{rel_path}::{qual}"
433
+ sig = lines[start - 1].strip() if 0 < start <= len(lines) else child.name
434
+ symbol = CodeSymbol(
435
+ name=child.name,
436
+ kind="function",
437
+ file_path=rel_path,
438
+ line_start=start,
439
+ line_end=end,
440
+ signature=sig,
441
+ )
442
+ self._register_symbol(rel_path, file_node, symbol, sym_key)
443
+ walk_py(child, class_name=class_name, fn_key=sym_key)
444
+ else:
445
+ if isinstance(child, ast.Call) and fn_key:
446
+ callee_name = None
447
+ if isinstance(child.func, ast.Name):
448
+ callee_name = child.func.id
449
+ elif isinstance(child.func, ast.Attribute):
450
+ callee_name = child.func.attr
451
+ if callee_name and callee_name not in _SKIP_CALLS:
452
+ self.add_edge(fn_key, f"call:{callee_name}")
453
+ walk_py(child, class_name=class_name, fn_key=fn_key)
454
+
455
+ walk_py(tree)
456
+
457
+ def _parse_braces(self, code: str, rel_path: str, file_node: str, ext: str):
458
+ from src.skeletonizer import BraceLexer, Skeletonizer
194
459
 
460
+ lines = code.splitlines()
461
+ count_lines = Skeletonizer.blank_template_literals(lines)
462
+ lexer = BraceLexer()
463
+
464
+ # Strip comments only (keep string literals intact for import path extraction)
465
+ no_block_comments = re.sub(r"/\*.*?\*/", "", code, flags=re.DOTALL)
466
+ cleaned_text = re.sub(r"//.*$", "", no_block_comments, flags=re.MULTILINE)
467
+ if ext in (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"):
468
+ imp_re = re.compile(
469
+ r"""(?:(?:import|export)\s+(?:.*?\s+from\s+)?['"]([^'"]+)['"]|require\(\s*['"]([^'"]+)['"]\s*\))"""
470
+ )
471
+ for m in imp_re.finditer(cleaned_text):
472
+ mod = m.group(1) or m.group(2)
473
+ if mod:
474
+ self.file_imports[rel_path].add(mod)
475
+ self.add_edge(file_node, f"mod:{mod}")
476
+ elif ext == ".go":
477
+ for m in re.finditer(r'^\s*import\s+(?:[A-Za-z_.]+\s+)?"([^"]+)"', cleaned_text, re.MULTILINE):
478
+ self.file_imports[rel_path].add(m.group(1))
479
+ self.add_edge(file_node, f"mod:{m.group(1)}")
480
+ for blk in re.finditer(r'import\s*\((.*?)\)', cleaned_text, re.DOTALL):
481
+ for m in re.finditer(r'"([^"]+)"', blk.group(1)):
482
+ self.file_imports[rel_path].add(m.group(1))
483
+ self.add_edge(file_node, f"mod:{m.group(1)}")
484
+ elif ext in (".c", ".h", ".cpp", ".cc", ".cxx", ".hpp"):
485
+ for m in re.finditer(r'^\s*#include\s+[<"]([^>"]+)[>"]', cleaned_text, re.MULTILINE):
486
+ self.file_imports[rel_path].add(m.group(1))
487
+ self.add_edge(file_node, f"mod:{m.group(1)}")
488
+ else:
489
+ for m in re.finditer(r'^\s*(?:pub\s+)?(?:use|import|using)\s+([^;\n]+)', cleaned_text, re.MULTILINE):
490
+ mod = m.group(1).strip().rstrip(";")
491
+ if mod:
492
+ self.file_imports[rel_path].add(mod)
493
+ self.add_edge(file_node, f"mod:{mod}")
494
+
495
+ container_re = re.compile(
496
+ r'^(?:export\s+(?:default\s+)?)?(?:pub(?:\([^)]*\))?\s+|public\s+|private\s+|protected\s+|internal\s+|abstract\s+|final\s+|sealed\s+|open\s+|data\s+)*'
497
+ r'(?:class|interface|struct|impl(?:\s+[A-Za-z0-9_<>,\s]+?\s+for)?|trait|enum|record|protocol|extension|namespace)\s+([A-Za-z0-9_]+)'
498
+ )
499
+ go_struct_re = re.compile(r'^type\s+([A-Za-z0-9_]+)\s+(?:struct|interface)\b')
500
+ ts_method_re = re.compile(
501
+ r'^(?:(?:public|private|protected|static|readonly|async|override|get|set)\s+)*([A-Za-z_$][A-Za-z0-9_$]*)\s*(?:<[^>]+>)?\s*\([^)]*\)\s*(?::\s*[^{;]+)?\{'
502
+ )
503
+ call_re = re.compile(r'\b([a-zA-Z_$][a-zA-Z0-9_$]{1,})\s*\(')
504
+
505
+ depth = 0
506
+ sym_stack: List[Tuple[str, int, str]] = []
507
+ pending_header: Optional[Tuple[str, str, int, str]] = None
508
+
509
+ for idx, (raw_line, count_src) in enumerate(zip(lines, count_lines), 1):
510
+ clean = lexer.clean_line(count_src).strip()
511
+ open_b, close_b = lexer.count_braces(count_src)
512
+
513
+ matched_name: Optional[str] = None
514
+ matched_kind: Optional[str] = None
515
+ matched_sig = raw_line.strip()
516
+ matched_start = idx
517
+
518
+ if clean:
519
+ cm = container_re.match(clean) or (go_struct_re.match(clean) if ext == ".go" else None)
520
+ if cm:
521
+ matched_name = cm.group(1)
522
+ matched_kind = "class"
523
+ else:
524
+ fn_info = Skeletonizer._extract_fn(clean)
525
+ if fn_info and fn_info[0] != "anonymous":
526
+ matched_name, raw_kind = fn_info
527
+ matched_kind = "function"
528
+ if raw_kind in ("arrow_multiline", "method_multiline", "fn_decl", "go_func", "rust_fn") and "{" not in clean:
529
+ if not clean.endswith(";"):
530
+ pending_header = (matched_name, matched_kind, idx, matched_sig)
531
+ matched_name = None
532
+ elif ext in (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs") and any(k == "class" for _, _, k in sym_stack):
533
+ mm = ts_method_re.match(clean)
534
+ if mm and mm.group(1) not in _SKIP_CALLS:
535
+ matched_name = mm.group(1)
536
+ matched_kind = "function"
537
+
538
+ if pending_header and not matched_name:
539
+ if "{" in clean:
540
+ matched_name, matched_kind, matched_start, matched_sig = pending_header
541
+ pending_header = None
542
+ elif ";" in clean:
543
+ pending_header = None
544
+
545
+ if matched_name and matched_kind:
546
+ class_ctx = [sk.split("::", 1)[-1] for sk, _, k in sym_stack if k == "class"]
547
+ qual = f"{class_ctx[-1]}::{matched_name}" if (class_ctx and matched_kind == "function") else matched_name
548
+ sym_key = f"{rel_path}::{qual}"
195
549
  symbol = CodeSymbol(
196
- name=node.name,
197
- kind=kind,
550
+ name=matched_name,
551
+ kind=matched_kind,
198
552
  file_path=rel_path,
199
- line_start=start,
200
- line_end=end,
201
- signature=sig
553
+ line_start=matched_start,
554
+ line_end=idx,
555
+ signature=matched_sig,
202
556
  )
203
- self.symbols[sym_key] = symbol
204
- self.file_symbols[rel_path].append(sym_key)
205
- self.add_edge(file_node, sym_key)
206
-
207
- # Scan function calls inside body
208
- for sub in ast.walk(node):
209
- if isinstance(sub, ast.Call):
210
- callee_name = None
211
- if isinstance(sub.func, ast.Name):
212
- callee_name = sub.func.id
213
- elif isinstance(sub.func, ast.Attribute):
214
- callee_name = sub.func.attr
215
- if callee_name:
216
- self.add_edge(sym_key, f"call:{callee_name}")
557
+ self._register_symbol(rel_path, file_node, symbol, sym_key)
558
+ if open_b > 0:
559
+ sym_stack.append((sym_key, depth + 1, matched_kind))
217
560
 
218
- def _parse_braces(self, code: str, rel_path: str, file_node: str, ext: str):
219
- lines = code.splitlines()
561
+ active_fn = next((sk for sk, _, k in reversed(sym_stack) if k == "function"), None)
562
+ if active_fn and clean:
563
+ for cm in call_re.finditer(clean):
564
+ callee = cm.group(1)
565
+ if callee != matched_name and callee not in _SKIP_CALLS:
566
+ self.add_edge(active_fn, f"call:{callee}")
567
+
568
+ depth += open_b - close_b
569
+ while sym_stack and depth < sym_stack[-1][1]:
570
+ finished_key, _, _ = sym_stack.pop()
571
+ if finished_key in self.symbols:
572
+ self.symbols[finished_key].line_end = idx
573
+
574
+ def _resolve_local_imports(self) -> None:
575
+ """Resolves raw `file_imports` strings to real `file:<rel_path>` edges."""
576
+ indexed_files = set(self.file_symbols.keys())
577
+ if not indexed_files:
578
+ return
220
579
 
221
- # Imports
222
- import_pattern = re.compile(r"""(?:import\s+.*?\s+from\s+['"](.*?)['"]|require\(['"](.*?)['"]\))""")
223
- for match in import_pattern.finditer(code):
224
- target_mod = match.group(1) or match.group(2)
225
- if target_mod:
226
- self.add_edge(file_node, f"mod:{target_mod}")
580
+ for rel_path in indexed_files:
581
+ src_node = f"file:{rel_path}"
582
+ existing = [t for t in self.edges.get(src_node, set()) if t.startswith("file:")]
583
+ for t in existing:
584
+ self._remove_edge(src_node, t)
585
+
586
+ dir_to_files: Dict[str, List[str]] = {}
587
+ for fp in indexed_files:
588
+ d = os.path.dirname(fp)
589
+ dir_to_files.setdefault(d, []).append(fp)
590
+
591
+ for rel_path, mods in self.file_imports.items():
592
+ src_node = f"file:{rel_path}"
593
+ src_dir = os.path.dirname(rel_path)
594
+ ext = os.path.splitext(rel_path)[1].lower()
595
+
596
+ for mod in mods:
597
+ for target_rel in self._resolve_single_import(mod, src_dir, ext, indexed_files, dir_to_files):
598
+ if target_rel != rel_path:
599
+ self.add_edge(src_node, f"file:{target_rel}")
600
+
601
+ @staticmethod
602
+ def _resolve_single_import(
603
+ mod: str,
604
+ src_dir: str,
605
+ ext: str,
606
+ indexed_files: Set[str],
607
+ dir_to_files: Dict[str, List[str]],
608
+ ) -> List[str]:
609
+ if not mod:
610
+ return []
227
611
 
228
- # Functions & Methods
229
- fn_pattern = re.compile(
230
- r"""(?:export\s+(?:default\s+)?)?(?:async\s+)?(?:function\s*\*?\s*([a-zA-Z0-9_$]+)|(?:class|interface|struct|impl|trait)\s+([a-zA-Z0-9_$]+)|func\s+(?:\(.*?\)\s+)?([a-zA-Z0-9_]+)|(?:const|let|var)\s+([a-zA-Z0-9_$]+)(?:\s*:\s*[^=]+)?\s*=\s*(?:async\s*)?(?:React\.(?:memo|forwardRef)\s*\()?(?:useCallback\s*\()?\s*\(?)"""
231
- )
232
- call_pattern = re.compile(r"""(?:<|\b)([a-zA-Z0-9_$]{3,})\s*(?:\(|>|(?:\s+[a-zA-Z0-9_$-]+))""")
233
- current_sym = None
234
-
235
- for idx, line in enumerate(lines, 1):
236
- match = fn_pattern.search(line)
237
- if match:
238
- name = match.group(1) or match.group(2) or match.group(3) or match.group(4)
239
- if name and name not in {"if", "for", "while", "switch", "catch", "return", "import", "export"}:
240
- kind = "class" if any(w in line for w in ("class", "interface", "struct", "impl")) else "function"
241
- sym_key = f"{rel_path}::{name}"
242
- symbol = CodeSymbol(
243
- name=name,
244
- kind=kind,
245
- file_path=rel_path,
246
- line_start=idx,
247
- line_end=idx,
248
- signature=line.strip()
249
- )
250
- self.symbols[sym_key] = symbol
251
- self.file_symbols[rel_path].append(sym_key)
252
- self.add_edge(file_node, sym_key)
253
- current_sym = sym_key
254
- elif current_sym:
255
- for cm in call_pattern.finditer(line):
256
- callee = cm.group(1)
257
- if callee not in {"div", "span", "button", "input", "label", "form", "svg", "path", "true", "false", "null", "undefined"}:
258
- self.add_edge(current_sym, f"call:{callee}")
612
+ if ext == ".py":
613
+ if mod.startswith("."):
614
+ dots = len(mod) - len(mod.lstrip("."))
615
+ rest = mod[dots:].replace(".", "/")
616
+ base_dir = src_dir
617
+ for _ in range(dots - 1):
618
+ base_dir = os.path.dirname(base_dir)
619
+ prefix = os.path.normpath(os.path.join(base_dir, rest)).replace("\\", "/") if rest else base_dir
620
+ else:
621
+ prefix = mod.replace(".", "/")
622
+ prefix = prefix.lstrip("./")
623
+ for cand in (f"{prefix}.py", f"{prefix}/__init__.py"):
624
+ if cand in indexed_files:
625
+ return [cand]
626
+ return []
627
+
628
+ if ext in (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"):
629
+ if not mod.startswith("."):
630
+ return []
631
+ base = os.path.normpath(os.path.join(src_dir, mod)).replace("\\", "/").lstrip("./")
632
+ for cand in (
633
+ base,
634
+ f"{base}.ts", f"{base}.tsx", f"{base}.js", f"{base}.jsx", f"{base}.mjs", f"{base}.cjs",
635
+ f"{base}/index.ts", f"{base}/index.tsx", f"{base}/index.js", f"{base}/index.mjs",
636
+ ):
637
+ if cand in indexed_files:
638
+ return [cand]
639
+ return []
640
+
641
+ if ext == ".go":
642
+ mod_clean = mod.strip("/")
643
+ for d, files in dir_to_files.items():
644
+ if d and (mod_clean == d or mod_clean.endswith(f"/{d}")):
645
+ return [f for f in files if f.endswith(".go")]
646
+ return []
647
+
648
+ if ext in (".c", ".h", ".cpp", ".cc", ".cxx", ".hpp"):
649
+ cand = os.path.normpath(os.path.join(src_dir, mod)).replace("\\", "/").lstrip("./")
650
+ return [cand] if cand in indexed_files else []
651
+
652
+ if ext == ".rs" and mod.startswith(("crate::", "super::", "self::")):
653
+ parts = mod.split("::")[1:]
654
+ if parts:
655
+ rel = "/".join(parts)
656
+ for cand in (f"{rel}.rs", f"{rel}/mod.rs", f"src/{rel}.rs", f"src/{rel}/mod.rs"):
657
+ if cand in indexed_files:
658
+ return [cand]
659
+ return []
660
+
661
+ return []
259
662
 
260
663
  # -------------------------------------------------------------
261
- # 1. God Nodes Analysis (Degree Centrality)
664
+ # 1. God Nodes Analysis (Import & Call Centrality)
262
665
  # -------------------------------------------------------------
263
666
  def get_god_nodes(self, top_n: int = 5) -> List[Dict[str, Any]]:
264
667
  """
265
- Calculates Degree Centrality across files to locate architectural hubs.
266
- God Nodes = files with highest incoming (depended upon) and outgoing connections.
668
+ Calculates architectural hub centrality across files.
669
+ Prioritizes resolved file-to-file imports and import-verified symbol calls,
670
+ and downweights test files when production files are present.
267
671
  """
672
+ has_prod_files = any(not _is_test_file(p) for p in self.file_symbols.keys())
673
+ has_resolved_imports = any(
674
+ t.startswith("file:")
675
+ for src, targets in self.edges.items()
676
+ if src.startswith("file:")
677
+ for t in targets
678
+ )
679
+
268
680
  scores: Dict[str, Dict[str, Any]] = {}
269
681
 
270
682
  for rel_path in self.file_symbols.keys():
271
683
  file_node = f"file:{rel_path}"
272
- # Outgoing: What this file imports or contains
273
684
  out_degree = len(self.edges.get(file_node, set()))
274
- # Incoming: Who imports or calls this file or its symbols
275
- in_degree = len(self.rev_edges.get(file_node, set()))
276
685
 
277
- # Aggregate symbol connections
686
+ importing_files = {
687
+ s[5:] for s in self.rev_edges.get(file_node, set()) if s.startswith("file:")
688
+ }
689
+ in_degree = len(importing_files)
690
+
278
691
  for sym_key in self.file_symbols.get(rel_path, []):
279
- sym_name = sym_key.split("::")[-1]
280
- call_ref = f"call:{sym_name}"
281
- in_degree += len(self.rev_edges.get(call_ref, set()))
692
+ sym = self.symbols.get(sym_key)
693
+ sym_name = sym.name if sym else sym_key.split("::")[-1].split(".")[-1]
694
+ for caller_key in self.rev_edges.get(f"call:{sym_name}", set()):
695
+ caller_file = caller_key.split("::", 1)[0]
696
+ if caller_file == rel_path:
697
+ continue
698
+ if not has_resolved_imports or caller_file in importing_files:
699
+ in_degree += 1
282
700
 
283
- total_centrality = in_degree * 2 + out_degree # Incoming imports weighted heavier
701
+ raw_centrality = in_degree * 2 + out_degree
702
+ rank_score = raw_centrality * 0.2 if (has_prod_files and _is_test_file(rel_path)) else float(raw_centrality)
284
703
  scores[rel_path] = {
285
704
  "file": rel_path,
286
- "centrality": total_centrality,
705
+ "centrality": raw_centrality,
287
706
  "dependents": in_degree,
288
707
  "dependencies": out_degree,
289
- "symbols_count": len(self.file_symbols.get(rel_path, []))
708
+ "symbols_count": len(self.file_symbols.get(rel_path, [])),
709
+ "_rank": rank_score,
290
710
  }
291
711
 
292
- ranked = sorted(scores.values(), key=lambda x: x["centrality"], reverse=True)
293
- return ranked[:top_n]
712
+ ranked = sorted(scores.values(), key=lambda x: (x["_rank"], x["centrality"]), reverse=True)
713
+ result = []
714
+ for item in ranked[:top_n]:
715
+ item.pop("_rank", None)
716
+ result.append(item)
717
+ return result
294
718
 
295
719
  # -------------------------------------------------------------
296
720
  # 2. Neighborhood & Graph-Guided Skeletonization
297
721
  # -------------------------------------------------------------
298
- def get_neighborhood(self, target_symbol: str) -> Dict[str, Set[str]]:
722
+ def _match_target_keys(self, target_symbol: str, target_file: Optional[str] = None) -> List[str]:
723
+ if target_symbol in self.symbols:
724
+ return [target_symbol]
725
+
726
+ norm_target = target_symbol.replace(".", "::")
727
+ candidates = []
728
+ for k, sym in self.symbols.items():
729
+ if sym.name == target_symbol or k.endswith(f"::{target_symbol}") or k.endswith(f"::{norm_target}"):
730
+ candidates.append(k)
731
+
732
+ if target_file:
733
+ in_file = [k for k in candidates if k.startswith(f"{target_file}::")]
734
+ if in_file:
735
+ return in_file
736
+ return candidates
737
+
738
+ def _resolve_callee_keys(self, callee_name: str, caller_file: str) -> List[str]:
739
+ imported_files = {
740
+ t[5:] for t in self.edges.get(f"file:{caller_file}", set()) if t.startswith("file:")
741
+ }
742
+ same_file = []
743
+ imported = []
744
+ others = []
745
+
746
+ for k, sym in self.symbols.items():
747
+ if sym.name == callee_name or k.endswith(f"::{callee_name}"):
748
+ if sym.file_path == caller_file:
749
+ same_file.append(k)
750
+ elif sym.file_path in imported_files:
751
+ imported.append(k)
752
+ else:
753
+ others.append(k)
754
+
755
+ if same_file or imported:
756
+ return same_file + imported
757
+ return others if len(others) <= 3 else []
758
+
759
+ def get_neighborhood(
760
+ self,
761
+ target_symbol: str,
762
+ target_file: Optional[str] = None,
763
+ include_two_hop: bool = False,
764
+ ) -> Dict[str, Set[str]]:
299
765
  """
300
- Returns 0-hop (target), 1-hop (callees/callers), and 2-hop related symbols.
766
+ Returns 0-hop (`target`), 1-hop (`one_hop`), and optionally 2-hop (`two_hop`) related symbols.
767
+ Prioritizes same-file and imported-file edges to eliminate bare-name collisions.
301
768
  """
302
- target_keys = [k for k in self.symbols if k.endswith(f"::{target_symbol}") or k == target_symbol]
303
- one_hop = set()
769
+ target_keys = self._match_target_keys(target_symbol, target_file=target_file)
770
+ one_hop: Set[str] = set()
771
+
772
+ def _expand_one(tk: str) -> Set[str]:
773
+ found: Set[str] = set()
774
+ sym = self.symbols.get(tk)
775
+ caller_file = sym.file_path if sym else tk.split("::", 1)[0]
776
+ short_name = sym.name if sym else tk.split("::")[-1].split(".")[-1]
304
777
 
305
- for tk in target_keys:
306
- # Direct callees
307
778
  for callee in self.edges.get(tk, set()):
308
779
  if callee.startswith("call:"):
309
- name = callee[5:]
310
- for k in self.symbols:
311
- if k.endswith(f"::{name}"):
312
- one_hop.add(k)
780
+ found.update(self._resolve_callee_keys(callee[5:], caller_file))
313
781
  elif callee in self.symbols:
314
- one_hop.add(callee)
315
- # Direct callers
316
- for caller in self.rev_edges.get(f"call:{target_symbol}", set()):
317
- if caller in self.symbols:
318
- one_hop.add(caller)
782
+ found.add(callee)
319
783
 
320
- return {
784
+ importing_files = {
785
+ s[5:] for s in self.rev_edges.get(f"file:{caller_file}", set()) if s.startswith("file:")
786
+ }
787
+ scoped_callers = []
788
+ fallback_callers = []
789
+ for caller in self.rev_edges.get(f"call:{short_name}", set()):
790
+ if caller not in self.symbols or caller == tk:
791
+ continue
792
+ cf = self.symbols[caller].file_path
793
+ if cf == caller_file or cf in importing_files:
794
+ scoped_callers.append(caller)
795
+ else:
796
+ fallback_callers.append(caller)
797
+ if scoped_callers:
798
+ found.update(scoped_callers)
799
+ elif len(fallback_callers) <= 3:
800
+ found.update(fallback_callers)
801
+
802
+ found.discard(tk)
803
+ return found
804
+
805
+ for tk in target_keys:
806
+ one_hop.update(_expand_one(tk))
807
+ one_hop -= set(target_keys)
808
+
809
+ result: Dict[str, Set[str]] = {
321
810
  "target": set(target_keys),
322
- "one_hop": one_hop
811
+ "one_hop": one_hop,
323
812
  }
324
813
 
814
+ if include_two_hop:
815
+ two_hop: Set[str] = set()
816
+ for ok in one_hop:
817
+ two_hop.update(_expand_one(ok))
818
+ two_hop -= set(target_keys)
819
+ two_hop -= one_hop
820
+ result["two_hop"] = two_hop
821
+
822
+ return result
823
+
325
824
  def graph_guided_skeletonize(
326
825
  self,
327
826
  full_path: str,
@@ -353,18 +852,27 @@ class CodeGraph:
353
852
  if not target_symbol:
354
853
  return Skeletonizer.skeletonize_code(code, ext, collapse_imports=collapse_imports)
355
854
 
356
- keep_full_names = {target_symbol}
855
+ try:
856
+ target_rel = os.path.relpath(os.path.abspath(full_path), self.root_dir).replace("\\", "/")
857
+ except ValueError:
858
+ target_rel = ""
859
+
860
+ keep_full_names: Set[str] = {target_symbol}
861
+ neighborhood = self.get_neighborhood(target_symbol, target_file=target_rel or None)
862
+ for tk in neighborhood.get("target", set()):
863
+ qual = tk.split("::", 1)[-1]
864
+ keep_full_names.add(qual)
865
+ keep_full_names.add(qual.replace("::", "."))
866
+ sym = self.symbols.get(tk)
867
+ if sym:
868
+ keep_full_names.add(sym.name)
869
+
357
870
  external_dep_lines: List[str] = []
358
871
  mode = (dep_mode or "full").strip().lower()
359
872
 
360
873
  if include_deps:
361
- neighborhood = self.get_neighborhood(target_symbol)
362
874
  one_hop = sorted(neighborhood.get("one_hop", set()))
363
875
  if mode == "signature":
364
- try:
365
- target_rel = os.path.relpath(os.path.abspath(full_path), self.root_dir).replace("\\", "/")
366
- except ValueError:
367
- target_rel = ""
368
876
  comment_prefix = "#" if ext == ".py" else "//"
369
877
  for k in one_hop:
370
878
  sym = self.symbols.get(k)
@@ -374,7 +882,12 @@ class CodeGraph:
374
882
  )
375
883
  else:
376
884
  for k in one_hop:
377
- keep_full_names.add(k.split("::")[-1])
885
+ qual = k.split("::", 1)[-1]
886
+ keep_full_names.add(qual)
887
+ keep_full_names.add(qual.replace("::", "."))
888
+ sym = self.symbols.get(k)
889
+ if sym:
890
+ keep_full_names.add(sym.name)
378
891
 
379
892
  skel = Skeletonizer.skeletonize_code(
380
893
  code,
@@ -429,10 +942,10 @@ class CodeGraph:
429
942
 
430
943
  if output_path is None:
431
944
  out_dir = os.path.join(self.root_dir, "tokensafe-out")
432
- os.makedirs(out_dir, exist_ok=True)
433
945
  output_path = os.path.join(out_dir, "API_SURFACE.md")
434
946
 
435
947
  try:
948
+ os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
436
949
  with open(output_path, "w", encoding="utf-8") as f:
437
950
  f.write(output_content)
438
951
  except OSError:
@@ -479,7 +992,7 @@ class GraphEngine:
479
992
  # smart_read_file(symbol=...) call. 60s keeps graphs fresh without the churn.
480
993
  rescan_ttl = float(os.environ.get("TOKENSAFE_GRAPH_TTL", "60.0"))
481
994
  if root_abs not in cls._instances:
482
- graph = CodeGraph(root_abs)
995
+ graph = CodeGraph(root_abs, use_disk_cache=True)
483
996
  graph.scan()
484
997
  cls._instances[root_abs] = graph
485
998
  else: