tokensafe 4.7.6 → 4.7.8

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.
@@ -52,7 +52,10 @@ _SKIP_CALLS = {
52
52
  "true", "false", "null", "undefined", "None", "True", "False",
53
53
  }
54
54
 
55
- _CACHE_SCHEMA_VERSION = 5
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
56
59
 
57
60
  _STATIC_ASSET_EXTS = {
58
61
  ".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico", ".webp",
@@ -62,10 +65,20 @@ _STATIC_ASSET_EXTS = {
62
65
  }
63
66
 
64
67
  _BACKEND_ROUTE_PATTERNS = [
68
+ # (regex, default_method). Group 1 is always the route literal; the declaring
69
+ # receiver (if any) is read back from the match text with _RECEIVER_RE.
65
70
  # Python: @app.get("/users"), @router.post('/login'), @bp.route('/data')
66
71
  (re.compile(r'@(?:app|router|api|bp)\.(?:get|post|put|delete|patch|route)\(\s*["\']([^"\']+)["\']', re.IGNORECASE), None),
67
72
  # JS/TS: app.get("/users", ...), router.post('/login', ...)
68
73
  (re.compile(r'(?<!@)\b(?:app|router|server|fastify)\.(?:get|post|put|delete|patch)\(\s*["\']([^"\']+)["\']', re.IGNORECASE), None),
74
+ # Named routers: usersRouter.get("/users", ...), wheelRoutes.post("/spin", ...).
75
+ # The suffix carries the intent, so a bare `axios.get("/x")` stays a client call.
76
+ (re.compile(r'\b[A-Za-z_$][\w$]*(?:Router|Routes|App|Server)\.(?:get|post|put|delete|patch)\(\s*[`"\'](/[^`"\'?#]*)'), None),
77
+ # Chained builders: Elysia/Fastify `new Elysia().post("/spin", h)` and
78
+ # `router\n .get("/status", h)`. The verb must be preceded by whitespace or
79
+ # ")" (a chain continuation) and the literal must start with "/", so
80
+ # `axios.get(...)` / `map.get(...)` receivers stay excluded.
81
+ (re.compile(r'(?<![\w$.])\.(?:get|post|put|delete|patch)\(\s*[`"\'](/[^`"\'?#]*)'), None),
69
82
  # Java/Kotlin Spring: @GetMapping("/users"), @PostMapping(value = "/login"), @RequestMapping("/api")
70
83
  (re.compile(r'@(?:Get|Post|Put|Delete|Patch|Request)Mapping\(\s*(?:value\s*=\s*)?["\']([^"\']+)["\']', re.IGNORECASE), None),
71
84
  # Go Gin/Echo/Fiber: r.GET("/users", ...), router.POST('/login', ...)
@@ -78,6 +91,23 @@ _BACKEND_ROUTE_PATTERNS = [
78
91
  (re.compile(r'Route::(?:get|post|put|delete|patch)\(\s*["\']([^"\']+)["\']'), None),
79
92
  ]
80
93
 
94
+ # Call targets that are language/runtime builtins rather than code this graph
95
+ # could resolve: reported as unresolved would drown the real gaps.
96
+ _STATIC_FLOW_NOISE = {
97
+ "Boolean", "Number", "String", "Object", "Array", "Date", "Promise", "Map",
98
+ "Set", "JSON", "Math", "Error", "RegExp", "Symbol", "Buffer", "console",
99
+ "process", "require", "setTimeout", "setInterval", "clearTimeout",
100
+ "clearInterval", "requestAnimationFrame", "cancelAnimationFrame",
101
+ "parseInt", "parseFloat", "isNaN", "fetch", "len", "str", "int", "float",
102
+ "list", "dict", "set", "tuple", "range", "print", "open", "super",
103
+ "self", "this", "None", "True", "False",
104
+ }
105
+
106
+ # The object a route is declared on, read from the start of the matched text:
107
+ # `app.get(...)` -> "app", `.post(...)` -> None (chained builder).
108
+ _RECEIVER_RE = re.compile(r'^\s*([A-Za-z_$][\w$]*)\.')
109
+
110
+
81
111
  _FRONTEND_CALL_PATTERNS = [
82
112
  # fetch("/api/users") or fetch(`/api/users/${id}`) (method unknown: depends on init options)
83
113
  (re.compile(r'\bfetch\(\s*[`"\']([^`"\'?#]+)'), None),
@@ -87,9 +117,71 @@ _FRONTEND_CALL_PATTERNS = [
87
117
  (re.compile(r'\buseSWR\(\s*[`"\']([^`"\'?#]+)'), "GET"),
88
118
  # axios("/api/users") (method unknown: depends on config)
89
119
  (re.compile(r'\baxios\(\s*[`"\']([^`"\'?#]+)'), None),
120
+ # Local HTTP wrappers: request('/wheel/spin') and TypeScript generics
121
+ # (request<SpinWheelResponse>('/wheel/spin', ...)) carrying a literal absolute
122
+ # route were invisible to cross-stack linking. Requiring a leading "/" keeps
123
+ # arg-of-something calls such as request('users') out.
124
+ (re.compile(r'\b(?:request|apiRequest|httpRequest|sendRequest|requestJson|fetchJson)'
125
+ r'(?:\s*<[^<>()]{1,120}>)?\s*\(\s*[`"\'](/[^`"\'?#]*)'), None),
90
126
  ]
91
127
 
92
128
  # HTTP method extraction from route-declaration / API-call matched text.
129
+ # File-level route prefixes declared by the framework constructor, so a route
130
+ # literal in that file is not the route clients call: Elysia
131
+ # `new Elysia({ prefix: "/wheel" })`, FastAPI/Flask `APIRouter(prefix=...)`,
132
+ # `Blueprint(..., url_prefix=...)`, Fastify plugin `{ prefix: "/v1" }`.
133
+ _FRAMEWORK_PREFIX_PATTERNS = [
134
+ re.compile(r'\bnew\s+Elysia\s*\([^)]*?\bprefix\s*:\s*[`"\']([^`"\']+)[`"\']'),
135
+ re.compile(r'\b(?:APIRouter|FastAPI|Blueprint|Flask)\s*\([^)]*?\b(?:url_)?prefix\s*=\s*["\']([^"\']+)["\']'),
136
+ re.compile(r'\bregister\s*\(\s*[A-Za-z_$][\w$]*\s*,\s*\{[^}]*?\bprefix\s*:\s*[`"\']([^`"\']+)[`"\']'),
137
+ ]
138
+
139
+ # Router mounts: app.use("/wheel", wheelRoutes) / server.register("/v1", routes).
140
+ _MOUNT_RE = re.compile(
141
+ r'\b(?:app|server|api|router|fastify|r)\.(?:use|register)\(\s*[`"\'](/[^`"\']*)[`"\']\s*,\s*([A-Za-z_$][\w$]*)'
142
+ )
143
+
144
+ # Where a mounted router identifier comes from: import/require bindings, so the
145
+ # mount prefix can be applied to the file that actually declares the routes.
146
+ _IMPORT_BINDING_PATTERNS = [
147
+ # import { a, b as c } from "./mod" / import def from "./mod"
148
+ re.compile(r'\bimport\s+(?:\{([^}]*)\}|([A-Za-z_$][\w$]*))\s*from\s*[`"\']([^`"\']+)[`"\']'),
149
+ # const { a, b: c } = require("./mod") / const def = require("./mod")
150
+ re.compile(r'\b(?:const|let|var)\s+(?:\{([^}]*)\}|([A-Za-z_$][\w$]*))\s*=\s*require\(\s*[`"\']([^`"\']+)[`"\']'),
151
+ ]
152
+
153
+
154
+ def _import_bindings(content: str) -> Dict[str, str]:
155
+ """Maps a local identifier to the module specifier it was imported from."""
156
+ bindings: Dict[str, str] = {}
157
+ for rx in _IMPORT_BINDING_PATTERNS:
158
+ for m in rx.finditer(content):
159
+ names_blob, default_name, module = m.group(1), m.group(2), m.group(3)
160
+ if default_name:
161
+ bindings[default_name] = module
162
+ continue
163
+ for part in (names_blob or "").split(","):
164
+ part = part.strip()
165
+ if not part:
166
+ continue
167
+ # `a as b` -> local b; `a: b` -> local b
168
+ local = re.split(r'\s+as\s+|:\s*', part)[-1].strip()
169
+ if local:
170
+ bindings[local] = module
171
+ return bindings
172
+
173
+
174
+ def _join_route(prefix: str, route: str) -> str:
175
+ """Compose a mount/constructor prefix with a declared route, without doubling it."""
176
+ p = (prefix or "").rstrip("/")
177
+ r = route if route.startswith("/") else "/" + route
178
+ if not p or p == "/":
179
+ return r
180
+ if r == p or r.startswith(p + "/"):
181
+ return r
182
+ return p + r
183
+
184
+
93
185
  _HTTP_METHOD_ANNOTATION_RE = re.compile(r'(?i)@(get|post|put|delete|patch)mapping\b')
94
186
  _HTTP_METHOD_BRACKET_RE = re.compile(r'(?i)\[\s*http(get|post|put|delete|patch)\b')
95
187
  _HTTP_METHOD_CALL_RE = re.compile(r'(?i)(?:\.|::)\s*(get|post|put|delete|patch|head|options)\s*\(')
@@ -239,6 +331,7 @@ class CodeGraph:
239
331
  self.file_imports: Dict[str, Set[str]] = {} # file_rel_path -> raw imported modules
240
332
  self.file_endpoints: Dict[str, List[Tuple[str, Optional[str], Optional[str]]]] = {} # rel_path -> [(norm_route, sym_key, http_method)]
241
333
  self.file_api_calls: Dict[str, List[Tuple[str, Optional[str], Optional[str]]]] = {} # rel_path -> [(norm_route, sym_key, http_method)]
334
+ self.file_mounts: Dict[str, List[Tuple[str, str, str]]] = {} # rel_path -> [(url_prefix, router_ident, module_or_".")]
242
335
  self.api_links: List[Dict[str, Any]] = [] # cross-stack edges: frontend call -> backend endpoint
243
336
  self.last_scanned: float = 0.0
244
337
  self.backend: str = self._detect_backend()
@@ -276,6 +369,7 @@ class CodeGraph:
276
369
  self.file_imports.clear()
277
370
  self.file_endpoints.clear()
278
371
  self.file_api_calls.clear()
372
+ self.file_mounts.clear()
279
373
  self.api_links.clear()
280
374
 
281
375
  def _load_disk_cache(self) -> bool:
@@ -341,6 +435,13 @@ class CodeGraph:
341
435
  except sqlite3.OperationalError:
342
436
  pass
343
437
 
438
+ self.file_mounts = {}
439
+ try:
440
+ for row in cur.execute("SELECT rel_path, prefix, ident, module FROM file_mounts").fetchall():
441
+ self.file_mounts.setdefault(row[0], []).append((row[1], row[2], row[3] or ""))
442
+ except sqlite3.OperationalError:
443
+ pass
444
+
344
445
  self.api_links = []
345
446
  try:
346
447
  for row in cur.execute("SELECT link_json FROM api_links").fetchall():
@@ -416,6 +517,7 @@ class CodeGraph:
416
517
  cur.execute("CREATE TABLE edges (source TEXT, target TEXT, PRIMARY KEY (source, target))")
417
518
  cur.execute("CREATE TABLE api_endpoints (rel_path TEXT, route TEXT, sym_key TEXT, method TEXT)")
418
519
  cur.execute("CREATE TABLE api_calls (rel_path TEXT, route TEXT, sym_key TEXT, method TEXT)")
520
+ cur.execute("CREATE TABLE file_mounts (rel_path TEXT, prefix TEXT, ident TEXT, module TEXT)")
419
521
  cur.execute("CREATE TABLE api_links (link_json TEXT)")
420
522
 
421
523
  cur.executemany(
@@ -460,6 +562,10 @@ class CodeGraph:
460
562
  "INSERT INTO api_calls VALUES (?, ?, ?, ?)",
461
563
  [(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],
462
564
  )
565
+ cur.executemany(
566
+ "INSERT INTO file_mounts VALUES (?, ?, ?, ?)",
567
+ [(rel, prefix, ident, module) for rel, mounts in self.file_mounts.items() for (prefix, ident, module) in mounts],
568
+ )
463
569
  cur.executemany(
464
570
  "INSERT INTO api_links VALUES (?)",
465
571
  [(json.dumps(lk, ensure_ascii=False),) for lk in self.api_links],
@@ -569,6 +675,7 @@ class CodeGraph:
569
675
  self.file_imports.pop(rel_path, None)
570
676
  self.file_endpoints.pop(rel_path, None)
571
677
  self.file_api_calls.pop(rel_path, None)
678
+ self.file_mounts.pop(rel_path, None)
572
679
  for k in sym_keys:
573
680
  self.symbols.pop(k, None)
574
681
  targets = self.edges.pop(k, set())
@@ -643,6 +750,7 @@ class CodeGraph:
643
750
  def _extract_api_routes_and_calls(self, content: str, rel_path: str) -> None:
644
751
  self.file_endpoints[rel_path] = []
645
752
  self.file_api_calls[rel_path] = []
753
+ self.file_mounts[rel_path] = []
646
754
 
647
755
  norm_rel = rel_path.replace("\\", "/")
648
756
 
@@ -651,6 +759,30 @@ class CodeGraph:
651
759
  if m_prefix:
652
760
  class_prefix = m_prefix.group(1) or m_prefix.group(2) or ""
653
761
 
762
+ # Framework-level prefix: routes are declared relative to it.
763
+ file_prefix = ""
764
+ for rx in _FRAMEWORK_PREFIX_PATTERNS:
765
+ m = rx.search(content)
766
+ if m:
767
+ file_prefix = (m.group(1) or "").strip()
768
+ break
769
+
770
+ # Mounted sub-routers: the prefix lives where the router is mounted,
771
+ # the routes where it is declared, so record the pair plus where the
772
+ # identifier comes from ("." = declared in this same file).
773
+ mount_matches = list(_MOUNT_RE.finditer(content))
774
+ if mount_matches:
775
+ bindings = _import_bindings(content)
776
+ for m in mount_matches:
777
+ prefix = (m.group(1) or "").strip()
778
+ ident = (m.group(2) or "").strip()
779
+ if not (prefix and ident):
780
+ continue
781
+ module = bindings.get(ident) or ""
782
+ if not module and re.search(r'\b(?:const|let|var|function|class)\s+' + re.escape(ident) + r'\b', content):
783
+ module = "."
784
+ self.file_mounts[rel_path].append((prefix, ident, module))
785
+
654
786
  # 1. Next.js file-based API routes
655
787
  m_app = _NEXT_APP_ROUTE_RE.match(norm_rel)
656
788
  m_pages = _NEXT_PAGES_ROUTE_RE.match(norm_rel)
@@ -670,6 +802,11 @@ class CodeGraph:
670
802
  self.file_endpoints[rel_path].append((norm_route, None, None))
671
803
 
672
804
  # 2. Backend route definitions
805
+ same_file_mounts: Dict[str, List[str]] = {}
806
+ if not file_prefix:
807
+ for (prefix, ident, module) in self.file_mounts[rel_path]:
808
+ if module == ".":
809
+ same_file_mounts.setdefault(ident, []).append(prefix)
673
810
  for rx, _default_method in _BACKEND_ROUTE_PATTERNS:
674
811
  for match in rx.finditer(content):
675
812
  route_raw = match.group(1)
@@ -677,13 +814,28 @@ class CodeGraph:
677
814
  full_route = class_prefix.rstrip("/") + "/" + route_raw.lstrip("/")
678
815
  else:
679
816
  full_route = route_raw
817
+ if file_prefix:
818
+ full_route = _join_route(file_prefix, full_route)
819
+ # Same-file mount: app.use("/api", router) prefixes only the routes
820
+ # declared on `router`, so app.get("/health") in the same file keeps
821
+ # its own path. A mounted route is not addressable unprefixed, so
822
+ # only the composed form is recorded.
823
+ line_no = content[:match.start()].count("\n") + 1
824
+ method = _match_http_method(match.group(0))
825
+ receiver_match = _RECEIVER_RE.match(match.group(0))
826
+ mount_prefixes = same_file_mounts.get(receiver_match.group(1), []) if receiver_match else []
827
+ if mount_prefixes:
828
+ for mount_prefix in mount_prefixes:
829
+ norm_composed = _normalize_route_path(_join_route(mount_prefix, full_route))
830
+ if norm_composed:
831
+ self.file_endpoints[rel_path].append(
832
+ (norm_composed, self._find_enclosing_symbol(rel_path, line_no), method)
833
+ )
834
+ continue
680
835
  norm_route = _normalize_route_path(full_route)
681
836
  if not norm_route:
682
837
  continue
683
- line_no = content[:match.start()].count("\n") + 1
684
- sym_key = self._find_enclosing_symbol(rel_path, line_no)
685
- method = _match_http_method(match.group(0))
686
- self.file_endpoints[rel_path].append((norm_route, sym_key, method))
838
+ self.file_endpoints[rel_path].append((norm_route, self._find_enclosing_symbol(rel_path, line_no), method))
687
839
 
688
840
  # 3. Frontend API call sites
689
841
  for rx, default_method in _FRONTEND_CALL_PATTERNS:
@@ -697,6 +849,21 @@ class CodeGraph:
697
849
  method = _match_http_method(match.group(0)) or default_method
698
850
  self.file_api_calls[rel_path].append((norm_route, sym_key, method))
699
851
 
852
+ def _resolve_relative_module(self, from_rel: str, spec: str) -> Optional[str]:
853
+ """Resolves a relative import specifier to an indexed file, if any."""
854
+ if not spec or not spec.startswith("."):
855
+ return None
856
+ base = os.path.normpath(os.path.join(os.path.dirname(from_rel), spec)).replace("\\", "/")
857
+ candidates = [base]
858
+ for ext in (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".py", ".go", ".rs", ".php", ".java"):
859
+ candidates.append(base + ext)
860
+ for ext in (".ts", ".tsx", ".js", ".jsx"):
861
+ candidates.append(base + "/index" + ext)
862
+ for cand in candidates:
863
+ if cand in self.file_symbols:
864
+ return cand
865
+ return None
866
+
700
867
  @staticmethod
701
868
  def _route_matches(path: str, pattern_route: str) -> bool:
702
869
  if not path or not pattern_route:
@@ -725,11 +892,38 @@ class CodeGraph:
725
892
  """
726
893
  self.api_links = []
727
894
  try:
895
+ # Mounted routers: `app.use("/wheel", wheelRoutes)` prefixes the routes
896
+ # declared in the router's own file. Resolve the module binding first
897
+ # (a router constant is not always a graph symbol), then fall back to
898
+ # a uniquely-named symbol.
899
+ name_to_files: Dict[str, Set[str]] = {}
900
+ for sym in self.symbols.values():
901
+ name_to_files.setdefault(sym.name, set()).add(sym.file_path)
902
+ mounted: Dict[str, List[str]] = {}
903
+ for mount_rel, mounts in self.file_mounts.items():
904
+ for prefix, ident, module in mounts:
905
+ target = None
906
+ if module == ".":
907
+ target = mount_rel
908
+ elif module:
909
+ target = self._resolve_relative_module(mount_rel, module)
910
+ if not target:
911
+ owners = name_to_files.get(ident) or set()
912
+ if len(owners) == 1:
913
+ target = next(iter(owners))
914
+ if target and target != mount_rel:
915
+ mounted.setdefault(target, []).append(prefix)
916
+
728
917
  endpoint_map: Dict[str, List[Tuple[str, Optional[str], Optional[str]]]] = {}
729
918
  for rel_path, endpoints in self.file_endpoints.items():
730
919
  for norm_route, sym_key, method in endpoints:
731
- if norm_route:
732
- endpoint_map.setdefault(norm_route, []).append((rel_path, sym_key, method))
920
+ if not norm_route:
921
+ continue
922
+ effective = [norm_route] + [
923
+ _join_route(prefix, norm_route) for prefix in mounted.get(rel_path, [])
924
+ ]
925
+ for eff_route in dict.fromkeys(effective):
926
+ endpoint_map.setdefault(eff_route, []).append((rel_path, sym_key, method))
733
927
 
734
928
  if not endpoint_map:
735
929
  return
@@ -1563,6 +1757,10 @@ class CodeGraph:
1563
1757
  }
1564
1758
 
1565
1759
  lvl = (level or "L0").upper()
1760
+ if lvl == "L2" and target:
1761
+ # L2 is the flow contract, and it is answerable offline: handler ->
1762
+ # callees -> literal client route.
1763
+ return self.get_static_flow(target)
1566
1764
  if lvl == "L0":
1567
1765
  god_nodes = self.get_god_nodes(top_n=5)
1568
1766
  endpoints_count = sum(len(eps) for eps in self.file_endpoints.values())
@@ -1629,8 +1827,12 @@ class CodeGraph:
1629
1827
 
1630
1828
  matching_symbols = []
1631
1829
  if target:
1830
+ t = target.lower()
1632
1831
  for sk, sym in self.symbols.items():
1633
- if target.lower() in sym.name.lower():
1832
+ # Match both names and file paths, like get_static_impact: a target
1833
+ # that is a file path ("src/api/wheel.ts") must resolve to that
1834
+ # file's symbols, or every path-shaped target silently matches none.
1835
+ if t in sym.name.lower() or t in sym.file_path.lower():
1634
1836
  matching_symbols.append({
1635
1837
  "name": sym.name,
1636
1838
  "kind": sym.kind,
@@ -1638,7 +1840,7 @@ class CodeGraph:
1638
1840
  "lines": [sym.line_start, sym.line_end],
1639
1841
  })
1640
1842
 
1641
- return {
1843
+ result = {
1642
1844
  "level": "L1",
1643
1845
  "target": target,
1644
1846
  "mode": "STATIC_SURFACE",
@@ -1648,6 +1850,18 @@ class CodeGraph:
1648
1850
  "matchingSymbols": matching_symbols[:20],
1649
1851
  "evidence": evidence,
1650
1852
  }
1853
+ if lvl != "L1":
1854
+ # Asking for L2-L4 offline used to return this L1 payload with
1855
+ # confidence "confirmed" and no marker, so callers could not tell a
1856
+ # served level from a substituted one.
1857
+ result["requestedLevel"] = lvl
1858
+ result["degraded"] = True
1859
+ result["degradedReason"] = (
1860
+ "L2 flow needs a target symbol"
1861
+ if lvl == "L2"
1862
+ else f"static engine serves L1 surface only; {lvl} requires a live OUMV runtime"
1863
+ )
1864
+ return result
1651
1865
 
1652
1866
  def get_static_impact(self, target: str, max_depth: int = 3) -> Dict[str, Any]:
1653
1867
  """
@@ -1727,6 +1941,173 @@ class CodeGraph:
1727
1941
  ],
1728
1942
  }
1729
1943
 
1944
+ def get_static_flow(self, target: str, max_depth: int = 3) -> Dict[str, Any]:
1945
+ """Static L2 flow: handler -> callee symbols -> literal client route.
1946
+
1947
+ Answers "what does this handler reach", not "what does it do": the walk is
1948
+ the forward call graph (handler, local helpers, imported functions) and the
1949
+ API call sites declared in the reached symbols. Dynamic dispatch, call
1950
+ order and runtime values stay out — the evidence says so.
1951
+ """
1952
+ evidence = {
1953
+ "provenance": "static",
1954
+ "sourceAdapter": "tokensafe-graph-engine",
1955
+ "confidence": "probable",
1956
+ }
1957
+ t = (target or "").strip()
1958
+ if not t:
1959
+ return {"target": t, "mode": "STATIC_FLOW", "error": "target is required", "evidence": evidence}
1960
+
1961
+ name_to_syms: Dict[str, List[str]] = {}
1962
+ for sk, sym in self.symbols.items():
1963
+ name_to_syms.setdefault(sym.name, []).append(sk)
1964
+
1965
+ start: Set[str] = set()
1966
+ exact: Set[str] = set()
1967
+ for sk, sym in self.symbols.items():
1968
+ if sym.name.lower() == t.lower():
1969
+ exact.add(sk)
1970
+ elif t.lower() in sym.name.lower() or t.lower() in sym.file_path.lower():
1971
+ start.add(sk)
1972
+ # An exact symbol name beats substring hits: `spinWheel` must not pull in
1973
+ # SpinWheelRequestProtoDto and everything else that merely contains it.
1974
+ start = exact or start
1975
+ if not start:
1976
+ return {
1977
+ "target": t,
1978
+ "mode": "STATIC_FLOW",
1979
+ "error": "NO_MATCHING_SYMBOL",
1980
+ "matchedSymbols": [],
1981
+ "hint": "Pass a symbol or file name (e.g. 'spinWheel', 'src/api/wheel.ts'), not a prose question.",
1982
+ "evidence": evidence,
1983
+ }
1984
+
1985
+ depth_of: Dict[str, int] = {sk: 0 for sk in start}
1986
+ frontier = list(start)
1987
+ unresolved: Set[str] = set()
1988
+ truncated = False
1989
+
1990
+ def _pick(name: str, caller_file: Optional[str]) -> Tuple[List[str], bool]:
1991
+ """Callee candidates scoped like a compiler would: same file first, then
1992
+ files the caller imports, and only then a globally unique name.
1993
+
1994
+ Name-only resolution used to drop every edge to a helper whose name
1995
+ recurs (four `loadStatus` closures in one app), which cut the flow at
1996
+ exactly the local-closure hop it was supposed to follow.
1997
+ """
1998
+ targets = name_to_syms.get(name) or []
1999
+ if not targets:
2000
+ return [], False
2001
+ if len(targets) == 1:
2002
+ return targets, False
2003
+ if caller_file:
2004
+ same = [tk for tk in targets if self.symbols[tk].file_path == caller_file]
2005
+ if same:
2006
+ return same, False
2007
+ imported: Set[str] = set()
2008
+ for spec in self.file_imports.get(caller_file, set()):
2009
+ resolved = self._resolve_relative_module(caller_file, spec)
2010
+ if resolved:
2011
+ imported.add(resolved)
2012
+ near = [tk for tk in targets if self.symbols[tk].file_path in imported]
2013
+ if near:
2014
+ return near, False
2015
+ return [], True
2016
+
2017
+ while frontier:
2018
+ node = frontier.pop(0)
2019
+ d = depth_of[node]
2020
+ caller_sym = self.symbols.get(node)
2021
+ caller_file = caller_sym.file_path if caller_sym else None
2022
+ for nxt in self.edges.get(node, ()):
2023
+ if nxt.startswith("call:"):
2024
+ callee_name = nxt[5:]
2025
+ # Language builtins are not code this graph could resolve.
2026
+ if callee_name in _STATIC_FLOW_NOISE or callee_name[:1].isupper():
2027
+ continue
2028
+ targets, ambiguous = _pick(callee_name, caller_file)
2029
+ if ambiguous:
2030
+ unresolved.add(callee_name + " (ambiguous)")
2031
+ continue
2032
+ if not targets:
2033
+ unresolved.add(callee_name)
2034
+ continue
2035
+ elif nxt.startswith("sym:"):
2036
+ targets, _ambiguous = _pick(nxt[4:], caller_file)
2037
+ if not targets:
2038
+ continue
2039
+ elif nxt.startswith(("file:", "mod:")):
2040
+ continue
2041
+ elif nxt in self.symbols:
2042
+ targets = [nxt]
2043
+ else:
2044
+ continue
2045
+ for tk in targets:
2046
+ if tk in depth_of or tk in start:
2047
+ continue
2048
+ if d >= max_depth:
2049
+ truncated = True
2050
+ continue
2051
+ depth_of[tk] = d + 1
2052
+ frontier.append(tk)
2053
+
2054
+ def _sym_info(sk: str) -> Dict[str, Any]:
2055
+ sym = self.symbols[sk]
2056
+ return {
2057
+ "name": sym.name,
2058
+ "kind": sym.kind,
2059
+ "file": sym.file_path,
2060
+ "lines": [sym.line_start, sym.line_end],
2061
+ "depth": depth_of[sk],
2062
+ }
2063
+
2064
+ callees = sorted(
2065
+ (_sym_info(sk) for sk in depth_of if depth_of[sk] > 0),
2066
+ key=lambda item: (item["depth"], item["file"], item["name"]),
2067
+ )
2068
+
2069
+ # Client route literals reached by the walk: the handler itself or any
2070
+ # callee that declares the call. Declared routes of the start symbol's own
2071
+ # file are included only when that symbol declares them.
2072
+ routes: List[Dict[str, Any]] = []
2073
+ seen_routes = set()
2074
+ for rel_path, calls in self.file_api_calls.items():
2075
+ for norm_route, caller_sym, method in calls:
2076
+ if not norm_route:
2077
+ continue
2078
+ if caller_sym is not None and caller_sym not in depth_of:
2079
+ continue
2080
+ if caller_sym is None and rel_path != self.symbols[next(iter(start))].file_path:
2081
+ continue
2082
+ key = (norm_route, method, rel_path, caller_sym)
2083
+ if key in seen_routes:
2084
+ continue
2085
+ seen_routes.add(key)
2086
+ routes.append({
2087
+ "route": norm_route,
2088
+ "method": method,
2089
+ "file": rel_path,
2090
+ "via": self.symbols[caller_sym].name if caller_sym else None,
2091
+ })
2092
+
2093
+ return {
2094
+ "target": t,
2095
+ "level": "L2",
2096
+ "mode": "STATIC_FLOW",
2097
+ "matchedSymbols": [
2098
+ {"name": self.symbols[sk].name, "file": self.symbols[sk].file_path}
2099
+ for sk in sorted(start)
2100
+ ][:10],
2101
+ "callees": callees[:40],
2102
+ "clientCalls": routes[:20],
2103
+ "unresolvedCalls": sorted(unresolved)[:20],
2104
+ "truncated": truncated,
2105
+ "evidence": evidence,
2106
+ "missingEvidence": [
2107
+ "Runtime-confirmed call order and dynamic dispatch are not included while dev-servers are offline.",
2108
+ ],
2109
+ }
2110
+
1730
2111
 
1731
2112
  class GraphEngine:
1732
2113
  """Multi-Project Manager for automatic background graph execution."""
package/src/installer.py CHANGED
@@ -2818,16 +2818,9 @@ WantedBy=default.target
2818
2818
  except Exception:
2819
2819
  pass
2820
2820
 
2821
- if pip_cmd:
2822
- try:
2823
- res = subprocess.run([pip_cmd, "list"], capture_output=True, text=True, timeout=10)
2824
- if "tokensafe-python" in (res.stdout or ""):
2825
- print(f" {CYAN}→{RESET} Updating backend package ({pip_cmd} install --upgrade tokensafe-python)...")
2826
- up_res = subprocess.run([pip_cmd, "install", "--upgrade", "tokensafe-python"], capture_output=True, text=True, timeout=120)
2827
- if up_res.returncode == 0:
2828
- print(f" {GREEN}✔{RESET} tokensafe-python upgraded successfully.")
2829
- except Exception:
2830
- pass
2821
+ # The Python backend runtime is installed per project from git
2822
+ # (`tokensafe-backend-python @ git+…`), not as a global pip distribution —
2823
+ # there is no `tokensafe-python` package to upgrade here.
2831
2824
 
2832
2825
  # Project-level dependencies update (if inside a TokenSafe project)
2833
2826
  cwd = os.getcwd()
@@ -2846,18 +2839,7 @@ WantedBy=default.target
2846
2839
  except Exception:
2847
2840
  pass
2848
2841
 
2849
- for cand_py in [os.path.join(cwd, "pyproject.toml"), os.path.join(cwd, "backend", "pyproject.toml")]:
2850
- if os.path.isfile(cand_py):
2851
- try:
2852
- with open(cand_py, "r", encoding="utf-8") as f:
2853
- txt = f.read()
2854
- if "tokensafe-python" in txt and pip_cmd:
2855
- pdir = os.path.dirname(cand_py)
2856
- print(f" {CYAN}→{RESET} Updating local tokensafe-python in {pdir}...")
2857
- subprocess.run([pip_cmd, "install", "--upgrade", "tokensafe-python"], cwd=pdir, capture_output=True, text=True, timeout=60)
2858
- print(f" {GREEN}✔{RESET} Local tokensafe-python updated.")
2859
- except Exception:
2860
- pass
2842
+ # Per-project Python backend installs come from git; nothing global to update.
2861
2843
 
2862
2844
  # 4. Re-synchronize active/configured agents using the FRESHLY upgraded binary when available
2863
2845
  # (so plugins, hooks, skills, and rules come from the new release instead of the old process).
package/src/mcp_server.py CHANGED
@@ -44,7 +44,7 @@ from src.session_context import current_root, current_session_id
44
44
 
45
45
  SERVER_INFO = {
46
46
  "name": "tokensafe-mcp",
47
- "version": "4.7.6"
47
+ "version": "4.7.8"
48
48
  }
49
49
 
50
50
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -435,13 +435,15 @@ FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
435
435
  'type': 'object'},
436
436
  'name': 'oumv_observe'},
437
437
  { 'annotations': {'readOnlyHint': True},
438
- 'description': "Answers 'Why is state X / why is button disabled?' (causality/why_state) or performs impact "
438
+ 'description': "Answers 'Why is state X / why is button disabled?' (causality/why_state), performs impact "
439
439
  'analysis: causality merges both runtimes and adds static cross-stack edges (frontend action '
440
440
  '-> backend endpoint) with evidence; impact walks reverse dependencies plus cross-stack '
441
- 'frontend callers of matching backend endpoints.',
441
+ 'frontend callers of matching backend endpoints; flow resolves the L2 path from a handler '
442
+ 'through its callees to the client routes it calls.',
442
443
  'inputSchema': { 'properties': { 'query': { 'default': 'causality',
443
- 'description': 'Query type (causality, impact, why_state)',
444
- 'enum': ['causality', 'impact', 'why_state'],
444
+ 'description': 'Query type (causality, impact, why_state, '
445
+ 'flow)',
446
+ 'enum': ['causality', 'impact', 'why_state', 'flow'],
445
447
  'type': 'string'},
446
448
  'runtime': { 'default': 'auto',
447
449
  'description': 'Target runtime',
@@ -489,6 +491,15 @@ FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
489
491
  "'backend', or 'auto')",
490
492
  'enum': ['frontend', 'backend', 'auto'],
491
493
  'type': 'string'},
494
+ 'sandbox': { 'description': 'Transactional sandbox (backend only): '
495
+ '{"mode": "rollback"} runs the whole '
496
+ 'verify in one transaction and rolls it '
497
+ 'back; the result reports rolledBack, '
498
+ 'rollbackStatus and dbDiff',
499
+ 'properties': { 'mode': {'enum': ['rollback'],
500
+ 'type': 'string'}},
501
+ 'required': ['mode'],
502
+ 'type': 'object'},
492
503
  'target': { 'description': "Action target (component ID, e.g. 'cart', "
493
504
  "or 'POST /api/v1/orders' or '#submit-btn')",
494
505
  'type': 'string'},
@@ -3295,7 +3306,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3295
3306
  ws, ws_err = _oumv_workspace_arg(args)
3296
3307
  if ws_err:
3297
3308
  return _fallback_error("oumv_verify", ws_err)
3298
- res = OUMVGateway.verify(target=tgt, action=act, payload=payload, runtime=rt, workspace_dir=ws)
3309
+ sandbox = args.get("sandbox") if isinstance(args.get("sandbox"), dict) else None
3310
+ res = OUMVGateway.verify(target=tgt, action=act, payload=payload, runtime=rt, workspace_dir=ws, sandbox=sandbox)
3299
3311
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
3300
3312
  except Exception as e:
3301
3313
  return _fallback_error("oumv_verify", f"failed to verify OUMV action: {e}")