tokensafe 4.4.9 → 4.5.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.
Files changed (65) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/bin/agy-tokens +10 -1
  3. package/bin/tokensafe.js +2 -1
  4. package/hooks/claude_code_hook.py +38 -126
  5. package/hooks/cursor_hook.py +45 -1
  6. package/hooks/kimi_hook.py +46 -90
  7. package/hooks/pre_invocation.py +23 -4
  8. package/hooks/pre_tool_use.py +40 -22
  9. package/hooks/session_start.py +44 -15
  10. package/hooks/zcode_hook.py +95 -0
  11. package/hooks.json +1 -1
  12. package/kimi.plugin.json +17 -1
  13. package/mcp_config.json +24 -1
  14. package/package.json +1 -1
  15. package/plugin.json +1 -1
  16. package/rules/AGENTS.md +24 -21
  17. package/server.json +3 -3
  18. package/skills/token-optimizer/SKILL.md +61 -76
  19. package/skills/token-optimizer/references/mcp-tools.md +32 -132
  20. package/src/adapter_core.py +231 -7
  21. package/src/batch_editor.py +403 -0
  22. package/src/batch_search.py +428 -0
  23. package/src/burn_monitor.py +581 -0
  24. package/src/cache_normalizer.py +2 -0
  25. package/src/cli.py +85 -4
  26. package/src/compactor.py +1 -1
  27. package/src/dashboard.py +17 -9
  28. package/src/diff_slicer.py +1 -1
  29. package/src/distiller.py +11 -1
  30. package/src/environment_auditor.py +30 -6
  31. package/src/format_parsers/ansi.py +1 -1
  32. package/src/format_parsers/lockfiles.py +22 -17
  33. package/src/format_parsers/tabular.py +6 -3
  34. package/src/fts_index.py +26 -20
  35. package/src/governor.py +2 -2
  36. package/src/graph_engine.py +232 -52
  37. package/src/guard.py +3 -3
  38. package/src/image_downscale.py +26 -0
  39. package/src/installer.py +61 -48
  40. package/src/license_manager.py +49 -16
  41. package/src/live_relay.py +9 -8
  42. package/src/mcp_proxy.py +13 -7
  43. package/src/mcp_server.py +758 -26
  44. package/src/metrics.py +10 -1
  45. package/src/mistakes.py +4 -2
  46. package/src/oumv_gateway.py +81 -7
  47. package/src/paths.py +4 -1
  48. package/src/proxy.py +302 -123
  49. package/src/result_ledger.py +39 -1
  50. package/src/schema_slicer.py +40 -18
  51. package/src/scoped_search.py +66 -23
  52. package/src/skeletonizer.py +22 -11
  53. package/src/slicer.py +6 -4
  54. package/src/snapshot.py +249 -0
  55. package/src/stash.py +37 -7
  56. package/src/superseded.py +42 -23
  57. package/src/syntax_guard.py +86 -0
  58. package/src/team_cache.py +3 -0
  59. package/src/telemetry_sync.py +66 -53
  60. package/src/thinking_fold.py +50 -12
  61. package/src/transcript_analyzer.py +483 -0
  62. package/src/treesitter_backend.py +2 -0
  63. package/src/type_slicer.py +60 -18
  64. package/src/version_checker.py +1 -1
  65. package/src/web_reader.py +55 -22
@@ -22,6 +22,7 @@ import re
22
22
  import sqlite3
23
23
  import stat
24
24
  import tempfile
25
+ import threading
25
26
  import time
26
27
  from typing import Dict, Set, List, Optional, Tuple, Any
27
28
 
@@ -51,7 +52,7 @@ _SKIP_CALLS = {
51
52
  "true", "false", "null", "undefined", "None", "True", "False",
52
53
  }
53
54
 
54
- _CACHE_SCHEMA_VERSION = 3
55
+ _CACHE_SCHEMA_VERSION = 5
55
56
 
56
57
  _STATIC_ASSET_EXTS = {
57
58
  ".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico", ".webp",
@@ -62,32 +63,57 @@ _STATIC_ASSET_EXTS = {
62
63
 
63
64
  _BACKEND_ROUTE_PATTERNS = [
64
65
  # Python: @app.get("/users"), @router.post('/login'), @bp.route('/data')
65
- re.compile(r'@(?:app|router|api|bp)\.(?:get|post|put|delete|patch|route)\(\s*["\']([^"\']+)["\']', re.IGNORECASE),
66
+ (re.compile(r'@(?:app|router|api|bp)\.(?:get|post|put|delete|patch|route)\(\s*["\']([^"\']+)["\']', re.IGNORECASE), None),
66
67
  # JS/TS: app.get("/users", ...), router.post('/login', ...)
67
- re.compile(r'(?<!@)\b(?:app|router|server|fastify)\.(?:get|post|put|delete|patch)\(\s*["\']([^"\']+)["\']', re.IGNORECASE),
68
+ (re.compile(r'(?<!@)\b(?:app|router|server|fastify)\.(?:get|post|put|delete|patch)\(\s*["\']([^"\']+)["\']', re.IGNORECASE), None),
68
69
  # Java/Kotlin Spring: @GetMapping("/users"), @PostMapping(value = "/login"), @RequestMapping("/api")
69
- re.compile(r'@(?:Get|Post|Put|Delete|Patch|Request)Mapping\(\s*(?:value\s*=\s*)?["\']([^"\']+)["\']', re.IGNORECASE),
70
+ (re.compile(r'@(?:Get|Post|Put|Delete|Patch|Request)Mapping\(\s*(?:value\s*=\s*)?["\']([^"\']+)["\']', re.IGNORECASE), None),
70
71
  # Go Gin/Echo/Fiber: r.GET("/users", ...), router.POST('/login', ...)
71
- re.compile(r'\b(?:r|router|g|e|app)\.(?:GET|POST|PUT|DELETE|PATCH)\(\s*["\']([^"\']+)["\']'),
72
+ (re.compile(r'\b(?:r|router|g|e|app)\.(?:GET|POST|PUT|DELETE|PATCH)\(\s*["\']([^"\']+)["\']'), None),
72
73
  # Go net/http: http.HandleFunc("/users", ...)
73
- re.compile(r'http\.HandleFunc\(\s*["\']([^"\']+)["\']'),
74
+ (re.compile(r'http\.HandleFunc\(\s*["\']([^"\']+)["\']'), None),
74
75
  # C# ASP.NET Core: [HttpGet("/users")], [Route("api/users")]
75
- re.compile(r'\[(?:Http(?:Get|Post|Put|Delete|Patch)|Route)\(\s*["\']([^"\']+)["\']'),
76
+ (re.compile(r'\[(?:Http(?:Get|Post|Put|Delete|Patch)|Route)\(\s*["\']([^"\']+)["\']'), None),
76
77
  # PHP Laravel: Route::get('/users', ...), Route::post('/login', ...)
77
- re.compile(r'Route::(?:get|post|put|delete|patch)\(\s*["\']([^"\']+)["\']'),
78
+ (re.compile(r'Route::(?:get|post|put|delete|patch)\(\s*["\']([^"\']+)["\']'), None),
78
79
  ]
79
80
 
80
81
  _FRONTEND_CALL_PATTERNS = [
81
- # fetch("/api/users") or fetch(`/api/users/${id}`)
82
- re.compile(r'\bfetch\(\s*[`"\']([^`"\'?#]+)'),
82
+ # fetch("/api/users") or fetch(`/api/users/${id}`) (method unknown: depends on init options)
83
+ (re.compile(r'\bfetch\(\s*[`"\']([^`"\'?#]+)'), None),
83
84
  # axios.get("/api/users"), api.post(`/api/users/${id}`), client.get, etc.
84
- re.compile(r'\b(?:axios|api|client|httpClient|ky)\.(?:get|post|put|delete|patch)\(\s*[`"\']([^`"\'?#]+)'),
85
- # useSWR("/api/users")
86
- re.compile(r'\buseSWR\(\s*[`"\']([^`"\'?#]+)'),
87
- # axios("/api/users")
88
- re.compile(r'\baxios\(\s*[`"\']([^`"\'?#]+)'),
85
+ (re.compile(r'\b(?:axios|api|client|httpClient|ky)\.(?:get|post|put|delete|patch)\(\s*[`"\']([^`"\'?#]+)'), None),
86
+ # useSWR("/api/users") — semantically always GET
87
+ (re.compile(r'\buseSWR\(\s*[`"\']([^`"\'?#]+)'), "GET"),
88
+ # axios("/api/users") (method unknown: depends on config)
89
+ (re.compile(r'\baxios\(\s*[`"\']([^`"\'?#]+)'), None),
89
90
  ]
90
91
 
92
+ # HTTP method extraction from route-declaration / API-call matched text.
93
+ _HTTP_METHOD_ANNOTATION_RE = re.compile(r'(?i)@(get|post|put|delete|patch)mapping\b')
94
+ _HTTP_METHOD_BRACKET_RE = re.compile(r'(?i)\[\s*http(get|post|put|delete|patch)\b')
95
+ _HTTP_METHOD_CALL_RE = re.compile(r'(?i)(?:\.|::)\s*(get|post|put|delete|patch|head|options)\s*\(')
96
+
97
+
98
+ def _match_http_method(matched_text: str) -> Optional[str]:
99
+ """Extracts the HTTP verb from a matched route-declaration or client-call fragment.
100
+
101
+ Searches only the matched fragment (method word always precedes the route string),
102
+ so route segments like `/get-started` never produce a false method.
103
+ """
104
+ if not matched_text:
105
+ return None
106
+ m = _HTTP_METHOD_ANNOTATION_RE.search(matched_text)
107
+ if m:
108
+ return m.group(1).upper()
109
+ m = _HTTP_METHOD_BRACKET_RE.search(matched_text)
110
+ if m:
111
+ return m.group(1).upper()
112
+ m = _HTTP_METHOD_CALL_RE.search(matched_text)
113
+ if m:
114
+ return m.group(1).upper()
115
+ return None
116
+
91
117
  _NEXT_APP_ROUTE_RE = re.compile(r'^(?:src/)?app/(api/.+?)/route\.[a-zA-Z0-9]+$')
92
118
  _NEXT_PAGES_ROUTE_RE = re.compile(r'^(?:src/)?pages/(api/.+?)\.[a-zA-Z0-9]+$')
93
119
  _CONTROLLER_PREFIX_RE = re.compile(r'@RequestMapping\(\s*(?:value\s*=\s*)?["\']([^"\']+)["\']|\[Route\(\s*["\']([^"\']+)["\']\)', re.IGNORECASE)
@@ -211,8 +237,9 @@ class CodeGraph:
211
237
  self.file_mtimes: Dict[str, float] = {} # file_rel_path -> mtime
212
238
  self.file_stats: Dict[str, Tuple[float, int]] = {} # file_rel_path -> (mtime, size)
213
239
  self.file_imports: Dict[str, Set[str]] = {} # file_rel_path -> raw imported modules
214
- self.file_endpoints: Dict[str, List[Tuple[str, Optional[str]]]] = {} # rel_path -> [(norm_route, sym_key)]
215
- self.file_api_calls: Dict[str, List[Tuple[str, Optional[str]]]] = {} # rel_path -> [(norm_route, sym_key)]
240
+ self.file_endpoints: Dict[str, List[Tuple[str, Optional[str], Optional[str]]]] = {} # rel_path -> [(norm_route, sym_key, http_method)]
241
+ self.file_api_calls: Dict[str, List[Tuple[str, Optional[str], Optional[str]]]] = {} # rel_path -> [(norm_route, sym_key, http_method)]
242
+ self.api_links: List[Dict[str, Any]] = [] # cross-stack edges: frontend call -> backend endpoint
216
243
  self.last_scanned: float = 0.0
217
244
  self.backend: str = self._detect_backend()
218
245
 
@@ -249,6 +276,7 @@ class CodeGraph:
249
276
  self.file_imports.clear()
250
277
  self.file_endpoints.clear()
251
278
  self.file_api_calls.clear()
279
+ self.api_links.clear()
252
280
 
253
281
  def _load_disk_cache(self) -> bool:
254
282
  path = self._cache_path()
@@ -299,18 +327,29 @@ class CodeGraph:
299
327
 
300
328
  self.file_endpoints = {}
301
329
  try:
302
- for row in cur.execute("SELECT rel_path, route, sym_key FROM api_endpoints").fetchall():
303
- self.file_endpoints.setdefault(row[0], []).append((row[1], row[2]))
330
+ for row in cur.execute("SELECT rel_path, route, sym_key, method FROM api_endpoints").fetchall():
331
+ method = row[3] if len(row) > 3 else None
332
+ self.file_endpoints.setdefault(row[0], []).append((row[1], row[2], method))
304
333
  except sqlite3.OperationalError:
305
334
  pass
306
335
 
307
336
  self.file_api_calls = {}
308
337
  try:
309
- for row in cur.execute("SELECT rel_path, route, sym_key FROM api_calls").fetchall():
310
- self.file_api_calls.setdefault(row[0], []).append((row[1], row[2]))
338
+ for row in cur.execute("SELECT rel_path, route, sym_key, method FROM api_calls").fetchall():
339
+ method = row[3] if len(row) > 3 else None
340
+ self.file_api_calls.setdefault(row[0], []).append((row[1], row[2], method))
311
341
  except sqlite3.OperationalError:
312
342
  pass
313
343
 
344
+ self.api_links = []
345
+ try:
346
+ for row in cur.execute("SELECT link_json FROM api_links").fetchall():
347
+ link_obj = json.loads(row[0])
348
+ if isinstance(link_obj, dict):
349
+ self.api_links.append(link_obj)
350
+ except Exception:
351
+ pass
352
+
314
353
  self.last_scanned = float(meta.get("last_scanned", 0.0))
315
354
  return True
316
355
  finally:
@@ -375,8 +414,9 @@ class CodeGraph:
375
414
  cur.execute("CREATE TABLE file_symbols (rel_path TEXT, sym_key TEXT, idx INTEGER, PRIMARY KEY (rel_path, sym_key))")
376
415
  cur.execute("CREATE TABLE file_imports (rel_path TEXT, imported TEXT, PRIMARY KEY (rel_path, imported))")
377
416
  cur.execute("CREATE TABLE edges (source TEXT, target TEXT, PRIMARY KEY (source, target))")
378
- cur.execute("CREATE TABLE api_endpoints (rel_path TEXT, route TEXT, sym_key TEXT)")
379
- cur.execute("CREATE TABLE api_calls (rel_path TEXT, route TEXT, sym_key TEXT)")
417
+ cur.execute("CREATE TABLE api_endpoints (rel_path TEXT, route TEXT, sym_key TEXT, method TEXT)")
418
+ cur.execute("CREATE TABLE api_calls (rel_path TEXT, route TEXT, sym_key TEXT, method TEXT)")
419
+ cur.execute("CREATE TABLE api_links (link_json TEXT)")
380
420
 
381
421
  cur.executemany(
382
422
  "INSERT INTO graph_meta VALUES (?, ?)",
@@ -413,12 +453,16 @@ class CodeGraph:
413
453
  [(src, tgt) for src, tgts in self.edges.items() for tgt in tgts],
414
454
  )
415
455
  cur.executemany(
416
- "INSERT INTO api_endpoints VALUES (?, ?, ?)",
417
- [(rel, ep[0], ep[1]) for rel, eps in self.file_endpoints.items() for ep in eps],
456
+ "INSERT INTO api_endpoints VALUES (?, ?, ?, ?)",
457
+ [(rel, ep[0], ep[1], ep[2] if len(ep) > 2 else None) for rel, eps in self.file_endpoints.items() for ep in eps],
458
+ )
459
+ cur.executemany(
460
+ "INSERT INTO api_calls VALUES (?, ?, ?, ?)",
461
+ [(rel, call[0], call[1], call[2] if len(call) > 2 else None) for rel, calls in self.file_api_calls.items() for call in calls],
418
462
  )
419
463
  cur.executemany(
420
- "INSERT INTO api_calls VALUES (?, ?, ?)",
421
- [(rel, call[0], call[1]) for rel, calls in self.file_api_calls.items() for call in calls],
464
+ "INSERT INTO api_links VALUES (?)",
465
+ [(json.dumps(lk, ensure_ascii=False),) for lk in self.api_links],
422
466
  )
423
467
  con.commit()
424
468
  finally:
@@ -478,6 +522,11 @@ class CodeGraph:
478
522
  try:
479
523
  st = os.stat(full_path)
480
524
  if not stat.S_ISREG(st.st_mode) or st.st_size > 2 * 1024 * 1024:
525
+ if rel_path in self.file_symbols or rel_path in self.file_stats:
526
+ self._purge_file(rel_path)
527
+ self.file_stats.pop(rel_path, None)
528
+ self.file_mtimes.pop(rel_path, None)
529
+ reindexed += 1
481
530
  continue
482
531
  sig = (st.st_mtime, st.st_size)
483
532
  except OSError:
@@ -614,13 +663,14 @@ class CodeGraph:
614
663
  for sk in sym_keys:
615
664
  s = self.symbols.get(sk)
616
665
  if s and s.name.upper() in {"GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS", "HANDLER", "DEFAULT"}:
617
- self.file_endpoints[rel_path].append((norm_route, sk))
666
+ method = s.name.upper() if s.name.upper() in {"GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"} else None
667
+ self.file_endpoints[rel_path].append((norm_route, sk, method))
618
668
  matched_any = True
619
669
  if not matched_any:
620
- self.file_endpoints[rel_path].append((norm_route, None))
670
+ self.file_endpoints[rel_path].append((norm_route, None, None))
621
671
 
622
672
  # 2. Backend route definitions
623
- for rx in _BACKEND_ROUTE_PATTERNS:
673
+ for rx, _default_method in _BACKEND_ROUTE_PATTERNS:
624
674
  for match in rx.finditer(content):
625
675
  route_raw = match.group(1)
626
676
  if class_prefix and not route_raw.startswith(class_prefix):
@@ -632,10 +682,11 @@ class CodeGraph:
632
682
  continue
633
683
  line_no = content[:match.start()].count("\n") + 1
634
684
  sym_key = self._find_enclosing_symbol(rel_path, line_no)
635
- self.file_endpoints[rel_path].append((norm_route, sym_key))
685
+ method = _match_http_method(match.group(0))
686
+ self.file_endpoints[rel_path].append((norm_route, sym_key, method))
636
687
 
637
688
  # 3. Frontend API call sites
638
- for rx in _FRONTEND_CALL_PATTERNS:
689
+ for rx, default_method in _FRONTEND_CALL_PATTERNS:
639
690
  for match in rx.finditer(content):
640
691
  route_raw = match.group(1)
641
692
  norm_route = _normalize_route_path(route_raw)
@@ -643,7 +694,8 @@ class CodeGraph:
643
694
  continue
644
695
  line_no = content[:match.start()].count("\n") + 1
645
696
  sym_key = self._find_enclosing_symbol(rel_path, line_no)
646
- self.file_api_calls[rel_path].append((norm_route, sym_key))
697
+ method = _match_http_method(match.group(0)) or default_method
698
+ self.file_api_calls[rel_path].append((norm_route, sym_key, method))
647
699
 
648
700
  @staticmethod
649
701
  def _route_matches(path: str, pattern_route: str) -> bool:
@@ -669,32 +721,35 @@ class CodeGraph:
669
721
  """
670
722
  Cross-boundary semantic linking between frontend client API calls
671
723
  and backend route endpoints across languages and frameworks.
724
+ Also records OUMV cross-stack relationships (with evidence) in `api_links`.
672
725
  """
726
+ self.api_links = []
673
727
  try:
674
- endpoint_map: Dict[str, List[Tuple[str, Optional[str]]]] = {}
728
+ endpoint_map: Dict[str, List[Tuple[str, Optional[str], Optional[str]]]] = {}
675
729
  for rel_path, endpoints in self.file_endpoints.items():
676
- for norm_route, sym_key in endpoints:
730
+ for norm_route, sym_key, method in endpoints:
677
731
  if norm_route:
678
- endpoint_map.setdefault(norm_route, []).append((rel_path, sym_key))
732
+ endpoint_map.setdefault(norm_route, []).append((rel_path, sym_key, method))
679
733
 
680
734
  if not endpoint_map:
681
735
  return
682
736
 
737
+ seen_links = set()
683
738
  for caller_rel, calls in self.file_api_calls.items():
684
739
  caller_file_node = f"file:{caller_rel}"
685
- for norm_route, caller_sym in calls:
740
+ for norm_route, caller_sym, caller_method in calls:
686
741
  if not norm_route:
687
742
  continue
688
- matched_endpoints: List[Tuple[str, Optional[str]]] = []
743
+ matched_endpoints: List[Tuple[str, str, Optional[str], Optional[str]]] = []
689
744
  if norm_route in endpoint_map:
690
- matched_endpoints.extend(endpoint_map[norm_route])
745
+ matched_endpoints.extend((norm_route, rel, sym, m) for (rel, sym, m) in endpoint_map[norm_route])
691
746
 
692
747
  for ep_route, eps in endpoint_map.items():
693
748
  if ep_route != norm_route and ("*" in ep_route or "*" in norm_route):
694
749
  if self._route_matches(norm_route, ep_route):
695
- matched_endpoints.extend(eps)
750
+ matched_endpoints.extend((ep_route, rel, sym, m) for (rel, sym, m) in eps)
696
751
 
697
- for ep_rel, ep_sym in matched_endpoints:
752
+ for ep_route, ep_rel, ep_sym, ep_method in matched_endpoints:
698
753
  if ep_rel == caller_rel:
699
754
  continue
700
755
  ep_file_node = f"file:{ep_rel}"
@@ -704,6 +759,26 @@ class CodeGraph:
704
759
  dst = ep_sym or ep_file_node
705
760
  if src != dst:
706
761
  self.add_edge(src, dst)
762
+
763
+ link_key = (caller_rel, caller_sym or "", norm_route, ep_rel, ep_sym or "", ep_route)
764
+ if link_key not in seen_links:
765
+ seen_links.add(link_key)
766
+ self.api_links.append({
767
+ "source": {
768
+ "type": "frontend.action",
769
+ "route": norm_route,
770
+ "method": caller_method,
771
+ "file": caller_rel,
772
+ "symbol": caller_sym,
773
+ },
774
+ "target": {
775
+ "type": "backend.endpoint",
776
+ "route": ep_route,
777
+ "method": ep_method,
778
+ "file": ep_rel,
779
+ "symbol": ep_sym,
780
+ },
781
+ })
707
782
  except Exception:
708
783
  pass
709
784
 
@@ -1496,11 +1571,12 @@ class CodeGraph:
1496
1571
  "level": "L0",
1497
1572
  "mode": "STATIC_OFFLINE_PULSE",
1498
1573
  "status": "OFFLINE_STATIC",
1499
- "summary": f"Indexed {len(self.file_symbols)} files, {len(self.symbols)} symbols, {endpoints_count} API endpoints, {calls_count} client calls",
1574
+ "summary": f"Indexed {len(self.file_symbols)} files, {len(self.symbols)} symbols, {endpoints_count} API endpoints, {calls_count} client calls, {len(self.api_links)} cross-stack links",
1500
1575
  "totalFiles": len(self.file_symbols),
1501
1576
  "totalSymbols": len(self.symbols),
1502
1577
  "totalEndpoints": endpoints_count,
1503
1578
  "totalClientCalls": calls_count,
1579
+ "totalRelationships": len(self.api_links),
1504
1580
  "topGodNodes": [g["file"] for g in god_nodes],
1505
1581
  "evidence": evidence,
1506
1582
  }
@@ -1508,10 +1584,11 @@ class CodeGraph:
1508
1584
  # L1: Discovered API surface & Routes
1509
1585
  endpoints = []
1510
1586
  for rel_path, eps in self.file_endpoints.items():
1511
- for norm_route, sym in eps:
1587
+ for norm_route, sym, method in eps:
1512
1588
  if not target or target.lower() in norm_route.lower() or target.lower() in rel_path.lower():
1513
1589
  endpoints.append({
1514
1590
  "route": norm_route,
1591
+ "method": method,
1515
1592
  "file": rel_path,
1516
1593
  "symbol": sym,
1517
1594
  "type": "backend.endpoint",
@@ -1519,15 +1596,37 @@ class CodeGraph:
1519
1596
 
1520
1597
  client_calls = []
1521
1598
  for rel_path, calls in self.file_api_calls.items():
1522
- for norm_route, sym in calls:
1599
+ for norm_route, sym, method in calls:
1523
1600
  if not target or target.lower() in norm_route.lower() or target.lower() in rel_path.lower():
1524
1601
  client_calls.append({
1525
1602
  "route": norm_route,
1603
+ "method": method,
1526
1604
  "file": rel_path,
1527
1605
  "symbol": sym,
1528
1606
  "type": "frontend.action",
1529
1607
  })
1530
1608
 
1609
+ # Cross-stack relationships (frontend call -> backend endpoint) with evidence
1610
+ relationships = []
1611
+ for link in self.api_links:
1612
+ if target:
1613
+ t = target.lower()
1614
+ hay = " ".join([
1615
+ link["source"]["route"] or "", link["source"]["file"] or "",
1616
+ link["target"]["route"] or "", link["target"]["file"] or "",
1617
+ ]).lower()
1618
+ if t not in hay:
1619
+ continue
1620
+ relationships.append({
1621
+ "source": link["source"],
1622
+ "target": link["target"],
1623
+ "evidence": {
1624
+ "provenance": "static",
1625
+ "sourceAdapter": "tokensafe-graph-engine",
1626
+ "confidence": "probable",
1627
+ },
1628
+ })
1629
+
1531
1630
  matching_symbols = []
1532
1631
  if target:
1533
1632
  for sk, sym in self.symbols.items():
@@ -1545,15 +1644,95 @@ class CodeGraph:
1545
1644
  "mode": "STATIC_SURFACE",
1546
1645
  "endpoints": endpoints[:30],
1547
1646
  "clientCalls": client_calls[:30],
1647
+ "relationships": relationships[:30],
1548
1648
  "matchingSymbols": matching_symbols[:20],
1549
1649
  "evidence": evidence,
1550
1650
  }
1551
1651
 
1652
+ def get_static_impact(self, target: str, max_depth: int = 3) -> Dict[str, Any]:
1653
+ """
1654
+ Static impact analysis over the AST graph: reverse-dependency walk
1655
+ ("who depends on the target") plus cross-stack frontend callers of
1656
+ matching backend endpoints. Honest about missing runtime evidence.
1657
+ """
1658
+ evidence = {
1659
+ "provenance": "static",
1660
+ "sourceAdapter": "tokensafe-graph-engine",
1661
+ "confidence": "probable",
1662
+ }
1663
+ t = (target or "").strip()
1664
+ if not t:
1665
+ return {"target": t, "mode": "STATIC_IMPACT", "error": "target is required", "evidence": evidence}
1666
+
1667
+ start_nodes: Set[str] = set()
1668
+ if t.startswith("file:"):
1669
+ start_nodes.add(t)
1670
+ for sk, sym in self.symbols.items():
1671
+ if t.lower() in sym.name.lower() or t.lower() in sym.file_path.lower():
1672
+ start_nodes.add(sk)
1673
+ for rel_path in self.file_symbols:
1674
+ if t.lower() in rel_path.lower():
1675
+ start_nodes.add(f"file:{rel_path}")
1676
+
1677
+ visited: Dict[str, int] = {}
1678
+ frontier = [(n, 0) for n in start_nodes]
1679
+ while frontier:
1680
+ node, depth = frontier.pop(0)
1681
+ if node in visited:
1682
+ continue
1683
+ visited[node] = depth
1684
+ if depth >= max_depth:
1685
+ continue
1686
+ for dep in self.rev_edges.get(node, ()):
1687
+ if dep not in visited:
1688
+ frontier.append((dep, depth + 1))
1689
+
1690
+ def _node_info(node: str) -> Dict[str, Any]:
1691
+ if node.startswith("file:"):
1692
+ return {"type": "file", "file": node[5:]}
1693
+ sym = self.symbols.get(node)
1694
+ if sym:
1695
+ return {"type": "symbol", "name": sym.name, "kind": sym.kind, "file": sym.file_path}
1696
+ return {"type": "node", "id": node}
1697
+
1698
+ direct = [_node_info(n) for n, d in visited.items() if d == 1 and n not in start_nodes]
1699
+ transitive = [_node_info(n) for n, d in visited.items() if d > 1]
1700
+
1701
+ frontend_callers = []
1702
+ for link in self.api_links:
1703
+ hay = " ".join([link["target"]["route"] or "", link["target"]["file"] or ""])
1704
+ if t.lower() in hay.lower():
1705
+ frontend_callers.append({
1706
+ "source": link["source"],
1707
+ "target": link["target"],
1708
+ "evidence": {
1709
+ "provenance": "static",
1710
+ "sourceAdapter": "tokensafe-graph-engine",
1711
+ "confidence": "probable",
1712
+ },
1713
+ })
1714
+
1715
+ return {
1716
+ "target": t,
1717
+ "mode": "STATIC_IMPACT",
1718
+ "directDependents": direct[:20],
1719
+ "transitiveDependents": transitive[:20],
1720
+ "crossStack": {
1721
+ "frontendCallers": frontend_callers[:20],
1722
+ "count": len(frontend_callers),
1723
+ },
1724
+ "evidence": evidence,
1725
+ "missingEvidence": [
1726
+ "Runtime-confirmed dependencies are not included while dev-servers are offline.",
1727
+ ],
1728
+ }
1729
+
1552
1730
 
1553
1731
  class GraphEngine:
1554
1732
  """Multi-Project Manager for automatic background graph execution."""
1555
1733
 
1556
1734
  _instances: Dict[str, CodeGraph] = {}
1735
+ _instances_lock = threading.RLock()
1557
1736
 
1558
1737
  @classmethod
1559
1738
  def find_project_root(cls, start_path: str) -> str:
@@ -1579,15 +1758,16 @@ class GraphEngine:
1579
1758
  # Rescans are full AST crawls; a 3s TTL caused near-constant rescans on every
1580
1759
  # smart_read_file(symbol=...) call. 60s keeps graphs fresh without the churn.
1581
1760
  rescan_ttl = float(os.environ.get("TOKENSAFE_GRAPH_TTL", "60.0"))
1582
- if root_abs not in cls._instances:
1583
- graph = CodeGraph(root_abs, use_disk_cache=True)
1584
- graph.scan()
1585
- cls._instances[root_abs] = graph
1586
- else:
1587
- graph = cls._instances[root_abs]
1588
- if time.time() - graph.last_scanned > rescan_ttl:
1761
+ with cls._instances_lock:
1762
+ if root_abs not in cls._instances:
1763
+ graph = CodeGraph(root_abs, use_disk_cache=True)
1589
1764
  graph.scan()
1590
- return graph
1765
+ cls._instances[root_abs] = graph
1766
+ else:
1767
+ graph = cls._instances[root_abs]
1768
+ if time.time() - graph.last_scanned > rescan_ttl:
1769
+ graph.scan()
1770
+ return graph
1591
1771
 
1592
1772
  @classmethod
1593
1773
  def for_file(cls, file_path: str) -> Tuple[CodeGraph, str]:
package/src/guard.py CHANGED
@@ -670,8 +670,8 @@ class TokenSafeGuard:
670
670
  f"TokenSafe Protocol mandates using MCP tools to prevent context window bloat:\n"
671
671
  f"• To search keywords, symbols, or configs: call 'tokensafe:scoped_search(query, scope)'\n"
672
672
  f"• To inspect definitions/symbols in a file: call 'tokensafe:smart_read_file(path, symbol)'\n"
673
- f"• To locate God Nodes & architecture: call 'tokensafe:get_architecture_graph(project_path)'\n"
674
- f"• To inspect project exports & types: call 'tokensafe:get_api_surface(project_path)'"
673
+ f"• To locate God Nodes & architecture: call 'tokensafe:repo_map(view=\"graph\", project_path=...)'\n"
674
+ f"• To inspect project exports & types: call 'tokensafe:repo_map(view=\"api\", project_path=...)'"
675
675
  )
676
676
 
677
677
  elif cmd_tok == "find":
@@ -681,7 +681,7 @@ class TokenSafeGuard:
681
681
  if has_code_ext or has_code_dir or is_root_file_crawl:
682
682
  return (
683
683
  f"Raw file crawl via 'find' blocked: '{sub_cmd}'. "
684
- f"Use 'tokensafe:scoped_search(query)' or 'tokensafe:get_architecture_graph(project_path)' "
684
+ f"Use 'tokensafe:scoped_search(query)' or 'tokensafe:repo_map(view=\"tree\")' "
685
685
  f"instead of scanning directory trees."
686
686
  )
687
687
 
@@ -72,6 +72,27 @@ def _read_dimensions_sips(path: str) -> Optional[Tuple[int, int]]:
72
72
  return None
73
73
 
74
74
 
75
+ def _read_dimensions_imagemagick(path: str) -> Optional[Tuple[int, int]]:
76
+ cmd = shutil.which("magick") or shutil.which("identify")
77
+ if not cmd:
78
+ return None
79
+ try:
80
+ args = [cmd, "identify"] if os.path.basename(cmd).startswith("magick") else [cmd]
81
+ res = subprocess.run(
82
+ [*args, "-format", "%w %h", path],
83
+ capture_output=True, text=True, timeout=5
84
+ )
85
+ if res.returncode == 0:
86
+ parts = res.stdout.strip().split()
87
+ if len(parts) >= 2:
88
+ w, h = int(parts[0]), int(parts[1])
89
+ if w > 0 and h > 0:
90
+ return (w, h)
91
+ except Exception:
92
+ pass
93
+ return None
94
+
95
+
75
96
  def get_image_dimensions(path: str) -> Optional[Tuple[int, int]]:
76
97
  dims = _read_dimensions_pillow(path)
77
98
  if dims:
@@ -80,6 +101,9 @@ def get_image_dimensions(path: str) -> Optional[Tuple[int, int]]:
80
101
  dims = _read_dimensions_sips(path)
81
102
  if dims:
82
103
  return dims
104
+ dims = _read_dimensions_imagemagick(path)
105
+ if dims:
106
+ return dims
83
107
  return None
84
108
 
85
109
 
@@ -163,6 +187,8 @@ class ImageDownscaler:
163
187
  with Image.open(image_path) as img:
164
188
  resample_filter = getattr(Image.Resampling, "LANCZOS", Image.LANCZOS if hasattr(Image, "LANCZOS") else 1)
165
189
  resized = img.resize((new_w, new_h), resample=resample_filter)
190
+ if ext in (".jpg", ".jpeg", ".bmp") and resized.mode in ("RGBA", "LA", "P"):
191
+ resized = resized.convert("RGB")
166
192
  resized.save(optimized_path)
167
193
  engine_used = "pillow"
168
194
  except Exception: