tokensafe 4.7.0 → 4.7.1
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/.codex-plugin/plugin.json +1 -1
- package/README.md +22 -0
- package/hooks/claude_code_hook.py +15 -13
- package/hooks/kimi_hook.py +14 -12
- package/hooks/session_start.py +8 -2
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +1 -1
- package/server.json +3 -3
- package/src/adapter_core.py +2 -1
- package/src/agent_firewall.py +16 -1
- package/src/auto_inject.py +93 -7
- package/src/batch_editor.py +106 -15
- package/src/bench/driver.py +18 -3
- package/src/bench/go_target.py +308 -22
- package/src/bench/mechanics.py +214 -0
- package/src/bench/react_target.py +312 -5
- package/src/bench/runner.py +114 -30
- package/src/bench/tokensafe_mcp.py +144 -0
- package/src/cli.py +32 -1
- package/src/installer.py +3 -3
- package/src/mcp_server.py +457 -227
- package/src/retrofit.py +27 -5
- package/src/scaffold.py +8 -6
- package/src/scoped_search.py +67 -5
- package/src/session_brief.py +180 -15
- package/src/skeletonizer.py +9 -3
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
|
@@ -21,6 +21,8 @@ import time
|
|
|
21
21
|
from pathlib import Path
|
|
22
22
|
from typing import Any, Dict, List, Optional, Tuple
|
|
23
23
|
|
|
24
|
+
from src.bench import tokensafe_mcp
|
|
25
|
+
|
|
24
26
|
REPO_ROOT = Path(__file__).resolve().parents[3]
|
|
25
27
|
AGENT_DOM = REPO_ROOT / "agent-dom"
|
|
26
28
|
PACKAGE = AGENT_DOM / "packages" / "benchmark"
|
|
@@ -30,6 +32,7 @@ STORE = f"{WRITE_PREFIX}store.ts"
|
|
|
30
32
|
TASKS: Dict[str, Dict[str, Any]] = {
|
|
31
33
|
"search-filter": {
|
|
32
34
|
"symptom": "typing in the search box no longer filters the task list (the query is ignored).",
|
|
35
|
+
"repro": "set the search query to 'milk': the list still shows every task instead of only matching titles/tags.",
|
|
33
36
|
"breaks": [(
|
|
34
37
|
STORE,
|
|
35
38
|
" if (state.searchQuery.trim()) {\n const q = state.searchQuery.toLowerCase();\n const inTitle = task.title.toLowerCase().includes(q);\n const inTags = task.tags?.some((tag) => tag.toLowerCase().includes(q)) ?? false;\n if (!inTitle && !inTags) return false;\n }\n",
|
|
@@ -38,6 +41,7 @@ TASKS: Dict[str, Dict[str, Any]] = {
|
|
|
38
41
|
},
|
|
39
42
|
"optimistic-rollback": {
|
|
40
43
|
"symptom": "when the background sync fails, the toggled task keeps the optimistic status instead of rolling back.",
|
|
44
|
+
"repro": "toggle a task while the mock backend rejects the sync: the task must return to its previous status and show an error.",
|
|
41
45
|
"breaks": [(
|
|
42
46
|
STORE,
|
|
43
47
|
""" } catch (err: any) {
|
|
@@ -55,6 +59,7 @@ TASKS: Dict[str, Dict[str, Any]] = {
|
|
|
55
59
|
},
|
|
56
60
|
"saving-indicator": {
|
|
57
61
|
"symptom": "the save button is never disabled while the request is in flight, so users double-submit.",
|
|
62
|
+
"repro": "click Save once: isSaving must become true for the duration of the request; it stays false.",
|
|
58
63
|
"breaks": [(
|
|
59
64
|
STORE,
|
|
60
65
|
" this.set({ isSaving: true, errorMessage: null, successMessage: null });",
|
|
@@ -64,11 +69,70 @@ TASKS: Dict[str, Dict[str, Any]] = {
|
|
|
64
69
|
}
|
|
65
70
|
|
|
66
71
|
|
|
72
|
+
OUMV_STDIO = AGENT_DOM / "packages" / "vite" / "scripts" / "oumv-stdio.mjs"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class OumvStdio:
|
|
76
|
+
"""Newline-delimited JSON-RPC client for the shipped React stdio adapter.
|
|
77
|
+
|
|
78
|
+
The adapter serves the same controller `tokensafe dev` uses; in headless mode
|
|
79
|
+
L0-L3 come from the static AST, which is exactly what an agent gets before a
|
|
80
|
+
browser tab connects. One process per workspace, closed with the workspace.
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
def __init__(self, root: Path):
|
|
84
|
+
self.proc = subprocess.Popen(
|
|
85
|
+
["node", str(OUMV_STDIO), "--root", str(root)],
|
|
86
|
+
stdin=subprocess.PIPE,
|
|
87
|
+
stdout=subprocess.PIPE,
|
|
88
|
+
stderr=subprocess.PIPE,
|
|
89
|
+
text=True,
|
|
90
|
+
cwd=str(AGENT_DOM),
|
|
91
|
+
)
|
|
92
|
+
self._id = 0
|
|
93
|
+
|
|
94
|
+
def request(self, method: str, params: Dict[str, Any]) -> Any:
|
|
95
|
+
self._id += 1
|
|
96
|
+
payload = {"jsonrpc": "2.0", "id": self._id, "method": method, "params": params}
|
|
97
|
+
try:
|
|
98
|
+
self.proc.stdin.write(json.dumps(payload) + "\n")
|
|
99
|
+
self.proc.stdin.flush()
|
|
100
|
+
line = self.proc.stdout.readline()
|
|
101
|
+
except (BrokenPipeError, ValueError) as exc:
|
|
102
|
+
return {"error": f"OUMV adapter is not running: {exc}"}
|
|
103
|
+
if not line:
|
|
104
|
+
stderr = (self.proc.stderr.read() or "")[-300:] if self.proc.stderr else ""
|
|
105
|
+
return {"error": f"OUMV adapter produced no output: {stderr}"}
|
|
106
|
+
try:
|
|
107
|
+
body = json.loads(line)
|
|
108
|
+
except json.JSONDecodeError:
|
|
109
|
+
return {"error": f"invalid JSON from adapter: {line[:200]}"}
|
|
110
|
+
if body.get("error"):
|
|
111
|
+
return {"error": body["error"]}
|
|
112
|
+
return body.get("result")
|
|
113
|
+
|
|
114
|
+
def close(self) -> None:
|
|
115
|
+
try:
|
|
116
|
+
self.proc.stdin.close()
|
|
117
|
+
except Exception:
|
|
118
|
+
pass
|
|
119
|
+
try:
|
|
120
|
+
self.proc.terminate()
|
|
121
|
+
self.proc.wait(timeout=5)
|
|
122
|
+
except Exception:
|
|
123
|
+
try:
|
|
124
|
+
self.proc.kill()
|
|
125
|
+
except Exception:
|
|
126
|
+
pass
|
|
127
|
+
|
|
128
|
+
|
|
67
129
|
class ReactWorkspace:
|
|
68
130
|
def __init__(self, task_id: str):
|
|
69
131
|
if task_id not in TASKS:
|
|
70
132
|
raise ValueError(f"unknown task {task_id}; valid: {', '.join(TASKS)}")
|
|
71
133
|
self.task_id = task_id
|
|
134
|
+
self._rpc: Optional[OumvStdio] = None
|
|
135
|
+
self._mcp = None
|
|
72
136
|
base = AGENT_DOM / f".bench-tmp-{next(tempfile._get_candidate_names())}"
|
|
73
137
|
self.dir = base / "benchmark"
|
|
74
138
|
base.mkdir(parents=True)
|
|
@@ -160,7 +224,48 @@ class ReactWorkspace:
|
|
|
160
224
|
proc = subprocess.run(cmd.split(), cwd=str(self.dir), capture_output=True, text=True, timeout=300)
|
|
161
225
|
return {"exit_code": proc.returncode, "output": ((proc.stdout or "") + (proc.stderr or "")).strip()[-2000:]}
|
|
162
226
|
|
|
227
|
+
def search_files(self, query: str, path: str = "sandboxes", max_hits: int = 40) -> Any:
|
|
228
|
+
"""Case-insensitive substring search — the grep a normal agent would have."""
|
|
229
|
+
base = self._resolve(path)
|
|
230
|
+
needle = query.strip().lower()
|
|
231
|
+
if not needle:
|
|
232
|
+
return {"error": "query is required"}
|
|
233
|
+
max_hits = max(1, min(int(max_hits), 100))
|
|
234
|
+
hits: List[str] = []
|
|
235
|
+
for entry in sorted(base.rglob("*")):
|
|
236
|
+
if not entry.is_file() or entry.suffix not in {".ts", ".tsx", ".js", ".jsx", ".json"}:
|
|
237
|
+
continue
|
|
238
|
+
try:
|
|
239
|
+
text = entry.read_text(encoding="utf-8", errors="replace")
|
|
240
|
+
except OSError:
|
|
241
|
+
continue
|
|
242
|
+
for number, line in enumerate(text.splitlines(), 1):
|
|
243
|
+
if needle in line.lower():
|
|
244
|
+
hits.append(f"{entry.relative_to(base)}:{number}: {line.strip()[:160]}")
|
|
245
|
+
if len(hits) >= max_hits:
|
|
246
|
+
return {"query": query, "hits": hits, "truncated": True}
|
|
247
|
+
return {"query": query, "hits": hits, "truncated": False}
|
|
248
|
+
|
|
249
|
+
# ---- OUMV -------------------------------------------------------------
|
|
250
|
+
def oumv(self, method: str, params: Dict[str, Any]) -> Any:
|
|
251
|
+
if self._rpc is None:
|
|
252
|
+
self._rpc = OumvStdio(self.dir)
|
|
253
|
+
return self._rpc.request(method, params)
|
|
254
|
+
|
|
255
|
+
def tokensafe(self, name: str, arguments: Dict[str, Any]) -> Any:
|
|
256
|
+
if self._mcp is None:
|
|
257
|
+
self._mcp = tokensafe_mcp.open_client(self.dir)
|
|
258
|
+
if self._mcp is None:
|
|
259
|
+
return {"error": "TokenSafe MCP is unavailable"}
|
|
260
|
+
return self._mcp.call(name, arguments)
|
|
261
|
+
|
|
163
262
|
def cleanup(self) -> None:
|
|
263
|
+
if self._mcp is not None:
|
|
264
|
+
self._mcp.close()
|
|
265
|
+
self._mcp = None
|
|
266
|
+
if self._rpc is not None:
|
|
267
|
+
self._rpc.close()
|
|
268
|
+
self._rpc = None
|
|
164
269
|
shutil.rmtree(self.dir.parent, ignore_errors=True)
|
|
165
270
|
|
|
166
271
|
|
|
@@ -197,6 +302,22 @@ TOOLS: List[Dict[str, Any]] = [
|
|
|
197
302
|
},
|
|
198
303
|
},
|
|
199
304
|
},
|
|
305
|
+
{
|
|
306
|
+
"type": "function",
|
|
307
|
+
"function": {
|
|
308
|
+
"name": "search_files",
|
|
309
|
+
"description": "Case-insensitive substring search across sandbox sources, returns path:line hits.",
|
|
310
|
+
"parameters": {
|
|
311
|
+
"type": "object",
|
|
312
|
+
"properties": {
|
|
313
|
+
"query": {"type": "string"},
|
|
314
|
+
"path": {"type": "string", "description": "Relative directory, default 'sandboxes'"},
|
|
315
|
+
"max_hits": {"type": "integer", "description": "Default 40, max 100"},
|
|
316
|
+
},
|
|
317
|
+
"required": ["query"],
|
|
318
|
+
},
|
|
319
|
+
},
|
|
320
|
+
},
|
|
200
321
|
{
|
|
201
322
|
"type": "function",
|
|
202
323
|
"function": {
|
|
@@ -208,26 +329,212 @@ TOOLS: List[Dict[str, Any]] = [
|
|
|
208
329
|
]
|
|
209
330
|
|
|
210
331
|
|
|
211
|
-
def registry(ws: ReactWorkspace) -> Dict[str, Any]:
|
|
212
|
-
|
|
332
|
+
def registry(ws: ReactWorkspace, arm: str = "baseline") -> Dict[str, Any]:
|
|
333
|
+
tools: Dict[str, Any] = {
|
|
213
334
|
"list_files": ws.list_files,
|
|
214
335
|
"read_file": ws.read_file,
|
|
215
336
|
"write_file": ws.write_file,
|
|
337
|
+
"search_files": ws.search_files,
|
|
216
338
|
"run_command": ws.run_command,
|
|
217
339
|
}
|
|
340
|
+
if arm == "tokensafe":
|
|
341
|
+
tools.update({
|
|
342
|
+
"ts_smart_read_file": lambda path, symbol="": ws.tokensafe(
|
|
343
|
+
"smart_read_file", {"path": path, **({"symbol": symbol} if symbol else {})}
|
|
344
|
+
),
|
|
345
|
+
"ts_scoped_search": lambda query, path="sandboxes": ws.tokensafe(
|
|
346
|
+
"scoped_search", {"query": query, "path": path, "max_results": 20}
|
|
347
|
+
),
|
|
348
|
+
"ts_repo_map": lambda view="graph": ws.tokensafe("repo_map", {"view": view, "project_path": "."}),
|
|
349
|
+
"ts_apply_edits": lambda path, edits, verify="": ws.tokensafe(
|
|
350
|
+
"apply_edits",
|
|
351
|
+
{
|
|
352
|
+
"edits": [{"path": path, "hunks": edits}],
|
|
353
|
+
**({"verify": verify} if verify else {}),
|
|
354
|
+
},
|
|
355
|
+
),
|
|
356
|
+
})
|
|
357
|
+
if arm == "oumv":
|
|
358
|
+
tools.update({
|
|
359
|
+
"oumv_observe": lambda level, target="": ws.oumv("oumv/observe", {"level": level, "target": target}),
|
|
360
|
+
"oumv_getSource": lambda path, symbol="": ws.oumv("oumv/getSource", {"path": path, "symbol": symbol}),
|
|
361
|
+
"oumv_applyEdit": lambda path, replacement, expectedVersion: ws.oumv(
|
|
362
|
+
"oumv/applyEdit", {"path": path, "replacement": replacement, "expectedVersion": expectedVersion}
|
|
363
|
+
),
|
|
364
|
+
"oumv_understand": lambda query, target: ws.oumv("oumv/understand", {"query": query, "target": target}),
|
|
365
|
+
})
|
|
366
|
+
return tools
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
TOKENSAFE_TOOLS: List[Dict[str, Any]] = TOOLS + [
|
|
370
|
+
{
|
|
371
|
+
"type": "function",
|
|
372
|
+
"function": {
|
|
373
|
+
"name": "ts_smart_read_file",
|
|
374
|
+
"description": "TokenSafe AST-skeleton reader: a compact symbol view of one file.",
|
|
375
|
+
"parameters": {
|
|
376
|
+
"type": "object",
|
|
377
|
+
"properties": {"path": {"type": "string"}, "symbol": {"type": "string"}},
|
|
378
|
+
"required": ["path"],
|
|
379
|
+
},
|
|
380
|
+
},
|
|
381
|
+
},
|
|
382
|
+
{
|
|
383
|
+
"type": "function",
|
|
384
|
+
"function": {
|
|
385
|
+
"name": "ts_scoped_search",
|
|
386
|
+
"description": "TokenSafe scoped search returning file:line hits inside the sandbox.",
|
|
387
|
+
"parameters": {
|
|
388
|
+
"type": "object",
|
|
389
|
+
"properties": {"query": {"type": "string"}, "path": {"type": "string"}},
|
|
390
|
+
"required": ["query"],
|
|
391
|
+
},
|
|
392
|
+
},
|
|
393
|
+
},
|
|
394
|
+
{
|
|
395
|
+
"type": "function",
|
|
396
|
+
"function": {
|
|
397
|
+
"name": "ts_repo_map",
|
|
398
|
+
"description": "TokenSafe architecture map: high-dependency files and API surface.",
|
|
399
|
+
"parameters": {
|
|
400
|
+
"type": "object",
|
|
401
|
+
"properties": {"view": {"type": "string", "enum": ["graph", "api", "tree"]}},
|
|
402
|
+
"required": ["view"],
|
|
403
|
+
},
|
|
404
|
+
},
|
|
405
|
+
},
|
|
406
|
+
{
|
|
407
|
+
"type": "function",
|
|
408
|
+
"function": {
|
|
409
|
+
"name": "ts_apply_edits",
|
|
410
|
+
"description": (
|
|
411
|
+
"TokenSafe surgical editor: replaces exact snippets (hunks of {target, replacement}) "
|
|
412
|
+
"and runs `verify` after the edit, returning a one-line pass/fail."
|
|
413
|
+
),
|
|
414
|
+
"parameters": {
|
|
415
|
+
"type": "object",
|
|
416
|
+
"properties": {
|
|
417
|
+
"path": {"type": "string"},
|
|
418
|
+
"edits": {
|
|
419
|
+
"type": "array",
|
|
420
|
+
"items": {
|
|
421
|
+
"type": "object",
|
|
422
|
+
"properties": {
|
|
423
|
+
"target": {"type": "string", "description": "Exact snippet to replace"},
|
|
424
|
+
"replacement": {"type": "string", "description": "Replacement snippet"},
|
|
425
|
+
},
|
|
426
|
+
"required": ["target", "replacement"],
|
|
427
|
+
},
|
|
428
|
+
},
|
|
429
|
+
"verify": {"type": "string", "description": "Shell command to run after the edit"},
|
|
430
|
+
},
|
|
431
|
+
"required": ["path", "edits"],
|
|
432
|
+
},
|
|
433
|
+
},
|
|
434
|
+
},
|
|
435
|
+
]
|
|
436
|
+
|
|
437
|
+
OUMV_TOOLS: List[Dict[str, Any]] = TOOLS + [
|
|
438
|
+
{
|
|
439
|
+
"type": "function",
|
|
440
|
+
"function": {
|
|
441
|
+
"name": "oumv_observe",
|
|
442
|
+
"description": "OUMV observe: L0 pulse, L1 component surface, L2 component contract, L3 source.",
|
|
443
|
+
"parameters": {
|
|
444
|
+
"type": "object",
|
|
445
|
+
"properties": {
|
|
446
|
+
"level": {"type": "string", "enum": ["L0", "L1", "L2", "L3"]},
|
|
447
|
+
"target": {"type": "string", "description": "e.g. 'sandboxes/react-task-manager/src/store.ts'"},
|
|
448
|
+
},
|
|
449
|
+
"required": ["level"],
|
|
450
|
+
},
|
|
451
|
+
},
|
|
452
|
+
},
|
|
453
|
+
{
|
|
454
|
+
"type": "function",
|
|
455
|
+
"function": {
|
|
456
|
+
"name": "oumv_getSource",
|
|
457
|
+
"description": "OUMV source read with the sha256 OCC version token; pass `symbol` to get just that function, method or class.",
|
|
458
|
+
"parameters": {
|
|
459
|
+
"type": "object",
|
|
460
|
+
"properties": {
|
|
461
|
+
"path": {"type": "string"},
|
|
462
|
+
"symbol": {"type": "string"},
|
|
463
|
+
},
|
|
464
|
+
"required": ["path"],
|
|
465
|
+
},
|
|
466
|
+
},
|
|
467
|
+
},
|
|
468
|
+
{
|
|
469
|
+
"type": "function",
|
|
470
|
+
"function": {
|
|
471
|
+
"name": "oumv_applyEdit",
|
|
472
|
+
"description": "OUMV guarded edit: writes the replacement only if `expectedVersion` from getSource matches the file on disk.",
|
|
473
|
+
"parameters": {
|
|
474
|
+
"type": "object",
|
|
475
|
+
"properties": {
|
|
476
|
+
"path": {"type": "string"},
|
|
477
|
+
"replacement": {"type": "string"},
|
|
478
|
+
"expectedVersion": {"type": "string", "description": "sha256 version from getSource"},
|
|
479
|
+
},
|
|
480
|
+
"required": ["path", "replacement", "expectedVersion"],
|
|
481
|
+
},
|
|
482
|
+
},
|
|
483
|
+
},
|
|
484
|
+
{
|
|
485
|
+
"type": "function",
|
|
486
|
+
"function": {
|
|
487
|
+
"name": "oumv_understand",
|
|
488
|
+
"description": "OUMV understand: impact analysis (importers and components affected by a file or symbol).",
|
|
489
|
+
"parameters": {
|
|
490
|
+
"type": "object",
|
|
491
|
+
"properties": {
|
|
492
|
+
"query": {"type": "string", "enum": ["impact", "causality"]},
|
|
493
|
+
"target": {"type": "string"},
|
|
494
|
+
},
|
|
495
|
+
"required": ["query", "target"],
|
|
496
|
+
},
|
|
497
|
+
},
|
|
498
|
+
},
|
|
499
|
+
]
|
|
218
500
|
|
|
219
501
|
|
|
220
502
|
SYSTEM = (
|
|
221
|
-
"You are a senior React engineer working in a small sandbox. Use
|
|
222
|
-
"
|
|
503
|
+
"You are a senior React engineer working in a small sandbox. Use search_files to locate code, "
|
|
504
|
+
"read_file to inspect it, write_file to fix the bug, and run_command to run the 12-assertion oracle. "
|
|
223
505
|
"The oracle output is JSON with `passed` and `failed` assertion ids. Tests and adapter.ts are read-only. "
|
|
224
506
|
"Make the smallest correct change and stop as soon as the oracle reports 12."
|
|
225
507
|
)
|
|
226
508
|
|
|
509
|
+
SYSTEM_TOKENSAFE = (
|
|
510
|
+
"You are a senior React engineer working in a small sandbox. The workspace has TokenSafe tools. "
|
|
511
|
+
"Use this loop and stop as soon as the oracle reports 12: (1) ts_scoped_search for the behaviour named "
|
|
512
|
+
"in the repro to get file:line hits; (2) ts_smart_read_file with that path and the identifier from the hit "
|
|
513
|
+
"as `symbol` — it returns the enclosing component/handler body (or a window around the hit) with line numbers; "
|
|
514
|
+
"(3) ts_apply_edits with one hunk {target: the exact snippet, replacement: the fix} plus "
|
|
515
|
+
'verify="auto" (the declared test command) — it edits and verifies in one call; (4) if verify fails, read the '
|
|
516
|
+
"reported line and repeat (2)-(3). ts_repo_map is for an unfamiliar repository; skip it when the repro "
|
|
517
|
+
"already names the component. Prefer these tools over list_files/read_file. Tests and adapter.ts are "
|
|
518
|
+
"read-only. Do not rewrite whole files."
|
|
519
|
+
)
|
|
520
|
+
|
|
521
|
+
SYSTEM_OUMV = (
|
|
522
|
+
"You are a senior React engineer working in a small sandbox that exposes the OUMV runtime. "
|
|
523
|
+
"Use this loop and stop as soon as the oracle reports 12: (1) search_files ONCE for the behaviour named in "
|
|
524
|
+
"the repro; only call oumv_observe L1 if that finds nothing; (2) oumv_getSource ONCE on the file, WITHOUT "
|
|
525
|
+
"`symbol` — it returns the full bytes and the sha256 OCC version (`symbol` is only for inspecting a single "
|
|
526
|
+
"function or method after you already have the file); (3) oumv_applyEdit with the full fixed file and that "
|
|
527
|
+
"version (it rejects a stale version); (4) run_command to run the oracle. Do not re-read a file you already "
|
|
528
|
+
"have in context, and do not use write_file unless an OUMV tool returns an error. Tests and adapter.ts are "
|
|
529
|
+
"read-only."
|
|
530
|
+
)
|
|
531
|
+
|
|
227
532
|
|
|
228
533
|
def task_prompt(task_id: str) -> str:
|
|
534
|
+
task = TASKS[task_id]
|
|
229
535
|
return (
|
|
230
|
-
f"The task manager has a regression: {
|
|
536
|
+
f"The task manager has a regression: {task['symptom']}\n"
|
|
537
|
+
f"Repro: {task['repro']}\n"
|
|
231
538
|
"Find the cause and fix the sandbox source. "
|
|
232
539
|
"Verification: `npx tsx src/bin/oracle-runner.ts` must print {\"passed\":12,\"failed\":[]}. "
|
|
233
540
|
"Do not modify the oracle, adapter.ts, or the test harness."
|
package/src/bench/runner.py
CHANGED
|
@@ -15,19 +15,18 @@ from src.bench.driver import BudgetExceeded, DeepSeekClient, run_agent
|
|
|
15
15
|
def run_one(
|
|
16
16
|
arm: str,
|
|
17
17
|
task_id: str,
|
|
18
|
-
helper: Path,
|
|
19
18
|
model: str = "deepseek-chat",
|
|
20
19
|
max_steps: int = 14,
|
|
21
20
|
budget_usd: float = 1.0,
|
|
22
21
|
) -> Dict[str, Any]:
|
|
23
|
-
ws = go_target.GoWorkspace(task_id
|
|
22
|
+
ws = go_target.GoWorkspace(task_id)
|
|
24
23
|
started = time.time()
|
|
25
24
|
try:
|
|
26
25
|
before = ws.oracle()
|
|
27
26
|
client = DeepSeekClient(model=model, temperature=0.0)
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
registry = go_target.
|
|
27
|
+
# one place decides prompt + schemas + dispatcher, so a schema the model sees is
|
|
28
|
+
# always a tool the dispatcher can run
|
|
29
|
+
system, tools, registry = go_target.build_arm(ws, arm)
|
|
31
30
|
|
|
32
31
|
result = run_agent(
|
|
33
32
|
client=client,
|
|
@@ -56,6 +55,7 @@ def run_one(
|
|
|
56
55
|
"solved": False,
|
|
57
56
|
"stop_reason": "budget_exceeded",
|
|
58
57
|
"error": str(exc),
|
|
58
|
+
"usage": getattr(exc, "usage", {}),
|
|
59
59
|
"wall_clock_s": round(time.time() - started, 1),
|
|
60
60
|
}
|
|
61
61
|
finally:
|
|
@@ -70,7 +70,6 @@ def run_matrix(
|
|
|
70
70
|
max_steps: int = 14,
|
|
71
71
|
budget_usd: float = 1.0,
|
|
72
72
|
) -> Dict[str, Any]:
|
|
73
|
-
helper = go_target.build_helper()
|
|
74
73
|
results: List[Dict[str, Any]] = []
|
|
75
74
|
spent = 0.0
|
|
76
75
|
aborted: Optional[str] = None
|
|
@@ -81,7 +80,7 @@ def run_matrix(
|
|
|
81
80
|
aborted = f"global budget ${budget_usd} exhausted after ${spent:.4f}"
|
|
82
81
|
break
|
|
83
82
|
per_run_budget = max(budget_usd - spent, 0.01)
|
|
84
|
-
row = run_one(arm, task_id,
|
|
83
|
+
row = run_one(arm, task_id, model=model, max_steps=max_steps, budget_usd=per_run_budget)
|
|
85
84
|
row["run"] = run_idx
|
|
86
85
|
results.append(row)
|
|
87
86
|
spent += float((row.get("usage") or {}).get("usd") or 0.0)
|
|
@@ -99,6 +98,7 @@ def run_matrix(
|
|
|
99
98
|
"spent_usd": round(spent, 6),
|
|
100
99
|
"aborted": aborted,
|
|
101
100
|
"results": results,
|
|
101
|
+
"provenance": _provenance("go", tasks, arms),
|
|
102
102
|
"generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
|
103
103
|
}
|
|
104
104
|
|
|
@@ -106,6 +106,7 @@ def run_matrix(
|
|
|
106
106
|
|
|
107
107
|
def run_react_one(
|
|
108
108
|
task_id: str,
|
|
109
|
+
arm: str = "baseline",
|
|
109
110
|
model: str = "deepseek-chat",
|
|
110
111
|
max_steps: int = 14,
|
|
111
112
|
budget_usd: float = 1.0,
|
|
@@ -115,19 +116,25 @@ def run_react_one(
|
|
|
115
116
|
try:
|
|
116
117
|
before = ws.oracle()
|
|
117
118
|
client = DeepSeekClient(model=model, temperature=0.0)
|
|
119
|
+
if arm == "oumv":
|
|
120
|
+
system, tools = react_target.SYSTEM_OUMV, react_target.OUMV_TOOLS
|
|
121
|
+
elif arm == "tokensafe":
|
|
122
|
+
system, tools = react_target.SYSTEM_TOKENSAFE, react_target.TOKENSAFE_TOOLS
|
|
123
|
+
else:
|
|
124
|
+
system, tools = react_target.SYSTEM, react_target.TOOLS
|
|
118
125
|
result = run_agent(
|
|
119
126
|
client=client,
|
|
120
|
-
system_prompt=
|
|
127
|
+
system_prompt=system,
|
|
121
128
|
task_prompt=react_target.task_prompt(task_id),
|
|
122
|
-
tools=
|
|
123
|
-
registry=react_target.registry(ws),
|
|
129
|
+
tools=tools,
|
|
130
|
+
registry=react_target.registry(ws, arm),
|
|
124
131
|
max_steps=max_steps,
|
|
125
132
|
budget_usd=budget_usd,
|
|
126
133
|
after_step=lambda _i: ws.oracle(),
|
|
127
134
|
)
|
|
128
135
|
after = ws.oracle()
|
|
129
136
|
return {
|
|
130
|
-
"arm":
|
|
137
|
+
"arm": arm,
|
|
131
138
|
"task": task_id,
|
|
132
139
|
"oracle_before": {"passed": before[0], "failed": before[1]},
|
|
133
140
|
"oracle_after": {"passed": after[0], "failed": after[1]},
|
|
@@ -136,8 +143,9 @@ def run_react_one(
|
|
|
136
143
|
**result,
|
|
137
144
|
}
|
|
138
145
|
except BudgetExceeded as exc:
|
|
139
|
-
return {"arm":
|
|
146
|
+
return {"arm": arm, "task": task_id, "solved": False,
|
|
140
147
|
"stop_reason": "budget_exceeded", "error": str(exc),
|
|
148
|
+
"usage": getattr(exc, "usage", {}),
|
|
141
149
|
"wall_clock_s": round(time.time() - started, 1)}
|
|
142
150
|
finally:
|
|
143
151
|
ws.cleanup()
|
|
@@ -145,6 +153,7 @@ def run_react_one(
|
|
|
145
153
|
|
|
146
154
|
def run_react_matrix(
|
|
147
155
|
tasks: List[str],
|
|
156
|
+
arms: List[str],
|
|
148
157
|
runs: int = 1,
|
|
149
158
|
model: str = "deepseek-chat",
|
|
150
159
|
max_steps: int = 14,
|
|
@@ -155,36 +164,78 @@ def run_react_matrix(
|
|
|
155
164
|
aborted: Optional[str] = None
|
|
156
165
|
for run_idx in range(1, runs + 1):
|
|
157
166
|
for task_id in tasks:
|
|
158
|
-
|
|
159
|
-
|
|
167
|
+
for arm in arms:
|
|
168
|
+
if spent >= budget_usd:
|
|
169
|
+
aborted = f"global budget ${budget_usd} exhausted after ${spent:.4f}"
|
|
170
|
+
break
|
|
171
|
+
row = run_react_one(task_id, arm, model=model, max_steps=max_steps,
|
|
172
|
+
budget_usd=max(budget_usd - spent, 0.01))
|
|
173
|
+
row["run"] = run_idx
|
|
174
|
+
results.append(row)
|
|
175
|
+
spent += float((row.get("usage") or {}).get("usd") or 0.0)
|
|
176
|
+
if aborted:
|
|
160
177
|
break
|
|
161
|
-
row = run_react_one(task_id, model=model, max_steps=max_steps,
|
|
162
|
-
budget_usd=max(budget_usd - spent, 0.01))
|
|
163
|
-
row["run"] = run_idx
|
|
164
|
-
results.append(row)
|
|
165
|
-
spent += float((row.get("usage") or {}).get("usd") or 0.0)
|
|
166
178
|
if aborted:
|
|
167
179
|
break
|
|
168
180
|
return {
|
|
169
181
|
"target": "react",
|
|
170
182
|
"tasks": tasks,
|
|
171
|
-
"arms":
|
|
183
|
+
"arms": arms,
|
|
172
184
|
"runs": runs,
|
|
173
185
|
"model": model,
|
|
174
186
|
"budget_usd": budget_usd,
|
|
175
187
|
"spent_usd": round(spent, 6),
|
|
176
188
|
"aborted": aborted,
|
|
177
189
|
"results": results,
|
|
178
|
-
"note": "React arm runs
|
|
190
|
+
"note": "React arm runs the shipped static controller over stdio (no browser tab).",
|
|
191
|
+
"provenance": _provenance("react", tasks, arms),
|
|
179
192
|
"generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
|
180
193
|
}
|
|
181
194
|
|
|
182
195
|
|
|
196
|
+
def _provenance(target: str, tasks: List[str], arms: List[str]) -> Dict[str, Any]:
|
|
197
|
+
"""Frozen prompts + harness revision, so a report can be audited later."""
|
|
198
|
+
import hashlib
|
|
199
|
+
import subprocess
|
|
200
|
+
|
|
201
|
+
module = react_target if target == "react" else go_target
|
|
202
|
+
harness_repo = Path(__file__).resolve().parents[2]
|
|
203
|
+
systems = {
|
|
204
|
+
"baseline": getattr(module, "SYSTEM_BASELINE", getattr(module, "SYSTEM", "")),
|
|
205
|
+
"tokensafe": getattr(module, "SYSTEM_TOKENSAFE", ""),
|
|
206
|
+
"oumv": getattr(module, "SYSTEM_OUMV", ""),
|
|
207
|
+
}
|
|
208
|
+
prompts = {task: module.task_prompt(task) for task in tasks}
|
|
209
|
+
try:
|
|
210
|
+
commit = subprocess.run(
|
|
211
|
+
["git", "rev-parse", "HEAD"], cwd=str(harness_repo), capture_output=True, text=True, timeout=10
|
|
212
|
+
).stdout.strip()
|
|
213
|
+
dirty = bool(
|
|
214
|
+
subprocess.run(
|
|
215
|
+
["git", "status", "--porcelain"], cwd=str(harness_repo), capture_output=True, text=True, timeout=10
|
|
216
|
+
).stdout.strip()
|
|
217
|
+
)
|
|
218
|
+
except Exception:
|
|
219
|
+
commit, dirty = "", False
|
|
220
|
+
return {
|
|
221
|
+
"prompt_sha256": {task: hashlib.sha256(prompt.encode()).hexdigest() for task, prompt in prompts.items()},
|
|
222
|
+
"system_sha256": {
|
|
223
|
+
arm: hashlib.sha256(systems.get(arm, "").encode()).hexdigest() for arm in arms
|
|
224
|
+
},
|
|
225
|
+
"harness_commit": commit,
|
|
226
|
+
"harness_dirty": dirty,
|
|
227
|
+
"price_snapshot": "2026-11-26",
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
|
|
183
231
|
def summarize(report: Dict[str, Any]) -> List[Dict[str, Any]]:
|
|
184
232
|
rows: Dict[str, Dict[str, Any]] = {}
|
|
185
233
|
for result in report["results"]:
|
|
186
234
|
key = result["arm"]
|
|
187
|
-
row = rows.setdefault(
|
|
235
|
+
row = rows.setdefault(
|
|
236
|
+
key,
|
|
237
|
+
{"arm": key, "runs": 0, "solved": 0, "input": 0, "output": 0, "usd": 0.0, "steps": 0, "seconds": 0.0},
|
|
238
|
+
)
|
|
188
239
|
row["runs"] += 1
|
|
189
240
|
row["solved"] += 1 if result.get("solved") else 0
|
|
190
241
|
usage = result.get("usage") or {}
|
|
@@ -192,35 +243,68 @@ def summarize(report: Dict[str, Any]) -> List[Dict[str, Any]]:
|
|
|
192
243
|
row["output"] += int(usage.get("output_tokens") or 0)
|
|
193
244
|
row["usd"] += float(usage.get("usd") or 0.0)
|
|
194
245
|
row["steps"] += len(result.get("steps") or [])
|
|
246
|
+
row["seconds"] += float(result.get("wall_clock_s") or 0.0)
|
|
247
|
+
for row in rows.values():
|
|
248
|
+
row["mean_steps"] = round(row["steps"] / row["runs"], 1) if row["runs"] else 0.0
|
|
249
|
+
row["mean_seconds"] = round(row["seconds"] / row["runs"], 1) if row["runs"] else 0.0
|
|
250
|
+
row["mean_input"] = round(row["input"] / row["runs"]) if row["runs"] else 0
|
|
251
|
+
row["mean_output"] = round(row["output"] / row["runs"]) if row["runs"] else 0
|
|
195
252
|
return sorted(rows.values(), key=lambda r: r["arm"])
|
|
196
253
|
|
|
197
254
|
|
|
198
255
|
def render_markdown(report: Dict[str, Any]) -> str:
|
|
256
|
+
target = report.get("target", "go")
|
|
257
|
+
oracle = (
|
|
258
|
+
"the 12-assertion TaskManagerOracle (`npx tsx src/bin/oracle-runner.ts`)"
|
|
259
|
+
if target == "react"
|
|
260
|
+
else "the real 12-assertion oracle (`go test ./benchmark -run TestGroundTruthOracleVanilla`)"
|
|
261
|
+
)
|
|
262
|
+
sandbox = "the `agent-dom` React benchmark sandbox" if target == "react" else "the `tokensafe-backend/go` module"
|
|
199
263
|
lines = [
|
|
200
|
-
f"# OUMV benchmark — {
|
|
264
|
+
f"# OUMV benchmark — {target} sandbox (measured)",
|
|
201
265
|
"",
|
|
202
266
|
f"> Model: `{report['model']}` · runs: {report['runs']} · budget: ${report['budget_usd']} · "
|
|
203
267
|
f"spent: ${report['spent_usd']} · {report['generated_at']}",
|
|
204
268
|
"",
|
|
205
269
|
"## Methodology",
|
|
206
270
|
"",
|
|
207
|
-
"- Each arm starts from a throwaway copy of
|
|
208
|
-
"- Correctness is
|
|
271
|
+
f"- Each arm starts from a throwaway copy of {sandbox} with one deliberate regression.",
|
|
272
|
+
f"- Correctness is {oracle}, re-run after every agent step.",
|
|
209
273
|
"- Token and cost numbers come from the provider `usage` payload; prices are a pinned snapshot printed in the JSON artifact.",
|
|
210
|
-
"- `baseline` uses file/command tools only; `oumv` gets the same tools plus observe/getSource/
|
|
274
|
+
"- `baseline` uses file/command tools only; `oumv` gets the same tools plus observe/getSource/applyEdit/understand served by the shipped OUMV adapter.",
|
|
211
275
|
"",
|
|
212
276
|
"## Results",
|
|
213
277
|
"",
|
|
214
|
-
"| Arm | Runs | Solved |
|
|
215
|
-
"| :--- | ---: | ---: | ---: | ---: | ---: | ---: |",
|
|
278
|
+
"| Arm | Runs | Solved | Mean steps | Mean wall clock | Mean input tokens | Mean output tokens | Cost |",
|
|
279
|
+
"| :--- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |",
|
|
216
280
|
]
|
|
217
281
|
for row in summarize(report):
|
|
218
282
|
lines.append(
|
|
219
|
-
f"| `{row['arm']}` | {row['runs']} | {row['solved']}/{row['runs']} | {row['
|
|
220
|
-
f"{row['
|
|
283
|
+
f"| `{row['arm']}` | {row['runs']} | {row['solved']}/{row['runs']} | {row['mean_steps']} | "
|
|
284
|
+
f"{row['mean_seconds']}s | {row['mean_input']:,} | {row['mean_output']:,} | ${row['usd']:.4f} |"
|
|
221
285
|
)
|
|
222
286
|
if report.get("aborted"):
|
|
223
287
|
lines += ["", f"> Stopped early: {report['aborted']}"]
|
|
288
|
+
rows = {row["arm"]: row for row in summarize(report)}
|
|
289
|
+
if "baseline" in rows and "oumv" in rows:
|
|
290
|
+
baseline, oumv = rows["baseline"], rows["oumv"]
|
|
291
|
+
def delta(before: float, after: float) -> str:
|
|
292
|
+
if not before:
|
|
293
|
+
return "—"
|
|
294
|
+
return f"{(after - before) / before * 100:+.1f}%"
|
|
295
|
+
lines += [
|
|
296
|
+
"",
|
|
297
|
+
"## OUMV vs baseline",
|
|
298
|
+
"",
|
|
299
|
+
"| Metric | Baseline | OUMV | Delta |",
|
|
300
|
+
"| :--- | ---: | ---: | ---: |",
|
|
301
|
+
f"| Solved | {baseline['solved']}/{baseline['runs']} | {oumv['solved']}/{oumv['runs']} | — |",
|
|
302
|
+
f"| Mean input tokens | {baseline['mean_input']:,} | {oumv['mean_input']:,} | {delta(baseline['mean_input'], oumv['mean_input'])} |",
|
|
303
|
+
f"| Mean output tokens | {baseline['mean_output']:,} | {oumv['mean_output']:,} | {delta(baseline['mean_output'], oumv['mean_output'])} |",
|
|
304
|
+
f"| Mean steps | {baseline['mean_steps']} | {oumv['mean_steps']} | {delta(baseline['mean_steps'], oumv['mean_steps'])} |",
|
|
305
|
+
f"| Mean wall clock | {baseline['mean_seconds']}s | {oumv['mean_seconds']}s | {delta(baseline['mean_seconds'], oumv['mean_seconds'])} |",
|
|
306
|
+
f"| Cost | ${baseline['usd']:.4f} | ${oumv['usd']:.4f} | {delta(baseline['usd'], oumv['usd'])} |",
|
|
307
|
+
]
|
|
224
308
|
lines += ["", "## Per-run detail", "", "| Run | Arm | Task | Oracle before | Oracle after | Stop | Steps |", "| ---: | :--- | :--- | :--- | :--- | :--- | ---: |"]
|
|
225
309
|
for result in report["results"]:
|
|
226
310
|
before = result.get("oracle_before") or {}
|