tokensafe 4.13.1 → 4.13.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,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 re
10
11
  import socket
11
12
  import hashlib
12
13
  import urllib.request
@@ -1191,7 +1192,14 @@ class OUMVGateway:
1191
1192
  notice = cls._unsupported_backend_notice(workspace_dir, runtime)
1192
1193
  if notice:
1193
1194
  return {"status": "unsupported", **notice}
1194
- url = cls._resolve_client_url(runtime=runtime, target=target, workspace_dir=workspace_dir)
1195
+ try:
1196
+ url = cls._resolve_client_url(runtime=runtime, target=target, workspace_dir=workspace_dir)
1197
+ except RuntimeError:
1198
+ # No runtime endpoint at all: answer the static subset the graph can
1199
+ # prove instead of a bare "No live OUMV runtime" the agent cannot act
1200
+ # on. A runtime that IS found but rejects or fails the call keeps
1201
+ # raising — "runtime answered with an error" is not "offline".
1202
+ return cls._static_verify(target, action, payload or {}, workspace_dir, sandbox)
1195
1203
  params = {
1196
1204
  "target": target,
1197
1205
  "componentId": target,
@@ -1217,6 +1225,174 @@ class OUMVGateway:
1217
1225
  ])
1218
1226
  return res
1219
1227
 
1228
+ @classmethod
1229
+ def _static_verify(cls, target: str, action: str, payload: dict, workspace_dir: Optional[str], sandbox: Optional[dict]) -> Dict[str, Any]:
1230
+ """Offline verify: only what the static index can prove, labelled as such.
1231
+
1232
+ A live runtime dispatches actions in memory; without one the gateway can
1233
+ still check the preconditions — the file exists, it parses, the OCC token
1234
+ matches, a named symbol is declared, and the route/symbol is present in
1235
+ the static surface. Those checks are named in ``scope.checked``; anything
1236
+ that needs execution is listed in ``scope.notExecuted``.
1237
+ """
1238
+ ws = os.path.abspath(workspace_dir or get_active_workspace() or os.getcwd())
1239
+ raw = (target or "").strip()
1240
+ checks: Dict[str, Any] = {}
1241
+ checked: List[str] = []
1242
+ not_executed: List[str] = [
1243
+ "in-memory dispatch (no live OUMV runtime)",
1244
+ "end-to-end browser flow",
1245
+ "production behavior",
1246
+ "full test suite",
1247
+ ]
1248
+ failures: List[str] = []
1249
+ resolved_file = False
1250
+ found_static = False
1251
+
1252
+ abs_path = raw if os.path.isabs(raw) else os.path.join(ws, raw)
1253
+ if raw and os.path.isfile(abs_path):
1254
+ resolved_file = True
1255
+ abs_path = os.path.abspath(abs_path)
1256
+ rel = os.path.relpath(abs_path, ws).replace(os.sep, "/")
1257
+ if rel.startswith("../"):
1258
+ # Outside the workspace: keep the absolute path instead of a
1259
+ # traversal-looking relative one (verify is read-only).
1260
+ rel = abs_path.replace(os.sep, "/")
1261
+ checks["file"] = {"path": rel, "exists": True}
1262
+ checked.append("target file exists")
1263
+ current_version = cls._hash_version(abs_path)
1264
+ checks["currentVersion"] = current_version
1265
+ try:
1266
+ with open(abs_path, "r", encoding="utf-8", errors="replace") as f:
1267
+ source = f.read()
1268
+ except OSError:
1269
+ source = ""
1270
+ from src.syntax_guard import check_syntax
1271
+ checks["syntax"] = check_syntax(abs_path, source) if source else {"status": "skipped", "reason": "unreadable file"}
1272
+ checked.append("syntax check")
1273
+ if checks["syntax"].get("status") == "failed":
1274
+ failures.append(f"syntax check failed: {checks['syntax'].get('error') or 'parse error'}")
1275
+ expected = str(payload.get("expectedVersion") or "").strip()
1276
+ if expected:
1277
+ occ_ok = expected == current_version
1278
+ checks["occ"] = {"expected": expected, "current": current_version, "match": occ_ok}
1279
+ checked.append("OCC version")
1280
+ if not occ_ok:
1281
+ failures.append(f"OCC version mismatch: expected {expected}, current is {current_version}")
1282
+ wanted_symbol = str(payload.get("symbol") or "").strip()
1283
+ if wanted_symbol:
1284
+ symbol_range = cls._resolve_symbol_range(ws, rel, wanted_symbol)
1285
+ checks["symbol"] = {
1286
+ "name": wanted_symbol,
1287
+ "found": bool(symbol_range),
1288
+ "lines": list(symbol_range) if symbol_range else None,
1289
+ }
1290
+ checked.append("symbol presence")
1291
+ if not symbol_range:
1292
+ failures.append(f"symbol '{wanted_symbol}' is not declared in {rel}")
1293
+ try:
1294
+ from src.graph_engine import GraphEngine
1295
+ surface = GraphEngine.get_instance(ws).get_static_oumv_slice(level="L1", target=rel)
1296
+ checks["staticSurface"] = {
1297
+ "endpoints": len(surface.get("endpoints") or []),
1298
+ "clientCalls": len(surface.get("clientCalls") or []),
1299
+ "symbols": len(surface.get("matchingSymbols") or []),
1300
+ }
1301
+ checked.append("static surface (endpoints/client calls)")
1302
+ except Exception:
1303
+ checks["staticSurface"] = {"status": "unavailable"}
1304
+ elif raw:
1305
+ route_method = ""
1306
+ lookup = raw
1307
+ method_match = re.match(r"^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+(\S+)$", raw, re.IGNORECASE)
1308
+ if method_match:
1309
+ # The documented target format is 'POST /api/orders'; the static
1310
+ # index keys endpoints by path, so verify the method separately.
1311
+ route_method = method_match.group(1).upper()
1312
+ lookup = method_match.group(2)
1313
+ try:
1314
+ from src.graph_engine import GraphEngine
1315
+ surface = GraphEngine.get_instance(ws).get_static_oumv_slice(level="L1", target=lookup)
1316
+ endpoints = surface.get("endpoints") or []
1317
+ symbols = surface.get("matchingSymbols") or []
1318
+ if route_method and endpoints:
1319
+ methods = sorted({str(item.get("method") or "").upper() for item in endpoints})
1320
+ matched = [item for item in endpoints if str(item.get("method") or "").upper() == route_method]
1321
+ checks["route"] = {
1322
+ "path": lookup,
1323
+ "method": route_method,
1324
+ "methodMatch": bool(matched),
1325
+ "availableMethods": methods,
1326
+ }
1327
+ checked.append("route method")
1328
+ endpoints = matched
1329
+ found_static = bool(endpoints or symbols)
1330
+ checks["staticSurface"] = {
1331
+ "endpoints": [
1332
+ {"method": item.get("method"), "path": item.get("path") or item.get("route") or item.get("target")}
1333
+ for item in endpoints[:10]
1334
+ ],
1335
+ "symbols": [
1336
+ {"name": item.get("name"), "kind": item.get("kind"), "file": item.get("file")}
1337
+ for item in symbols[:10]
1338
+ ],
1339
+ }
1340
+ checked.append("static endpoint/symbol index lookup")
1341
+ except Exception as exc:
1342
+ checks["staticSurface"] = {"status": "unavailable", "reason": str(exc)}
1343
+
1344
+ checks["action"] = {
1345
+ "requested": action,
1346
+ "executed": False,
1347
+ "reason": "in-memory action dispatch requires a live OUMV runtime",
1348
+ }
1349
+
1350
+ sandbox_note = None
1351
+ if isinstance(sandbox, dict) and sandbox.get("mode"):
1352
+ sandbox_note = {
1353
+ "requested": sandbox.get("mode"),
1354
+ "status": "unavailable offline",
1355
+ "reason": "sandbox rollback runs inside the live runtime's transaction",
1356
+ }
1357
+ not_executed.insert(0, "sandbox rollback")
1358
+
1359
+ if failures:
1360
+ status = "FAILED"
1361
+ hint = "Static checks failed and need no runtime to reproduce; fix them, then re-run verify."
1362
+ elif resolved_file or found_static:
1363
+ status = "PASSED"
1364
+ hint = (
1365
+ "Static checks only. Start the runtime (`tokensafe dev` or `tokensafe run-backend ...`) "
1366
+ "for in-memory dispatch and surface diffs."
1367
+ )
1368
+ else:
1369
+ status = "UNKNOWN"
1370
+ hint = (
1371
+ "Target is not in the static index — that is not proof of absence (dynamic routes, "
1372
+ "generated files). Start the runtime for a real dispatch, or pass a file path."
1373
+ )
1374
+
1375
+ result: Dict[str, Any] = {
1376
+ "status": status,
1377
+ "mode": "OFFLINE_STATIC_VERIFY",
1378
+ "target": raw,
1379
+ "action": action,
1380
+ "checks": checks,
1381
+ "scope": {"checked": checked, "notExecuted": not_executed, "mode": "static"},
1382
+ "requiresRuntime": True,
1383
+ "evidence": {
1384
+ "provenance": "static",
1385
+ "sourceAdapter": "tokensafe-graph-engine",
1386
+ "confidence": "confirmed",
1387
+ },
1388
+ "hint": hint,
1389
+ }
1390
+ if sandbox_note:
1391
+ result["sandbox"] = sandbox_note
1392
+ if failures:
1393
+ result["failures"] = failures
1394
+ return result
1395
+
1220
1396
  # 6. Tool: oumv_graph — unified cross-stack intelligence graph (spec §11)
1221
1397
  @classmethod
1222
1398
  def graph(cls, query: str = "overview", target: Optional[str] = None, workspace_dir: Optional[str] = None) -> Any:
package/src/retrofit.py CHANGED
@@ -352,7 +352,10 @@ def detect_project_stack(workspace_dir: str) -> Dict[str, Any]:
352
352
  framework = "flask"
353
353
  elif "starlette" in c:
354
354
  framework = "starlette"
355
- supported = framework in ("fastapi", "starlette")
355
+ # Flask/Django are certified WSGI adapters (65/65, L3 in
356
+ # tokensafe-backend), but they mount explicitly — `tokensafe
357
+ # inject` cannot patch a WSGI host, so their status is manual.
358
+ supported = framework in ("fastapi", "starlette", "flask", "django")
356
359
  py_entry = {
357
360
  "framework": framework,
358
361
  "provider": "fastapi" if framework == "fastapi" else "python",
@@ -361,7 +364,8 @@ def detect_project_stack(workspace_dir: str) -> Dict[str, Any]:
361
364
  "language": "python",
362
365
  "root": os.path.dirname(rel_pf) or ".",
363
366
  "oumv_supported": supported,
364
- "status": "ready" if supported else "planned",
367
+ "status": ("ready" if framework in ("fastapi", "starlette")
368
+ else ("manual" if supported else "planned")),
365
369
  }
366
370
  # A supported Python backend outranks an unsupported Node one,
367
371
  # mirroring the Go precedence rule above.
@@ -991,7 +995,7 @@ def _adapter_presence(workspace_dir: str, profile: str, provider: str, framework
991
995
  return {"installed": True, "evidence": "node_modules/tokensafe-ui"}
992
996
  return {"installed": False, "evidence": "node_modules/tokensafe-ui missing (run: npm install -D tokensafe-ui)"}
993
997
 
994
- if provider == "fastapi":
998
+ if provider in ("fastapi", "python"):
995
999
  try:
996
1000
  import importlib.util
997
1001
  if importlib.util.find_spec("tokensafe_python") is not None:
@@ -104,13 +104,16 @@ class ScopedSearch:
104
104
 
105
105
  @classmethod
106
106
  def _graph_symbol_index(cls, root_dir: str):
107
- """Cache-only view of the AST symbol index; never starts a repository crawl."""
107
+ """Cache-only view of the AST symbol index; never starts a repository crawl.
108
+
109
+ Uses the warm GraphEngine instance when one exists (``oumv index`` /
110
+ ``observe`` / ``status`` warm it) and the on-disk cache otherwise.
111
+ """
108
112
  try:
109
- from src.graph_engine import CodeGraph
110
- graph = CodeGraph(root_dir, use_disk_cache=True)
113
+ from src.graph_engine import GraphEngine
114
+ return GraphEngine.get_cached(root_dir)
111
115
  except Exception:
112
116
  return None
113
- return graph if graph.symbols else None
114
117
 
115
118
  @classmethod
116
119
  def _symbol_matches(
@@ -120,6 +123,7 @@ class ScopedSearch:
120
123
  scope: str,
121
124
  max_results: int,
122
125
  per_file: int,
126
+ graph,
123
127
  ) -> Optional[List[Dict[str, Any]]]:
124
128
  """Exact declaration lookup across every indexed file.
125
129
 
@@ -128,10 +132,12 @@ class ScopedSearch:
128
132
  is why a symbol declared in `paidz-workers` answered "0 matches" while the
129
133
  graph index held it. Returns None when this is not a symbol-shaped query or
130
134
  no cache exists — the caller then falls back to the bounded disk scan.
135
+
136
+ ``graph`` is loaded once per query by the caller, so an identifier search
137
+ deserializes the index exactly once instead of twice.
131
138
  """
132
139
  if not re.fullmatch(r"[A-Za-z_$][\w$]{2,}", query or ""):
133
140
  return None
134
- graph = cls._graph_symbol_index(root_dir)
135
141
  if graph is None:
136
142
  return None
137
143
  q = query.lower()
@@ -338,12 +344,14 @@ class ScopedSearch:
338
344
  # Symbol fast path: an identifier is a lookup, and the AST index covers every
339
345
  # file while the bounded disk walk below covers only the first 2,500.
340
346
  if not regex_mode and not case_sensitive:
341
- symbol_matches = cls._symbol_matches(query, root_dir, scope, max_results, per_file)
347
+ # One index load per query: the symbol fast path and its coverage
348
+ # count used to deserialize the same graph twice.
349
+ graph = cls._graph_symbol_index(root_dir)
350
+ symbol_matches = cls._symbol_matches(query, root_dir, scope, max_results, per_file, graph=graph)
342
351
  if symbol_matches is not None:
343
352
  hit_files = {m["file"] for m in symbol_matches}
344
353
  indexed = 0
345
354
  try:
346
- graph = cls._graph_symbol_index(root_dir)
347
355
  indexed = len(set(graph.file_stats) | set(graph.file_symbols)) if graph else 0
348
356
  except Exception:
349
357
  indexed = 0
@@ -43,34 +43,88 @@ _FRONTEND_LINES = {
43
43
  "tokensafe:oumv(action='observe', level='L1') before reading files; run "
44
44
  "`tokensafe dev --framework vue` if no runtime is live."
45
45
  ),
46
+ "nextjs": (
47
+ "frontend {provider}/{framework}: OUMV via `tokensafe inject` (App Router handler + browser "
48
+ "bridge, three generated files) or `tokensafe dev` for live browser RPC. Call "
49
+ "tokensafe:oumv(action='observe', level='L1') before reading files."
50
+ ),
46
51
  }
47
52
 
53
+ _NODE_MOUNT_LINE = (
54
+ "backend {provider}/{framework}: install `tokensafe-backend-node` and mount it "
55
+ "(`mountTokensafe(app)` for Express, `registerTokensafe(app)` for Fastify); "
56
+ "then use tokensafe:oumv for endpoints/impact and oumv_verify for live checks."
57
+ )
58
+
59
+ # Keyed by FRAMEWORK, not provider: the provider says which package ships the
60
+ # adapter; the framework says how it mounts. Flask/Django are WSGI and need an
61
+ # explicit mount (certified, but `tokensafe inject` cannot patch a WSGI host).
48
62
  _BACKEND_LINES = {
49
63
  "fastapi": (
50
64
  "backend fastapi/fastapi: OUMV auto-mounts when the dev server runs through "
51
65
  "`tokensafe run-backend uvicorn <module:app> --reload` (RPC at /__oumv/rpc). "
52
66
  "Prefer tokensafe:oumv(action='observe'|'understand'|'mutate'|'verify') over grep/curl."
53
67
  ),
54
- "go": (
55
- "backend {provider}/{framework}: OUMV mounts with one AutoMountAndServe line "
56
- "(discovery included; `tokensafe inject --status` shows it, `--revert` removes it). "
57
- "Use tokensafe:oumv for endpoints/source/impact, oumv_verify for in-process checks."
68
+ "starlette": (
69
+ "backend {provider}/{framework}: OUMV auto-mounts via `tokensafe run-backend uvicorn "
70
+ "<module:app> --reload` (the same mount_tokensafe detects a plain-ASGI host; "
71
+ "mount_tokensafe_starlette is the explicit alias). Prefer tokensafe:oumv over grep/curl."
58
72
  ),
59
- "node": (
60
- "backend node/{framework}: install `tokensafe-backend-node` and mount it "
61
- "(`mountTokensafe(app)` for Express, `registerTokensafe(app)` for Fastify); "
62
- "then use tokensafe:oumv for endpoints/impact and oumv_verify for live checks."
73
+ "flask": (
74
+ "backend {provider}/{framework} (WSGI, manual): mount explicitly in the app factory — "
75
+ "`from tokensafe_python.adapters.flask import mount_tokensafe; mount_tokensafe(app)` "
76
+ "(wraps app.wsgi_app); `tokensafe inject` cannot patch a WSGI host. Then use "
77
+ "tokensafe:oumv for endpoints/impact and oumv_verify."
63
78
  ),
64
- "python": (
65
- "backend python/{framework}: install `tokensafe-backend-python` and mount the adapter "
66
- "(`mount_tokensafe(app)` for FastAPI, `mount_tokensafe_starlette(app)` for Starlette); "
67
- "then use tokensafe:oumv for endpoints/impact and oumv_verify for live checks."
79
+ "django": (
80
+ "backend {provider}/{framework} (WSGI, manual): mount explicitly in wsgi.py — "
81
+ "`from tokensafe_python.adapters.django import mount_tokensafe; "
82
+ "application = mount_tokensafe(application)`; `tokensafe inject` cannot patch a WSGI "
83
+ "host. Then use tokensafe:oumv for endpoints/impact and oumv_verify."
68
84
  ),
85
+ "express": _NODE_MOUNT_LINE,
86
+ "fastify": _NODE_MOUNT_LINE,
69
87
  "elysia": (
70
88
  "backend elysia/{framework} (Bun): install `tokensafe-backend-node` and add "
71
89
  "`app.use(require('tokensafe-backend-node/elysia').oumv())` before `app.listen()`; "
72
90
  "then use tokensafe:oumv for endpoints/impact and oumv_verify for live checks."
73
91
  ),
92
+ "gin": (
93
+ "backend {provider}/{framework}: OUMV mounts with one AutoMount line "
94
+ "(`tokensafe inject`, reversible; discovery included). Use tokensafe:oumv for "
95
+ "endpoints/source/impact, oumv_verify for in-process checks."
96
+ ),
97
+ "chi": (
98
+ "backend {provider}/{framework}: OUMV mounts with one AutoMount line "
99
+ "(`tokensafe inject`, reversible; discovery included). Use tokensafe:oumv for "
100
+ "endpoints/source/impact, oumv_verify for in-process checks."
101
+ ),
102
+ "net/http": (
103
+ "backend {provider}/{framework} (manual): replace `http.NewServeMux()` with "
104
+ "`rt := oumv.NewRuntime(...)` + `mux := oumvstdhttp.NewServeMux(rt)` + "
105
+ "`mux.Mount(\"/__oumv/rpc\")`; `tokensafe inject --status` prints the exact recipe. "
106
+ "Then use tokensafe:oumv and oumv_verify."
107
+ ),
108
+ "spring": (
109
+ "backend {provider}/{framework} (Java): `tokensafe inject` caches the single-file "
110
+ "OumvSpring sidecar (nothing in the repo); run it via `tokensafe run-backend "
111
+ "--app-url <url>`; then use tokensafe:oumv and oumv_verify."
112
+ ),
113
+ "laravel": (
114
+ "backend {provider}/{framework} (PHP): `tokensafe inject` caches the content-addressed "
115
+ "`oumv-php` sidecar (nothing in the repo); run it via `tokensafe run-backend "
116
+ "--app-url <url>`; then use tokensafe:oumv and oumv_verify."
117
+ ),
118
+ "symfony": (
119
+ "backend {provider}/{framework} (PHP): `tokensafe inject` caches the content-addressed "
120
+ "`oumv-php` sidecar (nothing in the repo); run it via `tokensafe run-backend "
121
+ "--app-url <url>`; then use tokensafe:oumv and oumv_verify."
122
+ ),
123
+ "aspnetcore": (
124
+ "backend {provider}/{framework}: `tokensafe inject` adds one reversible "
125
+ "`AddTokensafe()`/`UseTokensafe()` pair plus the TokenSafe.Oumv.AspNetCore "
126
+ "PackageReference; then use tokensafe:oumv and oumv_verify."
127
+ ),
74
128
  }
75
129
 
76
130
 
@@ -134,28 +188,47 @@ def _profile_supported(kind: str, entry: Dict[str, Any]) -> bool:
134
188
  if isinstance(flag, bool):
135
189
  return flag
136
190
  table = _FRONTEND_LINES if kind == "frontend" else _BACKEND_LINES
137
- template = table.get(str(entry.get("provider") or ""))
191
+ template = table.get(str(entry.get("framework") or entry.get("provider") or ""))
138
192
  return bool(template) and "no OUMV adapter" not in template
139
193
 
140
194
 
195
+ def _routing_line(kind: str, entry: Dict[str, Any]) -> str:
196
+ """One brief line for a detected profile — template, generic ready, or honest planned."""
197
+ provider = str(entry.get("provider") or "")
198
+ framework = str(entry.get("framework") or provider)
199
+ supported = _profile_supported(kind, entry)
200
+ table = _FRONTEND_LINES if kind == "frontend" else _BACKEND_LINES
201
+ template = table.get(framework) if supported else None
202
+ if template:
203
+ return "- " + template.format(provider=provider, framework=framework)
204
+ if supported:
205
+ adapter = str(entry.get("adapter") or "")
206
+ via = f" via {adapter}" if adapter else ""
207
+ live = "; start live bridge via `tokensafe dev`" if entry.get("vite") else ""
208
+ return (
209
+ f"- {kind} {provider}/{framework}: OUMV ready{via}{live}; call "
210
+ "tokensafe:oumv(action='status'|'observe'|'mutate') before reading files."
211
+ )
212
+ return (
213
+ f"- {provider}/{framework}: OUMV has no adapter yet — use "
214
+ "tokensafe:repo_map / scoped_search / smart_read_file instead of oumv."
215
+ )
216
+
217
+
141
218
  def _stack_labels(stack: Dict[str, Any]) -> List[tuple]:
142
219
  """(kind, provider, framework, supported, adapter) per detected profile.
143
220
 
144
- A routing template decides when one exists (it says how to mount, or says
145
- there is no adapter); the detection flag only fills the gap for providers
146
- the templates do not cover yet (e.g. Solid)."""
221
+ The detector's ``oumv_supported`` flag is authoritative; a routing template
222
+ only decides the wording, never whether a stack is supported (a template for
223
+ ``python`` must not turn Flask or Django into "ready")."""
147
224
  labels: List[tuple] = []
148
- for kind, table in (("frontend", _FRONTEND_LINES), ("backend", _BACKEND_LINES)):
225
+ for kind in ("frontend", "backend"):
149
226
  entry = stack.get(kind) or {}
150
227
  provider = str(entry.get("provider") or "")
151
228
  if not provider:
152
229
  continue
153
230
  framework = str(entry.get("framework") or provider)
154
- template = table.get(provider)
155
- if template is not None:
156
- supported = "no OUMV adapter" not in template
157
- else:
158
- supported = _profile_supported(kind, entry)
231
+ supported = _profile_supported(kind, entry)
159
232
  labels.append((kind, provider, framework, supported, str(entry.get("adapter") or "")))
160
233
  return labels
161
234
 
@@ -218,14 +291,28 @@ def _activation(workspace: str, stack: Dict[str, Any]) -> List[str]:
218
291
  for profile, item in readiness.items():
219
292
  if item.get("ready"):
220
293
  continue
294
+ framework = str(item.get("framework") or "")
221
295
  if not item.get("supported", True):
222
- hints.append(
223
- f"no OUMV adapter for {item.get('provider')}/{item.get('framework')} yet — "
224
- "use tokensafe tools (repo_map, scoped_search, smart_read_file) instead"
225
- )
226
- elif profile == "frontend":
296
+ # The routing line already says "no adapter yet"; repeating it here
297
+ # only burns brief budget.
298
+ continue
299
+ if item.get("status") == "manual":
300
+ # The routing line carries the exact mount recipe; add only the
301
+ # missing install step (net/http needs the go get, not a patch).
302
+ if framework in ("flask", "django"):
303
+ hints.append(
304
+ 'activate backend (manual WSGI): `pip install "tokensafe-backend-python @ '
305
+ 'git+https://github.com/tokensafe-dev/tokensafe-backend.git#subdirectory=python"`'
306
+ )
307
+ elif framework == "net/http":
308
+ hints.append(
309
+ f"activate backend: `go get github.com/tokensafe-dev/tokensafe-backend/go@{BACKEND_RELEASE_TAG}` "
310
+ "then `tokensafe inject --status` prints the mux recipe (no auto-patch)"
311
+ )
312
+ continue
313
+ if profile == "frontend":
227
314
  hints.append("activate frontend: run `tokensafe dev` (installs nothing into the repo)")
228
- elif item.get("provider") == "fastapi":
315
+ elif framework in ("fastapi", "starlette"):
229
316
  hints.append('activate backend: `pip install "tokensafe-backend-python @ git+https://github.com/tokensafe-dev/tokensafe-backend.git#subdirectory=python"` then run the server via `tokensafe run-backend ...`')
230
317
  elif item.get("provider") == "go":
231
318
  hints.append(
@@ -237,6 +324,35 @@ def _activation(workspace: str, stack: Dict[str, Any]) -> List[str]:
237
324
  return hints
238
325
 
239
326
 
327
+ def _truncate_by_rank(entries: List[tuple], max_chars: int) -> str:
328
+ """Join brief lines, dropping the least important first until they fit.
329
+
330
+ The old tail-cut could remove the backend verdict (or a whole extra-root
331
+ line) because it only knew string order. Rank order keeps the title and the
332
+ backend/frontend verdicts whenever the limit allows them at all.
333
+ """
334
+ if not entries:
335
+ return ""
336
+ total = sum(len(line) + 1 for _, line in entries) - 1
337
+ if total <= max_chars:
338
+ return "\n".join(line for _, line in entries)
339
+ keep = [True] * len(entries)
340
+ dropped = False
341
+ # Drop the highest rank first; among equals, the later line goes first.
342
+ for idx in sorted(range(len(entries)), key=lambda i: (entries[i][0], i), reverse=True):
343
+ if total <= max_chars - 2:
344
+ break
345
+ keep[idx] = False
346
+ dropped = True
347
+ total -= len(entries[idx][1]) + 1
348
+ brief = "\n".join(line for idx, (_, line) in enumerate(entries) if keep[idx])
349
+ if dropped:
350
+ brief += "\n…"
351
+ if len(brief) > max_chars:
352
+ brief = brief[: max_chars - 1].rstrip() + "…"
353
+ return brief
354
+
355
+
240
356
  def build_workspace_brief(
241
357
  workspace: Optional[str] = None,
242
358
  include_live: bool = False,
@@ -269,55 +385,39 @@ def build_workspace_brief(
269
385
  seen = {os.path.realpath(workspace)}
270
386
  extra_lines = _extra_root_lines(extra_workspaces or [], seen)
271
387
 
272
- lines: List[str] = ["[TokenSafe OUMV routing brief]"]
388
+ # (rank, line) — lower rank is more important. Truncation drops the least
389
+ # important lines first, so the backend verdict can never be cut away while
390
+ # string-catalog hints survive. Output order stays as inserted.
391
+ entries: List[tuple] = [(0, "[TokenSafe OUMV routing brief]")]
273
392
  if extra_lines:
274
- lines.append(
393
+ entries.append((
394
+ 2,
275
395
  "- scope: per-root verdicts below; for any unlisted repo call "
276
- "tokensafe:oumv(action='status', workspace_dir='<repo>')."
277
- )
396
+ "tokensafe:oumv(action='status', workspace_dir='<repo>').",
397
+ ))
278
398
  else:
279
- lines.append(
399
+ entries.append((
400
+ 2,
280
401
  "- scope: this verdict covers this root only; before editing another repo call "
281
- "tokensafe:oumv(action='status', workspace_dir='<repo>')."
282
- )
402
+ "tokensafe:oumv(action='status', workspace_dir='<repo>').",
403
+ ))
283
404
  for kind, entry in (("frontend", frontend), ("backend", backend)):
284
- if not entry:
285
- continue
286
- provider = str(entry.get("provider") or "")
287
- framework = str(entry.get("framework") or provider)
288
- supported = _profile_supported(kind, entry)
289
- table = _FRONTEND_LINES if kind == "frontend" else _BACKEND_LINES
290
- template = table.get(provider)
291
- if template:
292
- lines.append("- " + template.format(provider=provider, framework=framework))
293
- elif _profile_supported(kind, entry):
294
- # Provider without a routing template (e.g. Solid) but with a
295
- # runtime-reported adapter: route through OUMV instead of greps.
296
- adapter = str(entry.get("adapter") or "")
297
- via = f" via {adapter}" if adapter else ""
298
- live = "; start live bridge via `tokensafe dev`" if entry.get("vite") else ""
299
- lines.append(
300
- f"- {kind} {provider}/{framework}: OUMV ready{via}{live}; call "
301
- "tokensafe:oumv(action='status'|'observe'|'mutate') before reading files."
302
- )
303
- else:
304
- lines.append(
305
- f"- {provider}/{framework}: OUMV has no adapter yet — use "
306
- "tokensafe:repo_map / scoped_search / smart_read_file instead of oumv."
307
- )
405
+ if entry:
406
+ entries.append((1 if kind == "backend" else 3, _routing_line(kind, entry)))
308
407
 
309
408
  if extra_lines:
310
- lines.append("- other workspace roots:")
311
- lines.extend(extra_lines)
409
+ entries.append((5, "- other workspace roots:"))
410
+ entries.extend((6, line) for line in extra_lines)
312
411
 
313
412
  permissions = _read_permissions(workspace)
314
413
  if permissions:
315
414
  mutate = permissions.get("mutate", True)
316
- lines.append(
415
+ entries.append((
416
+ 4,
317
417
  "- mutations: "
318
418
  + ("enabled with guardrails (OCC version, path jail, syntax pre-flight, backups)"
319
- if mutate else "disabled by .tokensafe/oumv.json (permissions.mutate=false)")
320
- )
419
+ if mutate else "disabled by .tokensafe/oumv.json (permissions.mutate=false)"),
420
+ ))
321
421
 
322
422
  if include_live:
323
423
  try:
@@ -329,32 +429,25 @@ def build_workspace_brief(
329
429
  if item.get("url") or item.get("status") in ("OK", "LIVE"):
330
430
  live.append(f"{profile}={item.get('url') or item.get('name', 'live')}")
331
431
  if live:
332
- lines.append("- live runtimes: " + ", ".join(live) + " — inspect/verify via OUMV first")
432
+ entries.append((7, "- live runtimes: " + ", ".join(live) + " — inspect/verify via OUMV first"))
333
433
  except Exception:
334
434
  pass
335
435
 
336
436
  hints = _activation(workspace, stack)
337
437
  if hints:
338
- lines.append("- " + "; ".join(hints))
438
+ entries.append((8, "- " + "; ".join(hints)))
339
439
 
340
440
  # String catalogs: only mention `dict` where a catalog actually exists, so
341
441
  # projects without i18n never pay for the line.
342
442
  try:
343
443
  from src.i18n_catalog import resolve_messages_dir
344
444
  if resolve_messages_dir(workspace):
345
- lines.append(
445
+ entries.append((
446
+ 9,
346
447
  "- string catalogs: review and patch via `tokensafe dict lint --locale <l>` then "
347
- "`dict apply` — never read whole messages/*/*.ts files (smart_read_file returns a digest)"
348
- )
448
+ "`dict apply` — never read whole messages/*/*.ts files (smart_read_file returns a digest)",
449
+ ))
349
450
  except Exception:
350
451
  pass
351
452
 
352
- brief = "\n".join(lines)
353
- if len(brief) > max_chars:
354
- # Cut on a line boundary: a half-written path in a truncated root line
355
- # is worse than a dropped tail line (the scope sentence stays at the top).
356
- cut = brief[: max_chars - 1]
357
- if "\n" in cut:
358
- cut = cut.rsplit("\n", 1)[0]
359
- brief = cut.rstrip() + "…"
360
- return brief
453
+ return _truncate_by_rank(entries, max_chars)
@@ -311,7 +311,7 @@ class TelemetrySync:
311
311
  current_last_id = last_id
312
312
  headers = {
313
313
  "Content-Type": "application/json",
314
- "User-Agent": "TokenSafe-Sync/4.13.1"
314
+ "User-Agent": "TokenSafe-Sync/4.13.3"
315
315
  }
316
316
  if active_key:
317
317
  headers["Authorization"] = f"Bearer {active_key}"
@@ -17,7 +17,7 @@ import urllib.request
17
17
  import urllib.error
18
18
  from typing import Dict, Any, Optional, Tuple
19
19
 
20
- CURRENT_VERSION = "4.13.1"
20
+ CURRENT_VERSION = "4.13.3"
21
21
  CACHE_TTL = 86400 # 24 hours
22
22
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
23
23
  # answer for a full day — otherwise an update released right after an outage