tokensafe 5.0.1 → 5.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.codex-plugin/plugin.json +1 -1
  4. package/assets/logo.svg +1 -13
  5. package/hooks/claude_code_hook.py +5 -1
  6. package/hooks/cursor_hook.py +1 -1
  7. package/kimi.plugin.json +3 -2
  8. package/package.json +1 -1
  9. package/plugin.json +1 -1
  10. package/rules/AGENTS.md +4 -3
  11. package/server.json +3 -3
  12. package/skills/oumv-protocol/SKILL.md +59 -0
  13. package/skills/token-optimizer/SKILL.md +5 -3
  14. package/skills/token-optimizer/references/mcp-tools.md +1 -1
  15. package/tokensafe/adapter_core.py +62 -18
  16. package/tokensafe/atomic_io.py +20 -16
  17. package/tokensafe/auto_inject.py +2 -2
  18. package/tokensafe/backend_release.py +3 -3
  19. package/tokensafe/batch_editor.py +299 -10
  20. package/tokensafe/batch_search.py +53 -0
  21. package/tokensafe/bounded_flock.py +60 -0
  22. package/tokensafe/burn_monitor.py +60 -2
  23. package/tokensafe/call_context.py +158 -0
  24. package/tokensafe/cli.py +41 -13
  25. package/tokensafe/compactor.py +87 -5
  26. package/tokensafe/context_index.py +3 -0
  27. package/tokensafe/dashboard.py +119 -43
  28. package/tokensafe/environment_auditor.py +30 -2
  29. package/tokensafe/fts_index.py +3 -0
  30. package/tokensafe/graph_engine.py +246 -29
  31. package/tokensafe/installer.py +72 -13
  32. package/tokensafe/loop_detector.py +8 -20
  33. package/tokensafe/mcp_server.py +1078 -186
  34. package/tokensafe/metrics.py +173 -46
  35. package/tokensafe/oumv_brief.py +144 -8
  36. package/tokensafe/oumv_gateway.py +689 -222
  37. package/tokensafe/oumv_home.py +259 -0
  38. package/tokensafe/oumv_policy.py +64 -1
  39. package/tokensafe/proc_run.py +162 -0
  40. package/tokensafe/proxy.py +78 -8
  41. package/tokensafe/retrofit.py +484 -82
  42. package/tokensafe/route_index.py +2 -0
  43. package/tokensafe/savings.py +10 -2
  44. package/tokensafe/scoped_search.py +77 -0
  45. package/tokensafe/session_brief.py +17 -2
  46. package/tokensafe/stack_summary.py +73 -0
  47. package/tokensafe/syntax_guard.py +8 -2
  48. package/tokensafe/telemetry_sync.py +1 -1
  49. package/tokensafe/version_checker.py +1 -1
  50. package/tokensafe/web_reader.py +53 -4
  51. package/tokensafe/workspace_roots.py +127 -9
  52. package/assets/social/linkedin_banner.png +0 -0
  53. package/assets/social/tokensafe_logo_square.png +0 -0
@@ -7,6 +7,7 @@ incrementally without migrating frameworks or restructuring codebases.
7
7
  import glob
8
8
  import os
9
9
  import json
10
+ import re
10
11
  import time
11
12
  from pathlib import Path
12
13
  from typing import Dict, Any, List, Optional, Tuple
@@ -20,6 +21,28 @@ _FRONTEND_SOURCE_DIRS = frozenset({
20
21
  "views", "stores", "store", "utils", "layouts", "router", "routes", "api",
21
22
  })
22
23
 
24
+ # Manifest fields that make a package a publishable library (an import target),
25
+ # not an app with a page to observe. `main` alone is not one: Electron and Expo
26
+ # apps declare it too.
27
+ _LIBRARY_ENTRY_FIELDS = ("exports", "module", "types", "typings", "bin")
28
+ # Files that mark a directory as a runnable UI app (a page a dev server serves).
29
+ _APP_ENTRY_FILES = (
30
+ "index.html", "public/index.html", "src/index.html", "angular.json",
31
+ "vite.config.ts", "vite.config.js", "vite.config.mts", "vite.config.mjs", "vite.config.cjs",
32
+ "next.config.js", "next.config.mjs", "next.config.ts",
33
+ "nuxt.config.ts", "nuxt.config.js", "svelte.config.js", "astro.config.mjs",
34
+ "app.config.ts", "app.config.js",
35
+ )
36
+
37
+
38
+ def _is_library_package(pkg_data: Dict[str, Any], pkg_dir: str) -> bool:
39
+ """True for a package that ships code to import (exports/types/bin) and has
40
+ no app entry of its own. A UI framework in its deps is then what it builds
41
+ against (tests, peer typing), not a page OUMV can attach to."""
42
+ if not any(pkg_data.get(field) for field in _LIBRARY_ENTRY_FIELDS):
43
+ return False
44
+ return not any(os.path.isfile(os.path.join(pkg_dir, rel)) for rel in _APP_ENTRY_FILES)
45
+
23
46
 
24
47
  def _detect_package_json_entry(pkg_json_path: str, rel_dir: str = ".") -> Tuple[Optional[Dict[str, Any]], Optional[Dict[str, Any]], List[str]]:
25
48
  """Inspects a single package.json for frontend or Node.js backend stack."""
@@ -29,9 +52,12 @@ def _detect_package_json_entry(pkg_json_path: str, rel_dir: str = ".") -> Tuple[
29
52
  try:
30
53
  with open(pkg_json_path, "r", encoding="utf-8") as f:
31
54
  pkg_data = json.load(f)
55
+ # Only this package's own manifest decides its stack: nothing is
56
+ # inherited from the workspace root or guessed from internal packages.
32
57
  deps = {
33
- **pkg_data.get("dependencies", {}),
34
- **pkg_data.get("devDependencies", {}),
58
+ **(pkg_data.get("peerDependencies") or {}),
59
+ **(pkg_data.get("devDependencies") or {}),
60
+ **(pkg_data.get("dependencies") or {}),
35
61
  }
36
62
 
37
63
  state_managers = []
@@ -70,7 +96,9 @@ def _detect_package_json_entry(pkg_json_path: str, rel_dir: str = ".") -> Tuple[
70
96
  fe_info.update({"framework": "react", "provider": "react", "adapter": "tokensafe-ui/oumv/react", "version": deps.get("react"), "oumv_supported": has_vite, "status": "ready" if has_vite else "needs-vite"})
71
97
  elif "vue" in deps:
72
98
  fe_info.update({"framework": "vue", "provider": "vue", "adapter": "tokensafe-ui/oumv/vue", "version": deps.get("vue"), "oumv_supported": has_vite, "status": "ready" if has_vite else "needs-vite"})
73
- elif "solid-js" in deps or "@tokensafe-ui/core" in deps:
99
+ elif "solid-js" in deps:
100
+ # `@tokensafe-ui/core` is NOT a Solid marker: the monorepo's MCP,
101
+ # observer and oumv packages depend on it and have no UI at all.
74
102
  # Solid has no DOM-attached component registry: the bridge reads the dev
75
103
  # build's owner tree (DEV.hooks.afterCreateOwner), so it needs a Vite dev
76
104
  # server like React/Vue do.
@@ -78,7 +106,7 @@ def _detect_package_json_entry(pkg_json_path: str, rel_dir: str = ".") -> Tuple[
78
106
  "framework": "solid",
79
107
  "provider": "solid",
80
108
  "adapter": "tokensafe-ui/solid",
81
- "version": deps.get("solid-js") or deps.get("@tokensafe-ui/core"),
109
+ "version": deps.get("solid-js"),
82
110
  "oumv_supported": has_vite,
83
111
  "status": "ready" if has_vite else "needs-vite",
84
112
  "note": "component discovery uses the Solid dev build's owner tree; the in-page bridge is the shared bridge-core generator",
@@ -101,6 +129,11 @@ def _detect_package_json_entry(pkg_json_path: str, rel_dir: str = ".") -> Tuple[
101
129
  "note": "requires the Vite dev server with @analogjs/vite-plugin-angular 3.x (Angular 20+); discovery reads the Angular dev build's window.ng, and the Angular CLI dev server (ng serve / @angular/build) is out of scope",
102
130
  })
103
131
 
132
+ pkg_dir = os.path.dirname(pkg_json_path)
133
+ if "framework" in fe_info and fe_info.get("provider") != "node" and _is_library_package(pkg_data, pkg_dir):
134
+ # A component/tooling library: React/Solid in its deps is what it
135
+ # builds or tests against, not a page a dev server serves.
136
+ fe_info.update({"role": "library", "oumv_supported": False, "status": "library"})
104
137
  if "framework" in fe_info:
105
138
  fe_out = fe_info
106
139
 
@@ -123,7 +156,6 @@ def _detect_package_json_entry(pkg_json_path: str, rel_dir: str = ".") -> Tuple[
123
156
  # all. They used to vanish from `packages` even though their manifest was
124
157
  # listed in `detected_files`, so a monorepo looked fully covered when 4 of
125
158
  # its 6 packages had no OUMV adapter.
126
- pkg_dir = os.path.dirname(pkg_json_path)
127
159
  bun_marker = (
128
160
  any(key in deps for key in ("@types/bun", "bun-types", "elysia"))
129
161
  or os.path.isfile(os.path.join(pkg_dir, "bun.lockb"))
@@ -231,7 +263,18 @@ def detect_project_stack(workspace_dir: str) -> Dict[str, Any]:
231
263
  for manager in pkg_managers:
232
264
  if manager not in stack["package_managers"]:
233
265
  stack["package_managers"].append(manager)
234
- if fe_info:
266
+ if fe_info and fe_info.get("role") == "library":
267
+ _add_package({
268
+ "role": "library",
269
+ "path": rel,
270
+ "framework": fe_info["framework"],
271
+ "provider": fe_info["provider"],
272
+ "adapter": None,
273
+ "oumvSupported": False,
274
+ "status": "library",
275
+ "reason": "publishable library (exports/types/bin, no app entry): no page to observe",
276
+ })
277
+ elif fe_info:
235
278
  if not stack["frontend"]:
236
279
  stack["frontend"] = fe_info
237
280
  _add_package({
@@ -984,65 +1027,391 @@ def get_adapters_catalog() -> List[Dict[str, Any]]:
984
1027
  ]
985
1028
 
986
1029
 
987
- def _adapter_presence(workspace_dir: str, profile: str, provider: str, framework: str) -> Dict[str, Any]:
1030
+ _NODE_ADAPTER_PACKAGE = "tokensafe-backend-node"
1031
+ _UI_ADAPTER_PACKAGE = "tokensafe-ui"
1032
+ _PYTHON_ADAPTER_DIST = "tokensafe-backend-python"
1033
+ _PYTHON_ADAPTER_MODULE = "tokensafe_python"
1034
+ _PYTHON_INSTALL_HINT = (
1035
+ 'pip install "tokensafe-backend-python @ '
1036
+ 'git+https://github.com/tokensafe-dev/tokensafe-backend.git#subdirectory=python"'
1037
+ )
1038
+ _NODE_PROVIDERS = ("node", "elysia", "bun")
1039
+ _PYTHON_PROVIDERS = ("fastapi", "python")
1040
+ _SIDECAR_PROVIDERS = ("spring", "php")
1041
+
1042
+
1043
+ def _entry_dir(workspace_dir: str, entry: Dict[str, Any]) -> str:
1044
+ root = entry.get("root") or "."
1045
+ return os.path.normpath(os.path.join(os.path.abspath(workspace_dir), root))
1046
+
1047
+
1048
+ def _rel_to(workspace_dir: str, path: str) -> str:
1049
+ try:
1050
+ return os.path.relpath(path, os.path.abspath(workspace_dir)).replace("\\", "/")
1051
+ except ValueError:
1052
+ return path
1053
+
1054
+
1055
+ def _display_path(workspace_dir: str, path: str) -> str:
1056
+ """Workspace-relative when inside the workspace, absolute otherwise."""
1057
+ rel = _rel_to(workspace_dir, path)
1058
+ return path if rel.startswith("..") else rel
1059
+
1060
+
1061
+ def _npm_presence(workspace_dir: str, pkg_dir: str, package: str, install_hint: str) -> Dict[str, Any]:
1062
+ """`node_modules/<package>` resolved the way Node does (walking up, so a
1063
+ hoisted monorepo install counts), else a declaration in the package.json."""
1064
+ curr = os.path.abspath(pkg_dir)
1065
+ while True:
1066
+ candidate = os.path.join(curr, "node_modules", package, "package.json")
1067
+ if os.path.isfile(candidate):
1068
+ return {"installed": True, "evidence": f"{_rel_to(workspace_dir, os.path.dirname(candidate))} installed"}
1069
+ parent = os.path.dirname(curr)
1070
+ if parent == curr:
1071
+ break
1072
+ curr = parent
1073
+ manifest = os.path.join(pkg_dir, "package.json")
1074
+ try:
1075
+ with open(manifest, "r", encoding="utf-8") as fh:
1076
+ data = json.load(fh)
1077
+ for field in ("dependencies", "devDependencies"):
1078
+ if isinstance(data.get(field), dict) and package in data[field]:
1079
+ return {
1080
+ "installed": True,
1081
+ "evidence": f"{_rel_to(workspace_dir, manifest)} declares {package} in {field} "
1082
+ f"(node_modules/{package} not found yet: run the package manager's install)",
1083
+ }
1084
+ except Exception:
1085
+ pass
1086
+ return {"installed": False, "evidence": f"node_modules/{package} missing (run: {install_hint})"}
1087
+
1088
+
1089
+ def _normalize_dist_name(name: str) -> str:
1090
+ return re.sub(r"[-_.]+", "-", name).lower()
1091
+
1092
+
1093
+ def _is_python_adapter_requirement(spec: str) -> bool:
1094
+ """A PEP 508 / pip requirement naming the TokenSafe Python adapter."""
1095
+ text = spec.strip()
1096
+ if not text or text.startswith("#"):
1097
+ return False
1098
+ if " #" in text:
1099
+ text = text.split(" #", 1)[0].strip()
1100
+ lowered = text.lower()
1101
+ if "tokensafe-backend" in lowered and "subdirectory=python" in lowered and (
1102
+ "git+" in lowered or "://" in lowered
1103
+ ):
1104
+ return True
1105
+ match = re.match(r"^([A-Za-z0-9][A-Za-z0-9._-]*)", text)
1106
+ return bool(match and _normalize_dist_name(match.group(1)) == _PYTHON_ADAPTER_DIST)
1107
+
1108
+
1109
+ def _pyproject_requirements(path: str) -> List[str]:
1110
+ """Dependency strings of a pyproject (PEP 621, dependency groups, Poetry)."""
1111
+ with open(path, "rb") as fh:
1112
+ raw = fh.read()
1113
+ try:
1114
+ import tomllib # Python 3.11+
1115
+ data = tomllib.loads(raw.decode("utf-8", errors="replace"))
1116
+ except Exception:
1117
+ # No TOML parser (or a broken file): every quoted string is a candidate.
1118
+ found = re.findall(r"\"([^\"\n]+)\"|'([^'\n]+)'", raw.decode("utf-8", errors="replace"))
1119
+ return [a or b for a, b in found]
1120
+ out: List[str] = []
1121
+ project = data.get("project") if isinstance(data.get("project"), dict) else {}
1122
+ out.extend(str(d) for d in project.get("dependencies") or [] if isinstance(d, str))
1123
+ for group in (project.get("optional-dependencies") or {}).values():
1124
+ out.extend(str(d) for d in group or [] if isinstance(d, str))
1125
+ for group in (data.get("dependency-groups") or {}).values():
1126
+ out.extend(str(d) for d in group or [] if isinstance(d, str))
1127
+ poetry = ((data.get("tool") or {}).get("poetry") or {})
1128
+ poetry_tables = [poetry.get("dependencies"), poetry.get("dev-dependencies")]
1129
+ poetry_tables.extend((g or {}).get("dependencies") for g in (poetry.get("group") or {}).values() if isinstance(g, dict))
1130
+ for table in poetry_tables:
1131
+ if not isinstance(table, dict):
1132
+ continue
1133
+ for name, value in table.items():
1134
+ if isinstance(value, dict) and value.get("git"):
1135
+ out.append(f"{name} @ git+{value['git']}#subdirectory={value.get('subdirectory', '')}")
1136
+ else:
1137
+ out.append(str(name))
1138
+ return out
1139
+
1140
+
1141
+ def _python_declared(workspace_dir: str, pkg_dir: str) -> Optional[str]:
1142
+ for name in ("requirements.txt", "requirements-dev.txt", "pyproject.toml"):
1143
+ path = os.path.join(pkg_dir, name)
1144
+ if not os.path.isfile(path):
1145
+ continue
1146
+ try:
1147
+ if name.endswith(".toml"):
1148
+ specs = _pyproject_requirements(path)
1149
+ else:
1150
+ with open(path, "r", encoding="utf-8", errors="replace") as fh:
1151
+ specs = fh.read().splitlines()
1152
+ except Exception:
1153
+ continue
1154
+ if any(_is_python_adapter_requirement(spec) for spec in specs):
1155
+ return f"{_rel_to(workspace_dir, path)} declares {_PYTHON_ADAPTER_DIST}"
1156
+ return None
1157
+
1158
+
1159
+ def _project_interpreter(workspace_dir: str, pkg_dir: str) -> Optional[str]:
1160
+ """The project's own Python: a local venv first, then $VIRTUAL_ENV."""
1161
+ bins = (os.path.join("bin", "python"), os.path.join("Scripts", "python.exe"))
1162
+ roots: List[str] = []
1163
+ for base in (pkg_dir, os.path.abspath(workspace_dir)):
1164
+ for venv in (".venv", "venv"):
1165
+ roots.append(os.path.join(base, venv))
1166
+ if os.environ.get("VIRTUAL_ENV"):
1167
+ roots.append(os.environ["VIRTUAL_ENV"])
1168
+ for root in roots:
1169
+ for rel in bins:
1170
+ candidate = os.path.join(root, rel)
1171
+ if os.path.isfile(candidate) and os.access(candidate, os.X_OK):
1172
+ return candidate
1173
+ return None
1174
+
1175
+
1176
+ def _interpreter_can_import(python: str, module: str, timeout: float = 3.0) -> Optional[bool]:
1177
+ """True/False from a `find_spec` probe in `python`; None if the probe failed."""
1178
+ import subprocess
1179
+ code = (
1180
+ "import importlib.util, sys; "
1181
+ f"sys.exit(0 if importlib.util.find_spec({module!r}) else 3)"
1182
+ )
1183
+ try:
1184
+ proc = subprocess.run(
1185
+ [python, "-c", code],
1186
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
1187
+ timeout=timeout, check=False,
1188
+ )
1189
+ except Exception:
1190
+ return None
1191
+ if proc.returncode == 0:
1192
+ return True
1193
+ if proc.returncode == 3:
1194
+ return False
1195
+ return None
1196
+
1197
+
1198
+ def _tokensafe_interpreter_can_import(module: str) -> bool:
1199
+ try:
1200
+ import importlib.util
1201
+ return importlib.util.find_spec(module) is not None
1202
+ except Exception:
1203
+ return False
1204
+
1205
+
1206
+ def _python_presence(workspace_dir: str, pkg_dir: str) -> Dict[str, Any]:
1207
+ declared = _python_declared(workspace_dir, pkg_dir)
1208
+ if declared:
1209
+ return {"installed": True, "evidence": declared}
1210
+ python = _project_interpreter(workspace_dir, pkg_dir)
1211
+ if python:
1212
+ found = _interpreter_can_import(python, _PYTHON_ADAPTER_MODULE)
1213
+ shown = _display_path(workspace_dir, python)
1214
+ if found:
1215
+ return {"installed": True, "evidence": f"{_PYTHON_ADAPTER_MODULE} importable in the project interpreter {shown}"}
1216
+ if found is False:
1217
+ return {
1218
+ "installed": False,
1219
+ "evidence": f"{_PYTHON_ADAPTER_MODULE} not importable in the project interpreter {shown} "
1220
+ f"and not declared (run: {_PYTHON_INSTALL_HINT})",
1221
+ }
1222
+ if _tokensafe_interpreter_can_import(_PYTHON_ADAPTER_MODULE):
1223
+ return {
1224
+ "installed": True,
1225
+ "evidence": f"{_PYTHON_ADAPTER_MODULE} importable in TokenSafe's own interpreter only "
1226
+ "(fallback: no project interpreter found; the app's may differ)",
1227
+ }
1228
+ return {
1229
+ "installed": False,
1230
+ "evidence": f"{_PYTHON_ADAPTER_DIST} not declared and no project interpreter can import "
1231
+ f"{_PYTHON_ADAPTER_MODULE} (run: {_PYTHON_INSTALL_HINT})",
1232
+ }
1233
+
1234
+
1235
+ def _go_presence(workspace_dir: str, pkg_dir: str) -> Dict[str, Any]:
1236
+ ws = os.path.abspath(workspace_dir)
1237
+ candidates = [os.path.join(pkg_dir, "go.mod"), os.path.join(ws, "go.mod"), os.path.join(ws, "go", "go.mod")]
1238
+ seen = set()
1239
+ for path in candidates:
1240
+ if path in seen:
1241
+ continue
1242
+ seen.add(path)
1243
+ try:
1244
+ if os.path.isfile(path):
1245
+ with open(path, encoding="utf-8", errors="replace") as fh:
1246
+ if "tokensafe-backend/go" in fh.read():
1247
+ return {"installed": True, "evidence": f"{_rel_to(ws, path)} requires tokensafe-backend/go"}
1248
+ except Exception:
1249
+ pass
1250
+ return {"installed": False, "evidence": "tokensafe-backend/go not in go.mod (run: go get github.com/tokensafe-dev/tokensafe-backend/go@vX.Y.Z)"}
1251
+
1252
+
1253
+ def _sidecar_presence(workspace_dir: str, provider: str) -> Dict[str, Any]:
1254
+ """Spring/PHP adapters are sidecars: nothing is installed into the project."""
1255
+ kind = "java" if provider == "spring" else "php"
1256
+ run = None
1257
+ try:
1258
+ from tokensafe import auto_inject
1259
+ path, _note = auto_inject.sidecar_cached(provider)
1260
+ if path:
1261
+ run = auto_inject.sidecar_run_command(provider, path, os.path.abspath(workspace_dir))
1262
+ except Exception:
1263
+ run = None
1264
+ if run:
1265
+ how = f"start it with `{run}`"
1266
+ else:
1267
+ how = f"`tokensafe inject` caches it, then start it with `tokensafe run-backend {kind} …`"
1268
+ return {
1269
+ "installed": True,
1270
+ "mode": "sidecar",
1271
+ "evidence": f"sidecar adapter: no project install needed; {how} (not checked whether it is running)",
1272
+ }
1273
+
1274
+
1275
+ def _dotnet_presence(workspace_dir: str, pkg_dir: str) -> Dict[str, Any]:
1276
+ pattern = re.compile(r"<(?:PackageReference|ProjectReference)\b[^>]*Include\s*=\s*\"[^\"]*TokenSafe\.Oumv", re.I)
1277
+ for csproj in sorted(glob.glob(os.path.join(pkg_dir, "**", "*.csproj"), recursive=True)):
1278
+ if any(part in ("bin", "obj", "node_modules") for part in Path(csproj).parts):
1279
+ continue
1280
+ try:
1281
+ with open(csproj, "r", encoding="utf-8", errors="replace") as fh:
1282
+ if pattern.search(fh.read()):
1283
+ return {"installed": True, "evidence": f"{_rel_to(workspace_dir, csproj)} references TokenSafe.Oumv"}
1284
+ except Exception:
1285
+ continue
1286
+ return {
1287
+ "installed": False,
1288
+ "evidence": "no TokenSafe.Oumv PackageReference in a *.csproj "
1289
+ "(run: dotnet add package TokenSafe.Oumv.AspNetCore)",
1290
+ }
1291
+
1292
+
1293
+ def _adapter_presence(workspace_dir: str, profile: str, provider: str, framework: str,
1294
+ entry: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
988
1295
  """Best-effort, side-effect-free check whether an adapter is available locally.
989
1296
 
990
- Returns {"installed": bool, "evidence": str} where evidence names what was
991
- actually found — never a bare True.
1297
+ `profile` is the entry's own profile (Next.js is a `backend` entry even though
1298
+ it fills the frontend slot). Returns {"installed": bool, "evidence": str}
1299
+ where evidence names what was actually found — never a bare True.
1300
+ """
1301
+ entry = entry or {}
1302
+ pkg_dir = _entry_dir(workspace_dir, entry)
1303
+ if provider in _NODE_PROVIDERS:
1304
+ return _npm_presence(
1305
+ workspace_dir, pkg_dir, _NODE_ADAPTER_PACKAGE,
1306
+ f"npm install -D {_NODE_ADAPTER_PACKAGE}@{BACKEND_NPM_VERSION}",
1307
+ )
1308
+ if profile == "frontend" and provider in ("react", "vue", "solid", "angular"):
1309
+ return _npm_presence(workspace_dir, pkg_dir, _UI_ADAPTER_PACKAGE, f"npm install -D {_UI_ADAPTER_PACKAGE}")
1310
+ if provider in _PYTHON_PROVIDERS:
1311
+ return _python_presence(workspace_dir, pkg_dir)
1312
+ if provider == "go":
1313
+ return _go_presence(workspace_dir, pkg_dir)
1314
+ if provider in _SIDECAR_PROVIDERS:
1315
+ return _sidecar_presence(workspace_dir, provider)
1316
+ if provider == "dotnet":
1317
+ return _dotnet_presence(workspace_dir, pkg_dir)
1318
+ return {"installed": False, "evidence": f"{provider}/{framework}: OUMV adapter not supported yet"}
1319
+
1320
+
1321
+ def _runtime_liveness(workspace_dir: str) -> Dict[str, Dict[str, Any]]:
1322
+ """Per runtime kind ("frontend"/"backend"): live / stale / absent.
1323
+
1324
+ Every descriptor the gateway reads (.oumv/runtime.json, .tokensafe/runtime.json
1325
+ and the global registry) is confirmed by a real `oumv/handshake`; a descriptor
1326
+ without one is `stale` and never makes a profile ready. One handshake per
1327
+ (url, token), each bounded by the gateway's short handshake budget.
992
1328
  """
1329
+ try:
1330
+ from tokensafe import oumv_home
1331
+ from tokensafe.oumv_gateway import OUMVGateway, _is_loopback_url, _remote_runtimes_allowed
1332
+ except Exception:
1333
+ return {}
993
1334
  ws = os.path.abspath(workspace_dir)
994
- if profile == "frontend":
995
- pkg_json = os.path.join(ws, "node_modules", "tokensafe-ui", "package.json")
996
- if os.path.isfile(pkg_json):
997
- return {"installed": True, "evidence": "node_modules/tokensafe-ui"}
998
- return {"installed": False, "evidence": "node_modules/tokensafe-ui missing (run: npm install -D tokensafe-ui)"}
1335
+ paths = [
1336
+ os.path.join(ws, ".oumv", "runtime.json"),
1337
+ os.path.join(ws, ".tokensafe", "runtime.json"),
1338
+ OUMVGateway.global_runtime_file(ws),
1339
+ ]
1340
+ out: Dict[str, Dict[str, Any]] = {}
1341
+ handshakes: Dict[Tuple[str, Optional[str]], bool] = {}
1342
+ now = time.time()
999
1343
 
1000
- if provider in ("fastapi", "python"):
1344
+ def _note(kind: str, record: Dict[str, Any]) -> None:
1345
+ # Later descriptors win (the global registry is authoritative), but a
1346
+ # live answer is never replaced by a stale one.
1347
+ prev = out.get(kind)
1348
+ if prev and prev["state"] == "live" and record["state"] != "live":
1349
+ return
1350
+ out[kind] = record
1351
+
1352
+ for path in paths:
1353
+ if not os.path.isfile(path):
1354
+ continue
1355
+ shown = _display_path(ws, path)
1001
1356
  try:
1002
- import importlib.util
1003
- if importlib.util.find_spec("tokensafe_python") is not None:
1004
- return {"installed": True, "evidence": "tokensafe_python importable"}
1357
+ trusted = OUMVGateway._descriptor_path_is_trusted(path, ws)
1005
1358
  except Exception:
1006
- pass
1007
- for req in ("requirements.txt", "pyproject.toml"):
1008
- path = os.path.join(ws, req)
1009
- try:
1010
- if os.path.isfile(path):
1011
- with open(path, encoding="utf-8", errors="replace") as fh:
1012
- if "tokensafe" in fh.read():
1013
- return {"installed": True, "evidence": f"{req} declares tokensafe"}
1014
- except Exception:
1015
- pass
1016
- return {"installed": False, "evidence": 'tokensafe_python not importable (run: pip install "tokensafe-backend-python @ git+https://github.com/tokensafe-dev/tokensafe-backend.git#subdirectory=python")'}
1359
+ trusted = True
1360
+ if not trusted:
1361
+ continue
1362
+ try:
1363
+ if now - os.path.getmtime(path) > OUMVGateway._DESCRIPTOR_MAX_AGE_SEC:
1364
+ for kind in ("frontend", "backend"):
1365
+ _note(kind, {"state": "stale", "descriptor": shown, "url": None,
1366
+ "reason": f"{shown} is older than 12 h"})
1367
+ continue
1368
+ with open(path, "r", encoding="utf-8") as fh:
1369
+ data = json.load(fh)
1370
+ if not isinstance(data, dict):
1371
+ raise ValueError("descriptor root is not an object")
1372
+ except Exception as exc:
1373
+ for kind in ("frontend", "backend"):
1374
+ _note(kind, {"state": "stale", "descriptor": shown, "url": None,
1375
+ "reason": f"{shown} is unreadable: {exc}"})
1376
+ continue
1377
+ for kind, info in data.items():
1378
+ if not isinstance(info, dict) or not info.get("url"):
1379
+ continue
1380
+ url = str(info["url"])
1381
+ if not _is_loopback_url(url) and not _remote_runtimes_allowed():
1382
+ _note(kind, {"state": "stale", "descriptor": shown, "url": url,
1383
+ "reason": "descriptor points at a non-loopback host (refused)"})
1384
+ continue
1385
+ token = (
1386
+ info.get("session_token") or info.get("sessionToken")
1387
+ or oumv_home.read_session_token(ws, kind)
1388
+ )
1389
+ key = (url, token)
1390
+ if key not in handshakes:
1391
+ try:
1392
+ handshakes[key] = OUMVGateway._handshake(url, token) is not None
1393
+ except Exception:
1394
+ handshakes[key] = False
1395
+ if handshakes[key]:
1396
+ _note(kind, {"state": "live", "descriptor": shown, "url": url, "reason": "live OUMV handshake"})
1397
+ else:
1398
+ _note(kind, {"state": "stale", "descriptor": shown, "url": url,
1399
+ "reason": f"{shown} names {url}, but no live OUMV handshake answers there"})
1400
+ return out
1017
1401
 
1018
- if provider == "go":
1019
- for rel in ("go.mod", os.path.join("go", "go.mod")):
1020
- path = os.path.join(ws, rel)
1021
- try:
1022
- if os.path.isfile(path):
1023
- with open(path, encoding="utf-8", errors="replace") as fh:
1024
- if "tokensafe-backend/go" in fh.read():
1025
- return {"installed": True, "evidence": f"{rel} requires tokensafe-backend/go"}
1026
- except Exception:
1027
- pass
1028
- return {"installed": False, "evidence": "tokensafe-backend/go not in go.mod (run: go get github.com/tokensafe-dev/tokensafe-backend/go@vX.Y.Z)"}
1029
1402
 
1030
- return {"installed": False, "evidence": f"no adapter published for {provider}/{framework}"}
1403
+ def _detected_entries(stack: Dict[str, Any]) -> List[Tuple[str, Dict[str, Any]]]:
1404
+ """(slot, entry) for every detected stack entry, whatever its slot name."""
1405
+ return [
1406
+ (slot, entry) for slot, entry in stack.items()
1407
+ if isinstance(entry, dict) and entry.get("framework") and "provider" in entry
1408
+ ]
1031
1409
 
1032
1410
 
1033
1411
  def run_doctor(workspace_dir: str) -> Dict[str, Any]:
1034
1412
  """Diagnostics for OUMV configuration, detected adapters and agent readiness."""
1035
1413
  stack = detect_project_stack(workspace_dir)
1036
1414
  conf_path = os.path.join(workspace_dir, ".tokensafe", "oumv.json")
1037
- runtime_paths = [
1038
- os.path.join(workspace_dir, ".tokensafe", "runtime.json"),
1039
- ]
1040
- try:
1041
- from tokensafe.oumv_gateway import OUMVGateway
1042
- runtime_paths.insert(0, OUMVGateway.global_runtime_file(workspace_dir))
1043
- except Exception:
1044
- pass
1045
- runtime_path = next((p for p in runtime_paths if os.path.isfile(p)), runtime_paths[-1])
1046
1415
 
1047
1416
  has_config = os.path.isfile(conf_path)
1048
1417
  config_data: Dict[str, Any] = {}
@@ -1053,63 +1422,93 @@ def run_doctor(workspace_dir: str) -> Dict[str, Any]:
1053
1422
  except Exception:
1054
1423
  pass
1055
1424
 
1056
- has_runtime = os.path.isfile(runtime_path)
1057
- runtime_data: Dict[str, Any] = {}
1058
- if has_runtime:
1059
- try:
1060
- with open(runtime_path, "r", encoding="utf-8") as f:
1061
- runtime_data = json.load(f)
1062
- except Exception:
1063
- pass
1425
+ runtimes = _runtime_liveness(workspace_dir)
1064
1426
 
1065
- # Per-profile readiness: a config file alone is not "ready for agent".
1427
+ # Per-entry readiness, keyed by stack slot for compatibility; presence and
1428
+ # liveness use the entry's own profile (Next.js fills the frontend slot but is
1429
+ # served by the Node backend adapter).
1066
1430
  readiness: Dict[str, Any] = {}
1067
- for profile, key in (("frontend", "frontend"), ("backend", "backend")):
1068
- detected = stack.get(key)
1069
- if not detected:
1070
- continue
1431
+ for slot, detected in _detected_entries(stack):
1432
+ profile = detected.get("profile") or slot
1071
1433
  provider = detected.get("provider", "")
1072
1434
  framework = detected.get("framework", "")
1073
1435
  supported = bool(detected.get("oumv_supported", True))
1074
- presence = _adapter_presence(workspace_dir, profile, provider, framework)
1075
- live = has_runtime and runtime_data.get("type", profile) in (profile, None)
1076
- readiness[profile] = {
1436
+ if supported:
1437
+ presence = _adapter_presence(workspace_dir, profile, provider, framework, detected)
1438
+ else:
1439
+ presence = {"installed": False, "evidence": f"{provider}/{framework}: OUMV adapter not supported yet"}
1440
+ runtime = runtimes.get(profile) or {"state": "absent", "descriptor": None, "url": None, "reason": "no runtime descriptor"}
1441
+ live = runtime["state"] == "live"
1442
+ evidence = presence["evidence"]
1443
+ if runtime["state"] == "stale":
1444
+ evidence = f"{evidence}; stale runtime: {runtime['reason']}"
1445
+ readiness[slot] = {
1446
+ "profile": profile,
1077
1447
  "provider": provider,
1078
1448
  "framework": framework,
1079
1449
  "supported": supported,
1080
1450
  "status": detected.get("status", "ready"),
1081
1451
  "installed": presence["installed"],
1082
- "evidence": presence["evidence"],
1083
- "live": bool(live),
1452
+ "mode": presence.get("mode", "in-process"),
1453
+ "evidence": evidence,
1454
+ "live": live,
1455
+ "stale": runtime["state"] == "stale",
1456
+ "runtime_state": runtime["state"],
1457
+ "runtime_url": runtime.get("url"),
1458
+ "runtime_reason": runtime.get("reason"),
1084
1459
  # A planned stack is never "ready": an installed npm package does not
1085
- # create an adapter that does not exist yet.
1460
+ # create an adapter that does not exist yet. A stale descriptor is not
1461
+ # a runtime.
1086
1462
  "ready": bool(supported and (presence["installed"] or live)),
1087
1463
  }
1088
1464
 
1089
- permissions = config_data.get("permissions", {"observe": True, "mutate": True})
1090
- config_enabled = bool(config_data.get("oumv", {}).get("enabled", has_config))
1465
+ permissions = dict(config_data.get("permissions") or {"observe": True, "mutate": True})
1466
+ policy_denials: Dict[str, str] = {}
1467
+ try:
1468
+ from tokensafe import oumv_home
1469
+ for action in ("observe", "mutate"):
1470
+ denial = oumv_home.permission_denial(workspace_dir, action)
1471
+ if denial:
1472
+ policy_denials[action] = denial
1473
+ permissions[action] = False
1474
+ except Exception:
1475
+ pass
1476
+ config_enabled = bool((config_data.get("oumv") or {}).get("enabled", True))
1477
+ observe_ok = bool(permissions.get("observe", True)) and "observe" not in policy_denials
1478
+ supported_items = [item for item in readiness.values() if item["supported"]]
1091
1479
  ready_for_agent = bool(
1092
- has_config
1093
- and config_enabled
1094
- and permissions.get("observe", True)
1095
- and all(item["ready"] for item in readiness.values())
1480
+ config_enabled
1481
+ and observe_ok
1482
+ and supported_items
1483
+ and all(item["ready"] for item in supported_items)
1096
1484
  )
1097
1485
 
1486
+ blocking = [
1487
+ f"{slot}: {item['evidence']}"
1488
+ for slot, item in readiness.items()
1489
+ if not item["ready"]
1490
+ ]
1491
+ if not observe_ok:
1492
+ blocking.insert(0, policy_denials.get("observe") or "observe is disabled (.tokensafe/oumv.json: permissions.observe=false)")
1493
+ if not config_enabled:
1494
+ blocking.insert(0, "OUMV is disabled (.tokensafe/oumv.json: oumv.enabled=false)")
1495
+
1496
+ live_kinds = sorted(kind for kind, rt in runtimes.items() if rt["state"] == "live")
1098
1497
  return {
1099
1498
  "workspace": workspace_dir,
1100
1499
  "detected_stack": stack,
1101
1500
  "config_present": has_config,
1102
1501
  "config": config_data,
1103
- "runtime_beacon_present": has_runtime,
1104
- "runtime_beacon": runtime_data,
1502
+ # Compatibility: "present" now means a descriptor answered a handshake.
1503
+ "runtime_beacon_present": bool(live_kinds),
1504
+ "runtime_beacon": {kind: rt.get("url") for kind, rt in runtimes.items() if rt["state"] == "live"},
1505
+ "runtimes": runtimes,
1506
+ "stale_runtimes": {kind: rt for kind, rt in runtimes.items() if rt["state"] == "stale"},
1105
1507
  "permissions": permissions,
1508
+ "policy_denials": policy_denials,
1106
1509
  "adapter_readiness": readiness,
1107
1510
  "ready_for_agent": ready_for_agent,
1108
- "blocking": [
1109
- f"{profile}: {item['evidence']}"
1110
- for profile, item in readiness.items()
1111
- if not item["ready"]
1112
- ],
1511
+ "blocking": blocking,
1113
1512
  }
1114
1513
 
1115
1514
 
@@ -1167,6 +1566,9 @@ class OUMVProjectContext:
1167
1566
  """Determines whether a target belongs to the frontend or backend profile."""
1168
1567
  if not target:
1169
1568
  return "auto"
1569
+ # Component files first: an absolute `/…/App.tsx` also starts with "/".
1570
+ if target.endswith((".tsx", ".jsx", ".vue", ".svelte")):
1571
+ return "frontend"
1170
1572
  # Backend hints
1171
1573
  if any(target.startswith(m) for m in ["GET ", "POST ", "PUT ", "DELETE ", "PATCH "]) or "/api/" in target or target.startswith("/"):
1172
1574
  return "backend"