tokensafe 4.7.0 → 4.7.2

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.
@@ -19,9 +19,12 @@ import re
19
19
  import shutil
20
20
  import subprocess
21
21
  import tempfile
22
+ import time
22
23
  from pathlib import Path
23
24
  from typing import Any, Dict, List, Optional, Tuple
24
25
 
26
+ from src.bench import tokensafe_mcp
27
+
25
28
  REPO_ROOT = Path(__file__).resolve().parents[3]
26
29
  GO_ROOT = REPO_ROOT / "tokensafe-backend" / "go"
27
30
  COPY_ITEMS = ("go.mod", "go.sum", "tokensafe.go", "pkg", "benchmark", "cmd")
@@ -32,10 +35,19 @@ MAX_TOOL_OUTPUT = 4000
32
35
  TASKS: Dict[str, Dict[str, Any]] = {
33
36
  "product-create-status": {
34
37
  "symptom": "creating a product returns HTTP 200 instead of 201, so the contract test fails.",
38
+ "repro": (
39
+ "POST /api/products with {\"title\":\"USB-C Hub\",\"price\":39.99,\"stock\":15,\"category\":\"electronics\"} "
40
+ "must answer 201; it answers 200. Stateless: one request is enough."
41
+ ),
35
42
  "breaks": [(f"{SANDBOX_FILE}", "c.JSON(http.StatusCreated, p)", "c.JSON(http.StatusOK, p)")],
36
43
  },
37
44
  "order-conflict-status": {
38
45
  "symptom": "a duplicate idempotency key returns HTTP 400 instead of 409, so clients retry blindly.",
46
+ "repro": (
47
+ "POST /api/orders with {\"idempotencyKey\":\"order_key_001\",\"customerId\":\"cust_100\","
48
+ "\"items\":[{\"productId\":2,\"quantity\":1}]} twice in the same process: the second call must answer 409 "
49
+ "and answers 400. Stateful: the first call creates the key, so the second call is the one that fails."
50
+ ),
39
51
  "breaks": [(
40
52
  SANDBOX_FILE,
41
53
  'c.JSON(http.StatusConflict, gin.H{"error": errMsg})',
@@ -44,6 +56,10 @@ TASKS: Dict[str, Dict[str, Any]] = {
44
56
  },
45
57
  "product-validation-status": {
46
58
  "symptom": "an invalid product payload is accepted with HTTP 200 instead of being rejected with 422.",
59
+ "repro": (
60
+ "POST /api/products with {\"title\":\"Bad Product\",\"price\":-10,\"stock\":5} must answer 422 (or 400); "
61
+ "it answers 200. Stateless: one request is enough."
62
+ ),
47
63
  "breaks": [(
48
64
  SANDBOX_FILE,
49
65
  # the CreateProduct validation branch (the binding branch alone is not
@@ -60,11 +76,10 @@ def _run(cmd: List[str], cwd: Path, timeout: float = 240.0, env: Optional[Dict[s
60
76
 
61
77
 
62
78
  class GoWorkspace:
63
- def __init__(self, task_id: str, helper: Path):
79
+ def __init__(self, task_id: str):
64
80
  if task_id not in TASKS:
65
81
  raise ValueError(f"unknown task {task_id}; valid: {', '.join(TASKS)}")
66
82
  self.task_id = task_id
67
- self.helper = helper
68
83
  self.dir = Path(tempfile.mkdtemp(prefix=f"oumv-bench-{task_id}-")) / "go"
69
84
  self.dir.mkdir(parents=True)
70
85
  for item in COPY_ITEMS:
@@ -74,6 +89,12 @@ class GoWorkspace:
74
89
  shutil.copytree(src, dst)
75
90
  else:
76
91
  shutil.copy2(src, dst)
92
+ # The runtime must serve the *workspace* code: build the helper inside the
93
+ # copied module and rebuild it when an edit changes the sources, otherwise
94
+ # oumv/verify would keep reporting the pristine app's behaviour.
95
+ self.helper = self.dir.parent / "benchoumv"
96
+ self._helper_built_at = 0.0
97
+ self._mcp = None
77
98
  self.break_build()
78
99
 
79
100
  # ---- task setup -------------------------------------------------------
@@ -160,8 +181,60 @@ class GoWorkspace:
160
181
  out = ((proc.stdout or "") + (proc.stderr or "")).strip()
161
182
  return {"exit_code": proc.returncode, "output": out[-MAX_TOOL_OUTPUT:]}
162
183
 
184
+ def search_files(self, query: str, path: str = ".", max_hits: int = 40) -> Any:
185
+ """Case-insensitive substring search — the grep a normal agent would have."""
186
+ base = self._resolve(path)
187
+ needle = query.strip().lower()
188
+ if not needle:
189
+ return {"error": "query is required"}
190
+ max_hits = max(1, min(int(max_hits), 100))
191
+ hits: List[str] = []
192
+ for entry in sorted(base.rglob("*")):
193
+ if not entry.is_file() or entry.suffix not in {".go", ".mod", ".sum"}:
194
+ continue
195
+ if any(part in {".git", "vendor"} for part in entry.relative_to(base).parts):
196
+ continue
197
+ try:
198
+ text = entry.read_text(encoding="utf-8", errors="replace")
199
+ except OSError:
200
+ continue
201
+ for number, line in enumerate(text.splitlines(), 1):
202
+ if needle in line.lower():
203
+ hits.append(f"{entry.relative_to(base)}:{number}: {line.strip()[:160]}")
204
+ if len(hits) >= max_hits:
205
+ return {"query": query, "hits": hits, "truncated": True}
206
+ return {"query": query, "hits": hits, "truncated": False}
207
+
163
208
  # ---- OUMV -------------------------------------------------------------
209
+ def _newest_source_mtime(self) -> float:
210
+ newest = 0.0
211
+ for path in self.dir.rglob("*.go"):
212
+ try:
213
+ newest = max(newest, path.stat().st_mtime)
214
+ except OSError:
215
+ continue
216
+ return newest
217
+
218
+ def _ensure_helper(self, rebuild: bool) -> Optional[Dict[str, Any]]:
219
+ """Builds the workspace helper; rebuilds only when live code is requested."""
220
+ if self.helper.exists() and (not rebuild or self._helper_built_at >= self._newest_source_mtime()):
221
+ return None
222
+ proc = _run(["go", "build", "-o", str(self.helper), "./cmd/benchoumv"], cwd=self.dir)
223
+ if proc.returncode != 0:
224
+ lines = ((proc.stderr or "") + (proc.stdout or "")).strip().splitlines()
225
+ return {"error": {"code": -32002, "message": "BUILD_ERROR: " + (lines[-1] if lines else "build failed")[:300]}}
226
+ self._helper_built_at = time.time()
227
+ return None
228
+
164
229
  def oumv(self, method: str, params: Dict[str, Any]) -> Any:
230
+ # verify/observe/understand must see the edited sources; getSource and L3
231
+ # read files directly, so they can reuse the last good binary.
232
+ live = method in ("oumv/verify", "oumv/understand") or (
233
+ method == "oumv/observe" and str(params.get("level") or "") != "L3"
234
+ )
235
+ failure = self._ensure_helper(rebuild=live)
236
+ if failure:
237
+ return failure
165
238
  request = {"jsonrpc": "2.0", "id": 1, "method": method, "params": params}
166
239
  proc = subprocess.run(
167
240
  [str(self.helper)],
@@ -183,20 +256,41 @@ class GoWorkspace:
183
256
  return {"error": payload["error"]}
184
257
  return payload.get("result")
185
258
 
259
+ def tokensafe_tool_schemas(self) -> Optional[List[Dict[str, Any]]]:
260
+ """The product's own `tools/list`, renamed to the arm's stable aliases.
261
+
262
+ `oumv` is excluded: it is a different product surface and would let this arm
263
+ call the protocol runtime the third arm is measuring.
264
+ """
265
+ if self._mcp is None:
266
+ self._mcp = tokensafe_mcp.open_client(self.dir)
267
+ if self._mcp is None:
268
+ return None
269
+ live = self._mcp.tool_schemas(exclude={"oumv"})
270
+ if not live:
271
+ return None
272
+ renamed = []
273
+ for tool in live:
274
+ clone = json.loads(json.dumps(tool))
275
+ real = clone["function"]["name"]
276
+ clone["function"]["name"] = TOKENSAFE_ALIASES.get(real, real)
277
+ renamed.append(clone)
278
+ return renamed
279
+
280
+ def tokensafe(self, name: str, arguments: Dict[str, Any]) -> Any:
281
+ if self._mcp is None:
282
+ self._mcp = tokensafe_mcp.open_client(self.dir)
283
+ if self._mcp is None:
284
+ return {"error": "TokenSafe MCP is unavailable"}
285
+ return self._mcp.call(name, arguments)
286
+
186
287
  def cleanup(self) -> None:
288
+ if self._mcp is not None:
289
+ self._mcp.close()
290
+ self._mcp = None
187
291
  shutil.rmtree(self.dir.parent, ignore_errors=True)
188
292
 
189
293
 
190
- def build_helper() -> Path:
191
- """Builds `cmd/benchoumv` once from the pristine module."""
192
- out_dir = Path(tempfile.mkdtemp(prefix="oumv-bench-helper-"))
193
- helper = out_dir / "benchoumv"
194
- proc = _run(["go", "build", "-o", str(helper), "./cmd/benchoumv"], cwd=GO_ROOT)
195
- if proc.returncode != 0:
196
- raise RuntimeError(f"failed to build benchoumv: {(proc.stderr or proc.stdout)[-800:]}")
197
- return helper
198
-
199
-
200
294
  # ---- tool schemas ---------------------------------------------------------
201
295
 
202
296
  BASE_TOOLS: List[Dict[str, Any]] = [
@@ -242,6 +336,22 @@ BASE_TOOLS: List[Dict[str, Any]] = [
242
336
  },
243
337
  },
244
338
  },
339
+ {
340
+ "type": "function",
341
+ "function": {
342
+ "name": "search_files",
343
+ "description": "Case-insensitive substring search across workspace .go files, returns path:line hits.",
344
+ "parameters": {
345
+ "type": "object",
346
+ "properties": {
347
+ "query": {"type": "string"},
348
+ "path": {"type": "string", "description": "Relative directory, default '.'"},
349
+ "max_hits": {"type": "integer", "description": "Default 40, max 100"},
350
+ },
351
+ "required": ["query"],
352
+ },
353
+ },
354
+ },
245
355
  {
246
356
  "type": "function",
247
357
  "function": {
@@ -256,6 +366,77 @@ BASE_TOOLS: List[Dict[str, Any]] = [
256
366
  },
257
367
  ]
258
368
 
369
+ TOKENSAFE_TOOLS: List[Dict[str, Any]] = BASE_TOOLS + [
370
+ {
371
+ "type": "function",
372
+ "function": {
373
+ "name": "ts_smart_read_file",
374
+ "description": "TokenSafe AST-skeleton reader: a compact symbol view (~90% fewer tokens than the 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 workspace.",
387
+ "parameters": {
388
+ "type": "object",
389
+ "properties": {
390
+ "query": {"type": "string"},
391
+ "path": {"type": "string", "description": "Relative directory, default '.'"},
392
+ },
393
+ "required": ["query"],
394
+ },
395
+ },
396
+ },
397
+ {
398
+ "type": "function",
399
+ "function": {
400
+ "name": "ts_apply_edits",
401
+ "description": (
402
+ "TokenSafe surgical editor: replaces exact snippets (hunks of {target, replacement}) "
403
+ "and runs `verify` after the edit, returning a one-line pass/fail."
404
+ ),
405
+ "parameters": {
406
+ "type": "object",
407
+ "properties": {
408
+ "path": {"type": "string"},
409
+ "edits": {
410
+ "type": "array",
411
+ "items": {
412
+ "type": "object",
413
+ "properties": {
414
+ "target": {"type": "string", "description": "Exact snippet to replace"},
415
+ "replacement": {"type": "string", "description": "Replacement snippet"},
416
+ },
417
+ "required": ["target", "replacement"],
418
+ },
419
+ },
420
+ "verify": {"type": "string", "description": "Shell command to run after the edit"},
421
+ },
422
+ "required": ["path", "edits"],
423
+ },
424
+ },
425
+ },
426
+ {
427
+ "type": "function",
428
+ "function": {
429
+ "name": "ts_repo_map",
430
+ "description": "TokenSafe architecture map: god nodes / high-dependency files, or an API surface.",
431
+ "parameters": {
432
+ "type": "object",
433
+ "properties": {"view": {"type": "string", "enum": ["graph", "api", "tree"]}},
434
+ "required": ["view"],
435
+ },
436
+ },
437
+ },
438
+ ]
439
+
259
440
  OUMV_TOOLS: List[Dict[str, Any]] = BASE_TOOLS + [
260
441
  {
261
442
  "type": "function",
@@ -284,6 +465,27 @@ OUMV_TOOLS: List[Dict[str, Any]] = BASE_TOOLS + [
284
465
  },
285
466
  },
286
467
  },
468
+ {
469
+ "type": "function",
470
+ "function": {
471
+ "name": "oumv_applyEdit",
472
+ "description": (
473
+ "OUMV guarded edit: applies only if `expectedVersion` matches the file on disk. "
474
+ "mode='symbol' replaces one declaration (cheaper than the whole file)."
475
+ ),
476
+ "parameters": {
477
+ "type": "object",
478
+ "properties": {
479
+ "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"]},
483
+ "symbol": {"type": "string", "description": "Declaration to replace when mode='symbol'"},
484
+ },
485
+ "required": ["path", "replacement", "expectedVersion"],
486
+ },
487
+ },
488
+ },
287
489
  {
288
490
  "type": "function",
289
491
  "function": {
@@ -317,17 +519,84 @@ OUMV_TOOLS: List[Dict[str, Any]] = BASE_TOOLS + [
317
519
  ]
318
520
 
319
521
 
522
+ # The product's tool names -> the arm's stable aliases (the prompts use these).
523
+ TOKENSAFE_ALIASES = {
524
+ "smart_read_file": "ts_smart_read_file",
525
+ "scoped_search": "ts_scoped_search",
526
+ "apply_edits": "ts_apply_edits",
527
+ "repo_map": "ts_repo_map",
528
+ "session_context": "ts_session_context",
529
+ "run_helper": "ts_run_helper",
530
+ }
531
+
532
+
533
+ def build_arm(ws: GoWorkspace, arm: str) -> Tuple[str, List[Dict[str, Any]], Dict[str, Any]]:
534
+ """What one arm sees: prompt, tool schemas and dispatcher, decided in one place.
535
+
536
+ For the `tokensafe` arm the schemas come from the server's own `tools/list` (falling
537
+ back to the hand-written aliases only when the CLI is missing), so the measured arm
538
+ pays the schema cost a real session pays.
539
+ """
540
+ if arm == "tokensafe":
541
+ live = ws.tokensafe_tool_schemas()
542
+ tools = BASE_TOOLS + (live if live else TOKENSAFE_TOOLS[len(BASE_TOOLS):])
543
+ dispatcher: Dict[str, Any] = {
544
+ "list_files": ws.list_files,
545
+ "read_file": ws.read_file,
546
+ "write_file": ws.write_file,
547
+ "search_files": ws.search_files,
548
+ "run_command": ws.run_command,
549
+ }
550
+ reverse = {alias: real for real, alias in TOKENSAFE_ALIASES.items()}
551
+ for tool in tools[len(BASE_TOOLS):]:
552
+ alias = tool["function"]["name"]
553
+ real = reverse.get(alias, alias)
554
+ dispatcher[alias] = (lambda r: lambda **kwargs: ws.tokensafe(r, kwargs))(real)
555
+ return SYSTEM_TOKENSAFE, tools, dispatcher
556
+ if arm == "oumv":
557
+ return SYSTEM_OUMV, OUMV_TOOLS, registry(ws, arm)
558
+ return SYSTEM_BASELINE, BASE_TOOLS, registry(ws, arm)
559
+
560
+
320
561
  def registry(ws: GoWorkspace, arm: str) -> Dict[str, Any]:
321
562
  tools: Dict[str, Any] = {
322
563
  "list_files": ws.list_files,
323
564
  "read_file": ws.read_file,
324
565
  "write_file": ws.write_file,
566
+ "search_files": ws.search_files,
325
567
  "run_command": ws.run_command,
326
568
  }
569
+ if arm == "tokensafe":
570
+ tools.update({
571
+ "ts_smart_read_file": lambda path, symbol="": ws.tokensafe(
572
+ "smart_read_file", {"path": path, **({"symbol": symbol} if symbol else {})}
573
+ ),
574
+ "ts_scoped_search": lambda query, path=".": ws.tokensafe(
575
+ "scoped_search", {"query": query, "path": path, "max_results": 20}
576
+ ),
577
+ "ts_apply_edits": lambda path, edits, verify="": ws.tokensafe(
578
+ "apply_edits",
579
+ {
580
+ "edits": [{"path": path, "hunks": edits}],
581
+ **({"verify": verify} if verify else {}),
582
+ },
583
+ ),
584
+ "ts_repo_map": lambda view="graph": ws.tokensafe("repo_map", {"view": view, "project_path": "."}),
585
+ })
327
586
  if arm == "oumv":
328
587
  tools.update({
329
588
  "oumv_observe": lambda level, target="": ws.oumv("oumv/observe", {"level": level, "target": target}),
330
589
  "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
+ },
599
+ ),
331
600
  "oumv_verify": lambda target, payload=None: ws.oumv(
332
601
  "oumv/verify", {"target": target, "action": "probe", "payload": payload}
333
602
  ),
@@ -337,24 +606,41 @@ def registry(ws: GoWorkspace, arm: str) -> Dict[str, Any]:
337
606
 
338
607
 
339
608
  SYSTEM_BASELINE = (
340
- "You are a senior Go engineer working in a small Go module. Use list_files/read_file to inspect code, "
341
- "write_file to fix it, and run_command to verify. Tests and the oracle are read-only. "
342
- "Make the smallest correct change; stop as soon as the oracle passes."
609
+ "You are a senior Go engineer working in a small Go module. Use search_files to locate code, "
610
+ "read_file to inspect it, write_file to fix it, and run_command to verify. Tests and the oracle are "
611
+ "read-only. Make the smallest correct change; stop as soon as the oracle passes."
612
+ )
613
+ SYSTEM_TOKENSAFE = (
614
+ "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) ts_scoped_search on the status code or error "
616
+ "text from the repro → file:line hits; (2) ts_smart_read_file(path, symbol=<identifier or "
617
+ "endpoint from the hit>) → the enclosing body or a window, with line numbers; "
618
+ "(3) ts_apply_edits with edits=[{path, hunks:[{target: exact snippet, replacement: fix, "
619
+ 'start_line: the L from (2)}]}] plus verify="auto" → edit and verdict in one call; '
620
+ "(4) if verify fails, fix the reported line and repeat (2)-(3). "
621
+ "Skip ts_repo_map when the repro names the endpoint. Prefer these over list_files/read_file; "
622
+ "never rewrite a whole file."
343
623
  )
624
+
344
625
  SYSTEM_OUMV = (
345
626
  "You are a senior Go engineer working in a small Go module that exposes the OUMV runtime. "
346
- "Prefer the OUMV tools before reading whole files: oumv_observe L1 lists endpoints, L2 gives an endpoint "
347
- "contract, oumv_getSource returns source with an OCC version token, oumv_verify dispatches a request "
348
- "in-process, oumv_understand gives impact analysis. Fix the code with write_file, confirm with "
349
- "oumv_verify or run_command, and stop as soon as the oracle passes. Tests are read-only."
627
+ "The bug report includes a repro; use it to go straight to the right handler instead of guessing payloads. "
628
+ "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\") — it returns the handler body, its workspace path and the sha256 OCC version; "
630
+ "(2) oumv_getSource for that path once to get the full file bytes; (3) oumv_applyEdit with the fixed file and "
631
+ "the version from step 1 or 2 (it rejects a stale version); (4) confirm with oumv_verify when the repro is a "
632
+ "single request. When the failure needs state created by earlier requests, run the oracle with run_command "
633
+ "instead — oumv_verify intentionally starts a fresh app per call. Do not call list_files/read_file unless an "
634
+ "OUMV tool returns an error. Tests are read-only."
350
635
  )
351
636
 
352
637
 
353
638
  def task_prompt(task_id: str) -> str:
354
- symptom = TASKS[task_id]["symptom"]
639
+ task = TASKS[task_id]
355
640
  return (
356
- f"The order API has a regression: {symptom}\n"
357
- "Reproduce it, find the cause, and fix the handler code. "
641
+ f"The order API has a regression: {task['symptom']}\n"
642
+ f"Repro: {task['repro']}\n"
643
+ "Find the cause and fix the handler code. "
358
644
  "Verification: `go test ./benchmark -run TestGroundTruthOracleVanilla -count=1` must pass all 12 assertions. "
359
645
  "Do not modify tests, the oracle, or the database package."
360
646
  )
@@ -0,0 +1,214 @@
1
+ """Deterministic protocol-mechanics measurements (no provider calls).
2
+
3
+ The agent matrix measures what a model chooses to do. These numbers measure the
4
+ runtime itself, so a reader can separate "the protocol is cheap" from "the model
5
+ happened to take few steps":
6
+
7
+ * discovery payload — observe L2 vs the same fact obtained by search + read;
8
+ * slicing — full-file getSource vs one-symbol getSource;
9
+ * verification — one in-process probe vs one oracle/test-suite run;
10
+ * safety — a stale OCC version and a broken edit are rejected.
11
+
12
+ Everything runs against a throwaway copy of the benchmark sandbox, so the numbers
13
+ are reproducible on a laptop without an API key.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import statistics
20
+ import time
21
+ from pathlib import Path
22
+ from typing import Any, Dict, List, Optional
23
+
24
+ from src.bench import go_target, react_target
25
+
26
+
27
+ def _ms(fn, repeats: int) -> Dict[str, float]:
28
+ samples: List[float] = []
29
+ for _ in range(repeats):
30
+ started = time.perf_counter()
31
+ fn()
32
+ samples.append((time.perf_counter() - started) * 1000)
33
+ return {
34
+ "median_ms": round(statistics.median(samples), 2),
35
+ "min_ms": round(min(samples), 2),
36
+ "max_ms": round(max(samples), 2),
37
+ "samples": repeats,
38
+ }
39
+
40
+
41
+ def _chars(payload: Any) -> int:
42
+ return len(json.dumps(payload, ensure_ascii=False))
43
+
44
+
45
+ def measure_go(task_id: str = "product-create-status", repeats: int = 15) -> Dict[str, Any]:
46
+ ws = go_target.GoWorkspace(task_id)
47
+ probe = {"target": "POST /api/products", "action": "probe", "payload": {"title": "probe", "price": 1}}
48
+ source_path = go_target.SANDBOX_FILE
49
+ try:
50
+ ws.oumv("oumv/verify", probe) # warm the helper and the Go build cache
51
+ full = ws.oumv("oumv/getSource", {"path": source_path})
52
+ sliced = ws.oumv("oumv/getSource", {"path": source_path, "symbol": "NewVanillaApp"})
53
+ l2 = ws.oumv("oumv/observe", {"level": "L2", "target": "POST /api/products"})
54
+ l3 = ws.oumv("oumv/observe", {"level": "L3", "target": "POST /api/products"})
55
+ hits = ws.search_files("StatusOK")
56
+ hit_line = 0
57
+ if hits.get("hits"):
58
+ hit_line = int(hits["hits"][0].split(":")[1])
59
+ window = ws.read_file(source_path, max(1, hit_line - 10), hit_line + 40)
60
+
61
+ # A stale version must be rejected before anything is written.
62
+ stale = ws.oumv(
63
+ "oumv/applyEdit",
64
+ {
65
+ "path": source_path,
66
+ "replacement": full.get("source") or "",
67
+ "expectedVersion": "sha256:" + "0" * 64,
68
+ },
69
+ )
70
+ # A syntactically broken replacement must be rejected by the pre-flight.
71
+ broken = ws.oumv(
72
+ "oumv/applyEdit",
73
+ {
74
+ "path": source_path,
75
+ "replacement": "package vanilla_gin\nfunc broken( {\n",
76
+ "expectedVersion": full.get("version") or "",
77
+ },
78
+ )
79
+
80
+ verify = _ms(lambda: ws.oumv("oumv/verify", probe), repeats)
81
+ verify_sample = ws.oumv("oumv/verify", probe)
82
+ test_run = _ms(
83
+ lambda: ws.run_command("go test ./benchmark -run TestGroundTruthOracleVanilla -count=1"),
84
+ 3,
85
+ )
86
+ return {
87
+ "target": "go",
88
+ "task": task_id,
89
+ "discovery": {
90
+ "oumv_l2_chars": _chars(l2),
91
+ "oumv_l3_chars": _chars(l3),
92
+ "oumv_handler_chars": len(str((l3.get("data") or {}).get("source") or "")),
93
+ "baseline_search_chars": _chars(hits),
94
+ "baseline_read_window_chars": _chars(window),
95
+ "baseline_total_chars": _chars(hits) + _chars(window),
96
+ },
97
+ "slicing": {
98
+ "full_file_chars": _chars(full),
99
+ "symbol_chars": _chars(sliced),
100
+ "symbol": sliced.get("symbol"),
101
+ "start_line": sliced.get("startLine"),
102
+ "end_line": sliced.get("endLine"),
103
+ },
104
+ "verification": {
105
+ "oumv_verify_end_to_end": verify,
106
+ "oumv_verify_reported_in_process_ms": verify_sample.get("durationMs"),
107
+ "oracle_run": test_run,
108
+ "speedup": round(test_run["median_ms"] / verify["median_ms"], 1) if verify["median_ms"] else None,
109
+ },
110
+ "safety": {
111
+ "stale_version_rejected": bool((stale.get("error") or {}).get("code") == -32001),
112
+ "broken_edit_rejected": bool((broken.get("error") or {}).get("code") == -32002),
113
+ "stale_error": (stale.get("error") or {}).get("code"),
114
+ "broken_error": (broken.get("error") or {}).get("code"),
115
+ },
116
+ }
117
+ finally:
118
+ ws.cleanup()
119
+
120
+
121
+ def measure_react(task_id: str = "search-filter", repeats: int = 15) -> Dict[str, Any]:
122
+ ws = react_target.ReactWorkspace(task_id)
123
+ store = "sandboxes/react-task-manager/src/store.ts"
124
+ try:
125
+ full = ws.oumv("oumv/getSource", {"path": store})
126
+ sliced = ws.oumv("oumv/getSource", {"path": store, "symbol": "selectFilteredTasks"})
127
+ l1 = ws.oumv("oumv/observe", {"level": "L1"})
128
+ hits = ws.search_files("searchQuery")
129
+ hit_line = 0
130
+ if hits.get("hits"):
131
+ hit_line = int(hits["hits"][0].split(":")[1].split(":")[0]) if ":" in hits["hits"][0] else 0
132
+ window = ws.read_file(store, max(1, hit_line - 10), hit_line + 40)
133
+ stale = ws.oumv(
134
+ "oumv/applyEdit",
135
+ {"path": store, "replacement": full.get("source") or "", "expectedVersion": "sha256:" + "0" * 64},
136
+ )
137
+ oracle = _ms(lambda: ws.run_command("npx tsx src/bin/oracle-runner.ts"), 3)
138
+ read = _ms(lambda: ws.oumv("oumv/getSource", {"path": store, "symbol": "selectFilteredTasks"}), repeats)
139
+ return {
140
+ "target": "react",
141
+ "task": task_id,
142
+ "discovery": {
143
+ "oumv_l1_chars": _chars(l1),
144
+ "baseline_search_chars": _chars(hits),
145
+ "baseline_read_window_chars": _chars(window),
146
+ "baseline_total_chars": _chars(hits) + _chars(window),
147
+ },
148
+ "slicing": {
149
+ "full_file_chars": _chars(full),
150
+ "symbol_chars": _chars(sliced),
151
+ "symbol": sliced.get("symbol"),
152
+ "start_line": sliced.get("startLine"),
153
+ "end_line": sliced.get("endLine"),
154
+ },
155
+ "verification": {
156
+ "oumv_get_source": read,
157
+ "oracle_run": oracle,
158
+ "speedup": round(oracle["median_ms"] / read["median_ms"], 1) if read["median_ms"] else None,
159
+ },
160
+ "safety": {
161
+ "stale_version_rejected": bool((stale.get("error") or {}).get("code") == -32001),
162
+ "stale_error": (stale.get("error") or {}).get("code"),
163
+ },
164
+ }
165
+ finally:
166
+ ws.cleanup()
167
+
168
+
169
+ def render_markdown(results: List[Dict[str, Any]]) -> str:
170
+ lines = ["# OUMV protocol mechanics (deterministic, no model)", ""]
171
+ for row in results:
172
+ lines += [f"## {row['target']} (`{row['task']}`)", ""]
173
+ discovery = row["discovery"]
174
+ slicing = row["slicing"]
175
+ lines += [
176
+ "| Measurement | Value |",
177
+ "| :--- | ---: |",
178
+ f"| OUMV observe payload | {discovery.get('oumv_l3_chars') or discovery.get('oumv_l2_chars') or discovery.get('oumv_l1_chars')} chars |",
179
+ *(
180
+ [f"| …of which the handler body | {discovery['oumv_handler_chars']} chars |"]
181
+ if discovery.get("oumv_handler_chars")
182
+ else []
183
+ ),
184
+ f"| Baseline search + read window | {discovery['baseline_total_chars']} chars |",
185
+ f"| `getSource` full file | {slicing['full_file_chars']} chars |",
186
+ f"| `getSource` one symbol | {slicing['symbol_chars']} chars |",
187
+ "",
188
+ ]
189
+ verification = row["verification"]
190
+ timing_label = (
191
+ "OUMV probe (end-to-end, one process)"
192
+ if verification.get("oumv_verify_end_to_end")
193
+ else "getSource, one symbol (end-to-end)"
194
+ )
195
+ timing_value = verification.get("oumv_verify_end_to_end") or verification.get("oumv_get_source") or {}
196
+ lines += [
197
+ "| Verification | Median |",
198
+ "| :--- | ---: |",
199
+ f"| {timing_label} | {timing_value.get('median_ms')} ms |",
200
+ f"| Oracle / test suite run | {verification['oracle_run']['median_ms']} ms |",
201
+ "",
202
+ ]
203
+ safety = row["safety"]
204
+ lines += [
205
+ f"Safety: stale `expectedVersion` rejected: **{safety['stale_version_rejected']}**"
206
+ + (f"; broken edit rejected: **{safety['broken_edit_rejected']}**" if "broken_edit_rejected" in safety else "")
207
+ + ".",
208
+ "",
209
+ ]
210
+ return "\n".join(lines)
211
+
212
+
213
+ def run(repeats: int = 15) -> List[Dict[str, Any]]:
214
+ return [measure_go(repeats=repeats), measure_react(repeats=repeats)]