tokensafe 4.7.3 → 4.7.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "4.7.3",
3
+ "version": "4.7.5",
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.3",
4
+ "version": "4.7.5",
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": {
@@ -11,6 +11,7 @@
11
11
  "bin/tokensafe.js",
12
12
  "bin/tokensafe",
13
13
  "bin/agy-tokens",
14
+ "bin/python-runtime.json",
14
15
  "src/",
15
16
  "!src/cloud_backend.py",
16
17
  "!src/mailer.py",
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "4.7.3",
4
+ "version": "4.7.5",
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.3",
6
+ "version": "4.7.5",
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.3",
26
+ "version": "4.7.5",
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.3",
42
+ "version": "4.7.5",
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)
@@ -13,6 +13,7 @@ from __future__ import annotations
13
13
 
14
14
  import json
15
15
  import os
16
+ import time
16
17
  import urllib.error
17
18
  import urllib.request
18
19
  from dataclasses import dataclass, field
@@ -83,17 +84,21 @@ class BudgetExceeded(RuntimeError):
83
84
 
84
85
 
85
86
  class DeepSeekClient:
87
+ _RETRY_STATUS = frozenset({408, 429, 500, 502, 503, 504})
88
+
86
89
  def __init__(
87
90
  self,
88
91
  model: str = "deepseek-chat",
89
92
  temperature: float = 0.0,
90
93
  base_url: Optional[str] = None,
91
- timeout: float = 120.0,
94
+ timeout: float = 300.0,
95
+ retries: int = 4,
92
96
  ):
93
97
  self.model = model
94
98
  self.temperature = temperature
95
99
  self.base_url = (base_url or os.environ.get("DEEPSEEK_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
96
100
  self.timeout = timeout
101
+ self.retries = max(1, int(retries))
97
102
  self.api_key = resolve_api_key()
98
103
  if not self.api_key:
99
104
  raise RuntimeError(
@@ -101,6 +106,11 @@ class DeepSeekClient:
101
106
  "into ~/.tokensafe/data/config.json"
102
107
  )
103
108
 
109
+ @staticmethod
110
+ def _backoff(attempt: int) -> float:
111
+ # 5s, 15s, 30s: a paid matrix must survive a flaky read, not restart.
112
+ return min(30.0, 5.0 * (3 ** (attempt - 1)))
113
+
104
114
  def chat(self, messages: List[Dict[str, Any]], tools: Optional[List[Dict[str, Any]]] = None) -> Tuple[Dict[str, Any], Dict[str, Any]]:
105
115
  body: Dict[str, Any] = {
106
116
  "model": self.model,
@@ -110,18 +120,35 @@ class DeepSeekClient:
110
120
  if tools:
111
121
  body["tools"] = tools
112
122
  body["tool_choice"] = "auto"
113
- req = urllib.request.Request(
114
- f"{self.base_url}/chat/completions",
115
- data=json.dumps(body).encode(),
116
- headers={"Content-Type": "application/json", "Authorization": f"Bearer {self.api_key}"},
117
- method="POST",
118
- )
119
- try:
120
- with urllib.request.urlopen(req, timeout=self.timeout) as resp:
121
- payload = json.loads(resp.read().decode())
122
- except urllib.error.HTTPError as exc:
123
- raise RuntimeError(f"provider HTTP {exc.code}: {exc.read().decode()[:300]}") from exc
124
- return payload["choices"][0]["message"], payload.get("usage") or {}
123
+ data = json.dumps(body).encode()
124
+ last_error = ""
125
+ for attempt in range(1, self.retries + 1):
126
+ req = urllib.request.Request(
127
+ f"{self.base_url}/chat/completions",
128
+ data=data,
129
+ headers={"Content-Type": "application/json", "Authorization": f"Bearer {self.api_key}"},
130
+ method="POST",
131
+ )
132
+ try:
133
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
134
+ payload = json.loads(resp.read().decode())
135
+ return payload["choices"][0]["message"], payload.get("usage") or {}
136
+ except urllib.error.HTTPError as exc:
137
+ last_error = f"provider HTTP {exc.code}: {exc.read().decode()[:300]}"
138
+ if exc.code not in self._RETRY_STATUS or attempt == self.retries:
139
+ raise RuntimeError(last_error) from exc
140
+ except (TimeoutError, urllib.error.URLError, ConnectionResetError, json.JSONDecodeError) as exc:
141
+ # A long generation can outlive the socket read, and a truncated body is
142
+ # not valid JSON. Both are transient and must not kill a paid matrix
143
+ # mid-run: the first v5 attempt died after ~$0.14 with 45 sessions
144
+ # collected and nothing written.
145
+ last_error = f"{type(exc).__name__}: {exc}"
146
+ if attempt == self.retries:
147
+ raise RuntimeError(
148
+ f"provider call failed after {self.retries} attempts — {last_error}"
149
+ ) from exc
150
+ time.sleep(self._backoff(attempt))
151
+ raise RuntimeError(f"provider call failed — {last_error}")
125
152
 
126
153
 
127
154
  ToolFn = Callable[..., Any]
@@ -75,11 +75,96 @@ def _run(cmd: List[str], cwd: Path, timeout: float = 240.0, env: Optional[Dict[s
75
75
  return subprocess.run(cmd, cwd=str(cwd), capture_output=True, text=True, timeout=timeout, env=env)
76
76
 
77
77
 
78
+ _FILLER_VERBS = ("List", "Create", "Pay", "Ship", "Cancel", "Get", "Update", "Delete")
79
+ _FILLER_NOUNS = ("Products", "Orders", "Carts", "Invoices", "Users", "Coupons")
80
+
81
+
82
+ def _generate_filler(root: Path, count: int) -> None:
83
+ """`count` generated service files so discovery competes with a real tree.
84
+
85
+ The oracle and the broken handler are untouched: only the amount of code a
86
+ workspace search or a read has to get through grows, which is the variable
87
+ matrix v4 could not measure on 69 files. Generated at copy time, never
88
+ committed — the product repo stays clean and the target is reproducible from
89
+ `--files N` alone.
90
+ """
91
+ pkg = root / "benchmark" / "sandboxes" / "gen"
92
+ pkg.mkdir(parents=True, exist_ok=True)
93
+ for idx in range(count):
94
+ noun = _FILLER_NOUNS[idx % len(_FILLER_NOUNS)]
95
+ verb = _FILLER_VERBS[(idx // len(_FILLER_NOUNS)) % len(_FILLER_VERBS)]
96
+ name = f"Svc{idx:03d}"
97
+ route = f"/api/{noun.lower()}"
98
+ (pkg / f"svc{idx:03d}.go").write_text(
99
+ f'''package gen
100
+
101
+ // Generated benchmark fixture — an unrelated service that mirrors the
102
+ // {noun.lower()} API surface ({verb}{noun} -> {route}) and mentions
103
+ // StatusCreated / StatusConflict / CONFLICT: so a status-code search has to
104
+ // distinguish a placeholder from the real handler.
105
+
106
+ import "net/http"
107
+
108
+ // {name} is not mounted anywhere; it exists so discovery has real competition.
109
+ type {name} struct{{}}
110
+
111
+ // {verb}{noun} is a placeholder for {route}.
112
+ func (h {name}) {verb}{noun}(w http.ResponseWriter, r *http.Request) {{
113
+ \tw.WriteHeader(http.StatusOK)
114
+ }}
115
+ ''',
116
+ encoding="utf-8",
117
+ )
118
+
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
+
78
162
  class GoWorkspace:
79
- def __init__(self, task_id: str):
163
+ def __init__(self, task_id: str, files: int = 0):
80
164
  if task_id not in TASKS:
81
165
  raise ValueError(f"unknown task {task_id}; valid: {', '.join(TASKS)}")
82
166
  self.task_id = task_id
167
+ self.files = int(files or 0)
83
168
  self.dir = Path(tempfile.mkdtemp(prefix=f"oumv-bench-{task_id}-")) / "go"
84
169
  self.dir.mkdir(parents=True)
85
170
  for item in COPY_ITEMS:
@@ -89,12 +174,18 @@ class GoWorkspace:
89
174
  shutil.copytree(src, dst)
90
175
  else:
91
176
  shutil.copy2(src, dst)
177
+ if self.files:
178
+ _generate_filler(self.dir, self.files)
92
179
  # The runtime must serve the *workspace* code: build the helper inside the
93
180
  # copied module and rebuild it when an edit changes the sources, otherwise
94
181
  # oumv/verify would keep reporting the pristine app's behaviour.
95
182
  self.helper = self.dir.parent / "benchoumv"
96
183
  self._helper_built_at = 0.0
97
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]] = {}
98
189
  self.break_build()
99
190
 
100
191
  # ---- task setup -------------------------------------------------------
@@ -254,7 +345,78 @@ class GoWorkspace:
254
345
  return {"error": f"invalid JSON from helper: {line[-1][:200]}"}
255
346
  if payload.get("error"):
256
347
  return {"error": payload["error"]}
257
- 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
258
420
 
259
421
  def tokensafe_tool_schemas(self) -> Optional[List[Dict[str, Any]]]:
260
422
  """The product's own `tools/list`, renamed to the arm's stable aliases.
@@ -471,18 +633,40 @@ OUMV_TOOLS: List[Dict[str, Any]] = BASE_TOOLS + [
471
633
  "name": "oumv_applyEdit",
472
634
  "description": (
473
635
  "OUMV guarded edit: applies only if `expectedVersion` matches the file on disk. "
474
- "mode='symbol' replaces one declaration (cheaper than the whole file)."
636
+ "mode='patch' splices hunks (cheapest — the file is never re-sent); mode='symbol' "
637
+ "replaces one declaration; mode='replace' rewrites the whole file."
475
638
  ),
476
639
  "parameters": {
477
640
  "type": "object",
478
641
  "properties": {
479
642
  "path": {"type": "string"},
480
- "replacement": {"type": "string", "description": "New file content, or the new declaration body for mode='symbol'"},
481
- "expectedVersion": {"type": "string", "description": "sha256 version from oumv_getSource"},
482
- "mode": {"type": "string", "enum": ["replace", "symbol"]},
643
+ "expectedVersion": {"type": "string", "description": "version from oumv_observe L3 or oumv_getSource"},
644
+ "mode": {"type": "string", "enum": ["patch", "symbol", "replace"]},
645
+ "hunks": {
646
+ "type": "array",
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
+ ),
652
+ "items": {
653
+ "type": "object",
654
+ "properties": {
655
+ "target": {"type": "string", "description": "Exact snippet from the source"},
656
+ "replacement": {"type": "string", "description": "Replacement snippet"},
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"},
662
+ },
663
+ "required": ["target", "replacement"],
664
+ },
665
+ },
666
+ "replacement": {"type": "string", "description": "New content, or the new declaration body for mode='symbol'"},
483
667
  "symbol": {"type": "string", "description": "Declaration to replace when mode='symbol'"},
484
668
  },
485
- "required": ["path", "replacement", "expectedVersion"],
669
+ "required": ["path", "expectedVersion"],
486
670
  },
487
671
  },
488
672
  },
@@ -587,15 +771,13 @@ def registry(ws: GoWorkspace, arm: str) -> Dict[str, Any]:
587
771
  tools.update({
588
772
  "oumv_observe": lambda level, target="": ws.oumv("oumv/observe", {"level": level, "target": target}),
589
773
  "oumv_getSource": lambda path, symbol="": ws.oumv("oumv/getSource", {"path": path, "symbol": symbol}),
590
- "oumv_applyEdit": lambda path, replacement, expectedVersion, mode="", symbol="": ws.oumv(
591
- "oumv/applyEdit",
592
- {
593
- "path": path,
594
- "replacement": replacement,
595
- "expectedVersion": expectedVersion,
596
- **({"mode": mode} if mode else {}),
597
- **({"symbol": symbol} if symbol else {}),
598
- },
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,
599
781
  ),
600
782
  "oumv_verify": lambda target, payload=None: ws.oumv(
601
783
  "oumv/verify", {"target": target, "action": "probe", "payload": payload}
@@ -630,12 +812,15 @@ SYSTEM_OUMV = (
630
812
  "You are a senior Go engineer working in a small Go module that exposes the OUMV runtime. "
631
813
  "The bug report includes a repro; use it to go straight to the right handler instead of guessing payloads. "
632
814
  "Use this loop and stop as soon as the oracle passes: (1) oumv_observe L3 with the failing endpoint target "
633
- "(e.g. \"POST /api/products\") — it returns the handler body, its workspace path and the sha256 OCC version; "
634
- "(2) oumv_getSource for that path once to get the full file bytes; (3) oumv_applyEdit with the fixed file and "
635
- "the version from step 1 or 2 (it rejects a stale version); (4) confirm with oumv_verify when the repro is a "
636
- "single request. When the failure needs state created by earlier requests, run the oracle with run_command "
637
- "instead — oumv_verify intentionally starts a fresh app per call. Do not call list_files/read_file unless an "
638
- "OUMV tool returns an error. Tests are read-only."
815
+ "(e.g. \"POST /api/products\") — ONE call returns the handler source, its workspace path, startLine/endLine and "
816
+ "the sha256 OCC version; (2) oumv_applyEdit with that path + expectedVersion and mode=\"patch\", "
817
+ "hunks=[{target: the exact line(s) you change, replacement: the fix, startLine: the line number from step 1, "
818
+ "endLine: the same line}] — scoping the hunk keeps it unique when the snippet appears elsewhere in the file; "
819
+ "the file is never re-sent and the edit is rejected on a "
820
+ "stale version; (3) if the result is an error, read the reported reason and repeat (2); (4) run_command to run "
821
+ "the oracle (oumv_verify starts a fresh app per call, so use it only for a single stateless request). "
822
+ "Do not fetch whole files with getSource and do not use write_file: the patch IS the edit. Do not call "
823
+ "list_files/read_file unless an OUMV tool returns an error. Tests are read-only."
639
824
  )
640
825
 
641
826
 
@@ -18,8 +18,9 @@ def run_one(
18
18
  model: str = "deepseek-chat",
19
19
  max_steps: int = 14,
20
20
  budget_usd: float = 1.0,
21
+ files: int = 0,
21
22
  ) -> Dict[str, Any]:
22
- ws = go_target.GoWorkspace(task_id)
23
+ ws = go_target.GoWorkspace(task_id, files=files)
23
24
  started = time.time()
24
25
  try:
25
26
  before = ws.oracle()
@@ -62,6 +63,58 @@ def run_one(
62
63
  ws.cleanup()
63
64
 
64
65
 
66
+ def _matrix_report(
67
+ tasks: List[str],
68
+ arms: List[str],
69
+ runs: int,
70
+ model: str,
71
+ budget_usd: float,
72
+ files: int,
73
+ results: List[Dict[str, Any]],
74
+ spent: float,
75
+ aborted: Optional[str],
76
+ ) -> Dict[str, Any]:
77
+ return {
78
+ "target": "go",
79
+ "sandbox_files": files,
80
+ "tasks": tasks,
81
+ "arms": arms,
82
+ "runs": runs,
83
+ "model": model,
84
+ "budget_usd": budget_usd,
85
+ "spent_usd": round(spent, 6),
86
+ "aborted": aborted,
87
+ "results": results,
88
+ "provenance": _provenance("go", tasks, arms),
89
+ "generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
90
+ }
91
+
92
+
93
+ def checkpoint_path(files: int = 0) -> Path:
94
+ from src.paths import resolve_data_dir
95
+
96
+ label = f"go-{files}f" if files else "go"
97
+ return Path(resolve_data_dir()) / "bench" / f"{label}-checkpoint.json"
98
+
99
+
100
+ def _write_checkpoint(files: int, report: Dict[str, Any]) -> None:
101
+ """Persist every finished session immediately.
102
+
103
+ The first v5 attempt spent ~$0.14 and lost all 45 rows to a socket timeout in
104
+ the last provider call, because the artifact was only written once at the end.
105
+ A checkpoint per row costs nothing and makes a crash resumable by reading the
106
+ finished rows instead of paying for them twice.
107
+ """
108
+ path = checkpoint_path(files)
109
+ try:
110
+ path.parent.mkdir(parents=True, exist_ok=True)
111
+ tmp = path.with_suffix(".tmp")
112
+ tmp.write_text(json.dumps({**report, "partial": True}, indent=2, ensure_ascii=False), encoding="utf-8")
113
+ tmp.replace(path)
114
+ except OSError:
115
+ pass
116
+
117
+
65
118
  def run_matrix(
66
119
  tasks: List[str],
67
120
  arms: List[str],
@@ -69,6 +122,7 @@ def run_matrix(
69
122
  model: str = "deepseek-chat",
70
123
  max_steps: int = 14,
71
124
  budget_usd: float = 1.0,
125
+ files: int = 0,
72
126
  ) -> Dict[str, Any]:
73
127
  results: List[Dict[str, Any]] = []
74
128
  spent = 0.0
@@ -80,27 +134,18 @@ def run_matrix(
80
134
  aborted = f"global budget ${budget_usd} exhausted after ${spent:.4f}"
81
135
  break
82
136
  per_run_budget = max(budget_usd - spent, 0.01)
83
- row = run_one(arm, task_id, model=model, max_steps=max_steps, budget_usd=per_run_budget)
137
+ row = run_one(arm, task_id, model=model, max_steps=max_steps,
138
+ budget_usd=per_run_budget, files=files)
84
139
  row["run"] = run_idx
85
140
  results.append(row)
86
141
  spent += float((row.get("usage") or {}).get("usd") or 0.0)
142
+ _write_checkpoint(files, _matrix_report(tasks, arms, runs, model, budget_usd, files,
143
+ results, spent, aborted))
87
144
  if aborted:
88
145
  break
89
146
  if aborted:
90
147
  break
91
- return {
92
- "target": "go",
93
- "tasks": tasks,
94
- "arms": arms,
95
- "runs": runs,
96
- "model": model,
97
- "budget_usd": budget_usd,
98
- "spent_usd": round(spent, 6),
99
- "aborted": aborted,
100
- "results": results,
101
- "provenance": _provenance("go", tasks, arms),
102
- "generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
103
- }
148
+ return _matrix_report(tasks, arms, runs, model, budget_usd, files, results, spent, aborted)
104
149
 
105
150
 
106
151
 
@@ -260,6 +305,12 @@ def render_markdown(report: Dict[str, Any]) -> str:
260
305
  else "the real 12-assertion oracle (`go test ./benchmark -run TestGroundTruthOracleVanilla`)"
261
306
  )
262
307
  sandbox = "the `agent-dom` React benchmark sandbox" if target == "react" else "the `tokensafe-backend/go` module"
308
+ files = int(report.get("sandbox_files") or 0)
309
+ sandbox_line = (
310
+ f"- Each arm starts from a throwaway copy of {sandbox} with one deliberate regression"
311
+ + (f", plus {files} generated service files so discovery competes with a realistic tree" if files else "")
312
+ + "."
313
+ )
263
314
  lines = [
264
315
  f"# OUMV benchmark — {target} sandbox (measured)",
265
316
  "",
@@ -268,10 +319,12 @@ def render_markdown(report: Dict[str, Any]) -> str:
268
319
  "",
269
320
  "## Methodology",
270
321
  "",
271
- f"- Each arm starts from a throwaway copy of {sandbox} with one deliberate regression.",
322
+ sandbox_line,
272
323
  f"- Correctness is {oracle}, re-run after every agent step.",
273
324
  "- Token and cost numbers come from the provider `usage` payload; prices are a pinned snapshot printed in the JSON artifact.",
274
- "- `baseline` uses file/command tools only; `oumv` gets the same tools plus observe/getSource/applyEdit/understand served by the shipped OUMV adapter.",
325
+ "- `baseline` uses file/command tools only; `tokensafe` adds the shipped MCP tools (`smart_read_file` with "
326
+ "`endpoint=`, `scoped_search`, `apply_edits` with inline verify); `oumv` adds observe L3 (endpoint → handler "
327
+ "source + version) and `applyEdit` `mode=patch` (hunks) served by the shipped OUMV adapter.",
275
328
  "",
276
329
  "## Results",
277
330
  "",
@@ -324,8 +377,15 @@ def write_artifacts(report: Dict[str, Any], out_dir: Optional[Path] = None) -> D
324
377
  base.mkdir(parents=True, exist_ok=True)
325
378
  stamp = time.strftime("%Y%m%d-%H%M%S", time.gmtime())
326
379
  target = report.get("target", "go")
327
- json_path = base / f"{target}-{stamp}.json"
328
- md_path = base / f"{target}-{stamp}.md"
380
+ files = int(report.get("sandbox_files") or 0)
381
+ label = f"{target}-{files}f" if files else target
382
+ json_path = base / f"{label}-{stamp}.json"
383
+ md_path = base / f"{label}-{stamp}.md"
329
384
  json_path.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")
330
385
  md_path.write_text(render_markdown(report), encoding="utf-8")
386
+ # The final artifact supersedes the per-row checkpoint.
387
+ try:
388
+ checkpoint_path(files).unlink()
389
+ except OSError:
390
+ pass
331
391
  return {"json": str(json_path), "markdown": str(md_path)}
package/src/cli.py CHANGED
@@ -952,21 +952,25 @@ def main(argv: Optional[List[str]] = None):
952
952
  budget = float(_flag("--budget", "1.0"))
953
953
  model = _flag("--model", "deepseek-chat")
954
954
  max_steps = int(_flag("--max-steps", "14"))
955
+ files = int(_flag("--files", "0"))
955
956
 
956
957
  if "--dry-run" in args:
957
958
  from src.bench.driver import PRICES
958
959
 
959
960
  sessions = len(task_ids) * len(arms) * runs
960
- print(f"\n dry run: {target} · tasks={task_ids} · arms={arms} · runs={runs} → {sessions} sessions")
961
+ print(f"\n dry run: {target} · tasks={task_ids} · arms={arms} · runs={runs} → {sessions} sessions"
962
+ + (f" · sandbox_files={files} (generated)" if files and target == "go" else ""))
961
963
  print(f" model={model} prices={PRICES.get(model)} budget=${budget}")
962
964
  print(" no provider call was made\n")
963
965
  return
964
966
 
965
- print(f"\n⚡ OUMV bench ({target}): tasks={task_ids} runs={runs} model={model} budget=${budget}\n")
967
+ print(f"\n⚡ OUMV bench ({target}): tasks={task_ids} runs={runs} model={model} budget=${budget}"
968
+ + (f" sandbox_files={files}" if files and target == "go" else "") + "\n")
966
969
  if target == "react":
967
970
  report = run_react_matrix(task_ids, arms, runs=runs, model=model, max_steps=max_steps, budget_usd=budget)
968
971
  else:
969
- report = run_matrix(task_ids, arms, runs=runs, model=model, max_steps=max_steps, budget_usd=budget)
972
+ report = run_matrix(task_ids, arms, runs=runs, model=model, max_steps=max_steps, budget_usd=budget,
973
+ files=files)
970
974
  paths = write_artifacts(report)
971
975
  if "--json" in args:
972
976
  import json as _json