tokensafe 4.6.0 → 4.6.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.
@@ -7,6 +7,7 @@ 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 hashlib
10
11
  import urllib.request
11
12
  import urllib.error
12
13
  from concurrent.futures import ThreadPoolExecutor, as_completed
@@ -14,6 +15,10 @@ from typing import Dict, Any, Optional, Tuple, List
14
15
  from src.paths import get_active_workspace
15
16
 
16
17
 
18
+ class OUMVRpcError(RuntimeError):
19
+ """Raised when a live OUMV runtime explicitly returns a JSON-RPC error."""
20
+
21
+
17
22
  class OUMVGateway:
18
23
  """Dispatches OUMV protocol calls to live DevServers with zero-config discovery."""
19
24
 
@@ -77,9 +82,18 @@ class OUMVGateway:
77
82
  if found_be:
78
83
  cls._cached_be = found_be
79
84
 
85
+ @staticmethod
86
+ def global_runtime_file(workspace_dir: str) -> str:
87
+ """Zero-footprint global runtime descriptor path outside the target repo."""
88
+ canonical = os.path.realpath(os.path.abspath(workspace_dir))
89
+ ws_id = hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:16]
90
+ tokensafe_home = os.environ.get("TOKENSAFE_HOME") or os.path.expanduser("~/.tokensafe")
91
+ return os.path.join(tokensafe_home, "runtimes", f"{ws_id}.json")
92
+
80
93
  @classmethod
81
94
  def _check_workspace_runtime_files(cls, workspace_dir: str):
82
95
  lock_paths = [
96
+ cls.global_runtime_file(workspace_dir),
83
97
  os.path.join(workspace_dir, ".tokensafe", "runtime.json"),
84
98
  os.path.join(workspace_dir, ".oumv", "runtime.json"),
85
99
  ]
@@ -165,13 +179,16 @@ class OUMVGateway:
165
179
  data = json.loads(resp.read().decode("utf-8"))
166
180
  if "error" in data and data["error"]:
167
181
  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}")
182
+ if isinstance(err, dict):
183
+ code = err.get("code")
184
+ msg = err.get("message") or str(err)
185
+ raise OUMVRpcError(f"JSON-RPC error ({code}) from {endpoint_url}: {msg}")
186
+ raise OUMVRpcError(f"JSON-RPC error from {endpoint_url}: {err}")
170
187
  return data.get("result")
171
188
 
172
189
  @classmethod
173
- def _resolve_client_url(cls, runtime: str = "auto", target: Optional[str] = None) -> str:
174
- fe, be = cls.get_endpoints()
190
+ def _resolve_client_url(cls, runtime: str = "auto", target: Optional[str] = None, workspace_dir: Optional[str] = None) -> str:
191
+ fe, be = cls.get_endpoints(workspace_dir=workspace_dir)
175
192
 
176
193
  if runtime == "frontend":
177
194
  if not fe:
@@ -211,9 +228,63 @@ class OUMVGateway:
211
228
  return fe["url"]
212
229
  raise RuntimeError("No live OUMV runtime (Frontend or Backend) detected in workspace.")
213
230
 
231
+ @classmethod
232
+ def _runtime_marker_path(cls, workspace_dir: Optional[str] = None) -> str:
233
+ from src.paths import resolve_data_dir
234
+ ws = os.path.realpath(os.path.abspath(workspace_dir or get_active_workspace()))
235
+ ws_id = hashlib.sha256(ws.encode("utf-8")).hexdigest()[:16]
236
+ return os.path.join(resolve_data_dir(), f".oumv_used_{ws_id}")
237
+
238
+ @classmethod
239
+ def mark_oumv_used(cls, workspace_dir: Optional[str] = None) -> None:
240
+ try:
241
+ marker = cls._runtime_marker_path(workspace_dir)
242
+ os.makedirs(os.path.dirname(marker), exist_ok=True)
243
+ with open(marker, "w", encoding="utf-8") as f:
244
+ f.write(str(time.time()))
245
+ except Exception:
246
+ pass
247
+
248
+ @classmethod
249
+ def was_recently_used(cls, workspace_dir: Optional[str] = None, max_age_sec: float = 1800.0) -> bool:
250
+ try:
251
+ marker = cls._runtime_marker_path(workspace_dir)
252
+ if not os.path.isfile(marker):
253
+ return False
254
+ return (time.time() - os.path.getmtime(marker)) < max_age_sec
255
+ except Exception:
256
+ return False
257
+
258
+ @classmethod
259
+ def get_live_ports(cls, workspace_dir: Optional[str] = None) -> List[int]:
260
+ """Returns localhost ports from active workspace/global OUMV runtime descriptors without blocking scans."""
261
+ import urllib.parse
262
+ ws = workspace_dir or get_active_workspace()
263
+ ports: List[int] = []
264
+ for lp in (
265
+ cls.global_runtime_file(ws),
266
+ os.path.join(ws, ".tokensafe", "runtime.json"),
267
+ os.path.join(ws, ".oumv", "runtime.json"),
268
+ ):
269
+ if not os.path.isfile(lp):
270
+ continue
271
+ try:
272
+ with open(lp, "r", encoding="utf-8") as f:
273
+ data = json.load(f)
274
+ for sec in ("frontend", "backend"):
275
+ url = (data.get(sec) or {}).get("url")
276
+ if url:
277
+ parsed = urllib.parse.urlparse(url)
278
+ if parsed.port and parsed.port not in ports:
279
+ ports.append(int(parsed.port))
280
+ except Exception:
281
+ pass
282
+ return ports
283
+
214
284
  # 1. Tool: oumv_status
215
285
  @classmethod
216
286
  def status(cls, workspace_dir: Optional[str] = None) -> Dict[str, Any]:
287
+ cls.mark_oumv_used(workspace_dir)
217
288
  cls.scan(workspace_dir=workspace_dir)
218
289
  fe, be = cls._cached_fe, cls._cached_be
219
290
  ws = workspace_dir or get_active_workspace()
@@ -226,18 +297,26 @@ class OUMVGateway:
226
297
  except Exception:
227
298
  pass
228
299
 
300
+ be_stack = stack_info.get("backend") or {}
301
+ be_unsupported = bool(be_stack) and not be_stack.get("oumv_supported", True) and not be
302
+
229
303
  return {
230
304
  "mode": "OUT_OF_THE_BOX_HYBRID",
231
305
  "frontend": fe or {
232
306
  "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."
307
+ "framework": (stack_info.get("frontend") or {}).get("framework", "None"),
308
+ "tip": "Static AST analysis active. Run 'tokensafe dev' (zero repo footprint) for live Vite+React OUMV.",
235
309
  },
236
- "backend": be or {
310
+ "backend": be or ({
311
+ "status": "UNSUPPORTED",
312
+ "framework": be_stack.get("framework", "node"),
313
+ "provider": be_stack.get("provider", "node"),
314
+ "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.",
315
+ } if be_unsupported else {
237
316
  "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
- },
317
+ "framework": be_stack.get("framework", "None"),
318
+ "tip": "Static AST analysis active. When backend DevServer starts (port 8080/8000), live OUMV auto-connects.",
319
+ }),
241
320
  "adapters": cls._adapter_lifecycle(stack_info, fe, be),
242
321
  "staticIntelligence": "ACTIVE (L0/L1/L2 AST observation & cross-stack linking ready)",
243
322
  "detectedStack": stack_info,
@@ -248,8 +327,10 @@ class OUMVGateway:
248
327
  def _adapter_lifecycle(stack_info: Dict[str, Any], fe: Optional[Dict[str, Any]], be: Optional[Dict[str, Any]]) -> List[Dict[str, Any]]:
249
328
  """Per-adapter lifecycle + health per the OUMV Adapter Contract (schemas/adapter.json)."""
250
329
  adapters: List[Dict[str, Any]] = []
251
- fe_detected = bool(stack_info.get("frontend"))
252
- be_detected = bool(stack_info.get("backend"))
330
+ fe_info = stack_info.get("frontend") or {}
331
+ be_info = stack_info.get("backend") or {}
332
+ fe_detected = bool(fe_info)
333
+ be_detected = bool(be_info)
253
334
  if not fe_detected and not be_detected:
254
335
  return adapters
255
336
 
@@ -262,17 +343,26 @@ class OUMVGateway:
262
343
  def _find_adapter(profile: str, provider: Optional[str]) -> Dict[str, Any]:
263
344
  if provider:
264
345
  for a in catalog:
265
- if a.get("id") == f"{profile}/{provider}" and a.get("status") == "ready":
346
+ if a.get("id") == f"{profile}/{provider}":
266
347
  return a
267
348
  for a in catalog:
268
349
  if a.get("profile") == profile and a.get("status") == "ready":
269
350
  return a
270
351
  return {}
271
352
 
272
- def _entry(profile: str, connected: Optional[Dict[str, Any]], detected: bool, provider: Optional[str] = None) -> Dict[str, Any]:
353
+ def _entry(profile: str, connected: Optional[Dict[str, Any]], detected: bool, info: Dict[str, Any]) -> Dict[str, Any]:
354
+ provider = info.get("provider")
273
355
  adapter = _find_adapter(profile, provider)
356
+ is_planned = detected and (info.get("status") == "planned" or info.get("oumv_supported") is False or adapter.get("status") == "planned")
274
357
  if connected:
275
358
  state, health, detail = "ACTIVE", "healthy", f"Live runtime: {connected.get('name', 'unknown')}"
359
+ elif is_planned:
360
+ state = "UNSUPPORTED"
361
+ health = "unsupported"
362
+ detail = (
363
+ f"{adapter.get('id', f'{profile}/{provider}')} is not implemented yet (planned). "
364
+ "Do not use tokensafe:oumv for this profile — use repo_map, smart_read_file, and scoped_search instead."
365
+ )
276
366
  elif detected:
277
367
  state, health, detail = "HANDSHAKE", "degraded", "Detected statically; runtime offline — hybrid static fallback active"
278
368
  else:
@@ -280,6 +370,7 @@ class OUMVGateway:
280
370
  return {
281
371
  "profile": profile,
282
372
  "adapter": adapter.get("id", f"{profile}/unknown"),
373
+ "status": adapter.get("status", "unknown"),
283
374
  "technology": adapter.get("technology"),
284
375
  "capabilities": adapter.get("capabilities"),
285
376
  "lifecycle": {"state": state, "health": {"status": health, "detail": detail}},
@@ -289,14 +380,49 @@ class OUMVGateway:
289
380
  },
290
381
  }
291
382
 
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")))
383
+ adapters.append(_entry("frontend", fe, fe_detected, fe_info))
384
+ adapters.append(_entry("backend", be, be_detected, be_info))
294
385
  return adapters
295
386
 
387
+ @staticmethod
388
+ def _unsupported_backend_notice(workspace_dir: Optional[str], runtime: str) -> Optional[Dict[str, Any]]:
389
+ if runtime != "backend":
390
+ return None
391
+ ws = workspace_dir or get_active_workspace()
392
+ try:
393
+ from src.retrofit import detect_project_stack
394
+ stack = detect_project_stack(ws)
395
+ be = stack.get("backend") or {}
396
+ if be and not be.get("oumv_supported", True):
397
+ fe = stack.get("frontend")
398
+ supported = [f"frontend/{fe['provider']}"] if fe and fe.get("oumv_supported", True) else []
399
+ return {
400
+ "unsupportedRuntime": f"backend/{be.get('provider', 'node')}",
401
+ "framework": be.get("framework"),
402
+ "supportedProfiles": supported,
403
+ "guidance": (
404
+ f"OUMV runtime adapter for {be.get('framework', 'Node.js')} is not available yet (planned). "
405
+ "Use tokensafe:repo_map, tokensafe:smart_read_file, and tokensafe:scoped_search for this backend; "
406
+ + ("keep using tokensafe:oumv(runtime='frontend') for UI." if supported else "use standard tests for verification.")
407
+ ),
408
+ }
409
+ except Exception:
410
+ pass
411
+ return None
412
+
296
413
  # 2. Tool: oumv_observe
297
414
  @classmethod
298
- def observe(cls, level: str = "L0", target: Optional[str] = None, runtime: str = "auto") -> Any:
299
- fe, be = cls.get_endpoints()
415
+ def observe(cls, level: str = "L0", target: Optional[str] = None, runtime: str = "auto", workspace_dir: Optional[str] = None) -> Any:
416
+ cls.mark_oumv_used(workspace_dir)
417
+ fe, be = cls.get_endpoints(workspace_dir=workspace_dir)
418
+ if runtime == "backend" and not be:
419
+ notice = cls._unsupported_backend_notice(workspace_dir, runtime)
420
+ if notice:
421
+ from src.graph_engine import GraphEngine
422
+ ws = workspace_dir or get_active_workspace()
423
+ res = GraphEngine.get_instance(ws).get_static_oumv_slice(level=level, target=target)
424
+ res.update(notice)
425
+ return res
300
426
 
301
427
  # Consolidated fullstack L0 pulse (~30 tokens)
302
428
  if level.upper() == "L0" and (not target or target == "fullstack") and (runtime in ("auto", "")):
@@ -315,7 +441,7 @@ class OUMVGateway:
315
441
  # Out-of-the-box fallback when both are offline
316
442
  if not fe and not be:
317
443
  from src.graph_engine import GraphEngine
318
- ws = get_active_workspace()
444
+ ws = workspace_dir or get_active_workspace()
319
445
  graph = GraphEngine.get_instance(ws)
320
446
  results["staticAnalysis"] = graph.get_static_oumv_slice(level="L0")
321
447
  results["tip"] = "DevServers offline — static AST intelligence active out-of-the-box."
@@ -328,7 +454,7 @@ class OUMVGateway:
328
454
  return results
329
455
 
330
456
  try:
331
- url = cls._resolve_client_url(runtime=runtime, target=target)
457
+ url = cls._resolve_client_url(runtime=runtime, target=target, workspace_dir=workspace_dir)
332
458
  res = cls._rpc_call(url, "oumv/observe", {"level": level, "target": target, "componentId": target})
333
459
  if isinstance(res, dict) and "evidence" not in res:
334
460
  res["evidence"] = {"provenance": "runtime", "confidence": "confirmed", "sourceAdapter": "live-devserver"}
@@ -336,17 +462,22 @@ class OUMVGateway:
336
462
  except RuntimeError:
337
463
  # Level 1 Static Fallback via GraphEngine
338
464
  from src.graph_engine import GraphEngine
339
- ws = get_active_workspace()
465
+ ws = workspace_dir or get_active_workspace()
340
466
  graph = GraphEngine.get_instance(ws)
341
467
  return graph.get_static_oumv_slice(level=level, target=target)
342
468
 
343
469
  # 3. Tool: oumv_understand
344
470
  @classmethod
345
- def understand(cls, query: str = "causality", target: Optional[str] = None, runtime: str = "auto") -> Any:
346
- fe, be = cls.get_endpoints()
471
+ def understand(cls, query: str = "causality", target: Optional[str] = None, runtime: str = "auto", workspace_dir: Optional[str] = None) -> Any:
472
+ cls.mark_oumv_used(workspace_dir)
473
+ fe, be = cls.get_endpoints(workspace_dir=workspace_dir)
474
+ if runtime == "backend" and not be:
475
+ notice = cls._unsupported_backend_notice(workspace_dir, runtime)
476
+ if notice:
477
+ return notice
347
478
 
348
479
  from src.graph_engine import GraphEngine
349
- ws = get_active_workspace()
480
+ ws = workspace_dir or get_active_workspace()
350
481
  graph = GraphEngine.get_instance(ws)
351
482
 
352
483
  # Impact analysis: static cross-stack graph as the backbone, runtime answers attached when online
@@ -401,7 +532,7 @@ class OUMVGateway:
401
532
  return report
402
533
 
403
534
  try:
404
- url = cls._resolve_client_url(runtime=runtime, target=target)
535
+ url = cls._resolve_client_url(runtime=runtime, target=target, workspace_dir=workspace_dir)
405
536
  return cls._rpc_call(url, "oumv/understand", {"query": query, "target": target, "componentId": target})
406
537
  except RuntimeError:
407
538
  if query == "impact":
@@ -431,9 +562,9 @@ class OUMVGateway:
431
562
 
432
563
  # 4. Tool: oumv_mutate
433
564
  @classmethod
434
- def mutate(cls, path: str, symbol: Optional[str] = None, replacement: Optional[str] = None, expected_version: Optional[str] = None, runtime: str = "auto") -> Any:
565
+ 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
566
  # Check workspace permissions (enabled by default out-of-the-box unless explicitly opted out)
436
- ws = get_active_workspace()
567
+ ws = workspace_dir or get_active_workspace()
437
568
  cfg_file = os.path.join(ws, ".tokensafe", "oumv.json")
438
569
  if os.path.isfile(cfg_file):
439
570
  try:
@@ -448,7 +579,7 @@ class OUMVGateway:
448
579
  pass
449
580
 
450
581
  try:
451
- url = cls._resolve_client_url(runtime=runtime, target=path)
582
+ url = cls._resolve_client_url(runtime=runtime, target=path, workspace_dir=workspace_dir)
452
583
  return cls._rpc_call(url, "oumv/applyEdit", {
453
584
  "path": path,
454
585
  "filePath": path,
@@ -457,6 +588,8 @@ class OUMVGateway:
457
588
  "source": replacement,
458
589
  "expectedVersion": expected_version,
459
590
  })
591
+ except OUMVRpcError:
592
+ raise
460
593
  except RuntimeError as e:
461
594
  # Out-of-the-box direct fallback when live dev-servers are offline
462
595
  if replacement is not None:
@@ -519,8 +652,15 @@ class OUMVGateway:
519
652
 
520
653
  # 5. Tool: oumv_verify
521
654
  @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)
655
+ def verify(cls, target: str, action: str = "invoke", payload: Optional[dict] = None, runtime: str = "auto", workspace_dir: Optional[str] = None) -> Any:
656
+ cls.mark_oumv_used(workspace_dir)
657
+ if runtime == "backend":
658
+ _, be = cls.get_endpoints(workspace_dir=workspace_dir)
659
+ if not be:
660
+ notice = cls._unsupported_backend_notice(workspace_dir, runtime)
661
+ if notice:
662
+ return {"status": "unsupported", **notice}
663
+ url = cls._resolve_client_url(runtime=runtime, target=target, workspace_dir=workspace_dir)
524
664
  res = cls._rpc_call(url, "oumv/verify", {
525
665
  "target": target,
526
666
  "componentId": target,
@@ -545,7 +685,7 @@ class OUMVGateway:
545
685
  @classmethod
546
686
  def graph(cls, query: str = "overview", target: Optional[str] = None, workspace_dir: Optional[str] = None) -> Any:
547
687
  """Unified graph over static + runtime evidence, with §11.4-style queries."""
548
- fe, be = cls.get_endpoints()
688
+ fe, be = cls.get_endpoints(workspace_dir=workspace_dir)
549
689
  from src.cross_stack import build_unified_graph, who_depends_on, impact_from_graph
550
690
 
551
691
  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