tokensafe 4.7.2 → 4.7.4
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 +9 -2
- package/bin/python-runtime.json +34 -0
- package/bin/tokensafe.js +363 -63
- package/kimi.plugin.json +1 -1
- package/package.json +2 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/agent_firewall.py +18 -2
- package/src/bench/driver.py +40 -13
- package/src/bench/go_target.py +89 -21
- package/src/bench/react_target.py +7 -6
- package/src/bench/runner.py +79 -19
- package/src/cli.py +7 -3
- package/src/installer.py +1 -1
- package/src/mcp_server.py +222 -52
- package/src/route_index.py +444 -0
- package/src/scaffold.py +1 -1
- package/src/scoped_search.py +4 -2
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
package/src/bench/driver.py
CHANGED
|
@@ -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 =
|
|
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
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
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]
|
package/src/bench/go_target.py
CHANGED
|
@@ -75,11 +75,54 @@ 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
|
+
|
|
78
120
|
class GoWorkspace:
|
|
79
|
-
def __init__(self, task_id: str):
|
|
121
|
+
def __init__(self, task_id: str, files: int = 0):
|
|
80
122
|
if task_id not in TASKS:
|
|
81
123
|
raise ValueError(f"unknown task {task_id}; valid: {', '.join(TASKS)}")
|
|
82
124
|
self.task_id = task_id
|
|
125
|
+
self.files = int(files or 0)
|
|
83
126
|
self.dir = Path(tempfile.mkdtemp(prefix=f"oumv-bench-{task_id}-")) / "go"
|
|
84
127
|
self.dir.mkdir(parents=True)
|
|
85
128
|
for item in COPY_ITEMS:
|
|
@@ -89,6 +132,8 @@ class GoWorkspace:
|
|
|
89
132
|
shutil.copytree(src, dst)
|
|
90
133
|
else:
|
|
91
134
|
shutil.copy2(src, dst)
|
|
135
|
+
if self.files:
|
|
136
|
+
_generate_filler(self.dir, self.files)
|
|
92
137
|
# The runtime must serve the *workspace* code: build the helper inside the
|
|
93
138
|
# copied module and rebuild it when an edit changes the sources, otherwise
|
|
94
139
|
# oumv/verify would keep reporting the pristine app's behaviour.
|
|
@@ -471,18 +516,33 @@ OUMV_TOOLS: List[Dict[str, Any]] = BASE_TOOLS + [
|
|
|
471
516
|
"name": "oumv_applyEdit",
|
|
472
517
|
"description": (
|
|
473
518
|
"OUMV guarded edit: applies only if `expectedVersion` matches the file on disk. "
|
|
474
|
-
"mode='
|
|
519
|
+
"mode='patch' splices hunks (cheapest — the file is never re-sent); mode='symbol' "
|
|
520
|
+
"replaces one declaration; mode='replace' rewrites the whole file."
|
|
475
521
|
),
|
|
476
522
|
"parameters": {
|
|
477
523
|
"type": "object",
|
|
478
524
|
"properties": {
|
|
479
525
|
"path": {"type": "string"},
|
|
480
|
-
"
|
|
481
|
-
"
|
|
482
|
-
"
|
|
526
|
+
"expectedVersion": {"type": "string", "description": "version from oumv_observe L3 or oumv_getSource"},
|
|
527
|
+
"mode": {"type": "string", "enum": ["patch", "symbol", "replace"]},
|
|
528
|
+
"hunks": {
|
|
529
|
+
"type": "array",
|
|
530
|
+
"description": "mode='patch': exact snippets to splice, applied in order",
|
|
531
|
+
"items": {
|
|
532
|
+
"type": "object",
|
|
533
|
+
"properties": {
|
|
534
|
+
"target": {"type": "string", "description": "Exact snippet from the source"},
|
|
535
|
+
"replacement": {"type": "string", "description": "Replacement snippet"},
|
|
536
|
+
"startLine": {"type": "integer"},
|
|
537
|
+
"endLine": {"type": "integer"},
|
|
538
|
+
},
|
|
539
|
+
"required": ["target", "replacement"],
|
|
540
|
+
},
|
|
541
|
+
},
|
|
542
|
+
"replacement": {"type": "string", "description": "New content, or the new declaration body for mode='symbol'"},
|
|
483
543
|
"symbol": {"type": "string", "description": "Declaration to replace when mode='symbol'"},
|
|
484
544
|
},
|
|
485
|
-
"required": ["path", "
|
|
545
|
+
"required": ["path", "expectedVersion"],
|
|
486
546
|
},
|
|
487
547
|
},
|
|
488
548
|
},
|
|
@@ -587,14 +647,15 @@ def registry(ws: GoWorkspace, arm: str) -> Dict[str, Any]:
|
|
|
587
647
|
tools.update({
|
|
588
648
|
"oumv_observe": lambda level, target="": ws.oumv("oumv/observe", {"level": level, "target": target}),
|
|
589
649
|
"oumv_getSource": lambda path, symbol="": ws.oumv("oumv/getSource", {"path": path, "symbol": symbol}),
|
|
590
|
-
"oumv_applyEdit": lambda path,
|
|
650
|
+
"oumv_applyEdit": lambda path, expectedVersion, mode="", replacement="", symbol="", hunks=None: ws.oumv(
|
|
591
651
|
"oumv/applyEdit",
|
|
592
652
|
{
|
|
593
653
|
"path": path,
|
|
594
|
-
"replacement": replacement,
|
|
595
654
|
"expectedVersion": expectedVersion,
|
|
596
655
|
**({"mode": mode} if mode else {}),
|
|
656
|
+
**({"replacement": replacement} if replacement else {}),
|
|
597
657
|
**({"symbol": symbol} if symbol else {}),
|
|
658
|
+
**({"hunks": hunks} if hunks else {}),
|
|
598
659
|
},
|
|
599
660
|
),
|
|
600
661
|
"oumv_verify": lambda target, payload=None: ws.oumv(
|
|
@@ -612,26 +673,33 @@ SYSTEM_BASELINE = (
|
|
|
612
673
|
)
|
|
613
674
|
SYSTEM_TOKENSAFE = (
|
|
614
675
|
"You are a senior Go engineer working in a small Go module. The bug report has a repro; "
|
|
615
|
-
"stop as soon as the oracle passes. Loop: (1)
|
|
616
|
-
"
|
|
617
|
-
"
|
|
676
|
+
"stop as soon as the oracle passes. Loop: (1) ts_smart_read_file(endpoint=<\"METHOD /path\" from the "
|
|
677
|
+
"repro>) → the handler body, its file, its line range and the whole-file version in ONE call; when the "
|
|
678
|
+
"route is registered in several apps the response lists each and shows all of them. "
|
|
679
|
+
"(2) if the defect is in a callee named on the response's `calls:` line, read it with "
|
|
680
|
+
"ts_smart_read_file(path=<that path>, symbol=<name>) — a symbol declared in another file is inlined in "
|
|
681
|
+
"the same response, so one call is enough. Every slice is exact file text: use it verbatim as the hunk "
|
|
682
|
+
"target, without re-reading to check. "
|
|
618
683
|
"(3) ts_apply_edits with edits=[{path, hunks:[{target: exact snippet, replacement: fix, "
|
|
619
|
-
'start_line: the L from
|
|
620
|
-
"(4) if verify fails, fix the reported line and repeat (
|
|
621
|
-
"
|
|
622
|
-
"never rewrite a whole file."
|
|
684
|
+
'start_line: the L from the slice}]}] plus verify="auto" → edit and verdict in one call; '
|
|
685
|
+
"(4) if verify fails, fix the reported line and repeat (1)-(3). "
|
|
686
|
+
"Use ts_scoped_search only when the repro names no route. Skip ts_repo_map. Prefer these over "
|
|
687
|
+
"list_files/read_file; never rewrite a whole file."
|
|
623
688
|
)
|
|
624
689
|
|
|
625
690
|
SYSTEM_OUMV = (
|
|
626
691
|
"You are a senior Go engineer working in a small Go module that exposes the OUMV runtime. "
|
|
627
692
|
"The bug report includes a repro; use it to go straight to the right handler instead of guessing payloads. "
|
|
628
693
|
"Use this loop and stop as soon as the oracle passes: (1) oumv_observe L3 with the failing endpoint target "
|
|
629
|
-
"(e.g. \"POST /api/products\") —
|
|
630
|
-
"
|
|
631
|
-
"the
|
|
632
|
-
"
|
|
633
|
-
"
|
|
634
|
-
"
|
|
694
|
+
"(e.g. \"POST /api/products\") — ONE call returns the handler source, its workspace path, startLine/endLine and "
|
|
695
|
+
"the sha256 OCC version; (2) oumv_applyEdit with that path + expectedVersion and mode=\"patch\", "
|
|
696
|
+
"hunks=[{target: the exact line(s) you change, replacement: the fix, startLine: the line number from step 1, "
|
|
697
|
+
"endLine: the same line}] — scoping the hunk keeps it unique when the snippet appears elsewhere in the file; "
|
|
698
|
+
"the file is never re-sent and the edit is rejected on a "
|
|
699
|
+
"stale version; (3) if the result is an error, read the reported reason and repeat (2); (4) run_command to run "
|
|
700
|
+
"the oracle (oumv_verify starts a fresh app per call, so use it only for a single stateless request). "
|
|
701
|
+
"Do not fetch whole files with getSource and do not use write_file: the patch IS the edit. Do not call "
|
|
702
|
+
"list_files/read_file unless an OUMV tool returns an error. Tests are read-only."
|
|
635
703
|
)
|
|
636
704
|
|
|
637
705
|
|
|
@@ -510,12 +510,13 @@ SYSTEM_TOKENSAFE = (
|
|
|
510
510
|
"You are a senior React engineer working in a small sandbox. The workspace has TokenSafe tools. "
|
|
511
511
|
"Use this loop and stop as soon as the oracle reports 12: (1) ts_scoped_search for the behaviour named "
|
|
512
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
|
|
514
|
-
"
|
|
515
|
-
|
|
516
|
-
"
|
|
517
|
-
"
|
|
518
|
-
"
|
|
513
|
+
"as `symbol` — it returns the enclosing component/handler body (or a window around the hit) with line "
|
|
514
|
+
"numbers, and inlines the body when the identifier is declared in another file, so one call is enough; "
|
|
515
|
+
"(3) ts_apply_edits with one hunk {target: the exact snippet from that slice, replacement: the fix} plus "
|
|
516
|
+
'verify="auto" (the declared test command) — it edits and verifies in one call. The slice is exact file '
|
|
517
|
+
"text: do not re-read_file to check it. (4) if verify fails, read the reported line and repeat (2)-(3). "
|
|
518
|
+
"ts_repo_map is for an unfamiliar repository; skip it when the repro already names the component. Prefer "
|
|
519
|
+
"these tools over list_files/read_file. Tests and adapter.ts are read-only. Do not rewrite whole files."
|
|
519
520
|
)
|
|
520
521
|
|
|
521
522
|
SYSTEM_OUMV = (
|
package/src/bench/runner.py
CHANGED
|
@@ -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,
|
|
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
|
-
|
|
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; `
|
|
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
|
-
|
|
328
|
-
|
|
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}
|
|
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
|
package/src/installer.py
CHANGED
|
@@ -48,7 +48,7 @@ UNIFIED_TOKENSAFE_RULE = (
|
|
|
48
48
|
"## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
|
|
49
49
|
"Always use `tokensafe` MCP tools (`smart_read_file`, `scoped_search`, `apply_edits`, `repo_map`, `session_context`, `oumv`, `run_helper`) over default raw file reads or high-output terminal executions.\n\n"
|
|
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
|
-
"2. **Mandatory Symbol, 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). `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 — that is the slice you edit, never a folded skeleton you have to 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"
|
|
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
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"
|
|
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"
|