tokensafe 4.4.6 → 4.4.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -95,6 +95,7 @@ class OUMVGateway:
95
95
  "name": fe_info.get("name", "tokensafe-ui"),
96
96
  "version": fe_info.get("version", "1.0.0"),
97
97
  "url": fe_info["url"],
98
+ "sessionToken": fe_info.get("sessionToken"),
98
99
  "healthy": True,
99
100
  "capabilities": fe_info.get("capabilities", {}),
100
101
  }
@@ -105,6 +106,7 @@ class OUMVGateway:
105
106
  "name": be_info.get("name", "tokensafe-backend"),
106
107
  "version": be_info.get("version", "1.0.0"),
107
108
  "url": be_info["url"],
109
+ "sessionToken": be_info.get("session_token") or be_info.get("sessionToken"),
108
110
  "healthy": True,
109
111
  "capabilities": be_info.get("capabilities", {}),
110
112
  }
@@ -142,10 +144,20 @@ class OUMVGateway:
142
144
  "params": params or {},
143
145
  }).encode("utf-8")
144
146
 
147
+ headers = {"Content-Type": "application/json", "User-Agent": "TokenSafe-Gateway/1.0"}
148
+ token = None
149
+ if cls._cached_fe and cls._cached_fe.get("url") == endpoint_url:
150
+ token = cls._cached_fe.get("sessionToken")
151
+ elif cls._cached_be and cls._cached_be.get("url") == endpoint_url:
152
+ token = cls._cached_be.get("sessionToken")
153
+
154
+ if token:
155
+ headers["X-OUMV-Session-Token"] = token
156
+
145
157
  req = urllib.request.Request(
146
158
  endpoint_url,
147
159
  data=payload,
148
- headers={"Content-Type": "application/json", "User-Agent": "TokenSafe-Gateway/1.0"},
160
+ headers=headers,
149
161
  method="POST",
150
162
  )
151
163
 
@@ -172,12 +184,23 @@ class OUMVGateway:
172
184
 
173
185
  # Auto detection based on target
174
186
  if target:
187
+ try:
188
+ from src.retrofit import OUMVProjectContext
189
+ ctx = OUMVProjectContext.get_for_workspace()
190
+ detected_rt = ctx.resolve_target_runtime(target)
191
+ if detected_rt == "backend" and be:
192
+ return be["url"]
193
+ elif detected_rt == "frontend" and fe:
194
+ return fe["url"]
195
+ except Exception:
196
+ pass
197
+
175
198
  # Backend hints: HTTP method prefixes, API paths, SQL, handlers
176
199
  if any(target.startswith(m) for m in ["GET ", "POST ", "PUT ", "DELETE ", "PATCH "]) or "/api/" in target or target.startswith("/"):
177
200
  if be:
178
201
  return be["url"]
179
202
  # Frontend hints: DOM selectors (#, .), components (<, JSX, Tab)
180
- if any(target.startswith(c) for c in ["#", ".", "[", "button", "input"]) or target.startswith("<"):
203
+ if any(target.startswith(c) for c in ["#", ".", "[", "button", "input"]) or target.startswith("<") or target.endswith((".tsx", ".jsx", ".vue")):
181
204
  if fe:
182
205
  return fe["url"]
183
206
 
@@ -193,10 +216,31 @@ class OUMVGateway:
193
216
  def status(cls, workspace_dir: Optional[str] = None) -> Dict[str, Any]:
194
217
  cls.scan(workspace_dir=workspace_dir)
195
218
  fe, be = cls._cached_fe, cls._cached_be
219
+ ws = workspace_dir or get_active_workspace()
220
+
221
+ # Out-of-the-box stack detection
222
+ stack_info = {}
223
+ try:
224
+ from src.retrofit import detect_project_stack
225
+ stack_info = detect_project_stack(ws)
226
+ except Exception:
227
+ pass
228
+
196
229
  return {
197
- "frontend": fe or {"status": "DISCONNECTED", "tip": "Start frontend dev-server (port 5173/3000)"},
198
- "backend": be or {"status": "DISCONNECTED", "tip": "Start backend dev-server (port 8080/8000)"},
199
- "workspace": workspace_dir or get_active_workspace(),
230
+ "mode": "OUT_OF_THE_BOX_HYBRID",
231
+ "frontend": fe or {
232
+ "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."
235
+ },
236
+ "backend": be or {
237
+ "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
+ },
241
+ "staticIntelligence": "ACTIVE (L0/L1/L2 AST observation & cross-stack linking ready)",
242
+ "detectedStack": stack_info,
243
+ "workspace": ws,
200
244
  }
201
245
 
202
246
  # 2. Tool: oumv_observe
@@ -212,21 +256,39 @@ class OUMVGateway:
212
256
  results["frontend"] = cls._rpc_call(fe["url"], "oumv/observe", {"level": "L0"})
213
257
  except Exception as e:
214
258
  results["frontend"] = {"error": str(e)}
215
- else:
216
- results["frontend"] = {"status": "DISCONNECTED", "tip": "No active frontend dev-server (port 5173/3000)"}
217
-
218
259
  if be:
219
260
  try:
220
261
  results["backend"] = cls._rpc_call(be["url"], "oumv/observe", {"level": "L0"})
221
262
  except Exception as e:
222
263
  results["backend"] = {"error": str(e)}
264
+
265
+ # Out-of-the-box fallback when both are offline
266
+ if not fe and not be:
267
+ from src.graph_engine import GraphEngine
268
+ ws = get_active_workspace()
269
+ graph = GraphEngine.get_instance(ws)
270
+ results["staticAnalysis"] = graph.get_static_oumv_slice(level="L0")
271
+ results["tip"] = "DevServers offline — static AST intelligence active out-of-the-box."
223
272
  else:
224
- results["backend"] = {"status": "DISCONNECTED", "tip": "No active backend dev-server (port 8080/8000)"}
273
+ if not fe:
274
+ results["frontend"] = {"status": "OFFLINE_STATIC", "tip": "Frontend DevServer offline (using static AST)"}
275
+ if not be:
276
+ results["backend"] = {"status": "OFFLINE_STATIC", "tip": "Backend DevServer offline (using static AST)"}
225
277
 
226
278
  return results
227
279
 
228
- url = cls._resolve_client_url(runtime=runtime, target=target)
229
- return cls._rpc_call(url, "oumv/observe", {"level": level, "target": target, "componentId": target})
280
+ try:
281
+ url = cls._resolve_client_url(runtime=runtime, target=target)
282
+ res = cls._rpc_call(url, "oumv/observe", {"level": level, "target": target, "componentId": target})
283
+ if isinstance(res, dict) and "evidence" not in res:
284
+ res["evidence"] = {"provenance": "runtime", "confidence": "confirmed", "sourceAdapter": "live-devserver"}
285
+ return res
286
+ except RuntimeError:
287
+ # Level 1 Static Fallback via GraphEngine
288
+ from src.graph_engine import GraphEngine
289
+ ws = get_active_workspace()
290
+ graph = GraphEngine.get_instance(ws)
291
+ return graph.get_static_oumv_slice(level=level, target=target)
230
292
 
231
293
  # 3. Tool: oumv_understand
232
294
  @classmethod
@@ -250,23 +312,86 @@ class OUMVGateway:
250
312
  report["frontendCausality"] = cls._rpc_call(fe["url"], "oumv/understand", {"query": query, "target": target, "componentId": target})
251
313
  except Exception as e:
252
314
  report["frontendError"] = str(e)
315
+
316
+ # Out-of-the-box static fallback if neither is online
317
+ if not be and not fe:
318
+ from src.graph_engine import GraphEngine
319
+ ws = get_active_workspace()
320
+ graph = GraphEngine.get_instance(ws)
321
+ report["staticAnalysis"] = graph.get_static_oumv_slice(level="L1", target=target)
322
+ report["evidence"] = {"provenance": "static", "confidence": "confirmed", "sourceAdapter": "tokensafe-graph-engine"}
323
+
253
324
  return report
254
325
 
255
- url = cls._resolve_client_url(runtime=runtime, target=target)
256
- return cls._rpc_call(url, "oumv/understand", {"query": query, "target": target, "componentId": target})
326
+ try:
327
+ url = cls._resolve_client_url(runtime=runtime, target=target)
328
+ return cls._rpc_call(url, "oumv/understand", {"query": query, "target": target, "componentId": target})
329
+ except RuntimeError:
330
+ from src.graph_engine import GraphEngine
331
+ ws = get_active_workspace()
332
+ graph = GraphEngine.get_instance(ws)
333
+ return graph.get_static_oumv_slice(level="L1", target=target)
257
334
 
258
335
  # 4. Tool: oumv_mutate
259
336
  @classmethod
260
337
  def mutate(cls, path: str, symbol: Optional[str] = None, replacement: Optional[str] = None, expected_version: Optional[str] = None, runtime: str = "auto") -> Any:
261
- url = cls._resolve_client_url(runtime=runtime, target=path)
262
- return cls._rpc_call(url, "oumv/applyEdit", {
263
- "path": path,
264
- "filePath": path,
265
- "symbol": symbol,
266
- "replacement": replacement,
267
- "source": replacement,
268
- "expectedVersion": expected_version,
269
- })
338
+ # Check workspace permissions (enabled by default out-of-the-box unless explicitly opted out)
339
+ ws = get_active_workspace()
340
+ cfg_file = os.path.join(ws, ".tokensafe", "oumv.json")
341
+ if os.path.isfile(cfg_file):
342
+ try:
343
+ with open(cfg_file, "r", encoding="utf-8") as f:
344
+ cfg = json.load(f)
345
+ perms = cfg.get("permissions", {})
346
+ if perms.get("mutate") is False:
347
+ raise RuntimeError("[OUMV PERMISSION_DENIED: -32007] Workspace policy explicitly prohibits mutations (.tokensafe/oumv.json: permissions.mutate=false).")
348
+ except RuntimeError:
349
+ raise
350
+ except Exception:
351
+ pass
352
+
353
+ try:
354
+ url = cls._resolve_client_url(runtime=runtime, target=path)
355
+ return cls._rpc_call(url, "oumv/applyEdit", {
356
+ "path": path,
357
+ "filePath": path,
358
+ "symbol": symbol,
359
+ "replacement": replacement,
360
+ "source": replacement,
361
+ "expectedVersion": expected_version,
362
+ })
363
+ except RuntimeError as e:
364
+ # Out-of-the-box direct fallback when live dev-servers are offline
365
+ if replacement is not None:
366
+ abs_path = os.path.normpath(os.path.join(ws, path))
367
+ # Validate workspace boundary
368
+ if not abs_path.startswith(os.path.abspath(ws)):
369
+ raise RuntimeError(f"[OUMV SECURITY_VIOLATION: -32003] Path traversal blocked: {path}")
370
+
371
+ import hashlib
372
+ current_version = None
373
+ if os.path.isfile(abs_path):
374
+ with open(abs_path, "rb") as f:
375
+ content = f.read()
376
+ current_version = "sha256:" + hashlib.sha256(content).hexdigest()
377
+
378
+ if expected_version and current_version and expected_version != current_version:
379
+ raise RuntimeError(f"[OUMV CONFLICT: -32001] OCC version mismatch: expected {expected_version}, current is {current_version}")
380
+
381
+ os.makedirs(os.path.dirname(abs_path), exist_ok=True)
382
+ with open(abs_path, "w", encoding="utf-8") as f:
383
+ f.write(replacement)
384
+
385
+ new_version = "sha256:" + hashlib.sha256(replacement.encode("utf-8")).hexdigest()
386
+ return {
387
+ "success": True,
388
+ "path": path,
389
+ "symbol": symbol,
390
+ "newVersion": new_version,
391
+ "mode": "OUT_OF_THE_BOX_DIRECT_EDIT",
392
+ "message": "Surgical edit applied directly to workspace file (dev-server offline)",
393
+ }
394
+ raise
270
395
 
271
396
  # 5. Tool: oumv_verify
272
397
  @classmethod
@@ -0,0 +1,355 @@
1
+ """
2
+ TokenSafe OUMV Retrofit Engine.
3
+ Enables existing frontend and backend projects to adopt the OUMV protocol
4
+ incrementally without migrating frameworks or restructuring codebases.
5
+ """
6
+
7
+ import os
8
+ import json
9
+ import time
10
+ from typing import Dict, Any, List, Optional, Tuple
11
+
12
+
13
+ def detect_project_stack(workspace_dir: str) -> Dict[str, Any]:
14
+ """Inspects workspace manifests to detect frontend and backend frameworks."""
15
+ stack: Dict[str, Any] = {
16
+ "workspace": workspace_dir,
17
+ "frontend": None,
18
+ "backend": None,
19
+ "package_managers": [],
20
+ "detected_files": [],
21
+ }
22
+
23
+ # 1. Frontend detection (package.json)
24
+ pkg_json_path = os.path.join(workspace_dir, "package.json")
25
+ if os.path.isfile(pkg_json_path):
26
+ stack["detected_files"].append("package.json")
27
+ try:
28
+ with open(pkg_json_path, "r", encoding="utf-8") as f:
29
+ pkg_data = json.load(f)
30
+ deps = {
31
+ **pkg_data.get("dependencies", {}),
32
+ **pkg_data.get("devDependencies", {}),
33
+ }
34
+
35
+ state_managers = []
36
+ if "zustand" in deps:
37
+ state_managers.append("zustand")
38
+ if "redux" in deps or "@reduxjs/toolkit" in deps:
39
+ state_managers.append("redux")
40
+ if "pinia" in deps:
41
+ state_managers.append("pinia")
42
+ if "jotai" in deps:
43
+ state_managers.append("jotai")
44
+
45
+ fe_info: Dict[str, Any] = {
46
+ "state_managers": state_managers,
47
+ "orm": "prisma" if "@prisma/client" in deps or "prisma" in deps else ("drizzle" if "drizzle-orm" in deps else None),
48
+ }
49
+
50
+ if "next" in deps:
51
+ fe_info.update({"framework": "nextjs", "provider": "react", "adapter": "tokensafe-ui/oumv/react", "version": deps.get("next")})
52
+ elif "react" in deps:
53
+ fe_info.update({"framework": "react", "provider": "react", "adapter": "tokensafe-ui/oumv/react", "version": deps.get("react")})
54
+ elif "vue" in deps:
55
+ fe_info.update({"framework": "vue", "provider": "vue", "adapter": "tokensafe-ui/oumv/vue", "version": deps.get("vue")})
56
+ elif "solid-js" in deps or "@tokensafe-ui/core" in deps:
57
+ fe_info.update({"framework": "solid", "provider": "solid", "adapter": "tokensafe-ui/core", "version": deps.get("solid-js") or deps.get("@tokensafe-ui/core")})
58
+ elif "svelte" in deps:
59
+ fe_info.update({"framework": "svelte", "provider": "svelte", "adapter": "tokensafe-ui/core", "version": deps.get("svelte")})
60
+
61
+ if "framework" in fe_info:
62
+ stack["frontend"] = fe_info
63
+ except Exception:
64
+ pass
65
+
66
+ # Lockfiles
67
+ for lock, pm in [("pnpm-lock.yaml", "pnpm"), ("bun.lockb", "bun"), ("bun.lock", "bun"), ("yarn.lock", "yarn"), ("package-lock.json", "npm")]:
68
+ if os.path.isfile(os.path.join(workspace_dir, lock)):
69
+ stack["package_managers"].append(pm)
70
+ stack["detected_files"].append(lock)
71
+
72
+ # 2. Go Backend detection (go.mod)
73
+ go_mod_path = os.path.join(workspace_dir, "go.mod")
74
+ if not os.path.isfile(go_mod_path) and os.path.isfile(os.path.join(workspace_dir, "go", "go.mod")):
75
+ go_mod_path = os.path.join(workspace_dir, "go", "go.mod")
76
+
77
+ if os.path.isfile(go_mod_path):
78
+ stack["detected_files"].append(os.path.relpath(go_mod_path, workspace_dir))
79
+ stack["package_managers"].append("go")
80
+ framework = "net/http"
81
+ try:
82
+ with open(go_mod_path, "r", encoding="utf-8") as f:
83
+ content = f.read()
84
+ if "github.com/gin-gonic/gin" in content:
85
+ framework = "gin"
86
+ elif "github.com/go-chi/chi" in content:
87
+ framework = "chi"
88
+ elif "github.com/labstack/echo" in content:
89
+ framework = "echo"
90
+ stack["backend"] = {"framework": framework, "provider": "go", "adapter": "tokensafe-backend/go", "language": "go"}
91
+ except Exception:
92
+ stack["backend"] = {"framework": "go", "provider": "go", "adapter": "tokensafe-backend/go", "language": "go"}
93
+
94
+ # 3. Python Backend detection (pyproject.toml, requirements.txt, setup.py)
95
+ py_files = [
96
+ os.path.join(workspace_dir, "pyproject.toml"),
97
+ os.path.join(workspace_dir, "python", "pyproject.toml"),
98
+ os.path.join(workspace_dir, "requirements.txt"),
99
+ ]
100
+ for pf in py_files:
101
+ if os.path.isfile(pf):
102
+ stack["detected_files"].append(os.path.relpath(pf, workspace_dir))
103
+ stack["package_managers"].append("pip/python")
104
+ try:
105
+ with open(pf, "r", encoding="utf-8") as f:
106
+ c = f.read().lower()
107
+ framework = "python"
108
+ if "fastapi" in c:
109
+ framework = "fastapi"
110
+ elif "django" in c:
111
+ framework = "django"
112
+ elif "flask" in c:
113
+ framework = "flask"
114
+ elif "starlette" in c:
115
+ framework = "starlette"
116
+ if not stack["backend"]:
117
+ stack["backend"] = {
118
+ "framework": framework,
119
+ "provider": "fastapi" if framework == "fastapi" else "python",
120
+ "adapter": "tokensafe-backend/python",
121
+ "language": "python",
122
+ }
123
+ except Exception:
124
+ pass
125
+ break
126
+
127
+ return stack
128
+
129
+
130
+ def generate_config(
131
+ workspace_dir: str,
132
+ stack: Optional[Dict[str, Any]] = None,
133
+ dry_run: bool = False,
134
+ force: bool = False,
135
+ ) -> Tuple[Dict[str, Any], str, bool]:
136
+ """
137
+ Generates non-destructive, idempotent .tokensafe/oumv.json manifest.
138
+ Default mutation policy is enabled out-of-the-box (mutate: true).
139
+ """
140
+ detected = stack or detect_project_stack(workspace_dir)
141
+ target_dir = os.path.join(workspace_dir, ".tokensafe")
142
+ target_file = os.path.join(target_dir, "oumv.json")
143
+
144
+ profiles = []
145
+ adapters: Dict[str, Any] = {}
146
+
147
+ if detected.get("frontend"):
148
+ fe = detected["frontend"]
149
+ profiles.append("frontend")
150
+ adapters["frontend"] = {
151
+ "provider": fe.get("provider", "react"),
152
+ "framework": fe.get("framework", "react"),
153
+ "mode": "hybrid",
154
+ }
155
+
156
+ if detected.get("backend"):
157
+ be = detected["backend"]
158
+ profiles.append("backend")
159
+ adapters["backend"] = {
160
+ "provider": be.get("provider", "go"),
161
+ "framework": be.get("framework", "go"),
162
+ "mode": "hybrid",
163
+ }
164
+
165
+ project_name = os.path.basename(os.path.abspath(workspace_dir))
166
+ config: Dict[str, Any] = {
167
+ "version": 1,
168
+ "project": {
169
+ "name": project_name,
170
+ },
171
+ "oumv": {
172
+ "enabled": True,
173
+ "profiles": profiles or ["frontend", "backend"],
174
+ },
175
+ "adapters": adapters,
176
+ "permissions": {
177
+ "observe": True,
178
+ "mutate": True,
179
+ "productionRuntime": False,
180
+ },
181
+ }
182
+
183
+ if os.path.isfile(target_file) and not force:
184
+ try:
185
+ with open(target_file, "r", encoding="utf-8") as f:
186
+ existing = json.load(f)
187
+ return existing, target_file, False
188
+ except Exception:
189
+ pass
190
+
191
+ if not dry_run:
192
+ os.makedirs(target_dir, exist_ok=True)
193
+ with open(target_file, "w", encoding="utf-8") as f:
194
+ json.dump(config, f, indent=2)
195
+
196
+ return config, target_file, True
197
+
198
+
199
+ def get_adapters_catalog() -> List[Dict[str, Any]]:
200
+ """Lists available OUMV adapters in the consolidated architecture."""
201
+ return [
202
+ {
203
+ "id": "frontend/react",
204
+ "name": "React Adapter (Zustand, Redux, Context, useReducer)",
205
+ "profile": "frontend",
206
+ "repo": "tokensafe-ui",
207
+ "mode": "hybrid",
208
+ "status": "ready",
209
+ "description": "Progressive AST component discovery + runtime action/state inspection",
210
+ },
211
+ {
212
+ "id": "frontend/solid",
213
+ "name": "SolidJS / TokenSafe UI Native Adapter",
214
+ "profile": "frontend",
215
+ "repo": "tokensafe-ui",
216
+ "mode": "hybrid",
217
+ "status": "ready",
218
+ "description": "Fine-grained reactive signals causality + virtual DOM observer",
219
+ },
220
+ {
221
+ "id": "frontend/vue",
222
+ "name": "Vue 3 Adapter (Composition API, Pinia)",
223
+ "profile": "frontend",
224
+ "repo": "tokensafe-ui",
225
+ "mode": "hybrid",
226
+ "status": "ready",
227
+ "description": "Vue component hierarchy and store snapshot observer",
228
+ },
229
+ {
230
+ "id": "backend/go",
231
+ "name": "Go Backend Adapter (Gin, Chi, net/http)",
232
+ "profile": "backend",
233
+ "repo": "tokensafe-backend/go",
234
+ "mode": "hybrid",
235
+ "status": "ready",
236
+ "description": "Go AST pre-flight compiler guard + transactional DB sandbox with rollback",
237
+ },
238
+ {
239
+ "id": "backend/fastapi",
240
+ "name": "Python FastAPI Adapter (Starlette, Pydantic)",
241
+ "profile": "backend",
242
+ "repo": "tokensafe-backend/python",
243
+ "mode": "hybrid",
244
+ "status": "ready",
245
+ "description": "FastAPI automatic route & schema introspection + SQLAlchemy dry-run sandbox",
246
+ },
247
+ {
248
+ "id": "backend/node",
249
+ "name": "Node.js Backend Adapter (Express, Fastify)",
250
+ "profile": "backend",
251
+ "repo": "tokensafe-backend/node",
252
+ "mode": "hybrid",
253
+ "status": "planned",
254
+ "description": "Express/Fastify route handler & middleware reflection",
255
+ },
256
+ ]
257
+
258
+
259
+ def run_doctor(workspace_dir: str) -> Dict[str, Any]:
260
+ """Diagnostics check for OUMV configuration, ports, lockfiles, and permissions."""
261
+ stack = detect_project_stack(workspace_dir)
262
+ conf_path = os.path.join(workspace_dir, ".tokensafe", "oumv.json")
263
+ runtime_path = os.path.join(workspace_dir, ".tokensafe", "runtime.json")
264
+
265
+ has_config = os.path.isfile(conf_path)
266
+ config_data: Dict[str, Any] = {}
267
+ if has_config:
268
+ try:
269
+ with open(conf_path, "r", encoding="utf-8") as f:
270
+ config_data = json.load(f)
271
+ except Exception:
272
+ pass
273
+
274
+ has_runtime = os.path.isfile(runtime_path)
275
+ runtime_data: Dict[str, Any] = {}
276
+ if has_runtime:
277
+ try:
278
+ with open(runtime_path, "r", encoding="utf-8") as f:
279
+ runtime_data = json.load(f)
280
+ except Exception:
281
+ pass
282
+
283
+ return {
284
+ "workspace": workspace_dir,
285
+ "detected_stack": stack,
286
+ "config_present": has_config,
287
+ "config": config_data,
288
+ "runtime_beacon_present": has_runtime,
289
+ "runtime_beacon": runtime_data,
290
+ "permissions": config_data.get("permissions", {"observe": True, "mutate": False}),
291
+ "ready_for_agent": True,
292
+ }
293
+
294
+
295
+ class OUMVProjectContext:
296
+ """
297
+ Automatic out-of-the-box OUMV Project Context & Adapter Resolver.
298
+ Inspects project manifests, resolves active adapters (frontend & backend),
299
+ and provisions runtime or static AST inspection seamlessly.
300
+ """
301
+ _cache: Dict[str, "OUMVProjectContext"] = {}
302
+ _last_checked: float = 0.0
303
+
304
+ def __init__(self, workspace_dir: str):
305
+ self.workspace_dir = os.path.abspath(workspace_dir)
306
+ self.stack = detect_project_stack(self.workspace_dir)
307
+ self.active_adapters = self._resolve_adapters()
308
+
309
+ @classmethod
310
+ def get_for_workspace(cls, workspace_dir: Optional[str] = None) -> "OUMVProjectContext":
311
+ from src.paths import get_active_workspace
312
+ ws = os.path.abspath(workspace_dir or get_active_workspace())
313
+ now = time.time()
314
+ if ws not in cls._cache or (now - cls._last_checked > 10.0):
315
+ cls._cache[ws] = cls(ws)
316
+ cls._last_checked = now
317
+ return cls._cache[ws]
318
+
319
+ def _resolve_adapters(self) -> Dict[str, Any]:
320
+ adapters: Dict[str, Any] = {}
321
+ fe = self.stack.get("frontend")
322
+ if fe:
323
+ adapters["frontend"] = {
324
+ "name": f"{fe.get('framework', 'React').title()} Adapter",
325
+ "profile": "frontend",
326
+ "repo": "tokensafe-ui",
327
+ "adapter": fe.get("adapter", "tokensafe-ui/oumv/react"),
328
+ "state_managers": fe.get("state_managers", []),
329
+ "orm": fe.get("orm"),
330
+ "mode": "hybrid",
331
+ }
332
+
333
+ be = self.stack.get("backend")
334
+ if be:
335
+ adapters["backend"] = {
336
+ "name": f"{be.get('framework', 'Backend').title()} Adapter",
337
+ "profile": "backend",
338
+ "repo": "tokensafe-backend",
339
+ "adapter": be.get("adapter", "tokensafe-backend"),
340
+ "language": be.get("language"),
341
+ "mode": "hybrid",
342
+ }
343
+ return adapters
344
+
345
+ def resolve_target_runtime(self, target: Optional[str] = None) -> str:
346
+ """Determines whether a target belongs to the frontend or backend profile."""
347
+ if not target:
348
+ return "auto"
349
+ # Backend hints
350
+ if any(target.startswith(m) for m in ["GET ", "POST ", "PUT ", "DELETE ", "PATCH "]) or "/api/" in target or target.startswith("/"):
351
+ return "backend"
352
+ # Frontend hints
353
+ if any(target.startswith(c) for c in ["#", ".", "[", "button", "input"]) or target.startswith("<") or target.endswith(".tsx") or target.endswith(".jsx"):
354
+ return "frontend"
355
+ return "auto"
@@ -241,7 +241,7 @@ class TelemetrySync:
241
241
  current_last_id = last_id
242
242
  headers = {
243
243
  "Content-Type": "application/json",
244
- "User-Agent": "TokenSafe-Sync/4.4.6"
244
+ "User-Agent": "TokenSafe-Sync/4.4.9"
245
245
  }
246
246
  if active_key:
247
247
  headers["Authorization"] = f"Bearer {active_key}"