tokensafe 4.7.7 → 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.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.7.7",
2
+ "version": "4.7.8",
3
3
  "name": "tokensafe",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "author": {
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "4.7.7",
3
+ "version": "4.7.8",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "homepage": "https://tokensafe.dev",
6
6
  "license": "Apache-2.0",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "4.7.7",
4
+ "version": "4.7.8",
5
5
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
6
6
  "main": "bin/tokensafe.js",
7
7
  "bin": {
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "4.7.7",
4
+ "version": "4.7.8",
5
5
  "license": "Apache-2.0",
6
6
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
7
7
  "logo": "assets/logo.png",
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "dev.tokensafe/tokensafe",
4
4
  "title": "TokenSafe",
5
5
  "description": "Your AI agent is smart enough to code all day. Local firewall & zero-loss runtime.",
6
- "version": "4.7.7",
6
+ "version": "4.7.8",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/tokensafe-dev/tokensafe",
@@ -23,7 +23,7 @@
23
23
  "registryType": "npm",
24
24
  "registryBaseUrl": "https://registry.npmjs.org",
25
25
  "identifier": "tokensafe",
26
- "version": "4.7.7",
26
+ "version": "4.7.8",
27
27
  "runtimeHint": "npx",
28
28
  "transport": {
29
29
  "type": "stdio"
@@ -39,7 +39,7 @@
39
39
  "registryType": "pypi",
40
40
  "registryBaseUrl": "https://pypi.org",
41
41
  "identifier": "tokensafe",
42
- "version": "4.7.7",
42
+ "version": "4.7.8",
43
43
  "runtimeHint": "uvx",
44
44
  "transport": {
45
45
  "type": "stdio"
@@ -235,7 +235,7 @@ def go_patch_state(workspace: str) -> Dict[str, Any]:
235
235
  _GO_MODULE = "github.com/tokensafe-dev/tokensafe-backend/go"
236
236
  # Keep in step with the backend release tag (go/vX.Y.Z): injection must never
237
237
  # downgrade an adapter that is already newer than this pin.
238
- _GO_MODULE_VERSION = "v0.6.0"
238
+ _GO_MODULE_VERSION = "v0.7.0"
239
239
 
240
240
 
241
241
  def _version_tuple(tag: str):
@@ -648,19 +648,66 @@ def _sidecar_cache_dir() -> str:
648
648
  return os.path.join(_tokensafe_home(), "sidecars")
649
649
 
650
650
 
651
+ # Pinned to the backend release: the sidecars are single files, so the cache is
652
+ # content-addressed by SHA-256 and a clean machine downloads the exact bytes the
653
+ # release was certified from. Bump both the tag and the hashes together.
654
+ _SIDECAR_RELEASE_TAG = "v0.7.0"
655
+ _SIDECARS = {
656
+ "spring": (
657
+ "java/src/dev/tokensafe/oumv/OumvSpring.java",
658
+ "OumvSpring.java",
659
+ "b6dda1ecf9638bbcb867310139d9dce1421d0f9f43e6db490ddf2e327637d949",
660
+ ),
661
+ "php": (
662
+ "php/bin/oumv-php",
663
+ "oumv-php",
664
+ "31955f8bd2735a47ef70edae05f978436d70f326da38043bc11248100761ed12",
665
+ ),
666
+ }
667
+
668
+
669
+ def _sha256_file(path: str) -> str:
670
+ digest = hashlib.sha256()
671
+ with open(path, "rb") as handle:
672
+ for chunk in iter(lambda: handle.read(65536), b""):
673
+ digest.update(chunk)
674
+ return digest.hexdigest()
675
+
676
+
677
+ def sidecar_run_command(kind: str, sidecar_path: str, workspace: str) -> Optional[str]:
678
+ """The exact command that starts the sidecar against `workspace`."""
679
+ if not sidecar_path:
680
+ return None
681
+ if kind == "spring":
682
+ return f"tokensafe run-backend java {sidecar_path} --root {workspace} --port 7331"
683
+ if kind == "php":
684
+ return f"tokensafe run-backend php -S 127.0.0.1:7332 {sidecar_path} --root {workspace}"
685
+ return None
686
+
687
+
651
688
  def ensure_sidecar(kind: str) -> Tuple[Optional[str], str]:
652
- """Copies OumvSpring.java / oumv-php into ~/.tokensafe/sidecars.
689
+ """Caches OumvSpring.java / oumv-php at the pinned release and verifies SHA-256.
653
690
 
654
- Prefers a local backend checkout (OUMV_BACKEND_REPO or a sibling directory);
655
- returns (path, note) where path is None when the source is not available.
691
+ Order: a valid cache → a local checkout whose bytes match the pin (developer
692
+ flow, no network) → download from the release tag. A hash mismatch is never
693
+ accepted silently; the note says what failed instead of handing back a
694
+ different file under the certified name.
656
695
  """
657
- source_map = {
658
- "spring": ("java/src/dev/tokensafe/oumv/OumvSpring.java", "OumvSpring.java"),
659
- "php": ("php/bin/oumv-php", "oumv-php"),
660
- }
661
- if kind not in source_map:
696
+ if kind not in _SIDECARS:
662
697
  return None, f"unknown sidecar {kind!r}"
663
- rel_source, filename = source_map[kind]
698
+ rel_source, filename, expected_sha = _SIDECARS[kind]
699
+ cache_dir = _sidecar_cache_dir()
700
+ target = os.path.join(cache_dir, filename)
701
+
702
+ def adopt(source: str, note: str) -> Tuple[str, str]:
703
+ os.makedirs(cache_dir, exist_ok=True)
704
+ shutil.copy2(source, target)
705
+ if kind == "php":
706
+ os.chmod(target, 0o755)
707
+ return target, note
708
+
709
+ if os.path.isfile(target) and _sha256_file(target) == expected_sha:
710
+ return target, f"cached at {_SIDECAR_RELEASE_TAG}"
664
711
 
665
712
  repo_candidates = []
666
713
  env_repo = os.environ.get("OUMV_BACKEND_REPO")
@@ -671,20 +718,43 @@ def ensure_sidecar(kind: str) -> Tuple[Optional[str], str]:
671
718
  os.path.join(os.path.dirname(here), "tokensafe-backend"),
672
719
  os.path.join(here, "..", "tokensafe-backend"),
673
720
  ]
721
+ local_mismatch = None
674
722
  for repo in repo_candidates:
675
723
  candidate = os.path.join(os.path.abspath(repo), rel_source)
676
- if os.path.isfile(candidate):
677
- cache_dir = _sidecar_cache_dir()
678
- os.makedirs(cache_dir, exist_ok=True)
679
- target = os.path.join(cache_dir, filename)
680
- shutil.copy2(candidate, target)
681
- if kind == "php":
682
- os.chmod(target, 0o755)
683
- return target, f"cached from {candidate}"
684
- return None, (
685
- "sidecar source not found: set OUMV_BACKEND_REPO to a tokensafe-backend "
686
- "checkout or clone it next to this one"
724
+ if not os.path.isfile(candidate):
725
+ continue
726
+ if _sha256_file(candidate) == expected_sha:
727
+ return adopt(candidate, f"cached from local checkout matching {_SIDECAR_RELEASE_TAG}")
728
+ local_mismatch = candidate
729
+
730
+ if os.environ.get("TOKENSAFE_SIDECAR_OFFLINE") == "1":
731
+ if local_mismatch:
732
+ return adopt(local_mismatch, f"local checkout (unpinned, offline): {local_mismatch}")
733
+ return None, "offline (TOKENSAFE_SIDECAR_OFFLINE=1) and no cached sidecar"
734
+
735
+ url = (
736
+ f"https://raw.githubusercontent.com/tokensafe-dev/tokensafe-backend/"
737
+ f"{_SIDECAR_RELEASE_TAG}/{rel_source}"
687
738
  )
739
+ try:
740
+ import urllib.request
741
+
742
+ with urllib.request.urlopen(url, timeout=30) as response:
743
+ payload = response.read()
744
+ except Exception as exc:
745
+ if local_mismatch:
746
+ return adopt(local_mismatch, f"download failed ({exc}); local checkout (unpinned): {local_mismatch}")
747
+ return None, f"cannot download {url}: {exc}"
748
+
749
+ actual = hashlib.sha256(payload).hexdigest()
750
+ if actual != expected_sha:
751
+ return None, f"sha256 mismatch for {url}: expected {expected_sha}, got {actual}"
752
+ os.makedirs(cache_dir, exist_ok=True)
753
+ with open(target, "wb") as handle:
754
+ handle.write(payload)
755
+ if kind == "php":
756
+ os.chmod(target, 0o755)
757
+ return target, f"downloaded from {_SIDECAR_RELEASE_TAG}"
688
758
 
689
759
 
690
760
  def plan(workspace: str) -> Dict[str, Any]:
@@ -753,11 +823,7 @@ def plan(workspace: str) -> Dict[str, Any]:
753
823
  })
754
824
  elif provider in ("spring", "php"):
755
825
  sidecar_path, note = ensure_sidecar(provider)
756
- command = (
757
- f"tokensafe run-backend java {sidecar_path}"
758
- if provider == "spring" and sidecar_path
759
- else (f"tokensafe run-backend {sidecar_path}" if sidecar_path else None)
760
- )
826
+ command = sidecar_run_command(provider, sidecar_path or "", workspace)
761
827
  actions.append({
762
828
  "kind": "sidecar",
763
829
  "profile": "backend",
@@ -825,11 +891,7 @@ def apply(workspace: str, dry_run: bool = False, include_go: bool = True) -> Dic
825
891
  "status": "ready" if sidecar_path else "needs-source",
826
892
  "sidecar": sidecar_path,
827
893
  "note": note,
828
- "run": (
829
- f"tokensafe run-backend java {sidecar_path}"
830
- if backend["provider"] == "spring" and sidecar_path
831
- else (f"tokensafe run-backend {sidecar_path}" if sidecar_path else None)
832
- ),
894
+ "run": sidecar_run_command(backend["provider"], sidecar_path or "", workspace),
833
895
  })
834
896
 
835
897
  return results
package/src/cli.py CHANGED
@@ -752,21 +752,30 @@ def main(argv: Optional[List[str]] = None):
752
752
  print(f" ✔ Existing configuration preserved: \033[1m{conf_file}\033[0m (use --force to overwrite)\n")
753
753
 
754
754
  elif command in ("run-backend", "run_backend"):
755
- # Executes the user's dev-server command with the OUMV autoload hook active.
756
- # Nothing is written into the repository: the hook lives in ~/.tokensafe.
755
+ # Executes the user's dev-server command. Python/uvicorn gets the OUMV
756
+ # autoload hook from ~/.tokensafe; Java/PHP/Node sidecars run as-is (they
757
+ # mount the runtime themselves and write their own descriptor).
757
758
  from src.auto_inject import backend_env, ensure_python_autoload
758
759
 
759
760
  argv_rest = [a for a in args[1:]]
760
761
  if not argv_rest:
761
- print("usage: tokensafe run-backend <command...> e.g. tokensafe run-backend uvicorn app:app --reload")
762
+ print(
763
+ "usage: tokensafe run-backend <command...>\n"
764
+ " tokensafe run-backend uvicorn app:app --reload\n"
765
+ " tokensafe run-backend java OumvSpring.java --root . --port 7331\n"
766
+ " tokensafe run-backend php -S 127.0.0.1:7332 oumv-php --root ."
767
+ )
762
768
  return
763
- ensure_python_autoload()
764
- env = backend_env()
765
769
  tool = argv_rest[0]
766
770
  resolved = shutil.which(tool)
767
771
  if not resolved:
768
772
  print(f"tokensafe run-backend: `{tool}` not found on PATH")
769
773
  return
774
+ if os.path.basename(tool) in ("java", "php", "node", "npm", "npx"):
775
+ print(f"⚡ Launching {os.path.basename(tool)} with the Sextant runtime")
776
+ os.execvpe(resolved, argv_rest, dict(os.environ))
777
+ ensure_python_autoload()
778
+ env = backend_env()
770
779
  os.execvpe(resolved, argv_rest, env)
771
780
 
772
781
  elif command in ("inject", "wire"):
@@ -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/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.7"
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',
@@ -635,8 +635,10 @@ class OUMVGateway:
635
635
  report["backendError"] = str(e)
636
636
  return report
637
637
 
638
- # Cross-layer causality query
639
- if query == "causality" and runtime in ("auto", ""):
638
+ # Cross-layer causality query. Handled for every runtime value: with an
639
+ # explicit runtime this used to skip the static backbone entirely, and
640
+ # offline it fell through to the generic slice below.
641
+ if query == "causality":
640
642
  report = {
641
643
  "query": "causality",
642
644
  "target": target,
@@ -665,13 +667,34 @@ class OUMVGateway:
665
667
 
666
668
  return report
667
669
 
670
+ # Static L2 flow (offline contract): handler -> callees -> literal route.
671
+ if query == "flow":
672
+ report = graph.get_static_flow(target or "")
673
+ report.setdefault("query", "flow")
674
+ return report
675
+
668
676
  try:
677
+ # A live adapter may accept queries beyond the offline contract.
669
678
  url = cls._resolve_client_url(runtime=runtime, target=target, workspace_dir=workspace_dir)
670
679
  return cls._rpc_call(url, "oumv/understand", {"query": query, "target": target, "componentId": target})
671
680
  except RuntimeError:
672
- if query == "impact":
673
- return graph.get_static_impact(target or "")
674
- return graph.get_static_oumv_slice(level="L1", target=target)
681
+ # Prose in `query` is not a question: the offline contract answers
682
+ # impact/causality/flow only. Returning a surface dump here looked like
683
+ # an answer (level "L1", confidence "confirmed") to a query nobody parsed.
684
+ return {
685
+ "query": query,
686
+ "target": target,
687
+ "error": "UNSUPPORTED_QUERY",
688
+ "mode": "STATIC_SURFACE",
689
+ "supportedQueries": ["impact", "causality", "flow"],
690
+ "hint": (
691
+ "query is an enum, not text: 'impact' answers who depends on the target, "
692
+ "'causality' answers why state X / how frontend calls map to endpoints, "
693
+ "'flow' answers which client routes a handler reaches (L2). "
694
+ "For 'what this handler does', read the symbol with smart_read_file."
695
+ ),
696
+ "evidence": {"provenance": "static", "confidence": "confirmed", "sourceAdapter": "tokensafe-graph-engine"},
697
+ }
675
698
 
676
699
  @staticmethod
677
700
  def _static_cross_stack(graph: Any, target: Optional[str]) -> Dict[str, Any]:
@@ -311,7 +311,7 @@ class TelemetrySync:
311
311
  current_last_id = last_id
312
312
  headers = {
313
313
  "Content-Type": "application/json",
314
- "User-Agent": "TokenSafe-Sync/4.7.7"
314
+ "User-Agent": "TokenSafe-Sync/4.7.8"
315
315
  }
316
316
  if active_key:
317
317
  headers["Authorization"] = f"Bearer {active_key}"
@@ -17,7 +17,7 @@ import urllib.request
17
17
  import urllib.error
18
18
  from typing import Dict, Any, Optional, Tuple
19
19
 
20
- CURRENT_VERSION = "4.7.7"
20
+ CURRENT_VERSION = "4.7.8"
21
21
  CACHE_TTL = 86400 # 24 hours
22
22
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
23
23
  # answer for a full day — otherwise an update released right after an outage