tokensafe 3.1.1 → 3.1.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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "3.1.1",
4
+ "version": "3.1.3",
5
5
  "description": "Reduce your AI bills by up to 99% locally. Your agents read only needed code, keep prompt caches intact across turns, and keep secrets out of git.",
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": "3.1.1",
4
+ "version": "3.1.3",
5
5
  "description": "Reduce your AI bills by up to 99% locally. Your agents read only needed code, keep prompt caches intact across turns, and keep secrets out of git.",
6
6
  "logo": "assets/logo.svg",
7
7
  "author": {
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "dev.tokensafe/tokensafe",
4
4
  "title": "TokenSafe",
5
5
  "description": "Reduce your AI bills by up to 99% locally: focused code, warm prompt caches & zero secret leaks.",
6
- "version": "3.1.1",
6
+ "version": "3.1.3",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/tokensafe-dev/tokensafe",
@@ -30,7 +30,7 @@
30
30
  "registryType": "npm",
31
31
  "registryBaseUrl": "https://registry.npmjs.org",
32
32
  "identifier": "tokensafe",
33
- "version": "3.1.1",
33
+ "version": "3.1.3",
34
34
  "runtimeHint": "npx",
35
35
  "transport": {
36
36
  "type": "stdio"
@@ -46,7 +46,7 @@
46
46
  "registryType": "pypi",
47
47
  "registryBaseUrl": "https://pypi.org",
48
48
  "identifier": "tokensafe",
49
- "version": "3.1.1",
49
+ "version": "3.1.3",
50
50
  "runtimeHint": "uvx",
51
51
  "transport": {
52
52
  "type": "stdio"
@@ -134,10 +134,13 @@ class RealRepoBenchmark:
134
134
  def __init__(self, registry: Optional[Dict[str, Any]] = None):
135
135
  self.reg = registry or load_registry()
136
136
  self.pricing = self.reg.get("pricing", PUBLISHED_PIN)
137
+ # Clone destination; the QA sweep (bench_sweep.py) redirects this to its
138
+ # own cache dir without touching the published benchmark's cache.
139
+ self.repos_dir = REPOS_DIR
137
140
 
138
141
  # -- repo cache ------------------------------------------------------
139
142
  def ensure_repo(self, repo: Dict[str, Any]) -> str:
140
- dest = os.path.join(REPOS_DIR, repo["key"])
143
+ dest = os.path.join(self.repos_dir, repo["key"])
141
144
  depth = str(repo.get("clone_depth", 1))
142
145
  if os.path.isdir(os.path.join(dest, ".git")):
143
146
  subprocess.run(["git", "fetch", "--depth", depth, "origin"], cwd=dest,
@@ -145,7 +148,7 @@ class RealRepoBenchmark:
145
148
  subprocess.run(["git", "reset", "--hard", "-q", "origin/HEAD"], cwd=dest,
146
149
  capture_output=True, timeout=60)
147
150
  else:
148
- os.makedirs(REPOS_DIR, exist_ok=True)
151
+ os.makedirs(self.repos_dir, exist_ok=True)
149
152
  subprocess.run(["git", "clone", "--depth", depth, "-q", repo["url"], dest],
150
153
  capture_output=True, timeout=600, check=True)
151
154
  return dest
@@ -214,7 +217,7 @@ class RealRepoBenchmark:
214
217
  targets.append("tests/")
215
218
  proc = subprocess.run(
216
219
  [venv_py, "-m", "pytest", *targets, "-q", "--tb=long", "--no-header", "-p", "no:cacheprovider"],
217
- cwd=repo_root, capture_output=True, text=True, timeout=300,
220
+ cwd=repo_root, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=300,
218
221
  )
219
222
  raw = (proc.stdout or "") + (proc.stderr or "")
220
223
  if not raw.strip():
@@ -297,14 +300,33 @@ class RealRepoBenchmark:
297
300
  if importlib.util.find_spec("pytest") is None:
298
301
  return {"status": "skipped", "reason": "pytest not installed"}
299
302
  py = sys.executable
303
+ # Local mode runs the suite AS-IS (no injected regression, no deps venv).
304
+ targets = ["tests/"]
300
305
  py_args = [py, "-m", "pytest"]
301
- if any(d.startswith("pytest-asyncio") for d in pytest_cfg.get("deps", [])):
302
- # pytest-asyncio >=0.24 emits a deprecation warning that repos running
303
- # with filterwarnings=error (fastapi) escalate into INTERNALERROR.
304
- py_args += ["-o", "asyncio_default_fixture_loop_scope=function"]
306
+ # pytest-asyncio >=0.24 emits a deprecation warning that repos running
307
+ # with filterwarnings=error (fastapi) escalate into INTERNALERROR. The
308
+ # published path knows the deps from the registry; local mode infers
309
+ # asyncio usage from the repo's own pytest config and only applies the
310
+ # override when pytest-asyncio is importable in the chosen interpreter.
311
+ asyncio_hint = False
312
+ for cfg_name in ("pytest.ini", "pyproject.toml", "setup.cfg", "tox.ini"):
313
+ cfg_path = os.path.join(root, cfg_name)
314
+ if os.path.isfile(cfg_path):
315
+ try:
316
+ with open(cfg_path, "r", encoding="utf-8", errors="replace") as f:
317
+ if "asyncio" in f.read():
318
+ asyncio_hint = True
319
+ break
320
+ except Exception:
321
+ pass
322
+ if asyncio_hint:
323
+ probe = subprocess.run([py, "-c", "import pytest_asyncio"],
324
+ capture_output=True, timeout=30)
325
+ if probe.returncode == 0:
326
+ py_args += ["-o", "asyncio_default_fixture_loop_scope=function"]
305
327
  py_args += [*targets, "-q", "--tb=long", "--no-header", "-p", "no:cacheprovider"]
306
328
  try:
307
- proc = subprocess.run(py_args, cwd=repo_root, capture_output=True, text=True, timeout=300)
329
+ proc = subprocess.run(py_args, cwd=root, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=300)
308
330
  except subprocess.TimeoutExpired:
309
331
  return {"status": "skipped", "reason": "pytest timeout 300s"}
310
332
  raw = (proc.stdout or "") + (proc.stderr or "")
@@ -436,9 +458,17 @@ class RealRepoBenchmark:
436
458
  return self._finish(baseline, optimized, gates, extra={"matches": len(raw_lines), "pattern": pattern})
437
459
 
438
460
  # -- scenario 6: git-diff churn → slice_diff ----------------------------
461
+ @staticmethod
462
+ def _changed_paths(raw_text: str) -> List[str]:
463
+ """Changed file paths from `+++ b/<path>` metadata lines (prefix stripped
464
+ correctly: '+++ b/' is 6 chars; the old [4:] slice left a 'b/' artifact
465
+ that broke path containment against omission notes — QA sweep finding)."""
466
+ return [ln[4:].strip().removeprefix("b/") for ln in raw_text.splitlines()
467
+ if ln.startswith("+++ b/")]
468
+
439
469
  @staticmethod
440
470
  def git_diff_gates(raw_text: str, sliced_text: str) -> Dict[str, bool]:
441
- changed = [ln[4:].strip() for ln in raw_text.splitlines() if ln.startswith("+++ b/")]
471
+ changed = RealRepoBenchmark._changed_paths(raw_text)
442
472
  non_lock = [p for p in changed if "lock" not in p.lower()]
443
473
  return {"changed_files_preserved": bool(non_lock) and all(p in sliced_text for p in non_lock)}
444
474
 
@@ -451,10 +481,16 @@ class RealRepoBenchmark:
451
481
  except ValueError:
452
482
  return {"status": "skipped", "reason": "no commit history"}
453
483
  proc = subprocess.run(["git", "diff", "HEAD~1", "HEAD"], cwd=root,
454
- capture_output=True, text=True, timeout=180)
484
+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=180)
455
485
  raw = proc.stdout or ""
456
486
  if not raw.strip():
457
487
  return {"status": "skipped", "reason": "empty diff at HEAD~1"}
488
+ # Zero-loss degenerate case: when the last commit touches ONLY
489
+ # lockfiles/binary assets there is nothing non-ignorable to preserve —
490
+ # that is a skip, not a gate rejection (QA sweep: ~10/150 real repos
491
+ # have asset-only HEAD~1 commits).
492
+ if not [p for p in self._changed_paths(raw) if "lock" not in p.lower()]:
493
+ return {"status": "skipped", "reason": "last commit only touches lockfiles/assets — nothing to slice"}
458
494
  baseline = count_tokens(raw)
459
495
  sliced, _orig, _new = DiffSlicer.slice_diff(raw)
460
496
  optimized = count_tokens(sliced)
@@ -560,6 +596,7 @@ class RealRepoBenchmark:
560
596
  b_in = 0
561
597
  o_in = 0
562
598
  hit_toks = 0
599
+ cur_totals: List[int] = []
563
600
  for msgs in turns:
564
601
  # inject_cache_control=False: we measure prefix BYTE-STABILITY (the
565
602
  # property that makes provider caching possible). Rolling breakpoints
@@ -569,6 +606,7 @@ class RealRepoBenchmark:
569
606
  units = _extract_canonical_units(None, norm_msgs)
570
607
  cur = sum(_cached_tokens(u, tok_cache) for u in units)
571
608
  b_in += cur
609
+ cur_totals.append(cur)
572
610
  prefix = _longest_prefix_tokens(prev_units, units, tok_cache) if prev_units else 0
573
611
  hit_toks += prefix
574
612
  o_in += max(0, cur - prefix) + prefix # full input still sent; prefix billed at cached rate
@@ -583,22 +621,37 @@ class RealRepoBenchmark:
583
621
  b_billed = b_in
584
622
  reduction = round((1 - o_billed / b_billed) * 100.0, 1) if b_billed else 0.0
585
623
  usd_saved = round((b_billed - o_billed) / 1e6 * self.pricing.get("sonnet_input_usd_per_mtok", 3.0), 4)
624
+ # Theoretical ceiling for an append-only replay: every turn could hit the
625
+ # ENTIRE previous turn's mass, so the ceiling is sum(T[i-1]) / sum(T[i]).
626
+ # A raw hit-rate threshold (v4: >=80%) actually measured hub-file SIZE
627
+ # distribution — a repo whose last hub file dominates can never reach 80%
628
+ # with a perfectly stable normalizer (QA sweep: uptime-kuma ceiling 77.9%
629
+ # with 99.96% per-turn stability). v5 gates the property under test —
630
+ # normalizer churn — as achieved prefix vs that ceiling.
631
+ ceiling_total = sum(cur_totals[:-1])
632
+ stability = round((hit_toks / ceiling_total) * 100.0, 1) if ceiling_total else 0.0
586
633
  gates = {
587
- "prefix_hit_rate_ge_80": hit_rate >= 80.0,
634
+ "prefix_stability_ge_95": stability >= 95.0,
588
635
  "input_reduction_positive": reduction > 0,
589
636
  }
590
- return {
637
+ result = {
591
638
  "status": "ok" if all(gates.values()) else "gate_failed",
592
639
  "baseline_tokens": b_billed,
593
640
  "optimized_tokens": o_billed,
594
641
  "saved_tokens": max(0, b_billed - o_billed),
595
642
  "reduction_pct": reduction,
596
643
  "kv_cache_hit_rate_pct": hit_rate,
644
+ "prefix_stability_pct": stability,
597
645
  "usd_saved": usd_saved,
598
646
  "gates": gates,
599
647
  "turns": len(turns),
600
- "note": "10-turn replay over repo hub files; cache-hit tokens billed at the 0.1x cached rate (Sonnet)",
648
+ "note": "10-turn replay over repo hub files; cache-hit tokens billed at the 0.1x cached rate (Sonnet); stability = achieved prefix vs append-only ceiling",
601
649
  }
650
+ if not all(gates.values()):
651
+ result["fail_reason"] = (
652
+ "gate rejection: " + ", ".join(g for g, ok in gates.items() if not ok)
653
+ + f" (stability={stability}%, hit_rate={hit_rate}%, billed_reduction={reduction}%)")
654
+ return result
602
655
 
603
656
  # -- scenario 10: secret guard --------------------------------------------
604
657
  def measure_secret_guard(self, root: str) -> Dict[str, Any]:
package/src/compactor.py CHANGED
@@ -248,9 +248,26 @@ class PromptCompactor:
248
248
  )),
249
249
  ]
250
250
 
251
+ # Extension alternation is sorted LONGEST-FIRST at class-definition time:
252
+ # a naive "ts|js|tsx|jsx" order (plus no trailing word boundary) made the
253
+ # regex match 'file.ts' inside 'file.tsx' and truncate the extracted
254
+ # target_file (QA sweep finding on real repos: App.tsx -> App.ts).
255
+ # Longest-first + \b is prefix-safe for every current and future extension.
256
+ _FILE_EXTS = sorted(
257
+ (
258
+ "tsx", "jsx", "cpp", "hpp", "ts", "js", "py", "go", "rs", "java",
259
+ "c", "h", "json", "yaml", "yml", "md", "mdx", "proto", "toml",
260
+ "sql", "html", "css", "scss", "sh", "bash", "zsh", "lock", "vue",
261
+ "svelte", "graphql", "prisma", "rb", "php", "swift", "kt", "scala",
262
+ "dart", "mjs", "cjs", "lua", "cs", "fs", "vb", "ex", "exs", "erl",
263
+ "clj", "zig", "nim",
264
+ ),
265
+ key=len,
266
+ reverse=True,
267
+ )
251
268
  FILE_REGEX = re.compile(
252
269
  r'(?:'
253
- r'(?:[\w\-\./\\]+[\/\\])?[\w\-\.]+\.(?:ts|js|tsx|jsx|py|go|rs|java|c|cpp|h|hpp|json|yaml|yml|md|proto|toml|sql|html|css|scss|sh|bash|zsh|lock|vue|svelte|graphql|prisma)'
270
+ r'(?:[\w\-\./\\][\w\-\./\\ ]*[\/\\])?[\w\-\.]+\.(?:' + "|".join(_FILE_EXTS) + r')\b'
254
271
  r'|(?:\.env(?:\.[\w\-]+)?|\.gitignore|\.dockerignore|\.prettierrc[\w\.\-]*|\.eslintrc[\w\.\-]*|\.npmignore|\.npmrc|\.yarnrc)'
255
272
  r'|\b(?:Dockerfile(?:\.[\w\-]+)?|Makefile|Procfile|Gemfile|Vagrantfile|Containerfile)\b'
256
273
  r'|\b(?:README(?:\.md)?|LICENSE|CHANGELOG(?:\.md)?)\b'
@@ -258,6 +275,29 @@ class PromptCompactor:
258
275
  re.I
259
276
  )
260
277
 
278
+ # Space-tolerant path extraction: Swift-style dirs ('Splay Tree/SplayTree.swift')
279
+ # contain spaces, so the leading directory group may include them; that can
280
+ # drag in sentence fillers ('look at docs/a.py') — trimmed below.
281
+ _PATH_NOISE_WORDS = frozenset((
282
+ "please", "look", "at", "in", "the", "a", "an", "file", "open", "read",
283
+ "see", "check", "review", "edit", "fix", "update", "modify", "show",
284
+ "find", "inspect", "refactor", "and", "to", "of", "on", "for",
285
+ "изучи", "открой", "прочитай", "файл", "в", "на",
286
+ ))
287
+
288
+ @classmethod
289
+ def _trim_path_noise(cls, path: str) -> str:
290
+ """Space-tolerant FILE_REGEX can drag sentence words into the match
291
+ ('function calculate_tax in src/billing.py', 'please look at Splay
292
+ Tree/SplayTree.swift'). Everything BEFORE the LAST noise word is
293
+ sentence context — keep only the tail after it."""
294
+ tokens = path.split(" ")
295
+ last_noise = -1
296
+ for i, tok in enumerate(tokens[:-1]): # the final token is path material
297
+ if tok.strip().lower() in cls._PATH_NOISE_WORDS:
298
+ last_noise = i
299
+ return " ".join(tokens[last_noise + 1:]) if last_noise >= 0 else path
300
+
261
301
  TRAIT_MAPPINGS = [
262
302
  (re.compile(r"\b(async|асинхронн\w*|as[ií]ncron\w*|asynchrone|asynchron)\b|(异步|非同期)", re.I), "async"),
263
303
  (re.compile(r"\b(sync|синхронн\w*|s[ií]ncron\w*|synchrone|synchron)\b|(同步)", re.I), "sync"),
@@ -426,7 +466,7 @@ class PromptCompactor:
426
466
 
427
467
  # Extract file if present
428
468
  files = cls.FILE_REGEX.findall(distilled)
429
- target_file = files[0] if files else ""
469
+ target_file = cls._trim_path_noise(files[0]) if files else ""
430
470
 
431
471
  # Extract symbol
432
472
  symbol = cls.extract_symbol(raw_text, target_file)
@@ -464,7 +504,7 @@ class PromptCompactor:
464
504
  code_free = re.sub(r"```[\s\S]*?```|`[^`\n]+`", _mask_span, url_free)
465
505
 
466
506
  files = cls.FILE_REGEX.findall(url_free)
467
- target_file = files[0] if files else ""
507
+ target_file = cls._trim_path_noise(files[0]) if files else ""
468
508
 
469
509
  action = "TASK"
470
510
  matched_action_regex = None
@@ -103,6 +103,13 @@ class DiffSlicer:
103
103
  compact_diff = "\n".join(output_lines)
104
104
  compact_tokens = count_tokens(compact_diff)
105
105
 
106
+ # Honest pass-through: when slicing earns nothing — tiny diffs where the
107
+ # omission annotations cost more than the context they save — return the
108
+ # raw diff unchanged (QA sweep finding: negative savings on ~30/150 real
109
+ # repos, 17 of them on diffs under 800 tokens).
110
+ if compact_tokens >= orig_tokens:
111
+ return raw_diff, orig_tokens, orig_tokens
112
+
106
113
  return compact_diff, orig_tokens, compact_tokens
107
114
 
108
115
  @classmethod
@@ -983,12 +983,55 @@ class CodeGraph:
983
983
  # -------------------------------------------------------------
984
984
  # 3. API Surface Generator (tokensafe-out/API_SURFACE.md)
985
985
  # -------------------------------------------------------------
986
+ # API-surface map guards (QA sweep finding: on real repos the map exploded to
987
+ # 114M tokens — minified/generated bundles leaked WHOLE LINES into symbol
988
+ # signatures (157KB each) and testdata/vendor files were not filtered).
989
+ _SURFACE_SKIP_DIR_SEGMENTS = frozenset((
990
+ "tests", "test", "testdata", "test_fixtures", "__tests__", "__mocks__",
991
+ "spec", "specs", "fixtures", "mocks", "examples", "docs", "doc",
992
+ "vendor", "third_party", "thirdparty", "node_modules", "dist", "build",
993
+ "out", "target", "__pycache__", ".venv", "venv", "generated",
994
+ ))
995
+ _SURFACE_SKIP_FILE_PATTERNS = (".min.js", ".min.css", ".bundle.js", ".map", ".d.ts")
996
+ _SURFACE_SIG_MAX = 160 # per-symbol signature cap (chars)
997
+ _SURFACE_BODY_BUDGET = 60_000 # whole-map body budget (chars, ~15k tokens)
998
+
999
+ @classmethod
1000
+ def _surface_skip_path(cls, rel_path: str) -> bool:
1001
+ low = rel_path.lower()
1002
+ if any(p in low for p in cls._SURFACE_SKIP_FILE_PATTERNS):
1003
+ return True
1004
+ if low.endswith((".lock", ".sum", ".lockb")):
1005
+ return True
1006
+ return any(seg in cls._SURFACE_SKIP_DIR_SEGMENTS
1007
+ for seg in low.replace("\\", "/").split("/")[:-1])
1008
+
1009
+ @classmethod
1010
+ def _surface_signature(cls, sig: str) -> str:
1011
+ sig = (sig or "").strip()
1012
+ if not sig:
1013
+ return ""
1014
+ # Cut minified/generated one-liners at the declaration boundary: the
1015
+ # text right before the first '{' of a function declaration ends with
1016
+ # ')' (e.g. 'var X=function(A){'); interior dict literals keep intact.
1017
+ cut = re.search(r"[{;]", sig)
1018
+ if cut and cut.start() >= 1 and sig[: cut.start()].rstrip().endswith(")"):
1019
+ sig = sig[: cut.start()].rstrip()
1020
+ if len(sig) > cls._SURFACE_SIG_MAX:
1021
+ sig = sig[: cls._SURFACE_SIG_MAX - 3] + "..."
1022
+ return sig
1023
+
986
1024
  def generate_api_surface(self, output_path: Optional[str] = None) -> str:
987
1025
  """
988
1026
  Generates a high-density, agent-friendly Markdown map of all classes,
989
- types, and exported interfaces in the project (~1,500 tokens).
1027
+ types, and exported interfaces in the project. Bounded: signatures are
1028
+ capped, testdata/vendor/minified paths skipped, whole map capped at
1029
+ _SURFACE_BODY_BUDGET chars (~15k tokens) — god-node files listed first.
1030
+ Writes a file ONLY when output_path is passed explicitly (the MCP tool
1031
+ and benchmarks consume the returned text; no implicit repo mutation).
990
1032
  """
991
1033
  god_nodes = self.get_god_nodes(top_n=5)
1034
+ god_files = {g["file"] for g in god_nodes}
992
1035
  lines = [
993
1036
  "# TokenSafe Architecture & API Surface",
994
1037
  f"*Generated locally at {time.strftime('%Y-%m-%d %H:%M:%S')} • Zero LLM Cost*",
@@ -1007,28 +1050,47 @@ class CodeGraph:
1007
1050
  ""
1008
1051
  ])
1009
1052
 
1053
+ sections: List[Tuple[str, List[str]]] = []
1010
1054
  for rel_path, sym_keys in sorted(self.file_symbols.items()):
1011
- if not sym_keys:
1055
+ if not sym_keys or self._surface_skip_path(rel_path):
1012
1056
  continue
1013
- lines.append(f"### `{rel_path}`")
1057
+ sym_lines = []
1014
1058
  for k in sym_keys:
1015
1059
  sym = self.symbols.get(k)
1016
1060
  if sym:
1017
- lines.append(f"- `{sym.kind}` **`{sym.name}`** (line {sym.line_start}): `{sym.signature}`")
1061
+ sym_lines.append(
1062
+ f"- `{sym.kind}` **`{sym.name}`** (line {sym.line_start}): "
1063
+ f"`{self._surface_signature(sym.signature)}`")
1064
+ if sym_lines:
1065
+ sections.append((rel_path, sym_lines))
1066
+
1067
+ # God-node files first (highest architectural value), then the rest.
1068
+ ordered = ([s for s in sections if s[0] in god_files]
1069
+ + [s for s in sections if s[0] not in god_files])
1070
+ omitted_files = 0
1071
+ used = 0
1072
+ for rel_path, sym_lines in ordered:
1073
+ block = len(rel_path) + sum(len(l) for l in sym_lines)
1074
+ if used + block > self._SURFACE_BODY_BUDGET:
1075
+ omitted_files += 1
1076
+ continue
1077
+ used += block
1078
+ lines.append(f"### `{rel_path}`")
1079
+ lines.extend(sym_lines)
1018
1080
  lines.append("")
1019
1081
 
1020
- output_content = "\n".join(lines)
1082
+ if omitted_files:
1083
+ lines.append(f"*+ {omitted_files} more source files omitted (API surface budget)*")
1021
1084
 
1022
- if output_path is None:
1023
- out_dir = os.path.join(self.root_dir, "tokensafe-out")
1024
- output_path = os.path.join(out_dir, "API_SURFACE.md")
1085
+ output_content = "\n".join(lines)
1025
1086
 
1026
- try:
1027
- os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
1028
- with open(output_path, "w", encoding="utf-8") as f:
1029
- f.write(output_content)
1030
- except OSError:
1031
- pass
1087
+ if output_path:
1088
+ try:
1089
+ os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
1090
+ with open(output_path, "w", encoding="utf-8") as f:
1091
+ f.write(output_content)
1092
+ except OSError:
1093
+ pass
1032
1094
 
1033
1095
  return output_content
1034
1096
 
package/src/installer.py CHANGED
@@ -59,9 +59,9 @@ UNIFIED_TOKENSAFE_RULE = (
59
59
  "11. **Secret Leak Prevention Directive (Zero Hardcoded Fallbacks)**:\n"
60
60
  "Never hardcode real private keys, API secrets, access tokens, or webhook secrets as default fallback arguments in `os.environ.get()`, `os.getenv()`, or `process.env`. If an environment variable is absent, raise an explicit configuration error or use an empty string / test mock. Whenever a secret fallback attempt is blocked, state:\n"
61
61
  "`🛡️ **TokenSafe Security Guard**: Prevented secret / private key leak into git (<target_file>: <details>)`\n"
62
- "12. **Proof-of-Savings Turn Footer (always in English)**:\n"
63
- "At the end of your response for any turn where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer in English:\n"
64
- "`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens (≈$<usd> approx)`\n"
62
+ "12. **Proof-of-Savings Turn Footer (strictly English)**:\n"
63
+ "At the end of your response for any turn where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer. The ENTIRE footer is product-facing copy — 100% English, including the savings breakdown in parentheses, regardless of the chat language:\n"
64
+ "`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown in English>) | Cumulative Total: <total> tokens (≈$<usd> approx)`\n"
65
65
  )
66
66
 
67
67
  # Short pointer written into PROJECT-level rule files when the full protocol is
@@ -83,6 +83,26 @@ def repair_json(s: str) -> Optional[str]:
83
83
  return cand
84
84
  except Exception:
85
85
  continue
86
+
87
+ # Truncation fallback (TRUE last resort — every closer-appending and
88
+ # quote-conversion strategy above has failed): retreat boundary-by-
89
+ # boundary. Handles cuts that land MID-TOKEN and right after a COMPLETED
90
+ # KEY ('{"a":1,"后"' — a dangling key with no colon), where appending
91
+ # closers alone can never produce valid JSON. Strictly validated like
92
+ # every other stage: json.loads must accept the result.
93
+ for cut in _iter_truncation_candidates(ctrl_fixed):
94
+ stripped = _strip_trailing_commas(cut)
95
+ trimmed = cut.rstrip(", ") # a dangling comma at the cut point (strip
96
+ # only removes commas BEFORE a closer, and the cut point has none yet)
97
+ for cand in (cut, stripped, _balance_brackets(cut), _balance_brackets(stripped),
98
+ trimmed, _balance_brackets(trimmed)):
99
+ if not cand:
100
+ continue
101
+ try:
102
+ json.loads(cand)
103
+ return cand
104
+ except Exception:
105
+ continue
86
106
  return None
87
107
 
88
108
 
@@ -124,6 +144,59 @@ def _escape_control_chars_in_strings(s: str) -> str:
124
144
  return "".join(out)
125
145
 
126
146
 
147
+ def _iter_truncation_candidates(s: str, max_boundaries: int = 10):
148
+ """Yields progressively earlier truncation cuts at safe structural
149
+ boundaries outside strings — after an opener ('{', '['), separator (','),
150
+ colon, closing bracket, or closing quote. A dangling colon gains a 'null'.
151
+
152
+ ONLY runs when the text is genuinely TRUNCATED — an unclosed bracket or
153
+ string at EOF. A balanced-but-broken payload ('{"a": ]}') is not a
154
+ truncation and must stay unrepairable (repairing it would mean deleting
155
+ user content). The LAST boundary alone is often unrepairable (a cut right
156
+ after a COMPLETED KEY leaves a dangling key with no colon —
157
+ '{"a":1,"后"'), so the caller retreats boundary-by-boundary; strict
158
+ json.loads validation accepts the first parseable candidate. Real-world
159
+ case: a 544KB search_index.json cut mid-key (QA sweep)."""
160
+ boundaries: List[int] = []
161
+ stack: List[str] = []
162
+ in_str = False
163
+ quote = ""
164
+ escaped = False
165
+ for i, ch in enumerate(s):
166
+ if in_str:
167
+ if escaped:
168
+ escaped = False
169
+ elif ch == "\\":
170
+ escaped = True
171
+ elif ch == quote:
172
+ in_str = False
173
+ boundaries.append(i)
174
+ continue
175
+ if ch in ('"', "'"):
176
+ in_str = True
177
+ quote = ch
178
+ elif ch in "{[":
179
+ stack.append(ch)
180
+ boundaries.append(i)
181
+ elif ch in "}]":
182
+ if stack:
183
+ stack.pop()
184
+ boundaries.append(i)
185
+ elif ch in ",:":
186
+ boundaries.append(i)
187
+ if not boundaries or (not in_str and not stack):
188
+ return # balanced and closed — nothing was truncated
189
+ attempts = 0
190
+ for pos in reversed(boundaries):
191
+ if attempts >= max_boundaries:
192
+ break
193
+ attempts += 1
194
+ cut = s[: pos + 1].rstrip()
195
+ if cut.endswith(":"):
196
+ cut += " null" # a dangling colon needs a value before the closers
197
+ yield cut
198
+
199
+
127
200
  def _balance_brackets(s: str) -> Optional[str]:
128
201
  """Appends missing closing brackets/braces (string-aware). Returns None when
129
202
  the structure cannot be balanced by appending closers alone."""
package/src/mcp_server.py CHANGED
@@ -42,7 +42,7 @@ from src.paths import get_active_workspace, is_plugin_or_system_dir
42
42
 
43
43
  SERVER_INFO = {
44
44
  "name": "tokensafe-mcp",
45
- "version": "3.1.1"
45
+ "version": "3.1.3"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -18,6 +18,8 @@ smart_read_file so agents use one familiar entry point.
18
18
  import json
19
19
  import os
20
20
  import re
21
+
22
+ from src.tokenizer import count_tokens
21
23
  from typing import Any, Dict, List, Optional, Tuple
22
24
 
23
25
  _MAX_REF_CHAIN = 15
@@ -55,17 +57,33 @@ class SchemaSlicer:
55
57
 
56
58
  @classmethod
57
59
  def slice_file(cls, path: str, target: str = "") -> Tuple[str, Dict[str, Any]]:
58
- """Returns (sliced_text, info). Empty `target` yields a compact overview."""
60
+ """Returns (sliced_text, info). Empty `target` yields a compact overview.
61
+
62
+ Never EXPANDS: when the slice is not smaller than the raw file (tiny
63
+ toy schemas — QA sweep found 14-token graphql fixtures growing to 23),
64
+ the raw text is returned unchanged, same honest pass-through as
65
+ DiffSlicer."""
66
+ raw_text = ""
67
+ try:
68
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
69
+ raw_text = f.read()
70
+ except OSError:
71
+ pass
59
72
  kind = cls.detect(path)
73
+ sliced = ""
60
74
  if kind == "openapi":
61
- return cls._slice_openapi(path, target.strip())
62
- if kind == "prisma":
63
- return cls._slice_prisma(path, target.strip())
64
- if kind == "graphql":
65
- return cls._slice_graphql(path, target.strip())
66
- if kind == "sql":
67
- return cls._slice_sql(path, target.strip())
68
- return "", {"kind": None}
75
+ sliced, info = cls._slice_openapi(path, target.strip())
76
+ elif kind == "prisma":
77
+ sliced, info = cls._slice_prisma(path, target.strip())
78
+ elif kind == "graphql":
79
+ sliced, info = cls._slice_graphql(path, target.strip())
80
+ elif kind == "sql":
81
+ sliced, info = cls._slice_sql(path, target.strip())
82
+ else:
83
+ return "", {"kind": None}
84
+ if not target.strip() and count_tokens(sliced) >= count_tokens(raw_text):
85
+ return raw_text, info # overview pass-through; targeted slices keep precision semantics
86
+ return sliced, info
69
87
 
70
88
  # ------------------------------------------------------------------ OpenAPI
71
89
 
@@ -228,7 +228,7 @@ class TelemetrySync:
228
228
  current_last_id = last_id
229
229
  headers = {
230
230
  "Content-Type": "application/json",
231
- "User-Agent": "TokenSafe-Sync/3.1.1"
231
+ "User-Agent": "TokenSafe-Sync/3.1.3"
232
232
  }
233
233
  if active_key:
234
234
  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 = "3.1.1"
20
+ CURRENT_VERSION = "3.1.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