tokensafe 4.6.1 → 4.6.3

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.
@@ -7,13 +7,37 @@ Connects AI coding agents to live Frontend (tokensafe-ui, Vite, React) and Backe
7
7
  import os
8
8
  import json
9
9
  import time
10
+ import socket
11
+ import hashlib
10
12
  import urllib.request
11
13
  import urllib.error
14
+ import urllib.parse
12
15
  from concurrent.futures import ThreadPoolExecutor, as_completed
13
16
  from typing import Dict, Any, Optional, Tuple, List
14
17
  from src.paths import get_active_workspace
15
18
 
16
19
 
20
+ class OUMVRpcError(RuntimeError):
21
+ """Raised when a live OUMV runtime explicitly returns a JSON-RPC error."""
22
+
23
+
24
+ class OUMVUnsupportedMethodError(OUMVRpcError):
25
+ """The runtime answered but does not implement the requested method.
26
+
27
+ This is not a safety rejection: the runtime cannot mediate the operation at
28
+ all, so the gateway may perform the guarded offline edit instead.
29
+ """
30
+
31
+
32
+ _UNSUPPORTED_HINTS = (
33
+ "unknown method",
34
+ "method not found",
35
+ "-32601",
36
+ "not implemented",
37
+ "not supported",
38
+ )
39
+
40
+
17
41
  class OUMVGateway:
18
42
  """Dispatches OUMV protocol calls to live DevServers with zero-config discovery."""
19
43
 
@@ -21,6 +45,65 @@ class OUMVGateway:
21
45
  _cached_be: Optional[Dict[str, Any]] = None
22
46
  _last_scan_time: float = 0.0
23
47
  _SCAN_INTERVAL_SEC: float = 5.0
48
+ # Liveness cache for descriptor-derived ports: the bash guard runs per command,
49
+ # so a TCP probe must be memoized instead of blocking every invocation.
50
+ _port_liveness: Dict[Tuple[str, int], Tuple[float, bool]] = {}
51
+ _PORT_TTL_SEC: float = 8.0
52
+ _PORT_PROBE_TIMEOUT: float = 0.05
53
+ # Descriptors left behind by a crashed dev server must not stay authoritative forever.
54
+ _DESCRIPTOR_MAX_AGE_SEC: float = 12 * 3600.0
55
+
56
+ @classmethod
57
+ def _is_port_open(cls, host: str, port: int, timeout: Optional[float] = None, use_cache: bool = True) -> bool:
58
+ """Cheap TCP liveness check with a short TTL cache (never raises)."""
59
+ key = (host or "127.0.0.1", int(port))
60
+ now = time.time()
61
+ if use_cache:
62
+ hit = cls._port_liveness.get(key)
63
+ if hit and (now - hit[0]) < cls._PORT_TTL_SEC:
64
+ return hit[1]
65
+ alive = False
66
+ try:
67
+ with socket.create_connection(key, timeout=timeout or cls._PORT_PROBE_TIMEOUT):
68
+ alive = True
69
+ except OSError:
70
+ alive = False
71
+ cls._port_liveness[key] = (now, alive)
72
+ return alive
73
+
74
+ @classmethod
75
+ def _is_url_live(cls, url: Optional[str]) -> bool:
76
+ """True when a runtime URL's port accepts connections (port-less URLs are trusted)."""
77
+ if not url:
78
+ return False
79
+ try:
80
+ parsed = urllib.parse.urlparse(url)
81
+ port = parsed.port
82
+ except ValueError:
83
+ return False
84
+ except Exception:
85
+ return True
86
+ if not port:
87
+ return True
88
+ return cls._is_port_open(parsed.hostname or "127.0.0.1", int(port))
89
+
90
+ @classmethod
91
+ def _drop_stale_descriptor_endpoints(cls) -> List[Dict[str, Any]]:
92
+ """Clears descriptor-sourced endpoints whose port no longer listens.
93
+
94
+ A descriptor is a hint written by the dev server; after a crash it keeps
95
+ pointing at a dead (or reused) port and every consumer would report CONNECTED.
96
+ Returns the dropped entries so callers can explain the downgrade.
97
+ """
98
+ 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)
106
+ return dropped
24
107
 
25
108
  @classmethod
26
109
  def get_endpoints(cls, workspace_dir: Optional[str] = None) -> Tuple[Optional[Dict[str, Any]], Optional[Dict[str, Any]]]:
@@ -28,6 +111,7 @@ class OUMVGateway:
28
111
  now = time.time()
29
112
  if (now - cls._last_scan_time > cls._SCAN_INTERVAL_SEC) or (not cls._cached_fe and not cls._cached_be):
30
113
  cls.scan(workspace_dir=workspace_dir)
114
+ cls._drop_stale_descriptor_endpoints()
31
115
  return cls._cached_fe, cls._cached_be
32
116
 
33
117
  @classmethod
@@ -77,9 +161,18 @@ class OUMVGateway:
77
161
  if found_be:
78
162
  cls._cached_be = found_be
79
163
 
164
+ @staticmethod
165
+ def global_runtime_file(workspace_dir: str) -> str:
166
+ """Zero-footprint global runtime descriptor path outside the target repo."""
167
+ canonical = os.path.realpath(os.path.abspath(workspace_dir))
168
+ ws_id = hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:16]
169
+ tokensafe_home = os.environ.get("TOKENSAFE_HOME") or os.path.expanduser("~/.tokensafe")
170
+ return os.path.join(tokensafe_home, "runtimes", f"{ws_id}.json")
171
+
80
172
  @classmethod
81
173
  def _check_workspace_runtime_files(cls, workspace_dir: str):
82
174
  lock_paths = [
175
+ cls.global_runtime_file(workspace_dir),
83
176
  os.path.join(workspace_dir, ".tokensafe", "runtime.json"),
84
177
  os.path.join(workspace_dir, ".oumv", "runtime.json"),
85
178
  ]
@@ -97,6 +190,7 @@ class OUMVGateway:
97
190
  "url": fe_info["url"],
98
191
  "sessionToken": fe_info.get("sessionToken"),
99
192
  "healthy": True,
193
+ "source": "descriptor",
100
194
  "capabilities": fe_info.get("capabilities", {}),
101
195
  }
102
196
  be_info = data.get("backend")
@@ -108,6 +202,7 @@ class OUMVGateway:
108
202
  "url": be_info["url"],
109
203
  "sessionToken": be_info.get("session_token") or be_info.get("sessionToken"),
110
204
  "healthy": True,
205
+ "source": "descriptor",
111
206
  "capabilities": be_info.get("capabilities", {}),
112
207
  }
113
208
  except Exception:
@@ -161,17 +256,48 @@ class OUMVGateway:
161
256
  method="POST",
162
257
  )
163
258
 
164
- with urllib.request.urlopen(req, timeout=timeout) as resp:
165
- data = json.loads(resp.read().decode("utf-8"))
166
- if "error" in data and data["error"]:
167
- err = data["error"]
168
- msg = err.get("message") if isinstance(err, dict) else str(err)
169
- raise RuntimeError(f"JSON-RPC error from {endpoint_url}: {msg}")
170
- return data.get("result")
259
+ try:
260
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
261
+ data = json.loads(resp.read().decode("utf-8"))
262
+ if "error" in data and data["error"]:
263
+ err = data["error"]
264
+ if isinstance(err, dict):
265
+ code = err.get("code")
266
+ msg = err.get("message") or str(err)
267
+ raise OUMVRpcError(f"JSON-RPC error ({code}) from {endpoint_url}: {msg}")
268
+ raise OUMVRpcError(f"JSON-RPC error from {endpoint_url}: {err}")
269
+ return data.get("result")
270
+ except urllib.error.HTTPError as exc:
271
+ # Some bridges answer an unsupported method with HTTP 400 instead of a
272
+ # JSON-RPC envelope. Treat that as a protocol error (RuntimeError) so
273
+ # callers can fall back to offline operation instead of crashing on OSError.
274
+ code, msg = cls._http_error_detail(exc)
275
+ raise OUMVRpcError(f"JSON-RPC error ({code}) from {endpoint_url}: {msg}") from exc
276
+ except urllib.error.URLError as exc:
277
+ raise OUMVRpcError(f"runtime unreachable at {endpoint_url}: {exc.reason}") from exc
278
+ except (TimeoutError, OSError) as exc:
279
+ raise OUMVRpcError(f"runtime unreachable at {endpoint_url}: {exc}") from exc
280
+
281
+ @staticmethod
282
+ def _http_error_detail(exc: urllib.error.HTTPError) -> Tuple[Optional[int], str]:
283
+ """Extracts (JSON-RPC code, message) from an HTTP error body (read once)."""
284
+ try:
285
+ raw = exc.read().decode("utf-8", "replace")
286
+ except Exception:
287
+ return None, str(exc)
288
+ try:
289
+ err = json.loads(raw).get("error")
290
+ if isinstance(err, dict):
291
+ return err.get("code"), err.get("message") or raw.strip() or str(exc)
292
+ if isinstance(err, str):
293
+ return None, err
294
+ except Exception:
295
+ pass
296
+ return None, raw.strip() or str(exc)
171
297
 
172
298
  @classmethod
173
- def _resolve_client_url(cls, runtime: str = "auto", target: Optional[str] = None) -> str:
174
- fe, be = cls.get_endpoints()
299
+ def _resolve_client_url(cls, runtime: str = "auto", target: Optional[str] = None, workspace_dir: Optional[str] = None) -> str:
300
+ fe, be = cls.get_endpoints(workspace_dir=workspace_dir)
175
301
 
176
302
  if runtime == "frontend":
177
303
  if not fe:
@@ -211,10 +337,79 @@ class OUMVGateway:
211
337
  return fe["url"]
212
338
  raise RuntimeError("No live OUMV runtime (Frontend or Backend) detected in workspace.")
213
339
 
340
+ @classmethod
341
+ def _runtime_marker_path(cls, workspace_dir: Optional[str] = None) -> str:
342
+ from src.paths import resolve_data_dir
343
+ ws = os.path.realpath(os.path.abspath(workspace_dir or get_active_workspace()))
344
+ ws_id = hashlib.sha256(ws.encode("utf-8")).hexdigest()[:16]
345
+ return os.path.join(resolve_data_dir(), f".oumv_used_{ws_id}")
346
+
347
+ @classmethod
348
+ def mark_oumv_used(cls, workspace_dir: Optional[str] = None) -> None:
349
+ try:
350
+ marker = cls._runtime_marker_path(workspace_dir)
351
+ os.makedirs(os.path.dirname(marker), exist_ok=True)
352
+ with open(marker, "w", encoding="utf-8") as f:
353
+ f.write(str(time.time()))
354
+ except Exception:
355
+ pass
356
+
357
+ @classmethod
358
+ def was_recently_used(cls, workspace_dir: Optional[str] = None, max_age_sec: float = 1800.0) -> bool:
359
+ try:
360
+ marker = cls._runtime_marker_path(workspace_dir)
361
+ if not os.path.isfile(marker):
362
+ return False
363
+ return (time.time() - os.path.getmtime(marker)) < max_age_sec
364
+ except Exception:
365
+ return False
366
+
367
+ @classmethod
368
+ def get_live_ports(cls, workspace_dir: Optional[str] = None) -> List[int]:
369
+ """Ports from OUMV runtime descriptors that are fresh AND actually listening.
370
+
371
+ Guards that hard-block raw curl rely on this list, so a descriptor left behind
372
+ by a crashed dev server (or a port later reused by another process) must not
373
+ count as a live runtime.
374
+ """
375
+ ws = workspace_dir or get_active_workspace()
376
+ now = time.time()
377
+ ports: List[int] = []
378
+ for lp in (
379
+ cls.global_runtime_file(ws),
380
+ os.path.join(ws, ".tokensafe", "runtime.json"),
381
+ os.path.join(ws, ".oumv", "runtime.json"),
382
+ ):
383
+ if not os.path.isfile(lp):
384
+ continue
385
+ try:
386
+ if (now - os.path.getmtime(lp)) > cls._DESCRIPTOR_MAX_AGE_SEC:
387
+ continue
388
+ with open(lp, "r", encoding="utf-8") as f:
389
+ data = json.load(f)
390
+ for sec in ("frontend", "backend"):
391
+ url = (data.get(sec) or {}).get("url")
392
+ if not url:
393
+ continue
394
+ parsed = urllib.parse.urlparse(url)
395
+ if not parsed.port:
396
+ continue
397
+ port = int(parsed.port)
398
+ if port in ports:
399
+ continue
400
+ if cls._is_port_open(parsed.hostname or "127.0.0.1", port):
401
+ ports.append(port)
402
+ except Exception:
403
+ pass
404
+ return ports
405
+
214
406
  # 1. Tool: oumv_status
215
407
  @classmethod
216
408
  def status(cls, workspace_dir: Optional[str] = None) -> Dict[str, Any]:
409
+ cls.mark_oumv_used(workspace_dir)
217
410
  cls.scan(workspace_dir=workspace_dir)
411
+ # A descriptor whose port is closed must not be reported as a live runtime.
412
+ dropped = cls._drop_stale_descriptor_endpoints()
218
413
  fe, be = cls._cached_fe, cls._cached_be
219
414
  ws = workspace_dir or get_active_workspace()
220
415
 
@@ -226,30 +421,50 @@ class OUMVGateway:
226
421
  except Exception:
227
422
  pass
228
423
 
229
- return {
424
+ be_stack = stack_info.get("backend") or {}
425
+ be_unsupported = bool(be_stack) and not be_stack.get("oumv_supported", True) and not be
426
+
427
+ result: Dict[str, Any] = {
230
428
  "mode": "OUT_OF_THE_BOX_HYBRID",
231
429
  "frontend": fe or {
232
430
  "status": "DISCONNECTED",
233
- "framework": stack_info.get("frontend", {}).get("framework", "None") if stack_info.get("frontend") else "None",
234
- "tip": "Static AST analysis active. When frontend DevServer starts (port 5173/3000), live OUMV auto-connects."
431
+ "framework": (stack_info.get("frontend") or {}).get("framework", "None"),
432
+ "tip": "Static AST analysis active. Run 'tokensafe dev' (zero repo footprint) for live Vite+React OUMV.",
235
433
  },
236
- "backend": be or {
434
+ "backend": be or ({
435
+ "status": "UNSUPPORTED",
436
+ "framework": be_stack.get("framework", "node"),
437
+ "provider": be_stack.get("provider", "node"),
438
+ "tip": f"No OUMV runtime adapter for {be_stack.get('framework', 'Node.js')} yet (planned). Use repo_map, smart_read_file, and scoped_search for backend code.",
439
+ } if be_unsupported else {
237
440
  "status": "DISCONNECTED",
238
- "framework": stack_info.get("backend", {}).get("framework", "None") if stack_info.get("backend") else "None",
239
- "tip": "Static AST analysis active. When backend DevServer starts (port 8080/8000), live OUMV auto-connects."
240
- },
441
+ "framework": be_stack.get("framework", "None"),
442
+ "tip": "Static AST analysis active. When backend DevServer starts (port 8080/8000), live OUMV auto-connects.",
443
+ }),
241
444
  "adapters": cls._adapter_lifecycle(stack_info, fe, be),
242
445
  "staticIntelligence": "ACTIVE (L0/L1/L2 AST observation & cross-stack linking ready)",
243
446
  "detectedStack": stack_info,
244
447
  "workspace": ws,
245
448
  }
449
+ if dropped:
450
+ result["staleRuntimes"] = [
451
+ {
452
+ "kind": d.get("kind"),
453
+ "url": d.get("url"),
454
+ "reason": "runtime descriptor present but its port is closed (crashed dev server?)",
455
+ }
456
+ for d in dropped
457
+ ]
458
+ return result
246
459
 
247
460
  @staticmethod
248
461
  def _adapter_lifecycle(stack_info: Dict[str, Any], fe: Optional[Dict[str, Any]], be: Optional[Dict[str, Any]]) -> List[Dict[str, Any]]:
249
462
  """Per-adapter lifecycle + health per the OUMV Adapter Contract (schemas/adapter.json)."""
250
463
  adapters: List[Dict[str, Any]] = []
251
- fe_detected = bool(stack_info.get("frontend"))
252
- be_detected = bool(stack_info.get("backend"))
464
+ fe_info = stack_info.get("frontend") or {}
465
+ be_info = stack_info.get("backend") or {}
466
+ fe_detected = bool(fe_info)
467
+ be_detected = bool(be_info)
253
468
  if not fe_detected and not be_detected:
254
469
  return adapters
255
470
 
@@ -262,17 +477,26 @@ class OUMVGateway:
262
477
  def _find_adapter(profile: str, provider: Optional[str]) -> Dict[str, Any]:
263
478
  if provider:
264
479
  for a in catalog:
265
- if a.get("id") == f"{profile}/{provider}" and a.get("status") == "ready":
480
+ if a.get("id") == f"{profile}/{provider}":
266
481
  return a
267
482
  for a in catalog:
268
483
  if a.get("profile") == profile and a.get("status") == "ready":
269
484
  return a
270
485
  return {}
271
486
 
272
- def _entry(profile: str, connected: Optional[Dict[str, Any]], detected: bool, provider: Optional[str] = None) -> Dict[str, Any]:
487
+ def _entry(profile: str, connected: Optional[Dict[str, Any]], detected: bool, info: Dict[str, Any]) -> Dict[str, Any]:
488
+ provider = info.get("provider")
273
489
  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")
274
491
  if connected:
275
492
  state, health, detail = "ACTIVE", "healthy", f"Live runtime: {connected.get('name', 'unknown')}"
493
+ elif is_planned:
494
+ state = "UNSUPPORTED"
495
+ health = "unsupported"
496
+ detail = (
497
+ f"{adapter.get('id', f'{profile}/{provider}')} is not implemented yet (planned). "
498
+ "Do not use tokensafe:oumv for this profile — use repo_map, smart_read_file, and scoped_search instead."
499
+ )
276
500
  elif detected:
277
501
  state, health, detail = "HANDSHAKE", "degraded", "Detected statically; runtime offline — hybrid static fallback active"
278
502
  else:
@@ -280,6 +504,7 @@ class OUMVGateway:
280
504
  return {
281
505
  "profile": profile,
282
506
  "adapter": adapter.get("id", f"{profile}/unknown"),
507
+ "status": adapter.get("status", "unknown"),
283
508
  "technology": adapter.get("technology"),
284
509
  "capabilities": adapter.get("capabilities"),
285
510
  "lifecycle": {"state": state, "health": {"status": health, "detail": detail}},
@@ -289,14 +514,49 @@ class OUMVGateway:
289
514
  },
290
515
  }
291
516
 
292
- adapters.append(_entry("frontend", fe, fe_detected, (stack_info.get("frontend") or {}).get("provider")))
293
- adapters.append(_entry("backend", be, be_detected, (stack_info.get("backend") or {}).get("provider")))
517
+ adapters.append(_entry("frontend", fe, fe_detected, fe_info))
518
+ adapters.append(_entry("backend", be, be_detected, be_info))
294
519
  return adapters
295
520
 
521
+ @staticmethod
522
+ def _unsupported_backend_notice(workspace_dir: Optional[str], runtime: str) -> Optional[Dict[str, Any]]:
523
+ if runtime != "backend":
524
+ return None
525
+ ws = workspace_dir or get_active_workspace()
526
+ try:
527
+ from src.retrofit import detect_project_stack
528
+ stack = detect_project_stack(ws)
529
+ be = stack.get("backend") or {}
530
+ if be and not be.get("oumv_supported", True):
531
+ fe = stack.get("frontend")
532
+ supported = [f"frontend/{fe['provider']}"] if fe and fe.get("oumv_supported", True) else []
533
+ return {
534
+ "unsupportedRuntime": f"backend/{be.get('provider', 'node')}",
535
+ "framework": be.get("framework"),
536
+ "supportedProfiles": supported,
537
+ "guidance": (
538
+ f"OUMV runtime adapter for {be.get('framework', 'Node.js')} is not available yet (planned). "
539
+ "Use tokensafe:repo_map, tokensafe:smart_read_file, and tokensafe:scoped_search for this backend; "
540
+ + ("keep using tokensafe:oumv(runtime='frontend') for UI." if supported else "use standard tests for verification.")
541
+ ),
542
+ }
543
+ except Exception:
544
+ pass
545
+ return None
546
+
296
547
  # 2. Tool: oumv_observe
297
548
  @classmethod
298
- def observe(cls, level: str = "L0", target: Optional[str] = None, runtime: str = "auto") -> Any:
299
- fe, be = cls.get_endpoints()
549
+ def observe(cls, level: str = "L0", target: Optional[str] = None, runtime: str = "auto", workspace_dir: Optional[str] = None) -> Any:
550
+ cls.mark_oumv_used(workspace_dir)
551
+ fe, be = cls.get_endpoints(workspace_dir=workspace_dir)
552
+ if runtime == "backend" and not be:
553
+ notice = cls._unsupported_backend_notice(workspace_dir, runtime)
554
+ if notice:
555
+ from src.graph_engine import GraphEngine
556
+ ws = workspace_dir or get_active_workspace()
557
+ res = GraphEngine.get_instance(ws).get_static_oumv_slice(level=level, target=target)
558
+ res.update(notice)
559
+ return res
300
560
 
301
561
  # Consolidated fullstack L0 pulse (~30 tokens)
302
562
  if level.upper() == "L0" and (not target or target == "fullstack") and (runtime in ("auto", "")):
@@ -315,7 +575,7 @@ class OUMVGateway:
315
575
  # Out-of-the-box fallback when both are offline
316
576
  if not fe and not be:
317
577
  from src.graph_engine import GraphEngine
318
- ws = get_active_workspace()
578
+ ws = workspace_dir or get_active_workspace()
319
579
  graph = GraphEngine.get_instance(ws)
320
580
  results["staticAnalysis"] = graph.get_static_oumv_slice(level="L0")
321
581
  results["tip"] = "DevServers offline — static AST intelligence active out-of-the-box."
@@ -328,7 +588,7 @@ class OUMVGateway:
328
588
  return results
329
589
 
330
590
  try:
331
- url = cls._resolve_client_url(runtime=runtime, target=target)
591
+ url = cls._resolve_client_url(runtime=runtime, target=target, workspace_dir=workspace_dir)
332
592
  res = cls._rpc_call(url, "oumv/observe", {"level": level, "target": target, "componentId": target})
333
593
  if isinstance(res, dict) and "evidence" not in res:
334
594
  res["evidence"] = {"provenance": "runtime", "confidence": "confirmed", "sourceAdapter": "live-devserver"}
@@ -336,17 +596,22 @@ class OUMVGateway:
336
596
  except RuntimeError:
337
597
  # Level 1 Static Fallback via GraphEngine
338
598
  from src.graph_engine import GraphEngine
339
- ws = get_active_workspace()
599
+ ws = workspace_dir or get_active_workspace()
340
600
  graph = GraphEngine.get_instance(ws)
341
601
  return graph.get_static_oumv_slice(level=level, target=target)
342
602
 
343
603
  # 3. Tool: oumv_understand
344
604
  @classmethod
345
- def understand(cls, query: str = "causality", target: Optional[str] = None, runtime: str = "auto") -> Any:
346
- fe, be = cls.get_endpoints()
605
+ def understand(cls, query: str = "causality", target: Optional[str] = None, runtime: str = "auto", workspace_dir: Optional[str] = None) -> Any:
606
+ cls.mark_oumv_used(workspace_dir)
607
+ fe, be = cls.get_endpoints(workspace_dir=workspace_dir)
608
+ if runtime == "backend" and not be:
609
+ notice = cls._unsupported_backend_notice(workspace_dir, runtime)
610
+ if notice:
611
+ return notice
347
612
 
348
613
  from src.graph_engine import GraphEngine
349
- ws = get_active_workspace()
614
+ ws = workspace_dir or get_active_workspace()
350
615
  graph = GraphEngine.get_instance(ws)
351
616
 
352
617
  # Impact analysis: static cross-stack graph as the backbone, runtime answers attached when online
@@ -401,7 +666,7 @@ class OUMVGateway:
401
666
  return report
402
667
 
403
668
  try:
404
- url = cls._resolve_client_url(runtime=runtime, target=target)
669
+ url = cls._resolve_client_url(runtime=runtime, target=target, workspace_dir=workspace_dir)
405
670
  return cls._rpc_call(url, "oumv/understand", {"query": query, "target": target, "componentId": target})
406
671
  except RuntimeError:
407
672
  if query == "impact":
@@ -431,9 +696,9 @@ class OUMVGateway:
431
696
 
432
697
  # 4. Tool: oumv_mutate
433
698
  @classmethod
434
- def mutate(cls, path: str, symbol: Optional[str] = None, replacement: Optional[str] = None, expected_version: Optional[str] = None, runtime: str = "auto") -> Any:
699
+ 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:
435
700
  # Check workspace permissions (enabled by default out-of-the-box unless explicitly opted out)
436
- ws = get_active_workspace()
701
+ ws = workspace_dir or get_active_workspace()
437
702
  cfg_file = os.path.join(ws, ".tokensafe", "oumv.json")
438
703
  if os.path.isfile(cfg_file):
439
704
  try:
@@ -448,7 +713,7 @@ class OUMVGateway:
448
713
  pass
449
714
 
450
715
  try:
451
- url = cls._resolve_client_url(runtime=runtime, target=path)
716
+ url = cls._resolve_client_url(runtime=runtime, target=path, workspace_dir=workspace_dir)
452
717
  return cls._rpc_call(url, "oumv/applyEdit", {
453
718
  "path": path,
454
719
  "filePath": path,
@@ -458,6 +723,13 @@ class OUMVGateway:
458
723
  "expectedVersion": expected_version,
459
724
  })
460
725
  except RuntimeError as e:
726
+ if isinstance(e, OUMVRpcError) and not isinstance(e, OUMVUnsupportedMethodError):
727
+ if not any(hint in str(e).lower() for hint in _UNSUPPORTED_HINTS):
728
+ # Explicit safety rejection (conflict, syntax, permission): obey it.
729
+ raise
730
+ # The runtime cannot mediate the edit at all; the offline path below
731
+ # performs the same guarded edit and reports why.
732
+ e = OUMVUnsupportedMethodError(str(e))
461
733
  # Out-of-the-box direct fallback when live dev-servers are offline
462
734
  if replacement is not None:
463
735
  abs_path = os.path.normpath(os.path.join(ws, path))
@@ -514,13 +786,30 @@ class OUMVGateway:
514
786
  if backup_path:
515
787
  result["backupPath"] = backup_path
516
788
  result["rollbackHint"] = f"Previous content backed up at {backup_path}"
789
+ if isinstance(e, OUMVUnsupportedMethodError):
790
+ # The runtime was reachable but has no applyEdit: the edit was
791
+ # mediated by the gateway instead. Say so instead of implying
792
+ # the runtime verified it.
793
+ result["mode"] = "RUNTIME_LACKS_APPLYEDIT_OFFLINE_FALLBACK"
794
+ result["runtimeFallbackReason"] = str(e)
795
+ result["message"] = (
796
+ "Live runtime does not implement oumv/applyEdit; edit applied by the gateway "
797
+ "with the same OCC, syntax-guard and backup checks"
798
+ )
517
799
  return result
518
800
  raise
519
801
 
520
802
  # 5. Tool: oumv_verify
521
803
  @classmethod
522
- def verify(cls, target: str, action: str = "invoke", payload: Optional[dict] = None, runtime: str = "auto") -> Any:
523
- url = cls._resolve_client_url(runtime=runtime, target=target)
804
+ def verify(cls, target: str, action: str = "invoke", payload: Optional[dict] = None, runtime: str = "auto", workspace_dir: Optional[str] = None) -> Any:
805
+ cls.mark_oumv_used(workspace_dir)
806
+ if runtime == "backend":
807
+ _, be = cls.get_endpoints(workspace_dir=workspace_dir)
808
+ if not be:
809
+ notice = cls._unsupported_backend_notice(workspace_dir, runtime)
810
+ if notice:
811
+ return {"status": "unsupported", **notice}
812
+ url = cls._resolve_client_url(runtime=runtime, target=target, workspace_dir=workspace_dir)
524
813
  res = cls._rpc_call(url, "oumv/verify", {
525
814
  "target": target,
526
815
  "componentId": target,
@@ -545,7 +834,7 @@ class OUMVGateway:
545
834
  @classmethod
546
835
  def graph(cls, query: str = "overview", target: Optional[str] = None, workspace_dir: Optional[str] = None) -> Any:
547
836
  """Unified graph over static + runtime evidence, with §11.4-style queries."""
548
- fe, be = cls.get_endpoints()
837
+ fe, be = cls.get_endpoints(workspace_dir=workspace_dir)
549
838
  from src.cross_stack import build_unified_graph, who_depends_on, impact_from_graph
550
839
 
551
840
  ws = workspace_dir or get_active_workspace()
package/src/proxy.py CHANGED
@@ -1286,19 +1286,26 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1286
1286
  pass
1287
1287
  target_symbol = compaction.get("symbol")
1288
1288
 
1289
- # 3. Automatic Architecture Awareness (God Nodes Injection — deterministic
1289
+ # 3. Automatic Architecture Awareness & OUMV Capability Matrix (deterministic
1290
1290
  # across turns for the active workspace so KV-cache prefixes stay identical).
1291
1291
  if messages and not is_quota_exceeded:
1292
1292
  try:
1293
1293
  from src.paths import get_active_workspace
1294
+ from src.retrofit import format_oumv_workspace_brief
1294
1295
  ws_root = get_active_workspace()
1295
1296
  if ws_root:
1296
1297
  graph = GraphEngine.get_instance(ws_root)
1297
1298
  banner = graph.format_topology_banner()
1299
+ oumv_brief = format_oumv_workspace_brief(ws_root, include_live=False)
1298
1300
  first_msg = messages[0]
1299
- if banner and isinstance(first_msg.get("content"), str) and "[TokenSafe Architecture" not in first_msg["content"]:
1300
- if first_msg.get("role") == "system":
1301
- first_msg["content"] = f"{banner}\n{first_msg['content']}"
1301
+ if isinstance(first_msg.get("content"), str) and first_msg.get("role") == "system":
1302
+ blocks = []
1303
+ if banner and "[TokenSafe Architecture" not in first_msg["content"]:
1304
+ blocks.append(banner)
1305
+ if oumv_brief and "[TokenSafe OUMV Workspace Matrix" not in first_msg["content"]:
1306
+ blocks.append(oumv_brief)
1307
+ if blocks:
1308
+ first_msg["content"] = "\n".join(blocks) + "\n" + first_msg["content"]
1302
1309
  except Exception:
1303
1310
  pass
1304
1311