tokensafe 4.16.3 → 5.0.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.
Files changed (151) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.codex-plugin/plugin.json +1 -1
  4. package/README.md +1 -1
  5. package/bin/agy-tokens +1 -1
  6. package/bin/tokensafe +1 -1
  7. package/bin/tokensafe-acp.js +1 -1
  8. package/bin/tokensafe-mcp +1 -1
  9. package/bin/tokensafe.js +1 -1
  10. package/hooks/claude_code_hook.py +49 -45
  11. package/hooks/cursor_hook.py +8 -8
  12. package/hooks/kimi_hook.py +23 -23
  13. package/hooks/post_tool_use.py +6 -6
  14. package/hooks/pre_invocation.py +21 -17
  15. package/hooks/pre_tool_use.py +27 -27
  16. package/hooks/session_start.py +17 -17
  17. package/hooks/stop_hook.py +3 -3
  18. package/hooks/zcode_hook.py +2 -2
  19. package/kimi.plugin.json +2 -2
  20. package/mcp_config.json +1 -1
  21. package/package.json +5 -4
  22. package/plugin.json +1 -1
  23. package/server.json +3 -3
  24. package/src/__init__.py +9 -5
  25. package/src/cli.py +11 -2487
  26. package/src/mcp_server.py +11 -5437
  27. package/src/proxy.py +11 -1834
  28. package/tokensafe/__init__.py +6 -0
  29. package/{src → tokensafe}/acp/__init__.py +2 -2
  30. package/{src → tokensafe}/acp/server.py +5 -5
  31. package/{src → tokensafe}/adapter_core.py +21 -18
  32. package/{src → tokensafe}/agent/__init__.py +1 -1
  33. package/{src → tokensafe}/agent/context.py +4 -4
  34. package/{src → tokensafe}/agent/loop.py +4 -4
  35. package/{src → tokensafe}/agent/providers.py +2 -2
  36. package/{src → tokensafe}/agent/tools.py +2 -2
  37. package/{src → tokensafe}/agent_firewall.py +51 -10
  38. package/{src → tokensafe}/angular_cli.py +4 -4
  39. package/{src → tokensafe}/auto_inject.py +37 -5
  40. package/{src → tokensafe}/batch_editor.py +185 -28
  41. package/tokensafe/batch_search.py +1191 -0
  42. package/{src → tokensafe}/bench/go_target.py +1 -1
  43. package/{src → tokensafe}/bench/mechanics.py +1 -1
  44. package/{src → tokensafe}/bench/react_target.py +1 -1
  45. package/{src → tokensafe}/bench/runner.py +4 -4
  46. package/{src → tokensafe}/benchmark.py +12 -12
  47. package/{src → tokensafe}/benchmark_real.py +18 -18
  48. package/{src → tokensafe}/build_parsers.py +3 -3
  49. package/{src → tokensafe}/bundle_probe.py +1 -1
  50. package/{src → tokensafe}/burn_monitor.py +3 -3
  51. package/{src → tokensafe}/cache_normalizer.py +1 -1
  52. package/tokensafe/cli.py +2490 -0
  53. package/{src → tokensafe}/command_sanitizer.py +94 -26
  54. package/{src → tokensafe}/compaction_recovery.py +5 -5
  55. package/{src → tokensafe}/compactor.py +148 -95
  56. package/{src → tokensafe}/context_index.py +194 -28
  57. package/{src → tokensafe}/cross_stack.py +2 -2
  58. package/{src → tokensafe}/dashboard.py +3 -3
  59. package/{src → tokensafe}/delegation.py +4 -4
  60. package/{src → tokensafe}/dependency_prefetcher.py +1 -1
  61. package/{src → tokensafe}/diff_slicer.py +2 -2
  62. package/{src → tokensafe}/distiller.py +7 -7
  63. package/{src → tokensafe}/distiller_cache.py +3 -3
  64. package/{src → tokensafe}/egress_counter.py +1 -1
  65. package/{src → tokensafe}/environment_auditor.py +7 -7
  66. package/{src → tokensafe}/file_state.py +2 -2
  67. package/{src → tokensafe}/format_invariants.py +1 -1
  68. package/tokensafe/format_parsers/__init__.py +20 -0
  69. package/{src → tokensafe}/format_parsers/compiler_errors.py +2 -2
  70. package/{src → tokensafe}/format_parsers/docker_k8s.py +1 -1
  71. package/{src → tokensafe}/format_parsers/i18n_strings.py +19 -9
  72. package/{src → tokensafe}/format_parsers/json_log.py +1 -1
  73. package/{src → tokensafe}/format_parsers/lockfiles.py +4 -4
  74. package/{src → tokensafe}/format_parsers/tabular.py +1 -1
  75. package/{src → tokensafe}/fts_index.py +20 -11
  76. package/{src → tokensafe}/governor.py +143 -31
  77. package/{src → tokensafe}/graph_engine.py +729 -126
  78. package/{src → tokensafe}/guard.py +80 -25
  79. package/{src → tokensafe}/history_compactor.py +407 -133
  80. package/{src → tokensafe}/i18n_catalog.py +39 -14
  81. package/{src → tokensafe}/image_downscale.py +1 -1
  82. package/{src → tokensafe}/ingress_staging.py +9 -9
  83. package/{src → tokensafe}/installer.py +118 -61
  84. package/{src → tokensafe}/license_manager.py +9 -67
  85. package/{src → tokensafe}/live_relay.py +2 -2
  86. package/{src → tokensafe}/loop_detector.py +2 -2
  87. package/{src → tokensafe}/mcp_config_manager.py +2 -2
  88. package/{src → tokensafe}/mcp_proxy.py +4 -4
  89. package/tokensafe/mcp_server.py +5664 -0
  90. package/{src → tokensafe}/metrics.py +56 -21
  91. package/{src → tokensafe}/mistakes.py +4 -4
  92. package/{src → tokensafe}/oumv_brief.py +21 -3
  93. package/{src → tokensafe}/oumv_gateway.py +146 -49
  94. package/{src → tokensafe}/oumv_policy.py +1 -1
  95. package/{src → tokensafe}/paths.py +1 -1
  96. package/{src → tokensafe}/project_memory.py +4 -4
  97. package/tokensafe/proxy.py +2075 -0
  98. package/{src → tokensafe}/quality_score.py +4 -4
  99. package/{src → tokensafe}/read_baseline.py +1 -1
  100. package/{src → tokensafe}/repo_compute.py +1 -1
  101. package/{src → tokensafe}/result_ledger.py +19 -19
  102. package/{src → tokensafe}/retrofit.py +6 -6
  103. package/{src → tokensafe}/savings.py +3 -3
  104. package/tokensafe/schema_slicer.py +1087 -0
  105. package/{src → tokensafe}/scoped_search.py +144 -6
  106. package/{src → tokensafe}/secret_redactor.py +22 -0
  107. package/{src → tokensafe}/session_brief.py +8 -8
  108. package/{src → tokensafe}/skeletonizer.py +89 -26
  109. package/{src → tokensafe}/slicer.py +3 -2
  110. package/{src → tokensafe}/snapshot.py +1 -1
  111. package/{src → tokensafe}/stash.py +1 -1
  112. package/{src → tokensafe}/statusline.py +1 -1
  113. package/{src → tokensafe}/superseded.py +22 -4
  114. package/{src → tokensafe}/team_cache.py +3 -3
  115. package/{src → tokensafe}/telemetry_sync.py +63 -11
  116. package/{src → tokensafe}/test_parsers.py +3 -3
  117. package/{src → tokensafe}/thinking_fold.py +3 -3
  118. package/{src → tokensafe}/tokenizer.py +37 -1
  119. package/{src → tokensafe}/tool_pruner.py +3 -3
  120. package/{src → tokensafe}/transcript_analyzer.py +1 -1
  121. package/{src → tokensafe}/transcript_recall.py +8 -8
  122. package/{src → tokensafe}/type_slicer.py +3 -3
  123. package/{src → tokensafe}/usage_ledger.py +4 -4
  124. package/{src → tokensafe}/version_checker.py +6 -6
  125. package/{src → tokensafe}/web_reader.py +86 -8
  126. package/{src → tokensafe}/workspace_roots.py +2 -2
  127. package/src/batch_search.py +0 -589
  128. package/src/format_parsers/__init__.py +0 -20
  129. package/src/schema_slicer.py +0 -578
  130. /package/{src → tokensafe}/agent/pricing.py +0 -0
  131. /package/{src → tokensafe}/atomic_io.py +0 -0
  132. /package/{src → tokensafe}/backend_release.py +0 -0
  133. /package/{src → tokensafe}/bench/__init__.py +0 -0
  134. /package/{src → tokensafe}/bench/driver.py +0 -0
  135. /package/{src → tokensafe}/bench/tokensafe_mcp.py +0 -0
  136. /package/{src → tokensafe}/bench_scenarios.json +0 -0
  137. /package/{src → tokensafe}/competitors.py +0 -0
  138. /package/{src → tokensafe}/format_parsers/ansi.py +0 -0
  139. /package/{src → tokensafe}/format_parsers/game_assets.py +0 -0
  140. /package/{src → tokensafe}/globmatch.py +0 -0
  141. /package/{src → tokensafe}/host_capabilities.py +0 -0
  142. /package/{src → tokensafe}/json_repair.py +0 -0
  143. /package/{src → tokensafe}/route_index.py +0 -0
  144. /package/{src → tokensafe}/scaffold.py +0 -0
  145. /package/{src → tokensafe}/session_context.py +0 -0
  146. /package/{src → tokensafe}/ssl_context.py +0 -0
  147. /package/{src → tokensafe}/stdio_io.py +0 -0
  148. /package/{src → tokensafe}/syntax_guard.py +0 -0
  149. /package/{src → tokensafe}/toml_mcp_config.py +0 -0
  150. /package/{src → tokensafe}/treesitter_backend.py +0 -0
  151. /package/{src → tokensafe}/win_paths.py +0 -0
@@ -3,7 +3,7 @@ TokenSafe Graph Engine: Dependency-Aware Graph Analysis & Skeletonization.
3
3
  Builds a zero-LLM deterministic code graph for Python, TypeScript/JavaScript, Go,
4
4
  Rust, Java, C#, C/C++, PHP, Kotlin, Ruby, and Swift.
5
5
 
6
- Uses the optional Tree-sitter backend when available (`src.treesitter_backend`)
6
+ Uses the optional Tree-sitter backend when available (`tokensafe.treesitter_backend`)
7
7
  and falls back seamlessly to the Python standard library `ast` and `BraceLexer`
8
8
  state-machine parsers with zero extra required runtime dependencies.
9
9
 
@@ -15,10 +15,13 @@ Powers:
15
15
  """
16
16
 
17
17
  import ast
18
+ import bisect
19
+ import copy
18
20
  import glob
19
21
  import hashlib
20
22
  import json
21
23
  import os
24
+ import posixpath
22
25
  import re
23
26
  import sqlite3
24
27
  import stat
@@ -26,9 +29,9 @@ import threading
26
29
  import time
27
30
  from typing import Dict, Set, List, Optional, Tuple, Any
28
31
 
29
- from src.paths import resolve_data_dir
30
- from src.context_index import ContextIndex, index_db_path, legacy_graph_db_path
31
- from src.globmatch import GlobPatternError, compile_patterns, matches_any, split_negations
32
+ from tokensafe.paths import resolve_data_dir
33
+ from tokensafe.context_index import ContextIndex, index_db_path, legacy_graph_db_path
34
+ from tokensafe.globmatch import GlobPatternError, compile_patterns, matches_any, split_negations
32
35
 
33
36
  IGNORED_DIRS = {
34
37
  ".git", ".hg", ".svn", "node_modules", "dist", "build", "venv", ".venv",
@@ -39,7 +42,7 @@ IGNORED_DIRS = {
39
42
  }
40
43
 
41
44
  SUPPORTED_EXTS = {
42
- ".py", ".ts", ".js", ".tsx", ".jsx", ".mjs", ".cjs",
45
+ ".py", ".ts", ".js", ".tsx", ".jsx", ".mjs", ".cjs", ".mts", ".cts",
43
46
  ".go", ".rs", ".java", ".cs",
44
47
  ".c", ".cpp", ".cc", ".cxx", ".h", ".hpp",
45
48
  ".php", ".kt", ".kts", ".swift", ".rb",
@@ -56,7 +59,9 @@ _SKIP_CALLS = {
56
59
 
57
60
  # v8: JS/TS extraction learned dynamic `import('./X')`, `React.lazy(() => import(...))`
58
61
  # and literal `import.meta.glob` patterns; v7 caches have neither edge nor glob set.
59
- _CACHE_SCHEMA_VERSION = 8
62
+ # v9: Python `from X import name` submodule candidates in file_imports and
63
+ # decorator-inclusive symbol ranges; v8 rows of unchanged files lack both.
64
+ _CACHE_SCHEMA_VERSION = 9
60
65
 
61
66
  _STATIC_ASSET_EXTS = {
62
67
  ".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico", ".webp",
@@ -127,6 +132,318 @@ def _glob_pattern_to_rel(root_dir: str, src_dir: str, pattern: str) -> str:
127
132
  return os.path.relpath(joined, root_dir).replace("\\", "/")
128
133
 
129
134
 
135
+ def _repo_rel_join(base_rel_dir: str, spec: str) -> Optional[str]:
136
+ """Joins a repo-relative directory and a relative specifier.
137
+
138
+ Returns None when the result climbs above the repository root: `../../x`
139
+ from a shallow file used to be normalised to `x` and linked to an unrelated
140
+ in-repo file.
141
+ """
142
+ joined = posixpath.normpath(posixpath.join(base_rel_dir or ".", spec.replace("\\", "/")))
143
+ if joined == ".." or joined.startswith("../") or joined.startswith("/"):
144
+ return None
145
+ return "" if joined == "." else joined
146
+
147
+
148
+ def _abs_to_repo_rel(root_dir: str, abs_path: str) -> Optional[str]:
149
+ """Repo-relative form of an absolute path, or None when it lies outside the root."""
150
+ rel = os.path.relpath(os.path.normpath(abs_path), root_dir).replace("\\", "/")
151
+ if rel == ".." or rel.startswith("../") or os.path.isabs(rel):
152
+ return None
153
+ return "" if rel == "." else rel
154
+
155
+
156
+ _JS_TS_EXTS = (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts")
157
+ _TS_SOURCE_EXTS = (".ts", ".tsx", ".mts", ".cts")
158
+ # TS ESM imports name the emitted file (`./foo.js`) while the source is `foo.ts`.
159
+ _JS_TO_TS_SOURCE = {
160
+ ".js": (".ts", ".tsx"),
161
+ ".jsx": (".tsx",),
162
+ ".mjs": (".mts",),
163
+ ".cjs": (".cts",),
164
+ }
165
+
166
+
167
+ def _js_ts_candidates(base: str, prefer_ts_source: bool) -> List[str]:
168
+ """Files a JS/TS module specifier (already joined to a repo path) may name."""
169
+ stem, ext = posixpath.splitext(base)
170
+ mapped = [stem + e for e in _JS_TO_TS_SOURCE.get(ext.lower(), ())]
171
+ head = (mapped + [base]) if prefer_ts_source else ([base] + mapped)
172
+ prefix = f"{base}/" if base else ""
173
+ return head + [base + e for e in _JS_TS_EXTS] + [
174
+ f"{prefix}index{e}" for e in (".ts", ".tsx", ".js", ".jsx", ".mjs", ".mts", ".cts")
175
+ ]
176
+
177
+
178
+ _JSONC_COMMENT_RE = re.compile(r'"(?:\\.|[^"\\])*"|//[^\n]*|/\*.*?\*/', re.DOTALL)
179
+ _JSONC_TRAILING_COMMA_RE = re.compile(r'"(?:\\.|[^"\\])*"|,(\s*[}\]])')
180
+
181
+
182
+ def _parse_jsonc(text: str) -> Any:
183
+ """json.loads for tsconfig/jsconfig: tolerates comments and trailing commas."""
184
+ text = text.lstrip("\ufeff")
185
+ no_comments = _JSONC_COMMENT_RE.sub(lambda m: m.group(0) if m.group(0).startswith('"') else "", text)
186
+ cleaned = _JSONC_TRAILING_COMMA_RE.sub(
187
+ lambda m: m.group(0) if m.group(0).startswith('"') else m.group(1), no_comments
188
+ )
189
+ return json.loads(cleaned)
190
+
191
+
192
+ class _TsPathResolver:
193
+ """Resolves bare TS/JS specifiers through `compilerOptions.paths`/`baseUrl`.
194
+
195
+ The nearest `tsconfig.json` (or `jsconfig.json`) above the importing file wins,
196
+ following relative `extends` and, for solution-style configs, `references`.
197
+ With no config at all, the common `@/` -> `src/` alias is assumed when the
198
+ repository has a `src/` directory.
199
+ """
200
+
201
+ _CONFIG_NAMES = ("tsconfig.json", "jsconfig.json")
202
+
203
+ def __init__(self, root_dir: str):
204
+ self.root = os.path.abspath(root_dir)
205
+ self._dir_config: Dict[str, Optional[str]] = {}
206
+ self._options: Dict[str, Dict[str, Any]] = {}
207
+ self._has_src = os.path.isdir(os.path.join(self.root, "src"))
208
+
209
+ def _config_path(self, rel_dir: str) -> Optional[str]:
210
+ if rel_dir in self._dir_config:
211
+ return self._dir_config[rel_dir]
212
+ found: Optional[str] = None
213
+ abs_dir = os.path.join(self.root, rel_dir) if rel_dir else self.root
214
+ for name in self._CONFIG_NAMES:
215
+ cand = os.path.join(abs_dir, name)
216
+ if os.path.isfile(cand):
217
+ found = cand
218
+ break
219
+ if found is None and rel_dir:
220
+ found = self._config_path(posixpath.dirname(rel_dir))
221
+ self._dir_config[rel_dir] = found
222
+ return found
223
+
224
+ @staticmethod
225
+ def _extends_path(cfg_dir: str, spec: str) -> Optional[str]:
226
+ if not isinstance(spec, str) or not (spec.startswith(".") or os.path.isabs(spec)):
227
+ return None # package-based extends (`@tsconfig/node20`) carry no repo aliases
228
+ path = os.path.normpath(os.path.join(cfg_dir, spec))
229
+ if os.path.isdir(path):
230
+ path = os.path.join(path, "tsconfig.json")
231
+ elif not os.path.isfile(path) and not path.endswith(".json"):
232
+ path += ".json"
233
+ return path if os.path.isfile(path) else None
234
+
235
+ def _load(self, cfg_path: str, depth: int = 0, follow_refs: bool = True) -> Dict[str, Any]:
236
+ key = f"{cfg_path}|{int(follow_refs)}"
237
+ if key in self._options:
238
+ return self._options[key]
239
+ self._options[key] = {} # cycle guard
240
+ result: Dict[str, Any] = {}
241
+ try:
242
+ with open(cfg_path, "r", encoding="utf-8", errors="replace") as fh:
243
+ data = _parse_jsonc(fh.read())
244
+ except (OSError, ValueError):
245
+ data = None
246
+ if isinstance(data, dict):
247
+ cfg_dir = os.path.dirname(cfg_path)
248
+ parents = data.get("extends")
249
+ if depth < 8:
250
+ for parent in (parents if isinstance(parents, list) else [parents]):
251
+ parent_path = self._extends_path(cfg_dir, parent) if parent else None
252
+ if parent_path:
253
+ result.update(self._load(parent_path, depth + 1, follow_refs=False))
254
+ co = data.get("compilerOptions")
255
+ if isinstance(co, dict):
256
+ if isinstance(co.get("baseUrl"), str):
257
+ result["baseUrl"] = os.path.normpath(os.path.join(cfg_dir, co["baseUrl"]))
258
+ if isinstance(co.get("paths"), dict):
259
+ result["paths"] = co["paths"]
260
+ result["paths_dir"] = cfg_dir
261
+ if "paths" in result:
262
+ # `paths` resolve against the effective baseUrl, else the config
263
+ # that declared them.
264
+ result["paths_base"] = result.get("baseUrl") or result["paths_dir"]
265
+ refs = data.get("references")
266
+ if follow_refs and "paths" not in result and isinstance(refs, list) and depth < 8:
267
+ # Solution-style root config (Vite templates): aliases live in a
268
+ # referenced tsconfig.app.json.
269
+ for ref in refs:
270
+ ref_spec = ref.get("path") if isinstance(ref, dict) else None
271
+ ref_path = self._extends_path(cfg_dir, ref_spec) if ref_spec else None
272
+ if not ref_path:
273
+ continue
274
+ ref_opts = self._load(ref_path, depth + 1, follow_refs=False)
275
+ if "paths" in ref_opts:
276
+ for name in ("paths", "paths_dir", "paths_base"):
277
+ result[name] = ref_opts[name]
278
+ break
279
+ self._options[key] = result
280
+ return result
281
+
282
+ def _to_rel(self, abs_path: str) -> Optional[str]:
283
+ return _abs_to_repo_rel(self.root, abs_path)
284
+
285
+ def bases(self, rel_dir: str, spec: str) -> List[str]:
286
+ """Repo-relative base paths a bare specifier may refer to (most specific first)."""
287
+ cfg = self._config_path(rel_dir)
288
+ if cfg is None:
289
+ if spec.startswith("@/") and self._has_src:
290
+ rel = _repo_rel_join("src", spec[2:])
291
+ return [rel] if rel else []
292
+ return []
293
+ opts = self._load(cfg)
294
+ out: List[str] = []
295
+ paths = opts.get("paths")
296
+ if isinstance(paths, dict):
297
+ paths_base = opts.get("paths_base") or os.path.dirname(cfg)
298
+ best_targets: Optional[List[Any]] = None
299
+ best_star = ""
300
+ best_prefix_len = -1
301
+ for pattern, targets in paths.items():
302
+ if not isinstance(pattern, str) or not isinstance(targets, list):
303
+ continue
304
+ if "*" not in pattern:
305
+ if pattern == spec:
306
+ best_targets, best_star, best_prefix_len = targets, "", 10 ** 6
307
+ continue
308
+ prefix, _, suffix = pattern.partition("*")
309
+ if (
310
+ spec.startswith(prefix)
311
+ and spec.endswith(suffix)
312
+ and len(spec) >= len(prefix) + len(suffix)
313
+ and len(prefix) > best_prefix_len
314
+ ):
315
+ best_targets = targets
316
+ best_star = spec[len(prefix):len(spec) - len(suffix)]
317
+ best_prefix_len = len(prefix)
318
+ for target in best_targets or []:
319
+ if not isinstance(target, str):
320
+ continue
321
+ rel = self._to_rel(os.path.join(paths_base, target.replace("*", best_star)))
322
+ if rel is not None:
323
+ out.append(rel)
324
+ base_url = opts.get("baseUrl")
325
+ if base_url and not out:
326
+ rel = self._to_rel(os.path.join(base_url, spec))
327
+ if rel is not None:
328
+ out.append(rel)
329
+ return out
330
+
331
+
332
+ _PY_FROM_IMPORT_RE = re.compile(
333
+ r"^[ \t]*from[ \t]+(\.+[\w.]*|[A-Za-z_][\w.]*)[ \t]+import[ \t]+(\([^)]*\)|(?:[^\n\\#;]|\\\n)+)",
334
+ re.MULTILINE,
335
+ )
336
+
337
+
338
+ def _py_submodule_candidate(module: str, name: str) -> str:
339
+ """`from <module> import <name>` may import the submodule `<module>.<name>`."""
340
+ return f"{module}{name}" if module.endswith(".") else f"{module}.{name}"
341
+
342
+
343
+ def _python_from_import_candidates(code: str) -> Set[str]:
344
+ """Submodule candidates of every `from X import a, b` (text scan, any backend)."""
345
+ out: Set[str] = set()
346
+ for m in _PY_FROM_IMPORT_RE.finditer(code):
347
+ module = m.group(1)
348
+ names = re.sub(r"#[^\n]*", "", m.group(2)).replace("\\\n", " ").strip("()")
349
+ for part in names.split(","):
350
+ tokens = part.split()
351
+ name = tokens[0] if tokens else ""
352
+ if name != "*" and re.fullmatch(r"[A-Za-z_]\w*", name or ""):
353
+ out.add(_py_submodule_candidate(module, name))
354
+ return out
355
+
356
+
357
+ _DECORATOR_EXTS = {".py"} | set(_JS_TS_EXTS)
358
+ _DECORATOR_NAME_RE = re.compile(r"@\s*[A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)*")
359
+ _DECORATOR_ATTR_RE = re.compile(r"\s*\.\s*[A-Za-z_$][\w$]*")
360
+ _LINE_STRING_RE = re.compile(r'"(?:\\.|[^"\\\n])*"|\'(?:\\.|[^\'\\\n])*\'|`(?:\\.|[^`\\\n])*`')
361
+
362
+
363
+ def _strip_line_noise(line: str, ext: str) -> str:
364
+ """One source line with string literals emptied and the trailing comment dropped."""
365
+ s = _LINE_STRING_RE.sub('""', line)
366
+ marker = "#" if ext == ".py" else "//"
367
+ return s.split(marker, 1)[0]
368
+
369
+
370
+ def _bracket_delta(text: str) -> int:
371
+ return sum(text.count(c) for c in "([{") - sum(text.count(c) for c in ")]}")
372
+
373
+
374
+ def _match_bracket(text: str, open_idx: int) -> int:
375
+ depth = 0
376
+ for i in range(open_idx, len(text)):
377
+ ch = text[i]
378
+ if ch in "([{":
379
+ depth += 1
380
+ elif ch in ")]}":
381
+ depth -= 1
382
+ if depth == 0:
383
+ return i
384
+ return -1
385
+
386
+
387
+ def _is_decorator_block(text: str) -> bool:
388
+ """True when `text` is nothing but one or more decorators (`@a.b(...)` ...)."""
389
+ i, n, seen = 0, len(text), False
390
+ while i < n:
391
+ if text[i].isspace():
392
+ i += 1
393
+ continue
394
+ m = _DECORATOR_NAME_RE.match(text, i)
395
+ if not m:
396
+ return False
397
+ i, seen = m.end(), True
398
+ while True:
399
+ j = i
400
+ while j < n and text[j] in " \t":
401
+ j += 1
402
+ if j < n and text[j] in "([":
403
+ end = _match_bracket(text, j)
404
+ if end < 0:
405
+ return False
406
+ i = end + 1
407
+ attr = _DECORATOR_ATTR_RE.match(text, i)
408
+ if attr:
409
+ i = attr.end()
410
+ continue
411
+ break
412
+ return seen
413
+
414
+
415
+ def _decorated_start(lines: List[str], start: int, ext: str, max_lookback: int = 200) -> int:
416
+ """1-based first line of the decorators attached to the declaration at `start`.
417
+
418
+ Only a contiguous run of pure decorator lines counts (comment-only lines may
419
+ sit between them); a decorated *property* such as `@Input() name: string;`
420
+ above a method is not part of that method.
421
+ """
422
+ best = start
423
+ j = start - 2 # 0-based index of the line above the current start
424
+ floor = max(0, start - 1 - max_lookback)
425
+ pending_delta = 0 # bracket balance of the lines between j and best
426
+ while j >= floor:
427
+ raw = lines[j]
428
+ cleaned = _strip_line_noise(raw, ext).strip()
429
+ if not cleaned:
430
+ if raw.strip() or pending_delta < 0:
431
+ j -= 1 # comment-only line, or blank line inside decorator arguments
432
+ continue
433
+ break
434
+ pending_delta += _bracket_delta(cleaned)
435
+ if cleaned.startswith("@"):
436
+ block = "\n".join(_strip_line_noise(l, ext) for l in lines[j:best - 1])
437
+ if pending_delta != 0 or not _is_decorator_block(block):
438
+ break
439
+ best = j + 1
440
+ pending_delta = 0
441
+ elif pending_delta >= 0:
442
+ break # not inside a multi-line decorator argument list
443
+ j -= 1
444
+ return best
445
+
446
+
130
447
  _BACKEND_ROUTE_PATTERNS = [
131
448
  # (regex, default_method). Group 1 is always the route literal; the declaring
132
449
  # receiver (if any) is read back from the match text with _RECEIVER_RE.
@@ -331,6 +648,70 @@ def _is_generated_file(rel_path: str) -> bool:
331
648
  or "openapi" in base
332
649
  )
333
650
 
651
+ def _newline_offsets(text: str) -> List[int]:
652
+ """Offsets of every `\\n` in `text`, ascending (for bisect line lookups)."""
653
+ offsets: List[int] = []
654
+ find = text.find
655
+ i = find("\n")
656
+ while i != -1:
657
+ offsets.append(i)
658
+ i = find("\n", i + 1)
659
+ return offsets
660
+
661
+
662
+ def _line_at(offsets: List[int], pos: int) -> int:
663
+ """1-based line of `pos`; equals `text[:pos].count("\\n") + 1`."""
664
+ return bisect.bisect_left(offsets, pos) + 1
665
+
666
+
667
+ def _changed_edge_sources(
668
+ old: Dict[str, Set[str]], new: Dict[str, Set[str]]
669
+ ) -> Set[str]:
670
+ """Sources whose outgoing edge set differs between two graph versions.
671
+
672
+ A missing source and an empty set are equivalent (neither has rows).
673
+ """
674
+ empty: frozenset = frozenset()
675
+ changed = {src for src, tgts in new.items() if tgts != old.get(src, empty)}
676
+ changed.update(src for src in old.keys() - new.keys() if old[src])
677
+ return changed
678
+
679
+
680
+ class _SymbolNameIndex:
681
+ """Short-name and `::`-suffix lookups over one `CodeGraph.symbols` dict.
682
+
683
+ Immutable once built: a graph version replaces it instead of editing it,
684
+ so a fork (which shallow-copies attributes) can never corrupt the index a
685
+ reader of the published version is using.
686
+ """
687
+ __slots__ = ("source", "size", "order", "by_name", "by_suffix")
688
+
689
+ def __init__(self, symbols: Dict[str, "CodeSymbol"]):
690
+ self.source = symbols
691
+ self.size = len(symbols)
692
+ self.order: Dict[str, int] = {}
693
+ self.by_name: Dict[str, List[str]] = {}
694
+ self.by_suffix: Dict[str, List[str]] = {}
695
+ for idx, (k, sym) in enumerate(symbols.items()):
696
+ self.order[k] = idx
697
+ self.by_name.setdefault(sym.name, []).append(k)
698
+ # Every (possibly overlapping) "::" occurrence: k.endswith("::" + t)
699
+ # holds exactly when t is one of these suffixes.
700
+ p = k.find("::")
701
+ while p != -1:
702
+ self.by_suffix.setdefault(k[p + 2:], []).append(k)
703
+ p = k.find("::", p + 1)
704
+
705
+ def candidates(self, *names: str) -> List[str]:
706
+ """Keys whose short name or `::` suffix is one of `names`, in dict order."""
707
+ seen: Set[str] = set()
708
+ for name in names:
709
+ seen.update(self.by_name.get(name, ()))
710
+ seen.update(self.by_suffix.get(name, ()))
711
+ order = self.order
712
+ return sorted(seen, key=order.__getitem__)
713
+
714
+
334
715
  class CodeSymbol:
335
716
  """Represents a structural code entity (file, class, or function)."""
336
717
  __slots__ = ("name", "kind", "file_path", "line_start", "line_end", "signature", "body")
@@ -404,6 +785,17 @@ class CodeGraph:
404
785
  self._dirty_files: Set[str] = set()
405
786
  self._deleted_files: Set[str] = set()
406
787
  self._ctx_index: Optional[ContextIndex] = None
788
+ # Serialises rescans of this instance; readers never take it.
789
+ self._scan_mutex = threading.Lock()
790
+ # Files the last walk visited (None until the first scan): lets import
791
+ # resolution tell glob-registered assets from indexed sources.
792
+ self._walked_files: Optional[Set[str]] = None
793
+ # Lazy name/suffix index over `symbols`; rebuilt when stale.
794
+ self._sym_index: Optional[_SymbolNameIndex] = None
795
+ # Edge sources whose outgoing set changed since the persisted index was
796
+ # last in sync with memory; None = unknown, so the next save rewrites
797
+ # the whole `edges` table. Only a successful SQLite load makes it known.
798
+ self._dirty_edge_sources: Optional[Set[str]] = None
407
799
 
408
800
  if self.use_disk_cache and os.environ.get("TOKENSAFE_GRAPH_DISK_CACHE", "1") != "0":
409
801
  self._load_disk_cache()
@@ -411,7 +803,7 @@ class CodeGraph:
411
803
  @staticmethod
412
804
  def _detect_backend() -> str:
413
805
  try:
414
- from src.treesitter_backend import TreeSitterBackend
806
+ from tokensafe.treesitter_backend import TreeSitterBackend
415
807
  if TreeSitterBackend.is_available():
416
808
  return "treesitter"
417
809
  except Exception:
@@ -429,6 +821,8 @@ class CodeGraph:
429
821
 
430
822
  def _clear_graph_state(self) -> None:
431
823
  self.symbols.clear()
824
+ self._sym_index = None
825
+ self._dirty_edge_sources = None
432
826
  self.file_symbols.clear()
433
827
  self.edges.clear()
434
828
  self.rev_edges.clear()
@@ -464,6 +858,7 @@ class CodeGraph:
464
858
  return False
465
859
 
466
860
  self.symbols = {}
861
+ self._sym_index = None
467
862
  for row in cur.execute("SELECT sym_key, rel_path, name, kind, line_start, line_end, signature FROM symbols").fetchall():
468
863
  self.symbols[row[0]] = CodeSymbol(
469
864
  name=row[2],
@@ -535,6 +930,8 @@ class CodeGraph:
535
930
  pass
536
931
 
537
932
  self.last_scanned = float(meta.get("last_scanned", 0.0))
933
+ # Memory now mirrors the persisted edges row for row.
934
+ self._dirty_edge_sources = set()
538
935
  return True
539
936
  finally:
540
937
  con.close()
@@ -553,6 +950,7 @@ class CodeGraph:
553
950
  and data.get("backend") == self.backend
554
951
  ):
555
952
  self.symbols = {k: CodeSymbol.from_dict(v) for k, v in data.get("symbols", {}).items()}
953
+ self._sym_index = None
556
954
  self.file_symbols = {k: list(v) for k, v in data.get("file_symbols", {}).items()}
557
955
  self.edges = {k: set(v) for k, v in data.get("edges", {}).items()}
558
956
  self.rev_edges = {k: set(v) for k, v in data.get("rev_edges", {}).items()}
@@ -593,9 +991,21 @@ class CodeGraph:
593
991
  self._dirty_files.clear()
594
992
  self._deleted_files.clear()
595
993
  changed: Optional[Set[str]] = dirty if (dirty or deleted) else None
994
+ edge_sources = self._dirty_edge_sources
995
+ self._dirty_edge_sources = set()
596
996
  try:
597
997
  index = self._context_index()
598
- index.save_graph(self, changed=changed, deleted=deleted)
998
+ try:
999
+ index.save_graph(
1000
+ self,
1001
+ changed=changed,
1002
+ deleted=deleted,
1003
+ edge_sources=None if edge_sources is None else set(edge_sources),
1004
+ )
1005
+ except Exception:
1006
+ # Unknown persisted state: the next save rewrites every edge.
1007
+ self._dirty_edge_sources = None
1008
+ raise
599
1009
  if changed is None:
600
1010
  index.sync_text(list(self.file_stats.keys()))
601
1011
  else:
@@ -622,24 +1032,94 @@ class CodeGraph:
622
1032
  if target in self.rev_edges:
623
1033
  self.rev_edges[target].discard(source)
624
1034
 
625
- def scan(self, force: bool = False) -> int:
1035
+ # Containers that together form one graph version. A rescan builds the next
1036
+ # version in copies of these and swaps them in at once (see `scan`).
1037
+ _GRAPH_STATE_ATTRS = (
1038
+ "symbols", "file_symbols", "edges", "rev_edges", "file_mtimes", "file_stats",
1039
+ "file_imports", "glob_imports", "file_endpoints", "file_api_calls",
1040
+ "file_mounts", "api_links",
1041
+ )
1042
+
1043
+ def _fork(self) -> "CodeGraph":
1044
+ """A private copy of the graph state that a rescan may mutate freely.
1045
+
1046
+ Symbols are shared: a rescan never mutates an existing CodeSymbol, it
1047
+ replaces the entries of re-indexed files with new objects.
626
1048
  """
627
- Fast incremental scan of the workspace.
628
- Parses modified files only (checked via `(mtime, size)`); returns number of files re-indexed.
1049
+ work = copy.copy(self)
1050
+ work.symbols = dict(self.symbols)
1051
+ work._sym_index = None
1052
+ work.file_symbols = {k: list(v) for k, v in self.file_symbols.items()}
1053
+ work.edges = {k: set(v) for k, v in self.edges.items()}
1054
+ work.rev_edges = {k: set(v) for k, v in self.rev_edges.items()}
1055
+ work.file_mtimes = dict(self.file_mtimes)
1056
+ work.file_stats = dict(self.file_stats)
1057
+ work.file_imports = {k: set(v) for k, v in self.file_imports.items()}
1058
+ work.glob_imports = {k: set(v) for k, v in self.glob_imports.items()}
1059
+ work.file_endpoints = {k: list(v) for k, v in self.file_endpoints.items()}
1060
+ work.file_api_calls = {k: list(v) for k, v in self.file_api_calls.items()}
1061
+ work.file_mounts = {k: list(v) for k, v in self.file_mounts.items()}
1062
+ work.api_links = list(self.api_links)
1063
+ work._dirty_files = set(self._dirty_files)
1064
+ work._deleted_files = set(self._deleted_files)
1065
+ work._dirty_edge_sources = (
1066
+ None if self._dirty_edge_sources is None else set(self._dirty_edge_sources)
1067
+ )
1068
+ return work
1069
+
1070
+ def _adopt(self, work: "CodeGraph") -> None:
1071
+ """Publishes a forked graph version in one step.
1072
+
1073
+ A single `__dict__.update` runs under the GIL without executing Python
1074
+ code, so a reader sees either every old container or every new one; the
1075
+ old containers are never mutated again, so an iteration that started on
1076
+ them finishes on a consistent snapshot.
629
1077
  """
630
- from src.win_paths import is_system_root
1078
+ state = {name: getattr(work, name) for name in self._GRAPH_STATE_ATTRS}
1079
+ state.update(
1080
+ backend=work.backend,
1081
+ last_scanned=work.last_scanned,
1082
+ _dirty_files=work._dirty_files,
1083
+ _deleted_files=work._deleted_files,
1084
+ _dirty_edge_sources=work._dirty_edge_sources,
1085
+ _walked_files=work._walked_files,
1086
+ # Built against work.symbols (or None): stays valid once adopted.
1087
+ _sym_index=work._sym_index,
1088
+ )
1089
+ self.__dict__.update(state)
631
1090
 
632
- if is_system_root(self.root_dir):
633
- return 0
1091
+ def _drop_file(self, rel_path: str) -> None:
1092
+ self._purge_file(rel_path)
1093
+ self.file_stats.pop(rel_path, None)
1094
+ self.file_mtimes.pop(rel_path, None)
1095
+ self._deleted_files.add(rel_path)
634
1096
 
635
- current_backend = self._detect_backend()
636
- if current_backend != self.backend:
637
- self.backend = current_backend
638
- force = True
1097
+ def _is_unchanged_unwalked_file(self, rel_path: str) -> bool:
1098
+ """True for a file the walk does not visit (an `import.meta.glob` asset
1099
+ registered by `_resolve_local_imports`) that is still on disk unchanged.
639
1100
 
640
- reindexed = 0
641
- current_files = set()
1101
+ Such files were reported as removed on every scan and re-added by the
1102
+ import resolution, so every TTL rescan rebuilt the graph and the cache.
1103
+ """
1104
+ prev = self.file_stats.get(rel_path)
1105
+ if prev is None:
1106
+ return False
1107
+ try:
1108
+ st = os.stat(os.path.join(self.root_dir, rel_path))
1109
+ except OSError:
1110
+ return False
1111
+ return stat.S_ISREG(st.st_mode) and (st.st_mtime, st.st_size) == prev
1112
+
1113
+ def _plan_scan(self, force: bool) -> Tuple[Set[str], List[Tuple[str, str, Tuple[float, int]]], List[str]]:
1114
+ """Walks the tree without touching graph state.
642
1115
 
1116
+ Returns (walked files, files to (re)index with their stat signature,
1117
+ previously known files that must be dropped).
1118
+ """
1119
+ current_files: Set[str] = set()
1120
+ to_index: List[Tuple[str, str, Tuple[float, int]]] = []
1121
+ to_drop: List[str] = []
1122
+ known = self.file_stats
643
1123
  for dirpath, dirnames, filenames in os.walk(self.root_dir):
644
1124
  dirnames[:] = [
645
1125
  d for d in dirnames
@@ -647,63 +1127,95 @@ class CodeGraph:
647
1127
  ]
648
1128
  for filename in filenames:
649
1129
  _, ext = os.path.splitext(filename)
650
- if ext.lower() in SUPPORTED_EXTS:
651
- full_path = os.path.join(dirpath, filename)
652
- rel_path = os.path.relpath(full_path, self.root_dir).replace("\\", "/")
653
- if _is_generated_asset(rel_path, filename):
654
- if rel_path in self.file_symbols or rel_path in self.file_stats:
655
- self._purge_file(rel_path)
656
- self.file_stats.pop(rel_path, None)
657
- self.file_mtimes.pop(rel_path, None)
658
- self._deleted_files.add(rel_path)
659
- reindexed += 1
660
- continue
661
- current_files.add(rel_path)
1130
+ if ext.lower() not in SUPPORTED_EXTS:
1131
+ continue
1132
+ full_path = os.path.join(dirpath, filename)
1133
+ rel_path = os.path.relpath(full_path, self.root_dir).replace("\\", "/")
1134
+ if _is_generated_asset(rel_path, filename):
1135
+ if rel_path in self.file_symbols or rel_path in known:
1136
+ to_drop.append(rel_path)
1137
+ continue
1138
+ current_files.add(rel_path)
1139
+ try:
1140
+ st = os.stat(full_path)
1141
+ except OSError:
1142
+ continue
1143
+ if not stat.S_ISREG(st.st_mode) or st.st_size > 2 * 1024 * 1024:
1144
+ if rel_path in self.file_symbols or rel_path in known:
1145
+ to_drop.append(rel_path)
1146
+ continue
1147
+ sig = (st.st_mtime, st.st_size)
1148
+ prev_sig = known.get(rel_path)
1149
+ prev_mtime = self.file_mtimes.get(rel_path)
1150
+ if (
1151
+ force
1152
+ or prev_sig is None
1153
+ or prev_sig != sig
1154
+ or prev_mtime is None
1155
+ or prev_mtime < st.st_mtime
1156
+ ):
1157
+ to_index.append((full_path, rel_path, sig))
1158
+ return current_files, to_index, to_drop
662
1159
 
663
- try:
664
- st = os.stat(full_path)
665
- if not stat.S_ISREG(st.st_mode) or st.st_size > 2 * 1024 * 1024:
666
- if rel_path in self.file_symbols or rel_path in self.file_stats:
667
- self._purge_file(rel_path)
668
- self.file_stats.pop(rel_path, None)
669
- self.file_mtimes.pop(rel_path, None)
670
- self._deleted_files.add(rel_path)
671
- reindexed += 1
672
- continue
673
- sig = (st.st_mtime, st.st_size)
674
- except OSError:
675
- continue
1160
+ def scan(self, force: bool = False) -> int:
1161
+ """
1162
+ Fast incremental scan of the workspace.
1163
+ Parses modified files only (checked via `(mtime, size)`); returns number of files re-indexed.
676
1164
 
677
- prev_sig = self.file_stats.get(rel_path)
678
- prev_mtime = self.file_mtimes.get(rel_path)
679
- changed = (
680
- force
681
- or prev_sig is None
682
- or prev_sig != sig
683
- or prev_mtime is None
684
- or prev_mtime < st.st_mtime
685
- )
686
- if changed:
687
- self._index_file(full_path, rel_path)
688
- self.file_stats[rel_path] = sig
689
- self.file_mtimes[rel_path] = st.st_mtime
690
- self._dirty_files.add(rel_path)
691
- reindexed += 1
692
-
693
- # Purge removed files
694
- deleted = (set(self.file_stats.keys()) | set(self.file_mtimes.keys())) - current_files
695
- for del_path in deleted:
696
- self._purge_file(del_path)
697
- self.file_stats.pop(del_path, None)
698
- self.file_mtimes.pop(del_path, None)
699
- self._deleted_files.add(del_path)
700
-
701
- if reindexed > 0 or deleted or force:
702
- self._resolve_local_imports()
703
- self._link_api_routes()
704
-
705
- self.last_scanned = time.time()
706
- if reindexed > 0 or deleted:
1165
+ Readers may run concurrently: the next graph version is built in private
1166
+ copies and published atomically, so a reader never sees a half-rebuilt
1167
+ graph (empty dependency lists) or a container changing size under it.
1168
+ """
1169
+ from tokensafe.win_paths import is_system_root
1170
+
1171
+ if is_system_root(self.root_dir):
1172
+ return 0
1173
+
1174
+ with self._scan_mutex:
1175
+ return self._scan_locked(force)
1176
+
1177
+ def _scan_locked(self, force: bool) -> int:
1178
+ backend = self._detect_backend()
1179
+ if backend != self.backend:
1180
+ force = True
1181
+
1182
+ current_files, to_index, to_drop = self._plan_scan(force)
1183
+ dropped = set(to_drop)
1184
+ stale = [
1185
+ p for p in sorted((set(self.file_stats) | set(self.file_mtimes)) - current_files - dropped)
1186
+ if not self._is_unchanged_unwalked_file(p)
1187
+ ]
1188
+
1189
+ if not (to_index or to_drop or stale or force):
1190
+ self._walked_files = current_files
1191
+ self.last_scanned = time.time()
1192
+ return 0
1193
+
1194
+ work = self._fork()
1195
+ work.backend = backend
1196
+ work._walked_files = current_files
1197
+ reindexed = 0
1198
+ for rel_path in to_drop:
1199
+ work._drop_file(rel_path)
1200
+ reindexed += 1
1201
+ for full_path, rel_path, sig in to_index:
1202
+ work._index_file(full_path, rel_path)
1203
+ work.file_stats[rel_path] = sig
1204
+ work.file_mtimes[rel_path] = sig[0]
1205
+ work._dirty_files.add(rel_path)
1206
+ reindexed += 1
1207
+ for del_path in stale:
1208
+ work._drop_file(del_path)
1209
+
1210
+ if reindexed > 0 or stale or force:
1211
+ work._resolve_local_imports()
1212
+ work._link_api_routes()
1213
+
1214
+ work.last_scanned = time.time()
1215
+ if work._dirty_edge_sources is not None:
1216
+ work._dirty_edge_sources |= _changed_edge_sources(self.edges, work.edges)
1217
+ self._adopt(work)
1218
+ if reindexed > 0 or self._deleted_files:
707
1219
  self._save_disk_cache()
708
1220
  return reindexed
709
1221
 
@@ -715,6 +1227,8 @@ class CodeGraph:
715
1227
  self.file_endpoints.pop(rel_path, None)
716
1228
  self.file_api_calls.pop(rel_path, None)
717
1229
  self.file_mounts.pop(rel_path, None)
1230
+ if sym_keys:
1231
+ self._sym_index = None
718
1232
  for k in sym_keys:
719
1233
  self.symbols.pop(k, None)
720
1234
  targets = self.edges.pop(k, set())
@@ -755,19 +1269,47 @@ class CodeGraph:
755
1269
  _, ext = os.path.splitext(full_path)
756
1270
  ext = ext.lower()
757
1271
 
758
- if self._try_index_treesitter(content, rel_path, file_node, ext):
759
- self._extract_api_routes_and_calls(content, rel_path)
760
- return
761
-
762
- if ext == ".py":
763
- self._parse_python(content, rel_path, file_node)
764
- elif ext == ".rb":
765
- self._parse_ruby(content, rel_path, file_node)
766
- elif ext in SUPPORTED_EXTS:
767
- self._parse_braces(content, rel_path, file_node, ext)
1272
+ try:
1273
+ self._index_content(content, rel_path, file_node, ext)
1274
+ except Exception:
1275
+ # One unparsable file (NUL bytes, pathological nesting, a parser
1276
+ # bug) must not abort the scan of the whole repository: keep the
1277
+ # file as an empty node and move on.
1278
+ self._purge_file(rel_path)
1279
+ self.file_symbols[rel_path] = []
1280
+ self.file_imports[rel_path] = set()
1281
+ self.glob_imports[rel_path] = set()
1282
+
1283
+ def _index_content(self, content: str, rel_path: str, file_node: str, ext: str) -> None:
1284
+ if not self._try_index_treesitter(content, rel_path, file_node, ext):
1285
+ if ext == ".py":
1286
+ self._parse_python(content, rel_path, file_node)
1287
+ elif ext == ".rb":
1288
+ self._parse_ruby(content, rel_path, file_node)
1289
+ elif ext in SUPPORTED_EXTS:
1290
+ self._parse_braces(content, rel_path, file_node, ext)
1291
+ elif ext == ".py":
1292
+ # Tree-sitter reports `from . import utils` as the module `.` only;
1293
+ # record the submodule candidates the stdlib parser records too.
1294
+ self.file_imports[rel_path].update(_python_from_import_candidates(content))
1295
+
1296
+ if ext in _DECORATOR_EXTS and "@" in content:
1297
+ self._extend_decorated_ranges(content, rel_path, ext)
768
1298
 
769
1299
  self._extract_api_routes_and_calls(content, rel_path)
770
1300
 
1301
+ def _extend_decorated_ranges(self, content: str, rel_path: str, ext: str) -> None:
1302
+ """Starts each symbol at its first decorator, so replacing the symbol's
1303
+ range (OUMV `mutate`) replaces its decorators instead of duplicating them."""
1304
+ lines = content.splitlines()
1305
+ for sym_key in self.file_symbols.get(rel_path, []):
1306
+ sym = self.symbols.get(sym_key)
1307
+ if sym is None or sym.line_start <= 1 or sym.line_start > len(lines):
1308
+ continue
1309
+ new_start = _decorated_start(lines, sym.line_start, ext)
1310
+ if new_start < sym.line_start:
1311
+ sym.line_start = new_start
1312
+
771
1313
  def _find_enclosing_symbol(self, rel_path: str, line_no: int) -> Optional[str]:
772
1314
  sym_keys = self.file_symbols.get(rel_path, [])
773
1315
  if not sym_keys:
@@ -842,6 +1384,7 @@ class CodeGraph:
842
1384
  self.file_endpoints[rel_path].append((norm_route, None, None))
843
1385
 
844
1386
  # 2. Backend route definitions
1387
+ nl_offsets: Optional[List[int]] = None # built on the first match
845
1388
  same_file_mounts: Dict[str, List[str]] = {}
846
1389
  if not file_prefix:
847
1390
  for (prefix, ident, module) in self.file_mounts[rel_path]:
@@ -860,7 +1403,9 @@ class CodeGraph:
860
1403
  # declared on `router`, so app.get("/health") in the same file keeps
861
1404
  # its own path. A mounted route is not addressable unprefixed, so
862
1405
  # only the composed form is recorded.
863
- line_no = content[:match.start()].count("\n") + 1
1406
+ if nl_offsets is None:
1407
+ nl_offsets = _newline_offsets(content)
1408
+ line_no = _line_at(nl_offsets, match.start())
864
1409
  method = _match_http_method(match.group(0))
865
1410
  receiver_match = _RECEIVER_RE.match(match.group(0))
866
1411
  mount_prefixes = same_file_mounts.get(receiver_match.group(1), []) if receiver_match else []
@@ -884,7 +1429,9 @@ class CodeGraph:
884
1429
  norm_route = _normalize_route_path(route_raw)
885
1430
  if not norm_route:
886
1431
  continue
887
- line_no = content[:match.start()].count("\n") + 1
1432
+ if nl_offsets is None:
1433
+ nl_offsets = _newline_offsets(content)
1434
+ line_no = _line_at(nl_offsets, match.start())
888
1435
  sym_key = self._find_enclosing_symbol(rel_path, line_no)
889
1436
  method = _match_http_method(match.group(0)) or default_method
890
1437
  self.file_api_calls[rel_path].append((norm_route, sym_key, method))
@@ -893,12 +1440,13 @@ class CodeGraph:
893
1440
  """Resolves a relative import specifier to an indexed file, if any."""
894
1441
  if not spec or not spec.startswith("."):
895
1442
  return None
896
- base = os.path.normpath(os.path.join(os.path.dirname(from_rel), spec)).replace("\\", "/")
897
- candidates = [base]
898
- for ext in (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".py", ".go", ".rs", ".php", ".java"):
1443
+ base = _repo_rel_join(posixpath.dirname(from_rel), spec)
1444
+ if not base:
1445
+ return None
1446
+ prefer_ts = os.path.splitext(from_rel)[1].lower() in _TS_SOURCE_EXTS
1447
+ candidates = _js_ts_candidates(base, prefer_ts)
1448
+ for ext in (".py", ".go", ".rs", ".php", ".java"):
899
1449
  candidates.append(base + ext)
900
- for ext in (".ts", ".tsx", ".js", ".jsx"):
901
- candidates.append(base + "/index" + ext)
902
1450
  for cand in candidates:
903
1451
  if cand in self.file_symbols:
904
1452
  return cand
@@ -1018,6 +1566,7 @@ class CodeGraph:
1018
1566
 
1019
1567
  def _register_symbol(self, rel_path: str, file_node: str, symbol: CodeSymbol, sym_key: str):
1020
1568
  self.symbols[sym_key] = symbol
1569
+ self._sym_index = None
1021
1570
  if sym_key not in self.file_symbols[rel_path]:
1022
1571
  self.file_symbols[rel_path].append(sym_key)
1023
1572
  self.add_edge(file_node, sym_key)
@@ -1026,7 +1575,7 @@ class CodeGraph:
1026
1575
  if self.backend != "treesitter":
1027
1576
  return False
1028
1577
  try:
1029
- from src.treesitter_backend import TreeSitterBackend
1578
+ from tokensafe.treesitter_backend import TreeSitterBackend
1030
1579
  data = TreeSitterBackend.extract_graph_data(code, ext, rel_path)
1031
1580
  except Exception:
1032
1581
  return False
@@ -1060,7 +1609,9 @@ class CodeGraph:
1060
1609
  def _parse_python(self, code: str, rel_path: str, file_node: str):
1061
1610
  try:
1062
1611
  tree = ast.parse(code)
1063
- except SyntaxError:
1612
+ except (SyntaxError, ValueError, RecursionError, MemoryError):
1613
+ # ValueError: NUL bytes (Python < 3.12); RecursionError/MemoryError:
1614
+ # pathologically nested code. The file stays an empty node.
1064
1615
  return
1065
1616
 
1066
1617
  lines = code.splitlines()
@@ -1080,12 +1631,18 @@ class CodeGraph:
1080
1631
  for alias in child.names:
1081
1632
  if alias.name != "*":
1082
1633
  self.add_edge(file_node, f"sym:{alias.name}")
1634
+ if mod_name:
1635
+ # `from . import utils` imports the submodule `.utils`
1636
+ # when one exists; resolution keeps only real files.
1637
+ self.file_imports[rel_path].add(_py_submodule_candidate(mod_name, alias.name))
1083
1638
  elif isinstance(child, ast.ClassDef):
1084
- start = getattr(child, "lineno", 1)
1085
- end = getattr(child, "end_lineno", start)
1639
+ def_line = getattr(child, "lineno", 1)
1640
+ end = getattr(child, "end_lineno", def_line)
1641
+ # Decorators belong to the declaration's range.
1642
+ start = min([def_line] + [getattr(d, "lineno", def_line) for d in child.decorator_list])
1086
1643
  qual = f"{class_name}::{child.name}" if class_name else child.name
1087
1644
  sym_key = f"{rel_path}::{qual}"
1088
- sig = lines[start - 1].strip() if 0 < start <= len(lines) else child.name
1645
+ sig = lines[def_line - 1].strip() if 0 < def_line <= len(lines) else child.name
1089
1646
  symbol = CodeSymbol(
1090
1647
  name=child.name,
1091
1648
  kind="class",
@@ -1097,11 +1654,13 @@ class CodeGraph:
1097
1654
  self._register_symbol(rel_path, file_node, symbol, sym_key)
1098
1655
  walk_py(child, class_name=qual, fn_key=None)
1099
1656
  elif isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
1100
- start = getattr(child, "lineno", 1)
1101
- end = getattr(child, "end_lineno", start)
1657
+ def_line = getattr(child, "lineno", 1)
1658
+ end = getattr(child, "end_lineno", def_line)
1659
+ # Decorators belong to the declaration's range.
1660
+ start = min([def_line] + [getattr(d, "lineno", def_line) for d in child.decorator_list])
1102
1661
  qual = f"{class_name}::{child.name}" if class_name else child.name
1103
1662
  sym_key = f"{rel_path}::{qual}"
1104
- sig = lines[start - 1].strip() if 0 < start <= len(lines) else child.name
1663
+ sig = lines[def_line - 1].strip() if 0 < def_line <= len(lines) else child.name
1105
1664
  symbol = CodeSymbol(
1106
1665
  name=child.name,
1107
1666
  kind="function",
@@ -1126,7 +1685,7 @@ class CodeGraph:
1126
1685
  walk_py(tree)
1127
1686
 
1128
1687
  def _parse_braces(self, code: str, rel_path: str, file_node: str, ext: str):
1129
- from src.skeletonizer import BraceLexer, Skeletonizer
1688
+ from tokensafe.skeletonizer import BraceLexer, Skeletonizer
1130
1689
 
1131
1690
  lines = code.splitlines()
1132
1691
  count_lines = Skeletonizer.blank_template_literals(lines)
@@ -1135,7 +1694,7 @@ class CodeGraph:
1135
1694
  # Strip comments only (keep string literals intact for import path extraction)
1136
1695
  no_block_comments = re.sub(r"/\*.*?\*/", "", code, flags=re.DOTALL)
1137
1696
  cleaned_text = re.sub(r"//.*$", "", no_block_comments, flags=re.MULTILINE)
1138
- if ext in (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"):
1697
+ if ext in _JS_TS_EXTS:
1139
1698
  imp_re = re.compile(
1140
1699
  r"""(?:(?:import|export)\s+(?:.*?\s+from\s+)?['"]([^'"]+)['"]|require\(\s*['"]([^'"]+)['"]\s*\))"""
1141
1700
  )
@@ -1215,7 +1774,7 @@ class CodeGraph:
1215
1774
  if not clean.endswith(";"):
1216
1775
  pending_header = (matched_name, matched_kind, idx, matched_sig)
1217
1776
  matched_name = None
1218
- elif ext in (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs") and any(k == "class" for _, _, k in sym_stack):
1777
+ elif ext in _JS_TS_EXTS and any(k == "class" for _, _, k in sym_stack):
1219
1778
  mm = ts_method_re.match(clean)
1220
1779
  if mm and mm.group(1) not in _SKIP_CALLS:
1221
1780
  matched_name = mm.group(1)
@@ -1351,16 +1910,21 @@ class CodeGraph:
1351
1910
  d = os.path.dirname(fp)
1352
1911
  dir_to_files.setdefault(d, []).append(fp)
1353
1912
 
1913
+ ts_resolver = _TsPathResolver(self.root_dir)
1354
1914
  for rel_path, mods in self.file_imports.items():
1355
1915
  src_node = f"file:{rel_path}"
1356
1916
  src_dir = os.path.dirname(rel_path)
1357
1917
  ext = os.path.splitext(rel_path)[1].lower()
1358
1918
 
1359
1919
  for mod in mods:
1360
- for target_rel in self._resolve_single_import(mod, src_dir, ext, indexed_files, dir_to_files):
1920
+ for target_rel in self._resolve_single_import(
1921
+ mod, src_dir, ext, indexed_files, dir_to_files, ts_resolver=ts_resolver
1922
+ ):
1361
1923
  if target_rel != rel_path:
1362
1924
  self.add_edge(src_node, f"file:{target_rel}")
1363
1925
 
1926
+ glob_assets: Set[str] = set()
1927
+
1364
1928
  # Expand `import.meta.glob` patterns last: the indexed file set is now
1365
1929
  # known, and brace patterns must be expanded rather than fnmatched.
1366
1930
  for rel_path, patterns in self.glob_imports.items():
@@ -1421,8 +1985,16 @@ class CodeGraph:
1421
1985
  self.file_stats[target_rel] = (st.st_mtime, st.st_size)
1422
1986
  self.file_mtimes[target_rel] = st.st_mtime
1423
1987
  self.file_symbols.setdefault(target_rel, [])
1988
+ glob_assets.add(target_rel)
1424
1989
  self.add_edge(src_node, f"file:{target_rel}")
1425
1990
 
1991
+ # Glob-registered assets no glob matches any more (pattern edited or the
1992
+ # importing file removed) leave the graph; still-matched ones stay put.
1993
+ walked = self._walked_files
1994
+ if walked is not None:
1995
+ for rel_path in [p for p in self.file_stats if p not in walked and p not in glob_assets]:
1996
+ self._drop_file(rel_path)
1997
+
1426
1998
  @staticmethod
1427
1999
  def _resolve_single_import(
1428
2000
  mod: str,
@@ -1430,37 +2002,49 @@ class CodeGraph:
1430
2002
  ext: str,
1431
2003
  indexed_files: Set[str],
1432
2004
  dir_to_files: Dict[str, List[str]],
2005
+ ts_resolver: Optional["_TsPathResolver"] = None,
1433
2006
  ) -> List[str]:
1434
2007
  if not mod:
1435
2008
  return []
2009
+ src_dir = src_dir.replace("\\", "/")
1436
2010
 
1437
2011
  if ext == ".py":
1438
2012
  if mod.startswith("."):
1439
2013
  dots = len(mod) - len(mod.lstrip("."))
1440
2014
  rest = mod[dots:].replace(".", "/")
2015
+ depth = len([p for p in src_dir.split("/") if p])
2016
+ if dots - 1 > depth:
2017
+ return [] # relative import beyond the repository root
1441
2018
  base_dir = src_dir
1442
2019
  for _ in range(dots - 1):
1443
- base_dir = os.path.dirname(base_dir)
1444
- prefix = os.path.normpath(os.path.join(base_dir, rest)).replace("\\", "/") if rest else base_dir
2020
+ base_dir = posixpath.dirname(base_dir)
2021
+ prefixes = [_repo_rel_join(base_dir, rest) if rest else base_dir]
1445
2022
  else:
1446
2023
  prefix = mod.replace(".", "/")
1447
- prefix = prefix.lstrip("./")
1448
- for cand in (f"{prefix}.py", f"{prefix}/__init__.py"):
1449
- if cand in indexed_files:
1450
- return [cand]
2024
+ # `src/` layout: `import mypkg.x` lives in `<root>/src/mypkg/x.py`.
2025
+ prefixes = [prefix, f"src/{prefix}"]
2026
+ for prefix in prefixes:
2027
+ if prefix is None:
2028
+ continue
2029
+ stem = f"{prefix}/" if prefix else ""
2030
+ for cand in (f"{prefix}.py", f"{stem}__init__.py"):
2031
+ if cand in indexed_files:
2032
+ return [cand]
1451
2033
  return []
1452
2034
 
1453
- if ext in (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"):
1454
- if not mod.startswith("."):
1455
- return []
1456
- base = os.path.normpath(os.path.join(src_dir, mod)).replace("\\", "/").lstrip("./")
1457
- for cand in (
1458
- base,
1459
- f"{base}.ts", f"{base}.tsx", f"{base}.js", f"{base}.jsx", f"{base}.mjs", f"{base}.cjs",
1460
- f"{base}/index.ts", f"{base}/index.tsx", f"{base}/index.js", f"{base}/index.mjs",
1461
- ):
1462
- if cand in indexed_files:
1463
- return [cand]
2035
+ if ext in _JS_TS_EXTS:
2036
+ prefer_ts = ext in _TS_SOURCE_EXTS
2037
+ if mod.startswith("."):
2038
+ base = _repo_rel_join(src_dir, mod)
2039
+ bases = [base] if base is not None else []
2040
+ elif ts_resolver is not None:
2041
+ bases = ts_resolver.bases(src_dir, mod)
2042
+ else:
2043
+ bases = []
2044
+ for base in bases:
2045
+ for cand in _js_ts_candidates(base, prefer_ts):
2046
+ if cand in indexed_files:
2047
+ return [cand]
1464
2048
  return []
1465
2049
 
1466
2050
  if ext == ".go":
@@ -1471,8 +2055,8 @@ class CodeGraph:
1471
2055
  return []
1472
2056
 
1473
2057
  if ext in (".c", ".h", ".cpp", ".cc", ".cxx", ".hpp"):
1474
- cand = os.path.normpath(os.path.join(src_dir, mod)).replace("\\", "/").lstrip("./")
1475
- return [cand] if cand in indexed_files else []
2058
+ cand = _repo_rel_join(src_dir, mod)
2059
+ return [cand] if cand and cand in indexed_files else []
1476
2060
 
1477
2061
  if ext == ".rs" and mod.startswith(("crate::", "super::", "self::")):
1478
2062
  parts = mod.split("::")[1:]
@@ -1551,13 +2135,30 @@ class CodeGraph:
1551
2135
  # -------------------------------------------------------------
1552
2136
  # 2. Neighborhood & Graph-Guided Skeletonization
1553
2137
  # -------------------------------------------------------------
2138
+ def _symbol_name_index(self) -> Tuple[Dict[str, CodeSymbol], _SymbolNameIndex]:
2139
+ """The symbols dict plus a name index that matches it.
2140
+
2141
+ Readers never lock: take one snapshot of `symbols` and reuse the cached
2142
+ index only when it was built from that very dict at its current size
2143
+ (mutation sites also drop it explicitly).
2144
+ """
2145
+ symbols = self.symbols
2146
+ index = self._sym_index
2147
+ if index is None or index.source is not symbols or index.size != len(symbols):
2148
+ index = _SymbolNameIndex(symbols)
2149
+ self._sym_index = index
2150
+ return symbols, index
2151
+
1554
2152
  def _match_target_keys(self, target_symbol: str, target_file: Optional[str] = None) -> List[str]:
1555
2153
  if target_symbol in self.symbols:
1556
2154
  return [target_symbol]
1557
2155
 
1558
2156
  norm_target = target_symbol.replace(".", "::")
2157
+ symbols, index = self._symbol_name_index()
1559
2158
  candidates = []
1560
- for k, sym in self.symbols.items():
2159
+ # Same predicate as a full scan, applied to the index hits in dict order.
2160
+ for k in index.candidates(target_symbol, norm_target):
2161
+ sym = symbols[k]
1561
2162
  if sym.name == target_symbol or k.endswith(f"::{target_symbol}") or k.endswith(f"::{norm_target}"):
1562
2163
  candidates.append(k)
1563
2164
 
@@ -1575,7 +2176,9 @@ class CodeGraph:
1575
2176
  imported = []
1576
2177
  others = []
1577
2178
 
1578
- for k, sym in self.symbols.items():
2179
+ symbols, index = self._symbol_name_index()
2180
+ for k in index.candidates(callee_name):
2181
+ sym = symbols[k]
1579
2182
  if sym.name == callee_name or k.endswith(f"::{callee_name}"):
1580
2183
  if sym.file_path == caller_file:
1581
2184
  same_file.append(k)
@@ -1682,7 +2285,7 @@ class CodeGraph:
1682
2285
  except OSError:
1683
2286
  return ""
1684
2287
 
1685
- from src.skeletonizer import Skeletonizer
2288
+ from tokensafe.skeletonizer import Skeletonizer
1686
2289
  _, ext = os.path.splitext(full_path)
1687
2290
  ext = ext.lower()
1688
2291