tokensafe 4.7.7 → 4.7.9

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.9",
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.9",
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.9",
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.9",
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.9",
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.9",
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.9",
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,288 @@ def _sidecar_cache_dir() -> str:
648
648
  return os.path.join(_tokensafe_home(), "sidecars")
649
649
 
650
650
 
651
+ # --- ASP.NET Core -----------------------------------------------------------------
652
+ #
653
+ # The .NET adapter is a NuGet package with a middleware mount, so injection is the
654
+ # same shape as Go/Node: one visible, reversible block in Program.cs. The builder
655
+ # line is required only because ASP.NET Core does not expose the service collection
656
+ # after Build(), and EF Core DbContext discovery needs it.
657
+
658
+ _DOTNET_MARK_BEGIN = "// tokensafe:oumv:begin"
659
+ _DOTNET_MARK_END = "// tokensafe:oumv:end"
660
+ _DOTNET_PACKAGE = "TokenSafe.Oumv.AspNetCore"
661
+ _DOTNET_PACKAGE_VERSION = "0.1.0"
662
+
663
+
664
+ def _dotnet_web_project(workspace: str) -> Optional[str]:
665
+ """Finds a web csproj (Microsoft.NET.Sdk.Web or the ASP.NET Core framework reference)."""
666
+ for root, dirs, files in os.walk(workspace):
667
+ dirs[:] = [d for d in dirs if d not in ("bin", "obj", "node_modules", ".git", ".tokensafe")]
668
+ for name in files:
669
+ if not name.endswith(".csproj"):
670
+ continue
671
+ path = os.path.join(root, name)
672
+ try:
673
+ with open(path, "r", encoding="utf-8") as handle:
674
+ content = handle.read()
675
+ except OSError:
676
+ continue
677
+ if "Microsoft.NET.Sdk.Web" in content or "Microsoft.AspNetCore.App" in content:
678
+ return path
679
+ return None
680
+
681
+
682
+ def _find_dotnet_entrypoint(workspace: str, project: Optional[str] = None) -> Optional[str]:
683
+ """Program.cs next to the web project (top-level statements), if present."""
684
+ if project:
685
+ candidate = os.path.join(os.path.dirname(project), "Program.cs")
686
+ if os.path.isfile(candidate):
687
+ return candidate
688
+ candidate = os.path.join(workspace, "Program.cs")
689
+ return candidate if os.path.isfile(candidate) else None
690
+
691
+
692
+ def dotnet_patch_state(workspace: str) -> Dict[str, Any]:
693
+ """Reports whether the OUMV mount is already present in Program.cs."""
694
+ project = _dotnet_web_project(workspace)
695
+ entrypoint = _find_dotnet_entrypoint(workspace, project)
696
+ if not entrypoint:
697
+ return {"entrypoint": None, "patched": False, "project": project}
698
+ try:
699
+ with open(entrypoint, "r", encoding="utf-8") as handle:
700
+ source = handle.read()
701
+ except OSError:
702
+ return {"entrypoint": os.path.relpath(entrypoint, workspace), "patched": False, "project": project}
703
+ return {
704
+ "entrypoint": os.path.relpath(entrypoint, workspace),
705
+ "patched": _DOTNET_MARK_BEGIN in source and _DOTNET_MARK_END in source,
706
+ "project": os.path.relpath(project, workspace) if project else None,
707
+ }
708
+
709
+
710
+ def _dotnet_build(project: str) -> Tuple[bool, str]:
711
+ try:
712
+ result = subprocess.run(
713
+ ["dotnet", "build", project, "-c", "Release", "--nologo", "-v", "quiet"],
714
+ capture_output=True,
715
+ text=True,
716
+ timeout=600,
717
+ )
718
+ return result.returncode == 0, (result.stdout + result.stderr)[-1500:]
719
+ except FileNotFoundError:
720
+ return False, "dotnet SDK not found on PATH"
721
+ except subprocess.TimeoutExpired:
722
+ return False, "dotnet build timed out"
723
+
724
+
725
+ def _ensure_dotnet_dependency(project: str) -> Optional[str]:
726
+ """Adds the NuGet package once; returns a note when the CLI could not do it."""
727
+ try:
728
+ with open(project, "r", encoding="utf-8") as handle:
729
+ content = handle.read()
730
+ except OSError:
731
+ return f"could not read {project}"
732
+ if _DOTNET_PACKAGE in content:
733
+ return None
734
+ try:
735
+ result = subprocess.run(
736
+ ["dotnet", "add", project, "package", _DOTNET_PACKAGE, "--version", _DOTNET_PACKAGE_VERSION],
737
+ capture_output=True,
738
+ text=True,
739
+ timeout=300,
740
+ )
741
+ except FileNotFoundError:
742
+ return f"dotnet SDK not found; add <PackageReference Include=\"{_DOTNET_PACKAGE}\" Version=\"{_DOTNET_PACKAGE_VERSION}\" /> manually"
743
+ except subprocess.TimeoutExpired:
744
+ return "dotnet add package timed out"
745
+ if result.returncode != 0:
746
+ return f"dotnet add package failed; add the PackageReference manually: {(result.stdout + result.stderr)[-300:]}"
747
+ return None
748
+
749
+
750
+ def apply_dotnet_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
751
+ """Inserts `using`, `AddTokensafe()` and `UseTokensafe()` between tokensafe markers."""
752
+ project = _dotnet_web_project(workspace)
753
+ if not project:
754
+ return {"status": "skipped", "reason": "no ASP.NET Core (Microsoft.NET.Sdk.Web) project found"}
755
+ entrypoint = _find_dotnet_entrypoint(workspace, project)
756
+ if not entrypoint:
757
+ return {"status": "skipped", "reason": "no Program.cs next to the web project"}
758
+
759
+ with open(entrypoint, "r", encoding="utf-8") as handle:
760
+ source = handle.read()
761
+ if _DOTNET_MARK_BEGIN in source:
762
+ return {"status": "already_patched", "entrypoint": os.path.relpath(entrypoint, workspace)}
763
+
764
+ builder = re.search(
765
+ r"(?m)^(?P<indent>[ \t]*)(?:var|WebApplicationBuilder)\s+(?P<builder>\w+)\s*=\s*WebApplication\.CreateBuilder\(",
766
+ source,
767
+ )
768
+ app = re.search(
769
+ r"(?m)^(?P<indent>[ \t]*)(?:var|WebApplication)\s+(?P<app>\w+)\s*=\s*(?P<builder>\w+)\.Build\(\)\s*;",
770
+ source,
771
+ )
772
+ if not builder or not app:
773
+ return {
774
+ "status": "skipped",
775
+ "reason": "could not find `WebApplication.CreateBuilder(...)` and `builder.Build()` in Program.cs",
776
+ }
777
+ if builder.group("builder") != app.group("builder"):
778
+ return {"status": "skipped", "reason": "Program.cs builds the app from a different builder variable"}
779
+
780
+ def insertion(line_match: "re.Match[str]", body: str) -> Tuple[int, str]:
781
+ line_end = source.find("\n", line_match.end())
782
+ insert_at = len(source) if line_end < 0 else line_end + 1
783
+ indent = line_match.group("indent")
784
+ block = f"{_DOTNET_MARK_BEGIN}\n{indent}{body}\n{_DOTNET_MARK_END}\n"
785
+ return insert_at, block
786
+
787
+ services_at, services_block = insertion(
788
+ builder, f"{builder.group('builder')}.Services.AddTokensafe();"
789
+ )
790
+ mount_at, mount_block = insertion(app, f"{app.group('app')}.UseTokensafe();")
791
+
792
+ using_block = ""
793
+ if not re.search(r"(?m)^\s*using\s+TokenSafe\.Oumv\s*;", source):
794
+ using_lines = list(re.finditer(r"(?m)^using\s+[^;]+;\s*$", source))
795
+ using_block = f"{_DOTNET_MARK_BEGIN}\nusing TokenSafe.Oumv;\n{_DOTNET_MARK_END}\n"
796
+ if using_lines:
797
+ last = using_lines[-1]
798
+ line_end = source.find("\n", last.end())
799
+ using_at = len(source) if line_end < 0 else line_end + 1
800
+ else:
801
+ using_at = 0
802
+
803
+ patched = source
804
+ # Insert from the bottom up so earlier offsets stay valid.
805
+ for position, block in sorted(((services_at, services_block), (mount_at, mount_block)), reverse=True):
806
+ patched = patched[:position] + block + patched[position:]
807
+ if using_block:
808
+ patched = patched[:using_at] + using_block + patched[using_at:]
809
+
810
+ if dry_run:
811
+ return {
812
+ "status": "dry_run",
813
+ "entrypoint": os.path.relpath(entrypoint, workspace),
814
+ "preview": f"{builder.group('builder')}.Services.AddTokensafe();\n{app.group('app')}.UseTokensafe();",
815
+ }
816
+
817
+ backup_dir = _inject_dir(workspace)
818
+ os.makedirs(backup_dir, exist_ok=True)
819
+ backup_path = os.path.join(backup_dir, os.path.relpath(entrypoint, workspace).replace(os.sep, "__") + ".bak")
820
+ shutil.copy2(entrypoint, backup_path)
821
+ with open(entrypoint, "w", encoding="utf-8") as handle:
822
+ handle.write(patched)
823
+
824
+ dependency_note = _ensure_dotnet_dependency(project)
825
+ build_ok, build_output = _dotnet_build(project) if dependency_note is None else (False, "skipped")
826
+ if not build_ok:
827
+ shutil.copy2(backup_path, entrypoint)
828
+ os.unlink(backup_path)
829
+ return {
830
+ "status": "reverted",
831
+ "entrypoint": os.path.relpath(entrypoint, workspace),
832
+ "reason": dependency_note or "dotnet build failed",
833
+ "build": build_output[-800:],
834
+ }
835
+
836
+ with open(os.path.join(backup_dir, "manifest.json"), "w", encoding="utf-8") as handle:
837
+ json.dump(
838
+ {"entrypoint": entrypoint, "backup": backup_path, "framework": "aspnetcore", "mode": "dotnet_mount"},
839
+ handle,
840
+ indent=2,
841
+ )
842
+ return {
843
+ "status": "patched",
844
+ "entrypoint": os.path.relpath(entrypoint, workspace),
845
+ "framework": "aspnetcore",
846
+ "mode": "dotnet_mount",
847
+ "backup": backup_path,
848
+ "line": f"{app.group('app')}.UseTokensafe();",
849
+ "dependency": f"{_DOTNET_PACKAGE}@{_DOTNET_PACKAGE_VERSION}",
850
+ }
851
+
852
+
853
+ def revert_dotnet_patch(workspace: str) -> Dict[str, Any]:
854
+ manifest_path = os.path.join(_inject_dir(workspace), "manifest.json")
855
+ if not os.path.isfile(manifest_path):
856
+ return {"status": "clean", "reason": "no .NET patch manifest"}
857
+ try:
858
+ with open(manifest_path, "r", encoding="utf-8") as handle:
859
+ manifest = json.load(handle)
860
+ except Exception as exc:
861
+ return {"status": "error", "reason": f"cannot read manifest: {exc}"}
862
+ if manifest.get("mode") != "dotnet_mount":
863
+ return {"status": "clean", "reason": "manifest is not a .NET patch"}
864
+ entrypoint = manifest.get("entrypoint")
865
+ backup = manifest.get("backup")
866
+ if not (entrypoint and backup and os.path.isfile(backup)):
867
+ return {"status": "error", "reason": "backup missing; restore manually"}
868
+ shutil.copy2(backup, entrypoint)
869
+ os.unlink(manifest_path)
870
+ return {"status": "reverted", "entrypoint": os.path.relpath(entrypoint, workspace)}
871
+
872
+
873
+ # Pinned to the backend release: the sidecars are single files, so the cache is
874
+ # content-addressed by SHA-256 and a clean machine downloads the exact bytes the
875
+ # release was certified from. Bump both the tag and the hashes together.
876
+ _SIDECAR_RELEASE_TAG = "v0.7.0"
877
+ _SIDECARS = {
878
+ "spring": (
879
+ "java/src/dev/tokensafe/oumv/OumvSpring.java",
880
+ "OumvSpring.java",
881
+ "b6dda1ecf9638bbcb867310139d9dce1421d0f9f43e6db490ddf2e327637d949",
882
+ ),
883
+ "php": (
884
+ "php/bin/oumv-php",
885
+ "oumv-php",
886
+ "31955f8bd2735a47ef70edae05f978436d70f326da38043bc11248100761ed12",
887
+ ),
888
+ }
889
+
890
+
891
+ def _sha256_file(path: str) -> str:
892
+ digest = hashlib.sha256()
893
+ with open(path, "rb") as handle:
894
+ for chunk in iter(lambda: handle.read(65536), b""):
895
+ digest.update(chunk)
896
+ return digest.hexdigest()
897
+
898
+
899
+ def sidecar_run_command(kind: str, sidecar_path: str, workspace: str) -> Optional[str]:
900
+ """The exact command that starts the sidecar against `workspace`."""
901
+ if not sidecar_path:
902
+ return None
903
+ if kind == "spring":
904
+ return f"tokensafe run-backend java {sidecar_path} --root {workspace} --port 7331"
905
+ if kind == "php":
906
+ return f"tokensafe run-backend php -S 127.0.0.1:7332 {sidecar_path} --root {workspace}"
907
+ return None
908
+
909
+
651
910
  def ensure_sidecar(kind: str) -> Tuple[Optional[str], str]:
652
- """Copies OumvSpring.java / oumv-php into ~/.tokensafe/sidecars.
911
+ """Caches OumvSpring.java / oumv-php at the pinned release and verifies SHA-256.
653
912
 
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.
913
+ Order: a valid cache → a local checkout whose bytes match the pin (developer
914
+ flow, no network) → download from the release tag. A hash mismatch is never
915
+ accepted silently; the note says what failed instead of handing back a
916
+ different file under the certified name.
656
917
  """
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:
918
+ if kind not in _SIDECARS:
662
919
  return None, f"unknown sidecar {kind!r}"
663
- rel_source, filename = source_map[kind]
920
+ rel_source, filename, expected_sha = _SIDECARS[kind]
921
+ cache_dir = _sidecar_cache_dir()
922
+ target = os.path.join(cache_dir, filename)
923
+
924
+ def adopt(source: str, note: str) -> Tuple[str, str]:
925
+ os.makedirs(cache_dir, exist_ok=True)
926
+ shutil.copy2(source, target)
927
+ if kind == "php":
928
+ os.chmod(target, 0o755)
929
+ return target, note
930
+
931
+ if os.path.isfile(target) and _sha256_file(target) == expected_sha:
932
+ return target, f"cached at {_SIDECAR_RELEASE_TAG}"
664
933
 
665
934
  repo_candidates = []
666
935
  env_repo = os.environ.get("OUMV_BACKEND_REPO")
@@ -671,20 +940,43 @@ def ensure_sidecar(kind: str) -> Tuple[Optional[str], str]:
671
940
  os.path.join(os.path.dirname(here), "tokensafe-backend"),
672
941
  os.path.join(here, "..", "tokensafe-backend"),
673
942
  ]
943
+ local_mismatch = None
674
944
  for repo in repo_candidates:
675
945
  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"
946
+ if not os.path.isfile(candidate):
947
+ continue
948
+ if _sha256_file(candidate) == expected_sha:
949
+ return adopt(candidate, f"cached from local checkout matching {_SIDECAR_RELEASE_TAG}")
950
+ local_mismatch = candidate
951
+
952
+ if os.environ.get("TOKENSAFE_SIDECAR_OFFLINE") == "1":
953
+ if local_mismatch:
954
+ return adopt(local_mismatch, f"local checkout (unpinned, offline): {local_mismatch}")
955
+ return None, "offline (TOKENSAFE_SIDECAR_OFFLINE=1) and no cached sidecar"
956
+
957
+ url = (
958
+ f"https://raw.githubusercontent.com/tokensafe-dev/tokensafe-backend/"
959
+ f"{_SIDECAR_RELEASE_TAG}/{rel_source}"
687
960
  )
961
+ try:
962
+ import urllib.request
963
+
964
+ with urllib.request.urlopen(url, timeout=30) as response:
965
+ payload = response.read()
966
+ except Exception as exc:
967
+ if local_mismatch:
968
+ return adopt(local_mismatch, f"download failed ({exc}); local checkout (unpinned): {local_mismatch}")
969
+ return None, f"cannot download {url}: {exc}"
970
+
971
+ actual = hashlib.sha256(payload).hexdigest()
972
+ if actual != expected_sha:
973
+ return None, f"sha256 mismatch for {url}: expected {expected_sha}, got {actual}"
974
+ os.makedirs(cache_dir, exist_ok=True)
975
+ with open(target, "wb") as handle:
976
+ handle.write(payload)
977
+ if kind == "php":
978
+ os.chmod(target, 0o755)
979
+ return target, f"downloaded from {_SIDECAR_RELEASE_TAG}"
688
980
 
689
981
 
690
982
  def plan(workspace: str) -> Dict[str, Any]:
@@ -714,6 +1006,7 @@ def plan(workspace: str) -> Dict[str, Any]:
714
1006
  "node": "backend/node",
715
1007
  "spring": "backend/spring",
716
1008
  "php": "backend/php",
1009
+ "dotnet": "backend/aspnetcore",
717
1010
  }.get(provider, "backend/go")
718
1011
  entry = catalog.get(entry_id, {})
719
1012
  install = entry.get("technology", {}).get("package", {}).get("install")
@@ -751,13 +1044,23 @@ def plan(workspace: str) -> Dict[str, Any]:
751
1044
  "description": "one mountTokensafe(app)/registerTokensafe(app) line between tokensafe markers; byte-exact backup + --revert",
752
1045
  "install": install or "npm install tokensafe-backend-node",
753
1046
  })
1047
+ elif provider == "dotnet":
1048
+ state = dotnet_patch_state(workspace)
1049
+ actions.append({
1050
+ "kind": "dotnet_one_line_patch",
1051
+ "profile": "backend",
1052
+ "framework": "aspnetcore",
1053
+ "writes_repo": True,
1054
+ "already_patched": state["patched"],
1055
+ "entrypoint": state["entrypoint"],
1056
+ "project": state.get("project"),
1057
+ "description": "one AddTokensafe()/UseTokensafe() pair between tokensafe markers; byte-exact backup + --revert",
1058
+ "install": install or f"dotnet add package {_DOTNET_PACKAGE}",
1059
+ "run": "dotnet run",
1060
+ })
754
1061
  elif provider in ("spring", "php"):
755
1062
  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
- )
1063
+ command = sidecar_run_command(provider, sidecar_path or "", workspace)
761
1064
  actions.append({
762
1065
  "kind": "sidecar",
763
1066
  "profile": "backend",
@@ -818,6 +1121,8 @@ def apply(workspace: str, dry_run: bool = False, include_go: bool = True) -> Dic
818
1121
  results["actions"].append({"kind": "go_one_line_patch", **apply_go_patch(workspace, dry_run=dry_run)})
819
1122
  elif backend.get("provider") == "node":
820
1123
  results["actions"].append({"kind": "node_one_line_patch", **apply_node_patch(workspace, dry_run=dry_run)})
1124
+ elif backend.get("provider") == "dotnet":
1125
+ results["actions"].append({"kind": "dotnet_one_line_patch", **apply_dotnet_patch(workspace, dry_run=dry_run)})
821
1126
  elif backend.get("provider") in ("spring", "php"):
822
1127
  sidecar_path, note = ensure_sidecar(backend["provider"])
823
1128
  results["actions"].append({
@@ -825,11 +1130,7 @@ def apply(workspace: str, dry_run: bool = False, include_go: bool = True) -> Dic
825
1130
  "status": "ready" if sidecar_path else "needs-source",
826
1131
  "sidecar": sidecar_path,
827
1132
  "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
- ),
1133
+ "run": sidecar_run_command(backend["provider"], sidecar_path or "", workspace),
833
1134
  })
834
1135
 
835
1136
  return results
@@ -840,4 +1141,5 @@ def revert(workspace: str) -> Dict[str, Any]:
840
1141
  "workspace": workspace,
841
1142
  "go": revert_go_patch(workspace),
842
1143
  "node": revert_node_patch(workspace),
1144
+ "dotnet": revert_dotnet_patch(workspace),
843
1145
  }
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.9"
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]:
package/src/retrofit.py CHANGED
@@ -4,9 +4,11 @@ Enables existing frontend and backend projects to adopt the OUMV protocol
4
4
  incrementally without migrating frameworks or restructuring codebases.
5
5
  """
6
6
 
7
+ import glob
7
8
  import os
8
9
  import json
9
10
  import time
11
+ from pathlib import Path
10
12
  from typing import Dict, Any, List, Optional, Tuple
11
13
 
12
14
  # Top-level directories that hold frontend source in a repo-root app (as opposed to
@@ -310,6 +312,44 @@ def detect_project_stack(workspace_dir: str) -> Dict[str, Any]:
310
312
  })
311
313
  break
312
314
 
315
+ # ASP.NET Core detection: Microsoft.NET.Sdk.Web or the ASP.NET Core
316
+ # framework reference in a csproj.
317
+ for csproj in sorted(glob.glob(os.path.join(target_dir, "**", "*.csproj"), recursive=True)):
318
+ if any(part in ("bin", "obj", "node_modules") for part in Path(csproj).parts):
319
+ continue
320
+ try:
321
+ with open(csproj, "r", encoding="utf-8", errors="replace") as f:
322
+ csproj_content = f.read()
323
+ except Exception:
324
+ continue
325
+ if "Microsoft.NET.Sdk.Web" not in csproj_content and "Microsoft.AspNetCore.App" not in csproj_content:
326
+ continue
327
+ rel_csproj = os.path.relpath(csproj, workspace_dir)
328
+ _add_detected(rel_csproj)
329
+ if "nuget/dotnet" not in stack["package_managers"]:
330
+ stack["package_managers"].append("nuget/dotnet")
331
+ dotnet_entry = {
332
+ "framework": "aspnetcore",
333
+ "provider": "dotnet",
334
+ "adapter": "tokensafe-backend/dotnet",
335
+ "language": "csharp",
336
+ "root": os.path.dirname(rel_csproj) or ".",
337
+ "oumv_supported": True,
338
+ "status": "ready",
339
+ }
340
+ if not stack["backend"] or not stack["backend"].get("oumv_supported", False):
341
+ stack["backend"] = dotnet_entry
342
+ _add_package({
343
+ "role": "backend",
344
+ "path": dotnet_entry["root"],
345
+ "framework": "aspnetcore",
346
+ "provider": "dotnet",
347
+ "adapter": "tokensafe-backend/dotnet",
348
+ "oumvSupported": True,
349
+ "status": "ready",
350
+ })
351
+ break
352
+
313
353
  composer_path = os.path.join(target_dir, "composer.json")
314
354
  if os.path.isfile(composer_path):
315
355
  try:
@@ -585,6 +625,32 @@ def get_adapters_catalog() -> List[Dict[str, Any]]:
585
625
  {"name": "verify.behavior", "constraints": {"readOnly": True, "developmentOnly": True}},
586
626
  ],
587
627
  },
628
+ {
629
+ "id": "backend/aspnetcore",
630
+ "name": "ASP.NET Core Adapter (minimal APIs, MVC controllers, EF Core)",
631
+ "profile": "backend",
632
+ "profiles": ["backend"],
633
+ "repo": "tokensafe-backend/dotnet",
634
+ "mode": "hybrid",
635
+ "status": "ready",
636
+ "description": "In-process endpoint dispatch for minimal APIs and controllers, Roslyn syntax pre-flight, and verify.sandboxRollback that rolls every auto-discovered EF Core DbContext back",
637
+ "technology": {
638
+ "language": "csharp",
639
+ "framework": "aspnetcore",
640
+ "package": {
641
+ "manager": "nuget",
642
+ "name": "TokenSafe.Oumv.AspNetCore",
643
+ "install": "dotnet add package TokenSafe.Oumv.AspNetCore",
644
+ },
645
+ },
646
+ "capabilities": [
647
+ {"name": "observe.resources", "constraints": {"readOnly": True, "developmentOnly": False}},
648
+ {"name": "observe.runtime_state", "constraints": {"readOnly": True, "developmentOnly": False}},
649
+ {"name": "understand.causality", "constraints": {"readOnly": True, "developmentOnly": False, "limitations": ["requires observed request traces (UseTokensafe middleware or oumv/verify)"]}},
650
+ {"name": "mutate.source", "constraints": {"readOnly": False, "developmentOnly": False, "requiresPermission": "permissions.mutate != false"}},
651
+ {"name": "verify.runtime_behavior", "constraints": {"readOnly": True, "developmentOnly": False}},
652
+ ],
653
+ },
588
654
  {
589
655
  "id": "backend/spring",
590
656
  "name": "Spring Boot Adapter (JDK-only sidecar)",
@@ -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.9"
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.9"
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