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.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.13.1",
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.1",
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.1",
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.1",
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.1",
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.1",
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.1",
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",
@@ -267,11 +279,21 @@ def _config_state_path(workspace: str) -> str:
267
279
  def _write_config_state(workspace: str, path: str, created: bool) -> None:
268
280
  state_path = _config_state_path(workspace)
269
281
  os.makedirs(os.path.dirname(state_path), exist_ok=True)
270
- payload = {
271
- "path": path,
272
- "created": bool(created),
273
- "sha": _sha256_file(path) if created and path and os.path.isfile(path) else None,
274
- }
282
+ previous: Dict[str, Any] = {}
283
+ if os.path.isfile(state_path):
284
+ try:
285
+ with open(state_path, "r", encoding="utf-8") as handle:
286
+ previous = json.load(handle)
287
+ except Exception:
288
+ previous = {}
289
+ owned = bool(created)
290
+ sha = _sha256_file(path) if created and path and os.path.isfile(path) else None
291
+ # A second `inject` sees the file it created and would otherwise record
292
+ # `created: false`, leaving the config behind after --revert.
293
+ if not owned and previous.get("created") and previous.get("path") == path:
294
+ owned = True
295
+ sha = previous.get("sha") or (_sha256_file(path) if path and os.path.isfile(path) else None)
296
+ payload = {"path": path, "created": owned, "sha": sha}
275
297
  with open(state_path, "w", encoding="utf-8") as handle:
276
298
  json.dump(payload, handle, indent=2)
277
299
 
@@ -605,11 +627,6 @@ def apply_go_patch(workspace: str, dry_run: bool = False, root: str = ".") -> Di
605
627
  "snippet": _GO_MANUAL_SNIPPET,
606
628
  }
607
629
 
608
- if not dry_run:
609
- dep_error = _ensure_go_dependency(root_dir)
610
- if dep_error:
611
- return {"status": "skipped", "reason": dep_error}
612
-
613
630
  with open(path, "r", encoding="utf-8") as f:
614
631
  original = f.read()
615
632
 
@@ -661,7 +678,7 @@ def apply_go_patch(workspace: str, dry_run: bool = False, root: str = ".") -> Di
661
678
  backup_path = _backup_path(workspace, path)
662
679
  os.makedirs(os.path.dirname(backup_path), exist_ok=True)
663
680
  shutil.copy2(path, backup_path)
664
- module_backups: List[Dict[str, str]] = []
681
+ module_backups: List[Dict[str, Any]] = []
665
682
  for mod_file in ("go.mod", "go.sum"):
666
683
  src = os.path.join(root_dir, mod_file)
667
684
  if os.path.isfile(src):
@@ -672,7 +689,24 @@ def apply_go_patch(workspace: str, dry_run: bool = False, root: str = ".") -> Di
672
689
  "path": src,
673
690
  "backup": dst,
674
691
  "before_sha": _sha256_file(src),
692
+ "created": False,
675
693
  })
694
+ else:
695
+ # `go get` may create go.sum; revert must remove it, not leave it.
696
+ module_backups.append({"path": src, "backup": None, "before_sha": None, "created": True})
697
+
698
+ # The dependency must be added *after* the backups: `go get` rewrites
699
+ # go.mod/go.sum, and a backup taken afterwards would restore the dependency
700
+ # instead of the pre-inject bytes.
701
+ dep_error = _ensure_go_dependency(root_dir)
702
+ if dep_error:
703
+ if os.path.isfile(backup_path):
704
+ os.unlink(backup_path)
705
+ for module in module_backups:
706
+ backup = module.get("backup")
707
+ if backup and os.path.isfile(backup):
708
+ os.unlink(backup)
709
+ return {"status": "skipped", "reason": dep_error}
676
710
 
677
711
  with open(path, "w", encoding="utf-8") as f:
678
712
  f.write(patched)
@@ -682,7 +716,11 @@ def apply_go_patch(workspace: str, dry_run: bool = False, root: str = ".") -> Di
682
716
  if not build_ok:
683
717
  shutil.copy2(backup_path, path)
684
718
  for module in module_backups:
685
- shutil.copy2(module["backup"], module["path"])
719
+ if module.get("created"):
720
+ if os.path.isfile(module["path"]):
721
+ os.remove(module["path"])
722
+ elif module.get("backup"):
723
+ shutil.copy2(module["backup"], module["path"])
686
724
  first_error = next((line for line in build_output.splitlines() if line.strip()), "")
687
725
  return {
688
726
  "status": "reverted",
@@ -692,7 +730,8 @@ def apply_go_patch(workspace: str, dry_run: bool = False, root: str = ".") -> Di
692
730
  }
693
731
 
694
732
  for module in module_backups:
695
- module["after_sha"] = _sha256_file(module["path"])
733
+ if os.path.isfile(module["path"]):
734
+ module["after_sha"] = _sha256_file(module["path"])
696
735
  _write_manifest(workspace, "go", {
697
736
  "kind": "go",
698
737
  "app": root,
@@ -746,6 +785,16 @@ def revert_go_patch(
746
785
  for module in manifest.get("modules") or []:
747
786
  path, module_backup = module.get("path"), module.get("backup")
748
787
  after = module.get("after_sha")
788
+ if module.get("created"):
789
+ if not path or not os.path.isfile(path):
790
+ modules.append({"path": path or "?", "status": "absent"})
791
+ continue
792
+ if after and _sha256_file(path) != after:
793
+ modules.append({"path": os.path.relpath(path, workspace), "status": "modules_modified"})
794
+ continue
795
+ os.remove(path)
796
+ modules.append({"path": os.path.relpath(path, workspace), "status": "removed"})
797
+ continue
749
798
  if not (path and module_backup and os.path.isfile(module_backup)):
750
799
  modules.append({"path": path or "?", "status": "backup-missing"})
751
800
  continue
@@ -1979,6 +2028,7 @@ def ensure_sidecar(kind: str) -> Tuple[Optional[str], str]:
1979
2028
  os.path.join(here, "..", "tokensafe-backend"),
1980
2029
  ]
1981
2030
  local_mismatch = None
2031
+ explicit_mismatch = None
1982
2032
  for repo in repo_candidates:
1983
2033
  candidate = os.path.join(os.path.abspath(repo), rel_source)
1984
2034
  if not os.path.isfile(candidate):
@@ -1986,10 +2036,12 @@ def ensure_sidecar(kind: str) -> Tuple[Optional[str], str]:
1986
2036
  if _sha256_file(candidate) == expected_sha:
1987
2037
  return adopt(candidate, f"cached from local checkout matching {_SIDECAR_RELEASE_TAG}")
1988
2038
  local_mismatch = candidate
2039
+ if explicit_repo and os.path.abspath(repo) == os.path.abspath(env_repo):
2040
+ explicit_mismatch = candidate
1989
2041
 
1990
2042
  def explicit_unpinned(note: str) -> Tuple[Optional[str], str]:
1991
- if explicit_repo and local_mismatch:
1992
- return adopt(local_mismatch, f"unpinned (OUMV_BACKEND_REPO): {local_mismatch}")
2043
+ if explicit_repo and explicit_mismatch:
2044
+ return adopt(explicit_mismatch, f"unpinned (OUMV_BACKEND_REPO): {explicit_mismatch}")
1993
2045
  return None, note
1994
2046
 
1995
2047
  if os.environ.get("TOKENSAFE_SIDECAR_OFFLINE") == "1":
@@ -2176,7 +2228,21 @@ def plan(workspace: str) -> Dict[str, Any]:
2176
2228
  continue
2177
2229
 
2178
2230
  install = _backend_install(catalog, provider)
2179
- 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"):
2180
2246
  actions.append({
2181
2247
  "kind": "python_autoload",
2182
2248
  "profile": "backend",
@@ -2349,6 +2415,19 @@ def apply(workspace: str, dry_run: bool = False, include_go: bool = True) -> Dic
2349
2415
  })
2350
2416
  continue
2351
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
+
2352
2431
  if provider in ("fastapi", "python") and framework in ("fastapi", "starlette"):
2353
2432
  if dry_run:
2354
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.1"
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: