tokensafe 5.0.1 → 5.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.codex-plugin/plugin.json +1 -1
  4. package/assets/logo.svg +1 -13
  5. package/hooks/claude_code_hook.py +5 -1
  6. package/hooks/cursor_hook.py +1 -1
  7. package/kimi.plugin.json +3 -2
  8. package/package.json +1 -1
  9. package/plugin.json +1 -1
  10. package/rules/AGENTS.md +4 -3
  11. package/server.json +3 -3
  12. package/skills/oumv-protocol/SKILL.md +59 -0
  13. package/skills/token-optimizer/SKILL.md +5 -3
  14. package/skills/token-optimizer/references/mcp-tools.md +1 -1
  15. package/tokensafe/adapter_core.py +62 -18
  16. package/tokensafe/atomic_io.py +20 -16
  17. package/tokensafe/auto_inject.py +2 -2
  18. package/tokensafe/backend_release.py +3 -3
  19. package/tokensafe/batch_editor.py +299 -10
  20. package/tokensafe/batch_search.py +53 -0
  21. package/tokensafe/bounded_flock.py +60 -0
  22. package/tokensafe/burn_monitor.py +60 -2
  23. package/tokensafe/call_context.py +158 -0
  24. package/tokensafe/cli.py +41 -13
  25. package/tokensafe/compactor.py +87 -5
  26. package/tokensafe/context_index.py +3 -0
  27. package/tokensafe/dashboard.py +119 -43
  28. package/tokensafe/environment_auditor.py +30 -2
  29. package/tokensafe/fts_index.py +3 -0
  30. package/tokensafe/graph_engine.py +246 -29
  31. package/tokensafe/installer.py +72 -13
  32. package/tokensafe/loop_detector.py +8 -20
  33. package/tokensafe/mcp_server.py +1078 -186
  34. package/tokensafe/metrics.py +173 -46
  35. package/tokensafe/oumv_brief.py +144 -8
  36. package/tokensafe/oumv_gateway.py +689 -222
  37. package/tokensafe/oumv_home.py +259 -0
  38. package/tokensafe/oumv_policy.py +64 -1
  39. package/tokensafe/proc_run.py +162 -0
  40. package/tokensafe/proxy.py +78 -8
  41. package/tokensafe/retrofit.py +484 -82
  42. package/tokensafe/route_index.py +2 -0
  43. package/tokensafe/savings.py +10 -2
  44. package/tokensafe/scoped_search.py +77 -0
  45. package/tokensafe/session_brief.py +17 -2
  46. package/tokensafe/stack_summary.py +73 -0
  47. package/tokensafe/syntax_guard.py +8 -2
  48. package/tokensafe/telemetry_sync.py +1 -1
  49. package/tokensafe/version_checker.py +1 -1
  50. package/tokensafe/web_reader.py +53 -4
  51. package/tokensafe/workspace_roots.py +127 -9
  52. package/assets/social/linkedin_banner.png +0 -0
  53. package/assets/social/tokensafe_logo_square.png +0 -0
@@ -10,6 +10,11 @@ import time
10
10
  import re
11
11
  import socket
12
12
  import hashlib
13
+ import ipaddress
14
+ import itertools
15
+ import functools
16
+ import threading
17
+ import uuid
13
18
  import urllib.request
14
19
  import urllib.error
15
20
  import urllib.parse
@@ -17,16 +22,21 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
17
22
  from typing import Dict, Any, Optional, Tuple, List
18
23
  from tokensafe.paths import get_active_workspace
19
24
  from tokensafe.win_paths import is_within
25
+ from tokensafe import oumv_home
20
26
 
21
27
 
22
28
  class OUMVRpcError(RuntimeError):
23
29
  """Raised when a live OUMV runtime explicitly returns a JSON-RPC error."""
24
30
 
25
- def __init__(self, message: str, code: Optional[int] = None):
31
+ def __init__(self, message: str, code: Optional[int] = None, transport: Optional[str] = None):
26
32
  super().__init__(message)
27
33
  # The JSON-RPC code, when the runtime sent one. Classification must not depend
28
34
  # on the message text: every adapter words -32601 differently.
29
35
  self.code = code
36
+ # None: the runtime answered. "refused": nothing was delivered (safe to fall
37
+ # back offline). "timeout": the request may have been applied — never retry
38
+ # a write behind it.
39
+ self.transport = transport
30
40
 
31
41
 
32
42
  class OUMVUnsupportedMethodError(OUMVRpcError):
@@ -45,6 +55,143 @@ _UNSUPPORTED_HINTS = (
45
55
  "not supported",
46
56
  )
47
57
 
58
+ # Handshake version this gateway speaks (previewEdit/batch/sandbox need 1.6.0).
59
+ _CLIENT_PROTOCOL_VERSION = "1.6.0"
60
+
61
+ # Per-method HTTP budgets. A write that outlives its budget may still land in the
62
+ # runtime, so these are sized for real work, not for liveness probes.
63
+ _RPC_TIMEOUTS = {
64
+ "oumv/handshake": 0.35,
65
+ "oumv/applyEdit": 20.0,
66
+ "oumv/previewEdit": 20.0,
67
+ "oumv/verify": 25.0,
68
+ "oumv/build": 25.0,
69
+ "oumv/cancel": 5.0,
70
+ }
71
+ _RPC_DEFAULT_TIMEOUT = 10.0
72
+ _RPC_MAX_TIMEOUT = 175.0
73
+ _RPC_MAX_REPLY_BYTES = 16 * 1024 * 1024
74
+
75
+ _LOOPBACK_NAMES = frozenset({"localhost", "ip6-localhost", "ip6-loopback"})
76
+
77
+
78
+ def _is_loopback_url(url: Optional[str]) -> bool:
79
+ """http(s) URL whose host is a loopback name or address."""
80
+ try:
81
+ parsed = urllib.parse.urlparse(str(url or ""))
82
+ except ValueError:
83
+ return False
84
+ if parsed.scheme not in ("http", "https"):
85
+ return False
86
+ host = (parsed.hostname or "").lower()
87
+ if not host:
88
+ return False
89
+ if host in _LOOPBACK_NAMES or host.endswith(".localhost"):
90
+ return True
91
+ try:
92
+ return ipaddress.ip_address(host).is_loopback
93
+ except ValueError:
94
+ return False
95
+
96
+
97
+ def _remote_runtimes_allowed() -> bool:
98
+ return (os.environ.get("TOKENSAFE_OUMV_ALLOW_REMOTE") or "").strip().lower() in ("1", "true", "yes", "on")
99
+
100
+
101
+ def _is_method_missing(exc: BaseException) -> bool:
102
+ """-32601 by code; message hints only when the runtime sent no code at all."""
103
+ if not isinstance(exc, OUMVRpcError) or exc.transport:
104
+ return False
105
+ if exc.code is not None:
106
+ return exc.code == -32601
107
+ text = str(exc).lower()
108
+ return any(hint in text for hint in _UNSUPPORTED_HINTS)
109
+
110
+
111
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
112
+ """A runtime never redirects; following one would carry the session token
113
+ and the edit payload to whatever host the Location header names."""
114
+
115
+ def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: D401
116
+ return None
117
+
118
+
119
+ # No proxies (HTTP_PROXY would otherwise route loopback traffic, token included,
120
+ # through a corporate proxy on Linux) and no redirects.
121
+ _RPC_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}), _NoRedirect())
122
+
123
+ # Unique JSON-RPC ids per process: every call used to send id 1.
124
+ _RPC_IDS = itertools.count(1)
125
+
126
+ # Spec §2.1: every request carries a `requestId` the runtime can be asked to
127
+ # cancel. Handshake and cancel itself are control messages and carry none.
128
+ _NO_REQUEST_ID_METHODS = frozenset({"oumv/handshake", "oumv/cancel"})
129
+
130
+ # In-flight registry: {workspace key: {requestId: {"url", "method", "count", "startedAt"}}}
131
+ # in insertion order, so cancel(target='last') names the most recent request.
132
+ _INFLIGHT_LOCK = threading.Lock()
133
+ _INFLIGHT: Dict[str, Dict[str, Dict[str, Any]]] = {}
134
+
135
+ # Per-thread call scope set by @_tracks_request: one tool call runs in one thread.
136
+ _CALL_CTX = threading.local()
137
+
138
+
139
+ def _new_request_id() -> str:
140
+ return str(uuid.uuid4())
141
+
142
+
143
+ def _inflight_add(ws_key: str, request_id: str, url: str, method: str) -> None:
144
+ with _INFLIGHT_LOCK:
145
+ per_ws = _INFLIGHT.setdefault(ws_key, {})
146
+ entry = per_ws.pop(request_id, None) or {"count": 0}
147
+ entry.update({"url": url, "method": method, "startedAt": time.time()})
148
+ entry["count"] += 1
149
+ per_ws[request_id] = entry # re-inserted last: most recent
150
+
151
+
152
+ def _inflight_remove(ws_key: str, request_id: str) -> None:
153
+ with _INFLIGHT_LOCK:
154
+ per_ws = _INFLIGHT.get(ws_key)
155
+ if not per_ws or request_id not in per_ws:
156
+ return
157
+ per_ws[request_id]["count"] -= 1
158
+ if per_ws[request_id]["count"] <= 0:
159
+ del per_ws[request_id]
160
+ if not per_ws:
161
+ _INFLIGHT.pop(ws_key, None)
162
+
163
+
164
+ def _tracks_request(fn):
165
+ """Gives a public gateway call one requestId for all of its runtime RPCs.
166
+
167
+ The caller may supply `request_id` (so a parallel call can cancel it);
168
+ otherwise a uuid4 is generated. A result produced by a live runtime echoes
169
+ it as `requestId`. Nested calls (preview's offline retry) reuse the outer
170
+ scope.
171
+ """
172
+
173
+ @functools.wraps(fn)
174
+ def wrapper(cls, *args, request_id: Optional[str] = None, **kwargs):
175
+ outer = getattr(_CALL_CTX, "scope", None)
176
+ rid = str(request_id or "").strip()
177
+ if outer is not None and not rid:
178
+ return fn(cls, *args, **kwargs)
179
+ scope = {
180
+ "requestId": rid or _new_request_id(),
181
+ "ws": cls._ws_key(kwargs.get("workspace_dir")),
182
+ "live": False,
183
+ }
184
+ _CALL_CTX.scope = scope
185
+ try:
186
+ res = fn(cls, *args, **kwargs)
187
+ finally:
188
+ _CALL_CTX.scope = outer
189
+ if scope["live"] and isinstance(res, dict):
190
+ res.setdefault("requestId", scope["requestId"])
191
+ return res
192
+
193
+ return wrapper
194
+
48
195
 
49
196
  class OUMVGateway:
50
197
  """Dispatches OUMV protocol calls to live DevServers with zero-config discovery."""
@@ -53,6 +200,10 @@ class OUMVGateway:
53
200
  # (multi-root sessions), so root A's live runtime must never leak into
54
201
  # root B's status/observe answer.
55
202
  _workspace_states: Dict[str, Dict[str, Any]] = {}
203
+ # The MCP server runs tool calls concurrently: one thread adding a root's
204
+ # state while another iterates every root raised "dictionary changed size
205
+ # during iteration". Inserts and whole-dict walks go through this lock.
206
+ _states_lock = threading.Lock()
56
207
  _SCAN_INTERVAL_SEC: float = 5.0
57
208
  # Liveness cache for descriptor-derived ports: the bash guard runs per command,
58
209
  # so a TCP probe must be memoized instead of blocking every invocation.
@@ -105,9 +256,15 @@ class OUMVGateway:
105
256
  @classmethod
106
257
  def _state_for(cls, workspace_dir: Optional[str] = None) -> Dict[str, Any]:
107
258
  """Per-workspace endpoint state: {"fe", "be", "last_scan"}."""
108
- return cls._workspace_states.setdefault(
109
- cls._ws_key(workspace_dir), {"fe": None, "be": None, "last_scan": 0.0}
110
- )
259
+ key = cls._ws_key(workspace_dir)
260
+ with cls._states_lock:
261
+ return cls._workspace_states.setdefault(key, {"fe": None, "be": None, "last_scan": 0.0})
262
+
263
+ @classmethod
264
+ def _states_snapshot(cls) -> List[Tuple[str, Dict[str, Any]]]:
265
+ """(ws key, state) pairs, copied under the lock so callers may iterate."""
266
+ with cls._states_lock:
267
+ return list(cls._workspace_states.items())
111
268
 
112
269
  @classmethod
113
270
  def _drop_stale_descriptor_endpoints(cls, workspace_dir: Optional[str] = None) -> List[Dict[str, Any]]:
@@ -123,19 +280,39 @@ class OUMVGateway:
123
280
  if workspace_dir is not None:
124
281
  states = [cls._state_for(workspace_dir)]
125
282
  elif cls._workspace_states:
126
- states = list(cls._workspace_states.values())
283
+ states = [st for _key, st in cls._states_snapshot()]
127
284
  else:
128
285
  states = [cls._state_for(None)]
129
286
  for st in states:
130
287
  for slot in ("fe", "be"):
131
288
  entry = st.get(slot)
132
- if entry and entry.get("source") == "descriptor":
289
+ # Probe-discovered endpoints die too: only descriptor entries used to
290
+ # be checked, so a stopped dev server stayed "connected" for the life
291
+ # of the process and every write failed instead of going offline.
292
+ if entry:
133
293
  url = entry.get("url")
134
294
  if url and not cls._is_url_live(url):
135
295
  dropped.append(entry)
136
296
  st[slot] = None
137
297
  return dropped
138
298
 
299
+ @classmethod
300
+ def _forget_endpoint(cls, url: Optional[str]) -> None:
301
+ """Drops every cached endpoint at `url` (it refused a connection)."""
302
+ if not url:
303
+ return
304
+ for _key, st in cls._states_snapshot():
305
+ for slot in ("fe", "be"):
306
+ entry = st.get(slot)
307
+ if entry and entry.get("url") == url:
308
+ st[slot] = None
309
+ try:
310
+ parsed = urllib.parse.urlparse(url)
311
+ if parsed.port:
312
+ cls._port_liveness.pop((parsed.hostname or "127.0.0.1", int(parsed.port)), None)
313
+ except ValueError:
314
+ pass
315
+
139
316
  @classmethod
140
317
  def get_endpoints(cls, workspace_dir: Optional[str] = None) -> Tuple[Optional[Dict[str, Any]], Optional[Dict[str, Any]]]:
141
318
  """Returns (frontend_endpoint, backend_endpoint) for the given workspace root.
@@ -165,6 +342,15 @@ class OUMVGateway:
165
342
  st["stale"] = []
166
343
  st["last_scan"] = time.time()
167
344
 
345
+ # 0. A probe-found endpoint is re-confirmed on every scan: its port may now
346
+ # belong to another checkout's dev server (or to nothing OUMV at all).
347
+ for slot in ("fe", "be"):
348
+ entry = st.get(slot)
349
+ if entry and entry.get("source") != "descriptor":
350
+ handshake = cls._handshake(entry.get("url"), entry.get("sessionToken"))
351
+ if handshake is None or not cls._probed_runtime_belongs_to(handshake, entry["url"], ws):
352
+ st[slot] = None
353
+
168
354
  # 1. Check workspace runtime files (.tokensafe/runtime.json or .oumv/runtime.json)
169
355
  cls._check_workspace_runtime_files(ws, st)
170
356
 
@@ -209,6 +395,7 @@ class OUMVGateway:
209
395
  @staticmethod
210
396
  def global_runtime_file(workspace_dir: str) -> str:
211
397
  """Zero-footprint global runtime descriptor path outside the target repo."""
398
+ # oumv_home.ws_id / tokensafe_home key policy, backups and tokens the same way.
212
399
  canonical = os.path.realpath(os.path.abspath(workspace_dir))
213
400
  ws_id = hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:16]
214
401
  tokensafe_home = os.environ.get("TOKENSAFE_HOME") or os.path.expanduser("~/.tokensafe")
@@ -258,10 +445,13 @@ class OUMVGateway:
258
445
  @classmethod
259
446
  def _check_workspace_runtime_files(cls, workspace_dir: str, st: Optional[Dict[str, Any]] = None):
260
447
  st = st if st is not None else cls._state_for(workspace_dir)
448
+ # Later entries win. The global registry is written by `tokensafe dev` outside
449
+ # the repo; the workspace files can arrive with a clone, so they never
450
+ # override it.
261
451
  lock_paths = [lp for lp in (
262
- cls.global_runtime_file(workspace_dir),
263
- os.path.join(workspace_dir, ".tokensafe", "runtime.json"),
264
452
  os.path.join(workspace_dir, ".oumv", "runtime.json"),
453
+ os.path.join(workspace_dir, ".tokensafe", "runtime.json"),
454
+ cls.global_runtime_file(workspace_dir),
265
455
  ) if cls._descriptor_path_is_trusted(lp, workspace_dir)]
266
456
  now = time.time()
267
457
  for lp in lock_paths:
@@ -281,41 +471,45 @@ class OUMVGateway:
281
471
  # A corrupt registry must be reported, never silently trusted.
282
472
  cls._record_stale(st, None, None, f"{os.path.basename(lp)} is unreadable: {exc}")
283
473
  continue
284
- fe_info = data.get("frontend")
285
- if fe_info and fe_info.get("url"):
474
+ for kind, slot, default_name in (
475
+ ("frontend", "fe", "tokensafe-ui"),
476
+ ("backend", "be", "tokensafe-backend"),
477
+ ):
478
+ info = data.get(kind)
479
+ if not isinstance(info, dict) or not info.get("url"):
480
+ continue
481
+ url = str(info["url"])
482
+ if not _is_loopback_url(url) and not _remote_runtimes_allowed():
483
+ # A descriptor committed to a repo could otherwise point the
484
+ # gateway (edits, session token, observe answers) at any host.
485
+ cls._record_stale(st, kind, url, "descriptor points at a non-loopback host (refused)")
486
+ continue
487
+ # Adapters that never write their token into the descriptor (PHP;
488
+ # Node given only the env token) were launched by TokenSafe with a
489
+ # token it recorded outside the repo.
490
+ token = (
491
+ info.get("session_token") or info.get("sessionToken")
492
+ or oumv_home.read_session_token(workspace_dir, kind)
493
+ )
494
+ handshake = cls._handshake(url, token)
495
+ if handshake is None:
496
+ cls._record_stale(st, kind, url, "descriptor present but no live OUMV handshake")
497
+ continue
286
498
  entry = {
287
- "kind": "frontend",
288
- "name": fe_info.get("name", "tokensafe-ui"),
289
- "version": fe_info.get("version", "1.0.0"),
290
- "url": fe_info["url"],
291
- "sessionToken": fe_info.get("sessionToken"),
499
+ "kind": kind,
500
+ "name": info.get("name", default_name),
501
+ "version": info.get("version", "1.0.0"),
502
+ "url": url,
503
+ "sessionToken": token,
292
504
  "healthy": True,
293
505
  "source": "descriptor",
294
- "capabilities": fe_info.get("capabilities", {}),
506
+ "capabilities": cls._caps_from_handshake(handshake),
295
507
  }
296
- if cls._runtime_is_reachable(entry["url"], entry.get("sessionToken")):
297
- st["fe"] = entry
298
- else:
299
- cls._record_stale(st, "frontend", entry["url"], "descriptor present but no live OUMV handshake")
300
- be_info = data.get("backend")
301
- if be_info and be_info.get("url"):
302
- entry = {
303
- "kind": "backend",
304
- "name": be_info.get("name", "tokensafe-backend"),
305
- "version": be_info.get("version", "1.0.0"),
306
- "url": be_info["url"],
307
- "sessionToken": be_info.get("session_token") or be_info.get("sessionToken"),
308
- "healthy": True,
309
- "source": "descriptor",
310
- "capabilities": be_info.get("capabilities", {}),
508
+ if kind == "backend" and info.get("frontend"):
311
509
  # Spec §7.4: the descriptor names its browser bridge, so
312
510
  # discovery knows client components are reachable.
313
- **({"bridge": be_info.get("frontend")} if be_info.get("frontend") else {}),
314
- }
315
- if cls._runtime_is_reachable(entry["url"], entry.get("sessionToken")):
316
- st["be"] = entry
317
- else:
318
- cls._record_stale(st, "backend", entry["url"], "descriptor present but no live OUMV handshake")
511
+ entry["bridge"] = info.get("frontend")
512
+ st[slot] = entry
319
513
  return st
320
514
 
321
515
  @classmethod
@@ -362,10 +556,11 @@ class OUMVGateway:
362
556
  @classmethod
363
557
  def prune_backups(cls, workspace_dir: str, *, keep_per_file: int = 20,
364
558
  max_age_days: int = 30) -> List[str]:
365
- """Bounds ``.tokensafe/backups``: the newest ``keep_per_file`` per source
366
- file and nothing older than ``max_age_days``. Best-effort by design — a
367
- retention failure must never fail the mutation that triggered it."""
368
- directory = os.path.join(workspace_dir, ".tokensafe", "backups")
559
+ """Bounds ``TOKENSAFE_HOME/backups/<ws_id>``: the newest ``keep_per_file``
560
+ per source file and nothing older than ``max_age_days``. Best-effort by
561
+ design — a retention failure must never fail the mutation that
562
+ triggered it."""
563
+ directory = oumv_home.backup_dir(workspace_dir)
369
564
  if not os.path.isdir(directory):
370
565
  return []
371
566
  try:
@@ -395,43 +590,70 @@ class OUMVGateway:
395
590
  pass
396
591
  return removed
397
592
 
593
+ @staticmethod
594
+ def _caps_from_handshake(res: Dict[str, Any]) -> Dict[str, Any]:
595
+ """Capability summary from a live handshake (never from a descriptor file:
596
+ a descriptor is a hint, the handshake is what the runtime actually serves)."""
597
+ caps = res.get("capabilities") if isinstance(res.get("capabilities"), dict) else {}
598
+
599
+ def _sub(name: str) -> Dict[str, Any]:
600
+ val = caps.get(name)
601
+ return val if isinstance(val, dict) else {}
602
+
603
+ return {
604
+ "observeLevels": _sub("observe").get("levels"),
605
+ "causality": _sub("understand").get("causality"),
606
+ "occ": _sub("mutate").get("occ"),
607
+ # Spec §8.5 (revision v1.11): a read-only deployment registers no writing
608
+ # method at all, so the answer is -32601 and this flag is the
609
+ # authoritative "do not edit behind its back" signal.
610
+ "readOnly": bool(caps.get("readOnly")),
611
+ # Spec §7.4 (revision v1.12): a browser bridge turns the server runtime
612
+ # into one that can see client components and dispatch DOM actions.
613
+ "bridge": {
614
+ "ephemeralDispatch": bool(_sub("mutate").get("ephemeralDispatch")),
615
+ "surfaceDiff": bool(_sub("verify").get("surfaceDiff")),
616
+ },
617
+ "protocolVersion": res.get("protocolVersion"),
618
+ }
619
+
620
+ @classmethod
621
+ def _handshake(cls, url: Optional[str], token: Optional[str] = None) -> Optional[Dict[str, Any]]:
622
+ """The runtime's handshake result, or None when nothing OUMV answers at `url`."""
623
+ if not url:
624
+ return None
625
+ try:
626
+ res = cls._rpc_call(url, "oumv/handshake", {"protocolVersion": _CLIENT_PROTOCOL_VERSION}, token=token)
627
+ except Exception:
628
+ return None
629
+ return res if isinstance(res, dict) and "runtimeInfo" in res else None
630
+
398
631
  @classmethod
399
632
  def _probe_candidates(cls, urls: List[str], kind: str, workspace_dir: Optional[str] = None) -> Optional[Dict[str, Any]]:
633
+ # A runtime TokenSafe spawned for this root answers only with its token.
634
+ token = oumv_home.read_session_token(workspace_dir, kind)
400
635
  for url in urls:
401
- try:
402
- res = cls._rpc_call(url, "oumv/handshake", {"protocolVersion": "1.0.0"}, timeout=0.35)
403
- if res and isinstance(res, dict) and "runtimeInfo" in res:
404
- if workspace_dir is not None and not cls._probed_runtime_belongs_to(res, url, workspace_dir):
405
- continue
406
- return {
407
- "kind": kind,
408
- "name": res.get("runtimeInfo", {}).get("name", f"{kind}-runtime"),
409
- "version": res.get("runtimeInfo", {}).get("version", "1.0.0"),
410
- "url": url,
411
- "healthy": True,
412
- "capabilities": {
413
- "observeLevels": res.get("capabilities", {}).get("observe", {}).get("levels"),
414
- "causality": res.get("capabilities", {}).get("understand", {}).get("causality"),
415
- "occ": res.get("capabilities", {}).get("mutate", {}).get("occ"),
416
- # Spec §8.5 (revision v1.11): a read-only deployment registers
417
- # no writing method at all, so the answer is -32601 and this flag
418
- # is the authoritative "do not edit behind its back" signal.
419
- "readOnly": bool(res.get("capabilities", {}).get("readOnly")),
420
- # Spec §7.4 (revision v1.12): a browser bridge turns the
421
- # server runtime into one that can see client components
422
- # and dispatch DOM actions — surface both claims.
423
- "bridge": {
424
- "ephemeralDispatch": bool(
425
- res.get("capabilities", {}).get("mutate", {}).get("ephemeralDispatch")
426
- ),
427
- "surfaceDiff": bool(
428
- res.get("capabilities", {}).get("verify", {}).get("surfaceDiff")
429
- ),
430
- },
431
- },
432
- }
433
- except Exception:
636
+ res = cls._handshake(url, token)
637
+ used_token = token
638
+ if res is None and token and cls._is_url_live(url):
639
+ # A runtime not launched by TokenSafe has its own (or no) token.
640
+ res = cls._handshake(url)
641
+ used_token = None
642
+ if res is None:
434
643
  continue
644
+ if workspace_dir is not None and not cls._probed_runtime_belongs_to(res, url, workspace_dir):
645
+ continue
646
+ info = res.get("runtimeInfo") if isinstance(res.get("runtimeInfo"), dict) else {}
647
+ return {
648
+ "kind": kind,
649
+ "name": info.get("name", f"{kind}-runtime"),
650
+ "version": info.get("version", "1.0.0"),
651
+ "url": url,
652
+ "sessionToken": used_token,
653
+ "healthy": True,
654
+ "source": "probe",
655
+ "capabilities": cls._caps_from_handshake(res),
656
+ }
435
657
  return None
436
658
 
437
659
  @classmethod
@@ -460,7 +682,7 @@ class OUMVGateway:
460
682
  return os.path.realpath(os.path.abspath(reported)) == want
461
683
  except Exception:
462
684
  return False
463
- for ws_key, st in cls._workspace_states.items():
685
+ for ws_key, st in cls._states_snapshot():
464
686
  if ws_key == want:
465
687
  continue
466
688
  for slot in ("fe", "be"):
@@ -472,13 +694,7 @@ class OUMVGateway:
472
694
  @classmethod
473
695
  def _runtime_is_reachable(cls, url: Optional[str], token: Optional[str] = None) -> bool:
474
696
  """True when a live OUMV runtime answers a handshake at `url`."""
475
- if not url:
476
- return False
477
- try:
478
- res = cls._rpc_call(url, "oumv/handshake", {"protocolVersion": "1.6.0"}, timeout=0.35, token=token)
479
- except Exception:
480
- return False
481
- return bool(res and isinstance(res, dict) and "runtimeInfo" in res)
697
+ return cls._handshake(url, token) is not None
482
698
 
483
699
  @classmethod
484
700
  def _rpc_call(
@@ -486,14 +702,30 @@ class OUMVGateway:
486
702
  endpoint_url: str,
487
703
  method: str,
488
704
  params: Optional[dict] = None,
489
- timeout: float = 3.0,
705
+ timeout: Optional[float] = None,
490
706
  token: Optional[str] = None,
491
707
  ) -> Any:
708
+ if timeout is None:
709
+ timeout = _RPC_TIMEOUTS.get(method, _RPC_DEFAULT_TIMEOUT)
710
+ if not _is_loopback_url(endpoint_url) and not _remote_runtimes_allowed():
711
+ raise OUMVRpcError(
712
+ f"refusing non-loopback OUMV runtime {endpoint_url} "
713
+ "(set TOKENSAFE_OUMV_ALLOW_REMOTE=1 to allow)",
714
+ transport="refused",
715
+ )
716
+ params = dict(params or {})
717
+ scope = getattr(_CALL_CTX, "scope", None)
718
+ tracked_id: Optional[str] = None
719
+ if method not in _NO_REQUEST_ID_METHODS:
720
+ tracked_id = str(params.get("requestId") or "").strip() or (
721
+ scope["requestId"] if scope else _new_request_id()
722
+ )
723
+ params["requestId"] = tracked_id
492
724
  payload = json.dumps({
493
725
  "jsonrpc": "2.0",
494
- "id": 1,
726
+ "id": next(_RPC_IDS),
495
727
  "method": method,
496
- "params": params or {},
728
+ "params": params,
497
729
  }).encode("utf-8")
498
730
 
499
731
  headers = {"Content-Type": "application/json", "User-Agent": "TokenSafe-Gateway/1.0"}
@@ -501,11 +733,14 @@ class OUMVGateway:
501
733
  # unambiguously, so scan every root's state for a match. A descriptor probe
502
734
  # passes the token before the entry is adopted.
503
735
  if token is None:
504
- for st in cls._workspace_states.values():
505
- if st.get("fe", {}) and st["fe"].get("url") == endpoint_url:
506
- token = st["fe"].get("sessionToken")
507
- elif st.get("be", {}) and st["be"].get("url") == endpoint_url:
508
- token = st["be"].get("sessionToken")
736
+ for _key, st in cls._states_snapshot():
737
+ for slot in ("fe", "be"):
738
+ entry = st.get(slot)
739
+ if entry and entry.get("url") == endpoint_url and entry.get("sessionToken"):
740
+ token = entry["sessionToken"]
741
+ break
742
+ if token:
743
+ break
509
744
 
510
745
  if token:
511
746
  headers["X-OUMV-Session-Token"] = token
@@ -517,9 +752,33 @@ class OUMVGateway:
517
752
  method="POST",
518
753
  )
519
754
 
755
+ ws_key = scope["ws"] if scope else "_global"
756
+ if tracked_id:
757
+ _inflight_add(ws_key, tracked_id, endpoint_url, method)
758
+ try:
759
+ result = cls._rpc_send(req, endpoint_url, timeout)
760
+ finally:
761
+ if tracked_id:
762
+ _inflight_remove(ws_key, tracked_id)
763
+ if tracked_id and scope is not None:
764
+ scope["live"] = True
765
+ return result
766
+
767
+ @classmethod
768
+ def _rpc_send(cls, req: urllib.request.Request, endpoint_url: str, timeout: float) -> Any:
769
+ # A tools/call that was cancelled or timed out sends no further RPC.
770
+ from tokensafe.call_context import check_cancelled
771
+ check_cancelled()
520
772
  try:
521
- with urllib.request.urlopen(req, timeout=timeout) as resp:
522
- data = json.loads(resp.read().decode("utf-8"))
773
+ with _RPC_OPENER.open(req, timeout=timeout) as resp:
774
+ # Bounded body: loopback-only, but a runaway runtime reply must not
775
+ # be buffered whole (16 MB is far above any OUMV answer).
776
+ body = resp.read(_RPC_MAX_REPLY_BYTES + 1)
777
+ if len(body) > _RPC_MAX_REPLY_BYTES:
778
+ raise OUMVRpcError(f"reply from {endpoint_url} exceeds {_RPC_MAX_REPLY_BYTES} bytes")
779
+ data = json.loads(body.decode("utf-8"))
780
+ if not isinstance(data, dict):
781
+ raise OUMVRpcError(f"non-JSON-RPC reply from {endpoint_url}")
523
782
  if "error" in data and data["error"]:
524
783
  err = data["error"]
525
784
  if isinstance(err, dict):
@@ -535,9 +794,21 @@ class OUMVGateway:
535
794
  code, msg = cls._http_error_detail(exc)
536
795
  raise OUMVRpcError(f"JSON-RPC error ({code}) from {endpoint_url}: {msg}", code=code) from exc
537
796
  except urllib.error.URLError as exc:
538
- raise OUMVRpcError(f"runtime unreachable at {endpoint_url}: {exc.reason}") from exc
539
- except (TimeoutError, OSError) as exc:
540
- raise OUMVRpcError(f"runtime unreachable at {endpoint_url}: {exc}") from exc
797
+ reason = exc.reason
798
+ if isinstance(reason, (ConnectionRefusedError, socket.gaierror)):
799
+ raise OUMVRpcError(f"runtime unreachable at {endpoint_url}: {reason}", transport="refused") from exc
800
+ kind = "timeout" if isinstance(reason, (TimeoutError, socket.timeout)) else "lost"
801
+ raise OUMVRpcError(f"runtime unreachable at {endpoint_url}: {reason}", transport=kind) from exc
802
+ except ValueError as exc:
803
+ raise OUMVRpcError(f"non-JSON reply from {endpoint_url}: {exc}") from exc
804
+ except (TimeoutError, socket.timeout) as exc:
805
+ raise OUMVRpcError(
806
+ f"runtime timed out at {endpoint_url} after {timeout:g}s: {exc}", transport="timeout"
807
+ ) from exc
808
+ except ConnectionRefusedError as exc:
809
+ raise OUMVRpcError(f"runtime unreachable at {endpoint_url}: {exc}", transport="refused") from exc
810
+ except OSError as exc:
811
+ raise OUMVRpcError(f"runtime connection lost at {endpoint_url}: {exc}", transport="lost") from exc
541
812
 
542
813
  @staticmethod
543
814
  def _http_error_detail(exc: urllib.error.HTTPError) -> Tuple[Optional[int], str]:
@@ -573,7 +844,8 @@ class OUMVGateway:
573
844
  if target:
574
845
  try:
575
846
  from tokensafe.retrofit import OUMVProjectContext
576
- ctx = OUMVProjectContext.get_for_workspace()
847
+ # The call's own root: the active workspace may be another repo.
848
+ ctx = OUMVProjectContext.get_for_workspace(workspace_dir)
577
849
  detected_rt = ctx.resolve_target_runtime(target)
578
850
  if detected_rt == "backend" and be:
579
851
  return be["url"]
@@ -582,12 +854,15 @@ class OUMVGateway:
582
854
  except Exception:
583
855
  pass
584
856
 
857
+ # Frontend files first: an absolute `/…/App.tsx` starts with "/" too.
858
+ if target.endswith((".tsx", ".jsx", ".vue", ".svelte")) and fe:
859
+ return fe["url"]
585
860
  # Backend hints: HTTP method prefixes, API paths, SQL, handlers
586
861
  if any(target.startswith(m) for m in ["GET ", "POST ", "PUT ", "DELETE ", "PATCH "]) or "/api/" in target or target.startswith("/"):
587
862
  if be:
588
863
  return be["url"]
589
864
  # Frontend hints: DOM selectors (#, .), components (<, JSX, Tab)
590
- if any(target.startswith(c) for c in ["#", ".", "[", "button", "input"]) or target.startswith("<") or target.endswith((".tsx", ".jsx", ".vue")):
865
+ if any(target.startswith(c) for c in ["#", ".", "[", "button", "input"]) or target.startswith("<"):
591
866
  if fe:
592
867
  return fe["url"]
593
868
 
@@ -636,6 +911,7 @@ class OUMVGateway:
636
911
  ws = workspace_dir or get_active_workspace()
637
912
  now = time.time()
638
913
  ports: List[int] = []
914
+ allow_remote = _remote_runtimes_allowed()
639
915
  for lp in (
640
916
  cls.global_runtime_file(ws),
641
917
  os.path.join(ws, ".tokensafe", "runtime.json"),
@@ -650,7 +926,7 @@ class OUMVGateway:
650
926
  data = json.load(f)
651
927
  for sec in ("frontend", "backend"):
652
928
  url = (data.get(sec) or {}).get("url")
653
- if not url:
929
+ if not url or (not allow_remote and not _is_loopback_url(url)):
654
930
  continue
655
931
  parsed = urllib.parse.urlparse(url)
656
932
  if not parsed.port:
@@ -677,6 +953,7 @@ class OUMVGateway:
677
953
 
678
954
  # Out-of-the-box stack detection
679
955
  stack_info = {}
956
+ from tokensafe.stack_summary import compact_detected_stack
680
957
  try:
681
958
  from tokensafe.retrofit import detect_project_stack_cached
682
959
  stack_info = detect_project_stack_cached(ws)
@@ -705,7 +982,9 @@ class OUMVGateway:
705
982
  }),
706
983
  "adapters": cls._adapter_lifecycle(stack_info, fe, be),
707
984
  "staticIntelligence": "ACTIVE (L0/L1/L2 AST observation & cross-stack linking ready)",
708
- "detectedStack": stack_info,
985
+ # Actionable rows verbatim; tooling/library packages folded into one
986
+ # line per role (the full list stays in detect_project_stack).
987
+ "detectedStack": compact_detected_stack(stack_info),
709
988
  "workspace": ws,
710
989
  }
711
990
  if dropped:
@@ -882,6 +1161,7 @@ class OUMVGateway:
882
1161
  return None
883
1162
 
884
1163
  @classmethod
1164
+ @_tracks_request
885
1165
  def observe(cls, level: str = "L0", target: Optional[str] = None, runtime: str = "auto",
886
1166
  workspace_dir: Optional[str] = None, path: Optional[str] = None) -> Any:
887
1167
  cls.mark_oumv_used(workspace_dir)
@@ -931,12 +1211,33 @@ class OUMVGateway:
931
1211
  if isinstance(res, dict) and "evidence" not in res:
932
1212
  res["evidence"] = {"provenance": "runtime", "confidence": "confirmed", "sourceAdapter": "live-devserver"}
933
1213
  return res
934
- except RuntimeError:
1214
+ except RuntimeError as exc:
935
1215
  # Level 1 Static Fallback via GraphEngine
936
1216
  from tokensafe.graph_engine import GraphEngine
937
1217
  ws = workspace_dir or get_active_workspace()
938
1218
  graph = GraphEngine.get_instance(ws)
939
- return graph.get_static_oumv_slice(level=level, target=target)
1219
+ res = graph.get_static_oumv_slice(level=level, target=target)
1220
+ cls._attach_runtime_error(res, exc)
1221
+ return res
1222
+
1223
+ @classmethod
1224
+ def _attach_runtime_error(cls, res: Any, exc: BaseException) -> None:
1225
+ """A static fallback must say why the live runtime did not answer.
1226
+
1227
+ Only "no runtime at all" is silent; a runtime that answered with an error
1228
+ (auth, invalid target, adapter crash) used to be indistinguishable from an
1229
+ offline one, so the agent trusted a static answer over a live failure.
1230
+ """
1231
+ if not isinstance(exc, OUMVRpcError) or not isinstance(res, dict):
1232
+ return
1233
+ if exc.transport == "refused":
1234
+ return # the dev server is gone; the static answer is the whole story
1235
+ res["runtimeError"] = {
1236
+ "message": str(exc),
1237
+ "code": exc.code,
1238
+ "transport": exc.transport,
1239
+ "note": "the live runtime failed this call; the answer below is the static fallback",
1240
+ }
940
1241
 
941
1242
  # 2.5 Tool: oumv_brief — one call for skeleton + call sites + props + state
942
1243
  @classmethod
@@ -950,6 +1251,7 @@ class OUMVGateway:
950
1251
 
951
1252
  # 3. Tool: oumv_understand
952
1253
  @classmethod
1254
+ @_tracks_request
953
1255
  def understand(cls, query: str = "causality", target: Optional[str] = None, runtime: str = "auto",
954
1256
  workspace_dir: Optional[str] = None, path: Optional[str] = None) -> Any:
955
1257
  cls.mark_oumv_used(workspace_dir)
@@ -1027,7 +1329,11 @@ class OUMVGateway:
1027
1329
  # A live adapter may accept queries beyond the offline contract.
1028
1330
  url = cls._resolve_client_url(runtime=runtime, target=target, workspace_dir=workspace_dir)
1029
1331
  return cls._rpc_call(url, "oumv/understand", {"query": query, "target": target, "componentId": target})
1030
- except RuntimeError:
1332
+ except RuntimeError as exc:
1333
+ if isinstance(exc, OUMVRpcError) and exc.transport is None and not _is_method_missing(exc):
1334
+ # The runtime answered this query with an error: report that, not
1335
+ # "unsupported query".
1336
+ raise
1031
1337
  # Prose in `query` is not a question: the offline contract answers
1032
1338
  # impact/causality/flow only. Returning a surface dump here looked like
1033
1339
  # an answer (level "L1", confidence "confirmed") to a query nobody parsed.
@@ -1171,21 +1477,13 @@ class OUMVGateway:
1171
1477
 
1172
1478
  # 4. Tool: oumv_mutate
1173
1479
  @classmethod
1480
+ @_tracks_request
1174
1481
  def mutate(cls, path: str, symbol: Optional[str] = None, replacement: Optional[str] = None, expected_version: Optional[str] = None, runtime: str = "auto", workspace_dir: Optional[str] = None) -> Any:
1175
- # Check workspace permissions (enabled by default out-of-the-box unless explicitly opted out)
1482
+ # Workspace policy (enabled by default unless explicitly opted out): the
1483
+ # repo's .tokensafe/oumv.json and the authoritative out-of-repo copy,
1484
+ # deny wins. The repo file itself is never an agent write target.
1176
1485
  ws = workspace_dir or get_active_workspace()
1177
- cfg_file = os.path.join(ws, ".tokensafe", "oumv.json")
1178
- if os.path.isfile(cfg_file):
1179
- try:
1180
- with open(cfg_file, "r", encoding="utf-8") as f:
1181
- cfg = json.load(f)
1182
- perms = cfg.get("permissions", {})
1183
- if perms.get("mutate") is False:
1184
- raise RuntimeError("[OUMV PERMISSION_DENIED: -32007] Workspace policy explicitly prohibits mutations (.tokensafe/oumv.json: permissions.mutate=false).")
1185
- except RuntimeError:
1186
- raise
1187
- except Exception:
1188
- pass
1486
+ cls._enforce_write_policy(ws, "mutate", [path])
1189
1487
 
1190
1488
  url: Optional[str] = None
1191
1489
  try:
@@ -1199,12 +1497,22 @@ class OUMVGateway:
1199
1497
  "expectedVersion": expected_version,
1200
1498
  })
1201
1499
  except RuntimeError as e:
1202
- if isinstance(e, OUMVRpcError) and not isinstance(e, OUMVUnsupportedMethodError):
1203
- # -32601 by code, or a message an older bridge only words that way.
1204
- method_missing = getattr(e, "code", None) == -32601 or any(
1205
- hint in str(e).lower() for hint in _UNSUPPORTED_HINTS
1206
- )
1207
- if not method_missing:
1500
+ fallback_reason: Optional[str] = None
1501
+ if isinstance(e, OUMVRpcError) and e.transport == "refused":
1502
+ # Nothing was delivered (the dev server stopped): forget the endpoint
1503
+ # and perform the same guarded edit offline.
1504
+ cls._forget_endpoint(url)
1505
+ fallback_reason = str(e)
1506
+ elif isinstance(e, OUMVRpcError) and e.transport in ("timeout", "lost"):
1507
+ # The request may have reached the runtime and been applied. Writing
1508
+ # it again offline (or letting the agent blindly retry) could apply
1509
+ # it twice or clobber what the runtime wrote.
1510
+ raise RuntimeError(
1511
+ f"[OUMV TIMEOUT] {e}. The runtime may have applied the edit: re-read "
1512
+ "file.version (oumv observe L1) before retrying with expectedVersion."
1513
+ ) from e
1514
+ elif isinstance(e, OUMVRpcError) and not isinstance(e, OUMVUnsupportedMethodError):
1515
+ if not _is_method_missing(e):
1208
1516
  # Explicit safety rejection (conflict, syntax, permission): obey it.
1209
1517
  raise
1210
1518
  # Spec §8.5 (revision v1.11): a *live* runtime that does not register
@@ -1230,100 +1538,169 @@ class OUMVGateway:
1230
1538
  if not is_within(ws, abs_path):
1231
1539
  raise RuntimeError(f"[OUMV SECURITY_VIOLATION: -32003] Path traversal blocked: {path}")
1232
1540
 
1233
- import hashlib
1234
- content = b""
1235
- current_version = None
1236
- if os.path.isfile(abs_path):
1237
- with open(abs_path, "rb") as f:
1238
- content = f.read()
1239
- current_version = "sha256:" + hashlib.sha256(content).hexdigest()
1240
-
1241
- if expected_version and current_version and expected_version != current_version:
1242
- raise RuntimeError(f"[OUMV CONFLICT: -32001] OCC version mismatch: expected {expected_version}, current is {current_version}")
1243
-
1244
- # A symbol-scoped edit replaces that declaration only. Writing the
1245
- # snippet as the whole file — which this path used to do — silently
1246
- # truncated every other symbol in the target.
1247
- new_content = replacement
1248
- symbol_range = None
1249
- if symbol and os.path.isfile(abs_path):
1250
- rel_path = os.path.relpath(abs_path, os.path.abspath(ws)).replace("\\", "/")
1251
- symbol_range = cls._resolve_symbol_range(ws, rel_path, symbol)
1252
- if not symbol_range:
1253
- known = cls._file_symbol_qualified_names(ws, rel_path)
1254
- raise RuntimeError(
1255
- f"[OUMV SYMBOL_NOT_FOUND] '{symbol}' is not declared in {path}, "
1256
- f"or several declarations share that name (qualify it, e.g. Class.method). "
1257
- f"Known symbols: {', '.join(known[:12]) or 'none'}. "
1258
- f"For a non-declaration range use apply_edits(start_line/end_line) instead."
1259
- )
1260
- start_line, end_line = symbol_range
1261
- new_content = cls._splice_range(
1262
- content.decode("utf-8", errors="replace"),
1263
- start_line,
1264
- end_line,
1265
- replacement,
1541
+ # Read -> OCC check -> write under TokenSafe's per-file lock.
1542
+ with oumv_home.file_write_lock(abs_path):
1543
+ return cls._offline_write_locked(
1544
+ ws, path, abs_path, symbol, replacement, expected_version, e, fallback_reason
1266
1545
  )
1546
+ raise
1267
1547
 
1268
- # Syntax pre-flight: never persist syntactically broken code (OUMV spec §8 Mutation Policy)
1269
- from tokensafe.syntax_guard import check_syntax
1270
- syntax_check = check_syntax(abs_path, new_content)
1271
- if syntax_check.get("status") == "failed":
1272
- raise RuntimeError(
1273
- f"[OUMV SYNTAX_ERROR: -32002] Edit rejected by syntax guard "
1274
- f"({syntax_check.get('tool')}): {syntax_check.get('error')}"
1275
- )
1548
+ @classmethod
1549
+ def _offline_write_locked(cls, ws: str, path: str, abs_path: str, symbol: Optional[str],
1550
+ replacement: str, expected_version: Optional[str],
1551
+ e: BaseException, fallback_reason: Optional[str]) -> Dict[str, Any]:
1552
+ """The guarded offline edit; the caller holds ``file_write_lock(abs_path)``.
1553
+
1554
+ The lock only serializes TokenSafe's own writers (gateway mutate and
1555
+ apply_edits). External editors do not take it, so the final re-hash
1556
+ right before ``os.replace`` stays.
1557
+ """
1558
+ content = b""
1559
+ current_version = None
1560
+ if os.path.isfile(abs_path):
1561
+ with open(abs_path, "rb") as f:
1562
+ content = f.read()
1563
+ current_version = "sha256:" + hashlib.sha256(content).hexdigest()
1564
+
1565
+ # OCC is the protocol's write contract, not an option: without a
1566
+ # version an offline write silently overwrote whatever changed since
1567
+ # the agent last looked. The current version is in the error, so the
1568
+ # retry is one call.
1569
+ if current_version is not None and not expected_version:
1570
+ raise RuntimeError(
1571
+ f"[OUMV VERSION_REQUIRED: -32602] expectedVersion is required to edit an existing file "
1572
+ f"({path}); its current version is {current_version}. Re-read it if you have not "
1573
+ "seen this version, then retry with expectedVersion."
1574
+ )
1575
+ if expected_version and current_version is None:
1576
+ raise RuntimeError(
1577
+ f"[OUMV CONFLICT: -32001] OCC version mismatch: expected {expected_version}, "
1578
+ f"but {path} does not exist"
1579
+ )
1580
+ if expected_version and current_version and expected_version != current_version:
1581
+ raise RuntimeError(f"[OUMV CONFLICT: -32001] OCC version mismatch: expected {expected_version}, current is {current_version}")
1582
+
1583
+ # A symbol-scoped edit replaces that declaration only. Writing the
1584
+ # snippet as the whole file — which this path used to do — silently
1585
+ # truncated every other symbol in the target.
1586
+ new_content = replacement
1587
+ symbol_range = None
1588
+ if symbol and os.path.isfile(abs_path):
1589
+ rel_path = os.path.relpath(abs_path, os.path.abspath(ws)).replace("\\", "/")
1590
+ symbol_range = cls._resolve_symbol_range(ws, rel_path, symbol)
1591
+ if not symbol_range:
1592
+ known = cls._file_symbol_qualified_names(ws, rel_path)
1593
+ raise RuntimeError(
1594
+ f"[OUMV SYMBOL_NOT_FOUND] '{symbol}' is not declared in {path}, "
1595
+ f"or several declarations share that name (qualify it, e.g. Class.method). "
1596
+ f"Known symbols: {', '.join(known[:12]) or 'none'}. "
1597
+ f"For a non-declaration range use apply_edits(start_line/end_line) instead."
1598
+ )
1599
+ start_line, end_line = symbol_range
1600
+ try:
1601
+ current_text = content.decode("utf-8")
1602
+ except UnicodeDecodeError as exc:
1603
+ # errors="replace" rewrote every non-UTF-8 byte outside the
1604
+ # symbol as U+FFFD: a one-function edit corrupted the file.
1605
+ raise RuntimeError(
1606
+ f"[OUMV ENCODING_UNSUPPORTED] {path} is not valid UTF-8 ({exc.reason} at byte "
1607
+ f"{exc.start}); a symbol edit would corrupt the rest of the file. Convert it to "
1608
+ "UTF-8 first or replace the whole file."
1609
+ ) from exc
1610
+ new_content = cls._splice_range(current_text, start_line, end_line, replacement)
1611
+
1612
+ # Syntax pre-flight: never persist syntactically broken code (OUMV spec §8 Mutation Policy)
1613
+ from tokensafe.syntax_guard import check_syntax
1614
+ syntax_check = check_syntax(abs_path, new_content)
1615
+ if syntax_check.get("status") == "failed":
1616
+ raise RuntimeError(
1617
+ f"[OUMV SYNTAX_ERROR: -32002] Edit rejected by syntax guard "
1618
+ f"({syntax_check.get('tool')}): {syntax_check.get('error')}"
1619
+ )
1276
1620
 
1277
- # Automatic backup of previous content before overwriting
1621
+ # Automatic backup of previous content before overwriting
1622
+ from tokensafe.atomic_io import write_atomic
1623
+ backup_path = None
1624
+ if current_version is not None:
1625
+ try:
1626
+ # Outside the repo: an agent could otherwise rewrite or delete
1627
+ # its own rollback points.
1628
+ backup_dir = oumv_home.backup_dir(ws)
1629
+ os.makedirs(backup_dir, exist_ok=True)
1630
+ digest = hashlib.sha256(content).hexdigest()[:8]
1631
+ # The path hash keeps `a/index.ts` and `b/index.ts` in separate
1632
+ # retention groups (prune_backups groups by the part after
1633
+ # the first "_").
1634
+ rel_key = os.path.relpath(abs_path, os.path.abspath(ws)).replace("\\", "/")
1635
+ path_tag = hashlib.sha256(rel_key.encode("utf-8")).hexdigest()[:8]
1636
+ backup_path = os.path.join(
1637
+ backup_dir, f"{digest}_{path_tag}-{os.path.basename(abs_path)}.bak"
1638
+ )
1639
+ write_atomic(backup_path, content)
1640
+ except Exception:
1278
1641
  backup_path = None
1279
- if current_version is not None:
1280
- try:
1281
- backup_dir = os.path.join(ws, ".tokensafe", "backups")
1282
- os.makedirs(backup_dir, exist_ok=True)
1283
- digest = hashlib.sha256(content).hexdigest()[:8]
1284
- backup_path = os.path.join(backup_dir, f"{digest}_{os.path.basename(abs_path)}.bak")
1285
- from tokensafe.atomic_io import write_atomic
1286
- write_atomic(backup_path, content)
1287
- except Exception:
1288
- backup_path = None
1289
-
1290
- from tokensafe.atomic_io import write_atomic
1291
- write_atomic(abs_path, new_content)
1292
-
1293
- new_version = "sha256:" + hashlib.sha256(new_content.encode("utf-8")).hexdigest()
1294
- try:
1295
- OUMVGateway.prune_backups(ws)
1296
- except Exception:
1297
- pass
1298
- result = {
1299
- "success": True,
1300
- "path": path,
1301
- "symbol": symbol,
1302
- "newVersion": new_version,
1303
- "mode": "OUT_OF_THE_BOX_DIRECT_EDIT",
1304
- "syntaxCheck": syntax_check,
1305
- "message": "Surgical edit applied directly to workspace file (dev-server offline)",
1306
- }
1307
- if symbol_range:
1308
- result["symbolRange"] = {"startLine": symbol_range[0], "endLine": symbol_range[1]}
1309
- if backup_path:
1310
- result["backupPath"] = backup_path
1311
- result["rollbackHint"] = f"Previous content backed up at {backup_path}"
1312
- if isinstance(e, OUMVUnsupportedMethodError):
1313
- # The runtime was reachable but has no applyEdit: the edit was
1314
- # mediated by the gateway instead. Say so instead of implying
1315
- # the runtime verified it.
1316
- result["mode"] = "RUNTIME_LACKS_APPLYEDIT_OFFLINE_FALLBACK"
1317
- result["runtimeFallbackReason"] = str(e)
1318
- result["message"] = (
1319
- "Live runtime does not implement oumv/applyEdit; edit applied by the gateway "
1320
- "with the same OCC, syntax-guard and backup checks"
1321
- )
1322
- return result
1323
- raise
1642
+
1643
+ # Re-check right before the rename: the syntax guard can take seconds,
1644
+ # and a write that landed meanwhile must not be overwritten.
1645
+ if cls._hash_version(abs_path) != current_version:
1646
+ raise RuntimeError(
1647
+ f"[OUMV CONFLICT: -32001] {path} changed while the edit was being checked "
1648
+ f"(expected {current_version}, now {cls._hash_version(abs_path)}); nothing was written."
1649
+ )
1650
+ # New files get ordinary permissions, not mkstemp's 0600.
1651
+ write_atomic(abs_path, new_content, mode=None if current_version is not None else 0o644)
1652
+
1653
+ new_version = "sha256:" + hashlib.sha256(new_content.encode("utf-8")).hexdigest()
1654
+ try:
1655
+ OUMVGateway.prune_backups(ws)
1656
+ except Exception:
1657
+ pass
1658
+ result = {
1659
+ "success": True,
1660
+ "path": path,
1661
+ "symbol": symbol,
1662
+ "newVersion": new_version,
1663
+ "mode": "OUT_OF_THE_BOX_DIRECT_EDIT",
1664
+ "syntaxCheck": syntax_check,
1665
+ "message": "Surgical edit applied directly to workspace file (dev-server offline)",
1666
+ }
1667
+ if symbol_range:
1668
+ result["symbolRange"] = {"startLine": symbol_range[0], "endLine": symbol_range[1]}
1669
+ if backup_path:
1670
+ result["backupPath"] = backup_path
1671
+ result["rollbackHint"] = f"Previous content backed up at {backup_path}"
1672
+ if isinstance(e, OUMVUnsupportedMethodError):
1673
+ # The runtime was reachable but has no applyEdit: the edit was
1674
+ # mediated by the gateway instead. Say so instead of implying
1675
+ # the runtime verified it.
1676
+ result["mode"] = "RUNTIME_LACKS_APPLYEDIT_OFFLINE_FALLBACK"
1677
+ result["runtimeFallbackReason"] = str(e)
1678
+ result["message"] = (
1679
+ "Live runtime does not implement oumv/applyEdit; edit applied by the gateway "
1680
+ "with the same OCC, syntax-guard and backup checks"
1681
+ )
1682
+ elif fallback_reason:
1683
+ result["mode"] = "RUNTIME_GONE_OFFLINE_FALLBACK"
1684
+ result["runtimeFallbackReason"] = fallback_reason
1685
+ return result
1686
+
1687
+ @classmethod
1688
+ def _enforce_write_policy(cls, ws: Optional[str], action: str, paths: List[Optional[str]] = ()) -> None:
1689
+ """Raises PERMISSION_DENIED for a policy-denied action or a policy-file target."""
1690
+ base = ws or get_active_workspace() or os.getcwd()
1691
+ for raw in paths:
1692
+ if not raw:
1693
+ continue
1694
+ abs_path = raw if os.path.isabs(raw) else os.path.join(base, raw)
1695
+ if oumv_home.is_policy_config_path(abs_path):
1696
+ raise RuntimeError(oumv_home.policy_edit_refusal(abs_path))
1697
+ denial = oumv_home.permission_denial(base, action)
1698
+ if denial:
1699
+ raise RuntimeError(denial)
1324
1700
 
1325
1701
  # 5. Tool: oumv_verify
1326
1702
  @classmethod
1703
+ @_tracks_request
1327
1704
  def verify(cls, target: str, action: str = "invoke", payload: Optional[dict] = None, runtime: str = "auto", workspace_dir: Optional[str] = None, sandbox: Optional[dict] = None) -> Any:
1328
1705
  cls.mark_oumv_used(workspace_dir)
1329
1706
  if runtime == "backend":
@@ -1340,6 +1717,9 @@ class OUMVGateway:
1340
1717
  # on. A runtime that IS found but rejects or fails the call keeps
1341
1718
  # raising — "runtime answered with an error" is not "offline".
1342
1719
  return cls._static_verify(target, action, payload or {}, workspace_dir, sandbox)
1720
+ # A live verify dispatches application code (handlers, DOM actions):
1721
+ # policy applies. The static subset above executes nothing.
1722
+ cls._enforce_write_policy(workspace_dir, "verify")
1343
1723
  params = {
1344
1724
  "target": target,
1345
1725
  "componentId": target,
@@ -1353,8 +1733,12 @@ class OUMVGateway:
1353
1733
  res = cls._rpc_call(url, "oumv/verify", params)
1354
1734
  # Honest verification scope (spec §13): state exactly what was verified.
1355
1735
  if isinstance(res, dict):
1356
- scope = res.setdefault("scope", {})
1357
- checked = scope.setdefault("checked", [])
1736
+ if not isinstance(res.get("scope"), dict):
1737
+ res["scope"] = {}
1738
+ scope = res["scope"]
1739
+ if not isinstance(scope.get("checked"), list):
1740
+ scope["checked"] = []
1741
+ checked = scope["checked"]
1358
1742
  checked_entry = "in-memory dispatch against live runtime"
1359
1743
  if checked_entry not in checked:
1360
1744
  checked.append(checked_entry)
@@ -1500,7 +1884,9 @@ class OUMVGateway:
1500
1884
  status = "FAILED"
1501
1885
  hint = "Static checks failed and need no runtime to reproduce; fix them, then re-run verify."
1502
1886
  elif resolved_file or found_static:
1503
- status = "PASSED"
1887
+ # Not "PASSED": nothing was executed, and agents read a bare PASSED as
1888
+ # "the behaviour works".
1889
+ status = "STATIC_PASSED"
1504
1890
  hint = (
1505
1891
  "Static checks only. Start the runtime (`tokensafe dev` or `tokensafe run-backend ...`) "
1506
1892
  "for in-memory dispatch and surface diffs."
@@ -1653,6 +2039,7 @@ class OUMVGateway:
1653
2039
 
1654
2040
  # 8. Tool: oumv preview — dry-run diff before commit (spec `oumv/previewEdit`)
1655
2041
  @classmethod
2042
+ @_tracks_request
1656
2043
  def preview(cls, path: str, symbol: Optional[str] = None, replacement: Optional[str] = None,
1657
2044
  expected_version: Optional[str] = None, batch: Optional[List[dict]] = None,
1658
2045
  runtime: str = "auto", workspace_dir: Optional[str] = None) -> Any:
@@ -1665,6 +2052,11 @@ class OUMVGateway:
1665
2052
  instead of guessing a diff the runtime never computed.
1666
2053
  """
1667
2054
  ws = workspace_dir or get_active_workspace() or os.getcwd()
2055
+ # A preview of an edit to the policy file is refused like the edit itself;
2056
+ # `permissions.preview=false` (either policy file) turns previews off.
2057
+ batch_paths = [str(item.get("path") or item.get("filePath") or "")
2058
+ for item in (batch or []) if isinstance(item, dict)]
2059
+ cls._enforce_write_policy(ws, "preview", [path, *batch_paths])
1668
2060
  params: Dict[str, Any] = {
1669
2061
  "path": path,
1670
2062
  "filePath": path,
@@ -1682,9 +2074,14 @@ class OUMVGateway:
1682
2074
  res.setdefault("mode", "LIVE_RUNTIME_PREVIEW")
1683
2075
  return res
1684
2076
  except OUMVRpcError as e:
1685
- if not any(hint in str(e).lower() for hint in _UNSUPPORTED_HINTS):
2077
+ if e.transport == "refused":
2078
+ cls._forget_endpoint(url)
2079
+ return cls.preview(path, symbol=symbol, replacement=replacement,
2080
+ expected_version=expected_version, batch=batch,
2081
+ runtime=runtime, workspace_dir=workspace_dir)
2082
+ if not _is_method_missing(e):
1686
2083
  raise # explicit protocol rejection (conflict/syntax/permission) — obey it
1687
- raise OUMVUnsupportedMethodError(str(e))
2084
+ raise OUMVUnsupportedMethodError(str(e), code=e.code)
1688
2085
  except RuntimeError as e:
1689
2086
  if not any(hint in str(e).lower() for hint in _UNSUPPORTED_HINTS):
1690
2087
  offline = {
@@ -1728,6 +2125,7 @@ class OUMVGateway:
1728
2125
 
1729
2126
  # 9. Tool: oumv build — run the runtime's build/test command (spec §14.3)
1730
2127
  @classmethod
2128
+ @_tracks_request
1731
2129
  def build(cls, command: Optional[str] = None, target: Optional[str] = None,
1732
2130
  timeout_ms: Optional[int] = None, runtime: str = "auto", workspace_dir: Optional[str] = None) -> Any:
1733
2131
  """Proxies `oumv/build` to a live runtime; no fabricated offline diagnostics.
@@ -1737,6 +2135,8 @@ class OUMVGateway:
1737
2135
  gateway cannot run the application's own build — not a guessed verdict.
1738
2136
  """
1739
2137
  cls.mark_oumv_used(workspace_dir)
2138
+ # Build runs the application's own commands: policy applies.
2139
+ cls._enforce_write_policy(workspace_dir, "build")
1740
2140
  params: Dict[str, Any] = {}
1741
2141
  if command:
1742
2142
  params["command"] = command
@@ -1746,14 +2146,19 @@ class OUMVGateway:
1746
2146
  params["timeoutMs"] = int(timeout_ms)
1747
2147
  try:
1748
2148
  url = cls._resolve_client_url(runtime=runtime, target=target, workspace_dir=workspace_dir)
1749
- res = cls._rpc_call(url, "oumv/build", params)
2149
+ # The caller's budget plus a margin for the runtime to report; a fixed
2150
+ # 3 s cut every real build and reported it as "runtime unreachable".
2151
+ http_timeout = (
2152
+ min(int(timeout_ms) / 1000.0 + 5.0, _RPC_MAX_TIMEOUT) if timeout_ms else None
2153
+ )
2154
+ res = cls._rpc_call(url, "oumv/build", params, timeout=http_timeout)
1750
2155
  if isinstance(res, dict) and "evidence" not in res:
1751
2156
  res["evidence"] = {"provenance": "runtime", "confidence": "confirmed", "sourceAdapter": "live-devserver"}
1752
2157
  return res
1753
2158
  except OUMVRpcError as e:
1754
- if not any(hint in str(e).lower() for hint in _UNSUPPORTED_HINTS):
2159
+ if not _is_method_missing(e):
1755
2160
  raise
1756
- raise OUMVUnsupportedMethodError(str(e))
2161
+ raise OUMVUnsupportedMethodError(str(e), code=e.code)
1757
2162
  except RuntimeError as e:
1758
2163
  # A plain RuntimeError here means no runtime is reachable: the honest
1759
2164
  # answer is a skip with a reason, never a fabricated verdict.
@@ -1787,18 +2192,80 @@ class OUMVGateway:
1787
2192
  target = (target or "").strip()
1788
2193
  if not request_id and not target:
1789
2194
  raise ValueError("cancel needs requestId or target='last'")
1790
- params: Dict[str, Any] = {"requestId": request_id} if request_id else {"target": target}
1791
- url = cls._resolve_client_url(runtime=runtime, workspace_dir=workspace_dir)
2195
+ url: Optional[str] = None
2196
+ if not request_id:
2197
+ if target.lower() != "last":
2198
+ raise ValueError("cancel target must be 'last' (or pass requestId)")
2199
+ found = cls.last_inflight(workspace_dir)
2200
+ if not found:
2201
+ return {
2202
+ "cancelled": False,
2203
+ "requestId": None,
2204
+ "reason": "no OUMV request is in flight for this workspace",
2205
+ }
2206
+ request_id, url = found
2207
+ else:
2208
+ url = cls._inflight_url(workspace_dir, request_id)
2209
+ params: Dict[str, Any] = {"requestId": request_id}
2210
+ if not url:
2211
+ url = cls._resolve_client_url(runtime=runtime, workspace_dir=workspace_dir)
1792
2212
  try:
1793
2213
  res = cls._rpc_call(url, "oumv/cancel", params)
1794
2214
  except OUMVRpcError as e:
1795
- if not any(hint in str(e).lower() for hint in _UNSUPPORTED_HINTS):
2215
+ if not _is_method_missing(e):
1796
2216
  raise
1797
- raise OUMVUnsupportedMethodError(str(e))
1798
- if isinstance(res, dict) and "evidence" not in res:
1799
- res["evidence"] = {"provenance": "runtime", "confidence": "confirmed", "sourceAdapter": "live-devserver"}
2217
+ raise OUMVUnsupportedMethodError(str(e), code=e.code)
2218
+ if isinstance(res, dict):
2219
+ res.setdefault("requestId", request_id)
2220
+ if "evidence" not in res:
2221
+ res["evidence"] = {"provenance": "runtime", "confidence": "confirmed", "sourceAdapter": "live-devserver"}
1800
2222
  return res
1801
2223
 
2224
+ @classmethod
2225
+ def cancel_inflight(cls, request_id: str) -> Optional[Any]:
2226
+ """Forwards `oumv/cancel` for `request_id` if it is in flight in any workspace.
2227
+
2228
+ Used by the MCP transport when the client sends `notifications/cancelled`
2229
+ (or a call times out): the transport knows the requestId it assigned, not
2230
+ the workspace key. Returns the runtime's answer, or None when nothing with
2231
+ that id is in flight (the call never reached a runtime). Never raises.
2232
+ """
2233
+ rid = str(request_id or "").strip()
2234
+ if not rid:
2235
+ return None
2236
+ with _INFLIGHT_LOCK:
2237
+ url = next((per_ws[rid]["url"] for per_ws in _INFLIGHT.values() if rid in per_ws), None)
2238
+ if not url:
2239
+ return None
2240
+ try:
2241
+ return cls._rpc_call(url, "oumv/cancel", {"requestId": rid})
2242
+ except Exception:
2243
+ return None
2244
+
2245
+ @classmethod
2246
+ def inflight(cls, workspace_dir: Optional[str] = None) -> List[Dict[str, Any]]:
2247
+ """In-flight requests of this workspace, oldest first (snapshot)."""
2248
+ key = cls._ws_key(workspace_dir)
2249
+ with _INFLIGHT_LOCK:
2250
+ return [
2251
+ {"requestId": rid, "url": e["url"], "method": e["method"], "startedAt": e["startedAt"]}
2252
+ for rid, e in _INFLIGHT.get(key, {}).items()
2253
+ ]
2254
+
2255
+ @classmethod
2256
+ def last_inflight(cls, workspace_dir: Optional[str] = None) -> Optional[Tuple[str, str]]:
2257
+ """(requestId, url) of the most recent in-flight request, or None."""
2258
+ items = cls.inflight(workspace_dir)
2259
+ if not items:
2260
+ return None
2261
+ return items[-1]["requestId"], items[-1]["url"]
2262
+
2263
+ @classmethod
2264
+ def _inflight_url(cls, workspace_dir: Optional[str], request_id: str) -> Optional[str]:
2265
+ with _INFLIGHT_LOCK:
2266
+ entry = _INFLIGHT.get(cls._ws_key(workspace_dir), {}).get(request_id)
2267
+ return entry["url"] if entry else None
2268
+
1802
2269
  @staticmethod
1803
2270
  def _hash_version(abs_path: str) -> Optional[str]:
1804
2271
  import hashlib as _hashlib