tokensafe 4.7.4 → 4.7.6

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.7.4",
2
+ "version": "4.7.6",
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
@@ -240,26 +240,30 @@ Full matrix and details: [docs/OUMV.md](docs/OUMV.md).
240
240
 
241
241
  ## Benchmarks
242
242
 
243
- ### Measured agent matrix (Go, DeepSeek — 3 tasks × 5 runs × 3 arms)
243
+ ### Measured agent matrix v5 (Go, DeepSeek — 3 tasks × 5 runs × 3 arms, 200-file target)
244
244
 
245
245
  Real 12-assertion oracle re-run after every step; tokens and cost from the provider's `usage`
246
246
  payload. `baseline` = file/search/command tools, `tokensafe` = this product's MCP server
247
- (`scoped_search` → `smart_read_file` → `apply_edits` with inline `verify="auto"`), `oumv` = the
248
- OUMV protocol runtime. All three arms solve every session.
247
+ (`smart_read_file(endpoint="POST /api/…")` in one call → `apply_edits` with the hunk and inline
248
+ `verify="auto"`), `oumv` = the OUMV protocol runtime (`observe L3` on the endpoint →
249
+ `applyEdit mode=patch`). The sandbox is the benchmark module plus **200 generated service
250
+ files**; all three arms solve every session.
249
251
 
250
252
  | Arm | Solved | Mean steps | Mean input | Mean output | Cost/run |
251
253
  | :--- | ---: | ---: | ---: | ---: | ---: |
252
- | `baseline` | 15/15 | 4.5 | 19,538 | 1,599 | $0.0035 |
253
- | `tokensafe` | 15/15 | 4.7 | 17,616 | **750** | **$0.0025** |
254
- | `oumv` | 15/15 | 4.3 | **12,323** | 1,735 | $0.0032 |
255
-
256
- **vs baseline: −9.8% input tokens, −53.1% output tokens, −28.7% cost.** The output column is
257
- where the product's advantage is structural: `apply_edits` sends the hunk and its target
258
- snippet, so a one-line fix never resends the file — the other arms reread and rewrite whole
259
- files. Full method, per-task table, artifacts and limits (including the ±5% run-to-run noise at
260
- this sample size): [`OUMV_AGENT_MATRIX_V4.md`](https://github.com/tokensafe-dev/tokensafe-backend/blob/main/go/benchmark/OUMV_AGENT_MATRIX_V4.md)
254
+ | `baseline` | 15/15 | 5.6 | 26,412 | 1,670 | $0.0044 |
255
+ | `tokensafe` | 15/15 | **3.1** | **8,177** | **414** | **$0.0012** |
256
+ | `oumv` | 15/15 | 3.7 | 9,553 | 521 | $0.0014 |
257
+
258
+ **vs baseline: −69.0% input tokens, −75.2% output tokens, −73.3% cost.** Tree size is the
259
+ lever: on the same tasks with a 69-file tree the file-tool arm costs 22,356 input tokens per
260
+ run and the two endpoint-keyed arms 8,823 / 9,756 — growing the tree by 200 files moves only
261
+ `baseline` (+18%). Full method, per-task table, the small-target comparison, artifacts and
262
+ limits (one model, ±5% run-to-run noise at this sample size):
263
+ [`OUMV_AGENT_MATRIX_V5.md`](https://github.com/tokensafe-dev/tokensafe-backend/blob/main/go/benchmark/OUMV_AGENT_MATRIX_V5.md)
261
264
  in the backend repo, generated from the run JSON by
262
- `go/benchmark/render_agent_matrix.py`.
265
+ `go/benchmark/render_agent_matrix.py`. The previous measured run is
266
+ [`OUMV_AGENT_MATRIX_V4.md`](https://github.com/tokensafe-dev/tokensafe-backend/blob/main/go/benchmark/OUMV_AGENT_MATRIX_V4.md).
263
267
 
264
268
  ### Agent Usability Benchmarks (AUB) — Full-Stack Agent Velocity
265
269
 
package/bin/tokensafe.js CHANGED
@@ -353,14 +353,16 @@ function printInstallGuidance() {
353
353
  console.error('Managed runtime downloads can be disabled: TOKENSAFE_NO_DOWNLOAD=1\n');
354
354
  }
355
355
 
356
- async function findPython() {
356
+ async function findPython(options = {}) {
357
+ const { allowProvision = true, requireDeps = true } = options;
357
358
  const pinned = (process.env.TOKENSAFE_PYTHON || '').trim();
358
359
  if (pinned) {
359
360
  if (probePython(pinned, true)) return pinned;
360
- if (probePython(pinned, false)) {
361
+ if (requireDeps && probePython(pinned, false)) {
361
362
  const bootstrapped = bootstrapDependencies(pinned);
362
363
  if (bootstrapped) return bootstrapped;
363
364
  }
365
+ if (!requireDeps && probePython(pinned, false)) return pinned;
364
366
  fail(`TOKENSAFE_PYTHON=${pinned} is not a usable CPython ${MIN_PYTHON[0]}.${MIN_PYTHON[1]}+ with 'cryptography'.`);
365
367
  }
366
368
 
@@ -369,6 +371,15 @@ async function findPython() {
369
371
  if (fs.existsSync(venvPy)) candidates.push(venvPy);
370
372
  candidates.push('python3', 'python');
371
373
 
374
+ if (!requireDeps) {
375
+ // `help` only prints: a bare interpreter is enough, and a dependency
376
+ // bootstrap there would turn a two-line reference into a pip install.
377
+ for (const cmd of candidates) {
378
+ if (probePython(cmd, false)) return cmd;
379
+ }
380
+ return allowProvision ? await ensureManagedRuntime() : null;
381
+ }
382
+
372
383
  for (const cmd of candidates) {
373
384
  if (probePython(cmd, true)) return cmd;
374
385
  }
@@ -379,54 +390,45 @@ async function findPython() {
379
390
  }
380
391
  }
381
392
 
382
- return await ensureManagedRuntime();
393
+ return allowProvision ? await ensureManagedRuntime() : null;
383
394
  }
384
395
 
385
396
  const firstArg = args[0] || '';
386
-
387
- if (firstArg === 'help' || firstArg === '--help' || firstArg === '-h') {
397
+ const wantsHelp = firstArg === 'help' || firstArg === '--help' || firstArg === '-h';
398
+
399
+ // The command reference lives in src/cli.py:_print_help(). This launcher used
400
+ // to carry its own copy and fell behind: `dev`, `inject`, `adapters` and
401
+ // `bench-oumv` were missing, so `tokensafe help` advertised a subset of the
402
+ // real dispatcher. Help is forwarded to the Python CLI now, so one list feeds
403
+ // both entrypoints. This fallback only prints when no interpreter exists yet.
404
+ function printHelpFallback() {
388
405
  console.log(`
389
406
  ⚡ TokenSafe - Local-First AI Coding Guardrails & Context Optimizer
390
407
  Website: https://tokensafe.dev
391
-
392
- Usage:
393
- tokensafe [command] [options]
394
-
395
- Commands:
396
- tokensafe init Initialize TokenSafe ecosystem in current directory
397
- tokensafe login Sign in to unlock 500k free monthly tokens
398
- tokensafe logout Sign out and revert to Guest 50k mode
399
- tokensafe stats Show token economy savings & performance metrics
400
- tokensafe sync Synchronize local token metrics with Cloud Dashboard
401
- tokensafe html Generate and open interactive browser dashboard
402
- tokensafe test "<prompt>" Test prompt compression on custom input
403
- tokensafe expand-ref <hash> Restore folded tool/command/file result by its 8-char hash
404
- tokensafe wrap <command> Run command with compact output folding (e.g. tests/logs)
405
- tokensafe web <url> Fetch web page/docs and print clean compact Markdown
406
- tokensafe doctor Audit MCP servers & skills context token tax
407
- tokensafe providers List active LLM distillation models & keys
408
- tokensafe benchmark Run zero-loss verification benchmark suite
409
- tokensafe mcp Manage MCP servers (list, disable <name>, enable <name>)
410
- tokensafe proxy [port] Start Transparent Local AI Proxy (default: 8765)
411
- tokensafe graph Analyze repository God Nodes & dependency topology
412
- tokensafe map Generate tokensafe-out/API_SURFACE.md interface snapshot
413
- tokensafe vacuum Compact SQLite metrics database storage
414
- tokensafe prune Prune granular telemetry events into lifetime rollup
415
- tokensafe digest Preview or send weekly team ROI digest email
416
- tokensafe tests Run the unit test suite (compact failure report)
417
- tokensafe activate <key> Activate commercial Solo or Team seat license key
418
- tokensafe license Show current license status and active tier
419
- tokensafe update One-click self-update for npm, pip & all AI agent rules
420
- tokensafe install Interactive installer for Cursor, Antigravity, Claude, etc.
421
- tokensafe uninstall Uninstall TokenSafe from AI agents, unwire proxy & clean rules
422
- tokensafe --help Show this help screen
408
+ Docs: https://tokensafe.dev/docs
409
+
410
+ The command reference is printed by the Python CLI, which is not available yet.
411
+ Install CPython ${MIN_PYTHON[0]}.${MIN_PYTHON[1]}+ once and rerun 'tokensafe help':
412
+ macOS: brew install python3
413
+ Debian/Ubuntu: sudo apt-get install python3 python3-venv
414
+ Fedora: sudo dnf install python3
415
+ Windows: winget install Python.Python.3.12
416
+
417
+ No interpreter at hand? The launcher can provision a pinned build on the first
418
+ real command (network required), or accept an existing one:
419
+ TOKENSAFE_PYTHON=/path/to/python3 tokensafe help
423
420
  `);
424
- process.exit(0);
425
421
  }
426
422
 
427
423
  async function main() {
428
- const python = await findPython();
424
+ // Help must never trigger the managed-runtime download: it is a print, not a
425
+ // run. Probe what is already installed; the fallback covers the rest.
426
+ const python = await findPython({ allowProvision: !wantsHelp, requireDeps: !wantsHelp });
429
427
  if (!python) {
428
+ if (wantsHelp) {
429
+ printHelpFallback();
430
+ process.exit(0);
431
+ }
430
432
  printInstallGuidance();
431
433
  process.exit(1);
432
434
  }
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "4.7.4",
3
+ "version": "4.7.6",
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.7.4",
4
+ "version": "4.7.6",
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.7.4",
4
+ "version": "4.7.6",
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.7.4",
6
+ "version": "4.7.6",
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.7.4",
26
+ "version": "4.7.6",
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.7.4",
42
+ "version": "4.7.6",
43
43
  "runtimeHint": "uvx",
44
44
  "transport": {
45
45
  "type": "stdio"
@@ -320,7 +320,12 @@ def _apply_hunk_to_text(
320
320
  occ.append(str(s_idx + sub_text.count("\n", 0, pos) + 1))
321
321
  scan = pos + 1
322
322
  locs = f" (near lines {', '.join(occ)})" if occ else ""
323
- return None, f"Target occurs {count} times within lines {s_idx+1}..{e_idx}{locs}. Specify replace_all=True or narrow the range."
323
+ retry = ""
324
+ if occ:
325
+ first = int(occ[0])
326
+ span = max(1, target.count("\n") + 1)
327
+ retry = f" Retry with start_line={first}, end_line={first + span - 1}."
328
+ return None, f"Target occurs {count} times within lines {s_idx+1}..{e_idx}{locs}.{retry} Or set replace_all=True."
324
329
  prepared_replacement = _normalize_eol(replacement, nl)
325
330
  new_sub = sub_text.replace(match_target, prepared_replacement) if replace_all else sub_text.replace(match_target, prepared_replacement, 1)
326
331
  new_lines = lines[:s_idx] + [new_sub] + lines[e_idx:]
@@ -339,7 +344,12 @@ def _apply_hunk_to_text(
339
344
  if match_target in l:
340
345
  occ_lines.append(str(i + 1))
341
346
  locs = f"lines {', '.join(occ_lines[:5])}" if occ_lines else "multiple locations"
342
- return None, f"Target occurs {count} times (near {locs}). Specify replace_all=True or pass start_line/end_line."
347
+ retry = ""
348
+ if occ_lines:
349
+ first = int(occ_lines[0])
350
+ span = max(1, target.count("\n") + 1)
351
+ retry = f" Retry with start_line={first}, end_line={first + span - 1}."
352
+ return None, f"Target occurs {count} times (near {locs}).{retry} Or set replace_all=True."
343
353
 
344
354
  prepared_replacement = _normalize_eol(replacement, nl)
345
355
  new_content = content.replace(match_target, prepared_replacement) if replace_all else content.replace(match_target, prepared_replacement, 1)
@@ -117,6 +117,48 @@ func (h {name}) {verb}{noun}(w http.ResponseWriter, r *http.Request) {{
117
117
  )
118
118
 
119
119
 
120
+ def choose_scoped_hunk(
121
+ hunks: Optional[List[Dict[str, Any]]],
122
+ error: Dict[str, Any],
123
+ window: Optional[Tuple[int, int]],
124
+ ) -> Optional[Tuple[List[Dict[str, Any]], Dict[str, int]]]:
125
+ """Pick a scoped retry for `-32011 target_not_unique`, or None.
126
+
127
+ The retry is deterministic: it is chosen only when exactly one reported
128
+ occurrence falls inside the line window the agent last read. Zero or two
129
+ candidates mean the tool refuses to guess and hands the error back.
130
+ """
131
+ if not isinstance(error, dict) or error.get("reason") != "target_not_unique":
132
+ return None
133
+ if not window or not isinstance(hunks, list) or not hunks:
134
+ return None
135
+ try:
136
+ start, end = int(window[0]), int(window[1])
137
+ except (TypeError, ValueError):
138
+ return None
139
+ if end < start:
140
+ return None
141
+ lines = []
142
+ for value in error.get("lines") or []:
143
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
144
+ lines.append(int(value))
145
+ inside = [line for line in lines if start <= line <= end]
146
+ if len(inside) != 1:
147
+ return None
148
+ index = error.get("hunk")
149
+ index = int(index) if isinstance(index, (int, float)) and not isinstance(index, bool) else 0
150
+ if index < 0 or index >= len(hunks):
151
+ return None
152
+ line = inside[0]
153
+ target = str(hunks[index].get("target") or "")
154
+ scope_start = max(start, line - 2)
155
+ scope_end = min(end, line + target.count("\n") + 2)
156
+ scoped = [dict(hunk) for hunk in hunks]
157
+ scoped[index]["startLine"] = scope_start
158
+ scoped[index]["endLine"] = scope_end
159
+ return scoped, {"hunk": index, "startLine": scope_start, "endLine": scope_end}
160
+
161
+
120
162
  class GoWorkspace:
121
163
  def __init__(self, task_id: str, files: int = 0):
122
164
  if task_id not in TASKS:
@@ -140,6 +182,10 @@ class GoWorkspace:
140
182
  self.helper = self.dir.parent / "benchoumv"
141
183
  self._helper_built_at = 0.0
142
184
  self._mcp = None
185
+ # Last line window the agent actually read per file (observe L3 / getSource).
186
+ # A hunk that repeats can be scoped to it without guessing: the caller just
187
+ # read those lines, so an occurrence outside them is not the one it means.
188
+ self._read_windows: Dict[str, Tuple[int, int]] = {}
143
189
  self.break_build()
144
190
 
145
191
  # ---- task setup -------------------------------------------------------
@@ -299,7 +345,78 @@ class GoWorkspace:
299
345
  return {"error": f"invalid JSON from helper: {line[-1][:200]}"}
300
346
  if payload.get("error"):
301
347
  return {"error": payload["error"]}
302
- return payload.get("result")
348
+ result = payload.get("result")
349
+ if isinstance(result, dict):
350
+ self._remember_read_window(method, result)
351
+ return result
352
+
353
+ # ---- read windows & scoped retries ------------------------------------
354
+ def _window_key(self, path: str) -> str:
355
+ candidate = Path(path)
356
+ if not candidate.is_absolute():
357
+ candidate = self.dir / candidate
358
+ return os.path.normpath(str(candidate))
359
+
360
+ def _remember_read_window(self, method: str, result: Dict[str, Any]) -> None:
361
+ if method == "oumv/observe" and isinstance(result.get("data"), dict):
362
+ data = result["data"]
363
+ source = "data.source" in data
364
+ elif method == "oumv/getSource" and "source" in result:
365
+ data = result
366
+ source = True
367
+ else:
368
+ return
369
+ if not source:
370
+ return
371
+ path = data.get("path")
372
+ start, end = data.get("startLine"), data.get("endLine")
373
+ if not path or not isinstance(start, int) or not isinstance(end, int) or end < start:
374
+ return
375
+ self._read_windows[self._window_key(str(path))] = (start, end)
376
+
377
+ def apply_edit_scoped(
378
+ self,
379
+ path: str,
380
+ expected_version: str,
381
+ mode: str = "",
382
+ replacement: str = "",
383
+ symbol: str = "",
384
+ hunks: Optional[List[Dict[str, Any]]] = None,
385
+ ) -> Any:
386
+ """applyEdit with one deterministic recovery from -32011 target_not_unique.
387
+
388
+ If the model omitted startLine/endLine and the target repeats, the runtime
389
+ answers with the occurrence lines. When exactly one of them lies inside the
390
+ window this agent just read, retry with that window. Two candidates are
391
+ never resolved by guessing: the error goes back to the model instead.
392
+ """
393
+ params: Dict[str, Any] = {
394
+ "path": path,
395
+ "expectedVersion": expected_version,
396
+ **({"mode": mode} if mode else {}),
397
+ **({"replacement": replacement} if replacement else {}),
398
+ **({"symbol": symbol} if symbol else {}),
399
+ **({"hunks": hunks} if hunks else {}),
400
+ }
401
+ result = self.oumv("oumv/applyEdit", params)
402
+ error = result.get("error") if isinstance(result, dict) else None
403
+ if mode == "patch" and isinstance(error, dict) and error.get("code") == -32011:
404
+ data = dict(error.get("data") or {})
405
+ if not data.get("reason") and "not_unique" in str(error.get("message", "")):
406
+ data["reason"] = "target_not_unique"
407
+ window = self._read_windows.get(self._window_key(path))
408
+ chosen = choose_scoped_hunk(hunks, data, window)
409
+ if chosen is not None:
410
+ scoped_hunks, scope = chosen
411
+ retry = self.oumv("oumv/applyEdit", {**params, "hunks": scoped_hunks})
412
+ if isinstance(retry, dict) and not retry.get("error"):
413
+ annotated = dict(retry)
414
+ annotated["autoScoped"] = {
415
+ **scope,
416
+ "source": "unique occurrence inside the last observe L3 window",
417
+ }
418
+ return annotated
419
+ return result
303
420
 
304
421
  def tokensafe_tool_schemas(self) -> Optional[List[Dict[str, Any]]]:
305
422
  """The product's own `tools/list`, renamed to the arm's stable aliases.
@@ -527,14 +644,21 @@ OUMV_TOOLS: List[Dict[str, Any]] = BASE_TOOLS + [
527
644
  "mode": {"type": "string", "enum": ["patch", "symbol", "replace"]},
528
645
  "hunks": {
529
646
  "type": "array",
530
- "description": "mode='patch': exact snippets to splice, applied in order",
647
+ "description": (
648
+ "mode='patch': exact snippets to splice, applied in order. Copy startLine/endLine "
649
+ "from the L3 slice: without them a snippet that occurs more than once is rejected "
650
+ "with -32011 (the error carries the occurrence lines and a scoped retry)."
651
+ ),
531
652
  "items": {
532
653
  "type": "object",
533
654
  "properties": {
534
655
  "target": {"type": "string", "description": "Exact snippet from the source"},
535
656
  "replacement": {"type": "string", "description": "Replacement snippet"},
536
- "startLine": {"type": "integer"},
537
- "endLine": {"type": "integer"},
657
+ "startLine": {
658
+ "type": "integer",
659
+ "description": "1-based first line to search, from observe L3; makes a repeated target unique",
660
+ },
661
+ "endLine": {"type": "integer", "description": "1-based last line to search"},
538
662
  },
539
663
  "required": ["target", "replacement"],
540
664
  },
@@ -647,16 +771,13 @@ def registry(ws: GoWorkspace, arm: str) -> Dict[str, Any]:
647
771
  tools.update({
648
772
  "oumv_observe": lambda level, target="": ws.oumv("oumv/observe", {"level": level, "target": target}),
649
773
  "oumv_getSource": lambda path, symbol="": ws.oumv("oumv/getSource", {"path": path, "symbol": symbol}),
650
- "oumv_applyEdit": lambda path, expectedVersion, mode="", replacement="", symbol="", hunks=None: ws.oumv(
651
- "oumv/applyEdit",
652
- {
653
- "path": path,
654
- "expectedVersion": expectedVersion,
655
- **({"mode": mode} if mode else {}),
656
- **({"replacement": replacement} if replacement else {}),
657
- **({"symbol": symbol} if symbol else {}),
658
- **({"hunks": hunks} if hunks else {}),
659
- },
774
+ "oumv_applyEdit": lambda path, expectedVersion, mode="", replacement="", symbol="", hunks=None: ws.apply_edit_scoped(
775
+ path,
776
+ expectedVersion,
777
+ mode=mode,
778
+ replacement=replacement,
779
+ symbol=symbol,
780
+ hunks=hunks,
660
781
  ),
661
782
  "oumv_verify": lambda target, payload=None: ws.oumv(
662
783
  "oumv/verify", {"target": target, "action": "probe", "payload": payload}
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.4"
47
+ "version": "4.7.6"
48
48
  }
49
49
 
50
50
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -430,7 +430,8 @@ FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
430
430
  'target': { 'description': "Target component ID, route (e.g. 'POST "
431
431
  "/api/products'), or DOM element "
432
432
  "('#submit-btn')",
433
- 'type': 'string'}},
433
+ 'type': 'string'},
434
+ 'workspace_dir': {'type': 'string'}},
434
435
  'type': 'object'},
435
436
  'name': 'oumv_observe'},
436
437
  { 'annotations': {'readOnlyHint': True},
@@ -448,7 +449,8 @@ FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
448
449
  'type': 'string'},
449
450
  'target': { 'description': 'Target component ID, state key, endpoint, '
450
451
  'or UI element',
451
- 'type': 'string'}},
452
+ 'type': 'string'},
453
+ 'workspace_dir': {'type': 'string'}},
452
454
  'type': 'object'},
453
455
  'name': 'oumv_understand'},
454
456
  { 'annotations': {'destructiveHint': False, 'readOnlyHint': False},
@@ -467,7 +469,8 @@ FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
467
469
  "'backend', or 'auto')",
468
470
  'enum': ['frontend', 'backend', 'auto'],
469
471
  'type': 'string'},
470
- 'symbol': {'description': 'Target symbol to edit', 'type': 'string'}},
472
+ 'symbol': {'description': 'Target symbol to edit', 'type': 'string'},
473
+ 'workspace_dir': {'type': 'string'}},
471
474
  'required': ['path'],
472
475
  'type': 'object'},
473
476
  'name': 'oumv_mutate'},
@@ -488,7 +491,8 @@ FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
488
491
  'type': 'string'},
489
492
  'target': { 'description': "Action target (component ID, e.g. 'cart', "
490
493
  "or 'POST /api/v1/orders' or '#submit-btn')",
491
- 'type': 'string'}},
494
+ 'type': 'string'},
495
+ 'workspace_dir': {'type': 'string'}},
492
496
  'required': ['target'],
493
497
  'type': 'object'},
494
498
  'name': 'oumv_verify'},
@@ -503,7 +507,8 @@ FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
503
507
  'type': 'string'},
504
508
  'target': { 'description': "Target resource (e.g. '/api/orders' or "
505
509
  "'POST /api/orders')",
506
- 'type': 'string'}},
510
+ 'type': 'string'},
511
+ 'workspace_dir': {'type': 'string'}},
507
512
  'type': 'object'},
508
513
  'name': 'oumv_graph'},
509
514
  { 'annotations': {'readOnlyHint': False, 'destructiveHint': False},
@@ -780,7 +785,11 @@ TOOLS = [{'name': 'smart_read_file',
780
785
  'replacement': {'type': 'string'},
781
786
  'expectedVersion': {'type': 'string'},
782
787
  'verify_action': {'type': 'string'},
783
- 'payload': {'type': 'object'}}}},
788
+ 'payload': {'type': 'object'},
789
+ 'workspace_dir': {'type': 'string',
790
+ 'description': 'Target repo root; for '
791
+ 'status/observe/understand/verify/graph '
792
+ 'also accepted as path'}}}},
784
793
  {'name': 'run_helper',
785
794
  'annotations': {'readOnlyHint': False},
786
795
  'description': "Utilities: 'sanitize','guard','diff','deps','web','expand','image','compress'.",
@@ -806,6 +815,33 @@ TOOLS = [{'name': 'smart_read_file',
806
815
  'max_edge': {'type': 'integer'},
807
816
  'prompt': {'type': 'string'}}}}]
808
817
 
818
+
819
+ def _tighten_apply_edits_schema() -> None:
820
+ """Put the scoping rule where the model reads it on every request.
821
+
822
+ The 2026-11-27 matrix left one outlier: the model dropped start_line/end_line,
823
+ got -32011 target_not_unique, and paid a re-read before retrying. The runtime
824
+ now answers with occurrence lines and suggested hunks, and the tool text says
825
+ where the range comes from, so the retry is a one-parameter fix.
826
+ """
827
+ for tool in TOOLS:
828
+ if tool.get("name") != "apply_edits":
829
+ continue
830
+ hunks = tool["inputSchema"]["properties"]["edits"]["items"]["properties"]["hunks"]
831
+ hunks["description"] = (
832
+ "Replacement hunks. Copy start_line/end_line from the read slice header "
833
+ "(`// --- Lx-Ly`): a target that occurs more than once is rejected with the "
834
+ "occurrence lines and a scoped retry, and a ranged hunk is never ambiguous. "
835
+ "The tool auto-scopes when the last read window contains exactly one occurrence."
836
+ )
837
+ hunks["items"]["properties"]["start_line"]["description"] = (
838
+ "1-based first line to search; take it from the slice header (// --- Lx-Ly)"
839
+ )
840
+ hunks["items"]["properties"]["end_line"]["description"] = "1-based last line to search"
841
+
842
+
843
+ _tighten_apply_edits_schema()
844
+
809
845
  def format_file_size(size_bytes: int) -> str:
810
846
  if size_bytes < 1024:
811
847
  return f"{size_bytes} B"
@@ -980,6 +1016,68 @@ def _resolve_project_root(args: dict) -> Tuple[Optional[str], Optional[str]]:
980
1016
 
981
1017
  return None, "Error: Invalid or root project_path. Please specify an explicit 'project_path' pointing to your project directory (e.g. project_path='/path/to/project')."
982
1018
 
1019
+
1020
+ def _shared_batch_root(paths: List[str], real_cwd: str) -> Optional[str]:
1021
+ """Narrowest project directory that contains every absolute sub-query path.
1022
+
1023
+ Batch search is one root per call. When every explicit sub-query path lives
1024
+ outside the current root but inside one repo, that repo IS the root: rebasing
1025
+ there beats failing the call (agents batch a second checkout this way). Paths
1026
+ that share only a wide parent — the directory that also holds the current
1027
+ root, or two sibling repos — return None so the caller keeps the split rule.
1028
+ """
1029
+ try:
1030
+ shared = os.path.commonpath(paths)
1031
+ except ValueError:
1032
+ return None
1033
+ if os.path.isfile(shared):
1034
+ shared = os.path.dirname(shared)
1035
+ if not shared or shared == os.path.abspath(os.sep) or not os.path.isdir(shared):
1036
+ return None
1037
+
1038
+ def _swallows_cwd(candidate: str) -> bool:
1039
+ try:
1040
+ return os.path.commonpath([real_cwd, candidate]) == candidate
1041
+ except ValueError:
1042
+ return False
1043
+
1044
+ if _swallows_cwd(shared):
1045
+ return None
1046
+ # Prefer the enclosing project root, so a batch of sub-paths searches its
1047
+ # repo instead of just their common sub-directory.
1048
+ try:
1049
+ from src.graph_engine import GraphEngine
1050
+ shared = GraphEngine.find_project_root(shared)
1051
+ except Exception:
1052
+ pass
1053
+ if not os.path.isdir(shared) or _swallows_cwd(shared) or is_plugin_or_system_dir(shared):
1054
+ return None
1055
+ return shared
1056
+
1057
+
1058
+ def _oumv_workspace_arg(args: dict, allow_path: bool = False) -> Tuple[Optional[str], Optional[str]]:
1059
+ """Validated workspace root for an OUMV call; None means "use the active one".
1060
+
1061
+ The MCP server inherits the host process cwd, so without this an explicit
1062
+ target repo was either dropped (unadvertised property) or ignored, and the
1063
+ answer described the bound workspace. A root that does not exist now fails
1064
+ closed instead of reporting another repo's stack.
1065
+ """
1066
+ raw = str(args.get("workspace_dir") or "").strip()
1067
+ if not raw and allow_path:
1068
+ raw = str(args.get("path") or "").strip()
1069
+ if not raw:
1070
+ return None, None
1071
+ ws = os.path.abspath(raw)
1072
+ if os.path.isfile(ws):
1073
+ ws = os.path.dirname(ws)
1074
+ if not os.path.isdir(ws):
1075
+ return None, f"workspace_dir not found or not a directory: '{raw}'"
1076
+ if is_plugin_or_system_dir(ws):
1077
+ return None, f"refusing to use system root or plugin dir as workspace: '{ws}'"
1078
+ return ws, None
1079
+
1080
+
983
1081
  MCP_TOOL_TIMEOUT = float(os.environ.get("TOKENSAFE_MCP_TIMEOUT", "8.0"))
984
1082
 
985
1083
 
@@ -1141,6 +1239,113 @@ def _is_binary_file(path: str, probe_bytes: int = 4096) -> bool:
1141
1239
  return False
1142
1240
 
1143
1241
 
1242
+ # Line windows this session actually delivered per file. A batch hunk with no
1243
+ # start_line/end_line can be scoped to one of them when a target repeats: the
1244
+ # agent just read those lines, so an occurrence outside them is not the one it
1245
+ # means. Only a window containing exactly one occurrence qualifies — the tool
1246
+ # never chooses between two candidates.
1247
+ _LAST_READ_WINDOWS: Dict[str, List[Tuple[int, int]]] = {}
1248
+ _LAST_READ_WINDOWS_LOCK = threading.Lock()
1249
+ _MAX_READ_WINDOWS = 8
1250
+
1251
+
1252
+ def _remember_read_window(path: str, start: Any, end: Any) -> None:
1253
+ try:
1254
+ first, last = int(start), int(end)
1255
+ except (TypeError, ValueError):
1256
+ return
1257
+ if not path or first < 1 or last < first:
1258
+ return
1259
+ try:
1260
+ key = os.path.realpath(path)
1261
+ except OSError:
1262
+ key = os.path.abspath(path)
1263
+ with _LAST_READ_WINDOWS_LOCK:
1264
+ windows = _LAST_READ_WINDOWS.setdefault(key, [])
1265
+ entry = (first, last)
1266
+ if entry in windows:
1267
+ windows.remove(entry)
1268
+ windows.append(entry)
1269
+ del windows[:-_MAX_READ_WINDOWS]
1270
+
1271
+
1272
+ def _remember_rendered_windows(path: str, text: str) -> None:
1273
+ """Records every `// --- Lx-Ly` slice header in a rendered read (symbol hits,
1274
+ cross-file inlines). The header names the file when it is not the one read."""
1275
+ for match in re.finditer(r"// --- L(\d+)-L(\d+)(?: \(([^,()]+),)?", text or ""):
1276
+ target = os.path.join(os.path.dirname(path), match.group(3)) if match.group(3) else path
1277
+ _remember_read_window(target, match.group(1), match.group(2))
1278
+
1279
+
1280
+ def _autoscope_edits(edits: Any, cwd: str) -> Tuple[Any, List[str]]:
1281
+ """Scopes unambiguous hunks to the window the agent last read.
1282
+
1283
+ Returns (edits, notes). A hunk is touched only when it has no range, its
1284
+ target repeats in the file, and exactly one remembered window contains it.
1285
+ """
1286
+ if not isinstance(edits, list):
1287
+ return edits, []
1288
+ notes: List[str] = []
1289
+ out: List[Any] = []
1290
+ for edit in edits:
1291
+ if not isinstance(edit, dict) or not isinstance(edit.get("hunks"), list) or not edit.get("path"):
1292
+ out.append(edit)
1293
+ continue
1294
+ rel = str(edit.get("path"))
1295
+ abs_path = rel if os.path.isabs(rel) else os.path.join(cwd, rel)
1296
+ key = os.path.realpath(abs_path)
1297
+ with _LAST_READ_WINDOWS_LOCK:
1298
+ windows = list(_LAST_READ_WINDOWS.get(key) or [])
1299
+ if not windows:
1300
+ out.append(edit)
1301
+ continue
1302
+ try:
1303
+ with open(abs_path, "r", encoding="utf-8", errors="replace") as handle:
1304
+ content = handle.read()
1305
+ except OSError:
1306
+ out.append(edit)
1307
+ continue
1308
+ lines = content.splitlines()
1309
+ new_hunks: List[Any] = []
1310
+ changed = False
1311
+ for hunk in edit["hunks"]:
1312
+ if not isinstance(hunk, dict) or not isinstance(hunk.get("target"), str) or not hunk["target"]:
1313
+ new_hunks.append(hunk)
1314
+ continue
1315
+ if hunk.get("start_line") is not None or hunk.get("end_line") is not None:
1316
+ new_hunks.append(hunk)
1317
+ continue
1318
+ target = hunk["target"]
1319
+ if content.count(target) <= 1:
1320
+ new_hunks.append(hunk)
1321
+ continue
1322
+ candidates = []
1323
+ for start, end in windows:
1324
+ if start > len(lines):
1325
+ continue
1326
+ window_text = "\n".join(lines[start - 1:min(end, len(lines))])
1327
+ if window_text.count(target) == 1:
1328
+ candidates.append((start, min(end, len(lines))))
1329
+ if len(candidates) == 1:
1330
+ scoped = dict(hunk)
1331
+ scoped["start_line"], scoped["end_line"] = candidates[0]
1332
+ new_hunks.append(scoped)
1333
+ changed = True
1334
+ notes.append(
1335
+ f"`{rel}`: hunk auto-scoped to lines {candidates[0][0]}-{candidates[0][1]} "
1336
+ "(the target repeats; it occurs once in the window last read)"
1337
+ )
1338
+ else:
1339
+ new_hunks.append(hunk)
1340
+ if changed:
1341
+ clone = dict(edit)
1342
+ clone["hunks"] = new_hunks
1343
+ out.append(clone)
1344
+ else:
1345
+ out.append(edit)
1346
+ return out, notes
1347
+
1348
+
1144
1349
  def _read_line_slice(path: str, start_line: Optional[int], end_line: Optional[int]) -> Tuple[Optional[str], Optional[str]]:
1145
1350
  """Reads 1-based [start_line..end_line] using bounded iteration. Returns (content, err_msg)."""
1146
1351
  if start_line is not None and start_line < 1:
@@ -1498,6 +1703,7 @@ def _render_endpoint_slice(
1498
1703
  f"ver={version} via {hit.via}]"
1499
1704
  )
1500
1705
  body_lines, first, last = hit.body, hit.line, hit.end_line
1706
+ body_file = hit.file
1501
1707
  if hit.handler_kind == "named" and hit.handler:
1502
1708
  short = hit.handler.split(".")[-1]
1503
1709
  decls = [d for d in index.get(short, []) if d[0] != hit.file] or index.get(short, [])
@@ -1507,6 +1713,7 @@ def _render_endpoint_slice(
1507
1713
  with open(os.path.join(root, file), "r", encoding="utf-8", errors="replace") as handle:
1508
1714
  src = handle.read().splitlines()
1509
1715
  body_lines, first, last = src[start - 1:end], start, end
1716
+ body_file = file
1510
1717
  head = (
1511
1718
  f"// [TS endpoint {prefix}{verb} {route} → handler {short} in {file} "
1512
1719
  f"L{start}-L{end} ver={route_index.file_version(os.path.join(root, file))}]"
@@ -1524,6 +1731,7 @@ def _render_endpoint_slice(
1524
1731
  entries.append(f"// calls: {callees}")
1525
1732
  entries.append(f"// --- L{first}-L{last}")
1526
1733
  entries.extend(body_lines)
1734
+ _remember_read_window(os.path.join(root, body_file), first, last)
1527
1735
  delivered = "\n".join(entries) + "\n"
1528
1736
  if tracker is not None:
1529
1737
  try:
@@ -1732,6 +1940,18 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1732
1940
  action = str(args.get("action") or "status").strip().lower()
1733
1941
  if action not in _OUMV_ACTIONS:
1734
1942
  return _fallback_error("oumv", f"unknown action '{action}'")
1943
+ # Target-repo routing: the MCP server inherits the host's cwd, so an agent
1944
+ # inspecting a second repo (workspace_dir, or `path` for the read actions)
1945
+ # used to get the bound workspace's stack back with no error — a silently
1946
+ # wrong answer. Resolve the explicit root here and fail closed on a bad one.
1947
+ ws, ws_err = _oumv_workspace_arg(
1948
+ args,
1949
+ allow_path=action in ("status", "observe", "understand", "verify", "graph"),
1950
+ )
1951
+ if ws_err:
1952
+ return _fallback_error("oumv", ws_err)
1953
+ if ws:
1954
+ args = dict(args, workspace_dir=ws)
1735
1955
  mapped = _OUMV_ACTIONS[action]
1736
1956
  if action == "verify":
1737
1957
  args = dict(args, action=args.get("verify_action") or "invoke")
@@ -1980,6 +2200,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1980
2200
  slice_lines = (content or "").splitlines()
1981
2201
  slice_first = start_line if start_line is not None else 1
1982
2202
  slice_last = slice_first + len(slice_lines) - 1 if slice_lines else max(1, slice_first - 1)
2203
+ _remember_read_window(path, slice_first, slice_last)
1983
2204
  range_label = f"{slice_first}-{slice_last}" if slice_lines else str(slice_first)
1984
2205
  prefetch_block = ""
1985
2206
  if not sym_clean or eff_dep_mode == "full":
@@ -2017,6 +2238,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2017
2238
  scope_plan = None
2018
2239
  if scope_plan and scope_plan["status"] in ("body_here", "absent"):
2019
2240
  anchored = _render_symbol_scope_miss(scope_plan, path, symbol, raw_for_scope)
2241
+ _remember_rendered_windows(path, anchored)
2020
2242
  tracker.record_event(
2021
2243
  session_id=_mcp_session_id(),
2022
2244
  event_type="SYMBOL_TEXT_ANCHOR",
@@ -3010,7 +3232,10 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3010
3232
  elif name == "oumv_status":
3011
3233
  try:
3012
3234
  from src.oumv_gateway import OUMVGateway
3013
- ws = str(args.get("workspace_dir") or "").strip() or get_active_workspace() or os.getcwd()
3235
+ ws, ws_err = _oumv_workspace_arg(args, allow_path=True)
3236
+ if ws_err:
3237
+ return _fallback_error("oumv_status", ws_err)
3238
+ ws = ws or get_active_workspace() or os.getcwd()
3014
3239
  res = OUMVGateway.status(workspace_dir=ws)
3015
3240
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
3016
3241
  except Exception as e:
@@ -3022,7 +3247,9 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3022
3247
  lvl = str(args.get("level") or "L0").strip()
3023
3248
  tgt = str(args.get("target") or "").strip() or None
3024
3249
  rt = str(args.get("runtime") or "auto").strip()
3025
- ws = str(args.get("workspace_dir") or "").strip() or None
3250
+ ws, ws_err = _oumv_workspace_arg(args)
3251
+ if ws_err:
3252
+ return _fallback_error("oumv_observe", ws_err)
3026
3253
  res = OUMVGateway.observe(level=lvl, target=tgt, runtime=rt, workspace_dir=ws)
3027
3254
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
3028
3255
  except Exception as e:
@@ -3034,7 +3261,9 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3034
3261
  qry = str(args.get("query") or "causality").strip()
3035
3262
  tgt = str(args.get("target") or "").strip() or None
3036
3263
  rt = str(args.get("runtime") or "auto").strip()
3037
- ws = str(args.get("workspace_dir") or "").strip() or None
3264
+ ws, ws_err = _oumv_workspace_arg(args)
3265
+ if ws_err:
3266
+ return _fallback_error("oumv_understand", ws_err)
3038
3267
  res = OUMVGateway.understand(query=qry, target=tgt, runtime=rt, workspace_dir=ws)
3039
3268
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
3040
3269
  except Exception as e:
@@ -3048,7 +3277,9 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3048
3277
  rep = args.get("replacement")
3049
3278
  ev = str(args.get("expectedVersion") or "").strip() or None
3050
3279
  rt = str(args.get("runtime") or "auto").strip()
3051
- ws = str(args.get("workspace_dir") or "").strip() or None
3280
+ ws, ws_err = _oumv_workspace_arg(args)
3281
+ if ws_err:
3282
+ return _fallback_error("oumv_mutate", ws_err)
3052
3283
  res = OUMVGateway.mutate(path=p, symbol=sym, replacement=rep, expected_version=ev, runtime=rt, workspace_dir=ws)
3053
3284
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
3054
3285
  except Exception as e:
@@ -3061,7 +3292,9 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3061
3292
  act = str(args.get("action") or "invoke").strip()
3062
3293
  payload = args.get("payload") if isinstance(args.get("payload"), dict) else None
3063
3294
  rt = str(args.get("runtime") or "auto").strip()
3064
- ws = str(args.get("workspace_dir") or "").strip() or None
3295
+ ws, ws_err = _oumv_workspace_arg(args)
3296
+ if ws_err:
3297
+ return _fallback_error("oumv_verify", ws_err)
3065
3298
  res = OUMVGateway.verify(target=tgt, action=act, payload=payload, runtime=rt, workspace_dir=ws)
3066
3299
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
3067
3300
  except Exception as e:
@@ -3072,7 +3305,9 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3072
3305
  from src.oumv_gateway import OUMVGateway
3073
3306
  qry = str(args.get("query") or "overview").strip()
3074
3307
  tgt = str(args.get("target") or "").strip() or None
3075
- ws = str(args.get("workspace_dir") or "").strip() or None
3308
+ ws, ws_err = _oumv_workspace_arg(args)
3309
+ if ws_err:
3310
+ return _fallback_error("oumv_graph", ws_err)
3076
3311
  res = OUMVGateway.graph(query=qry, target=tgt, workspace_dir=ws)
3077
3312
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
3078
3313
  except Exception as e:
@@ -3102,6 +3337,11 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3102
3337
  if is_plugin_or_system_dir(cwd):
3103
3338
  return _fallback_error("apply_edits", f"refusing to run apply_edits in system root or plugin dir '{cwd}'")
3104
3339
 
3340
+ # Deterministic recovery for a repeated hunk target: if the session just
3341
+ # read a window that contains exactly one occurrence, scope the hunk to
3342
+ # it instead of handing the model another round trip.
3343
+ edits, scope_notes = _autoscope_edits(edits, cwd)
3344
+
3105
3345
  res = execute_batch_edits(
3106
3346
  edits=edits,
3107
3347
  best_effort=best_effort,
@@ -3137,6 +3377,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3137
3377
  is_cr = f.get("is_create", False)
3138
3378
  label = "created" if is_cr else f"{h_cnt} hunk(s)"
3139
3379
  lines.append(f" - `{f.get('path')}` ({label})")
3380
+ for note in scope_notes:
3381
+ lines.append(f" ↳ {note}")
3140
3382
 
3141
3383
  if "verify" in res:
3142
3384
  v = res["verify"]
@@ -3224,9 +3466,15 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3224
3466
 
3225
3467
  safe_queries: List[Dict[str, Any]] = []
3226
3468
  real_cwd = os.path.realpath(cwd)
3469
+ # Pass 1: resolve every sub-query path. A relative path that climbs out
3470
+ # of the root is still a hard error (traversal); absolute paths are an
3471
+ # explicit intent to search elsewhere, so they may be rebased below.
3472
+ q_copies: List[Any] = []
3473
+ path_abs: Dict[int, str] = {}
3474
+ outside: List[str] = []
3227
3475
  for q_item in queries:
3228
3476
  if not isinstance(q_item, dict):
3229
- safe_queries.append(q_item)
3477
+ q_copies.append(q_item)
3230
3478
  continue
3231
3479
  q_copy = dict(q_item)
3232
3480
  sub_p = q_copy.get("path")
@@ -3243,18 +3491,54 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3243
3491
  except ValueError:
3244
3492
  inside = False
3245
3493
  if not inside:
3246
- return _fallback_error(
3247
- "batch_search",
3248
- f"subquery path '{sub_p}' resolves to '{sub_abs}', outside project root "
3249
- f"'{real_cwd}'. One call searches one root: pass that repo as cwd/project_path "
3250
- f"with repo-relative paths, and split queries for other repos into separate calls.",
3251
- )
3494
+ if not os.path.isabs(str(sub_p)):
3495
+ return _fallback_error(
3496
+ "batch_search",
3497
+ f"subquery path '{sub_p}' resolves to '{sub_abs}', outside project root "
3498
+ f"'{real_cwd}'. One call searches one root: pass that repo as cwd/project_path "
3499
+ f"with repo-relative paths, and split queries for other repos into separate calls.",
3500
+ )
3501
+ outside.append(sub_abs)
3502
+ path_abs[len(q_copies)] = sub_abs
3503
+ q_copies.append(q_copy)
3504
+
3505
+ rebased_from: Optional[str] = None
3506
+ if outside:
3507
+ shared_root = _shared_batch_root(outside, real_cwd) if len(outside) == len(path_abs) else None
3508
+ if not shared_root:
3509
+ detail = (
3510
+ "queries mix paths inside and outside it"
3511
+ if len(outside) != len(path_abs)
3512
+ else "they share no single enclosing project directory"
3513
+ )
3514
+ return _fallback_error(
3515
+ "batch_search",
3516
+ f"subquery paths resolve outside project root '{real_cwd}' and {detail}. "
3517
+ f"One call searches one root: pass that repo as cwd/project_path with "
3518
+ f"repo-relative paths, and split queries for other repos into separate calls.",
3519
+ )
3520
+ rebased_from = cwd
3521
+ cwd = shared_root
3522
+ real_cwd = os.path.realpath(shared_root)
3523
+ for idx, sub_abs in path_abs.items():
3524
+ if isinstance(q_copies[idx], dict):
3525
+ q_copies[idx]["path"] = os.path.relpath(sub_abs, shared_root)
3526
+
3527
+ for q_copy in q_copies:
3528
+ if not isinstance(q_copy, dict):
3529
+ safe_queries.append(q_copy)
3530
+ continue
3252
3531
  if is_quota_exceeded:
3253
3532
  q_copy["max_results"] = min(_safe_int(q_copy.get("max_results"), 3, lo=1, hi=100), 3)
3254
3533
  safe_queries.append(q_copy)
3255
3534
 
3256
3535
  res = execute_batch_search(queries=safe_queries, cwd=cwd)
3257
3536
  summary_md = res.get("summary_md", "")
3537
+ if rebased_from:
3538
+ summary_md = (
3539
+ f"// [TokenSafe: batch root auto-rebased to '{cwd}' (was '{rebased_from}') — "
3540
+ f"every subquery path lives there]\n" + summary_md
3541
+ )
3258
3542
  if is_quota_exceeded:
3259
3543
  banner = _quota_banner_if_due(quota, tracker, _mcp_session_id())
3260
3544
  current_tier = str(quota.get("tier") or "guest").lower()
@@ -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.4"
314
+ "User-Agent": "TokenSafe-Sync/4.7.6"
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.4"
20
+ CURRENT_VERSION = "4.7.6"
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