tokensafe 4.13.2 → 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.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.13.2",
2
+ "version": "4.13.3",
3
3
  "name": "tokensafe",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "author": {
package/README.md CHANGED
@@ -233,11 +233,21 @@ You install TokenSafe, open a project in your agent, and the first turn does the
233
233
  older Next gets the two route files plus a manual snippet. `--revert` deletes
234
234
  exactly the files it created and restores a pre-existing v1 route it upgraded;
235
235
  * Elysia (Bun) — one `app.use(oumv())` line before `app.listen()`
236
- (`tokensafe-backend-node/elysia`), same markers and byte-exact revert.
236
+ (`tokensafe-backend-node/elysia`), same markers and byte-exact revert;
237
+ * Flask / Django — certified WSGI adapters mounted explicitly: `mount_tokensafe(app)` in the
238
+ app factory (wraps `app.wsgi_app`) or `mount_tokensafe(application)` in `wsgi.py`;
239
+ `tokensafe inject --status` prints the recipe and writes nothing, because the WSGI
240
+ application is yours to wrap.
237
241
  3. **Brief the agent** — a short routing block (hook context and MCP `instructions`) says which
238
242
  stack is worked through OUMV and which through the TokenSafe tools. Nothing is written into
239
243
  the repository by the brief.
240
244
 
245
+ Without a live runtime `oumv` stays useful and says what it did: `observe`/`understand`/`index`
246
+ answer from the static graph, `verify` answers a labelled static subset (`OFFLINE_STATIC_VERIFY`:
247
+ file exists, syntax, OCC version, symbol/route presence) instead of failing, and `observe` on a
248
+ file at L1+ returns the same skeleton a read would and seeds the read cache — a later
249
+ `smart_read_file` on that file returns a pointer instead of the body again.
250
+
241
251
  ```bash
242
252
  tokensafe inject --status # what would be wired, and where
243
253
  tokensafe inject --dry-run # same, but explicit
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "4.13.2",
3
+ "version": "4.13.3",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "homepage": "https://tokensafe.dev",
6
6
  "license": "Apache-2.0",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "4.13.2",
4
+ "version": "4.13.3",
5
5
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
6
6
  "main": "bin/tokensafe.js",
7
7
  "bin": {
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "4.13.2",
4
+ "version": "4.13.3",
5
5
  "license": "Apache-2.0",
6
6
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
7
7
  "logo": "assets/logo.png",
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "dev.tokensafe/tokensafe",
4
4
  "title": "TokenSafe",
5
5
  "description": "Your AI agent is smart enough to code all day. Local firewall & zero-loss runtime.",
6
- "version": "4.13.2",
6
+ "version": "4.13.3",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/tokensafe-dev/tokensafe",
@@ -23,7 +23,7 @@
23
23
  "registryType": "npm",
24
24
  "registryBaseUrl": "https://registry.npmjs.org",
25
25
  "identifier": "tokensafe",
26
- "version": "4.13.2",
26
+ "version": "4.13.3",
27
27
  "runtimeHint": "npx",
28
28
  "transport": {
29
29
  "type": "stdio"
@@ -39,7 +39,7 @@
39
39
  "registryType": "pypi",
40
40
  "registryBaseUrl": "https://pypi.org",
41
41
  "identifier": "tokensafe",
42
- "version": "4.13.2",
42
+ "version": "4.13.3",
43
43
  "runtimeHint": "uvx",
44
44
  "transport": {
45
45
  "type": "stdio"
@@ -45,7 +45,7 @@ TOKENSAFE_DIRECTIVES = (
45
45
  "• When context budget reports warning/critical or Grade C/F: call 'tokensafe:session_context(action=\"compact\", transcript_path=...)' to fold history before continuing.\n"
46
46
  "• Prohibited File Edits: NEVER use 'sed -i', 'perl -i', or stream editors to modify source files; ALWAYS use 'edit_file' with exact string targets. NEVER suppress errors with '2>/dev/null'.\n"
47
47
  "• Prefer 'edit_file' over 'write_file' for existing files.\n"
48
- "• Universal OUMV Protocol (Mandatory When Supported): If the workspace reports an OUMV-supported stack (React+Vite, Vue, Solid, Angular, Go, FastAPI, Express/Fastify, Next.js, Elysia on Bun, ASP.NET Core), ALWAYS prefer the 'oumv' MCP tool (status/observe/understand/verify) before full file crawls, raw curl, or browser checks — even when only reading/editing files (static AST OUMV works offline; use 'tokensafe dev' for zero-footprint live Vite RPC). Check capability boundaries in mixed monorepos (for unsupported stacks like backend/node Express/Fastify/Nest, use repo_map/smart_read_file/scoped_search).\n"
48
+ "• Universal OUMV Protocol (Mandatory When Supported): If the workspace reports an OUMV-supported stack (React+Vite, Vue, Solid, Angular, Go/Gin+Chi, FastAPI/Starlette, Express/Fastify, Next.js, Elysia on Bun, Spring Boot, Laravel/Symfony, ASP.NET Core; Flask/Django mount explicitly as WSGI), ALWAYS prefer the 'oumv' MCP tool (status/observe/understand/verify) before full file crawls, raw curl, or browser checks — even when only reading/editing files (static AST OUMV works offline and verify answers a labelled static subset without a runtime; use 'tokensafe dev' for zero-footprint live Vite RPC). Stacks without an adapter (Nest/Hono/Koa, Svelte, Go/Echo) use repo_map/smart_read_file/scoped_search.\n"
49
49
  "• Multi-Root Sessions: the OUMV routing brief is classified PER workspace root (hosts that report several folders get every root listed). A single-root verdict never describes another repo — before editing a repo outside the listed roots, call 'oumv' with workspace_dir='<that repo>'; never conclude 'OUMV is unavailable' from one root's line.\n"
50
50
  "• String Catalogs (i18n): NEVER read a whole messages/<locale>/*.ts catalog, and never spawn one subagent per locale that each re-reads the English files. Run 'tokensafe dict lint --locale <l> --base en' (MCP: run_helper(action='dict', command='lint --locale <l>')) to get only the suspect keys, then patch them with 'tokensafe dict apply --locale <l> --patch patch.json' (add --dry-run first). smart_read_file on a catalog returns a digest by design; 'dict show --keys a.b' returns exact values."
51
51
  )
@@ -51,6 +51,18 @@ mux.Mount("/__oumv/rpc")
51
51
  // oumv "github.com/tokensafe-dev/tokensafe-backend/go/pkg/oumv"
52
52
  // oumvstdhttp "github.com/tokensafe-dev/tokensafe-backend/go/pkg/adapters/stdhttp"'''
53
53
 
54
+ # WSGI hosts (Flask, Django) are certified adapters but mount explicitly: the
55
+ # adapter wraps the WSGI application, so there is no app factory or mux line to
56
+ # patch safely. The plan shows the recipe and apply() writes nothing.
57
+ _PY_MANUAL_SNIPPETS = {
58
+ "flask": '''# in the app factory, after `app = Flask(__name__)`
59
+ from tokensafe_python.adapters.flask import mount_tokensafe
60
+ mount_tokensafe(app) # wraps app.wsgi_app; routes come from app.url_map''',
61
+ "django": '''# in <project>/wsgi.py, after `application = get_wsgi_application()`
62
+ from tokensafe_python.adapters.django import mount_tokensafe
63
+ application = mount_tokensafe(application)''',
64
+ }
65
+
54
66
  _GO_ADAPTERS = {
55
67
  "gin": (
56
68
  "oumvgin",
@@ -2216,7 +2228,21 @@ def plan(workspace: str) -> Dict[str, Any]:
2216
2228
  continue
2217
2229
 
2218
2230
  install = _backend_install(catalog, provider)
2219
- if provider in ("fastapi", "python") and framework in ("fastapi", "starlette"):
2231
+ if provider in ("fastapi", "python") and framework in ("flask", "django"):
2232
+ actions.append({
2233
+ "kind": "python_manual_mount",
2234
+ "profile": "backend",
2235
+ "app": root,
2236
+ "framework": framework,
2237
+ "writes_repo": False,
2238
+ "status": "manual",
2239
+ "snippet": _PY_MANUAL_SNIPPETS[framework],
2240
+ "reason": info.get("note") or (
2241
+ "WSGI host: the adapter wraps the WSGI application, so inject cannot patch it"
2242
+ ),
2243
+ "install": install,
2244
+ })
2245
+ elif provider in ("fastapi", "python") and framework in ("fastapi", "starlette"):
2220
2246
  actions.append({
2221
2247
  "kind": "python_autoload",
2222
2248
  "profile": "backend",
@@ -2389,6 +2415,19 @@ def apply(workspace: str, dry_run: bool = False, include_go: bool = True) -> Dic
2389
2415
  })
2390
2416
  continue
2391
2417
 
2418
+ if provider in ("fastapi", "python") and framework in ("flask", "django"):
2419
+ results["actions"].append({
2420
+ "kind": "python_manual_mount",
2421
+ "profile": "backend",
2422
+ "app": root,
2423
+ "status": "manual",
2424
+ "framework": framework,
2425
+ "writes_repo": False,
2426
+ "snippet": _PY_MANUAL_SNIPPETS[framework],
2427
+ "reason": "WSGI host: mount_tokensafe() wraps the WSGI application; inject writes nothing",
2428
+ })
2429
+ continue
2430
+
2392
2431
  if provider in ("fastapi", "python") and framework in ("fastapi", "starlette"):
2393
2432
  if dry_run:
2394
2433
  action = {
@@ -117,7 +117,7 @@ class PromptCacheNormalizer:
117
117
  re.compile(r"Generated locally at \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}", re.IGNORECASE),
118
118
  re.compile(r"⚡ \*\*TokenSafe Turn Savings\*\*:.*?(?=\n|$)", re.IGNORECASE),
119
119
  re.compile(r"\(TokenSafe: compacted ~?\d[\d,]* prompt tokens.*?\)", re.IGNORECASE),
120
- re.compile(r"\[TokenSafe: Pointer Hit .*?\]", re.IGNORECASE),
120
+ re.compile(r"\[TokenSafe(?: Subagent Firewall)?: Pointer Hit .*?\]", re.IGNORECASE),
121
121
  re.compile(r"Community Edition limit reached.*?(?=\n|$)", re.IGNORECASE),
122
122
  ]
123
123
 
package/src/cli.py CHANGED
@@ -866,6 +866,10 @@ def main(argv: Optional[List[str]] = None):
866
866
  print(f" run: {action['run']}")
867
867
  if action.get("reason"):
868
868
  print(f" reason: {action['reason']}")
869
+ if action.get("snippet"):
870
+ print(" snippet:")
871
+ for line in action["snippet"].splitlines():
872
+ print(f" {line}")
869
873
  print()
870
874
 
871
875
  elif command in ("adapters", "adapter"):
@@ -2626,6 +2626,25 @@ class GraphEngine:
2626
2626
  # graph instead of stacking a second crawl behind it.
2627
2627
  return graph
2628
2628
 
2629
+ @classmethod
2630
+ def get_cached(cls, root_dir: str = ".") -> Optional[CodeGraph]:
2631
+ """Warm instance or the on-disk index — never starts a repository crawl.
2632
+
2633
+ ``scoped_search`` used to deserialize the graph SQLite cache twice per
2634
+ identifier query and never saw the instance ``oumv index``/``observe``
2635
+ had already warmed. Returns None when no index exists for this root.
2636
+ """
2637
+ root_abs = os.path.abspath(root_dir)
2638
+ with cls._instances_lock:
2639
+ graph = cls._instances.get(root_abs)
2640
+ if graph is not None:
2641
+ return graph
2642
+ try:
2643
+ graph = CodeGraph(root_abs, use_disk_cache=True)
2644
+ except Exception:
2645
+ return None
2646
+ return graph if graph.symbols else None
2647
+
2629
2648
  @classmethod
2630
2649
  def warm_async(cls, root_dir: str = ".") -> bool:
2631
2650
  """Starts one background crawl per root so the first graph tool call is warm.
package/src/installer.py CHANGED
@@ -60,10 +60,10 @@ UNIFIED_TOKENSAFE_RULE = (
60
60
  "`🛡️ **TokenSafe Security Guard**: Prevented secret / private key leak into git (<target_file>: <details>)`\n"
61
61
  "11. **Proof-of-Savings Turn Footer (strictly English)**: Append on tool-using turns:\n"
62
62
  "`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown in English>) | Cumulative Total: <total> tokens (≈$<usd> approx)`\n"
63
- "12. **Universal OUMV Protocol (`oumv`)**: When a workspace profile is OUMV-supported (React+Vite, Vue, Solid, Angular, Go, FastAPI, Express/Fastify, Next.js, Elysia on Bun, ASP.NET Core), "
63
+ "12. **Universal OUMV Protocol (`oumv`)**: When a workspace profile is OUMV-supported (React+Vite, Vue, Solid, Angular, Go/Gin+Chi, FastAPI/Starlette, Express/Fastify, Next.js, Elysia on Bun, Spring Boot, Laravel/Symfony, ASP.NET Core; Flask/Django mount explicitly as WSGI), "
64
64
  "ALWAYS prefer `tokensafe:oumv(action='status'|'observe'|'understand'|'verify'|'mutate'|'graph', ...)` BEFORE full file crawls, raw curls, or browser checks — "
65
- "static OUMV works offline on read/edit tasks too, and `tokensafe dev` starts zero-footprint live Vite RPC without touching repo files. "
66
- "In mixed monorepos (e.g. React + Node.js), use `oumv` on supported profiles and `repo_map`/`smart_read_file`/`scoped_search` on unsupported stacks (e.g. `backend/node`).\n"
65
+ "static OUMV works offline on read/edit tasks too (verify answers a labelled static subset without a runtime), and `tokensafe dev` starts zero-footprint live Vite RPC without touching repo files. "
66
+ "In mixed monorepos use `oumv` on supported profiles and `repo_map`/`smart_read_file`/`scoped_search` on stacks without an adapter (Nest/Hono/Koa, Svelte, Go/Echo).\n"
67
67
  "13. **String Catalogs (`dict`)**: NEVER read a whole i18n catalog (`messages/<locale>/*.ts`, `locales/*.json`) to review or edit translations. A catalog is 100% payload, so reading 18 files per locale is the most expensive way to work, and fanning out one subagent per locale that each re-reads the English oracle multiplies it. Start with `tokensafe:run_helper(action='dict', command='lint --locale <l> --base en --json')` (CLI: `tokensafe dict lint --locale <l>`), which returns only suspect keys: untranslated, missing, orphan, placeholder drift, English leakage, brand loss. Patch with `dict apply --locale <l> --patch patch.json`, after `--dry-run`: it writes byte-preserving edits. `smart_read_file` on a catalog returns a digest on purpose; `dict show --keys a.b` returns exact values.\n"
68
68
  )
69
69
 
@@ -76,7 +76,7 @@ POINTER_RULE = (
76
76
  "(~/.zcode/AGENTS.md, ~/.claude/CLAUDE.md, ~/.codex/AGENTS.md, ~/.kimi-code/AGENTS.md) and applies to this project. "
77
77
  "Core tools: `tokensafe:repo_map(view='graph'|'api'|'tree')` for architecture & directory trees, "
78
78
  "`tokensafe:scoped_search` (single or `queries` batch, never raw grep/find), `tokensafe:smart_read_file` (symbol, `targets` bundle, or `.d.ts` `package_name`), "
79
- "`tokensafe:apply_edits` for multi-file edits, `tokensafe:oumv` (MANDATORY first on OUMV-supported React/Vue/Go/FastAPI stacks — live or static offline; check `status` in mixed monorepos), "
79
+ "`tokensafe:apply_edits` for multi-file edits, `tokensafe:oumv` (MANDATORY first on OUMV-supported React/Vue/Solid/Angular/Next, Go/Gin+Chi, FastAPI/Starlette/Flask/Django, Express/Fastify/Elysia, Spring/Laravel, ASP.NET Core — live or static offline; check `status` in mixed monorepos), "
80
80
  "`tokensafe:session_context(action='budget'|'compact'|'prune'|'mistakes')` for context & anti-stuck hygiene, and "
81
81
  "`tokensafe:run_helper(action='sanitize'|'guard'|'diff'|'deps'|'web'|'expand'|'image'|'compress'|'dict')` "
82
82
  "(string catalogs: `dict lint --locale <l>`, then `dict apply`, never read whole catalogs); "
package/src/mcp_server.py CHANGED
@@ -46,7 +46,7 @@ from src.session_context import current_root, current_session_id
46
46
 
47
47
  SERVER_INFO = {
48
48
  "name": "tokensafe-mcp",
49
- "version": "4.13.2"
49
+ "version": "4.13.3"
50
50
  }
51
51
 
52
52
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -548,7 +548,8 @@ FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
548
548
  { 'annotations': {'readOnlyHint': True},
549
549
  'description': 'Instantly verifies actions in memory (UI synthetic actions, React reducers/Zustand/Redux '
550
550
  'actions, Context updaters, or Backend transactional sandbox) with structured state and surface '
551
- 'diffs.',
551
+ 'diffs. Without a live runtime it answers a labelled static subset instead of failing: file '
552
+ 'existence, syntax, OCC version, and symbol/route presence (mode OFFLINE_STATIC_VERIFY).',
552
553
  'inputSchema': { 'properties': { 'action': { 'default': 'invoke',
553
554
  'description': 'Action name (invoke, click, submit, or '
554
555
  'store action)',
@@ -865,12 +866,15 @@ TOOLS = [{'name': 'smart_read_file',
865
866
  'transcript_path': {'type': 'string'}}}},
866
867
  {'name': 'oumv',
867
868
  'annotations': {'readOnlyHint': False},
868
- 'description': "OUMV runtime: 'status'|'observe' L0-L4|'brief' (skeleton + call sites + props + module "
869
- "state in one call)|'understand'|'verify'|'mutate' (OCC edit)|'graph'|'index' "
870
- "(repo-wide symbol search: query, kinds?, limit?)|'preview' (dry-run diff, no write)|'build' "
871
- "(run the runtime's build/test command, §14.3)|'cancel' (cooperative, by requestId). "
872
- "Observation is free on every plan; the write actions (verify, mutate, preview, build) "
873
- "need Solo or higher and are refused with a read-only notice on guest/free.",
869
+ 'description': "Call this FIRST on an OUMV-supported stack: status/brief/observe before grep or full-file "
870
+ "reads. OUMV runtime: 'status'|'observe' L0-L4 (a file target at L1+ returns the same skeleton a "
871
+ "read would and seeds the read cache: a later smart_read_file returns a pointer)|'brief' (skeleton + "
872
+ "call sites + props + module state in one call)|'understand'|'verify'|'mutate' (OCC edit)|'graph'|"
873
+ "'index' (repo-wide symbol search: query, kinds?, limit?)|'preview' (dry-run diff, no write)|'build' "
874
+ "(run the runtime's build/test command, §14.3)|'cancel' (cooperative, by requestId). Offline the "
875
+ "static graph answers observe/understand/index and a labelled verify subset (exists/syntax/OCC/"
876
+ "symbol/route presence). Observation is free on every plan; the write actions (verify, mutate, "
877
+ "preview, build) need Solo or higher and are refused with a read-only notice on guest/free.",
874
878
  'inputSchema': {'type': 'object',
875
879
  'properties': {'action': {'type': 'string',
876
880
  'enum': ['status',
@@ -904,8 +908,13 @@ TOOLS = [{'name': 'smart_read_file',
904
908
  'description': 'preview: batch edits envelope (wire 1.5.0+)'},
905
909
  'timeout_ms': {'type': 'integer',
906
910
  'description': 'preview/build: per-call budget (§3/§14.3)'},
907
- 'verify_action': {'type': 'string'},
908
- 'payload': {'type': 'object'},
911
+ 'verify_action': {'type': 'string',
912
+ 'enum': ['invoke', 'click', 'submit'],
913
+ 'description': 'verify: action kind to verify (default invoke)'},
914
+ 'payload': {'type': 'object',
915
+ 'description': 'verify: request body/action payload; may carry '
916
+ "expectedVersion and symbol for the offline static "
917
+ 'checks'},
909
918
  'requestId': {'type': 'string',
910
919
  'description': 'cancel: the requestId echoed by the target call'},
911
920
  'workspace_dir': {'type': 'string',
@@ -1246,9 +1255,10 @@ _GRAPH_TOOLS = {
1246
1255
  }
1247
1256
 
1248
1257
 
1249
- def _fallback_error(tool_name: str, reason: str) -> dict:
1258
+ def _fallback_error(tool_name: str, reason: str, hint: str = "") -> dict:
1250
1259
  """Returns a non-blocking, actionable error telling the AI model to try another approach."""
1251
1260
  clean_reason = (reason or "unknown error").strip()
1261
+ tail = f" Hint: {hint.strip()}" if hint and hint.strip() else ""
1252
1262
  return {
1253
1263
  "isError": True,
1254
1264
  "content": [{
@@ -1258,6 +1268,7 @@ def _fallback_error(tool_name: str, reason: str) -> dict:
1258
1268
  "Try an alternative approach instead of repeating this exact call: "
1259
1269
  "narrow the target 'path'/'project_path' or 'depth', inspect a specific file with 'smart_read_file', "
1260
1270
  "or fall back to standard 'read_file' / bounded 'run_command'."
1271
+ + tail
1261
1272
  )
1262
1273
  }]
1263
1274
  }
@@ -1932,6 +1943,82 @@ def _repo_fingerprint(graph) -> str:
1932
1943
  return h.hexdigest()[:40]
1933
1944
 
1934
1945
 
1946
+ def _default_read_text(abs_path: str):
1947
+ """Render the symbol-less read: AST skeleton, else bounded raw text.
1948
+
1949
+ Returns (text, original_tokens, skeleton_tokens, source) with source being
1950
+ "skeleton" or "raw". `oumv observe` calls this too, so the text it delivers
1951
+ (and seeds into the read cache) is byte-identical to a real read.
1952
+ """
1953
+ try:
1954
+ skel_path, orig_t, skel_t = Skeletonizer.get_skeleton_file(abs_path, target_symbol=None)
1955
+ if skel_path and os.path.exists(skel_path):
1956
+ with open(skel_path, "r", encoding="utf-8", errors="replace") as f:
1957
+ return f.read(), orig_t, skel_t, "skeleton"
1958
+ except Exception:
1959
+ pass
1960
+ try:
1961
+ size = os.path.getsize(abs_path)
1962
+ except OSError:
1963
+ return "", 0, 0, "raw"
1964
+ try:
1965
+ prefetch_block, _ = DependencyPrefetcher.prefetch_for_file(abs_path)
1966
+ except Exception:
1967
+ prefetch_block = ""
1968
+ max_raw_bytes = 512 * 1024
1969
+ with open(abs_path, "r", encoding="utf-8", errors="replace") as f:
1970
+ content = f.read(max_raw_bytes) if size > max_raw_bytes else f.read()
1971
+ if size > max_raw_bytes:
1972
+ content += f"\n// [TokenSafe: file truncated at 512KB ({size:,} bytes total). Use start_line/end_line or symbol to inspect specific sections.]\n"
1973
+ return (prefetch_block or "") + content, 0, 0, "raw"
1974
+
1975
+
1976
+ def _observe_seed_read_cache(res, level, target, path_arg, workspace_dir) -> None:
1977
+ """Hand the file text `oumv observe` just delivered to the read cache.
1978
+
1979
+ A pointer is only honest when the content reached the model: observe attaches
1980
+ the same skeleton a read would return (``file.skeleton``), records it in the
1981
+ firewall cache and marks it delivered. A later `smart_read_file(path)` then
1982
+ answers with a ~40-token pointer instead of the body. L0 stays a pulse.
1983
+ """
1984
+ if not isinstance(res, dict) or str(level or "").upper() == "L0":
1985
+ return
1986
+ if res.get("targetKind") != "file" or not res.get("targetResolved"):
1987
+ return
1988
+ ws = workspace_dir or _oumv_default_workspace() or os.getcwd()
1989
+ candidates = []
1990
+ for raw in (target, path_arg):
1991
+ raw = str(raw or "").strip()
1992
+ if raw:
1993
+ candidates.append(raw if os.path.isabs(raw) else os.path.join(ws, raw))
1994
+ file_info = res.get("file") or {}
1995
+ rel = str(file_info.get("path") or "").strip()
1996
+ if rel:
1997
+ candidates.append(rel if os.path.isabs(rel) else os.path.join(ws, rel))
1998
+ abs_path = next((os.path.abspath(c) for c in candidates if c and os.path.isfile(c)), None)
1999
+ if not abs_path:
2000
+ return
2001
+ content, _orig_t, _skel_t, source = _default_read_text(abs_path)
2002
+ if not content or len(content) > AgentFirewall._MAX_CONTENT_CHARS:
2003
+ return
2004
+ file_info = res.setdefault("file", {})
2005
+ file_info["skeleton"] = content
2006
+ file_info["skeletonSource"] = source
2007
+ cur_hash = AgentFirewall._file_content_hash(abs_path)
2008
+ if cur_hash:
2009
+ _IN_PROCESS_DELIVERED[(abs_path, "", "signature")] = (cur_hash, _EPOCH_GEN)
2010
+ try:
2011
+ AgentFirewall.record_cache(
2012
+ session_id=_mcp_session_id(),
2013
+ file_path=abs_path,
2014
+ content=content,
2015
+ symbol="",
2016
+ tracker=_get_safe_tracker(),
2017
+ )
2018
+ except Exception:
2019
+ pass
2020
+
2021
+
1935
2022
  def handle_tool_call(name: str, args: dict) -> dict:
1936
2023
  if args is None or not isinstance(args, dict):
1937
2024
  args = {}
@@ -2555,32 +2642,19 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2555
2642
  header = f"// [TOCP Targeted Window: lines {s_line}-{e_line} for '{symbol}']\n"
2556
2643
  return {"content": [{"type": "text", "text": (prefetch_block or "") + header + (content or "")}]}
2557
2644
 
2558
- # Check AST skeleton (preserves target_symbol body when symbol was given; avoids duplicate prefetch)
2559
- skel_path, orig_t, skel_t = Skeletonizer.get_skeleton_file(path, target_symbol=(symbol or None))
2560
- if skel_path and os.path.exists(skel_path):
2561
- with open(skel_path, "r", encoding="utf-8", errors="replace") as f:
2562
- content = f.read()
2563
- if orig_t > skel_t:
2564
- tracker.record_event(
2565
- session_id=_mcp_session_id(),
2566
- event_type="AST_SKELETON",
2567
- original_tokens=orig_t,
2568
- optimized_tokens=skel_t,
2569
- details={"target_file": os.path.basename(path), "saved_tokens": orig_t - skel_t}
2570
- )
2571
- return {"content": [{"type": "text", "text": content}]}
2572
-
2573
- # Default bounded read (avoid dumping multi-MB files raw)
2574
- prefetch_block, _ = DependencyPrefetcher.prefetch_for_file(path)
2575
- max_raw_bytes = 512 * 1024
2576
- if st.st_size > max_raw_bytes:
2577
- with open(path, "r", encoding="utf-8", errors="replace") as f:
2578
- content = f.read(max_raw_bytes)
2579
- content += f"\n// [TokenSafe: file truncated at 512KB ({st.st_size:,} bytes total). Use start_line/end_line or symbol to inspect specific sections.]\n"
2580
- else:
2581
- with open(path, "r", encoding="utf-8", errors="replace") as f:
2582
- content = f.read()
2583
- return {"content": [{"type": "text", "text": (prefetch_block or "") + content}]}
2645
+ # AST skeleton or bounded raw, rendered by the same helper `oumv observe`
2646
+ # uses to seed the read cache — one renderer means a pointer always refers
2647
+ # to text the model actually received.
2648
+ content, orig_t, skel_t, source = _default_read_text(path)
2649
+ if source == "skeleton" and orig_t > skel_t:
2650
+ tracker.record_event(
2651
+ session_id=_mcp_session_id(),
2652
+ event_type="AST_SKELETON",
2653
+ original_tokens=orig_t,
2654
+ optimized_tokens=skel_t,
2655
+ details={"target_file": os.path.basename(path), "saved_tokens": orig_t - skel_t}
2656
+ )
2657
+ return {"content": [{"type": "text", "text": content}]}
2584
2658
 
2585
2659
  elif name == "smart_bundle":
2586
2660
  targets = args.get("targets")
@@ -3586,6 +3660,10 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3586
3660
  if ws_err:
3587
3661
  return _fallback_error("oumv_observe", ws_err)
3588
3662
  res = OUMVGateway.observe(level=lvl, target=tgt, runtime=rt, workspace_dir=ws, path=raw_path)
3663
+ try:
3664
+ _observe_seed_read_cache(res, lvl, tgt, raw_path, ws)
3665
+ except Exception:
3666
+ pass
3589
3667
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
3590
3668
  except Exception as e:
3591
3669
  return _fallback_error("oumv_observe", f"failed to observe OUMV runtime: {e}")
@@ -3649,7 +3727,15 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3649
3727
  res = OUMVGateway.verify(target=tgt, action=act, payload=payload, runtime=rt, workspace_dir=ws, sandbox=sandbox)
3650
3728
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
3651
3729
  except Exception as e:
3652
- return _fallback_error("oumv_verify", f"failed to verify OUMV action: {e}")
3730
+ return _fallback_error(
3731
+ "oumv_verify",
3732
+ f"failed to verify OUMV action: {e}",
3733
+ hint=(
3734
+ "static verify answers without a live runtime (file exists, syntax, OCC version, "
3735
+ "symbol/route presence); if this errored, call oumv(action='verify', target=<file or route>) "
3736
+ "again or use oumv(action='observe', path=<file>) for the static surface."
3737
+ ),
3738
+ )
3653
3739
 
3654
3740
  elif name == "oumv_graph":
3655
3741
  try:
@@ -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.2"
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.2"
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