tokensafe 4.7.9 → 4.7.10

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.9",
2
+ "version": "4.7.10",
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.9",
3
+ "version": "4.7.10",
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.9",
4
+ "version": "4.7.10",
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.9",
4
+ "version": "4.7.10",
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.9",
6
+ "version": "4.7.10",
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.9",
26
+ "version": "4.7.10",
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.9",
42
+ "version": "4.7.10",
43
43
  "runtimeHint": "uvx",
44
44
  "transport": {
45
45
  "type": "stdio"
@@ -18,6 +18,7 @@ Two very different injection strategies live here, because the runtimes differ:
18
18
 
19
19
  from __future__ import annotations
20
20
 
21
+ import glob
21
22
  import hashlib
22
23
  import json
23
24
  import os
@@ -63,6 +64,51 @@ def _inject_dir(workspace: str) -> str:
63
64
  return os.path.join(_tokensafe_home(), _INJECT_DIRNAME, _workspace_id(workspace))
64
65
 
65
66
 
67
+ def _manifest_path(workspace: str, kind: str) -> str:
68
+ """One manifest per adapter kind: a monorepo can carry a Go patch and a .NET
69
+ patch at once, and a single shared file would lose the first one's backup."""
70
+ return os.path.join(_inject_dir(workspace), "manifests", f"{kind}.json")
71
+
72
+
73
+ def _write_manifest(workspace: str, kind: str, payload: Dict[str, Any]) -> str:
74
+ path = _manifest_path(workspace, kind)
75
+ os.makedirs(os.path.dirname(path), exist_ok=True)
76
+ with open(path, "w", encoding="utf-8") as f:
77
+ json.dump(payload, f, indent=2)
78
+ return path
79
+
80
+
81
+ def _read_manifest(workspace: str, kind: str, legacy_modes: tuple) -> Optional[Dict[str, Any]]:
82
+ """Own manifest first; a legacy single manifest.json only when its mode belongs
83
+ to this adapter (the old file was shared by every kind)."""
84
+ own = _manifest_path(workspace, kind)
85
+ if os.path.isfile(own):
86
+ try:
87
+ with open(own, "r", encoding="utf-8") as f:
88
+ data = json.load(f)
89
+ data["_manifest"] = own
90
+ return data
91
+ except Exception:
92
+ return None
93
+ legacy = os.path.join(_inject_dir(workspace), "manifest.json")
94
+ if os.path.isfile(legacy):
95
+ try:
96
+ with open(legacy, "r", encoding="utf-8") as f:
97
+ data = json.load(f)
98
+ except Exception:
99
+ return None
100
+ if data.get("mode") in legacy_modes:
101
+ data["_manifest"] = legacy
102
+ return data
103
+ return None
104
+
105
+
106
+ def _delete_manifest(manifest: Dict[str, Any]) -> None:
107
+ path = manifest.get("_manifest")
108
+ if path and os.path.isfile(path):
109
+ os.unlink(path)
110
+
111
+
66
112
  def pyhooks_dir() -> str:
67
113
  return os.path.join(_tokensafe_home(), _PYHOOKS_DIRNAME)
68
114
 
@@ -235,7 +281,7 @@ def go_patch_state(workspace: str) -> Dict[str, Any]:
235
281
  _GO_MODULE = "github.com/tokensafe-dev/tokensafe-backend/go"
236
282
  # Keep in step with the backend release tag (go/vX.Y.Z): injection must never
237
283
  # downgrade an adapter that is already newer than this pin.
238
- _GO_MODULE_VERSION = "v0.7.0"
284
+ _GO_MODULE_VERSION = "v0.9.0"
239
285
 
240
286
 
241
287
  def _version_tuple(tag: str):
@@ -454,17 +500,12 @@ def apply_go_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
454
500
  "build_output": build_output[-1200:],
455
501
  }
456
502
 
457
- with open(os.path.join(backup_dir, "manifest.json"), "w", encoding="utf-8") as f:
458
- json.dump(
459
- {
460
- "entrypoint": path,
461
- "backup": backup_path,
462
- "framework": framework,
463
- "mode": "serve" if wrapped is not None else "mount",
464
- },
465
- f,
466
- indent=2,
467
- )
503
+ _write_manifest(workspace, "go", {
504
+ "entrypoint": path,
505
+ "backup": backup_path,
506
+ "framework": framework,
507
+ "mode": "serve" if wrapped is not None else "mount",
508
+ })
468
509
 
469
510
  return {
470
511
  "status": "patched",
@@ -494,17 +535,15 @@ def _go_build(workspace: str) -> Tuple[bool, str]:
494
535
 
495
536
 
496
537
  def revert_go_patch(workspace: str) -> Dict[str, Any]:
497
- manifest_path = os.path.join(_inject_dir(workspace), "manifest.json")
498
- if not os.path.isfile(manifest_path):
538
+ manifest = _read_manifest(workspace, "go", ("serve", "mount", "go_patch"))
539
+ if manifest is None:
499
540
  return {"status": "nothing-to-revert"}
500
- with open(manifest_path, "r", encoding="utf-8") as f:
501
- manifest = json.load(f)
502
541
  target = manifest.get("entrypoint")
503
542
  backup = manifest.get("backup")
504
543
  if not target or not backup or not os.path.isfile(backup):
505
544
  return {"status": "error", "reason": "backup missing"}
506
545
  shutil.copy2(backup, target)
507
- os.remove(manifest_path)
546
+ _delete_manifest(manifest)
508
547
  return {"status": "reverted", "entrypoint": os.path.relpath(target, workspace)}
509
548
 
510
549
 
@@ -612,8 +651,7 @@ def apply_node_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
612
651
  shutil.copy2(path, backup_path)
613
652
  with open(path, "w", encoding="utf-8") as f:
614
653
  f.write(patched)
615
- with open(os.path.join(backup_dir, "manifest.json"), "w", encoding="utf-8") as f:
616
- json.dump({"entrypoint": path, "backup": backup_path, "framework": framework, "mode": "node_mount"}, f, indent=2)
654
+ _write_manifest(workspace, "node", {"entrypoint": path, "backup": backup_path, "framework": framework})
617
655
  return {
618
656
  "status": "patched",
619
657
  "entrypoint": os.path.relpath(path, workspace),
@@ -625,22 +663,15 @@ def apply_node_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
625
663
 
626
664
 
627
665
  def revert_node_patch(workspace: str) -> Dict[str, Any]:
628
- manifest_path = os.path.join(_inject_dir(workspace), "manifest.json")
629
- if not os.path.isfile(manifest_path):
666
+ manifest = _read_manifest(workspace, "node", ("node_mount",))
667
+ if manifest is None:
630
668
  return {"status": "clean", "reason": "no Node patch manifest"}
631
- try:
632
- with open(manifest_path, "r", encoding="utf-8") as f:
633
- manifest = json.load(f)
634
- except Exception as exc:
635
- return {"status": "error", "reason": f"cannot read manifest: {exc}"}
636
- if manifest.get("mode") != "node_mount":
637
- return {"status": "clean", "reason": "manifest is not a Node patch"}
638
669
  entrypoint = manifest.get("entrypoint")
639
670
  backup = manifest.get("backup")
640
671
  if not (entrypoint and backup and os.path.isfile(backup)):
641
672
  return {"status": "error", "reason": "backup missing; restore manually"}
642
673
  shutil.copy2(backup, entrypoint)
643
- os.unlink(manifest_path)
674
+ _delete_manifest(manifest)
644
675
  return {"status": "reverted", "entrypoint": os.path.relpath(entrypoint, workspace)}
645
676
 
646
677
 
@@ -658,8 +689,26 @@ def _sidecar_cache_dir() -> str:
658
689
  _DOTNET_MARK_BEGIN = "// tokensafe:oumv:begin"
659
690
  _DOTNET_MARK_END = "// tokensafe:oumv:end"
660
691
  _DOTNET_PACKAGE = "TokenSafe.Oumv.AspNetCore"
661
- _DOTNET_PACKAGE_VERSION = "0.1.0"
692
+ _DOTNET_PACKAGE_VERSION = "0.1.1"
693
+
694
+
662
695
 
696
+ def _dotnet_cli() -> str:
697
+ """Resolves the dotnet executable: explicit override, then DOTNET_ROOT, then PATH.
698
+
699
+ A machine can carry an old SDK on PATH (this one had 7.0) while a current one
700
+ lives under DOTNET_ROOT; the build pre-flight must use the latter or a net10
701
+ project fails to compile for the wrong reason.
702
+ """
703
+ override = os.environ.get("TOKENSAFE_DOTNET")
704
+ if override and os.path.isfile(override):
705
+ return override
706
+ root = os.environ.get("DOTNET_ROOT")
707
+ if root:
708
+ candidate = os.path.join(root, "dotnet.exe" if os.name == "nt" else "dotnet")
709
+ if os.path.isfile(candidate):
710
+ return candidate
711
+ return "dotnet"
663
712
 
664
713
  def _dotnet_web_project(workspace: str) -> Optional[str]:
665
714
  """Finds a web csproj (Microsoft.NET.Sdk.Web or the ASP.NET Core framework reference)."""
@@ -710,7 +759,7 @@ def dotnet_patch_state(workspace: str) -> Dict[str, Any]:
710
759
  def _dotnet_build(project: str) -> Tuple[bool, str]:
711
760
  try:
712
761
  result = subprocess.run(
713
- ["dotnet", "build", project, "-c", "Release", "--nologo", "-v", "quiet"],
762
+ [_dotnet_cli(), "build", project, "-c", "Release", "--nologo", "-v", "quiet"],
714
763
  capture_output=True,
715
764
  text=True,
716
765
  timeout=600,
@@ -733,7 +782,7 @@ def _ensure_dotnet_dependency(project: str) -> Optional[str]:
733
782
  return None
734
783
  try:
735
784
  result = subprocess.run(
736
- ["dotnet", "add", project, "package", _DOTNET_PACKAGE, "--version", _DOTNET_PACKAGE_VERSION],
785
+ [_dotnet_cli(), "add", project, "package", _DOTNET_PACKAGE, "--version", _DOTNET_PACKAGE_VERSION],
737
786
  capture_output=True,
738
787
  text=True,
739
788
  timeout=300,
@@ -833,12 +882,8 @@ def apply_dotnet_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
833
882
  "build": build_output[-800:],
834
883
  }
835
884
 
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
- )
885
+ _write_manifest(workspace, "dotnet",
886
+ {"entrypoint": entrypoint, "backup": backup_path, "framework": "aspnetcore"})
842
887
  return {
843
888
  "status": "patched",
844
889
  "entrypoint": os.path.relpath(entrypoint, workspace),
@@ -851,39 +896,32 @@ def apply_dotnet_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
851
896
 
852
897
 
853
898
  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):
899
+ manifest = _read_manifest(workspace, "dotnet", ("dotnet_mount",))
900
+ if manifest is None:
856
901
  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
902
  entrypoint = manifest.get("entrypoint")
865
903
  backup = manifest.get("backup")
866
904
  if not (entrypoint and backup and os.path.isfile(backup)):
867
905
  return {"status": "error", "reason": "backup missing; restore manually"}
868
906
  shutil.copy2(backup, entrypoint)
869
- os.unlink(manifest_path)
907
+ _delete_manifest(manifest)
870
908
  return {"status": "reverted", "entrypoint": os.path.relpath(entrypoint, workspace)}
871
909
 
872
910
 
873
911
  # Pinned to the backend release: the sidecars are single files, so the cache is
874
912
  # content-addressed by SHA-256 and a clean machine downloads the exact bytes the
875
913
  # release was certified from. Bump both the tag and the hashes together.
876
- _SIDECAR_RELEASE_TAG = "v0.7.0"
914
+ _SIDECAR_RELEASE_TAG = "v0.9.0"
877
915
  _SIDECARS = {
878
916
  "spring": (
879
917
  "java/src/dev/tokensafe/oumv/OumvSpring.java",
880
918
  "OumvSpring.java",
881
- "b6dda1ecf9638bbcb867310139d9dce1421d0f9f43e6db490ddf2e327637d949",
919
+ "011b770c69e182f339b36ef1002dbcf135e066744285354b64990ec3b595afb3",
882
920
  ),
883
921
  "php": (
884
922
  "php/bin/oumv-php",
885
923
  "oumv-php",
886
- "31955f8bd2735a47ef70edae05f978436d70f326da38043bc11248100761ed12",
924
+ "f22c19c050869d613989dea24edde0cacdc3d3fb876cd43834ca4e614ec89900",
887
925
  ),
888
926
  }
889
927
 
@@ -1085,7 +1123,8 @@ def plan(workspace: str) -> Dict[str, Any]:
1085
1123
  "profiles": [p for p in ("frontend", "backend") if stack.get(p)],
1086
1124
  "actions": actions,
1087
1125
  "python_autoload_present": python_autoload_present(),
1088
- "revertable": os.path.isfile(os.path.join(_inject_dir(workspace), "manifest.json")),
1126
+ "revertable": bool(glob.glob(os.path.join(_inject_dir(workspace), "manifests", "*.json")))
1127
+ or os.path.isfile(os.path.join(_inject_dir(workspace), "manifest.json")),
1089
1128
  }
1090
1129
 
1091
1130
 
package/src/installer.py CHANGED
@@ -2345,7 +2345,7 @@ WantedBy=default.target
2345
2345
  "message": "; ".join(msgs) if msgs else "Cleaned"
2346
2346
  }
2347
2347
 
2348
- cls.restart_mcp_daemons()
2348
+ cls.restart_mcp_daemons(kill_running=True)
2349
2349
  proj_report = cls.uninstall_project(os.getcwd())
2350
2350
 
2351
2351
  purged = False
@@ -2429,7 +2429,7 @@ WantedBy=default.target
2429
2429
  else:
2430
2430
  print(f" \033[33m–\033[0m \033[1m{name}\033[0m: Nothing to remove")
2431
2431
 
2432
- cls.restart_mcp_daemons()
2432
+ cls.restart_mcp_daemons(kill_running=True)
2433
2433
  proj_rep = cls.uninstall_project(os.getcwd())
2434
2434
  if proj_rep.get("cleaned_rules"):
2435
2435
  print(f"\n\033[32m✔ Cleaned project rules from: {', '.join(proj_rep['cleaned_rules'])}\033[0m")
@@ -2482,10 +2482,16 @@ WantedBy=default.target
2482
2482
  return False
2483
2483
 
2484
2484
  @classmethod
2485
- def restart_mcp_daemons(cls) -> int:
2485
+ def restart_mcp_daemons(cls, kill_running: bool = False) -> int:
2486
2486
  """
2487
- Touches the MCP reload marker and terminates active TokenSafe MCP server daemons
2488
- so auto-reconnecting IDEs (Antigravity, Cursor, Claude Code) spawn the updated version.
2487
+ Touches the MCP reload marker so auto-reconnecting IDEs (Antigravity, Cursor,
2488
+ Claude Code) spawn the updated version.
2489
+
2490
+ By default nothing is killed: running TokenSafe MCP servers belong to live
2491
+ sessions of any host, and a machine-wide SIGTERM during an update kills
2492
+ concurrent sessions' gateways (session-scoped MCP hosts never respawn them).
2493
+ Uninstall flows pass kill_running=True because removing TokenSafe should
2494
+ stop it everywhere.
2489
2495
  """
2490
2496
  try:
2491
2497
  # Data-dir resolution is context-independent (canonical
@@ -2500,7 +2506,7 @@ WantedBy=default.target
2500
2506
  except Exception:
2501
2507
  pass
2502
2508
 
2503
- if os.name == "nt":
2509
+ if not kill_running or os.name == "nt":
2504
2510
  return 0
2505
2511
 
2506
2512
  my_pid = os.getpid()
@@ -2906,11 +2912,12 @@ WantedBy=default.target
2906
2912
  except Exception:
2907
2913
  pass
2908
2914
 
2909
- # 6. Restart running MCP server daemons so IDEs load the new version
2915
+ # 6. Flag the reload so auto-reconnecting IDEs pick the new version.
2916
+ # Running servers are NOT killed: they belong to live sessions of
2917
+ # other agents, and session-scoped MCP hosts never respawn them.
2910
2918
  restarted_count = cls.restart_mcp_daemons()
2911
- if restarted_count > 0:
2912
- print(f" {GREEN}✔{RESET} Restarted {restarted_count} running TokenSafe MCP daemon(s).")
2913
- print(f" {CYAN}ℹ{RESET} Antigravity/Cursor/Claude Code reconnect automatically; reload MCP in Claude Desktop/VS Code if disconnected.")
2919
+ if restarted_count == 0:
2920
+ print(f" {CYAN}ℹ{RESET} Reload marker written; running sessions keep their current engine until restarted (by design).")
2914
2921
 
2915
2922
  # 7. Proxy re-assertion (ultimate, default-on): TokenSafe is the default LLM
2916
2923
  # route for every wire-able agent. Agent/app updates are known to rewrite
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.9"
47
+ "version": "4.7.10"
48
48
  }
49
49
 
50
50
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -86,6 +86,48 @@ def _workspace_root() -> Optional[str]:
86
86
  return current_root() or get_active_workspace()
87
87
 
88
88
 
89
+ def _plausible_project_root(path: Optional[str]) -> bool:
90
+ """True when a directory can act as this server's workspace root.
91
+
92
+ Rejects missing/non-dirs, system/plugin dirs, and OS scratch space — the
93
+ same classes of roots the lifecycle hooks refuse for the active marker."""
94
+ if not path or not os.path.isdir(path):
95
+ return False
96
+ if is_plugin_or_system_dir(path):
97
+ return False
98
+ try:
99
+ from src.paths import is_transient_dir
100
+ if is_transient_dir(path):
101
+ return False
102
+ except Exception:
103
+ pass
104
+ return True
105
+
106
+
107
+ def _oumv_default_workspace() -> Optional[str]:
108
+ """Default workspace for an oumv call that carries no explicit root.
109
+
110
+ Precedence: session scope (ACP agent, in-process loop) > this server's own
111
+ spawn cwd > the machine-wide active marker. The marker is rewritten by the
112
+ hooks of EVERY concurrent session, so in multi-root setups it can name a
113
+ repo the caller never asked about; the MCP server is started by the host
114
+ with cwd in the primary workspace, which is per-server and race-free.
115
+ """
116
+ scoped = current_root()
117
+ # Session scope is bound explicitly by our own in-process agent / ACP server
118
+ # (benchmark and smoke workspaces legitimately live in temp dirs), so only
119
+ # existence and system-dir checks apply here.
120
+ if scoped and os.path.isdir(scoped) and not is_plugin_or_system_dir(scoped):
121
+ return scoped
122
+ cwd = os.getcwd()
123
+ if _plausible_project_root(cwd):
124
+ return cwd
125
+ marker = get_active_workspace()
126
+ if marker:
127
+ return marker
128
+ return cwd or None
129
+
130
+
89
131
  def _client_supports_pointers() -> bool:
90
132
  """Out-of-the-box capability detection (zero env vars): returns True once the
91
133
  MCP client has fetched tools/list (seeing force_full) or identified as an
@@ -779,7 +821,8 @@ TOOLS = [{'name': 'smart_read_file',
779
821
  'transcript_path': {'type': 'string'}}}},
780
822
  {'name': 'oumv',
781
823
  'annotations': {'readOnlyHint': False},
782
- 'description': "OUMV runtime: 'status'|'observe' L0-L4|'understand'|'verify'|'mutate' (OCC edit)|'graph'.",
824
+ 'description': "OUMV runtime: 'status'|'observe' L0-L4|'understand'|'verify'|'mutate' (OCC edit)|'graph'|'index' "
825
+ "(repo-wide symbol search: query, kinds?, limit?)|'preview' (dry-run diff, no write).",
783
826
  'inputSchema': {'type': 'object',
784
827
  'properties': {'action': {'type': 'string',
785
828
  'enum': ['status',
@@ -787,7 +830,10 @@ TOOLS = [{'name': 'smart_read_file',
787
830
  'understand',
788
831
  'verify',
789
832
  'mutate',
790
- 'graph']},
833
+ 'graph',
834
+ 'index',
835
+ 'preview',
836
+ 'build']},
791
837
  'level': {'type': 'string'},
792
838
  'query': {'type': 'string'},
793
839
  'target': {'type': 'string'},
@@ -795,11 +841,20 @@ TOOLS = [{'name': 'smart_read_file',
795
841
  'symbol': {'type': 'string'},
796
842
  'replacement': {'type': 'string'},
797
843
  'expectedVersion': {'type': 'string'},
844
+ 'kinds': {'type': 'array',
845
+ 'items': {'type': 'string'},
846
+ 'description': 'index: symbol-kind filter (function, class, ...)'},
847
+ 'limit': {'type': 'integer'},
848
+ 'batch': {'type': 'array',
849
+ 'items': {'type': 'object'},
850
+ 'description': 'preview: batch edits envelope (wire 1.5.0+)'},
851
+ 'timeout_ms': {'type': 'integer',
852
+ 'description': 'preview/build: per-call budget (§3/§14.3)'},
798
853
  'verify_action': {'type': 'string'},
799
854
  'payload': {'type': 'object'},
800
855
  'workspace_dir': {'type': 'string',
801
856
  'description': 'Target repo root; for '
802
- 'status/observe/understand/verify/graph '
857
+ 'status/observe/understand/verify/graph/index/preview '
803
858
  'also accepted as path'}}}},
804
859
  {'name': 'run_helper',
805
860
  'annotations': {'readOnlyHint': False},
@@ -1067,18 +1122,20 @@ def _shared_batch_root(paths: List[str], real_cwd: str) -> Optional[str]:
1067
1122
 
1068
1123
 
1069
1124
  def _oumv_workspace_arg(args: dict, allow_path: bool = False) -> Tuple[Optional[str], Optional[str]]:
1070
- """Validated workspace root for an OUMV call; None means "use the active one".
1125
+ """Validated workspace root for an OUMV call; falls back to a per-server default.
1071
1126
 
1072
1127
  The MCP server inherits the host process cwd, so without this an explicit
1073
1128
  target repo was either dropped (unadvertised property) or ignored, and the
1074
1129
  answer described the bound workspace. A root that does not exist now fails
1075
- closed instead of reporting another repo's stack.
1130
+ closed instead of reporting another repo's stack. With no explicit root the
1131
+ default is the session scope or this server's own cwd — not the machine-wide
1132
+ marker another concurrent session may have just rewritten.
1076
1133
  """
1077
1134
  raw = str(args.get("workspace_dir") or "").strip()
1078
1135
  if not raw and allow_path:
1079
1136
  raw = str(args.get("path") or "").strip()
1080
1137
  if not raw:
1081
- return None, None
1138
+ return _oumv_default_workspace(), None
1082
1139
  ws = os.path.abspath(raw)
1083
1140
  if os.path.isfile(ws):
1084
1141
  ws = os.path.dirname(ws)
@@ -1866,6 +1923,9 @@ _OUMV_ACTIONS = {
1866
1923
  "mutate": "oumv_mutate",
1867
1924
  "verify": "oumv_verify",
1868
1925
  "graph": "oumv_graph",
1926
+ "index": "oumv_index",
1927
+ "preview": "oumv_preview",
1928
+ "build": "oumv_build",
1869
1929
  }
1870
1930
  _HELPER_ACTIONS = {
1871
1931
  "sanitize": "sanitize_command",
@@ -1957,7 +2017,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1957
2017
  # wrong answer. Resolve the explicit root here and fail closed on a bad one.
1958
2018
  ws, ws_err = _oumv_workspace_arg(
1959
2019
  args,
1960
- allow_path=action in ("status", "observe", "understand", "verify", "graph"),
2020
+ allow_path=action in ("status", "observe", "understand", "verify", "graph", "index", "preview", "build"),
1961
2021
  )
1962
2022
  if ws_err:
1963
2023
  return _fallback_error("oumv", ws_err)
@@ -3246,7 +3306,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3246
3306
  ws, ws_err = _oumv_workspace_arg(args, allow_path=True)
3247
3307
  if ws_err:
3248
3308
  return _fallback_error("oumv_status", ws_err)
3249
- ws = ws or get_active_workspace() or os.getcwd()
3309
+ ws = ws or _oumv_default_workspace() or os.getcwd()
3250
3310
  res = OUMVGateway.status(workspace_dir=ws)
3251
3311
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
3252
3312
  except Exception as e:
@@ -3325,6 +3385,57 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3325
3385
  except Exception as e:
3326
3386
  return _fallback_error("oumv_graph", f"failed to query cross-stack graph: {e}")
3327
3387
 
3388
+ elif name == "oumv_index":
3389
+ try:
3390
+ from src.oumv_gateway import OUMVGateway
3391
+ q = str(args.get("query") or "").strip()
3392
+ kinds = args.get("kinds") if isinstance(args.get("kinds"), list) else None
3393
+ limit = args.get("limit") if isinstance(args.get("limit"), int) else 25
3394
+ ws, ws_err = _oumv_workspace_arg(args)
3395
+ if ws_err:
3396
+ return _fallback_error("oumv_index", ws_err)
3397
+ if not q:
3398
+ return _fallback_error("oumv_index", "missing required 'query' (symbol name or substring)")
3399
+ res = OUMVGateway.index(query=q, kinds=kinds, limit=limit, workspace_dir=ws)
3400
+ return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
3401
+ except Exception as e:
3402
+ return _fallback_error("oumv_index", f"failed to search symbol index: {e}")
3403
+
3404
+ elif name == "oumv_preview":
3405
+ try:
3406
+ from src.oumv_gateway import OUMVGateway
3407
+ p = str(args.get("path") or "").strip()
3408
+ sym = str(args.get("symbol") or "").strip() or None
3409
+ rep = args.get("replacement")
3410
+ ev = str(args.get("expectedVersion") or "").strip() or None
3411
+ batch = args.get("batch") if isinstance(args.get("batch"), list) else None
3412
+ rt = str(args.get("runtime") or "auto").strip()
3413
+ ws, ws_err = _oumv_workspace_arg(args)
3414
+ if ws_err:
3415
+ return _fallback_error("oumv_preview", ws_err)
3416
+ if not p:
3417
+ return _fallback_error("oumv_preview", "missing required 'path'")
3418
+ res = OUMVGateway.preview(path=p, symbol=sym, replacement=rep, expected_version=ev,
3419
+ batch=batch, runtime=rt, workspace_dir=ws)
3420
+ return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
3421
+ except Exception as e:
3422
+ return _fallback_error("oumv_preview", f"failed to preview OUMV mutation: {e}")
3423
+
3424
+ elif name == "oumv_build":
3425
+ try:
3426
+ from src.oumv_gateway import OUMVGateway
3427
+ cmd = str(args.get("command") or "").strip() or None
3428
+ tgt = str(args.get("target") or "").strip() or None
3429
+ tms = args.get("timeout_ms") if isinstance(args.get("timeout_ms"), int) else None
3430
+ rt = str(args.get("runtime") or "auto").strip()
3431
+ ws, ws_err = _oumv_workspace_arg(args)
3432
+ if ws_err:
3433
+ return _fallback_error("oumv_build", ws_err)
3434
+ res = OUMVGateway.build(command=cmd, target=tgt, timeout_ms=tms, runtime=rt, workspace_dir=ws)
3435
+ return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
3436
+ except Exception as e:
3437
+ return _fallback_error("oumv_build", f"failed to run OUMV build: {e}")
3438
+
3328
3439
  elif name == "apply_edits":
3329
3440
  try:
3330
3441
  from src.batch_editor import execute_batch_edits
@@ -3918,15 +4029,23 @@ def run_mcp_server():
3918
4029
  }
3919
4030
  # Routing brief (MCP `instructions`): which stacks this workspace
3920
4031
  # works through OUMV and which through the TokenSafe tools. The
3921
- # server usually runs from the plugin dir, so prefer the session
3922
- # workspace marker; extra roots (TOKENSAFE_WORKSPACES) are
4032
+ # default root resolves per server (session scope, then the spawn
4033
+ # cwd, then the active marker), and extra roots — TOKENSAFE_WORKSPACES
4034
+ # plus any multi-root payload the host passed to initialize — are
3923
4035
  # classified one by one so a single-root verdict is never global.
3924
4036
  try:
3925
- from src.session_brief import build_workspace_brief, workspace_roots_from_env
4037
+ from src.session_brief import (
4038
+ build_workspace_brief,
4039
+ workspace_roots_from_env,
4040
+ workspace_roots_from_payload,
4041
+ )
4042
+ extra_roots = workspace_roots_from_env() + workspace_roots_from_payload(params)
4043
+ seen_roots = set()
4044
+ extra_roots = [r for r in extra_roots if not (r in seen_roots or seen_roots.add(r))]
3926
4045
  brief = build_workspace_brief(
3927
- _workspace_root() or os.getcwd(),
4046
+ _oumv_default_workspace() or os.getcwd(),
3928
4047
  include_live=False,
3929
- extra_workspaces=workspace_roots_from_env(),
4048
+ extra_workspaces=extra_roots,
3930
4049
  )
3931
4050
  if brief:
3932
4051
  response["result"]["instructions"] = brief
@@ -41,9 +41,10 @@ _UNSUPPORTED_HINTS = (
41
41
  class OUMVGateway:
42
42
  """Dispatches OUMV protocol calls to live DevServers with zero-config discovery."""
43
43
 
44
- _cached_fe: Optional[Dict[str, Any]] = None
45
- _cached_be: Optional[Dict[str, Any]] = None
46
- _last_scan_time: float = 0.0
44
+ # Per-workspace endpoint cache: one process serves several workspace roots
45
+ # (multi-root sessions), so root A's live runtime must never leak into
46
+ # root B's status/observe answer.
47
+ _workspace_states: Dict[str, Dict[str, Any]] = {}
47
48
  _SCAN_INTERVAL_SEC: float = 5.0
48
49
  # Liveness cache for descriptor-derived ports: the bash guard runs per command,
49
50
  # so a TCP probe must be memoized instead of blocking every invocation.
@@ -88,40 +89,68 @@ class OUMVGateway:
88
89
  return cls._is_port_open(parsed.hostname or "127.0.0.1", int(port))
89
90
 
90
91
  @classmethod
91
- def _drop_stale_descriptor_endpoints(cls) -> List[Dict[str, Any]]:
92
+ def _ws_key(cls, workspace_dir: Optional[str] = None) -> str:
93
+ """Canonical per-workspace cache key (realpath'd, never empty)."""
94
+ base = workspace_dir or get_active_workspace() or os.getcwd()
95
+ return os.path.realpath(os.path.abspath(base))
96
+
97
+ @classmethod
98
+ def _state_for(cls, workspace_dir: Optional[str] = None) -> Dict[str, Any]:
99
+ """Per-workspace endpoint state: {"fe", "be", "last_scan"}."""
100
+ return cls._workspace_states.setdefault(
101
+ cls._ws_key(workspace_dir), {"fe": None, "be": None, "last_scan": 0.0}
102
+ )
103
+
104
+ @classmethod
105
+ def _drop_stale_descriptor_endpoints(cls, workspace_dir: Optional[str] = None) -> List[Dict[str, Any]]:
92
106
  """Clears descriptor-sourced endpoints whose port no longer listens.
93
107
 
94
108
  A descriptor is a hint written by the dev server; after a crash it keeps
95
109
  pointing at a dead (or reused) port and every consumer would report CONNECTED.
110
+ Without a workspace_dir, every cached workspace is checked; with one, only
111
+ that root's state is touched (and its drops reported to the caller).
96
112
  Returns the dropped entries so callers can explain the downgrade.
97
113
  """
98
114
  dropped: List[Dict[str, Any]] = []
99
- for attr in ("_cached_fe", "_cached_be"):
100
- entry = getattr(cls, attr)
101
- if entry and entry.get("source") == "descriptor":
102
- url = entry.get("url")
103
- if url and not cls._is_url_live(url):
104
- dropped.append(entry)
105
- setattr(cls, attr, None)
115
+ if workspace_dir is not None:
116
+ states = [cls._state_for(workspace_dir)]
117
+ elif cls._workspace_states:
118
+ states = list(cls._workspace_states.values())
119
+ else:
120
+ states = [cls._state_for(None)]
121
+ for st in states:
122
+ for slot in ("fe", "be"):
123
+ entry = st.get(slot)
124
+ if entry and entry.get("source") == "descriptor":
125
+ url = entry.get("url")
126
+ if url and not cls._is_url_live(url):
127
+ dropped.append(entry)
128
+ st[slot] = None
106
129
  return dropped
107
130
 
108
131
  @classmethod
109
132
  def get_endpoints(cls, workspace_dir: Optional[str] = None) -> Tuple[Optional[Dict[str, Any]], Optional[Dict[str, Any]]]:
110
- """Returns (frontend_endpoint, backend_endpoint) with periodic cache invalidation."""
133
+ """Returns (frontend_endpoint, backend_endpoint) for the given workspace root.
134
+
135
+ Each root has its own scan timestamp and endpoint pair; a scan performed for
136
+ root A never satisfies root B's discovery.
137
+ """
138
+ st = cls._state_for(workspace_dir)
111
139
  now = time.time()
112
- if (now - cls._last_scan_time > cls._SCAN_INTERVAL_SEC) or (not cls._cached_fe and not cls._cached_be):
140
+ if (now - st["last_scan"] > cls._SCAN_INTERVAL_SEC) or (not st["fe"] and not st["be"]):
113
141
  cls.scan(workspace_dir=workspace_dir)
114
- cls._drop_stale_descriptor_endpoints()
115
- return cls._cached_fe, cls._cached_be
142
+ cls._drop_stale_descriptor_endpoints(workspace_dir)
143
+ return st["fe"], st["be"]
116
144
 
117
145
  @classmethod
118
146
  def scan(cls, workspace_dir: Optional[str] = None):
119
147
  """Scans workspace runtime lockfiles and local ports in parallel."""
120
- cls._last_scan_time = time.time()
121
- ws = workspace_dir or get_active_workspace()
148
+ ws = workspace_dir or get_active_workspace() or os.getcwd()
149
+ st = cls._state_for(ws)
150
+ st["last_scan"] = time.time()
122
151
 
123
152
  # 1. Check workspace runtime files (.tokensafe/runtime.json or .oumv/runtime.json)
124
- cls._check_workspace_runtime_files(ws)
153
+ cls._check_workspace_runtime_files(ws, st)
125
154
 
126
155
  # 2. Parallel candidate probe for remaining missing endpoints
127
156
  env_fe = os.environ.get("TOKENSAFE_FRONTEND_URL")
@@ -149,17 +178,17 @@ class OUMVGateway:
149
178
  ]
150
179
 
151
180
  with ThreadPoolExecutor(max_workers=6) as executor:
152
- future_fe = executor.submit(cls._probe_candidates, fe_candidates, "frontend") if not cls._cached_fe else None
153
- future_be = executor.submit(cls._probe_candidates, be_candidates, "backend") if not cls._cached_be else None
181
+ future_fe = executor.submit(cls._probe_candidates, fe_candidates, "frontend") if not st["fe"] else None
182
+ future_be = executor.submit(cls._probe_candidates, be_candidates, "backend") if not st["be"] else None
154
183
 
155
184
  if future_fe:
156
185
  found_fe = future_fe.result()
157
186
  if found_fe:
158
- cls._cached_fe = found_fe
187
+ st["fe"] = found_fe
159
188
  if future_be:
160
189
  found_be = future_be.result()
161
190
  if found_be:
162
- cls._cached_be = found_be
191
+ st["be"] = found_be
163
192
 
164
193
  @staticmethod
165
194
  def global_runtime_file(workspace_dir: str) -> str:
@@ -169,13 +198,50 @@ class OUMVGateway:
169
198
  tokensafe_home = os.environ.get("TOKENSAFE_HOME") or os.path.expanduser("~/.tokensafe")
170
199
  return os.path.join(tokensafe_home, "runtimes", f"{ws_id}.json")
171
200
 
201
+ @staticmethod
202
+ def _descriptor_path_is_trusted(path: str, workspace_dir: Optional[str] = None) -> bool:
203
+ """A global descriptor whose workspace died must not be adopted.
204
+
205
+ Transient roots (system temp dirs) outlive their dev servers: a leftover
206
+ descriptor keeps describing a directory that no longer exists. Such an
207
+ entry is trusted only while the recorded root is still on disk (so live
208
+ smoke-test/benchmark workspaces in temp dirs keep working); user-project
209
+ roots are always trusted and rely on the port-liveness check instead.
210
+ """
211
+ try:
212
+ canonical = os.path.realpath(os.path.abspath(path))
213
+ # Only the global registry entry needs this check: workspace-local files
214
+ # live inside the root they describe, so they cannot outlive it this way.
215
+ runtimes_dir = os.path.realpath(os.path.join(
216
+ os.environ.get("TOKENSAFE_HOME") or os.path.expanduser("~/.tokensafe"), "runtimes"
217
+ ))
218
+ if os.path.dirname(canonical) != runtimes_dir:
219
+ return True
220
+ with open(path, "r", encoding="utf-8") as f:
221
+ data = json.load(f)
222
+ recorded = (data.get("frontend") or {}).get("workspaceRoot") or (data.get("backend") or {}).get("workspaceRoot")
223
+ if not recorded:
224
+ # Legacy descriptors without a workspaceRoot: judge by the file's
225
+ # own location — the sha256 key cannot be reverse-mapped.
226
+ return True
227
+ recorded_real = os.path.realpath(os.path.abspath(recorded))
228
+ if workspace_dir and recorded_real != os.path.realpath(os.path.abspath(workspace_dir)):
229
+ return False # entry under this key describes another root: stale reuse
230
+ from src.paths import is_transient_dir
231
+ if is_transient_dir(recorded_real) and not os.path.isdir(recorded_real):
232
+ return False
233
+ return True
234
+ except Exception:
235
+ return True
236
+
172
237
  @classmethod
173
- def _check_workspace_runtime_files(cls, workspace_dir: str):
174
- lock_paths = [
238
+ def _check_workspace_runtime_files(cls, workspace_dir: str, st: Optional[Dict[str, Any]] = None):
239
+ st = st if st is not None else cls._state_for(workspace_dir)
240
+ lock_paths = [lp for lp in (
175
241
  cls.global_runtime_file(workspace_dir),
176
242
  os.path.join(workspace_dir, ".tokensafe", "runtime.json"),
177
243
  os.path.join(workspace_dir, ".oumv", "runtime.json"),
178
- ]
244
+ ) if cls._descriptor_path_is_trusted(lp, workspace_dir)]
179
245
  for lp in lock_paths:
180
246
  if os.path.isfile(lp):
181
247
  try:
@@ -183,7 +249,7 @@ class OUMVGateway:
183
249
  data = json.load(f)
184
250
  fe_info = data.get("frontend")
185
251
  if fe_info and fe_info.get("url"):
186
- cls._cached_fe = {
252
+ st["fe"] = {
187
253
  "kind": "frontend",
188
254
  "name": fe_info.get("name", "tokensafe-ui"),
189
255
  "version": fe_info.get("version", "1.0.0"),
@@ -195,7 +261,7 @@ class OUMVGateway:
195
261
  }
196
262
  be_info = data.get("backend")
197
263
  if be_info and be_info.get("url"):
198
- cls._cached_be = {
264
+ st["be"] = {
199
265
  "kind": "backend",
200
266
  "name": be_info.get("name", "tokensafe-backend"),
201
267
  "version": be_info.get("version", "1.0.0"),
@@ -207,6 +273,7 @@ class OUMVGateway:
207
273
  }
208
274
  except Exception:
209
275
  pass
276
+ return st
210
277
 
211
278
  @classmethod
212
279
  def _probe_candidates(cls, urls: List[str], kind: str) -> Optional[Dict[str, Any]]:
@@ -240,11 +307,14 @@ class OUMVGateway:
240
307
  }).encode("utf-8")
241
308
 
242
309
  headers = {"Content-Type": "application/json", "User-Agent": "TokenSafe-Gateway/1.0"}
310
+ # Session tokens live in per-workspace states; a URL identifies its runtime
311
+ # unambiguously, so scan every root's state for a match.
243
312
  token = None
244
- if cls._cached_fe and cls._cached_fe.get("url") == endpoint_url:
245
- token = cls._cached_fe.get("sessionToken")
246
- elif cls._cached_be and cls._cached_be.get("url") == endpoint_url:
247
- token = cls._cached_be.get("sessionToken")
313
+ for st in cls._workspace_states.values():
314
+ if st.get("fe", {}) and st["fe"].get("url") == endpoint_url:
315
+ token = st["fe"].get("sessionToken")
316
+ elif st.get("be", {}) and st["be"].get("url") == endpoint_url:
317
+ token = st["be"].get("sessionToken")
248
318
 
249
319
  if token:
250
320
  headers["X-OUMV-Session-Token"] = token
@@ -380,7 +450,7 @@ class OUMVGateway:
380
450
  os.path.join(ws, ".tokensafe", "runtime.json"),
381
451
  os.path.join(ws, ".oumv", "runtime.json"),
382
452
  ):
383
- if not os.path.isfile(lp):
453
+ if not os.path.isfile(lp) or not cls._descriptor_path_is_trusted(lp, ws):
384
454
  continue
385
455
  try:
386
456
  if (now - os.path.getmtime(lp)) > cls._DESCRIPTOR_MAX_AGE_SEC:
@@ -407,11 +477,12 @@ class OUMVGateway:
407
477
  @classmethod
408
478
  def status(cls, workspace_dir: Optional[str] = None) -> Dict[str, Any]:
409
479
  cls.mark_oumv_used(workspace_dir)
410
- cls.scan(workspace_dir=workspace_dir)
480
+ ws = workspace_dir or get_active_workspace() or os.getcwd()
481
+ cls.scan(workspace_dir=ws)
411
482
  # A descriptor whose port is closed must not be reported as a live runtime.
412
- dropped = cls._drop_stale_descriptor_endpoints()
413
- fe, be = cls._cached_fe, cls._cached_be
414
- ws = workspace_dir or get_active_workspace()
483
+ dropped = cls._drop_stale_descriptor_endpoints(ws)
484
+ st = cls._state_for(ws)
485
+ fe, be = st["fe"], st["be"]
415
486
 
416
487
  # Out-of-the-box stack detection
417
488
  stack_info = {}
@@ -459,7 +530,13 @@ class OUMVGateway:
459
530
 
460
531
  @staticmethod
461
532
  def _adapter_lifecycle(stack_info: Dict[str, Any], fe: Optional[Dict[str, Any]], be: Optional[Dict[str, Any]]) -> List[Dict[str, Any]]:
462
- """Per-adapter lifecycle + health per the OUMV Adapter Contract (schemas/adapter.json)."""
533
+ """Per-adapter readiness per the OUMV Adapter Contract (schemas/adapter.json).
534
+
535
+ Every entry carries ONE machine-readable readiness verdict (`status`, mirrored
536
+ by `effective`): active > supported > partial > planned > unsupported. A runtime
537
+ that answers UNSUPPORTED for a detected stack can no longer be reported as a
538
+ `ready` adapter from the catalog at the same time.
539
+ """
463
540
  adapters: List[Dict[str, Any]] = []
464
541
  fe_info = stack_info.get("frontend") or {}
465
542
  be_info = stack_info.get("backend") or {}
@@ -475,38 +552,64 @@ class OUMVGateway:
475
552
  catalog = []
476
553
 
477
554
  def _find_adapter(profile: str, provider: Optional[str]) -> Dict[str, Any]:
555
+ """Exact catalog match only — never substitute a ready adapter of the same
556
+ profile for a different provider (that is how planned stacks looked ready)."""
478
557
  if provider:
479
558
  for a in catalog:
480
559
  if a.get("id") == f"{profile}/{provider}":
481
560
  return a
482
- for a in catalog:
483
- if a.get("profile") == profile and a.get("status") == "ready":
484
- return a
485
561
  return {}
486
562
 
487
563
  def _entry(profile: str, connected: Optional[Dict[str, Any]], detected: bool, info: Dict[str, Any]) -> Dict[str, Any]:
488
564
  provider = info.get("provider")
489
565
  adapter = _find_adapter(profile, provider)
490
- is_planned = detected and (info.get("status") == "planned" or info.get("oumv_supported") is False or adapter.get("status") == "planned")
566
+ catalog_status = adapter.get("status", "planned")
567
+ catalog_ready = catalog_status == "ready"
568
+ exact_match = bool(adapter)
569
+ detection_planned = info.get("status") == "planned" or info.get("oumv_supported") is False
570
+
491
571
  if connected:
492
- state, health, detail = "ACTIVE", "healthy", f"Live runtime: {connected.get('name', 'unknown')}"
493
- elif is_planned:
494
- state = "UNSUPPORTED"
495
- health = "unsupported"
572
+ effective = "active"
573
+ elif not detected:
574
+ effective = "unsupported"
575
+ elif detection_planned or not catalog_ready:
576
+ effective = "planned"
577
+ elif not exact_match:
578
+ # A ready adapter exists for the profile but not for this provider.
579
+ effective = "partial"
580
+ else:
581
+ effective = "supported"
582
+
583
+ if effective == "active":
584
+ state, health = "ACTIVE", "healthy"
585
+ detail = f"Live runtime: {connected.get('name', 'unknown')}"
586
+ elif effective in ("supported", "partial"):
587
+ state, health = "HANDSHAKE", "degraded"
588
+ detail = (
589
+ f"Detected statically ({info.get('framework', 'unknown')}); runtime offline — "
590
+ "hybrid static fallback active"
591
+ )
592
+ if effective == "partial":
593
+ detail += f"; no exact adapter for {profile}/{provider} yet"
594
+ elif effective == "planned":
595
+ state, health = "UNSUPPORTED", "unsupported"
496
596
  detail = (
497
- f"{adapter.get('id', f'{profile}/{provider}')} is not implemented yet (planned). "
597
+ f"{f'{profile}/{provider}' if provider else profile} has no implemented OUMV runtime adapter yet. "
498
598
  "Do not use tokensafe:oumv for this profile — use repo_map, smart_read_file, and scoped_search instead."
499
599
  )
500
- elif detected:
501
- state, health, detail = "HANDSHAKE", "degraded", "Detected statically; runtime offline — hybrid static fallback active"
502
600
  else:
503
- state, health, detail = "DISCOVER", "unavailable", "Not detected in this workspace"
601
+ state, health = "DISCOVER", "unavailable"
602
+ detail = "Not detected in this workspace"
603
+
604
+ caps = adapter.get("capabilities") if effective in ("active", "supported", "partial") else []
504
605
  return {
505
606
  "profile": profile,
506
- "adapter": adapter.get("id", f"{profile}/unknown"),
507
- "status": adapter.get("status", "unknown"),
607
+ "adapter": adapter.get("id", f"{profile}/{provider or 'unknown'}"),
608
+ "status": effective,
609
+ "effective": effective,
610
+ "catalogStatus": catalog_status,
508
611
  "technology": adapter.get("technology"),
509
- "capabilities": adapter.get("capabilities"),
612
+ "capabilities": caps,
510
613
  "lifecycle": {"state": state, "health": {"status": health, "detail": detail}},
511
614
  "security": {
512
615
  "productionFailClosed": True,
@@ -882,3 +985,224 @@ class OUMVGateway:
882
985
  g["edges"] = [e for e in g["edges"] if t in (e["source"] + e["target"]).lower()][:50]
883
986
  g["filteredBy"] = target
884
987
  return g
988
+
989
+ # 7. Tool: oumv index — repo-wide symbol search (spec §14, optional extension)
990
+ _INDEX_MATCH_CAP = 50
991
+
992
+ @classmethod
993
+ def index(cls, query: str, kinds: Optional[List[str]] = None, limit: int = 25, workspace_dir: Optional[str] = None) -> Dict[str, Any]:
994
+ """Repo-wide symbol search over the static code graph (spec `oumv/index`).
995
+
996
+ Closes the largest remaining agent token sink: without it, "where is X
997
+ defined / who calls Y" needs raw grep. Ranking: exact name > prefix >
998
+ qualified-suffix > substring; reverse-edge count (who imports/calls this
999
+ symbol) breaks ties. Falls back to the FTS5 content index when the graph
1000
+ holds nothing for the query, and labels that fallback honestly.
1001
+ """
1002
+ from src.graph_engine import GraphEngine
1003
+ ws = workspace_dir or get_active_workspace() or os.getcwd()
1004
+ q = (query or "").strip()
1005
+ if not q:
1006
+ return {
1007
+ "workspace": ws,
1008
+ "query": query,
1009
+ "error": "VALIDATION_FAILED",
1010
+ "hint": "query is required (a symbol name, Type.member, or substring)",
1011
+ }
1012
+ kind_filter = {k.strip().lower() for k in (kinds or []) if str(k).strip()}
1013
+
1014
+ graph = GraphEngine.get_instance(ws)
1015
+ q_lower = q.lower()
1016
+ scored: List[Tuple[int, int, str, Any]] = [] # (rank, -refs, sym_key, sym)
1017
+ for key, sym in getattr(graph, "symbols", {}).items():
1018
+ name = (sym.name or "").lower()
1019
+ if not name:
1020
+ continue
1021
+ if q_lower == name:
1022
+ rank = 0
1023
+ elif name.startswith(q_lower):
1024
+ rank = 1
1025
+ elif key.lower().endswith("." + q_lower) or key.lower().endswith("::" + q_lower) or name.endswith("." + q_lower):
1026
+ rank = 2
1027
+ elif q_lower in name or q_lower in (sym.signature or "").lower():
1028
+ rank = 3
1029
+ else:
1030
+ continue
1031
+ if kind_filter and sym.kind.lower() not in kind_filter:
1032
+ continue
1033
+ refs = len(getattr(graph, "rev_edges", {}).get(key, ()) or ())
1034
+ scored.append((rank, -refs, key, sym))
1035
+
1036
+ scored.sort(key=lambda item: (item[0], item[1], item[2]))
1037
+ matches = [
1038
+ {
1039
+ "resourceId": f"{sym.kind}:{sym.name}@{sym.file_path}",
1040
+ "name": sym.name,
1041
+ "kind": sym.kind,
1042
+ "file": sym.file_path,
1043
+ "lines": [int(sym.line_start or 0), int(sym.line_end or 0)],
1044
+ "signature": (sym.signature or "").strip(),
1045
+ "refs": -neg_refs,
1046
+ "match": {0: "exact", 1: "prefix", 2: "qualified-suffix", 3: "substring"}[rank],
1047
+ }
1048
+ for rank, neg_refs, _key, sym in scored[:limit]
1049
+ ]
1050
+ provenance = "static-graph"
1051
+ if not matches:
1052
+ try:
1053
+ from src.fts_index import CodeFTSIndex
1054
+ fts_rows = CodeFTSIndex(ws).search(q, limit=limit) or []
1055
+ matches = [
1056
+ {
1057
+ "resourceId": f"text:{row.get('file')}:{row.get('line')}",
1058
+ "name": str(row.get("content", ""))[:120],
1059
+ "kind": "text",
1060
+ "file": row.get("file"),
1061
+ "lines": [int(row.get("line") or 0), int(row.get("line") or 0)],
1062
+ "signature": "",
1063
+ "refs": 0,
1064
+ "match": "fts-content",
1065
+ }
1066
+ for row in fts_rows
1067
+ ]
1068
+ provenance = "fts-content-index"
1069
+ except Exception:
1070
+ matches = []
1071
+ matches = matches[: cls._INDEX_MATCH_CAP]
1072
+ return {
1073
+ "workspace": ws,
1074
+ "query": q,
1075
+ "matches": matches,
1076
+ "totalMatches": len(scored) if provenance == "static-graph" else len(matches),
1077
+ "truncated": (len(scored) if provenance == "static-graph" else len(matches)) > len(matches),
1078
+ "provenance": provenance,
1079
+ "evidence": {"provenance": "static", "confidence": "confirmed", "sourceAdapter": "tokensafe-graph-engine"},
1080
+ }
1081
+
1082
+ # 8. Tool: oumv preview — dry-run diff before commit (spec `oumv/previewEdit`)
1083
+ @classmethod
1084
+ def preview(cls, path: str, symbol: Optional[str] = None, replacement: Optional[str] = None,
1085
+ expected_version: Optional[str] = None, batch: Optional[List[dict]] = None,
1086
+ runtime: str = "auto", workspace_dir: Optional[str] = None) -> Any:
1087
+ """Dry-run an edit: returns the would-be result WITHOUT writing anything.
1088
+
1089
+ Delegates to a live runtime implementing `oumv/previewEdit` when one is
1090
+ connected. Without a live runtime, only the honest subset is served
1091
+ offline: a whole-file replacement preview (real unified diff against the
1092
+ current bytes + syntax check). Symbol-level offline preview is refused
1093
+ instead of guessing a diff the runtime never computed.
1094
+ """
1095
+ ws = workspace_dir or get_active_workspace() or os.getcwd()
1096
+ params: Dict[str, Any] = {
1097
+ "path": path,
1098
+ "filePath": path,
1099
+ "symbol": symbol,
1100
+ "replacement": replacement,
1101
+ "source": replacement,
1102
+ "expectedVersion": expected_version,
1103
+ }
1104
+ if batch:
1105
+ params["edits"] = batch
1106
+ try:
1107
+ url = cls._resolve_client_url(runtime=runtime, target=path, workspace_dir=workspace_dir)
1108
+ res = cls._rpc_call(url, "oumv/previewEdit", params)
1109
+ if isinstance(res, dict):
1110
+ res.setdefault("mode", "LIVE_RUNTIME_PREVIEW")
1111
+ return res
1112
+ except OUMVRpcError as e:
1113
+ if not any(hint in str(e).lower() for hint in _UNSUPPORTED_HINTS):
1114
+ raise # explicit protocol rejection (conflict/syntax/permission) — obey it
1115
+ raise OUMVUnsupportedMethodError(str(e))
1116
+ except RuntimeError as e:
1117
+ if not any(hint in str(e).lower() for hint in _UNSUPPORTED_HINTS):
1118
+ offline = {
1119
+ "mode": "OFFLINE_FULL_FILE_PREVIEW",
1120
+ "path": path,
1121
+ "workspace": ws,
1122
+ "requiresRuntime": True,
1123
+ "hint": (
1124
+ "mutate.preview needs a live OUMV runtime implementing oumv/previewEdit "
1125
+ "(wire 1.6.0+). Only whole-file replacement previews work offline."
1126
+ ),
1127
+ }
1128
+ if symbol:
1129
+ offline["error"] = "UNSUPPORTED_OFFLINE"
1130
+ offline["detail"] = "symbol-level preview needs the runtime's AST; nothing was computed or written"
1131
+ return offline
1132
+ if replacement is None:
1133
+ offline["error"] = "VALIDATION_FAILED"
1134
+ offline["detail"] = "offline preview requires 'replacement' (whole-file content)"
1135
+ return offline
1136
+ abs_path = os.path.normpath(os.path.join(ws, path))
1137
+ if not abs_path.startswith(os.path.abspath(ws)):
1138
+ return {"mode": "OFFLINE_FULL_FILE_PREVIEW", "error": "SECURITY_VIOLATION", "detail": f"Path traversal blocked: {path}"}
1139
+ current = ""
1140
+ if os.path.isfile(abs_path):
1141
+ with open(abs_path, "r", encoding="utf-8", errors="replace") as f:
1142
+ current = f.read()
1143
+ import difflib
1144
+ diff_lines = list(difflib.unified_diff(
1145
+ current.splitlines(keepends=True),
1146
+ (replacement or "").splitlines(keepends=True),
1147
+ fromfile=f"a/{path}", tofile=f"b/{path}",
1148
+ ))
1149
+ offline["diff"] = "".join(diff_lines)
1150
+ offline["unchanged"] = current == (replacement or "")
1151
+ offline["currentVersion"] = cls._hash_version(abs_path)
1152
+ from src.syntax_guard import check_syntax
1153
+ offline["syntaxCheck"] = check_syntax(abs_path, replacement)
1154
+ return offline
1155
+ raise
1156
+
1157
+ # 9. Tool: oumv build — run the runtime's build/test command (spec §14.3)
1158
+ @classmethod
1159
+ def build(cls, command: Optional[str] = None, target: Optional[str] = None,
1160
+ timeout_ms: Optional[int] = None, runtime: str = "auto", workspace_dir: Optional[str] = None) -> Any:
1161
+ """Proxies `oumv/build` to a live runtime; no fabricated offline diagnostics.
1162
+
1163
+ §14.3 is an optional extension: a runtime that does not implement it
1164
+ answers -32601, and without a live runtime the honest answer is that the
1165
+ gateway cannot run the application's own build — not a guessed verdict.
1166
+ """
1167
+ cls.mark_oumv_used(workspace_dir)
1168
+ params: Dict[str, Any] = {}
1169
+ if command:
1170
+ params["command"] = command
1171
+ if target:
1172
+ params["target"] = target
1173
+ if timeout_ms:
1174
+ params["timeoutMs"] = int(timeout_ms)
1175
+ try:
1176
+ url = cls._resolve_client_url(runtime=runtime, target=target, workspace_dir=workspace_dir)
1177
+ res = cls._rpc_call(url, "oumv/build", params)
1178
+ if isinstance(res, dict) and "evidence" not in res:
1179
+ res["evidence"] = {"provenance": "runtime", "confidence": "confirmed", "sourceAdapter": "live-devserver"}
1180
+ return res
1181
+ except OUMVRpcError as e:
1182
+ if not any(hint in str(e).lower() for hint in _UNSUPPORTED_HINTS):
1183
+ raise
1184
+ raise OUMVUnsupportedMethodError(str(e))
1185
+ except RuntimeError as e:
1186
+ # A plain RuntimeError here means no runtime is reachable: the honest
1187
+ # answer is a skip with a reason, never a fabricated verdict.
1188
+ if any(hint in str(e).lower() for hint in _UNSUPPORTED_HINTS):
1189
+ raise
1190
+ return {
1191
+ "status": "skipped",
1192
+ "command": command or "none",
1193
+ "diagnostics": [],
1194
+ "skipReason": (
1195
+ "oumv/build needs a live OUMV runtime implementing §14.3; "
1196
+ "no DevServer is reachable in this workspace"
1197
+ ),
1198
+ "requiresRuntime": True,
1199
+ "hint": "start 'tokensafe dev' (or the app's OUMV adapter) and retry; or run the build/test command yourself",
1200
+ }
1201
+
1202
+ @staticmethod
1203
+ def _hash_version(abs_path: str) -> Optional[str]:
1204
+ import hashlib as _hashlib
1205
+ if not os.path.isfile(abs_path):
1206
+ return None
1207
+ with open(abs_path, "rb") as f:
1208
+ return "sha256:" + _hashlib.sha256(f.read()).hexdigest()
package/src/retrofit.py CHANGED
@@ -516,21 +516,14 @@ def get_adapters_catalog() -> List[Dict[str, Any]]:
516
516
  "profiles": ["frontend"],
517
517
  "repo": "tokensafe-ui",
518
518
  "mode": "hybrid",
519
- "status": "ready",
520
- "description": "Fine-grained reactive signals causality + virtual DOM observer",
519
+ "status": "planned",
520
+ "description": "Planned: fine-grained reactive signals causality + virtual DOM observer. No Solid runtime adapter is implemented yet (the tokensafe-ui plugin ships React and Vue); a Solid repo must use static analysis tools instead",
521
521
  "technology": {
522
522
  "language": "typescript",
523
523
  "framework": "solidjs",
524
524
  "package": {"manager": "npm", "name": "tokensafe-ui", "install": "npm install tokensafe-ui"},
525
525
  },
526
- "capabilities": [
527
- {"name": "observe.resources", "constraints": {"readOnly": True, "developmentOnly": False}},
528
- {"name": "observe.runtime_state", "constraints": {"readOnly": True, "developmentOnly": True}},
529
- {"name": "understand.causality", "constraints": {"readOnly": True, "developmentOnly": True}},
530
- {"name": "understand.impact", "constraints": {"readOnly": True, "developmentOnly": False}},
531
- {"name": "mutate.source", "constraints": {"readOnly": False, "developmentOnly": False, "requiresPermission": "permissions.mutate != false"}},
532
- {"name": "verify.runtime_behavior", "constraints": {"readOnly": True, "developmentOnly": True}},
533
- ],
526
+ "capabilities": [],
534
527
  },
535
528
  {
536
529
  "id": "frontend/vue",
@@ -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.9"
314
+ "User-Agent": "TokenSafe-Sync/4.7.10"
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.9"
20
+ CURRENT_VERSION = "4.7.10"
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