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.
@@ -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/cli.py CHANGED
@@ -903,7 +903,7 @@ def main(argv: Optional[List[str]] = None):
903
903
  cmd, source = resolve_zero_footprint_vite_command(
904
904
  target_dir, port=port_val, host=host_val, open_browser=open_browser
905
905
  )
906
- print(f"⚡ Launching Zero-Footprint Vite+React OUMV server ({source})...")
906
+ print(f"⚡ Launching Zero-Footprint Vite OUMV server ({source})...")
907
907
  proc = subprocess.run(cmd, cwd=target_dir)
908
908
  sys.exit(proc.returncode)
909
909
 
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"
@@ -2818,16 +2818,9 @@ WantedBy=default.target
2818
2818
  except Exception:
2819
2819
  pass
2820
2820
 
2821
- if pip_cmd:
2822
- try:
2823
- res = subprocess.run([pip_cmd, "list"], capture_output=True, text=True, timeout=10)
2824
- if "tokensafe-python" in (res.stdout or ""):
2825
- print(f" {CYAN}→{RESET} Updating backend package ({pip_cmd} install --upgrade tokensafe-python)...")
2826
- up_res = subprocess.run([pip_cmd, "install", "--upgrade", "tokensafe-python"], capture_output=True, text=True, timeout=120)
2827
- if up_res.returncode == 0:
2828
- print(f" {GREEN}✔{RESET} tokensafe-python upgraded successfully.")
2829
- except Exception:
2830
- pass
2821
+ # The Python backend runtime is installed per project from git
2822
+ # (`tokensafe-backend-python @ git+…`), not as a global pip distribution —
2823
+ # there is no `tokensafe-python` package to upgrade here.
2831
2824
 
2832
2825
  # Project-level dependencies update (if inside a TokenSafe project)
2833
2826
  cwd = os.getcwd()
@@ -2846,18 +2839,7 @@ WantedBy=default.target
2846
2839
  except Exception:
2847
2840
  pass
2848
2841
 
2849
- for cand_py in [os.path.join(cwd, "pyproject.toml"), os.path.join(cwd, "backend", "pyproject.toml")]:
2850
- if os.path.isfile(cand_py):
2851
- try:
2852
- with open(cand_py, "r", encoding="utf-8") as f:
2853
- txt = f.read()
2854
- if "tokensafe-python" in txt and pip_cmd:
2855
- pdir = os.path.dirname(cand_py)
2856
- print(f" {CYAN}→{RESET} Updating local tokensafe-python in {pdir}...")
2857
- subprocess.run([pip_cmd, "install", "--upgrade", "tokensafe-python"], cwd=pdir, capture_output=True, text=True, timeout=60)
2858
- print(f" {GREEN}✔{RESET} Local tokensafe-python updated.")
2859
- except Exception:
2860
- pass
2842
+ # Per-project Python backend installs come from git; nothing global to update.
2861
2843
 
2862
2844
  # 4. Re-synchronize active/configured agents using the FRESHLY upgraded binary when available
2863
2845
  # (so plugins, hooks, skills, and rules come from the new release instead of the old process).