tokensafe 4.12.4 → 4.13.1

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.
package/src/governor.py CHANGED
@@ -331,15 +331,17 @@ class ContextBudget:
331
331
  @classmethod
332
332
  def estimate(cls, tracker: MetricsTracker, session_id: str = "mcp_session",
333
333
  model: str = "", window_tokens: Optional[int] = None,
334
- history_tokens: int = 0, transcript_path: str = "") -> Dict[str, Any]:
335
- """Estimate context-window usage for the session.
336
-
337
- history_tokens / transcript_path upgrade the HUD from a pure
338
- instrumented floor to a semi-real estimate: the REAL mass of past
339
- conversation turns (measured from the transcript by the caller via
340
- HistoryCompactor) is counted into the history bucket. Callers that
341
- only know the transcript path can pass transcript_path instead; the
342
- transcript is probed with HistoryCompactor.measure_transcript."""
334
+ history_tokens: int = 0, transcript_path: str = "",
335
+ prompt_tokens: Optional[int] = None,
336
+ discover_transcript: bool = False) -> Dict[str, Any]:
337
+ """Estimate how full the context window is.
338
+
339
+ The primary figure is the last request's prompt size (`prompt_tokens`,
340
+ else the agent transcript's usage block). Cumulative instrumented
341
+ events and transcript text are a labelled floor only: summing them
342
+ across a session answers "how much did this session read", not "how
343
+ full is the window now", and must never trigger a critical threshold.
344
+ With neither source available the measurement is reported as unknown."""
343
345
  window = cls.resolve_window(model, window_tokens)
344
346
  breakdown = {"tools": 0, "history": 0, "prompts": 0, "other": 0}
345
347
  instrumented_events = 0
@@ -362,53 +364,127 @@ class ContextBudget:
362
364
  except Exception:
363
365
  pass
364
366
 
365
- # Real history mass (estimated label per METRICS.md): the transcript
366
- # content genuinely sits in the model context even though no TokenSafe
367
- # instrument metered it.
368
- transcript_mass = int(history_tokens or 0)
369
- if transcript_mass <= 0 and transcript_path:
367
+ # Measured prompt size of the last request: the only figure that answers
368
+ # "how full is the window". Cumulative event/history totals answer "how
369
+ # much did this session read", which is how 764k/200k (382%) happened.
370
+ measured: Optional[int] = None
371
+ measured_source = ""
372
+ measured_from = ""
373
+ if prompt_tokens is not None:
370
374
  try:
371
- from src.history_compactor import HistoryCompactor
372
- transcript_mass = HistoryCompactor.measure_transcript(transcript_path)
375
+ candidate = int(prompt_tokens)
376
+ except (TypeError, ValueError):
377
+ candidate = 0
378
+ if candidate > 0:
379
+ measured = candidate
380
+ measured_source = "caller.prompt_tokens"
381
+ if measured is None and (transcript_path or discover_transcript):
382
+ try:
383
+ from src.burn_monitor import collect_live_burn_snapshot
384
+ snap = collect_live_burn_snapshot(
385
+ agent="auto",
386
+ session_id=session_id or "",
387
+ transcript_path=transcript_path or "",
388
+ ) or {}
389
+ candidate = int(snap.get("last_input_tokens") or 0)
390
+ if candidate <= 0 and transcript_path:
391
+ try:
392
+ from src.transcript_analyzer import analyze_transcript
393
+ candidate = int(analyze_transcript(transcript_path).get("last_input_tokens") or 0)
394
+ except Exception:
395
+ candidate = 0
396
+ if candidate > 0:
397
+ measured = candidate
398
+ measured_source = f"transcript_usage:{snap.get('agent') or 'auto'}"
399
+ measured_from = str(snap.get("file_path") or transcript_path or "")
373
400
  except Exception:
374
- transcript_mass = 0
375
- if transcript_mass > breakdown["history"]:
376
- breakdown["history"] = transcript_mass
377
-
378
- used = sum(breakdown.values())
379
- pct = round(used / window * 100.0, 1) if window > 0 else 0.0
380
- if pct >= 95:
381
- threshold, recommendation = "critical", (
382
- "Context nearly exhausted. Call tokensafe:session_context(action='compact', ...) on the "
383
- "session transcript now, or start a fresh session carrying the ledger.")
384
- elif pct >= 80:
385
- threshold, recommendation = "warning", (
386
- "Context is heavy. Prefer tokensafe:smart_read_file with symbol= for "
387
- "further reads and consider tokensafe:session_context(action='compact', ...).")
388
- elif pct >= 50:
389
- threshold, recommendation = "notice", (
390
- "Half the estimated window is used. Keep reads surgical (symbol=, include_deps=false).")
391
- else:
392
- threshold, recommendation = "healthy", "Context budget healthy."
393
-
394
- if transcript_mass > 0:
395
- caveat = ("Semi-real estimate: history mass is measured from the session "
396
- "transcript; agent reasoning and output tokens stay invisible to "
397
- "local hooks, so this remains a lower bound.")
401
+ measured = None
402
+
403
+ transcript_mass = 0
404
+ if measured is None:
405
+ # Real history mass (estimated label per METRICS.md): the transcript
406
+ # content genuinely sits in the model context even though no TokenSafe
407
+ # instrument metered it.
408
+ transcript_mass = int(history_tokens or 0)
409
+ if transcript_mass <= 0 and transcript_path:
410
+ try:
411
+ from src.history_compactor import HistoryCompactor
412
+ transcript_mass = HistoryCompactor.measure_transcript(transcript_path)
413
+ except Exception:
414
+ transcript_mass = 0
415
+ if transcript_mass > breakdown["history"]:
416
+ breakdown["history"] = transcript_mass
417
+
418
+ def _band(p: float) -> Tuple[str, str]:
419
+ if p >= 95:
420
+ return "critical", (
421
+ "Context nearly exhausted. Call tokensafe:session_context(action='compact', ...) on the "
422
+ "session transcript now, or start a fresh session carrying the ledger.")
423
+ if p >= 80:
424
+ return "warning", (
425
+ "Context is heavy. Prefer tokensafe:smart_read_file with symbol= for "
426
+ "further reads and consider tokensafe:session_context(action='compact', ...).")
427
+ if p >= 50:
428
+ return "notice", (
429
+ "Half the estimated window is used. Keep reads surgical (symbol=, include_deps=false).")
430
+ return "healthy", "Context budget healthy."
431
+
432
+ estimate_used = sum(breakdown.values())
433
+ if measured is not None:
434
+ used: Optional[int] = measured
435
+ pct: Optional[float] = round(measured / window * 100.0, 1) if window > 0 else 0.0
436
+ measurement = "measured"
437
+ used_source = measured_source
438
+ threshold, recommendation = _band(pct or 0.0)
439
+ caveat = (
440
+ "Measured: prompt tokens of the last request, read from the agent "
441
+ "transcript usage block."
442
+ )
443
+ elif estimate_used > 0:
444
+ used = estimate_used
445
+ pct = round(estimate_used / window * 100.0, 1) if window > 0 else 0.0
446
+ measurement = "estimated"
447
+ used_source = "instrumented_events"
448
+ threshold, recommendation = _band(pct)
449
+ if threshold in ("critical", "warning"):
450
+ threshold = "notice"
451
+ recommendation = (
452
+ "Context size is an estimate (a floor, not the current prompt size), so no "
453
+ "compaction is triggered. Pass transcript_path or prompt_tokens for a measured figure.")
454
+ elif threshold == "notice":
455
+ recommendation = (
456
+ "Half the estimated window is used (floor estimate); keep reads surgical "
457
+ "(symbol=, include_deps=false).")
458
+ caveat = (
459
+ "Estimated floor: only TokenSafe-instrumented flows and transcript text are counted; "
460
+ "agent reasoning and output tokens are invisible, so this never triggers a critical "
461
+ "or warning threshold."
462
+ )
398
463
  else:
399
- caveat = ("Floor estimate: only TokenSafe-instrumented flows are counted "
400
- "(agent reasoning/output is invisible to local hooks).")
464
+ used = None
465
+ pct = None
466
+ measurement = "unknown"
467
+ used_source = ""
468
+ threshold = "unknown"
469
+ recommendation = (
470
+ "Context size is unknown: no transcript usage and no instrumented events were found. "
471
+ "Pass transcript_path (or prompt_tokens) to measure the last request.")
472
+ caveat = "Unknown: no measured prompt size is available."
401
473
 
402
474
  res = {
403
475
  "window_tokens": window,
404
- "used_estimated": used,
476
+ "used_tokens": used,
477
+ "used_estimated": used if used is not None else 0,
405
478
  "used_pct": pct,
479
+ "used_pct_is_estimate": measurement != "measured",
480
+ "measurement": measurement,
481
+ "used_source": used_source,
482
+ "measured_from": measured_from,
406
483
  "breakdown": breakdown,
407
484
  "instrumented_events": instrumented_events,
408
485
  "threshold": threshold,
409
486
  "recommendation": recommendation,
410
487
  "caveat": caveat,
411
- "measurement": "estimated",
412
488
  }
413
489
  try:
414
490
  from src.quality_score import ContextQualityScore
@@ -15,6 +15,7 @@ Powers:
15
15
  """
16
16
 
17
17
  import ast
18
+ import glob
18
19
  import hashlib
19
20
  import json
20
21
  import os
@@ -27,6 +28,7 @@ import time
27
28
  from typing import Dict, Set, List, Optional, Tuple, Any
28
29
 
29
30
  from src.paths import resolve_data_dir
31
+ from src.globmatch import GlobPatternError, compile_patterns, matches_any, split_negations
30
32
 
31
33
  IGNORED_DIRS = {
32
34
  ".git", ".hg", ".svn", "node_modules", "dist", "build", "venv", ".venv",
@@ -52,10 +54,9 @@ _SKIP_CALLS = {
52
54
  "true", "false", "null", "undefined", "None", "True", "False",
53
55
  }
54
56
 
55
- # v7: endpoint extraction learned chained router calls (Elysia/Fastify `.post("/x")`),
56
- # file-level framework prefixes and app.use('/p', router) mounts; older caches hold
57
- # an empty endpoint set for those stacks.
58
- _CACHE_SCHEMA_VERSION = 7
57
+ # v8: JS/TS extraction learned dynamic `import('./X')`, `React.lazy(() => import(...))`
58
+ # and literal `import.meta.glob` patterns; v7 caches have neither edge nor glob set.
59
+ _CACHE_SCHEMA_VERSION = 8
59
60
 
60
61
  _STATIC_ASSET_EXTS = {
61
62
  ".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico", ".webp",
@@ -91,6 +92,41 @@ def _is_generated_asset(rel_path: str, filename: str) -> bool:
91
92
  return "/public/assets/" in normalized or "/dist/assets/" in normalized
92
93
 
93
94
 
95
+ def _balanced_call_args(text: str, open_paren_idx: int) -> str:
96
+ """Text between `(` and its matching `)` (string literals aware)."""
97
+ depth = 0
98
+ quote = ""
99
+ i = open_paren_idx
100
+ while i < len(text):
101
+ ch = text[i]
102
+ if quote:
103
+ if ch == "\\":
104
+ i += 2
105
+ continue
106
+ if ch == quote:
107
+ quote = ""
108
+ elif ch in ("'", '"', "`"):
109
+ quote = ch
110
+ elif ch == "(":
111
+ depth += 1
112
+ elif ch == ")":
113
+ depth -= 1
114
+ if depth == 0:
115
+ return text[open_paren_idx + 1:i]
116
+ i += 1
117
+ return text[open_paren_idx + 1:]
118
+
119
+
120
+ def _glob_pattern_to_rel(root_dir: str, src_dir: str, pattern: str) -> str:
121
+ """Resolves a Vite file-relative glob to a repo-relative pattern."""
122
+ p = str(pattern or "").replace("\\", "/").strip()
123
+ if p.startswith("/"):
124
+ return p.lstrip("/")
125
+ base = os.path.join(root_dir, src_dir) if src_dir else root_dir
126
+ joined = os.path.normpath(os.path.join(base, p))
127
+ return os.path.relpath(joined, root_dir).replace("\\", "/")
128
+
129
+
94
130
  _BACKEND_ROUTE_PATTERNS = [
95
131
  # (regex, default_method). Group 1 is always the route literal; the declaring
96
132
  # receiver (if any) is read back from the match text with _RECEIVER_RE.
@@ -356,6 +392,7 @@ class CodeGraph:
356
392
  self.file_mtimes: Dict[str, float] = {} # file_rel_path -> mtime
357
393
  self.file_stats: Dict[str, Tuple[float, int]] = {} # file_rel_path -> (mtime, size)
358
394
  self.file_imports: Dict[str, Set[str]] = {} # file_rel_path -> raw imported modules
395
+ self.glob_imports: Dict[str, Set[str]] = {} # file_rel_path -> import.meta.glob patterns
359
396
  self.file_endpoints: Dict[str, List[Tuple[str, Optional[str], Optional[str]]]] = {} # rel_path -> [(norm_route, sym_key, http_method)]
360
397
  self.file_api_calls: Dict[str, List[Tuple[str, Optional[str], Optional[str]]]] = {} # rel_path -> [(norm_route, sym_key, http_method)]
361
398
  self.file_mounts: Dict[str, List[Tuple[str, str, str]]] = {} # rel_path -> [(url_prefix, router_ident, module_or_".")]
@@ -394,6 +431,7 @@ class CodeGraph:
394
431
  self.file_stats.clear()
395
432
  self.file_mtimes.clear()
396
433
  self.file_imports.clear()
434
+ self.glob_imports.clear()
397
435
  self.file_endpoints.clear()
398
436
  self.file_api_calls.clear()
399
437
  self.file_mounts.clear()
@@ -439,6 +477,13 @@ class CodeGraph:
439
477
  for row in cur.execute("SELECT rel_path, imported FROM file_imports").fetchall():
440
478
  self.file_imports.setdefault(row[0], set()).add(row[1])
441
479
 
480
+ self.glob_imports = {}
481
+ try:
482
+ for row in cur.execute("SELECT rel_path, pattern FROM glob_imports").fetchall():
483
+ self.glob_imports.setdefault(row[0], set()).add(row[1])
484
+ except sqlite3.OperationalError:
485
+ pass
486
+
442
487
  self.edges = {}
443
488
  self.rev_edges = {}
444
489
  for row in cur.execute("SELECT source, target FROM edges").fetchall():
@@ -507,6 +552,7 @@ class CodeGraph:
507
552
  }
508
553
  self.file_mtimes = {k: v[0] for k, v in self.file_stats.items()}
509
554
  self.file_imports = {k: set(v) for k, v in data.get("file_imports", {}).items()}
555
+ self.glob_imports = {k: set(v) for k, v in data.get("glob_imports", {}).items()}
510
556
  self.last_scanned = float(data.get("last_scanned", 0.0))
511
557
  # Migrate to SQLite format
512
558
  self._save_disk_cache()
@@ -541,6 +587,7 @@ class CodeGraph:
541
587
  cur.execute("CREATE TABLE symbols (sym_key TEXT PRIMARY KEY, rel_path TEXT, name TEXT, kind TEXT, line_start INTEGER, line_end INTEGER, signature TEXT)")
542
588
  cur.execute("CREATE TABLE file_symbols (rel_path TEXT, sym_key TEXT, idx INTEGER, PRIMARY KEY (rel_path, sym_key))")
543
589
  cur.execute("CREATE TABLE file_imports (rel_path TEXT, imported TEXT, PRIMARY KEY (rel_path, imported))")
590
+ cur.execute("CREATE TABLE glob_imports (rel_path TEXT, pattern TEXT, PRIMARY KEY (rel_path, pattern))")
544
591
  cur.execute("CREATE TABLE edges (source TEXT, target TEXT, PRIMARY KEY (source, target))")
545
592
  cur.execute("CREATE TABLE api_endpoints (rel_path TEXT, route TEXT, sym_key TEXT, method TEXT)")
546
593
  cur.execute("CREATE TABLE api_calls (rel_path TEXT, route TEXT, sym_key TEXT, method TEXT)")
@@ -577,6 +624,10 @@ class CodeGraph:
577
624
  "INSERT INTO file_imports VALUES (?, ?)",
578
625
  [(rel_path, imp) for rel_path, imps in self.file_imports.items() for imp in imps],
579
626
  )
627
+ cur.executemany(
628
+ "INSERT INTO glob_imports VALUES (?, ?)",
629
+ [(rel_path, pat) for rel_path, pats in self.glob_imports.items() for pat in pats],
630
+ )
580
631
  cur.executemany(
581
632
  "INSERT INTO edges VALUES (?, ?)",
582
633
  [(src, tgt) for src, tgts in self.edges.items() for tgt in tgts],
@@ -712,6 +763,7 @@ class CodeGraph:
712
763
  """Removes symbols, imports, and edges belonging to a file."""
713
764
  sym_keys = self.file_symbols.pop(rel_path, [])
714
765
  self.file_imports.pop(rel_path, None)
766
+ self.glob_imports.pop(rel_path, None)
715
767
  self.file_endpoints.pop(rel_path, None)
716
768
  self.file_api_calls.pop(rel_path, None)
717
769
  self.file_mounts.pop(rel_path, None)
@@ -750,6 +802,7 @@ class CodeGraph:
750
802
  file_node = f"file:{rel_path}"
751
803
  self.file_symbols[rel_path] = []
752
804
  self.file_imports[rel_path] = set()
805
+ self.glob_imports[rel_path] = set()
753
806
 
754
807
  _, ext = os.path.splitext(full_path)
755
808
  ext = ext.lower()
@@ -1035,6 +1088,8 @@ class CodeGraph:
1035
1088
  for mod in data.get("imports", []):
1036
1089
  self.file_imports[rel_path].add(mod)
1037
1090
  self.add_edge(file_node, f"mod:{mod}")
1091
+ for pattern in data.get("glob_imports", []):
1092
+ self.glob_imports[rel_path].add(pattern)
1038
1093
  for sym in data.get("imported_symbols", []):
1039
1094
  self.add_edge(file_node, f"sym:{sym}")
1040
1095
 
@@ -1141,6 +1196,21 @@ class CodeGraph:
1141
1196
  if mod:
1142
1197
  self.file_imports[rel_path].add(mod)
1143
1198
  self.add_edge(file_node, f"mod:{mod}")
1199
+ # Dynamic import: `import('./X')` and `React.lazy(() => import('./X'))`.
1200
+ # The static regex requires whitespace after `import`, so lazy routes
1201
+ # produced no edge and impact analysis reported "no consumers".
1202
+ for m in re.finditer(r"""\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)""", cleaned_text):
1203
+ mod = m.group(1)
1204
+ if mod:
1205
+ self.file_imports[rel_path].add(mod)
1206
+ self.add_edge(file_node, f"mod:{mod}")
1207
+ # Vite glob imports are patterns, not module specifiers: record them
1208
+ # and expand against the indexed file set in _resolve_local_imports.
1209
+ for m in re.finditer(r"""import\s*\.\s*meta\s*\.\s*glob(?:Eager)?\s*\(""", cleaned_text):
1210
+ args = _balanced_call_args(cleaned_text, m.end() - 1)
1211
+ for lit in re.findall(r"""['"`]([^'"`]+)['"`]""", args):
1212
+ if lit and "${" not in lit:
1213
+ self.glob_imports[rel_path].add(lit)
1144
1214
  elif ext == ".go":
1145
1215
  for m in re.finditer(r'^\s*import\s+(?:[A-Za-z_.]+\s+)?"([^"]+)"', cleaned_text, re.MULTILINE):
1146
1216
  self.file_imports[rel_path].add(m.group(1))
@@ -1343,6 +1413,68 @@ class CodeGraph:
1343
1413
  if target_rel != rel_path:
1344
1414
  self.add_edge(src_node, f"file:{target_rel}")
1345
1415
 
1416
+ # Expand `import.meta.glob` patterns last: the indexed file set is now
1417
+ # known, and brace patterns must be expanded rather than fnmatched.
1418
+ for rel_path, patterns in self.glob_imports.items():
1419
+ src_node = f"file:{rel_path}"
1420
+ src_dir = os.path.dirname(rel_path)
1421
+ positive, negative = split_negations(patterns)
1422
+ try:
1423
+ pos = [
1424
+ p
1425
+ for pattern in positive
1426
+ for p in compile_patterns(_glob_pattern_to_rel(self.root_dir, src_dir, pattern))
1427
+ ]
1428
+ neg = [
1429
+ p
1430
+ for pattern in negative
1431
+ for p in compile_patterns(_glob_pattern_to_rel(self.root_dir, src_dir, pattern))
1432
+ ]
1433
+ except GlobPatternError:
1434
+ continue
1435
+ if not pos:
1436
+ continue
1437
+ for target_rel in indexed_files:
1438
+ if target_rel == rel_path:
1439
+ continue
1440
+ if matches_any(pos, target_rel) and not matches_any(neg, target_rel):
1441
+ self.add_edge(src_node, f"file:{target_rel}")
1442
+
1443
+ # Vite globs often point at assets the graph does not index (locale
1444
+ # JSON, SVG, markdown). Register the matched files as plain file
1445
+ # nodes so impact analysis can still answer "who imports this".
1446
+ for pattern in positive:
1447
+ rel_pattern = _glob_pattern_to_rel(self.root_dir, src_dir, pattern)
1448
+ if os.path.isabs(rel_pattern) or rel_pattern.startswith(".."):
1449
+ continue
1450
+ try:
1451
+ fs_matches = glob.glob(os.path.join(self.root_dir, rel_pattern), recursive=True)
1452
+ except (OSError, re.error):
1453
+ continue
1454
+ for full_path in fs_matches[:200]:
1455
+ if not os.path.isfile(full_path):
1456
+ continue
1457
+ target_rel = os.path.relpath(full_path, self.root_dir).replace("\\", "/")
1458
+ if target_rel == rel_path:
1459
+ continue
1460
+ if any(part in IGNORED_DIRS for part in target_rel.split("/")):
1461
+ continue
1462
+ if _is_generated_asset(target_rel, os.path.basename(target_rel)):
1463
+ continue
1464
+ if matches_any(neg, target_rel):
1465
+ continue
1466
+ if target_rel not in self.file_stats and target_rel not in self.file_symbols:
1467
+ try:
1468
+ st = os.stat(full_path)
1469
+ if not stat.S_ISREG(st.st_mode) or st.st_size > 2 * 1024 * 1024:
1470
+ continue
1471
+ except OSError:
1472
+ continue
1473
+ self.file_stats[target_rel] = (st.st_mtime, st.st_size)
1474
+ self.file_mtimes[target_rel] = st.st_mtime
1475
+ self.file_symbols.setdefault(target_rel, [])
1476
+ self.add_edge(src_node, f"file:{target_rel}")
1477
+
1346
1478
  @staticmethod
1347
1479
  def _resolve_single_import(
1348
1480
  mod: str,
@@ -2032,6 +2164,91 @@ class CodeGraph:
2032
2164
  )
2033
2165
  return result
2034
2166
 
2167
+ def _suggest_targets(self, target: str, limit: int = 5) -> List[str]:
2168
+ """Basename candidates for a target that is not in the graph."""
2169
+ base = os.path.basename((target or "").replace("\\", "/")).lower()
2170
+ if not base:
2171
+ return []
2172
+ pool = sorted(set(self.file_stats) | set(self.file_symbols))
2173
+ exact = [p for p in pool if os.path.basename(p).lower() == base]
2174
+ if exact:
2175
+ return exact[:limit]
2176
+ stem = base.rsplit(".", 1)[0]
2177
+ if len(stem) < 3:
2178
+ return []
2179
+ return [p for p in pool if stem in os.path.basename(p).lower()][:limit]
2180
+
2181
+ def _text_references(
2182
+ self,
2183
+ name: str,
2184
+ target_file: str = "",
2185
+ max_files: int = 800,
2186
+ deadline_s: float = 3.0,
2187
+ max_hits: int = 20,
2188
+ ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
2189
+ """Bounded grep for a component/symbol name when import edges miss.
2190
+
2191
+ Lazy imports, string-built module paths and JSX-only usage leave no edge
2192
+ in the graph; an empty `directDependents` must not read as "no
2193
+ consumers". Every hit is labelled probable, never confirmed.
2194
+ """
2195
+ token = os.path.basename((name or "").replace("\\", "/")).rsplit(".", 1)[0]
2196
+ token = re.sub(r"[^A-Za-z0-9_$]", "", token)
2197
+ indexed = [
2198
+ p
2199
+ for p in sorted(set(self.file_stats) | set(self.file_symbols))
2200
+ if p != target_file and not _is_generated_asset(p, os.path.basename(p))
2201
+ ]
2202
+ total = len(indexed)
2203
+ if len(token) < 3 or not indexed:
2204
+ return [], {"scanned_files": 0, "total_files": total, "partial": False}
2205
+ word_re = re.compile(rf"(?<![\w$]){re.escape(token)}(?![\w$])")
2206
+ jsx_re = re.compile(rf"<\s*{re.escape(token)}(?=[\s/>])")
2207
+ call_re = re.compile(rf"(?<![\w$.]){re.escape(token)}\s*\(")
2208
+ target_dir = os.path.dirname(target_file)
2209
+ ordered = sorted(
2210
+ indexed,
2211
+ key=lambda p: (
2212
+ 0 if target_dir and os.path.dirname(p) == target_dir else 1,
2213
+ 0 if token.lower() in os.path.basename(p).lower() else 1,
2214
+ p,
2215
+ ),
2216
+ )
2217
+ start = time.monotonic()
2218
+ hits: List[Dict[str, Any]] = []
2219
+ scanned = 0
2220
+ for rel in ordered:
2221
+ if scanned >= max_files or time.monotonic() - start > deadline_s:
2222
+ break
2223
+ full = os.path.join(self.root_dir, rel)
2224
+ try:
2225
+ if os.path.getsize(full) > 1024 * 1024:
2226
+ continue
2227
+ with open(full, "r", encoding="utf-8", errors="replace") as fh:
2228
+ lines = fh.readlines()
2229
+ except OSError:
2230
+ continue
2231
+ scanned += 1
2232
+ for line_no, line in enumerate(lines, 1):
2233
+ if not word_re.search(line):
2234
+ continue
2235
+ if jsx_re.search(line):
2236
+ kind = "jsx"
2237
+ elif call_re.search(line):
2238
+ kind = "call"
2239
+ else:
2240
+ kind = "identifier"
2241
+ hits.append({
2242
+ "file": rel,
2243
+ "line": line_no,
2244
+ "kind": kind,
2245
+ "text": line.strip()[:120],
2246
+ "confidence": "probable",
2247
+ })
2248
+ if len(hits) >= max_hits:
2249
+ return hits, {"scanned_files": scanned, "total_files": total, "partial": True}
2250
+ return hits, {"scanned_files": scanned, "total_files": total, "partial": scanned < total}
2251
+
2035
2252
  def get_static_impact(self, target: str, max_depth: int = 3) -> Dict[str, Any]:
2036
2253
  """
2037
2254
  Static impact analysis over the AST graph: reverse-dependency walk
@@ -2043,20 +2260,47 @@ class CodeGraph:
2043
2260
  "sourceAdapter": "tokensafe-graph-engine",
2044
2261
  "confidence": "probable",
2045
2262
  }
2046
- t = (target or "").strip()
2047
- if not t:
2048
- return {"target": t, "mode": "STATIC_IMPACT", "error": "target is required", "evidence": evidence}
2263
+ raw = (target or "").strip()
2264
+ if not raw:
2265
+ return {
2266
+ "target": raw,
2267
+ "targetResolved": False,
2268
+ "mode": "STATIC_IMPACT",
2269
+ "error": "target is required",
2270
+ "warnings": ["target is required"],
2271
+ "directDependents": [],
2272
+ "transitiveDependents": [],
2273
+ "textLevelReferences": [],
2274
+ "counts": {"direct": 0, "transitive": 0, "textLevel": 0},
2275
+ "evidence": evidence,
2276
+ }
2277
+
2278
+ # `path=` reaches this method absolute (MCP injects the absolute file
2279
+ # target); without normalisation no repo-relative node could match and
2280
+ # the empty result read as "no consumers".
2281
+ t = raw[5:] if raw.startswith("file:") else raw
2282
+ t = self._as_repo_rel(t)
2283
+ indexed_files = set(self.file_stats) | set(self.file_symbols)
2049
2284
 
2050
2285
  start_nodes: Set[str] = set()
2051
- if t.startswith("file:"):
2052
- start_nodes.add(t)
2286
+ if raw.startswith("file:") and t in indexed_files:
2287
+ start_nodes.add(f"file:{t}")
2288
+ if t in indexed_files:
2289
+ start_nodes.add(f"file:{t}")
2053
2290
  for sk, sym in self.symbols.items():
2054
2291
  if t.lower() in sym.name.lower() or t.lower() in sym.file_path.lower():
2055
2292
  start_nodes.add(sk)
2056
- for rel_path in self.file_symbols:
2293
+ for rel_path in indexed_files:
2057
2294
  if t.lower() in rel_path.lower():
2058
2295
  start_nodes.add(f"file:{rel_path}")
2059
2296
 
2297
+ target_resolved = bool(start_nodes)
2298
+ warnings: List[str] = []
2299
+ suggestions: List[str] = []
2300
+ if not target_resolved:
2301
+ suggestions = self._suggest_targets(t)
2302
+ warnings.append("target not found in the graph index: no static import edges were walked")
2303
+
2060
2304
  visited: Dict[str, int] = {}
2061
2305
  frontier = [(n, 0) for n in start_nodes]
2062
2306
  while frontier:
@@ -2078,8 +2322,26 @@ class CodeGraph:
2078
2322
  return {"type": "symbol", "name": sym.name, "kind": sym.kind, "file": sym.file_path}
2079
2323
  return {"type": "node", "id": node}
2080
2324
 
2081
- direct = [_node_info(n) for n, d in visited.items() if d == 1 and n not in start_nodes]
2082
- transitive = [_node_info(n) for n, d in visited.items() if d > 1]
2325
+ direct_all = [_node_info(n) for n, d in visited.items() if d == 1 and n not in start_nodes]
2326
+ transitive_all = [_node_info(n) for n, d in visited.items() if d > 1]
2327
+ if len(direct_all) > 20:
2328
+ warnings.append(f"directDependents truncated at 20 of {len(direct_all)}")
2329
+ if len(transitive_all) > 20:
2330
+ warnings.append(f"transitiveDependents truncated at 20 of {len(transitive_all)}")
2331
+
2332
+ text_refs, text_cov = self._text_references(
2333
+ t, target_file=t if t in indexed_files else ""
2334
+ )
2335
+ if not direct_all and not transitive_all and text_refs:
2336
+ warnings.append(
2337
+ f"no static import edge reaches this target; {len(text_refs)} probable "
2338
+ "text-level reference(s) found (lazy import, dynamic path or JSX-only usage)"
2339
+ )
2340
+ if text_cov.get("partial"):
2341
+ warnings.append(
2342
+ "text-level reference scan was bounded "
2343
+ f"({text_cov.get('scanned_files')}/{text_cov.get('total_files')} files)"
2344
+ )
2083
2345
 
2084
2346
  frontend_callers = []
2085
2347
  for link in self.api_links:
@@ -2097,9 +2359,25 @@ class CodeGraph:
2097
2359
 
2098
2360
  return {
2099
2361
  "target": t,
2362
+ "targetRequested": raw,
2363
+ "targetResolved": target_resolved,
2100
2364
  "mode": "STATIC_IMPACT",
2101
- "directDependents": direct[:20],
2102
- "transitiveDependents": transitive[:20],
2365
+ "directDependents": direct_all[:20],
2366
+ "transitiveDependents": transitive_all[:20],
2367
+ "textLevelReferences": text_refs[:20],
2368
+ "counts": {
2369
+ "direct": len(direct_all),
2370
+ "transitive": len(transitive_all),
2371
+ "textLevel": len(text_refs),
2372
+ },
2373
+ "truncated": {
2374
+ "direct": len(direct_all) > 20,
2375
+ "transitive": len(transitive_all) > 20,
2376
+ "textLevel": len(text_refs) > 20,
2377
+ },
2378
+ "textLevelCoverage": text_cov,
2379
+ "warnings": warnings,
2380
+ "suggestions": suggestions,
2103
2381
  "crossStack": {
2104
2382
  "frontendCallers": frontend_callers[:20],
2105
2383
  "count": len(frontend_callers),