tokensafe 4.7.4 → 4.7.7

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/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.7"
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'},
@@ -486,9 +489,19 @@ FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
486
489
  "'backend', or 'auto')",
487
490
  'enum': ['frontend', 'backend', 'auto'],
488
491
  'type': 'string'},
492
+ 'sandbox': { 'description': 'Transactional sandbox (backend only): '
493
+ '{"mode": "rollback"} runs the whole '
494
+ 'verify in one transaction and rolls it '
495
+ 'back; the result reports rolledBack, '
496
+ 'rollbackStatus and dbDiff',
497
+ 'properties': { 'mode': {'enum': ['rollback'],
498
+ 'type': 'string'}},
499
+ 'required': ['mode'],
500
+ 'type': 'object'},
489
501
  'target': { 'description': "Action target (component ID, e.g. 'cart', "
490
502
  "or 'POST /api/v1/orders' or '#submit-btn')",
491
- 'type': 'string'}},
503
+ 'type': 'string'},
504
+ 'workspace_dir': {'type': 'string'}},
492
505
  'required': ['target'],
493
506
  'type': 'object'},
494
507
  'name': 'oumv_verify'},
@@ -503,7 +516,8 @@ FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
503
516
  'type': 'string'},
504
517
  'target': { 'description': "Target resource (e.g. '/api/orders' or "
505
518
  "'POST /api/orders')",
506
- 'type': 'string'}},
519
+ 'type': 'string'},
520
+ 'workspace_dir': {'type': 'string'}},
507
521
  'type': 'object'},
508
522
  'name': 'oumv_graph'},
509
523
  { 'annotations': {'readOnlyHint': False, 'destructiveHint': False},
@@ -780,7 +794,11 @@ TOOLS = [{'name': 'smart_read_file',
780
794
  'replacement': {'type': 'string'},
781
795
  'expectedVersion': {'type': 'string'},
782
796
  'verify_action': {'type': 'string'},
783
- 'payload': {'type': 'object'}}}},
797
+ 'payload': {'type': 'object'},
798
+ 'workspace_dir': {'type': 'string',
799
+ 'description': 'Target repo root; for '
800
+ 'status/observe/understand/verify/graph '
801
+ 'also accepted as path'}}}},
784
802
  {'name': 'run_helper',
785
803
  'annotations': {'readOnlyHint': False},
786
804
  'description': "Utilities: 'sanitize','guard','diff','deps','web','expand','image','compress'.",
@@ -806,6 +824,33 @@ TOOLS = [{'name': 'smart_read_file',
806
824
  'max_edge': {'type': 'integer'},
807
825
  'prompt': {'type': 'string'}}}}]
808
826
 
827
+
828
+ def _tighten_apply_edits_schema() -> None:
829
+ """Put the scoping rule where the model reads it on every request.
830
+
831
+ The 2026-11-27 matrix left one outlier: the model dropped start_line/end_line,
832
+ got -32011 target_not_unique, and paid a re-read before retrying. The runtime
833
+ now answers with occurrence lines and suggested hunks, and the tool text says
834
+ where the range comes from, so the retry is a one-parameter fix.
835
+ """
836
+ for tool in TOOLS:
837
+ if tool.get("name") != "apply_edits":
838
+ continue
839
+ hunks = tool["inputSchema"]["properties"]["edits"]["items"]["properties"]["hunks"]
840
+ hunks["description"] = (
841
+ "Replacement hunks. Copy start_line/end_line from the read slice header "
842
+ "(`// --- Lx-Ly`): a target that occurs more than once is rejected with the "
843
+ "occurrence lines and a scoped retry, and a ranged hunk is never ambiguous. "
844
+ "The tool auto-scopes when the last read window contains exactly one occurrence."
845
+ )
846
+ hunks["items"]["properties"]["start_line"]["description"] = (
847
+ "1-based first line to search; take it from the slice header (// --- Lx-Ly)"
848
+ )
849
+ hunks["items"]["properties"]["end_line"]["description"] = "1-based last line to search"
850
+
851
+
852
+ _tighten_apply_edits_schema()
853
+
809
854
  def format_file_size(size_bytes: int) -> str:
810
855
  if size_bytes < 1024:
811
856
  return f"{size_bytes} B"
@@ -980,6 +1025,68 @@ def _resolve_project_root(args: dict) -> Tuple[Optional[str], Optional[str]]:
980
1025
 
981
1026
  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
1027
 
1028
+
1029
+ def _shared_batch_root(paths: List[str], real_cwd: str) -> Optional[str]:
1030
+ """Narrowest project directory that contains every absolute sub-query path.
1031
+
1032
+ Batch search is one root per call. When every explicit sub-query path lives
1033
+ outside the current root but inside one repo, that repo IS the root: rebasing
1034
+ there beats failing the call (agents batch a second checkout this way). Paths
1035
+ that share only a wide parent — the directory that also holds the current
1036
+ root, or two sibling repos — return None so the caller keeps the split rule.
1037
+ """
1038
+ try:
1039
+ shared = os.path.commonpath(paths)
1040
+ except ValueError:
1041
+ return None
1042
+ if os.path.isfile(shared):
1043
+ shared = os.path.dirname(shared)
1044
+ if not shared or shared == os.path.abspath(os.sep) or not os.path.isdir(shared):
1045
+ return None
1046
+
1047
+ def _swallows_cwd(candidate: str) -> bool:
1048
+ try:
1049
+ return os.path.commonpath([real_cwd, candidate]) == candidate
1050
+ except ValueError:
1051
+ return False
1052
+
1053
+ if _swallows_cwd(shared):
1054
+ return None
1055
+ # Prefer the enclosing project root, so a batch of sub-paths searches its
1056
+ # repo instead of just their common sub-directory.
1057
+ try:
1058
+ from src.graph_engine import GraphEngine
1059
+ shared = GraphEngine.find_project_root(shared)
1060
+ except Exception:
1061
+ pass
1062
+ if not os.path.isdir(shared) or _swallows_cwd(shared) or is_plugin_or_system_dir(shared):
1063
+ return None
1064
+ return shared
1065
+
1066
+
1067
+ def _oumv_workspace_arg(args: dict, allow_path: bool = False) -> Tuple[Optional[str], Optional[str]]:
1068
+ """Validated workspace root for an OUMV call; None means "use the active one".
1069
+
1070
+ The MCP server inherits the host process cwd, so without this an explicit
1071
+ target repo was either dropped (unadvertised property) or ignored, and the
1072
+ answer described the bound workspace. A root that does not exist now fails
1073
+ closed instead of reporting another repo's stack.
1074
+ """
1075
+ raw = str(args.get("workspace_dir") or "").strip()
1076
+ if not raw and allow_path:
1077
+ raw = str(args.get("path") or "").strip()
1078
+ if not raw:
1079
+ return None, None
1080
+ ws = os.path.abspath(raw)
1081
+ if os.path.isfile(ws):
1082
+ ws = os.path.dirname(ws)
1083
+ if not os.path.isdir(ws):
1084
+ return None, f"workspace_dir not found or not a directory: '{raw}'"
1085
+ if is_plugin_or_system_dir(ws):
1086
+ return None, f"refusing to use system root or plugin dir as workspace: '{ws}'"
1087
+ return ws, None
1088
+
1089
+
983
1090
  MCP_TOOL_TIMEOUT = float(os.environ.get("TOKENSAFE_MCP_TIMEOUT", "8.0"))
984
1091
 
985
1092
 
@@ -1141,6 +1248,113 @@ def _is_binary_file(path: str, probe_bytes: int = 4096) -> bool:
1141
1248
  return False
1142
1249
 
1143
1250
 
1251
+ # Line windows this session actually delivered per file. A batch hunk with no
1252
+ # start_line/end_line can be scoped to one of them when a target repeats: the
1253
+ # agent just read those lines, so an occurrence outside them is not the one it
1254
+ # means. Only a window containing exactly one occurrence qualifies — the tool
1255
+ # never chooses between two candidates.
1256
+ _LAST_READ_WINDOWS: Dict[str, List[Tuple[int, int]]] = {}
1257
+ _LAST_READ_WINDOWS_LOCK = threading.Lock()
1258
+ _MAX_READ_WINDOWS = 8
1259
+
1260
+
1261
+ def _remember_read_window(path: str, start: Any, end: Any) -> None:
1262
+ try:
1263
+ first, last = int(start), int(end)
1264
+ except (TypeError, ValueError):
1265
+ return
1266
+ if not path or first < 1 or last < first:
1267
+ return
1268
+ try:
1269
+ key = os.path.realpath(path)
1270
+ except OSError:
1271
+ key = os.path.abspath(path)
1272
+ with _LAST_READ_WINDOWS_LOCK:
1273
+ windows = _LAST_READ_WINDOWS.setdefault(key, [])
1274
+ entry = (first, last)
1275
+ if entry in windows:
1276
+ windows.remove(entry)
1277
+ windows.append(entry)
1278
+ del windows[:-_MAX_READ_WINDOWS]
1279
+
1280
+
1281
+ def _remember_rendered_windows(path: str, text: str) -> None:
1282
+ """Records every `// --- Lx-Ly` slice header in a rendered read (symbol hits,
1283
+ cross-file inlines). The header names the file when it is not the one read."""
1284
+ for match in re.finditer(r"// --- L(\d+)-L(\d+)(?: \(([^,()]+),)?", text or ""):
1285
+ target = os.path.join(os.path.dirname(path), match.group(3)) if match.group(3) else path
1286
+ _remember_read_window(target, match.group(1), match.group(2))
1287
+
1288
+
1289
+ def _autoscope_edits(edits: Any, cwd: str) -> Tuple[Any, List[str]]:
1290
+ """Scopes unambiguous hunks to the window the agent last read.
1291
+
1292
+ Returns (edits, notes). A hunk is touched only when it has no range, its
1293
+ target repeats in the file, and exactly one remembered window contains it.
1294
+ """
1295
+ if not isinstance(edits, list):
1296
+ return edits, []
1297
+ notes: List[str] = []
1298
+ out: List[Any] = []
1299
+ for edit in edits:
1300
+ if not isinstance(edit, dict) or not isinstance(edit.get("hunks"), list) or not edit.get("path"):
1301
+ out.append(edit)
1302
+ continue
1303
+ rel = str(edit.get("path"))
1304
+ abs_path = rel if os.path.isabs(rel) else os.path.join(cwd, rel)
1305
+ key = os.path.realpath(abs_path)
1306
+ with _LAST_READ_WINDOWS_LOCK:
1307
+ windows = list(_LAST_READ_WINDOWS.get(key) or [])
1308
+ if not windows:
1309
+ out.append(edit)
1310
+ continue
1311
+ try:
1312
+ with open(abs_path, "r", encoding="utf-8", errors="replace") as handle:
1313
+ content = handle.read()
1314
+ except OSError:
1315
+ out.append(edit)
1316
+ continue
1317
+ lines = content.splitlines()
1318
+ new_hunks: List[Any] = []
1319
+ changed = False
1320
+ for hunk in edit["hunks"]:
1321
+ if not isinstance(hunk, dict) or not isinstance(hunk.get("target"), str) or not hunk["target"]:
1322
+ new_hunks.append(hunk)
1323
+ continue
1324
+ if hunk.get("start_line") is not None or hunk.get("end_line") is not None:
1325
+ new_hunks.append(hunk)
1326
+ continue
1327
+ target = hunk["target"]
1328
+ if content.count(target) <= 1:
1329
+ new_hunks.append(hunk)
1330
+ continue
1331
+ candidates = []
1332
+ for start, end in windows:
1333
+ if start > len(lines):
1334
+ continue
1335
+ window_text = "\n".join(lines[start - 1:min(end, len(lines))])
1336
+ if window_text.count(target) == 1:
1337
+ candidates.append((start, min(end, len(lines))))
1338
+ if len(candidates) == 1:
1339
+ scoped = dict(hunk)
1340
+ scoped["start_line"], scoped["end_line"] = candidates[0]
1341
+ new_hunks.append(scoped)
1342
+ changed = True
1343
+ notes.append(
1344
+ f"`{rel}`: hunk auto-scoped to lines {candidates[0][0]}-{candidates[0][1]} "
1345
+ "(the target repeats; it occurs once in the window last read)"
1346
+ )
1347
+ else:
1348
+ new_hunks.append(hunk)
1349
+ if changed:
1350
+ clone = dict(edit)
1351
+ clone["hunks"] = new_hunks
1352
+ out.append(clone)
1353
+ else:
1354
+ out.append(edit)
1355
+ return out, notes
1356
+
1357
+
1144
1358
  def _read_line_slice(path: str, start_line: Optional[int], end_line: Optional[int]) -> Tuple[Optional[str], Optional[str]]:
1145
1359
  """Reads 1-based [start_line..end_line] using bounded iteration. Returns (content, err_msg)."""
1146
1360
  if start_line is not None and start_line < 1:
@@ -1498,6 +1712,7 @@ def _render_endpoint_slice(
1498
1712
  f"ver={version} via {hit.via}]"
1499
1713
  )
1500
1714
  body_lines, first, last = hit.body, hit.line, hit.end_line
1715
+ body_file = hit.file
1501
1716
  if hit.handler_kind == "named" and hit.handler:
1502
1717
  short = hit.handler.split(".")[-1]
1503
1718
  decls = [d for d in index.get(short, []) if d[0] != hit.file] or index.get(short, [])
@@ -1507,6 +1722,7 @@ def _render_endpoint_slice(
1507
1722
  with open(os.path.join(root, file), "r", encoding="utf-8", errors="replace") as handle:
1508
1723
  src = handle.read().splitlines()
1509
1724
  body_lines, first, last = src[start - 1:end], start, end
1725
+ body_file = file
1510
1726
  head = (
1511
1727
  f"// [TS endpoint {prefix}{verb} {route} → handler {short} in {file} "
1512
1728
  f"L{start}-L{end} ver={route_index.file_version(os.path.join(root, file))}]"
@@ -1524,6 +1740,7 @@ def _render_endpoint_slice(
1524
1740
  entries.append(f"// calls: {callees}")
1525
1741
  entries.append(f"// --- L{first}-L{last}")
1526
1742
  entries.extend(body_lines)
1743
+ _remember_read_window(os.path.join(root, body_file), first, last)
1527
1744
  delivered = "\n".join(entries) + "\n"
1528
1745
  if tracker is not None:
1529
1746
  try:
@@ -1732,6 +1949,18 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1732
1949
  action = str(args.get("action") or "status").strip().lower()
1733
1950
  if action not in _OUMV_ACTIONS:
1734
1951
  return _fallback_error("oumv", f"unknown action '{action}'")
1952
+ # Target-repo routing: the MCP server inherits the host's cwd, so an agent
1953
+ # inspecting a second repo (workspace_dir, or `path` for the read actions)
1954
+ # used to get the bound workspace's stack back with no error — a silently
1955
+ # wrong answer. Resolve the explicit root here and fail closed on a bad one.
1956
+ ws, ws_err = _oumv_workspace_arg(
1957
+ args,
1958
+ allow_path=action in ("status", "observe", "understand", "verify", "graph"),
1959
+ )
1960
+ if ws_err:
1961
+ return _fallback_error("oumv", ws_err)
1962
+ if ws:
1963
+ args = dict(args, workspace_dir=ws)
1735
1964
  mapped = _OUMV_ACTIONS[action]
1736
1965
  if action == "verify":
1737
1966
  args = dict(args, action=args.get("verify_action") or "invoke")
@@ -1980,6 +2209,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1980
2209
  slice_lines = (content or "").splitlines()
1981
2210
  slice_first = start_line if start_line is not None else 1
1982
2211
  slice_last = slice_first + len(slice_lines) - 1 if slice_lines else max(1, slice_first - 1)
2212
+ _remember_read_window(path, slice_first, slice_last)
1983
2213
  range_label = f"{slice_first}-{slice_last}" if slice_lines else str(slice_first)
1984
2214
  prefetch_block = ""
1985
2215
  if not sym_clean or eff_dep_mode == "full":
@@ -2017,6 +2247,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2017
2247
  scope_plan = None
2018
2248
  if scope_plan and scope_plan["status"] in ("body_here", "absent"):
2019
2249
  anchored = _render_symbol_scope_miss(scope_plan, path, symbol, raw_for_scope)
2250
+ _remember_rendered_windows(path, anchored)
2020
2251
  tracker.record_event(
2021
2252
  session_id=_mcp_session_id(),
2022
2253
  event_type="SYMBOL_TEXT_ANCHOR",
@@ -3010,7 +3241,10 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3010
3241
  elif name == "oumv_status":
3011
3242
  try:
3012
3243
  from src.oumv_gateway import OUMVGateway
3013
- ws = str(args.get("workspace_dir") or "").strip() or get_active_workspace() or os.getcwd()
3244
+ ws, ws_err = _oumv_workspace_arg(args, allow_path=True)
3245
+ if ws_err:
3246
+ return _fallback_error("oumv_status", ws_err)
3247
+ ws = ws or get_active_workspace() or os.getcwd()
3014
3248
  res = OUMVGateway.status(workspace_dir=ws)
3015
3249
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
3016
3250
  except Exception as e:
@@ -3022,7 +3256,9 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3022
3256
  lvl = str(args.get("level") or "L0").strip()
3023
3257
  tgt = str(args.get("target") or "").strip() or None
3024
3258
  rt = str(args.get("runtime") or "auto").strip()
3025
- ws = str(args.get("workspace_dir") or "").strip() or None
3259
+ ws, ws_err = _oumv_workspace_arg(args)
3260
+ if ws_err:
3261
+ return _fallback_error("oumv_observe", ws_err)
3026
3262
  res = OUMVGateway.observe(level=lvl, target=tgt, runtime=rt, workspace_dir=ws)
3027
3263
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
3028
3264
  except Exception as e:
@@ -3034,7 +3270,9 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3034
3270
  qry = str(args.get("query") or "causality").strip()
3035
3271
  tgt = str(args.get("target") or "").strip() or None
3036
3272
  rt = str(args.get("runtime") or "auto").strip()
3037
- ws = str(args.get("workspace_dir") or "").strip() or None
3273
+ ws, ws_err = _oumv_workspace_arg(args)
3274
+ if ws_err:
3275
+ return _fallback_error("oumv_understand", ws_err)
3038
3276
  res = OUMVGateway.understand(query=qry, target=tgt, runtime=rt, workspace_dir=ws)
3039
3277
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
3040
3278
  except Exception as e:
@@ -3048,7 +3286,9 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3048
3286
  rep = args.get("replacement")
3049
3287
  ev = str(args.get("expectedVersion") or "").strip() or None
3050
3288
  rt = str(args.get("runtime") or "auto").strip()
3051
- ws = str(args.get("workspace_dir") or "").strip() or None
3289
+ ws, ws_err = _oumv_workspace_arg(args)
3290
+ if ws_err:
3291
+ return _fallback_error("oumv_mutate", ws_err)
3052
3292
  res = OUMVGateway.mutate(path=p, symbol=sym, replacement=rep, expected_version=ev, runtime=rt, workspace_dir=ws)
3053
3293
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
3054
3294
  except Exception as e:
@@ -3061,8 +3301,11 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3061
3301
  act = str(args.get("action") or "invoke").strip()
3062
3302
  payload = args.get("payload") if isinstance(args.get("payload"), dict) else None
3063
3303
  rt = str(args.get("runtime") or "auto").strip()
3064
- ws = str(args.get("workspace_dir") or "").strip() or None
3065
- res = OUMVGateway.verify(target=tgt, action=act, payload=payload, runtime=rt, workspace_dir=ws)
3304
+ ws, ws_err = _oumv_workspace_arg(args)
3305
+ if ws_err:
3306
+ return _fallback_error("oumv_verify", ws_err)
3307
+ sandbox = args.get("sandbox") if isinstance(args.get("sandbox"), dict) else None
3308
+ res = OUMVGateway.verify(target=tgt, action=act, payload=payload, runtime=rt, workspace_dir=ws, sandbox=sandbox)
3066
3309
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
3067
3310
  except Exception as e:
3068
3311
  return _fallback_error("oumv_verify", f"failed to verify OUMV action: {e}")
@@ -3072,7 +3315,9 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3072
3315
  from src.oumv_gateway import OUMVGateway
3073
3316
  qry = str(args.get("query") or "overview").strip()
3074
3317
  tgt = str(args.get("target") or "").strip() or None
3075
- ws = str(args.get("workspace_dir") or "").strip() or None
3318
+ ws, ws_err = _oumv_workspace_arg(args)
3319
+ if ws_err:
3320
+ return _fallback_error("oumv_graph", ws_err)
3076
3321
  res = OUMVGateway.graph(query=qry, target=tgt, workspace_dir=ws)
3077
3322
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
3078
3323
  except Exception as e:
@@ -3102,6 +3347,11 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3102
3347
  if is_plugin_or_system_dir(cwd):
3103
3348
  return _fallback_error("apply_edits", f"refusing to run apply_edits in system root or plugin dir '{cwd}'")
3104
3349
 
3350
+ # Deterministic recovery for a repeated hunk target: if the session just
3351
+ # read a window that contains exactly one occurrence, scope the hunk to
3352
+ # it instead of handing the model another round trip.
3353
+ edits, scope_notes = _autoscope_edits(edits, cwd)
3354
+
3105
3355
  res = execute_batch_edits(
3106
3356
  edits=edits,
3107
3357
  best_effort=best_effort,
@@ -3137,6 +3387,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3137
3387
  is_cr = f.get("is_create", False)
3138
3388
  label = "created" if is_cr else f"{h_cnt} hunk(s)"
3139
3389
  lines.append(f" - `{f.get('path')}` ({label})")
3390
+ for note in scope_notes:
3391
+ lines.append(f" ↳ {note}")
3140
3392
 
3141
3393
  if "verify" in res:
3142
3394
  v = res["verify"]
@@ -3224,9 +3476,15 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3224
3476
 
3225
3477
  safe_queries: List[Dict[str, Any]] = []
3226
3478
  real_cwd = os.path.realpath(cwd)
3479
+ # Pass 1: resolve every sub-query path. A relative path that climbs out
3480
+ # of the root is still a hard error (traversal); absolute paths are an
3481
+ # explicit intent to search elsewhere, so they may be rebased below.
3482
+ q_copies: List[Any] = []
3483
+ path_abs: Dict[int, str] = {}
3484
+ outside: List[str] = []
3227
3485
  for q_item in queries:
3228
3486
  if not isinstance(q_item, dict):
3229
- safe_queries.append(q_item)
3487
+ q_copies.append(q_item)
3230
3488
  continue
3231
3489
  q_copy = dict(q_item)
3232
3490
  sub_p = q_copy.get("path")
@@ -3243,18 +3501,54 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3243
3501
  except ValueError:
3244
3502
  inside = False
3245
3503
  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
- )
3504
+ if not os.path.isabs(str(sub_p)):
3505
+ return _fallback_error(
3506
+ "batch_search",
3507
+ f"subquery path '{sub_p}' resolves to '{sub_abs}', outside project root "
3508
+ f"'{real_cwd}'. One call searches one root: pass that repo as cwd/project_path "
3509
+ f"with repo-relative paths, and split queries for other repos into separate calls.",
3510
+ )
3511
+ outside.append(sub_abs)
3512
+ path_abs[len(q_copies)] = sub_abs
3513
+ q_copies.append(q_copy)
3514
+
3515
+ rebased_from: Optional[str] = None
3516
+ if outside:
3517
+ shared_root = _shared_batch_root(outside, real_cwd) if len(outside) == len(path_abs) else None
3518
+ if not shared_root:
3519
+ detail = (
3520
+ "queries mix paths inside and outside it"
3521
+ if len(outside) != len(path_abs)
3522
+ else "they share no single enclosing project directory"
3523
+ )
3524
+ return _fallback_error(
3525
+ "batch_search",
3526
+ f"subquery paths resolve outside project root '{real_cwd}' and {detail}. "
3527
+ f"One call searches one root: pass that repo as cwd/project_path with "
3528
+ f"repo-relative paths, and split queries for other repos into separate calls.",
3529
+ )
3530
+ rebased_from = cwd
3531
+ cwd = shared_root
3532
+ real_cwd = os.path.realpath(shared_root)
3533
+ for idx, sub_abs in path_abs.items():
3534
+ if isinstance(q_copies[idx], dict):
3535
+ q_copies[idx]["path"] = os.path.relpath(sub_abs, shared_root)
3536
+
3537
+ for q_copy in q_copies:
3538
+ if not isinstance(q_copy, dict):
3539
+ safe_queries.append(q_copy)
3540
+ continue
3252
3541
  if is_quota_exceeded:
3253
3542
  q_copy["max_results"] = min(_safe_int(q_copy.get("max_results"), 3, lo=1, hi=100), 3)
3254
3543
  safe_queries.append(q_copy)
3255
3544
 
3256
3545
  res = execute_batch_search(queries=safe_queries, cwd=cwd)
3257
3546
  summary_md = res.get("summary_md", "")
3547
+ if rebased_from:
3548
+ summary_md = (
3549
+ f"// [TokenSafe: batch root auto-rebased to '{cwd}' (was '{rebased_from}') — "
3550
+ f"every subquery path lives there]\n" + summary_md
3551
+ )
3258
3552
  if is_quota_exceeded:
3259
3553
  banner = _quota_banner_if_due(quota, tracker, _mcp_session_id())
3260
3554
  current_tier = str(quota.get("tier") or "guest").lower()
@@ -801,7 +801,7 @@ class OUMVGateway:
801
801
 
802
802
  # 5. Tool: oumv_verify
803
803
  @classmethod
804
- def verify(cls, target: str, action: str = "invoke", payload: Optional[dict] = None, runtime: str = "auto", workspace_dir: Optional[str] = None) -> Any:
804
+ def verify(cls, target: str, action: str = "invoke", payload: Optional[dict] = None, runtime: str = "auto", workspace_dir: Optional[str] = None, sandbox: Optional[dict] = None) -> Any:
805
805
  cls.mark_oumv_used(workspace_dir)
806
806
  if runtime == "backend":
807
807
  _, be = cls.get_endpoints(workspace_dir=workspace_dir)
@@ -810,12 +810,17 @@ class OUMVGateway:
810
810
  if notice:
811
811
  return {"status": "unsupported", **notice}
812
812
  url = cls._resolve_client_url(runtime=runtime, target=target, workspace_dir=workspace_dir)
813
- res = cls._rpc_call(url, "oumv/verify", {
813
+ params = {
814
814
  "target": target,
815
815
  "componentId": target,
816
816
  "action": action,
817
817
  "payload": payload or {},
818
- })
818
+ }
819
+ # spec §4 (wire 1.4.0): the runtime decides whether it can honour the
820
+ # sandbox; we forward the request instead of guessing.
821
+ if isinstance(sandbox, dict) and sandbox.get("mode"):
822
+ params["sandbox"] = sandbox
823
+ res = cls._rpc_call(url, "oumv/verify", params)
819
824
  # Honest verification scope (spec §13): state exactly what was verified.
820
825
  if isinstance(res, dict):
821
826
  scope = res.setdefault("scope", {})