tokensafe 4.13.2 → 4.14.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.
@@ -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
@@ -350,6 +351,42 @@ class OUMVGateway:
350
351
  removed.append(path)
351
352
  return removed
352
353
 
354
+ @classmethod
355
+ def prune_backups(cls, workspace_dir: str, *, keep_per_file: int = 20,
356
+ max_age_days: int = 30) -> List[str]:
357
+ """Bounds ``.tokensafe/backups``: the newest ``keep_per_file`` per source
358
+ file and nothing older than ``max_age_days``. Best-effort by design — a
359
+ retention failure must never fail the mutation that triggered it."""
360
+ directory = os.path.join(workspace_dir, ".tokensafe", "backups")
361
+ if not os.path.isdir(directory):
362
+ return []
363
+ try:
364
+ entries = list(os.scandir(directory))
365
+ except OSError:
366
+ return []
367
+ groups: Dict[str, List[Any]] = {}
368
+ for entry in entries:
369
+ if not entry.is_file() or not entry.name.endswith(".bak"):
370
+ continue
371
+ stem = entry.name.split("_", 1)[1] if "_" in entry.name else entry.name
372
+ groups.setdefault(stem, []).append(entry)
373
+ now = time.time()
374
+ removed: List[str] = []
375
+ for backups in groups.values():
376
+ backups.sort(key=lambda item: item.stat().st_mtime, reverse=True)
377
+ for index, entry in enumerate(backups):
378
+ try:
379
+ age_days = (now - entry.stat().st_mtime) / 86400
380
+ except OSError:
381
+ continue
382
+ if index >= keep_per_file or age_days > max_age_days:
383
+ try:
384
+ os.unlink(entry.path)
385
+ removed.append(entry.path)
386
+ except OSError:
387
+ pass
388
+ return removed
389
+
353
390
  @classmethod
354
391
  def _probe_candidates(cls, urls: List[str], kind: str) -> Optional[Dict[str, Any]]:
355
392
  for url in urls:
@@ -1144,16 +1181,19 @@ class OUMVGateway:
1144
1181
  os.makedirs(backup_dir, exist_ok=True)
1145
1182
  digest = hashlib.sha256(content).hexdigest()[:8]
1146
1183
  backup_path = os.path.join(backup_dir, f"{digest}_{os.path.basename(abs_path)}.bak")
1147
- with open(backup_path, "wb") as f:
1148
- f.write(content)
1184
+ from src.atomic_io import write_atomic
1185
+ write_atomic(backup_path, content)
1149
1186
  except Exception:
1150
1187
  backup_path = None
1151
1188
 
1152
- os.makedirs(os.path.dirname(abs_path), exist_ok=True)
1153
- with open(abs_path, "w", encoding="utf-8") as f:
1154
- f.write(new_content)
1189
+ from src.atomic_io import write_atomic
1190
+ write_atomic(abs_path, new_content)
1155
1191
 
1156
1192
  new_version = "sha256:" + hashlib.sha256(new_content.encode("utf-8")).hexdigest()
1193
+ try:
1194
+ OUMVGateway.prune_backups(ws)
1195
+ except Exception:
1196
+ pass
1157
1197
  result = {
1158
1198
  "success": True,
1159
1199
  "path": path,
@@ -1191,7 +1231,14 @@ class OUMVGateway:
1191
1231
  notice = cls._unsupported_backend_notice(workspace_dir, runtime)
1192
1232
  if notice:
1193
1233
  return {"status": "unsupported", **notice}
1194
- url = cls._resolve_client_url(runtime=runtime, target=target, workspace_dir=workspace_dir)
1234
+ try:
1235
+ url = cls._resolve_client_url(runtime=runtime, target=target, workspace_dir=workspace_dir)
1236
+ except RuntimeError:
1237
+ # No runtime endpoint at all: answer the static subset the graph can
1238
+ # prove instead of a bare "No live OUMV runtime" the agent cannot act
1239
+ # on. A runtime that IS found but rejects or fails the call keeps
1240
+ # raising — "runtime answered with an error" is not "offline".
1241
+ return cls._static_verify(target, action, payload or {}, workspace_dir, sandbox)
1195
1242
  params = {
1196
1243
  "target": target,
1197
1244
  "componentId": target,
@@ -1217,6 +1264,174 @@ class OUMVGateway:
1217
1264
  ])
1218
1265
  return res
1219
1266
 
1267
+ @classmethod
1268
+ def _static_verify(cls, target: str, action: str, payload: dict, workspace_dir: Optional[str], sandbox: Optional[dict]) -> Dict[str, Any]:
1269
+ """Offline verify: only what the static index can prove, labelled as such.
1270
+
1271
+ A live runtime dispatches actions in memory; without one the gateway can
1272
+ still check the preconditions — the file exists, it parses, the OCC token
1273
+ matches, a named symbol is declared, and the route/symbol is present in
1274
+ the static surface. Those checks are named in ``scope.checked``; anything
1275
+ that needs execution is listed in ``scope.notExecuted``.
1276
+ """
1277
+ ws = os.path.abspath(workspace_dir or get_active_workspace() or os.getcwd())
1278
+ raw = (target or "").strip()
1279
+ checks: Dict[str, Any] = {}
1280
+ checked: List[str] = []
1281
+ not_executed: List[str] = [
1282
+ "in-memory dispatch (no live OUMV runtime)",
1283
+ "end-to-end browser flow",
1284
+ "production behavior",
1285
+ "full test suite",
1286
+ ]
1287
+ failures: List[str] = []
1288
+ resolved_file = False
1289
+ found_static = False
1290
+
1291
+ abs_path = raw if os.path.isabs(raw) else os.path.join(ws, raw)
1292
+ if raw and os.path.isfile(abs_path):
1293
+ resolved_file = True
1294
+ abs_path = os.path.abspath(abs_path)
1295
+ rel = os.path.relpath(abs_path, ws).replace(os.sep, "/")
1296
+ if rel.startswith("../"):
1297
+ # Outside the workspace: keep the absolute path instead of a
1298
+ # traversal-looking relative one (verify is read-only).
1299
+ rel = abs_path.replace(os.sep, "/")
1300
+ checks["file"] = {"path": rel, "exists": True}
1301
+ checked.append("target file exists")
1302
+ current_version = cls._hash_version(abs_path)
1303
+ checks["currentVersion"] = current_version
1304
+ try:
1305
+ with open(abs_path, "r", encoding="utf-8", errors="replace") as f:
1306
+ source = f.read()
1307
+ except OSError:
1308
+ source = ""
1309
+ from src.syntax_guard import check_syntax
1310
+ checks["syntax"] = check_syntax(abs_path, source) if source else {"status": "skipped", "reason": "unreadable file"}
1311
+ checked.append("syntax check")
1312
+ if checks["syntax"].get("status") == "failed":
1313
+ failures.append(f"syntax check failed: {checks['syntax'].get('error') or 'parse error'}")
1314
+ expected = str(payload.get("expectedVersion") or "").strip()
1315
+ if expected:
1316
+ occ_ok = expected == current_version
1317
+ checks["occ"] = {"expected": expected, "current": current_version, "match": occ_ok}
1318
+ checked.append("OCC version")
1319
+ if not occ_ok:
1320
+ failures.append(f"OCC version mismatch: expected {expected}, current is {current_version}")
1321
+ wanted_symbol = str(payload.get("symbol") or "").strip()
1322
+ if wanted_symbol:
1323
+ symbol_range = cls._resolve_symbol_range(ws, rel, wanted_symbol)
1324
+ checks["symbol"] = {
1325
+ "name": wanted_symbol,
1326
+ "found": bool(symbol_range),
1327
+ "lines": list(symbol_range) if symbol_range else None,
1328
+ }
1329
+ checked.append("symbol presence")
1330
+ if not symbol_range:
1331
+ failures.append(f"symbol '{wanted_symbol}' is not declared in {rel}")
1332
+ try:
1333
+ from src.graph_engine import GraphEngine
1334
+ surface = GraphEngine.get_instance(ws).get_static_oumv_slice(level="L1", target=rel)
1335
+ checks["staticSurface"] = {
1336
+ "endpoints": len(surface.get("endpoints") or []),
1337
+ "clientCalls": len(surface.get("clientCalls") or []),
1338
+ "symbols": len(surface.get("matchingSymbols") or []),
1339
+ }
1340
+ checked.append("static surface (endpoints/client calls)")
1341
+ except Exception:
1342
+ checks["staticSurface"] = {"status": "unavailable"}
1343
+ elif raw:
1344
+ route_method = ""
1345
+ lookup = raw
1346
+ method_match = re.match(r"^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+(\S+)$", raw, re.IGNORECASE)
1347
+ if method_match:
1348
+ # The documented target format is 'POST /api/orders'; the static
1349
+ # index keys endpoints by path, so verify the method separately.
1350
+ route_method = method_match.group(1).upper()
1351
+ lookup = method_match.group(2)
1352
+ try:
1353
+ from src.graph_engine import GraphEngine
1354
+ surface = GraphEngine.get_instance(ws).get_static_oumv_slice(level="L1", target=lookup)
1355
+ endpoints = surface.get("endpoints") or []
1356
+ symbols = surface.get("matchingSymbols") or []
1357
+ if route_method and endpoints:
1358
+ methods = sorted({str(item.get("method") or "").upper() for item in endpoints})
1359
+ matched = [item for item in endpoints if str(item.get("method") or "").upper() == route_method]
1360
+ checks["route"] = {
1361
+ "path": lookup,
1362
+ "method": route_method,
1363
+ "methodMatch": bool(matched),
1364
+ "availableMethods": methods,
1365
+ }
1366
+ checked.append("route method")
1367
+ endpoints = matched
1368
+ found_static = bool(endpoints or symbols)
1369
+ checks["staticSurface"] = {
1370
+ "endpoints": [
1371
+ {"method": item.get("method"), "path": item.get("path") or item.get("route") or item.get("target")}
1372
+ for item in endpoints[:10]
1373
+ ],
1374
+ "symbols": [
1375
+ {"name": item.get("name"), "kind": item.get("kind"), "file": item.get("file")}
1376
+ for item in symbols[:10]
1377
+ ],
1378
+ }
1379
+ checked.append("static endpoint/symbol index lookup")
1380
+ except Exception as exc:
1381
+ checks["staticSurface"] = {"status": "unavailable", "reason": str(exc)}
1382
+
1383
+ checks["action"] = {
1384
+ "requested": action,
1385
+ "executed": False,
1386
+ "reason": "in-memory action dispatch requires a live OUMV runtime",
1387
+ }
1388
+
1389
+ sandbox_note = None
1390
+ if isinstance(sandbox, dict) and sandbox.get("mode"):
1391
+ sandbox_note = {
1392
+ "requested": sandbox.get("mode"),
1393
+ "status": "unavailable offline",
1394
+ "reason": "sandbox rollback runs inside the live runtime's transaction",
1395
+ }
1396
+ not_executed.insert(0, "sandbox rollback")
1397
+
1398
+ if failures:
1399
+ status = "FAILED"
1400
+ hint = "Static checks failed and need no runtime to reproduce; fix them, then re-run verify."
1401
+ elif resolved_file or found_static:
1402
+ status = "PASSED"
1403
+ hint = (
1404
+ "Static checks only. Start the runtime (`tokensafe dev` or `tokensafe run-backend ...`) "
1405
+ "for in-memory dispatch and surface diffs."
1406
+ )
1407
+ else:
1408
+ status = "UNKNOWN"
1409
+ hint = (
1410
+ "Target is not in the static index — that is not proof of absence (dynamic routes, "
1411
+ "generated files). Start the runtime for a real dispatch, or pass a file path."
1412
+ )
1413
+
1414
+ result: Dict[str, Any] = {
1415
+ "status": status,
1416
+ "mode": "OFFLINE_STATIC_VERIFY",
1417
+ "target": raw,
1418
+ "action": action,
1419
+ "checks": checks,
1420
+ "scope": {"checked": checked, "notExecuted": not_executed, "mode": "static"},
1421
+ "requiresRuntime": True,
1422
+ "evidence": {
1423
+ "provenance": "static",
1424
+ "sourceAdapter": "tokensafe-graph-engine",
1425
+ "confidence": "confirmed",
1426
+ },
1427
+ "hint": hint,
1428
+ }
1429
+ if sandbox_note:
1430
+ result["sandbox"] = sandbox_note
1431
+ if failures:
1432
+ result["failures"] = failures
1433
+ return result
1434
+
1220
1435
  # 6. Tool: oumv_graph — unified cross-stack intelligence graph (spec §11)
1221
1436
  @classmethod
1222
1437
  def graph(cls, query: str = "overview", target: Optional[str] = None, workspace_dir: Optional[str] = None) -> Any:
package/src/retrofit.py CHANGED
@@ -11,6 +11,8 @@ import time
11
11
  from pathlib import Path
12
12
  from typing import Dict, Any, List, Optional, Tuple
13
13
 
14
+ from src.backend_release import BACKEND_NPM_VERSION, BACKEND_WIRE_VERSION
15
+
14
16
  # Top-level directories that hold frontend source in a repo-root app (as opposed to
15
17
  # scripts/, tooling/ and configs, which are .ts/.js but not OUMV-observable).
16
18
  _FRONTEND_SOURCE_DIRS = frozenset({
@@ -352,7 +354,10 @@ def detect_project_stack(workspace_dir: str) -> Dict[str, Any]:
352
354
  framework = "flask"
353
355
  elif "starlette" in c:
354
356
  framework = "starlette"
355
- supported = framework in ("fastapi", "starlette")
357
+ # Flask/Django are certified WSGI adapters (65/65, L3 in
358
+ # tokensafe-backend), but they mount explicitly — `tokensafe
359
+ # inject` cannot patch a WSGI host, so their status is manual.
360
+ supported = framework in ("fastapi", "starlette", "flask", "django")
356
361
  py_entry = {
357
362
  "framework": framework,
358
363
  "provider": "fastapi" if framework == "fastapi" else "python",
@@ -361,7 +366,8 @@ def detect_project_stack(workspace_dir: str) -> Dict[str, Any]:
361
366
  "language": "python",
362
367
  "root": os.path.dirname(rel_pf) or ".",
363
368
  "oumv_supported": supported,
364
- "status": "ready" if supported else "planned",
369
+ "status": ("ready" if framework in ("fastapi", "starlette")
370
+ else ("manual" if supported else "planned")),
365
371
  }
366
372
  # A supported Python backend outranks an unsupported Node one,
367
373
  # mirroring the Go precedence rule above.
@@ -804,7 +810,7 @@ def get_adapters_catalog() -> List[Dict[str, Any]]:
804
810
  "technology": {
805
811
  "language": "typescript",
806
812
  "framework": "express | fastify",
807
- "package": {"manager": "npm", "name": "tokensafe-backend-node", "install": "npm install tokensafe-backend-node"},
813
+ "package": {"manager": "npm", "name": "tokensafe-backend-node", "install": f"npm install tokensafe-backend-node@{BACKEND_NPM_VERSION}"},
808
814
  },
809
815
  "capabilities": [
810
816
  {"name": "observe.pulse", "constraints": {"readOnly": True, "developmentOnly": True}},
@@ -830,7 +836,7 @@ def get_adapters_catalog() -> List[Dict[str, Any]]:
830
836
  "technology": {
831
837
  "language": "typescript",
832
838
  "framework": "elysia (bun)",
833
- "package": {"manager": "bun", "name": "tokensafe-backend-node", "install": "bun add tokensafe-backend-node"},
839
+ "package": {"manager": "bun", "name": "tokensafe-backend-node", "install": f"bun add tokensafe-backend-node@{BACKEND_NPM_VERSION}"},
834
840
  },
835
841
  "capabilities": [
836
842
  {"name": "observe.pulse", "constraints": {"readOnly": True, "developmentOnly": True}},
@@ -858,7 +864,7 @@ def get_adapters_catalog() -> List[Dict[str, Any]]:
858
864
  "technology": {
859
865
  "language": "typescript",
860
866
  "framework": "next (app router)",
861
- "package": {"manager": "npm", "name": "tokensafe-backend-node", "install": "npm install --save-dev tokensafe-backend-node"},
867
+ "package": {"manager": "npm", "name": "tokensafe-backend-node", "install": f"npm install --save-dev tokensafe-backend-node@{BACKEND_NPM_VERSION}"},
862
868
  },
863
869
  "capabilities": [
864
870
  {"name": "observe.pulse", "constraints": {"readOnly": True, "developmentOnly": True}},
@@ -882,7 +888,7 @@ def get_adapters_catalog() -> List[Dict[str, Any]]:
882
888
  "repo": "tokensafe-backend/dotnet",
883
889
  "mode": "hybrid",
884
890
  "status": "ready",
885
- "description": "In-process endpoint dispatch for minimal APIs and controllers, Roslyn syntax pre-flight, the full wire 1.6.0 surface (previewEdit, index, query, build, cancel), and verify.sandboxRollback that rolls every auto-discovered EF Core DbContext back",
891
+ "description": f"In-process endpoint dispatch for minimal APIs and controllers, Roslyn syntax pre-flight, the full wire {BACKEND_WIRE_VERSION} surface (previewEdit, index, query, build, cancel), and verify.sandboxRollback that rolls every auto-discovered EF Core DbContext back",
886
892
  "technology": {
887
893
  "language": "csharp",
888
894
  "framework": "aspnetcore",
@@ -991,7 +997,7 @@ def _adapter_presence(workspace_dir: str, profile: str, provider: str, framework
991
997
  return {"installed": True, "evidence": "node_modules/tokensafe-ui"}
992
998
  return {"installed": False, "evidence": "node_modules/tokensafe-ui missing (run: npm install -D tokensafe-ui)"}
993
999
 
994
- if provider == "fastapi":
1000
+ if provider in ("fastapi", "python"):
995
1001
  try:
996
1002
  import importlib.util
997
1003
  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