tokensafe 4.15.1 → 4.16.0

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.
@@ -28,6 +28,8 @@ import glob
28
28
  import hashlib
29
29
  import json
30
30
  import os
31
+
32
+ from src import angular_cli
31
33
  import re
32
34
  import shutil
33
35
  import subprocess
@@ -1937,12 +1939,12 @@ _SIDECARS = {
1937
1939
  "spring": (
1938
1940
  "java/src/dev/tokensafe/oumv/OumvSpring.java",
1939
1941
  "OumvSpring.java",
1940
- "edcb33b5c250ef6a087f20efe4fd9ebd8519f03e2f6f2f8484ff26835cf06694",
1942
+ "6d99e1165b62a8053dcb3ae08bebeb5f6dd7d092e9b39eb98deaf596afd3c4e7",
1941
1943
  ),
1942
1944
  "php": (
1943
1945
  "php/bin/oumv-php",
1944
1946
  "oumv-php",
1945
- "ed61eabc1cd92b775a014a380f393922a3046a476ef9ed24d63a083623efefb2",
1947
+ "a075372d575c394d42134b5af62f0f228c271a1ce95984bf4dae9811808945fd",
1946
1948
  ),
1947
1949
  }
1948
1950
 
@@ -2191,6 +2193,27 @@ def plan(workspace: str) -> Dict[str, Any]:
2191
2193
  }
2192
2194
  actions.append(action)
2193
2195
  continue
2196
+ if framework in ("angular", "angular-cli"):
2197
+ app_root = _app_root(workspace, root)
2198
+ angular_state = angular_cli.patch_state(app_root)
2199
+ if angular_state.get("projects"):
2200
+ actions.append({
2201
+ "kind": "angular_cli_builder",
2202
+ "profile": "frontend",
2203
+ "app": root,
2204
+ "framework": "angular",
2205
+ "writes_repo": True,
2206
+ "already_patched": angular_state["patched"],
2207
+ "projects": angular_state["projects"],
2208
+ "installed": angular_state.get("installed"),
2209
+ "install": angular_cli.INSTALL_COMMAND,
2210
+ "run": "ng serve",
2211
+ "description": (
2212
+ "points projects.*.architect.serve.builder at "
2213
+ f"{angular_cli.BUILDER_ID}; no source file is touched and --revert restores the previous builder"
2214
+ ),
2215
+ })
2216
+ continue
2194
2217
  if not app["supported"]:
2195
2218
  reason = app["reason"] or f"no OUMV adapter for {framework} yet"
2196
2219
  actions.append({
@@ -2388,6 +2411,16 @@ def apply(workspace: str, dry_run: bool = False, include_go: bool = True) -> Dic
2388
2411
  "app": root,
2389
2412
  **apply_next_patch(workspace, dry_run=dry_run, root=root),
2390
2413
  })
2414
+ elif framework in ("angular", "angular-cli"):
2415
+ app_root = _app_root(workspace, root)
2416
+ if angular_cli.patch_state(app_root).get("projects"):
2417
+ results["actions"].append({
2418
+ "kind": "angular_cli_builder",
2419
+ "profile": "frontend",
2420
+ "app": root,
2421
+ **angular_cli.apply(workspace, app_root, dry_run=dry_run),
2422
+ })
2423
+ continue
2391
2424
  elif not app["supported"]:
2392
2425
  results["actions"].append({
2393
2426
  "kind": "frontend_unsupported",
@@ -2555,4 +2588,5 @@ def revert(workspace: str) -> Dict[str, Any]:
2555
2588
  results[kind] = _revert_manifest(workspace, kind, manifest)
2556
2589
 
2557
2590
  results["config"] = revert_config(workspace)
2591
+ results["angular_cli_builder"] = angular_cli.revert_all(workspace)
2558
2592
  return results
@@ -10,7 +10,7 @@ from __future__ import annotations
10
10
 
11
11
  # Backend tag (`vX.Y.Z`); the Go module resolves against the matching `go/vX.Y.Z`,
12
12
  # which the backend release workflow creates alongside it.
13
- BACKEND_RELEASE_TAG = "v0.21.0"
13
+ BACKEND_RELEASE_TAG = "v0.22.1"
14
14
 
15
15
  # Wire version that tag speaks. Printed in briefs so an agent never mixes a
16
16
  # backend release with an older protocol line.
@@ -38,6 +38,10 @@ from src.format_parsers.ansi import strip_ansi
38
38
 
39
39
  MAX_BATCH_FILES = 50
40
40
  MAX_VERIFY_OUTPUT_CHARS = 4000
41
+ # Payload caps: a single call that re-emits libraries is a rewrite in disguise.
42
+ MAX_REPLACEMENT_CHARS = int(os.environ.get("TOKENSAFE_MAX_REPLACEMENT_CHARS", "200000") or 200000)
43
+ MAX_HUNKS_PER_FILE = int(os.environ.get("TOKENSAFE_MAX_HUNKS_PER_FILE", "200") or 200)
44
+ MAX_BATCH_CHARS = int(os.environ.get("TOKENSAFE_MAX_BATCH_CHARS", "600000") or 600000)
41
45
 
42
46
  _VERIFY_SIMPLE_RUNNERS = frozenset({
43
47
  "pytest", "py.test", "ruff", "mypy", "pyright", "flake8", "tox", "nox",
@@ -482,17 +486,52 @@ def detect_verify_command(base_dir: str, files: Optional[List[str]] = None) -> O
482
486
  return None
483
487
 
484
488
 
489
+ def _normalize_hunk_text(value: Any) -> Any:
490
+ """Accepts a string or an array of lines for a hunk field.
491
+
492
+ Models break JSON mostly by putting raw newlines inside a string: 16
493
+ apply_edits calls in sess_ba3e8135 died as SyntaxError before the request
494
+ ever reached this server. An array of lines removes newline escaping from
495
+ the payload; everything downstream keeps seeing one string.
496
+ """
497
+ if isinstance(value, list):
498
+ return "\n".join(str(part) for part in value)
499
+ return value
500
+
501
+
502
+ def _normalize_hunks(edits: List[Any]) -> None:
503
+ """In-place: joins array-form target/replacement into strings."""
504
+ for edit in edits:
505
+ if not isinstance(edit, dict):
506
+ continue
507
+ hunks = edit.get("hunks")
508
+ if not isinstance(hunks, list):
509
+ continue
510
+ for hunk in hunks:
511
+ if not isinstance(hunk, dict):
512
+ continue
513
+ for key in ("target", "replacement"):
514
+ if isinstance(hunk.get(key), list):
515
+ hunk[key] = _normalize_hunk_text(hunk[key])
516
+
517
+
485
518
  def execute_batch_edits(
486
519
  edits: List[Dict[str, Any]],
487
520
  best_effort: bool = False,
488
521
  dry_run: bool = False,
489
522
  verify: Optional[str] = None,
490
- verify_timeout_sec: int = 30,
523
+ verify_timeout_sec: int = 120,
524
+ strict_verify: bool = False,
491
525
  cwd: Optional[str] = None
492
526
  ) -> Dict[str, Any]:
493
527
  """
494
528
  Applies multi-file, multi-hunk edits in memory, writes atomically or best-effort,
495
529
  and optionally executes an inline verify command.
530
+
531
+ `strict_verify` only decides what a failed verify does to the tree: with it, the
532
+ edit is rolled back (the old atomic contract); without it, the edits stay and the
533
+ verdict is reported, because a red suite is information rather than an instruction
534
+ to discard the caller's work.
496
535
  """
497
536
  if not isinstance(edits, list) or not edits:
498
537
  return {
@@ -502,6 +541,9 @@ def execute_batch_edits(
502
541
  "failed_files": []
503
542
  }
504
543
 
544
+ # Array-form hunk text is the JSON-safe envelope, not a second edit language.
545
+ _normalize_hunks(edits)
546
+
505
547
  if len(edits) > MAX_BATCH_FILES:
506
548
  return {
507
549
  "success": False,
@@ -555,6 +597,8 @@ def execute_batch_edits(
555
597
  # Pre-validation & secret check
556
598
  prepared_files: Dict[str, Dict[str, Any]] = {}
557
599
  failed_files: List[Dict[str, Any]] = []
600
+ warnings: List[Dict[str, str]] = []
601
+ total_payload_chars = 0
558
602
 
559
603
  for item in edits:
560
604
  if not isinstance(item, dict):
@@ -603,6 +647,24 @@ def execute_batch_edits(
603
647
  create_content = item.get("create")
604
648
  overwrite = bool(item.get("overwrite"))
605
649
  hunks = item.get("hunks") or []
650
+ item_path = str(item.get("path") or "?")
651
+
652
+ if isinstance(create_content, str) and len(create_content) > MAX_REPLACEMENT_CHARS:
653
+ failed_files.append({
654
+ "path": item_path,
655
+ "error": f"'create' content is {len(create_content):,} chars (cap {MAX_REPLACEMENT_CHARS:,}). Send hunks or split the file.",
656
+ })
657
+ continue
658
+ if isinstance(hunks, list) and len(hunks) > MAX_HUNKS_PER_FILE:
659
+ failed_files.append({
660
+ "path": item_path,
661
+ "error": f"{len(hunks)} hunks in one file (cap {MAX_HUNKS_PER_FILE}). Split into smaller calls.",
662
+ })
663
+ continue
664
+ total_payload_chars += (
665
+ len(create_content) if isinstance(create_content, str)
666
+ else sum(len(str(h.get("target") or "")) + len(str(h.get("replacement") or "")) for h in hunks if isinstance(h, dict))
667
+ )
606
668
 
607
669
  if create_content is not None:
608
670
  # Creation mode
@@ -624,6 +686,25 @@ def execute_batch_edits(
624
686
  failed_files.append({"path": rel_path, "error": f"File '{rel_path}' already exists. Set 'overwrite: true' to overwrite."})
625
687
  continue
626
688
 
689
+ if os.path.exists(abs_path) and overwrite and os.environ.get("TOKENSAFE_CREATE_OVERWRITE_GUARD", "1").strip().lower() not in ("0", "false", "no"):
690
+ try:
691
+ with open(abs_path, "rb") as bf:
692
+ existing_text = bf.read().decode("utf-8")
693
+ existing_lines = existing_text.splitlines()
694
+ if len(existing_lines) >= 40:
695
+ ratio = difflib.SequenceMatcher(None, existing_text, create_content).quick_ratio()
696
+ if ratio >= 0.6:
697
+ failed_files.append({
698
+ "path": rel_path,
699
+ "error": (
700
+ f"TokenSafe Output Guard: 'create'+overwrite re-emits ~{ratio:.0%} of "
701
+ f"'{rel_path}' ({len(existing_lines)} lines). Send hunks instead of the whole file."
702
+ ),
703
+ })
704
+ continue
705
+ except (OSError, UnicodeDecodeError):
706
+ pass
707
+
627
708
  prepared_files[abs_path] = {
628
709
  "rel_path": rel_path,
629
710
  "new_content": create_content,
@@ -647,6 +728,8 @@ def execute_batch_edits(
647
728
  prev_noop_count = prior_prepared.get("noop_hunks", 0)
648
729
  prev_clamped_count = prior_prepared.get("clamped_hunks", 0)
649
730
  is_create = prior_prepared["is_create"]
731
+ original_chars = prior_prepared.get("original_chars", len(current_text))
732
+ original_lines = prior_prepared.get("original_lines", len(current_text.splitlines()))
650
733
  else:
651
734
  if not os.path.exists(abs_path):
652
735
  failed_files.append({"path": rel_path, "error": f"File '{rel_path}' does not exist on disk."})
@@ -669,6 +752,8 @@ def execute_batch_edits(
669
752
  prev_noop_count = 0
670
753
  prev_clamped_count = 0
671
754
  is_create = False
755
+ original_chars = len(current_text)
756
+ original_lines = len(current_text.splitlines())
672
757
 
673
758
  file_failed = False
674
759
  applied_hunk_count = 0
@@ -742,6 +827,15 @@ def execute_batch_edits(
742
827
  hunk_clamped = False
743
828
 
744
829
  if not file_failed:
830
+ replacement_chars = sum(len(str(h.get("replacement") or "")) for h in hunks if isinstance(h, dict))
831
+ if original_lines >= 40 and replacement_chars and replacement_chars / max(1, original_chars) >= 0.6:
832
+ warnings.append({
833
+ "path": rel_path,
834
+ "message": (
835
+ f"replacement re-emits ~{replacement_chars / original_chars:.0%} of a "
836
+ f"{original_lines}-line file; hunks this wide cost like a rewrite."
837
+ ),
838
+ })
745
839
  prepared_files[abs_path] = {
746
840
  "rel_path": rel_path,
747
841
  "new_content": current_text,
@@ -749,8 +843,21 @@ def execute_batch_edits(
749
843
  "hunk_count": prev_hunk_count + applied_hunk_count,
750
844
  "noop_hunks": noop_hunk_count,
751
845
  "clamped_hunks": prev_clamped_count + clamped_hunk_count,
846
+ "original_chars": original_chars,
847
+ "original_lines": original_lines,
752
848
  }
753
849
 
850
+ if total_payload_chars > MAX_BATCH_CHARS:
851
+ return {
852
+ "success": False,
853
+ "error": f"Batch payload is {total_payload_chars:,} chars (cap {MAX_BATCH_CHARS:,}); split into smaller calls.",
854
+ "applied_count": 0,
855
+ "applied_files": [],
856
+ "failed_count": len(failed_files),
857
+ "failed_files": failed_files,
858
+ "warnings": warnings,
859
+ }
860
+
754
861
  # Atomic enforcement: if any file failed and not best_effort, reject all
755
862
  if failed_files and not best_effort:
756
863
  return {
@@ -850,15 +957,25 @@ def execute_batch_edits(
850
957
  "changed_hunks": total_changed_hunks,
851
958
  "failed_count": len(failed_files),
852
959
  "failed_files": failed_files,
960
+ "warnings": warnings,
853
961
  "dry_run": dry_run,
854
962
  "rolled_back": rolled_back,
855
963
  }
856
964
 
857
965
  def _rollback_after_verify_failure() -> None:
858
- """Atomic mode means atomic including the verification step: keep the tree consistent."""
966
+ """Report a failed verdict; only `strict_verify` restores the tree."""
859
967
  nonlocal rolled_back
860
968
  if best_effort:
861
969
  return
970
+ if not strict_verify:
971
+ result["edits_kept"] = True
972
+ if isinstance(result.get("verify"), dict):
973
+ result["verify"]["rolled_back"] = False
974
+ result["verify"]["hint"] = (
975
+ "Edits kept: a failed verify is a verdict, not a rollback. "
976
+ "Pass strict_verify=true to restore the files on failure."
977
+ )
978
+ return
862
979
  _restore_backups()
863
980
  rolled_back = True
864
981
  result["rolled_back"] = True
@@ -40,18 +40,35 @@ def resolve_api_key() -> str:
40
40
  return ""
41
41
 
42
42
 
43
+ def _usage_snapshot(payload: Optional[Dict[str, Any]]) -> Dict[str, int]:
44
+ """Normalizes one provider `usage` payload (reasoning tokens included
45
+ when the provider reports them under completion_tokens_details)."""
46
+ payload = payload or {}
47
+ details = payload.get("completion_tokens_details")
48
+ reasoning = int(details.get("reasoning_tokens") or 0) if isinstance(details, dict) else 0
49
+ return {
50
+ "input_tokens": int(payload.get("prompt_tokens") or 0),
51
+ "cache_hit_tokens": int(payload.get("prompt_cache_hit_tokens") or 0),
52
+ "output_tokens": int(payload.get("completion_tokens") or 0),
53
+ "reasoning_tokens": reasoning,
54
+ }
55
+
56
+
43
57
  @dataclass
44
58
  class Usage:
45
59
  input_tokens: int = 0
46
60
  cache_hit_tokens: int = 0
47
61
  output_tokens: int = 0
62
+ reasoning_tokens: int = 0
48
63
  calls: int = 0
49
64
 
50
65
  def add(self, payload: Dict[str, Any]) -> None:
66
+ snap = _usage_snapshot(payload)
51
67
  self.calls += 1
52
- self.input_tokens += int(payload.get("prompt_tokens") or 0)
53
- self.cache_hit_tokens += int(payload.get("prompt_cache_hit_tokens") or 0)
54
- self.output_tokens += int(payload.get("completion_tokens") or 0)
68
+ self.input_tokens += snap["input_tokens"]
69
+ self.cache_hit_tokens += snap["cache_hit_tokens"]
70
+ self.output_tokens += snap["output_tokens"]
71
+ self.reasoning_tokens += snap["reasoning_tokens"]
55
72
 
56
73
  @property
57
74
  def cache_miss_tokens(self) -> int:
@@ -73,6 +90,7 @@ class Usage:
73
90
  "cache_hit_tokens": self.cache_hit_tokens,
74
91
  "cache_miss_tokens": self.cache_miss_tokens,
75
92
  "output_tokens": self.output_tokens,
93
+ "reasoning_tokens": self.reasoning_tokens,
76
94
  "usd": self.usd(model),
77
95
  }
78
96
 
@@ -99,6 +117,10 @@ class DeepSeekClient:
99
117
  self.base_url = (base_url or os.environ.get("DEEPSEEK_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
100
118
  self.timeout = timeout
101
119
  self.retries = max(1, int(retries))
120
+ # A/B knob: hold the reasoning budget constant across arms. Providers
121
+ # that do not understand reasoning_effort ignore it; the artifact records
122
+ # which value was requested so a run is never ambiguous.
123
+ self.reasoning_effort = (os.environ.get("TOKENSAFE_BENCH_REASONING_EFFORT") or "").strip()
102
124
  self.api_key = resolve_api_key()
103
125
  if not self.api_key:
104
126
  raise RuntimeError(
@@ -111,16 +133,31 @@ class DeepSeekClient:
111
133
  # 5s, 15s, 30s: a paid matrix must survive a flaky read, not restart.
112
134
  return min(30.0, 5.0 * (3 ** (attempt - 1)))
113
135
 
114
- def chat(self, messages: List[Dict[str, Any]], tools: Optional[List[Dict[str, Any]]] = None) -> Tuple[Dict[str, Any], Dict[str, Any]]:
136
+ def build_body(
137
+ self, messages: List[Dict[str, Any]], tools: Optional[List[Dict[str, Any]]] = None
138
+ ) -> Dict[str, Any]:
139
+ """Request body shared by chat() and tests, so effort/max_tokens knobs
140
+ are verifiable without a network call."""
115
141
  body: Dict[str, Any] = {
116
142
  "model": self.model,
117
143
  "messages": messages,
118
144
  "temperature": self.temperature,
119
145
  }
146
+ if self.reasoning_effort:
147
+ body["reasoning_effort"] = self.reasoning_effort
148
+ max_tokens = os.environ.get("TOKENSAFE_BENCH_MAX_TOKENS", "").strip()
149
+ if max_tokens:
150
+ try:
151
+ body["max_tokens"] = int(max_tokens)
152
+ except ValueError:
153
+ pass
120
154
  if tools:
121
155
  body["tools"] = tools
122
156
  body["tool_choice"] = "auto"
123
- data = json.dumps(body).encode()
157
+ return body
158
+
159
+ def chat(self, messages: List[Dict[str, Any]], tools: Optional[List[Dict[str, Any]]] = None) -> Tuple[Dict[str, Any], Dict[str, Any]]:
160
+ data = json.dumps(self.build_body(messages, tools)).encode()
124
161
  last_error = ""
125
162
  for attempt in range(1, self.retries + 1):
126
163
  req = urllib.request.Request(
@@ -192,6 +229,7 @@ class StepRecord:
192
229
  tool_args: List[str] = field(default_factory=list)
193
230
  error_codes: List[Optional[str]] = field(default_factory=list)
194
231
  duration_ms: float = 0.0
232
+ usage: Dict[str, int] = field(default_factory=dict)
195
233
  oracle_passed: Optional[int] = None
196
234
  oracle_failed: List[str] = field(default_factory=list)
197
235
  note: str = ""
@@ -220,13 +258,20 @@ def run_agent(
220
258
  stop_reason = "step_limit"
221
259
 
222
260
  for index in range(1, max_steps + 1):
261
+ started = time.perf_counter()
223
262
  message, raw_usage = client.chat(messages, tools)
263
+ elapsed_ms = (time.perf_counter() - started) * 1000.0
224
264
  usage.add(raw_usage)
225
265
 
226
266
  calls = message.get("tool_calls") or []
227
267
  messages.append(message)
228
268
 
229
- record = StepRecord(index=index, tool_calls=[c["function"]["name"] for c in calls])
269
+ record = StepRecord(
270
+ index=index,
271
+ tool_calls=[c["function"]["name"] for c in calls],
272
+ duration_ms=round(elapsed_ms, 1),
273
+ usage=_usage_snapshot(raw_usage),
274
+ )
230
275
  if not calls:
231
276
  stop_reason = "agent_finished"
232
277
  steps.append(record)
@@ -277,6 +322,7 @@ def run_agent(
277
322
  return {
278
323
  "model": client.model,
279
324
  "temperature": client.temperature,
325
+ "reasoning_effort": getattr(client, "reasoning_effort", ""),
280
326
  "price_snapshot": PRICE_SNAPSHOT,
281
327
  "prices_usd_per_mtok": PRICES.get(client.model),
282
328
  "stop_reason": stop_reason,
@@ -290,6 +336,8 @@ def run_agent(
290
336
  "result_chars": s.result_chars,
291
337
  "tool_args": s.tool_args,
292
338
  "error_codes": s.error_codes,
339
+ "duration_ms": s.duration_ms,
340
+ "usage": s.usage,
293
341
  "oracle_passed": s.oracle_passed,
294
342
  "oracle_failed": s.oracle_failed,
295
343
  "note": s.note,
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import json
6
+ import os
6
7
  import tempfile
7
8
  import time
8
9
  from pathlib import Path
@@ -81,6 +82,8 @@ def _matrix_report(
81
82
  "arms": arms,
82
83
  "runs": runs,
83
84
  "model": model,
85
+ "reasoning_effort": (os.environ.get("TOKENSAFE_BENCH_REASONING_EFFORT") or "").strip() or None,
86
+ "max_tokens": (os.environ.get("TOKENSAFE_BENCH_MAX_TOKENS") or "").strip() or None,
84
87
  "budget_usd": budget_usd,
85
88
  "spent_usd": round(spent, 6),
86
89
  "aborted": aborted,
@@ -228,6 +231,8 @@ def run_react_matrix(
228
231
  "arms": arms,
229
232
  "runs": runs,
230
233
  "model": model,
234
+ "reasoning_effort": (os.environ.get("TOKENSAFE_BENCH_REASONING_EFFORT") or "").strip() or None,
235
+ "max_tokens": (os.environ.get("TOKENSAFE_BENCH_MAX_TOKENS") or "").strip() or None,
231
236
  "budget_usd": budget_usd,
232
237
  "spent_usd": round(spent, 6),
233
238
  "aborted": aborted,
@@ -279,13 +284,22 @@ def summarize(report: Dict[str, Any]) -> List[Dict[str, Any]]:
279
284
  key = result["arm"]
280
285
  row = rows.setdefault(
281
286
  key,
282
- {"arm": key, "runs": 0, "solved": 0, "input": 0, "output": 0, "usd": 0.0, "steps": 0, "seconds": 0.0},
287
+ {"arm": key, "runs": 0, "solved": 0, "input": 0, "output": 0, "usd": 0.0, "steps": 0, "seconds": 0.0,
288
+ "calls": 0, "reasoning": 0, "output_solved": 0, "reasoning_solved": 0,
289
+ "reasoning_reported": False},
283
290
  )
284
291
  row["runs"] += 1
285
292
  row["solved"] += 1 if result.get("solved") else 0
286
293
  usage = result.get("usage") or {}
287
294
  row["input"] += int(usage.get("input_tokens") or 0)
288
295
  row["output"] += int(usage.get("output_tokens") or 0)
296
+ row["calls"] += int(usage.get("calls") or 0)
297
+ if "reasoning_tokens" in usage:
298
+ row["reasoning_reported"] = True
299
+ row["reasoning"] += int(usage.get("reasoning_tokens") or 0)
300
+ if result.get("solved"):
301
+ row["output_solved"] += int(usage.get("output_tokens") or 0)
302
+ row["reasoning_solved"] += int(usage.get("reasoning_tokens") or 0)
289
303
  row["usd"] += float(usage.get("usd") or 0.0)
290
304
  row["steps"] += len(result.get("steps") or [])
291
305
  row["seconds"] += float(result.get("wall_clock_s") or 0.0)
@@ -294,6 +308,25 @@ def summarize(report: Dict[str, Any]) -> List[Dict[str, Any]]:
294
308
  row["mean_seconds"] = round(row["seconds"] / row["runs"], 1) if row["runs"] else 0.0
295
309
  row["mean_input"] = round(row["input"] / row["runs"]) if row["runs"] else 0
296
310
  row["mean_output"] = round(row["output"] / row["runs"]) if row["runs"] else 0
311
+ row["output_per_call"] = round(row["output"] / row["calls"], 1) if row["calls"] else 0.0
312
+ row["output_per_solved"] = (
313
+ round(row["output_solved"] / row["solved"], 1) if row["solved"] else 0.0
314
+ )
315
+ if row["reasoning_reported"]:
316
+ row["reasoning_per_solved"] = (
317
+ round(row["reasoning_solved"] / row["solved"], 1) if row["solved"] else 0.0
318
+ )
319
+ row["reasoning_per_call"] = (
320
+ round(row["reasoning"] / row["calls"], 1) if row["calls"] else 0.0
321
+ )
322
+ row["reasoning_share_pct"] = (
323
+ round(row["reasoning"] / row["output"] * 100.0, 1) if row["output"] else 0.0
324
+ )
325
+ else:
326
+ # Older artifacts did not record reasoning_tokens: unknown is not zero.
327
+ row["reasoning_per_solved"] = None
328
+ row["reasoning_per_call"] = None
329
+ row["reasoning_share_pct"] = None
297
330
  return sorted(rows.values(), key=lambda r: r["arm"])
298
331
 
299
332
 
@@ -311,10 +344,24 @@ def render_markdown(report: Dict[str, Any]) -> str:
311
344
  + (f", plus {files} generated service files so discovery competes with a realistic tree" if files else "")
312
345
  + "."
313
346
  )
347
+ arms = report.get("arms") or []
348
+ arm_bits = ["`baseline` uses file/command tools only"]
349
+ if "tokensafe" in arms:
350
+ arm_bits.append(
351
+ "`tokensafe` adds the shipped MCP tools (`smart_read_file` with `endpoint=`, "
352
+ "`scoped_search`, `apply_edits` with inline verify)"
353
+ )
354
+ if "oumv" in arms:
355
+ arm_bits.append(
356
+ "`oumv` adds observe L3 (endpoint → handler source + version) and `applyEdit` "
357
+ "`mode=patch` (hunks) served by the shipped OUMV adapter"
358
+ )
359
+ methodology_line = "; ".join(arm_bits) + "."
314
360
  lines = [
315
361
  f"# OUMV benchmark — {target} sandbox (measured)",
316
362
  "",
317
- f"> Model: `{report['model']}` · runs: {report['runs']} · budget: ${report['budget_usd']} · "
363
+ f"> Model: `{report['model']}` · reasoning: `{report.get('reasoning_effort') or 'default'}` · "
364
+ f"runs: {report['runs']} · budget: ${report['budget_usd']} · "
318
365
  f"spent: ${report['spent_usd']} · {report['generated_at']}",
319
366
  "",
320
367
  "## Methodology",
@@ -322,19 +369,22 @@ def render_markdown(report: Dict[str, Any]) -> str:
322
369
  sandbox_line,
323
370
  f"- Correctness is {oracle}, re-run after every agent step.",
324
371
  "- Token and cost numbers come from the provider `usage` payload; prices are a pinned snapshot printed in the JSON artifact.",
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.",
372
+ f"- {methodology_line}",
328
373
  "",
329
374
  "## Results",
330
375
  "",
331
- "| Arm | Runs | Solved | Mean steps | Mean wall clock | Mean input tokens | Mean output tokens | Cost |",
332
- "| :--- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |",
376
+ "| Arm | Runs | Solved | Mean steps | Mean wall clock | Mean input tokens | Mean output tokens | Output / call | Output / solved | Reasoning / call | Cost |",
377
+ "| :--- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |",
333
378
  ]
334
379
  for row in summarize(report):
380
+ reasoning_cell = (
381
+ f"{row['reasoning_per_call']:,}" if row["reasoning_per_call"] is not None else "—"
382
+ )
335
383
  lines.append(
336
384
  f"| `{row['arm']}` | {row['runs']} | {row['solved']}/{row['runs']} | {row['mean_steps']} | "
337
- f"{row['mean_seconds']}s | {row['mean_input']:,} | {row['mean_output']:,} | ${row['usd']:.4f} |"
385
+ f"{row['mean_seconds']}s | {row['mean_input']:,} | {row['mean_output']:,} | "
386
+ f"{row['output_per_call']:,} | {row['output_per_solved']:,} | "
387
+ f"{reasoning_cell} | ${row['usd']:.4f} |"
338
388
  )
339
389
  if report.get("aborted"):
340
390
  lines += ["", f"> Stopped early: {report['aborted']}"]
@@ -41,10 +41,16 @@ _WEBPACK_FILE_SIZES_RE = re.compile(r"File\s+sizes\s+after\s+gzip:", re.IGNORECA
41
41
  _CARGO_FINISHED_RE = re.compile(r"Finished\s+(release|dev|bench)\s+\[(.*?)\]\s+target\(s\)\s+in\s+([\d.]+[a-zA-Z]*)", re.IGNORECASE)
42
42
  _CARGO_COMPILING_LINE_RE = re.compile(r"^\s*Compiling\s+(\S+)\s+v(\S+)", re.MULTILINE)
43
43
 
44
+ # Go: failures print `# import/path` followed by `file.go:12:3: message`; a verbose
45
+ # success prints one module path per compiled package and nothing else.
46
+ _GO_PKG_HEADER_RE = re.compile(r"^#\s+[\w.\-]+(?:/[\w.\-]+)+\s*$", re.MULTILINE)
47
+ _GO_PACKAGE_LINE_RE = re.compile(r"^[\w.\-]+(?:/[\w.\-]+)+\s*$")
48
+ _GO_ERROR_RE = re.compile(r"\.go:\d+:\d+:")
49
+
44
50
  _FAILURE_SIGNALS_RE = re.compile(
45
- r"\b(error\s+TS\d+|SyntaxError|Failed\s+to\s+compile|error\s+during\s+build|"
51
+ r"(?:\b(error\s+TS\d+|SyntaxError|Failed\s+to\s+compile|error\s+during\s+build|"
46
52
  r"Rollup\s+failed\s+to\s+resolve|Could\s+not\s+resolve|error\[E\d+\]|"
47
- r"could\s+not\s+compile|UnhandledSchemeError|ModuleNotFoundException)\b",
53
+ r"could\s+not\s+compile|UnhandledSchemeError|ModuleNotFoundException)\b|\.go:\d+:\d+:)",
48
54
  re.IGNORECASE
49
55
  )
50
56
 
@@ -90,6 +96,8 @@ class BuildOutputParser:
90
96
  return "next"
91
97
  if "cargo" in cmd_lower and "build" in cmd_lower:
92
98
  return "cargo"
99
+ if re.search(r"(?:^|[;&|]\s*)go\s+(?:build|vet)\b", cmd_lower):
100
+ return "go"
93
101
 
94
102
  # Check content signatures
95
103
  if _VITE_START_RE.search(raw) or _VITE_BUILT_RE.search(raw) or ("modules transformed" in raw and "dist/" in raw):
@@ -100,6 +108,8 @@ class BuildOutputParser:
100
108
  return "webpack"
101
109
  if _CARGO_FINISHED_RE.search(raw) or ("Compiling " in raw and "Finished " in raw):
102
110
  return "cargo"
111
+ if _GO_ERROR_RE.search(raw) and _GO_PKG_HEADER_RE.search(raw):
112
+ return "go"
103
113
  if "[bun] Built in" in raw:
104
114
  return "bun"
105
115
 
@@ -138,6 +148,8 @@ class BuildOutputParser:
138
148
  return cls._compact_webpack_success(cleaned, raw)
139
149
  elif runner == "cargo":
140
150
  return cls._compact_cargo_success(cleaned, raw)
151
+ elif runner == "go":
152
+ return cls._compact_go_success(cleaned, raw)
141
153
  else:
142
154
  return cls._compact_generic_success(cleaned, raw)
143
155
 
@@ -301,6 +313,27 @@ class BuildOutputParser:
301
313
 
302
314
  return "\n".join(out_lines), True
303
315
 
316
+ @classmethod
317
+ def _compact_go_success(cls, cleaned: str, raw_original: str) -> Tuple[str, bool]:
318
+ """Compacts a successful `go build`/`go vet` run.
319
+
320
+ Plain `go build` is silent on success, so the only compressible case is a
321
+ verbose run that lists one module path per compiled package.
322
+ """
323
+ packages = [ln.strip() for ln in cleaned.splitlines() if _GO_PACKAGE_LINE_RE.match(ln.strip())]
324
+ if packages:
325
+ out_lines = [f"✓ go build succeeded ({len(packages)} packages compiled)"]
326
+ for pkg in packages[:3]:
327
+ out_lines.append(f" • {pkg}")
328
+ if len(packages) > 3:
329
+ out_lines.append(f" ... (+{len(packages) - 3} more packages folded)")
330
+ else:
331
+ out_lines = ["✓ go build succeeded (no output)"]
332
+ if len(cleaned.splitlines()) > 8:
333
+ _, marker = stash_block(raw_original, source="go_build")
334
+ out_lines.append(marker)
335
+ return "\n".join(out_lines), True
336
+
304
337
  @classmethod
305
338
  def _compact_generic_success(cls, cleaned: str, raw_original: str) -> Tuple[str, bool]:
306
339
  """Generic fallback for build commands with long asset/progress outputs."""