tokensafe 4.4.7 → 4.5.0

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,27 +256,70 @@ 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
233
295
  def understand(cls, query: str = "causality", target: Optional[str] = None, runtime: str = "auto") -> Any:
234
296
  fe, be = cls.get_endpoints()
235
297
 
298
+ from src.graph_engine import GraphEngine
299
+ ws = get_active_workspace()
300
+ graph = GraphEngine.get_instance(ws)
301
+
302
+ # Impact analysis: static cross-stack graph as the backbone, runtime answers attached when online
303
+ if query == "impact":
304
+ report: Dict[str, Any] = {
305
+ "query": "impact",
306
+ "target": target,
307
+ "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
308
+ }
309
+ report.update(graph.get_static_impact(target or ""))
310
+ if target:
311
+ if fe:
312
+ try:
313
+ report["frontendImpact"] = cls._rpc_call(fe["url"], "oumv/understand", {"query": "impact", "target": target, "componentId": target})
314
+ except Exception as e:
315
+ report["frontendError"] = str(e)
316
+ if be:
317
+ try:
318
+ report["backendImpact"] = cls._rpc_call(be["url"], "oumv/understand", {"query": "impact", "target": target})
319
+ except Exception as e:
320
+ report["backendError"] = str(e)
321
+ return report
322
+
236
323
  # Cross-layer causality query
237
324
  if query == "causality" and runtime in ("auto", ""):
238
325
  report = {
@@ -250,23 +337,135 @@ class OUMVGateway:
250
337
  report["frontendCausality"] = cls._rpc_call(fe["url"], "oumv/understand", {"query": query, "target": target, "componentId": target})
251
338
  except Exception as e:
252
339
  report["frontendError"] = str(e)
340
+
341
+ # Unified cross-stack relationships (frontend call -> backend endpoint), available online and offline
342
+ cross = cls._static_cross_stack(graph, target)
343
+ if cross["edges"]:
344
+ report["crossStack"] = cross
345
+
346
+ # Out-of-the-box static fallback if neither is online
347
+ if not be and not fe:
348
+ report["staticAnalysis"] = graph.get_static_oumv_slice(level="L1", target=target)
349
+ report["evidence"] = {"provenance": "static", "confidence": "confirmed", "sourceAdapter": "tokensafe-graph-engine"}
350
+
253
351
  return report
254
352
 
255
- url = cls._resolve_client_url(runtime=runtime, target=target)
256
- return cls._rpc_call(url, "oumv/understand", {"query": query, "target": target, "componentId": target})
353
+ try:
354
+ url = cls._resolve_client_url(runtime=runtime, target=target)
355
+ return cls._rpc_call(url, "oumv/understand", {"query": query, "target": target, "componentId": target})
356
+ except RuntimeError:
357
+ if query == "impact":
358
+ return graph.get_static_impact(target or "")
359
+ return graph.get_static_oumv_slice(level="L1", target=target)
360
+
361
+ @staticmethod
362
+ def _static_cross_stack(graph: Any, target: Optional[str]) -> Dict[str, Any]:
363
+ """Cross-stack edges (frontend API call -> backend endpoint) from the static graph."""
364
+ evidence = {"provenance": "static", "sourceAdapter": "tokensafe-graph-engine", "confidence": "probable"}
365
+ edges: List[Dict[str, Any]] = []
366
+ for link in getattr(graph, "api_links", []):
367
+ if target:
368
+ t = target.lower()
369
+ hay = " ".join([
370
+ link["source"].get("route") or "", link["source"].get("file") or "",
371
+ link["target"].get("route") or "", link["target"].get("file") or "",
372
+ ]).lower()
373
+ if t not in hay:
374
+ continue
375
+ edges.append({
376
+ "source": link["source"],
377
+ "target": link["target"],
378
+ "evidence": evidence,
379
+ })
380
+ return {"edges": edges[:30], "count": len(edges), "evidence": evidence}
257
381
 
258
382
  # 4. Tool: oumv_mutate
259
383
  @classmethod
260
384
  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
- })
385
+ # Check workspace permissions (enabled by default out-of-the-box unless explicitly opted out)
386
+ ws = get_active_workspace()
387
+ cfg_file = os.path.join(ws, ".tokensafe", "oumv.json")
388
+ if os.path.isfile(cfg_file):
389
+ try:
390
+ with open(cfg_file, "r", encoding="utf-8") as f:
391
+ cfg = json.load(f)
392
+ perms = cfg.get("permissions", {})
393
+ if perms.get("mutate") is False:
394
+ raise RuntimeError("[OUMV PERMISSION_DENIED: -32007] Workspace policy explicitly prohibits mutations (.tokensafe/oumv.json: permissions.mutate=false).")
395
+ except RuntimeError:
396
+ raise
397
+ except Exception:
398
+ pass
399
+
400
+ try:
401
+ url = cls._resolve_client_url(runtime=runtime, target=path)
402
+ return cls._rpc_call(url, "oumv/applyEdit", {
403
+ "path": path,
404
+ "filePath": path,
405
+ "symbol": symbol,
406
+ "replacement": replacement,
407
+ "source": replacement,
408
+ "expectedVersion": expected_version,
409
+ })
410
+ except RuntimeError as e:
411
+ # Out-of-the-box direct fallback when live dev-servers are offline
412
+ if replacement is not None:
413
+ abs_path = os.path.normpath(os.path.join(ws, path))
414
+ # Validate workspace boundary
415
+ if not abs_path.startswith(os.path.abspath(ws)):
416
+ raise RuntimeError(f"[OUMV SECURITY_VIOLATION: -32003] Path traversal blocked: {path}")
417
+
418
+ import hashlib
419
+ current_version = None
420
+ if os.path.isfile(abs_path):
421
+ with open(abs_path, "rb") as f:
422
+ content = f.read()
423
+ current_version = "sha256:" + hashlib.sha256(content).hexdigest()
424
+
425
+ if expected_version and current_version and expected_version != current_version:
426
+ raise RuntimeError(f"[OUMV CONFLICT: -32001] OCC version mismatch: expected {expected_version}, current is {current_version}")
427
+
428
+ # Syntax pre-flight: never persist syntactically broken code (OUMV spec §8 Mutation Policy)
429
+ from src.syntax_guard import check_syntax
430
+ syntax_check = check_syntax(abs_path, replacement)
431
+ if syntax_check.get("status") == "failed":
432
+ raise RuntimeError(
433
+ f"[OUMV SYNTAX_ERROR: -32002] Edit rejected by syntax guard "
434
+ f"({syntax_check.get('tool')}): {syntax_check.get('error')}"
435
+ )
436
+
437
+ # Automatic backup of previous content before overwriting
438
+ backup_path = None
439
+ if current_version is not None:
440
+ try:
441
+ backup_dir = os.path.join(ws, ".tokensafe", "backups")
442
+ os.makedirs(backup_dir, exist_ok=True)
443
+ digest = hashlib.sha256(content).hexdigest()[:8]
444
+ backup_path = os.path.join(backup_dir, f"{digest}_{os.path.basename(abs_path)}.bak")
445
+ with open(backup_path, "wb") as f:
446
+ f.write(content)
447
+ except Exception:
448
+ backup_path = None
449
+
450
+ os.makedirs(os.path.dirname(abs_path), exist_ok=True)
451
+ with open(abs_path, "w", encoding="utf-8") as f:
452
+ f.write(replacement)
453
+
454
+ new_version = "sha256:" + hashlib.sha256(replacement.encode("utf-8")).hexdigest()
455
+ result = {
456
+ "success": True,
457
+ "path": path,
458
+ "symbol": symbol,
459
+ "newVersion": new_version,
460
+ "mode": "OUT_OF_THE_BOX_DIRECT_EDIT",
461
+ "syntaxCheck": syntax_check,
462
+ "message": "Surgical edit applied directly to workspace file (dev-server offline)",
463
+ }
464
+ if backup_path:
465
+ result["backupPath"] = backup_path
466
+ result["rollbackHint"] = f"Previous content backed up at {backup_path}"
467
+ return result
468
+ raise
270
469
 
271
470
  # 5. Tool: oumv_verify
272
471
  @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"