tokensafe 4.7.3 → 4.7.5

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/src/installer.py CHANGED
@@ -50,7 +50,7 @@ UNIFIED_TOKENSAFE_RULE = (
50
50
  "1. **Zero Raw Grep/Find (Blocked & Replaced by `scoped_search`)**: Strictly NEVER execute terminal `grep`, `egrep`, `ripgrep`, or `find` on source code files or directories (`src/`, `views/`, `components/`, `.ts`, `.tsx`, `.py`, `.js`). Use `tokensafe:scoped_search(query, path='.', scope='code')` for single searches (`mode='auto'|'text'|'regex'|'glob'|'fuzzy'|'git'`) or `queries=[...]` for up to 20 concurrent queries in one call.\n"
51
51
  "2. **Mandatory Symbol, Endpoint, Bundle & External Type Inspection (`smart_read_file`)**: Always call `tokensafe:smart_read_file(path, symbol)` (default `dep_mode='signature'` folds inert code -95%+ tokens; pass `dep_mode='full'` only when needed, or `force_full=true` if a pointer hit references missing context). When the bug names a route, call `smart_read_file(endpoint='POST /api/orders')` FIRST: one call resolves the route registration across the repo → handler body + file path + line range + whole-file version (and names the handler's cross-file callees). `symbol` accepts an identifier, a qualified member (`Type.Method`) or an endpoint target (`'POST /api/orders'`): when the target is not a declaration in that file you get the enclosing handler body (or a tight ±window around the hit) with line numbers, plus the declaration itself when it lives in another file — that is the slice you edit, never a folded skeleton you have to re-read, and it is exact file text so it needs no confirming re-read. Pass `targets=[{path, symbol}]` to bundle 2-8 symbols across files in one call, or `package_name`+`symbol` for 3rd-party `.d.ts` interfaces. OpenAPI/Prisma/GraphQL/SQL schemas auto-slice via `symbol`.\n"
52
52
  "3. **Repeat Read Deduplication**: Never re-read unchanged files or symbols within the same session. Reuse the earlier skeleton or pointer hit (`// [TokenSafe: Pointer Hit ...]`).\n"
53
- "4. **Zero-Fluff Egress & Surgical Diffs**: Omit conversational filler. Reference line ranges (`file.ts#L10-L25`) and use `tokensafe:apply_edits` for multi-hunk/multi-file edits with optional inline `verify`. For a failing test, one hunk + `verify='auto'` (the project's own declared test command) per attempt: the edit and the verdict come back in one call, so read the reported line and apply the next hunk instead of rewriting whole files.\n"
53
+ "4. **Zero-Fluff Egress & Surgical Diffs**: Omit conversational filler. Reference line ranges (`file.ts#L10-L25`) and use `tokensafe:apply_edits` for multi-hunk/multi-file edits with optional inline `verify`. Take `start_line`/`end_line` from the slice header (`// --- Lx-Ly`): a target that occurs more than once is rejected with its occurrence lines and a ready scoped retry, and the tool auto-scopes to the window just read when exactly one occurrence is inside it. For a failing test, one hunk + `verify='auto'` (the project's own declared test command) per attempt: the edit and the verdict come back in one call, so read the reported line and apply the next hunk instead of rewriting whole files.\n"
54
54
  "5. **Architecture Graph, API Surface & Directory Tree (`repo_map`)**: For an unfamiliar repository or a broad refactor, FIRST call `tokensafe:repo_map(view='graph', project_path=...)` for God Nodes (<250 tokens). Use `view='api'` for exported types/interfaces and `view='tree'` instead of `ls -la`. Skip the map when the task already names the failing endpoint, symbol or file — go straight to `scoped_search` + `smart_read_file`.\n"
55
55
  "6. **Utilities (`run_helper`)**: Use `tokensafe:run_helper(action=...)` for rare/auxiliary operations: `'sanitize'` (rewrite shell/test commands), `'guard'` (pre-flight secret/safety audit), `'diff'` (slice diff), `'deps'` (lockfile point lookup), `'web'` (fetch clean Markdown), `'expand'` (restore `#hash`), `'image'` (downscale >1024px), and `'compress'` (TOCP prompt).\n"
56
56
  "7. **Compact Tests & Build Output**: Run noisy commands, builds, and test suites via `tokensafe wrap '<cmd>'` or `tokensafe tests [cmd]` (clean 1-line summary on pass, full trace on failure; never leave `vitest`/`jest`/`bun` in watch mode).\n"
package/src/mcp_server.py CHANGED
@@ -44,7 +44,7 @@ from src.session_context import current_root, current_session_id
44
44
 
45
45
  SERVER_INFO = {
46
46
  "name": "tokensafe-mcp",
47
- "version": "4.7.3"
47
+ "version": "4.7.5"
48
48
  }
49
49
 
50
50
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -806,6 +806,33 @@ TOOLS = [{'name': 'smart_read_file',
806
806
  'max_edge': {'type': 'integer'},
807
807
  'prompt': {'type': 'string'}}}}]
808
808
 
809
+
810
+ def _tighten_apply_edits_schema() -> None:
811
+ """Put the scoping rule where the model reads it on every request.
812
+
813
+ The 2026-11-27 matrix left one outlier: the model dropped start_line/end_line,
814
+ got -32011 target_not_unique, and paid a re-read before retrying. The runtime
815
+ now answers with occurrence lines and suggested hunks, and the tool text says
816
+ where the range comes from, so the retry is a one-parameter fix.
817
+ """
818
+ for tool in TOOLS:
819
+ if tool.get("name") != "apply_edits":
820
+ continue
821
+ hunks = tool["inputSchema"]["properties"]["edits"]["items"]["properties"]["hunks"]
822
+ hunks["description"] = (
823
+ "Replacement hunks. Copy start_line/end_line from the read slice header "
824
+ "(`// --- Lx-Ly`): a target that occurs more than once is rejected with the "
825
+ "occurrence lines and a scoped retry, and a ranged hunk is never ambiguous. "
826
+ "The tool auto-scopes when the last read window contains exactly one occurrence."
827
+ )
828
+ hunks["items"]["properties"]["start_line"]["description"] = (
829
+ "1-based first line to search; take it from the slice header (// --- Lx-Ly)"
830
+ )
831
+ hunks["items"]["properties"]["end_line"]["description"] = "1-based last line to search"
832
+
833
+
834
+ _tighten_apply_edits_schema()
835
+
809
836
  def format_file_size(size_bytes: int) -> str:
810
837
  if size_bytes < 1024:
811
838
  return f"{size_bytes} B"
@@ -1141,6 +1168,113 @@ def _is_binary_file(path: str, probe_bytes: int = 4096) -> bool:
1141
1168
  return False
1142
1169
 
1143
1170
 
1171
+ # Line windows this session actually delivered per file. A batch hunk with no
1172
+ # start_line/end_line can be scoped to one of them when a target repeats: the
1173
+ # agent just read those lines, so an occurrence outside them is not the one it
1174
+ # means. Only a window containing exactly one occurrence qualifies — the tool
1175
+ # never chooses between two candidates.
1176
+ _LAST_READ_WINDOWS: Dict[str, List[Tuple[int, int]]] = {}
1177
+ _LAST_READ_WINDOWS_LOCK = threading.Lock()
1178
+ _MAX_READ_WINDOWS = 8
1179
+
1180
+
1181
+ def _remember_read_window(path: str, start: Any, end: Any) -> None:
1182
+ try:
1183
+ first, last = int(start), int(end)
1184
+ except (TypeError, ValueError):
1185
+ return
1186
+ if not path or first < 1 or last < first:
1187
+ return
1188
+ try:
1189
+ key = os.path.realpath(path)
1190
+ except OSError:
1191
+ key = os.path.abspath(path)
1192
+ with _LAST_READ_WINDOWS_LOCK:
1193
+ windows = _LAST_READ_WINDOWS.setdefault(key, [])
1194
+ entry = (first, last)
1195
+ if entry in windows:
1196
+ windows.remove(entry)
1197
+ windows.append(entry)
1198
+ del windows[:-_MAX_READ_WINDOWS]
1199
+
1200
+
1201
+ def _remember_rendered_windows(path: str, text: str) -> None:
1202
+ """Records every `// --- Lx-Ly` slice header in a rendered read (symbol hits,
1203
+ cross-file inlines). The header names the file when it is not the one read."""
1204
+ for match in re.finditer(r"// --- L(\d+)-L(\d+)(?: \(([^,()]+),)?", text or ""):
1205
+ target = os.path.join(os.path.dirname(path), match.group(3)) if match.group(3) else path
1206
+ _remember_read_window(target, match.group(1), match.group(2))
1207
+
1208
+
1209
+ def _autoscope_edits(edits: Any, cwd: str) -> Tuple[Any, List[str]]:
1210
+ """Scopes unambiguous hunks to the window the agent last read.
1211
+
1212
+ Returns (edits, notes). A hunk is touched only when it has no range, its
1213
+ target repeats in the file, and exactly one remembered window contains it.
1214
+ """
1215
+ if not isinstance(edits, list):
1216
+ return edits, []
1217
+ notes: List[str] = []
1218
+ out: List[Any] = []
1219
+ for edit in edits:
1220
+ if not isinstance(edit, dict) or not isinstance(edit.get("hunks"), list) or not edit.get("path"):
1221
+ out.append(edit)
1222
+ continue
1223
+ rel = str(edit.get("path"))
1224
+ abs_path = rel if os.path.isabs(rel) else os.path.join(cwd, rel)
1225
+ key = os.path.realpath(abs_path)
1226
+ with _LAST_READ_WINDOWS_LOCK:
1227
+ windows = list(_LAST_READ_WINDOWS.get(key) or [])
1228
+ if not windows:
1229
+ out.append(edit)
1230
+ continue
1231
+ try:
1232
+ with open(abs_path, "r", encoding="utf-8", errors="replace") as handle:
1233
+ content = handle.read()
1234
+ except OSError:
1235
+ out.append(edit)
1236
+ continue
1237
+ lines = content.splitlines()
1238
+ new_hunks: List[Any] = []
1239
+ changed = False
1240
+ for hunk in edit["hunks"]:
1241
+ if not isinstance(hunk, dict) or not isinstance(hunk.get("target"), str) or not hunk["target"]:
1242
+ new_hunks.append(hunk)
1243
+ continue
1244
+ if hunk.get("start_line") is not None or hunk.get("end_line") is not None:
1245
+ new_hunks.append(hunk)
1246
+ continue
1247
+ target = hunk["target"]
1248
+ if content.count(target) <= 1:
1249
+ new_hunks.append(hunk)
1250
+ continue
1251
+ candidates = []
1252
+ for start, end in windows:
1253
+ if start > len(lines):
1254
+ continue
1255
+ window_text = "\n".join(lines[start - 1:min(end, len(lines))])
1256
+ if window_text.count(target) == 1:
1257
+ candidates.append((start, min(end, len(lines))))
1258
+ if len(candidates) == 1:
1259
+ scoped = dict(hunk)
1260
+ scoped["start_line"], scoped["end_line"] = candidates[0]
1261
+ new_hunks.append(scoped)
1262
+ changed = True
1263
+ notes.append(
1264
+ f"`{rel}`: hunk auto-scoped to lines {candidates[0][0]}-{candidates[0][1]} "
1265
+ "(the target repeats; it occurs once in the window last read)"
1266
+ )
1267
+ else:
1268
+ new_hunks.append(hunk)
1269
+ if changed:
1270
+ clone = dict(edit)
1271
+ clone["hunks"] = new_hunks
1272
+ out.append(clone)
1273
+ else:
1274
+ out.append(edit)
1275
+ return out, notes
1276
+
1277
+
1144
1278
  def _read_line_slice(path: str, start_line: Optional[int], end_line: Optional[int]) -> Tuple[Optional[str], Optional[str]]:
1145
1279
  """Reads 1-based [start_line..end_line] using bounded iteration. Returns (content, err_msg)."""
1146
1280
  if start_line is not None and start_line < 1:
@@ -1498,6 +1632,7 @@ def _render_endpoint_slice(
1498
1632
  f"ver={version} via {hit.via}]"
1499
1633
  )
1500
1634
  body_lines, first, last = hit.body, hit.line, hit.end_line
1635
+ body_file = hit.file
1501
1636
  if hit.handler_kind == "named" and hit.handler:
1502
1637
  short = hit.handler.split(".")[-1]
1503
1638
  decls = [d for d in index.get(short, []) if d[0] != hit.file] or index.get(short, [])
@@ -1507,6 +1642,7 @@ def _render_endpoint_slice(
1507
1642
  with open(os.path.join(root, file), "r", encoding="utf-8", errors="replace") as handle:
1508
1643
  src = handle.read().splitlines()
1509
1644
  body_lines, first, last = src[start - 1:end], start, end
1645
+ body_file = file
1510
1646
  head = (
1511
1647
  f"// [TS endpoint {prefix}{verb} {route} → handler {short} in {file} "
1512
1648
  f"L{start}-L{end} ver={route_index.file_version(os.path.join(root, file))}]"
@@ -1524,6 +1660,7 @@ def _render_endpoint_slice(
1524
1660
  entries.append(f"// calls: {callees}")
1525
1661
  entries.append(f"// --- L{first}-L{last}")
1526
1662
  entries.extend(body_lines)
1663
+ _remember_read_window(os.path.join(root, body_file), first, last)
1527
1664
  delivered = "\n".join(entries) + "\n"
1528
1665
  if tracker is not None:
1529
1666
  try:
@@ -1980,6 +2117,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1980
2117
  slice_lines = (content or "").splitlines()
1981
2118
  slice_first = start_line if start_line is not None else 1
1982
2119
  slice_last = slice_first + len(slice_lines) - 1 if slice_lines else max(1, slice_first - 1)
2120
+ _remember_read_window(path, slice_first, slice_last)
1983
2121
  range_label = f"{slice_first}-{slice_last}" if slice_lines else str(slice_first)
1984
2122
  prefetch_block = ""
1985
2123
  if not sym_clean or eff_dep_mode == "full":
@@ -2017,6 +2155,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2017
2155
  scope_plan = None
2018
2156
  if scope_plan and scope_plan["status"] in ("body_here", "absent"):
2019
2157
  anchored = _render_symbol_scope_miss(scope_plan, path, symbol, raw_for_scope)
2158
+ _remember_rendered_windows(path, anchored)
2020
2159
  tracker.record_event(
2021
2160
  session_id=_mcp_session_id(),
2022
2161
  event_type="SYMBOL_TEXT_ANCHOR",
@@ -3102,6 +3241,11 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3102
3241
  if is_plugin_or_system_dir(cwd):
3103
3242
  return _fallback_error("apply_edits", f"refusing to run apply_edits in system root or plugin dir '{cwd}'")
3104
3243
 
3244
+ # Deterministic recovery for a repeated hunk target: if the session just
3245
+ # read a window that contains exactly one occurrence, scope the hunk to
3246
+ # it instead of handing the model another round trip.
3247
+ edits, scope_notes = _autoscope_edits(edits, cwd)
3248
+
3105
3249
  res = execute_batch_edits(
3106
3250
  edits=edits,
3107
3251
  best_effort=best_effort,
@@ -3137,6 +3281,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3137
3281
  is_cr = f.get("is_create", False)
3138
3282
  label = "created" if is_cr else f"{h_cnt} hunk(s)"
3139
3283
  lines.append(f" - `{f.get('path')}` ({label})")
3284
+ for note in scope_notes:
3285
+ lines.append(f" ↳ {note}")
3140
3286
 
3141
3287
  if "verify" in res:
3142
3288
  v = res["verify"]
@@ -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.7.3"
314
+ "User-Agent": "TokenSafe-Sync/4.7.5"
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.7.3"
20
+ CURRENT_VERSION = "4.7.5"
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