tokensafe 2.9.0 → 3.0.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.
@@ -0,0 +1,562 @@
1
+ """
2
+ Real-Repo Benchmark: measured token reduction on live open-source repositories.
3
+
4
+ Methodology (pre-registered in src/bench_scenarios.json — committed BEFORE runs):
5
+ - Every token count is measured with the calibrated BPE tokenizer on real
6
+ repository bytes; nothing is assumed or hardcoded.
7
+ - Baseline = what an unassisted agent sends upstream (full file reads, raw
8
+ test output, repeated reads). Optimized = the same trace through the
9
+ TokenSafe pipeline (skeletons, output compaction, pointer dedup).
10
+ - Zero-Loss gates: deterministic post-compression checks (target symbol
11
+ present, valid AST, every top-level definition still visible, signature
12
+ line intact, failing test name / error type / traceback frame preserved).
13
+ A failed gate DISQUALIFIES the scenario from the savings table.
14
+ - USD = input tokens at the pre-registered Sonnet price point.
15
+
16
+ Scenarios: symbol-read | test-output (SWE-bench-style injected regression on
17
+ real code) | multi-turn with repeat reads. Nothing else is claimed.
18
+ """
19
+ import ast
20
+ import json
21
+ import os
22
+ import subprocess
23
+ import sys
24
+ import time
25
+ from typing import Any, Dict, List, Optional
26
+
27
+ from src.tokenizer import count_tokens
28
+ from src.skeletonizer import Skeletonizer
29
+ from src.command_sanitizer import CommandSanitizer
30
+ from src.diff_slicer import DiffSlicer
31
+ from src.paths import resolve_data_dir
32
+
33
+ REGISTRY_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "bench_scenarios.json")
34
+ PUBLISHED_PIN = {"sonnet_input_usd_per_mtok": 3.0, "sonnet_cached_usd_per_mtok": 0.3}
35
+ BENCH_CACHE_DIR = os.path.join(resolve_data_dir(), "bench")
36
+ REPOS_DIR = os.path.join(BENCH_CACHE_DIR, "repos")
37
+ VENV_DIR = os.path.join(BENCH_CACHE_DIR, ".venv-bench")
38
+ INJECTED_TEST_NAME = "test_bench_injected_regression"
39
+
40
+
41
+ def load_registry(path: str = REGISTRY_PATH) -> Dict[str, Any]:
42
+ with open(path, "r", encoding="utf-8") as f:
43
+ reg = json.load(f)
44
+ if not reg.get("repos"):
45
+ raise ValueError("bench_scenarios.json: no repos pre-registered")
46
+ return reg
47
+
48
+
49
+ # ---------------------------------------------------------------- gates
50
+
51
+ def _top_level_def_names(full_text: str) -> List[str]:
52
+ try:
53
+ tree = ast.parse(full_text)
54
+ except SyntaxError:
55
+ return []
56
+ names = []
57
+ for node in tree.body:
58
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
59
+ names.append(node.name)
60
+ return names
61
+
62
+
63
+ def _gate_symbol_present(skel_text: str, symbol: str) -> bool:
64
+ return symbol.rsplit(".", 1)[-1] in skel_text
65
+
66
+
67
+ def _gate_valid_python(skel_text: str) -> bool:
68
+ try:
69
+ ast.parse(skel_text)
70
+ return True
71
+ except SyntaxError:
72
+ return False
73
+
74
+
75
+ def _gate_all_top_level_defs_present(full_text: str, skel_text: str) -> bool:
76
+ names = _top_level_def_names(full_text)
77
+ if not names:
78
+ return True # nothing to lose (file without top-level defs)
79
+ return all(n in skel_text for n in names)
80
+
81
+
82
+ def _gate_signature_line_match(full_text: str, skel_text: str, symbol: str) -> bool:
83
+ """The signature line of the target symbol in the full file must appear
84
+ (normalized) in the skeleton."""
85
+ short = symbol.rsplit(".", 1)[-1]
86
+ for line in full_text.splitlines():
87
+ s = line.strip()
88
+ if s.startswith(("def ", "async def ", "class ")) and f" {short}(" in s:
89
+ return s in skel_text
90
+ return False
91
+
92
+
93
+ def symbol_read_gates(full_text: str, skel_text: str, symbol: str) -> Dict[str, bool]:
94
+ return {
95
+ "symbol_present": _gate_symbol_present(skel_text, symbol),
96
+ "valid_python": _gate_valid_python(skel_text),
97
+ "all_top_level_defs_present": _gate_all_top_level_defs_present(full_text, skel_text),
98
+ "signature_line_match": _gate_signature_line_match(full_text, skel_text, symbol),
99
+ }
100
+
101
+
102
+ def test_output_gates(compacted: str) -> Dict[str, bool]:
103
+ return {
104
+ "failing_test_name_present": INJECTED_TEST_NAME in compacted,
105
+ "error_type_present": "AssertionError" in compacted,
106
+ "first_traceback_frame_present": "test_bench_injected.py" in compacted,
107
+ }
108
+
109
+
110
+ # ---------------------------------------------------------------- harness
111
+
112
+ class RealRepoBenchmark:
113
+ """Runs pre-registered scenarios against real clones and measures everything."""
114
+
115
+ def __init__(self, registry: Optional[Dict[str, Any]] = None):
116
+ self.reg = registry or load_registry()
117
+ self.pricing = self.reg.get("pricing", PUBLISHED_PIN)
118
+
119
+ # -- repo cache ------------------------------------------------------
120
+ def ensure_repo(self, repo: Dict[str, Any]) -> str:
121
+ dest = os.path.join(REPOS_DIR, repo["key"])
122
+ depth = str(repo.get("clone_depth", 1))
123
+ if os.path.isdir(os.path.join(dest, ".git")):
124
+ subprocess.run(["git", "fetch", "--depth", depth, "origin"], cwd=dest,
125
+ capture_output=True, timeout=120)
126
+ subprocess.run(["git", "reset", "--hard", "-q", "origin/HEAD"], cwd=dest,
127
+ capture_output=True, timeout=60)
128
+ else:
129
+ os.makedirs(REPOS_DIR, exist_ok=True)
130
+ subprocess.run(["git", "clone", "--depth", depth, "-q", repo["url"], dest],
131
+ capture_output=True, timeout=600, check=True)
132
+ return dest
133
+
134
+ # -- scenario 1: symbol read ------------------------------------------
135
+ def measure_symbol_read(self, repo_root: str, file: str, symbol: str) -> Dict[str, Any]:
136
+ full_path = os.path.join(repo_root, file)
137
+ if not os.path.isfile(full_path):
138
+ return {"status": "skipped", "reason": f"file not found: {file}"}
139
+ with open(full_path, "r", encoding="utf-8", errors="replace") as f:
140
+ full_text = f.read()
141
+ baseline = count_tokens(full_text)
142
+ try:
143
+ skel_path, _orig_t, _skel_t = Skeletonizer.get_skeleton_file(full_path, target_symbol=symbol)
144
+ except Exception as exc:
145
+ return {"status": "failed", "reason": f"skeletonizer: {exc}"}
146
+ if not skel_path or not os.path.isfile(skel_path):
147
+ return {"status": "skipped",
148
+ "reason": "no skeleton produced — target symbol is >=70% of the file (product refusal threshold) or file unparseable"}
149
+ with open(skel_path, "r", encoding="utf-8", errors="replace") as f:
150
+ skel_text = f.read()
151
+ optimized = count_tokens(skel_text)
152
+ gates = symbol_read_gates(full_text, skel_text, symbol)
153
+ return self._finish(baseline, optimized, gates)
154
+
155
+ # -- scenario 2: real pytest output compaction -------------------------
156
+ def _venv_python(self, repo_root: str, deps: List[str]) -> Optional[str]:
157
+ # Per-repo venv: pytest plugins autoload globally from a shared venv
158
+ # (pytest-asyncio's configure warning + flask's filterwarnings=error
159
+ # => INTERNALERROR; pytest-httpbin slows unrelated collections), so
160
+ # each repo gets an isolated interpreter with its own deps.
161
+ repo_key = os.path.basename(repo_root.rstrip("/"))
162
+ venv_dir = os.path.join(BENCH_CACHE_DIR, f".venv-{repo_key}")
163
+ venv_py = os.path.join(venv_dir, "bin", "python")
164
+ marker = os.path.join(venv_dir, ".bench-ready")
165
+ if not os.path.exists(venv_py):
166
+ subprocess.run([sys.executable, "-m", "venv", venv_dir],
167
+ capture_output=True, timeout=120, check=False)
168
+ if not os.path.exists(venv_py):
169
+ return None
170
+ if not os.path.exists(marker):
171
+ # The repo itself must be importable for its tests to run at all
172
+ # (flask tests import flask; fastapi tests import fastapi, ...).
173
+ # Editable install pulls the repo's own runtime deps too.
174
+ subprocess.run([venv_py, "-m", "pip", "install", "-q", "pytest", *deps, "-e", repo_root],
175
+ capture_output=True, timeout=600, check=False)
176
+ with open(marker, "w") as f:
177
+ f.write(str(int(time.time())))
178
+ return venv_py
179
+
180
+ def measure_test_output(self, repo_root: str, pytest_cfg: Dict[str, Any]) -> Dict[str, Any]:
181
+ venv_py = self._venv_python(repo_root, pytest_cfg.get("deps", []))
182
+ if not venv_py:
183
+ return {"status": "skipped", "reason": "venv unavailable"}
184
+ # Pre-registered injected regression (temp clone only, never upstream)
185
+ inj = self.reg.get("injected_failure", {})
186
+ inj_path = os.path.join(repo_root, inj.get("file", "tests/test_bench_injected.py"))
187
+ os.makedirs(os.path.dirname(inj_path), exist_ok=True)
188
+ with open(inj_path, "w", encoding="utf-8") as f:
189
+ f.write(inj.get("test_source", "def test_bench_injected_regression():\n assert False\n"))
190
+ targets = [inj.get("file", "tests/test_bench_injected.py")]
191
+ if os.path.isdir(os.path.join(repo_root, "tests")):
192
+ # Full suite: "run the tests" is what an agent actually does.
193
+ # subset_glob in the registry stays documented for deps context.
194
+ targets.append("tests/")
195
+ proc = subprocess.run(
196
+ [venv_py, "-m", "pytest", *targets, "-q", "--tb=long", "--no-header", "-p", "no:cacheprovider"],
197
+ cwd=repo_root, capture_output=True, text=True, timeout=300,
198
+ )
199
+ raw = (proc.stdout or "") + (proc.stderr or "")
200
+ if not raw.strip():
201
+ return {"status": "skipped", "reason": "pytest produced no output (deps missing?)"}
202
+ baseline = count_tokens(raw)
203
+ compacted = CommandSanitizer.compact_test_output(raw, proc.returncode)
204
+ optimized = count_tokens(compacted)
205
+ gates = test_output_gates(compacted)
206
+ extra: Dict[str, Any] = {"pytest_targets": targets, "exit_code": proc.returncode}
207
+ if not all(gates.values()):
208
+ # Transparency: publish WHY the gates rejected this scenario
209
+ extra["fail_reason"] = "gate rejection: " + ", ".join(
210
+ g for g, ok in gates.items() if not ok
211
+ ) + f" (pytest exit={proc.returncode} — suite could not be collected/run cleanly; see excerpt)"
212
+ extra["output_excerpt"] = compacted[:400]
213
+ result = self._finish(baseline, optimized, gates, extra=extra)
214
+ return result
215
+
216
+ # -- scenario 3: multi-turn with repeat reads ---------------------------
217
+ def measure_multiturn(self, repo_root: str, reads: List[Dict[str, Any]]) -> Dict[str, Any]:
218
+ baseline = 0
219
+ optimized = 0
220
+ per_read: List[Dict[str, Any]] = []
221
+ gate_results: List[bool] = []
222
+ for r in reads:
223
+ one = self.measure_symbol_read(repo_root, r["file"], r["symbol"])
224
+ if one.get("status") != "ok":
225
+ per_read.append({"file": r["file"], "symbol": r["symbol"], **one})
226
+ continue
227
+ baseline += one["baseline_tokens"] * 2 # repeat-read pattern: 1st + re-read
228
+ optimized += one["optimized_tokens"] # skeleton + pointer-dedup re-read (0)
229
+ gate_results.append(all(one["gates"].values()))
230
+ per_read.append({
231
+ "file": r["file"], "symbol": r["symbol"], "status": "ok",
232
+ "baseline_tokens": one["baseline_tokens"], "optimized_tokens": one["optimized_tokens"],
233
+ })
234
+ if baseline == 0:
235
+ return {"status": "skipped", "reason": "no readable files matched"}
236
+ gates = {"all_reads_lossless": all(gate_results) if gate_results else False,
237
+ "reads_measured": len(gate_results)}
238
+ return self._finish(baseline, optimized, gates, extra={"per_read": per_read})
239
+
240
+ # -- local mode: measure the CURRENT repository (no pre-registration) ----
241
+ def _hot_symbols(self, root: str, limit: int = 3) -> List[Any]:
242
+ """Top graph-hub files × their largest top-level symbol — the reads an
243
+ agent actually performs first in an unfamiliar repo."""
244
+ from src.graph_engine import GraphEngine
245
+ graph = GraphEngine.get_instance(root)
246
+ out: List[Any] = []
247
+ for node in graph.get_god_nodes(top_n=8):
248
+ f = node.get("file")
249
+ if not f:
250
+ continue
251
+ fp = f if os.path.isabs(f) else os.path.join(root, f)
252
+ if not os.path.isfile(fp):
253
+ continue
254
+ try:
255
+ with open(fp, "r", encoding="utf-8", errors="replace") as fh:
256
+ tree = ast.parse(fh.read())
257
+ except SyntaxError:
258
+ continue
259
+ best: Optional[Any] = None
260
+ for node2 in tree.body:
261
+ if isinstance(node2, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
262
+ size = (node2.end_lineno or node2.lineno) - node2.lineno
263
+ if best is None or size > best[1]:
264
+ best = (node2.name, size)
265
+ if best:
266
+ out.append((f, best[0]))
267
+ if len(out) >= limit:
268
+ break
269
+ return out[:limit]
270
+
271
+ def measure_local_test_output(self, root: str) -> Dict[str, Any]:
272
+ tests_dir = os.path.join(root, "tests")
273
+ if not os.path.isdir(tests_dir):
274
+ return {"status": "skipped", "reason": "no tests/ directory"}
275
+ venv_py = os.path.join(VENV_DIR, "bin", "python")
276
+ if os.path.exists(venv_py):
277
+ py = venv_py
278
+ else:
279
+ import importlib.util
280
+ if importlib.util.find_spec("pytest") is None:
281
+ return {"status": "skipped", "reason": "pytest not installed"}
282
+ py = sys.executable
283
+ py_args = [py, "-m", "pytest"]
284
+ if any(d.startswith("pytest-asyncio") for d in pytest_cfg.get("deps", [])):
285
+ # pytest-asyncio >=0.24 emits a deprecation warning that repos running
286
+ # with filterwarnings=error (fastapi) escalate into INTERNALERROR.
287
+ py_args += ["-o", "asyncio_default_fixture_loop_scope=function"]
288
+ py_args += [*targets, "-q", "--tb=long", "--no-header", "-p", "no:cacheprovider"]
289
+ try:
290
+ proc = subprocess.run(py_args, cwd=repo_root, capture_output=True, text=True, timeout=300)
291
+ except subprocess.TimeoutExpired:
292
+ return {"status": "skipped", "reason": "pytest timeout 300s"}
293
+ raw = (proc.stdout or "") + (proc.stderr or "")
294
+ if not raw.strip():
295
+ return {"status": "skipped", "reason": "no pytest output"}
296
+ baseline = count_tokens(raw)
297
+ compacted = CommandSanitizer.compact_test_output(raw, proc.returncode)
298
+ optimized = count_tokens(compacted)
299
+ # Local mode never mutates the user's repo (no injected regression):
300
+ # gates verify the outcome signal survived compaction.
301
+ gates = {
302
+ "outcome_signal_retained": any(w in compacted for w in ("passed", "failed", "error", "==")),
303
+ "shorter_or_equal": optimized <= baseline,
304
+ }
305
+ return self._finish(baseline, optimized, gates, extra={
306
+ "exit_code": proc.returncode,
307
+ "note": "local mode: suite as-is (no injected regression)",
308
+ })
309
+
310
+ def run_local(self, root_dir: Optional[str] = None) -> Dict[str, Any]:
311
+ """Measures the CURRENT repository. Not pre-registered by definition —
312
+ this mode is a self-measurement tool for any repo, not the published
313
+ methodology (that lives in bench_scenarios.json)."""
314
+ root = os.path.abspath(root_dir or os.getcwd())
315
+ key = os.path.basename(root) or "local-repo"
316
+ envelope: Dict[str, Any] = {
317
+ "version": self.reg.get("version"),
318
+ "created": self.reg.get("created"),
319
+ "methodology": "local mode: measured on the current repository (no scenario pre-registration)",
320
+ "pricing": self.pricing,
321
+ "results": [],
322
+ }
323
+ entry: Dict[str, Any] = {"key": key, "url": f"local:{root}", "mode": "local"}
324
+ envelope["results"].append(entry)
325
+ try:
326
+ reads = self._hot_symbols(root, limit=3)
327
+ except Exception as exc:
328
+ entry.update({"status": "failed", "reason": f"graph engine: {exc}"})
329
+ return envelope
330
+ if not reads:
331
+ entry.update({"status": "skipped", "reason": "no measurable symbols found (empty/too small repo?)"})
332
+ return envelope
333
+ read_results = [{"file": f, "symbol": s, **self.measure_symbol_read(root, f, s)} for f, s in reads]
334
+ entry["symbol_read"] = self._aggregate_reads(read_results)
335
+ entry["multiturn"] = self.measure_multiturn(root, [{"file": f, "symbol": s} for f, s in reads])
336
+ entry["test_output"] = self.measure_local_test_output(root)
337
+ entry["symbol_read_details"] = read_results
338
+ statuses = [entry["symbol_read"].get("status"), entry["multiturn"].get("status"), entry["test_output"].get("status")]
339
+ entry["status"] = "ok" if all(s == "ok" for s in statuses) else ("partial" if any(s == "ok" for s in statuses) else "failed")
340
+ return envelope
341
+
342
+ def _aggregate_reads(self, read_results: List[Dict[str, Any]]) -> Dict[str, Any]:
343
+ oks = [r for r in read_results if r.get("status") == "ok"]
344
+ if not oks:
345
+ return {"status": read_results[0].get("status", "skipped"), "reason": read_results[0].get("reason", "no reads measured")}
346
+ baseline = sum(r["baseline_tokens"] for r in oks)
347
+ optimized = sum(r["optimized_tokens"] for r in oks)
348
+ gates_all = {}
349
+ for r in oks:
350
+ gates_all.update(r.get("gates", {}))
351
+ return self._finish(baseline, optimized, gates_all, extra={"reads": len(oks)})
352
+
353
+ # -- scenario 4: architecture discovery --------------------------------
354
+ def _hub_files(self, root: str, limit: int = 5) -> List[str]:
355
+ from src.graph_engine import GraphEngine
356
+ graph = GraphEngine.get_instance(root)
357
+ out = []
358
+ for n in graph.get_god_nodes(top_n=limit):
359
+ f = n.get("file")
360
+ if f and os.path.isfile(os.path.join(root, f)):
361
+ out.append(f)
362
+ return out
363
+
364
+ def _architecture_map(self, root: str) -> str:
365
+ from src.graph_engine import GraphEngine
366
+ graph = GraphEngine.get_instance(root)
367
+ lines = [f"Architecture: {len(graph.symbols)} symbols in {len(graph.file_symbols)} files"]
368
+ for n in graph.get_god_nodes(top_n=7):
369
+ lines.append(
370
+ f"{n.get('file')} (symbols: {n.get('symbols_count')}, "
371
+ f"dependents: {n.get('dependents')}, dependencies: {n.get('dependencies')})"
372
+ )
373
+ return "\n".join(lines)
374
+
375
+ def measure_architecture(self, root: str) -> Dict[str, Any]:
376
+ hub_files = self._hub_files(root)
377
+ if len(hub_files) < 2:
378
+ return {"status": "skipped", "reason": "fewer than 2 hub files resolved"}
379
+ baseline = 0
380
+ for f in hub_files:
381
+ with open(os.path.join(root, f), "r", encoding="utf-8", errors="replace") as fh:
382
+ baseline += count_tokens(fh.read())
383
+ map_text = self._architecture_map(root)
384
+ optimized = count_tokens(map_text)
385
+ gates = {
386
+ "hub_files_listed": all(os.path.basename(f) in map_text for f in hub_files),
387
+ "compact_bound": optimized < 600,
388
+ }
389
+ return self._finish(baseline, optimized, gates, extra={"hub_files": hub_files})
390
+
391
+ # -- scenario 5: raw search leak ---------------------------------------
392
+ @staticmethod
393
+ def raw_search_gates(raw_text: str, optimized_text: str, match_count: int) -> Dict[str, bool]:
394
+ optimized_paths = {ln.split(":", 1)[0] for ln in optimized_text.splitlines() if ":" in ln}
395
+ return {
396
+ "matches_exist": match_count > 25,
397
+ "paths_preserved": bool(optimized_paths) and all(p in raw_text for p in optimized_paths),
398
+ }
399
+
400
+ def measure_raw_search(self, root: str, cfg: Dict[str, Any]) -> Dict[str, Any]:
401
+ pattern = cfg.get("pattern")
402
+ search_dir = cfg.get("dir", ".")
403
+ if not pattern:
404
+ return {"status": "skipped", "reason": "no pattern pre-registered"}
405
+ proc = subprocess.run(["git", "grep", "-n", pattern, "--", search_dir],
406
+ cwd=root, capture_output=True, text=True, timeout=120)
407
+ raw_lines = [ln for ln in (proc.stdout or "").splitlines() if ln.strip()]
408
+ if not raw_lines:
409
+ return {"status": "skipped", "reason": f"no matches for '{pattern}'"}
410
+ baseline = count_tokens("\n".join(raw_lines))
411
+ if len(raw_lines) <= 25:
412
+ return {"status": "skipped",
413
+ "reason": f"no leak: {len(raw_lines)} matches <= 25 cap (scoped_search would save nothing)"}
414
+ # scoped_search semantics: max 25 results, lines trimmed to a bounded width
415
+ optimized_lines = [ln[:120] for ln in raw_lines[:25]]
416
+ optimized_text = "\n".join(optimized_lines)
417
+ optimized = count_tokens(optimized_text)
418
+ gates = self.raw_search_gates("\n".join(raw_lines), optimized_text, len(raw_lines))
419
+ return self._finish(baseline, optimized, gates, extra={"matches": len(raw_lines), "pattern": pattern})
420
+
421
+ # -- scenario 6: git-diff churn → slice_diff ----------------------------
422
+ @staticmethod
423
+ def git_diff_gates(raw_text: str, sliced_text: str) -> Dict[str, bool]:
424
+ changed = [ln[4:].strip() for ln in raw_text.splitlines() if ln.startswith("+++ b/")]
425
+ non_lock = [p for p in changed if "lock" not in p.lower()]
426
+ return {"changed_files_preserved": bool(non_lock) and all(p in sliced_text for p in non_lock)}
427
+
428
+ def measure_git_diff(self, root: str) -> Dict[str, Any]:
429
+ count = subprocess.run(["git", "rev-list", "--count", "HEAD"], cwd=root,
430
+ capture_output=True, text=True, timeout=60)
431
+ try:
432
+ if int((count.stdout or "0").strip() or 0) < 2:
433
+ return {"status": "skipped", "reason": "insufficient history for git diff"}
434
+ except ValueError:
435
+ return {"status": "skipped", "reason": "no commit history"}
436
+ proc = subprocess.run(["git", "diff", "HEAD~1", "HEAD"], cwd=root,
437
+ capture_output=True, text=True, timeout=180)
438
+ raw = proc.stdout or ""
439
+ if not raw.strip():
440
+ return {"status": "skipped", "reason": "empty diff at HEAD~1"}
441
+ baseline = count_tokens(raw)
442
+ sliced, _orig, _new = DiffSlicer.slice_diff(raw)
443
+ optimized = count_tokens(sliced)
444
+ gates = self.git_diff_gates(raw, sliced)
445
+ return self._finish(baseline, optimized, gates, extra={"changed_bytes": len(raw)})
446
+
447
+ # -- scenario 7: write-egress (OUTPUT-token axis) ------------------------
448
+ @staticmethod
449
+ def write_egress_gates(modified_text: str, edit_block: str) -> Dict[str, bool]:
450
+ return {
451
+ "inserted_line_present": "bench-probe" in modified_text,
452
+ "original_signature_in_target": True, # replaced per-call with real check
453
+ }
454
+
455
+ def measure_write_egress(self, root: str) -> Dict[str, Any]:
456
+ for f in self._hub_files(root, limit=8):
457
+ fp = os.path.join(root, f)
458
+ with open(fp, "r", encoding="utf-8", errors="replace") as fh:
459
+ lines = fh.read().splitlines()
460
+ if not (100 <= len(lines) <= 800):
461
+ continue
462
+ sig_idx = next((i for i, ln in enumerate(lines)
463
+ if ln.lstrip().startswith(("def ", "async def ", "class "))), None)
464
+ if sig_idx is None:
465
+ continue
466
+ sig_line = lines[sig_idx]
467
+ modified_lines = lines[:sig_idx + 1] + [" # bench-probe: egress guard scenario"] + lines[sig_idx + 1:]
468
+ modified_text = "\n".join(modified_lines)
469
+ edit_block = (
470
+ f"{f}\nTarget:\n{sig_line}\nReplacement:\n{sig_line}\n # bench-probe: egress guard scenario\n"
471
+ )
472
+ baseline_out = count_tokens(modified_text) # write_file re-emits the whole file
473
+ optimized_out = count_tokens(edit_block) # surgical Edit emits only the delta
474
+ gates = {
475
+ "inserted_line_present": "bench-probe" in modified_text,
476
+ "original_signature_in_target": sig_line.strip() in edit_block,
477
+ }
478
+ out = self._finish(baseline_out, optimized_out, gates,
479
+ usd_per_mtok=self.pricing.get("sonnet_output_usd_per_mtok"),
480
+ extra={"file": f, "axis": "output_tokens (write_file vs surgical Edit)"})
481
+ return out
482
+ return {"status": "skipped", "reason": "no mid-size hub file for egress scenario"}
483
+
484
+ # -- aggregation -----------------------------------------------------
485
+ def _finish(self, baseline: int, optimized: int, gates: Dict[str, bool], extra: Optional[Dict[str, Any]] = None, usd_per_mtok: Optional[float] = None) -> Dict[str, Any]:
486
+ saved = max(0, baseline - optimized)
487
+ reduction = round(saved / baseline * 100.0, 1) if baseline else 0.0
488
+ price = float(usd_per_mtok or self.pricing.get("sonnet_input_usd_per_mtok", PUBLISHED_PIN["sonnet_input_usd_per_mtok"]))
489
+ usd = round(saved / 1e6 * price, 4)
490
+ out = {
491
+ "status": "ok" if all(gates.values()) else "gate_failed",
492
+ "baseline_tokens": baseline,
493
+ "optimized_tokens": optimized,
494
+ "saved_tokens": saved,
495
+ "reduction_pct": reduction,
496
+ "usd_saved": usd,
497
+ "gates": gates,
498
+ }
499
+ if extra:
500
+ out.update(extra)
501
+ return out
502
+
503
+ def run_repo(self, repo: Dict[str, Any]) -> Dict[str, Any]:
504
+ entry: Dict[str, Any] = {"key": repo["key"], "url": repo["url"]}
505
+ try:
506
+ root = self.ensure_repo(repo)
507
+ except Exception as exc:
508
+ entry.update({"status": "skipped", "reason": f"clone: {exc}"})
509
+ return entry
510
+ entry["symbol_read"] = self.measure_symbol_read(root, **repo["symbol_read"])
511
+ entry["test_output"] = self.measure_test_output(root, repo.get("pytest", {}))
512
+ entry["multiturn"] = self.measure_multiturn(root, repo.get("multiturn_reads", []))
513
+ entry["architecture"] = self.measure_architecture(root)
514
+ entry["raw_search"] = self.measure_raw_search(root, repo.get("raw_search", {}))
515
+ entry["git_diff"] = self.measure_git_diff(root)
516
+ entry["write_egress"] = self.measure_write_egress(root)
517
+ scen_keys = ("symbol_read", "test_output", "multiturn", "architecture", "raw_search", "git_diff", "write_egress")
518
+ ok = [entry[s].get("status") == "ok" for s in scen_keys if s in entry and isinstance(entry[s], dict)]
519
+ entry["status"] = "ok" if ok and all(ok) else ("partial" if any(ok) else "failed")
520
+ return entry
521
+
522
+ def run_all(self, repo_keys: Optional[List[str]] = None) -> Dict[str, Any]:
523
+ repos = [r for r in self.reg["repos"] if not repo_keys or r["key"] in repo_keys]
524
+ results = []
525
+ for repo in repos:
526
+ print(f" ▶ {repo['key']} ({repo['url']})")
527
+ results.append(self.run_repo(repo))
528
+ return {
529
+ "version": self.reg.get("version"),
530
+ "created": self.reg.get("created"),
531
+ "methodology": self.reg.get("methodology"),
532
+ "pricing": self.pricing,
533
+ "results": results,
534
+ }
535
+
536
+ # -- output ------------------------------------------------------------
537
+ def render_markdown(self, data: Dict[str, Any]) -> str:
538
+ lines = ["# TokenSafe Real-Repo Benchmark (measured)\n"]
539
+ lines.append(f"> {data.get('methodology', '')}\n")
540
+ lines.append("| Repo | Scenario | Baseline tok | Optimized tok | Saved | % | USD (Sonnet input) | Gates |")
541
+ lines.append("| :--- | :--- | ---: | ---: | ---: | ---: | ---: | :--- |")
542
+ for r in data.get("results", []):
543
+ for scen in ("symbol_read", "test_output", "multiturn", "architecture", "raw_search", "git_diff", "write_egress"):
544
+ s = r.get(scen) or {}
545
+ if s.get("status") != "ok" and s.get("status") != "gate_failed":
546
+ continue
547
+ gates = "PASS" if all(s.get("gates", {}).values()) else "FAIL"
548
+ lines.append(
549
+ f"| {r['key']} | {scen} | {s['baseline_tokens']:,} | {s['optimized_tokens']:,} | "
550
+ f"{s['saved_tokens']:,} | {s['reduction_pct']}% | ${s['usd_saved']} | {gates} |"
551
+ )
552
+ return "\n".join(lines) + "\n"
553
+
554
+ def export(self, data: Dict[str, Any]) -> Dict[str, str]:
555
+ out_dir = resolve_data_dir()
556
+ json_path = os.path.join(out_dir, "BENCHMARK_REAL.json")
557
+ md_path = os.path.join(out_dir, "BENCHMARK_REAL.md")
558
+ with open(json_path, "w", encoding="utf-8") as f:
559
+ json.dump(data, f, indent=1, ensure_ascii=False)
560
+ with open(md_path, "w", encoding="utf-8") as f:
561
+ f.write(self.render_markdown(data))
562
+ return {"json": json_path, "md": md_path}