usta 0.2.0__py3-none-any.whl

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.
Files changed (156) hide show
  1. usta/__init__.py +0 -0
  2. usta/agent.py +319 -0
  3. usta/api.py +834 -0
  4. usta/apis.py +103 -0
  5. usta/attachments.py +60 -0
  6. usta/audit.py +47 -0
  7. usta/auth.py +55 -0
  8. usta/bench.py +904 -0
  9. usta/bench_tasks/add-feature/check/test_todo.py +37 -0
  10. usta/bench_tasks/add-feature/repo/test_todo.py +11 -0
  11. usta/bench_tasks/add-feature/repo/todo.py +10 -0
  12. usta/bench_tasks/add-feature/task.json +10 -0
  13. usta/bench_tasks/cli-args/check/test_cli.py +44 -0
  14. usta/bench_tasks/cli-args/repo/cli.py +2 -0
  15. usta/bench_tasks/cli-args/task.json +10 -0
  16. usta/bench_tasks/cross-module-bug/check/test_cart.py +19 -0
  17. usta/bench_tasks/cross-module-bug/check/test_pricing.py +12 -0
  18. usta/bench_tasks/cross-module-bug/repo/cart.py +7 -0
  19. usta/bench_tasks/cross-module-bug/repo/pricing.py +5 -0
  20. usta/bench_tasks/cross-module-bug/repo/test_cart.py +8 -0
  21. usta/bench_tasks/cross-module-bug/repo/test_pricing.py +12 -0
  22. usta/bench_tasks/cross-module-bug/task.json +10 -0
  23. usta/bench_tasks/csv-quotes/check/test_parse.py +22 -0
  24. usta/bench_tasks/csv-quotes/repo/parse.py +2 -0
  25. usta/bench_tasks/csv-quotes/task.json +10 -0
  26. usta/bench_tasks/deep-merge/check/test_config.py +31 -0
  27. usta/bench_tasks/deep-merge/repo/config.py +2 -0
  28. usta/bench_tasks/deep-merge/task.json +10 -0
  29. usta/bench_tasks/expr-eval/check/test_calc.py +37 -0
  30. usta/bench_tasks/expr-eval/repo/calc.py +2 -0
  31. usta/bench_tasks/expr-eval/task.json +10 -0
  32. usta/bench_tasks/implement-slugify/check/test_slug.py +19 -0
  33. usta/bench_tasks/implement-slugify/repo/slug.py +2 -0
  34. usta/bench_tasks/implement-slugify/task.json +10 -0
  35. usta/bench_tasks/interval-merge/check/test_intervals.py +30 -0
  36. usta/bench_tasks/interval-merge/repo/intervals.py +2 -0
  37. usta/bench_tasks/interval-merge/task.json +10 -0
  38. usta/bench_tasks/leap-dates/check/test_dates.py +34 -0
  39. usta/bench_tasks/leap-dates/repo/dates.py +15 -0
  40. usta/bench_tasks/leap-dates/repo/test_dates.py +9 -0
  41. usta/bench_tasks/leap-dates/task.json +10 -0
  42. usta/bench_tasks/lru-cache/check/test_lru.py +50 -0
  43. usta/bench_tasks/lru-cache/repo/lru.py +3 -0
  44. usta/bench_tasks/lru-cache/task.json +10 -0
  45. usta/bench_tasks/money-rounding/check/test_money.py +27 -0
  46. usta/bench_tasks/money-rounding/repo/money.py +7 -0
  47. usta/bench_tasks/money-rounding/repo/test_money.py +8 -0
  48. usta/bench_tasks/money-rounding/task.json +10 -0
  49. usta/bench_tasks/multi-file-rename/check/test_users.py +21 -0
  50. usta/bench_tasks/multi-file-rename/repo/api.py +5 -0
  51. usta/bench_tasks/multi-file-rename/repo/greeting.py +5 -0
  52. usta/bench_tasks/multi-file-rename/repo/report.py +5 -0
  53. usta/bench_tasks/multi-file-rename/repo/test_users.py +8 -0
  54. usta/bench_tasks/multi-file-rename/repo/users.py +2 -0
  55. usta/bench_tasks/multi-file-rename/task.json +10 -0
  56. usta/bench_tasks/off-by-one/check/test_stats.py +21 -0
  57. usta/bench_tasks/off-by-one/repo/stats.py +8 -0
  58. usta/bench_tasks/off-by-one/repo/test_stats.py +8 -0
  59. usta/bench_tasks/off-by-one/task.json +10 -0
  60. usta/bench_tasks/text-wrap/check/test_wrap.py +28 -0
  61. usta/bench_tasks/text-wrap/repo/wrap.py +2 -0
  62. usta/bench_tasks/text-wrap/task.json +10 -0
  63. usta/bench_tasks/tiny-case-insensitive/check/test_find.py +17 -0
  64. usta/bench_tasks/tiny-case-insensitive/repo/find.py +3 -0
  65. usta/bench_tasks/tiny-case-insensitive/repo/test_find.py +8 -0
  66. usta/bench_tasks/tiny-case-insensitive/task.json +11 -0
  67. usta/bench_tasks/tiny-default-sep/check/test_words.py +17 -0
  68. usta/bench_tasks/tiny-default-sep/repo/test_words.py +8 -0
  69. usta/bench_tasks/tiny-default-sep/repo/words.py +3 -0
  70. usta/bench_tasks/tiny-default-sep/task.json +11 -0
  71. usta/bench_tasks/tiny-greeting/check/test_greet.py +14 -0
  72. usta/bench_tasks/tiny-greeting/repo/greet.py +3 -0
  73. usta/bench_tasks/tiny-greeting/repo/test_greet.py +8 -0
  74. usta/bench_tasks/tiny-greeting/task.json +11 -0
  75. usta/bench_tasks/tiny-is-even/check/test_parity.py +18 -0
  76. usta/bench_tasks/tiny-is-even/repo/parity.py +5 -0
  77. usta/bench_tasks/tiny-is-even/repo/test_parity.py +9 -0
  78. usta/bench_tasks/tiny-is-even/task.json +11 -0
  79. usta/bench_tasks/tiny-missing-return/check/test_nums.py +19 -0
  80. usta/bench_tasks/tiny-missing-return/repo/nums.py +5 -0
  81. usta/bench_tasks/tiny-missing-return/repo/test_nums.py +8 -0
  82. usta/bench_tasks/tiny-missing-return/task.json +11 -0
  83. usta/bench_tasks/tiny-strip-names/check/test_names.py +17 -0
  84. usta/bench_tasks/tiny-strip-names/repo/names.py +3 -0
  85. usta/bench_tasks/tiny-strip-names/repo/test_names.py +8 -0
  86. usta/bench_tasks/tiny-strip-names/task.json +11 -0
  87. usta/bench_tasks/tiny-swap-args/check/test_pct.py +17 -0
  88. usta/bench_tasks/tiny-swap-args/repo/pct.py +5 -0
  89. usta/bench_tasks/tiny-swap-args/repo/test_pct.py +8 -0
  90. usta/bench_tasks/tiny-swap-args/task.json +11 -0
  91. usta/bench_tasks/tiny-wrong-operator/check/test_avg.py +17 -0
  92. usta/bench_tasks/tiny-wrong-operator/repo/avg.py +5 -0
  93. usta/bench_tasks/tiny-wrong-operator/repo/test_avg.py +8 -0
  94. usta/bench_tasks/tiny-wrong-operator/task.json +11 -0
  95. usta/bench_tasks/word-count-fix/check/test_text.py +25 -0
  96. usta/bench_tasks/word-count-fix/repo/test_text.py +10 -0
  97. usta/bench_tasks/word-count-fix/repo/text.py +5 -0
  98. usta/bench_tasks/word-count-fix/task.json +10 -0
  99. usta/breaker.py +132 -0
  100. usta/capability.py +643 -0
  101. usta/cli.py +1358 -0
  102. usta/context.py +122 -0
  103. usta/fetch.py +406 -0
  104. usta/fetch_inner.py +112 -0
  105. usta/filetree.py +134 -0
  106. usta/jsonproto.py +155 -0
  107. usta/lab/__init__.py +4 -0
  108. usta/lab/env.py +127 -0
  109. usta/lab/evaluator.py +108 -0
  110. usta/lab/metrics.py +109 -0
  111. usta/lab/report.py +124 -0
  112. usta/lab/runner.py +242 -0
  113. usta/lab/scenario.py +266 -0
  114. usta/lab/scenarios/v1.jsonl +25 -0
  115. usta/lab/scripted.py +47 -0
  116. usta/mcp.py +344 -0
  117. usta/mcp_runtime.py +362 -0
  118. usta/mcp_tools.py +162 -0
  119. usta/mcpcatalog.py +39 -0
  120. usta/mcpconfig.py +306 -0
  121. usta/memory.py +218 -0
  122. usta/modelctl.py +124 -0
  123. usta/modelinfo.py +19 -0
  124. usta/models.py +170 -0
  125. usta/outline.py +191 -0
  126. usta/pdf_inner.py +59 -0
  127. usta/phases.py +267 -0
  128. usta/policy.py +104 -0
  129. usta/portal.py +107 -0
  130. usta/profile.py +177 -0
  131. usta/projectcfg.py +90 -0
  132. usta/projects.py +67 -0
  133. usta/proxy.py +302 -0
  134. usta/repl.py +590 -0
  135. usta/rescue.py +66 -0
  136. usta/sandbox.py +359 -0
  137. usta/sessions.py +120 -0
  138. usta/settings.py +93 -0
  139. usta/skills.py +79 -0
  140. usta/symbols.py +618 -0
  141. usta/tasks.py +633 -0
  142. usta/taxonomy.py +169 -0
  143. usta/textproto.py +149 -0
  144. usta/theme.py +104 -0
  145. usta/tools.py +369 -0
  146. usta/verify.py +233 -0
  147. usta/web/app.css +160 -0
  148. usta/web/app.js +1064 -0
  149. usta/web/index.html +197 -0
  150. usta/web/logic.js +175 -0
  151. usta/workspace.py +236 -0
  152. usta-0.2.0.dist-info/METADATA +211 -0
  153. usta-0.2.0.dist-info/RECORD +156 -0
  154. usta-0.2.0.dist-info/WHEEL +4 -0
  155. usta-0.2.0.dist-info/entry_points.txt +2 -0
  156. usta-0.2.0.dist-info/licenses/LICENSE +202 -0
usta/bench.py ADDED
@@ -0,0 +1,904 @@
1
+ """Ölçüm düzeneği: küçük gerçek yazılım görevlerini bir modelle çalıştırıp gizli testle doğrular.
2
+
3
+ Amaç harness değişikliklerinin (araç seti, istem, doğrulama döngüsü, bağlam yönetimi) küçük modellerde
4
+ gerçekten fark yaratıp yaratmadığını sayıyla görmek. Her görev: başlangıç deposu (`repo/`), ajanın
5
+ GÖRMEDİĞİ doğrulama dosyaları (`check/`, bitince çalışma alanına yazılır ve ajanın testleri ezilir) ve
6
+ sandbox'ta çalışan doğrulama komutu. Görevler stdlib `unittest` kullanır (imajda ek paket gerekmez).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import shutil
13
+ import statistics
14
+ import tempfile
15
+ import threading
16
+ import time
17
+ from collections import Counter
18
+ from collections.abc import Callable
19
+ from dataclasses import asdict, dataclass, field, replace
20
+ from pathlib import Path
21
+
22
+ from usta import taxonomy
23
+ from usta.agent import SYSTEM_PROMPT, Agent
24
+ from usta.audit import AuditLog
25
+ from usta.breaker import CircuitBreaker
26
+ from usta.models import ModelClient, ModelError
27
+ from usta.phases import PhaseTracker
28
+ from usta.policy import Policy
29
+ from usta.sandbox import SandboxConfig, SandboxError, run_command
30
+ from usta.tools import ToolContext, build_registry
31
+ from usta.verify import CompletionGate, Verifier
32
+ from usta.verify import env_problem as verify_env_problem
33
+
34
+ TASKS_DIR = Path(__file__).with_name("bench_tasks")
35
+ SPLITS = (
36
+ "train",
37
+ "dev",
38
+ "final",
39
+ ) # eğitim: harness/istem ayarı; geliştirme: ara kontrol; final: yalnız sürüm ölçümü
40
+ TRACE_VERSION = 1
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class Arm:
45
+ """Deney kolu: hangi harness yapılandırmasıyla ölçüldü."""
46
+
47
+ name: str
48
+ description: str
49
+ tools: frozenset[str] | None = None # None: Usta'nın tüm varsayılan araçları
50
+ system_prompt: str | None = None # None: Usta'nın varsayılan sistem istemi
51
+ verify: bool = False # düzenleme geri bildirimi + bitirme kapısı (verify.py)
52
+ breaker: bool = False # devre kesici: döngüde geri sar, denenenleri bildir (breaker.py)
53
+ context_window: int | None = None # verilirse bağlam bütçesi/sıkıştırma etkin (token)
54
+ symbol_tools: bool = False # find_symbol / symbol_context / related_files (usta[symbols])
55
+ max_read: int | None = (
56
+ None # verilirse read_file çıktısı bu karakterle sınırlı (kod okuma bütçesi)
57
+ )
58
+ experimental: bool = (
59
+ False # A-D'nin anlamı değişmez; deneysel yapılandırmalar ayrı etiketle eklenir
60
+ )
61
+
62
+
63
+ MINIMAL_PROMPT = (
64
+ "Bir yazılım görevini çözen ajansın. Tek aracın var: run (çalışma dizininde kabuk komutu çalıştırır). "
65
+ "Dosyaları komutlarla oku ve düzenle, testleri çalıştır. İş bitince kısa bir yanıt yaz."
66
+ )
67
+ SYMBOL_PROMPT = (
68
+ f"{SYSTEM_PROMPT} Koda yaklaşırken önce related_files ile ilgili dosyaları sırala, find_symbol/symbol_context ile "
69
+ "yalnız gereken fonksiyon ve çağıranlarına bak; tüm dosyayı yalnız bu yetmezse oku."
70
+ )
71
+ ARMS: dict[str, Arm] = {
72
+ "A": Arm(
73
+ "A", "minimal ajan: yalnız kabuk aracı, kısa istem", frozenset({"run"}), MINIMAL_PROMPT
74
+ ),
75
+ "B": Arm("B", "mevcut Usta: dosya araçları, varsayılan istem"),
76
+ "C": Arm("C", "Usta + doğrulama: sözdizimi geri bildirimi, bitirme kapısı", verify=True),
77
+ "D": Arm("D", "Usta + doğrulama + devre kesici", verify=True, breaker=True),
78
+ # --- deneysel yapılandırmalar (varsayılan değil; A-D anlamları değişmedi) ---
79
+ "X-BRK": Arm("X-BRK", "Usta + yalnız devre kesici (doğrulama kapısı yok)", breaker=True, experimental=True),
80
+ "X-CTX": Arm(
81
+ "X-CTX", "Usta + bağlam bütçesi (8K pencere, araç çıktısı kırpma, sıkıştırma)",
82
+ context_window=8192, experimental=True,
83
+ ),
84
+ "X-ALL": Arm(
85
+ "X-ALL", "Usta + doğrulama + devre kesici + bağlam bütçesi",
86
+ verify=True, breaker=True, context_window=8192, experimental=True,
87
+ ),
88
+ "X-FULL": Arm(
89
+ "X-FULL", "Usta, yalnız tam dosya okuma (outline/read_symbol yok): seçici bağlamın karşılaştırma tabanı",
90
+ tools=frozenset({"read_file", "write_file", "edit_file", "list_dir", "run", "remember", "fetch_url"}),
91
+ experimental=True,
92
+ ),
93
+ "X-SYM": Arm(
94
+ "X-SYM", "Usta + Tree-sitter sembol araçları (find_symbol/symbol_context/related_files) + 12K okuma bütçesi",
95
+ symbol_tools=True, max_read=12_000, system_prompt=SYMBOL_PROMPT, experimental=True,
96
+ ),
97
+ } # fmt: skip
98
+
99
+
100
+ @dataclass(frozen=True)
101
+ class BenchTask:
102
+ id: str
103
+ prompt: str
104
+ repo: Path
105
+ check: Path
106
+ check_cmd: tuple[str, ...]
107
+ split: str = "dev"
108
+
109
+
110
+ @dataclass(frozen=True)
111
+ class TaskResult:
112
+ task: str
113
+ passed: bool
114
+ steps: int = 0
115
+ tool_calls: int = 0
116
+ tool_errors: int = 0
117
+ denied: int = 0
118
+ seconds: float = 0.0
119
+ truncated: bool = False
120
+ error: str = ""
121
+ check_output: str = ""
122
+ outcome: str = "" # pass | fail | infra (altyapı: görev başarısızlığı sayılmaz)
123
+ attempts: int = 1
124
+ prompt_tokens: int = 0
125
+ completion_tokens: int = 0
126
+ requests: int = 0
127
+ edits: int = 0
128
+ verified: bool = False # son düzenlemeden sonra en az bir `run` çalıştırıldı
129
+ unverified_claim: bool = False # düzenledi, bitti dedi, ama doğrulamadı
130
+ gate: str = "" # bitirme kapısının son durumu: passed | failed | unavailable | ""
131
+ gate_rounds: int = 0 # kapının başarısız saydığı tur sayısı
132
+ breaker_trips: int = 0 # devre kesicinin açıldığı sayı
133
+ blocked: bool = False # devre kesici akışı kesip kullanıcıya bıraktı
134
+ tests_modified: bool = False # depodaki mevcut test dosyalarını değiştirdi/sildi
135
+ failure: str = "" # başarısızlık sınıfı (taxonomy.py); başarılıda boş
136
+ split: str = "" # görev bölümü (train/dev/final)
137
+ terminal: str = "" # yürütme aşamaları terminal durumu (phases.TERMINALS)
138
+ phase_steps: dict = field(default_factory=dict) # aşama -> araç çağrısı sayısı
139
+ phase_transitions: int = 0
140
+ signals: tuple[str, ...] = () # tespit edilen tüm işaretler (birincil neden dışındakiler dahil)
141
+ repair_attempts: int = 0 # ilk testten sonra yapılan düzenleme (onarım) sayısı
142
+ context_peak: int = 0 # en büyük bağlam (girdi token, uç nokta bildirirse)
143
+ compactions: int = 0 # bağlam sıkıştırma sayısı
144
+ trace: str = "" # adım izi dosyası (--trace-dir verilirse)
145
+
146
+ def __post_init__(self) -> None:
147
+ if not self.outcome:
148
+ object.__setattr__(self, "outcome", "pass" if self.passed else "fail")
149
+
150
+
151
+ def load_tasks(root: Path = TASKS_DIR) -> list[BenchTask]:
152
+ tasks = []
153
+ for d in sorted(Path(root).iterdir()):
154
+ spec = d / "task.json"
155
+ if not spec.is_file():
156
+ continue
157
+ data = json.loads(spec.read_text())
158
+ split = data.get("split", "dev")
159
+ if split not in SPLITS:
160
+ raise ValueError(f"{d.name}: bilinmeyen split {split!r}")
161
+ tasks.append(
162
+ BenchTask(
163
+ d.name, data["prompt"], d / "repo", d / "check", tuple(data["check_cmd"]), split
164
+ )
165
+ )
166
+ return tasks
167
+
168
+
169
+ def select_tasks(tasks: list[BenchTask], split: str) -> list[BenchTask]:
170
+ """`dev-all`: eğitim + geliştirme (final hariç, varsayılan); `all`: hepsi; aksi halde tek bölüm."""
171
+ if split == "all":
172
+ return list(tasks)
173
+ if split == "dev-all":
174
+ return [t for t in tasks if t.split in ("train", "dev")]
175
+ if split not in SPLITS:
176
+ raise ValueError(f"bilinmeyen split: {split}")
177
+ return [t for t in tasks if t.split == split]
178
+
179
+
180
+ def verify(task: BenchTask, workspace: Path, timeout: float = 60.0) -> tuple[bool, str]:
181
+ """Gizli doğrulama dosyalarını çalışma alanına yazar (ajanın testlerini ezer) ve komutu koşar."""
182
+ shutil.copytree(task.check, workspace, dirs_exist_ok=True)
183
+ cfg = SandboxConfig(workdir=workspace, timeout=timeout, memory="256m")
184
+ try:
185
+ r = run_command(cfg, list(task.check_cmd))
186
+ except SandboxError as e:
187
+ return False, f"sandbox hatası: {e}"
188
+ out = (r.stdout + r.stderr).strip()
189
+ return r.exit_code == 0 and not r.timed_out, out[-1500:]
190
+
191
+
192
+ def _tests_modified(repo: Path, ws: Path) -> bool:
193
+ for f in repo.rglob("test_*.py"):
194
+ mine = ws / f.relative_to(repo)
195
+ if not mine.is_file() or mine.read_bytes() != f.read_bytes():
196
+ return True
197
+ return False
198
+
199
+
200
+ class RecordingModel:
201
+ """Modelin yanıtlarını sırayla kaydeder (tekrar oynatma için). `usage` ve diğer alanlar alttaki istemciden gelir."""
202
+
203
+ def __init__(self, inner: ModelClient):
204
+ self._inner = inner
205
+ self.replies: list[dict] = []
206
+
207
+ def __getattr__(self, name: str):
208
+ return getattr(self._inner, name)
209
+
210
+ def chat(self, messages, tools=None):
211
+ reply = self._inner.chat(messages, tools)
212
+ self.replies.append(
213
+ {
214
+ "content": reply.content,
215
+ "tool_calls": [
216
+ {"id": c.id, "name": c.name, "arguments": c.arguments} for c in reply.tool_calls
217
+ ],
218
+ }
219
+ )
220
+ return reply
221
+
222
+
223
+ class ReplayModel:
224
+ """Kaydedilmiş yanıtları aynen verir: harness/araç tarafını modelsiz yeniden çalıştırmak için."""
225
+
226
+ def __init__(self, replies: list[dict]):
227
+ self._replies = list(replies)
228
+ self._n = 0
229
+ self.usage = None
230
+
231
+ def chat(self, messages, tools=None):
232
+ from usta.models import ModelResponse, ToolCall
233
+
234
+ if self._n >= len(self._replies):
235
+ raise ModelError(
236
+ "tekrar oynatma: kayıtlı yanıtlar bitti (harness kayıttan farklı ilerliyor)"
237
+ )
238
+ r = self._replies[self._n]
239
+ self._n += 1
240
+ return ModelResponse(
241
+ r["content"], [ToolCall(c["id"], c["name"], c["arguments"]) for c in r["tool_calls"]]
242
+ )
243
+
244
+
245
+ def _attempt(
246
+ task: BenchTask,
247
+ model: ModelClient,
248
+ *,
249
+ max_steps: int,
250
+ time_limit: float,
251
+ agent_factory: Callable[..., Agent],
252
+ arm: Arm,
253
+ trace_dir: Path | None = None,
254
+ replay: list[dict] | None = None,
255
+ ) -> TaskResult:
256
+ t0 = time.monotonic()
257
+ counts = {"tool_calls": 0, "tool_errors": 0, "denied": 0}
258
+ gate_events: list[str] = []
259
+ trips: list[bool] = []
260
+ order: list[str] = [] # araç çağrılarının sırası: doğrulama, son düzenlemeden sonra mı?
261
+ calls: list[tuple[str, str]] = []
262
+ errors: list[str] = []
263
+ events: list[dict] = [] # adım bazında iz: zaman, araç, sonuç, kaynak tüketimi
264
+ stats = {"syntax": 0, "compactions": 0, "context_peak": 0}
265
+ recorder = RecordingModel(model) if trace_dir is not None and replay is None else None
266
+ active: ModelClient = ReplayModel(replay) if replay is not None else (recorder or model)
267
+ usage = getattr(model, "usage", None)
268
+ before = (usage.prompt, usage.completion, usage.requests) if usage else (0, 0, 0)
269
+
270
+ def stamp(kind: str, **data) -> None:
271
+ events.append({"t_ms": round((time.monotonic() - t0) * 1000), "kind": kind, **data})
272
+
273
+ def on_event(kind: str, data: dict) -> None:
274
+ if kind == "tool_call":
275
+ counts["tool_calls"] += 1
276
+ order.append(str(data.get("tool")))
277
+ calls.append((str(data.get("tool")), taxonomy.summarize_args(data.get("args"))))
278
+ stamp("tool_call", tool=data.get("tool"), args=calls[-1][1])
279
+ elif kind == "breaker":
280
+ trips.append(bool(data.get("final")))
281
+ stamp(
282
+ "breaker", reason=str(data.get("reason", ""))[:120], final=bool(data.get("final"))
283
+ )
284
+ elif kind == "verification":
285
+ gate_events.append(str(data.get("status")))
286
+ stamp("verification", status=data.get("status"))
287
+ elif kind == "denied":
288
+ counts["denied"] += 1
289
+ stamp("denied", tool=data.get("tool"))
290
+ elif kind == "tool_result":
291
+ result = str(data.get("result", ""))
292
+ if result.startswith("hata:"):
293
+ counts["tool_errors"] += 1
294
+ errors.append(result[:200])
295
+ if "\nuyarı:" in result: # düzenleme sonrası sözdizimi geri bildirimi
296
+ stats["syntax"] += 1
297
+ stamp(
298
+ "tool_result",
299
+ tool=data.get("tool"),
300
+ ok=not result.startswith("hata:"),
301
+ head=result[:100],
302
+ )
303
+ elif kind == "usage":
304
+ stats["context_peak"] = max(stats["context_peak"], int(data.get("context") or 0))
305
+ stamp(
306
+ "usage",
307
+ prompt=data.get("prompt"),
308
+ completion=data.get("completion"),
309
+ requests=data.get("requests"),
310
+ context=data.get("context"),
311
+ )
312
+ elif kind == "compacted":
313
+ stats["compactions"] += 1
314
+ stamp("compacted", saved_chars=data.get("saved_chars"))
315
+
316
+ cancel = threading.Event()
317
+ timer = threading.Timer(time_limit, cancel.set)
318
+ timer.daemon = True
319
+ tracker = PhaseTracker()
320
+ with tempfile.TemporaryDirectory(prefix="usta-bench-") as tmp:
321
+ ws = Path(tmp) / "ws"
322
+ shutil.copytree(task.repo, ws)
323
+ registry = build_registry(
324
+ ToolContext(
325
+ root=ws,
326
+ cancel=cancel,
327
+ symbol_tools=arm.symbol_tools,
328
+ **({"max_read": arm.max_read} if arm.max_read else {}),
329
+ )
330
+ )
331
+ if arm.tools is not None:
332
+ registry = registry.subset(arm.tools)
333
+ agent = agent_factory(
334
+ active,
335
+ registry,
336
+ Policy(ws),
337
+ AuditLog(Path(tmp) / "audit.jsonl"),
338
+ approver=lambda *_: False, # ölçümde insan yok: onay gerektiren eylem reddedilir
339
+ max_steps=max_steps,
340
+ on_event=on_event,
341
+ cancel=cancel,
342
+ system_prompt=arm.system_prompt,
343
+ verifier=Verifier(CompletionGate(ws, cancel=cancel)) if arm.verify else None,
344
+ breaker=CircuitBreaker(ws) if arm.breaker else None,
345
+ context_window=arm.context_window,
346
+ phases=tracker,
347
+ )
348
+ error, steps, truncated, infra, answer, timed_out = "", 0, False, False, "", False
349
+ timer.start()
350
+ try:
351
+ result = agent.run(task.prompt)
352
+ steps, truncated, answer = result.steps, result.truncated, result.answer
353
+ if result.cancelled:
354
+ error, timed_out = "zaman sınırı aşıldı", True
355
+ except ModelError as e:
356
+ error, infra = f"model hatası: {e}", e.infra
357
+ finally:
358
+ timer.cancel()
359
+ modified = _tests_modified(task.repo, ws)
360
+ passed, out = verify(task, ws)
361
+ if not passed and verify_env_problem(
362
+ out, ws
363
+ ): # gizli doğrulama ortamı sorunu: modelin başarısızlığı değil
364
+ infra, error = True, f"doğrulama ortamı: {verify_env_problem(out, ws)}"
365
+ edit_idx = [i for i, n in enumerate(order) if n in ("write_file", "edit_file")]
366
+ run_idx = [i for i, n in enumerate(order) if n == "run"]
367
+ gate_passed = bool(gate_events) and gate_events[-1] == "passed"
368
+ verified = gate_passed or (bool(edit_idx) and bool(run_idx) and run_idx[-1] > edit_idx[-1])
369
+ answered = not error and not truncated
370
+ after = (usage.prompt, usage.completion, usage.requests) if usage else (0, 0, 0)
371
+ ok = passed and not error
372
+ unverified = answered and bool(edit_idx) and not verified
373
+ repairs = sum(1 for i in edit_idx if run_idx and i > run_idx[0])
374
+ verdict = taxonomy.classify(
375
+ taxonomy.Facts(
376
+ passed=ok,
377
+ infra=infra,
378
+ timed_out=timed_out,
379
+ model_error=bool(error) and not infra and not timed_out,
380
+ truncated=truncated,
381
+ tool_calls=counts["tool_calls"],
382
+ edits=len(edit_idx),
383
+ steps=steps,
384
+ max_steps=max_steps,
385
+ answer=answer,
386
+ tool_errors=errors,
387
+ calls=calls,
388
+ gate_rounds=gate_events.count("failed"),
389
+ breaker_trips=len(trips),
390
+ compactions=stats["compactions"],
391
+ context_peak=stats["context_peak"],
392
+ context_window=arm.context_window or 0,
393
+ syntax_warnings=stats["syntax"],
394
+ tests_modified=modified,
395
+ unverified_claim=unverified,
396
+ )
397
+ )
398
+ res = TaskResult(
399
+ task.id,
400
+ ok,
401
+ steps=steps,
402
+ seconds=round(time.monotonic() - t0, 2),
403
+ truncated=truncated,
404
+ error=error,
405
+ check_output="" if passed else out,
406
+ outcome="infra" if infra else "pass" if ok else "fail",
407
+ prompt_tokens=after[0] - before[0],
408
+ completion_tokens=after[1] - before[1],
409
+ requests=after[2] - before[2],
410
+ edits=len(edit_idx),
411
+ verified=verified,
412
+ unverified_claim=unverified,
413
+ tests_modified=modified,
414
+ gate=next((g for g in reversed(gate_events) if g != "nudge"), ""),
415
+ gate_rounds=gate_events.count("failed"),
416
+ breaker_trips=len(trips),
417
+ blocked=bool(trips) and trips[-1],
418
+ failure=verdict.primary,
419
+ split=task.split,
420
+ terminal=tracker.terminal
421
+ or tracker.finish(
422
+ answered=answered and not infra,
423
+ truncated=truncated,
424
+ cancelled=timed_out,
425
+ error=bool(error) and not timed_out,
426
+ ),
427
+ phase_steps=dict(tracker.steps_in),
428
+ phase_transitions=len(tracker.transitions),
429
+ signals=tuple(verdict.signals),
430
+ repair_attempts=repairs,
431
+ context_peak=stats["context_peak"],
432
+ compactions=stats["compactions"],
433
+ **counts,
434
+ )
435
+ if trace_dir is not None and replay is None:
436
+ res = replace(
437
+ res, trace=_write_trace(trace_dir, task, arm, max_steps, res, events, recorder)
438
+ )
439
+ return res
440
+
441
+
442
+ def _write_trace(
443
+ trace_dir: Path,
444
+ task: BenchTask,
445
+ arm: Arm,
446
+ max_steps: int,
447
+ res: TaskResult,
448
+ events: list[dict],
449
+ recorder: RecordingModel | None,
450
+ ) -> str:
451
+ """Adım izi + model yanıtları (tekrar oynatma için). Sırlar maskelenir."""
452
+ from usta.audit import mask_deep
453
+
454
+ trace_dir = Path(trace_dir)
455
+ trace_dir.mkdir(parents=True, exist_ok=True)
456
+ n = len(list(trace_dir.glob(f"{task.id}.*.json"))) + 1
457
+ path = trace_dir / f"{task.id}.{n}.json"
458
+ doc = mask_deep(
459
+ {
460
+ "version": TRACE_VERSION,
461
+ "task": task.id,
462
+ "split": task.split,
463
+ "arm": arm.name,
464
+ "max_steps": max_steps,
465
+ "result": asdict(res),
466
+ "events": events,
467
+ "replies": recorder.replies if recorder else [],
468
+ }
469
+ )
470
+ path.write_text(json.dumps(doc, ensure_ascii=False, indent=1))
471
+ return path.name
472
+
473
+
474
+ def replay_trace(path: Path, *, tasks: list[BenchTask] | None = None) -> tuple[TaskResult, dict]:
475
+ """Kaydı modelsiz yeniden oynatır; (yeni sonuç, özgün sonuç). Harness/araç tarafı kararlıysa aynı çıkar."""
476
+ doc = json.loads(Path(path).read_text())
477
+ if doc.get("version") != TRACE_VERSION or not doc.get("replies"):
478
+ raise ValueError(f"{path}: yeniden oynatılabilir iz değil")
479
+ pool = tasks or load_tasks()
480
+ task = next((t for t in pool if t.id == doc["task"]), None)
481
+ if task is None:
482
+ raise ValueError(f"görev yok: {doc['task']}")
483
+ arm = ARMS[doc["arm"]]
484
+ r = _attempt(
485
+ task,
486
+ ReplayModel(doc["replies"]),
487
+ max_steps=int(doc["max_steps"]),
488
+ time_limit=600.0,
489
+ agent_factory=Agent,
490
+ arm=arm,
491
+ replay=doc["replies"],
492
+ )
493
+ return r, doc["result"]
494
+
495
+
496
+ def run_task(
497
+ task: BenchTask,
498
+ model: ModelClient,
499
+ *,
500
+ max_steps: int = 30,
501
+ time_limit: float = 600.0,
502
+ agent_factory: Callable[..., Agent] = Agent,
503
+ infra_retries: int = 2,
504
+ retry_delay: float = 3.0,
505
+ arm: Arm = ARMS["B"],
506
+ trace_dir: Path | None = None,
507
+ ) -> TaskResult:
508
+ """Altyapı hatasında (uç nokta/ağ) yeniden dener; hâlâ başarısızsa `infra` olarak döner."""
509
+ for attempt in range(1, infra_retries + 2):
510
+ r = _attempt(
511
+ task,
512
+ model,
513
+ max_steps=max_steps,
514
+ time_limit=time_limit,
515
+ agent_factory=agent_factory,
516
+ arm=arm,
517
+ trace_dir=trace_dir,
518
+ )
519
+ if r.outcome != "infra" or attempt == infra_retries + 1:
520
+ return replace(r, attempts=attempt)
521
+ time.sleep(retry_delay)
522
+ raise AssertionError("ulaşılamaz")
523
+
524
+
525
+ def summarize(results: list[TaskResult]) -> dict:
526
+ valid = [r for r in results if r.outcome != "infra"]
527
+ n = len(valid)
528
+ passed = sum(r.passed for r in valid)
529
+ tokens = sum(r.prompt_tokens + r.completion_tokens for r in valid)
530
+ calls = sum(r.tool_calls for r in valid)
531
+ per_task: dict[str, dict[str, int]] = {}
532
+ for r in results:
533
+ d = per_task.setdefault(r.task, {"passed": 0, "runs": 0, "infra": 0})
534
+ if r.outcome == "infra":
535
+ d["infra"] += 1
536
+ else:
537
+ d["runs"] += 1
538
+ d["passed"] += r.passed
539
+ return {
540
+ "runs": len(results),
541
+ "valid_runs": n,
542
+ "infra_errors": len(results) - n,
543
+ "passed": passed,
544
+ "pass_rate": round(passed / n, 3) if n else 0.0,
545
+ "mean_steps": round(statistics.fmean(r.steps for r in valid), 2) if n else 0.0,
546
+ "mean_seconds": round(statistics.fmean(r.seconds for r in valid), 1) if n else 0.0,
547
+ "mean_tokens": round(tokens / n, 1) if n else 0.0,
548
+ "tokens_per_solved": round(tokens / passed) if passed else None,
549
+ "tool_error_rate": round(sum(r.tool_errors for r in valid) / calls, 3) if calls else 0.0,
550
+ "unverified_claims": sum(r.unverified_claim for r in valid),
551
+ "claimed_but_failed": sum(
552
+ r.outcome == "fail" and not r.error and not r.truncated for r in valid
553
+ ),
554
+ "tests_modified": sum(r.tests_modified for r in valid),
555
+ "breaker_trips": sum(r.breaker_trips for r in valid),
556
+ "blocked": sum(r.blocked for r in valid),
557
+ "per_task": per_task,
558
+ "infra_error_rate": round((len(results) - n) / len(results), 3) if results else 0.0,
559
+ "failures": dict(Counter(r.failure for r in valid if not r.passed and r.failure)),
560
+ "signals": dict(Counter(sig for r in valid for sig in r.signals)),
561
+ "mean_tool_calls": round(statistics.fmean(r.tool_calls for r in valid), 2) if n else 0.0,
562
+ "mean_repairs": round(statistics.fmean(r.repair_attempts for r in valid), 2) if n else 0.0,
563
+ "mean_requests": round(statistics.fmean(r.requests for r in valid), 2) if n else 0.0,
564
+ "context_peak_max": max((r.context_peak for r in valid), default=0),
565
+ "compactions": sum(r.compactions for r in valid),
566
+ "gate_rounds": sum(r.gate_rounds for r in valid),
567
+ }
568
+
569
+
570
+ def run_bench(
571
+ model_factory: Callable[[], ModelClient],
572
+ tasks: list[BenchTask],
573
+ *,
574
+ repeat: int = 1,
575
+ max_steps: int = 30,
576
+ time_limit: float = 600.0,
577
+ infra_retries: int = 2,
578
+ arm: Arm = ARMS["B"],
579
+ agent_factory: Callable[..., Agent] = Agent,
580
+ on_result: Callable[[TaskResult], None] | None = None,
581
+ should_stop: Callable[[], bool] | None = None,
582
+ trace_dir: Path | None = None,
583
+ ) -> list[TaskResult]:
584
+ results = []
585
+ for _ in range(repeat):
586
+ for task in tasks:
587
+ if should_stop is not None and should_stop(): # her koşudan önce: dış taraf kesebilir
588
+ return results
589
+ r = run_task(
590
+ task,
591
+ model_factory(),
592
+ max_steps=max_steps,
593
+ time_limit=time_limit,
594
+ infra_retries=infra_retries,
595
+ arm=arm,
596
+ agent_factory=agent_factory,
597
+ trace_dir=trace_dir,
598
+ )
599
+ results.append(r)
600
+ if on_result:
601
+ on_result(r)
602
+ return results
603
+
604
+
605
+ def report(model: str, protocol: str, results: list[TaskResult], arm: str = "B") -> dict:
606
+ return {
607
+ "arm": arm,
608
+ "model": model,
609
+ "protocol": protocol,
610
+ "summary": summarize(results),
611
+ "results": [asdict(r) for r in results],
612
+ }
613
+
614
+
615
+ def wilson(passed: int, n: int, z: float = 1.96) -> tuple[float, float]:
616
+ """Başarı oranı için Wilson %95 güven aralığı (küçük örneklemde normal yaklaşımdan güvenilir)."""
617
+ if n <= 0:
618
+ return 0.0, 0.0
619
+ p = passed / n
620
+ denom = 1 + z * z / n
621
+ centre = (p + z * z / (2 * n)) / denom
622
+ half = z * ((p * (1 - p) / n + z * z / (4 * n * n)) ** 0.5) / denom
623
+ return max(0.0, round(centre - half, 4)), min(1.0, round(centre + half, 4))
624
+
625
+
626
+ def load_report(path: Path) -> dict:
627
+ data = json.loads(Path(path).read_text())
628
+ if not isinstance(data, dict) or "results" not in data or "model" not in data:
629
+ raise ValueError(f"{path}: bench raporu değil")
630
+ data.setdefault("arm", "B") # kol alanından önce üretilen raporlar B koluydu
631
+ return data
632
+
633
+
634
+ def _results(rep: dict) -> list[TaskResult]:
635
+ return [
636
+ TaskResult(**{k: v for k, v in r.items() if k in TaskResult.__dataclass_fields__})
637
+ for r in rep["results"]
638
+ ]
639
+
640
+
641
+ def paired(a: list[TaskResult], b: list[TaskResult]) -> dict:
642
+ """Aynı görev + aynı tekrar sırası eşleştirilir; yalnız iki tarafı da geçerli (altyapı hatasız) çiftler sayılır."""
643
+
644
+ def keyed(rs: list[TaskResult]) -> dict[tuple[str, int], TaskResult]:
645
+ seen: Counter[str] = Counter()
646
+ out = {}
647
+ for r in rs:
648
+ seen[r.task] += 1
649
+ out[(r.task, seen[r.task])] = r
650
+ return out
651
+
652
+ ka, kb = keyed(a), keyed(b)
653
+ both = a_only = b_only = neither = 0
654
+ for key in sorted(ka.keys() & kb.keys()):
655
+ x, y = ka[key], kb[key]
656
+ if x.outcome == "infra" or y.outcome == "infra":
657
+ continue
658
+ if x.passed and y.passed:
659
+ both += 1
660
+ elif x.passed:
661
+ a_only += 1
662
+ elif y.passed:
663
+ b_only += 1
664
+ else:
665
+ neither += 1
666
+ return {
667
+ "pairs": both + a_only + b_only + neither,
668
+ "both": both,
669
+ "a_only": a_only,
670
+ "b_only": b_only,
671
+ "neither": neither,
672
+ }
673
+
674
+
675
+ def paired_verdict(p: dict, a: str, b: str) -> str:
676
+ """Yön + belirsizlik. Küçük örneklemde anlamlılık İDDİA EDİLMEZ."""
677
+ d = p["a_only"] + p["b_only"]
678
+ if p["pairs"] == 0:
679
+ return "eşleşen çift yok"
680
+ if d == 0:
681
+ return "tüm çiftlerde aynı sonuç (fark gözlenmedi)"
682
+ lo, hi = wilson(p["b_only"], d)
683
+ lean = b if p["b_only"] > p["a_only"] else a if p["a_only"] > p["b_only"] else None
684
+ if lean is None:
685
+ return f"yön yok ({d} uyuşmayan çift eşit bölündü)"
686
+ note = (
687
+ "örneklem çok küçük; yalnız yön"
688
+ if d < 10
689
+ else "aralık 0,5'i içeriyor: belirsiz"
690
+ if lo <= 0.5 <= hi
691
+ else "aralık 0,5'i dışlıyor"
692
+ )
693
+ return f"yön {lean} lehine ({d} uyuşmayan çift); {note}"
694
+
695
+
696
+ def compare_markdown(tiers: dict[str, list[Path]]) -> str:
697
+ """Katman (zayıf/orta/büyük) başına kol karşılaştırma tablosu, güven aralığı, eşleştirilmiş analiz, hata nedenleri."""
698
+ lines = ["# USTA Bench karşılaştırması", ""]
699
+ for tier, paths in tiers.items():
700
+ reports = [load_report(p) for p in paths]
701
+ lines += [f"## {tier}", ""]
702
+ header = (
703
+ "| Model | Kol | Geçen | %95 aralık | Token/görev | Çözülen başına token | Süre (sn) "
704
+ "| Araç çağrısı | Onarım | Kanıtsız | 'Bitti' deyip kalan | Altyapı hatası |"
705
+ )
706
+ lines += [header, "|---|---|---|---|---|---|---|---|---|---|---|---|"]
707
+ ci: dict[tuple[str, str], tuple[float, float, float]] = {}
708
+ by_model: dict[str, dict[str, list[TaskResult]]] = {}
709
+ fails: list[tuple[str, str, dict]] = []
710
+ for rep in sorted(reports, key=lambda r: (r["model"], r["arm"])):
711
+ rs = _results(rep)
712
+ s = summarize(rs)
713
+ lo, hi = wilson(s["passed"], s["valid_runs"])
714
+ ci[(rep["model"], rep["arm"])] = (s["pass_rate"], lo, hi)
715
+ by_model.setdefault(rep["model"], {})[rep["arm"]] = rs
716
+ fails.append((rep["model"], rep["arm"], s))
717
+ solved = s["tokens_per_solved"]
718
+ lines.append(
719
+ f"| {rep['model']} | {rep['arm']} | {s['passed']}/{s['valid_runs']} (%{s['pass_rate'] * 100:.0f}) "
720
+ f"| %{lo * 100:.0f}-%{hi * 100:.0f} | {s['mean_tokens']:g} | {solved if solved is not None else '-'} "
721
+ f"| {s['mean_seconds']:g} | {s['mean_tool_calls']:g} | {s['mean_repairs']:g} | {s['unverified_claims']} "
722
+ f"| {s['claimed_but_failed']} | {s['infra_errors']}/{s['runs']} (%{s['infra_error_rate'] * 100:.0f}) |"
723
+ )
724
+ lines += ["", *_verdicts(ci), ""]
725
+ lines += ["**Başarısızlık nedenleri** (geçerli, başarısız koşular):", ""]
726
+ for model, arm, s in fails:
727
+ dist = (
728
+ ", ".join(
729
+ f"{k} {v}" for k, v in sorted(s["failures"].items(), key=lambda kv: -kv[1])
730
+ )
731
+ or "—"
732
+ )
733
+ lines.append(f"- {model} / {arm}: {dist}")
734
+ lines.append("")
735
+ for model, arms in by_model.items():
736
+ base = arms.get("B")
737
+ others = [a for a in arms if a != "B"]
738
+ if base is None or not others:
739
+ continue
740
+ lines += [
741
+ f"**Eşleştirilmiş karşılaştırma — {model}** (B ile; aynı görev + tekrar sırası):",
742
+ "",
743
+ ]
744
+ lines += [
745
+ "| Kol | Çift | İkisi geçti | Yalnız B | Yalnız kol | İkisi kaldı | Yorum |",
746
+ "|---|---|---|---|---|---|---|",
747
+ ]
748
+ for arm in others:
749
+ pr = paired(base, arms[arm])
750
+ lines.append(
751
+ f"| {arm} | {pr['pairs']} | {pr['both']} | {pr['a_only']} | {pr['b_only']} | {pr['neither']} "
752
+ f"| {paired_verdict(pr, 'B', arm)} |"
753
+ )
754
+ lines.append("")
755
+ lines += [
756
+ (
757
+ "> Küçük örneklemde istatistiksel anlamlılık iddia edilmez: aralıklar örtüşüyorsa ya da uyuşmayan çift azsa "
758
+ "fark kanıtlanmış sayılmaz. Altyapı hataları başarısızlık sayılmadı; sayıları ve oranları tabloda ayrıca verilir."
759
+ ),
760
+ "",
761
+ ]
762
+ return "\n".join(lines).rstrip("\n") + "\n"
763
+
764
+
765
+ def regress_markdown(old_path: Path, new_path: Path) -> str:
766
+ """Önceki sürümün raporuna göre regresyonlar: görev bazında geçme farkı, maliyet farkı, neden kayması."""
767
+ old, new = load_report(old_path), load_report(new_path)
768
+ ro, rn = _results(old), _results(new)
769
+ so, sn = summarize(ro), summarize(rn)
770
+ lines = [
771
+ "# USTA Bench regresyon raporu",
772
+ "",
773
+ f"- Önceki: `{Path(old_path).name}` ({old['model']}, kol {old['arm']}, protokol {old.get('protocol', '?')})",
774
+ f"- Yeni: `{Path(new_path).name}` ({new['model']}, kol {new['arm']}, protokol {new.get('protocol', '?')})",
775
+ ]
776
+ for key, label in (("model", "model"), ("arm", "kol"), ("protocol", "protokol")):
777
+ if old.get(key) != new.get(key):
778
+ lines.append(
779
+ f"- UYARI: {label} farklı ({old.get(key)} → {new.get(key)}); fark harness değişikliğinden gelmeyebilir."
780
+ )
781
+ if {r.task for r in ro} != {r.task for r in rn}:
782
+ lines.append("- UYARI: görev kümeleri farklı; yalnız ortak görevler karşılaştırıldı.")
783
+ lines += ["", "| Metrik | Önceki | Yeni | Fark |", "|---|---|---|---|"]
784
+ for label, key, fmt in (
785
+ ("Geçen", "passed", "{:g}"),
786
+ ("Geçerli koşu", "valid_runs", "{:g}"),
787
+ ("Altyapı hatası", "infra_errors", "{:g}"),
788
+ ("Token/görev", "mean_tokens", "{:g}"),
789
+ ("Süre (sn)", "mean_seconds", "{:g}"),
790
+ ("Araç çağrısı", "mean_tool_calls", "{:g}"),
791
+ ("Onarım", "mean_repairs", "{:g}"),
792
+ ):
793
+ a, b_ = so[key], sn[key]
794
+ lines.append(f"| {label} | {fmt.format(a)} | {fmt.format(b_)} | {b_ - a:+g} |")
795
+ common = sorted({r.task for r in ro} & {r.task for r in rn})
796
+ reg, imp = [], []
797
+ for t in common:
798
+ po = [r for r in ro if r.task == t and r.outcome != "infra"]
799
+ pn = [r for r in rn if r.task == t and r.outcome != "infra"]
800
+ if not po or not pn:
801
+ continue
802
+ ao, an = sum(r.passed for r in po) / len(po), sum(r.passed for r in pn) / len(pn)
803
+ row = (
804
+ f"- {t}: {sum(r.passed for r in po)}/{len(po)} → {sum(r.passed for r in pn)}/{len(pn)}"
805
+ )
806
+ if an < ao:
807
+ reg.append(row)
808
+ elif an > ao:
809
+ imp.append(row)
810
+ lines += [
811
+ "",
812
+ f"**Regresyonlar ({len(reg)})**",
813
+ "",
814
+ *(reg or ["- yok"]),
815
+ "",
816
+ f"**İyileşmeler ({len(imp)})**",
817
+ "",
818
+ *(imp or ["- yok"]),
819
+ ]
820
+ cats = sorted(set(so["failures"]) | set(sn["failures"]))
821
+ if cats:
822
+ lines += [
823
+ "",
824
+ "**Başarısızlık nedeni kayması**",
825
+ "",
826
+ "| Neden | Önceki | Yeni |",
827
+ "|---|---|---|",
828
+ ]
829
+ lines += [
830
+ f"| {c} | {so['failures'].get(c, 0)} | {sn['failures'].get(c, 0)} |" for c in cats
831
+ ]
832
+ lines += [
833
+ "",
834
+ "> Küçük örneklemde fark kanıtlanmış sayılmaz; gerçek bir regresyonu doğrulamak için aynı görevleri daha çok tekrarla.",
835
+ ]
836
+ return "\n".join(lines) + "\n"
837
+
838
+
839
+ def diagnose_markdown(paths: list[Path]) -> str:
840
+ """Başarısızlık nedenleri dağılımı, görev başına maliyet ve harness yükü: `neden başarısız?` sorusunun tablosu."""
841
+ lines = ["# USTA Bench teşhisi", ""]
842
+ for path in paths:
843
+ rep = load_report(path)
844
+ rs = _results(rep)
845
+ s = summarize(rs)
846
+ lines += [
847
+ f"## {rep['model']} — kol {rep['arm']} (`{Path(path).name}`)",
848
+ "",
849
+ (
850
+ f"- Koşu {s['runs']} (geçerli {s['valid_runs']}, altyapı {s['infra_errors']} = "
851
+ f"%{s['infra_error_rate'] * 100:.0f}); geçen {s['passed']}/{s['valid_runs']}"
852
+ ),
853
+ (
854
+ f"- Ortalama: {s['mean_tool_calls']:g} araç çağrısı, {s['mean_requests']:g} istek, "
855
+ f"{s['mean_repairs']:g} onarım denemesi, {s['mean_tokens']:g} token, {s['mean_seconds']:g} sn; "
856
+ f"en büyük bağlam {s['context_peak_max']}; sıkıştırma {s['compactions']}; "
857
+ f"kapı turu {s['gate_rounds']}; devre kesici {s['breaker_trips']}"
858
+ ),
859
+ "",
860
+ "| Neden | Koşu | Pay |",
861
+ "|---|---|---|",
862
+ ]
863
+ bad = sum(s["failures"].values())
864
+ for k, v in sorted(s["failures"].items(), key=lambda kv: -kv[1]):
865
+ lines.append(f"| {k} | {v} | %{v / bad * 100:.0f} |")
866
+ if not bad:
867
+ lines.append("| (başarısız koşu yok) | 0 | — |")
868
+ sig = (
869
+ ", ".join(f"{k} {v}" for k, v in sorted(s["signals"].items(), key=lambda kv: -kv[1]))
870
+ or "—"
871
+ )
872
+ lines += ["", f"İşaretler (tüm koşular, birincil neden dışındakiler dahil): {sig}", ""]
873
+ lines += [
874
+ "| Görev | Bölüm | Sonuç | Neden | Çağrı | Onarım | Token | Süre |",
875
+ "|---|---|---|---|---|---|---|---|",
876
+ ]
877
+ for r in rs:
878
+ res = "GEÇTİ" if r.passed else "ALTYAPI" if r.outcome == "infra" else "KALDI"
879
+ lines.append(
880
+ f"| {r.task} | {r.split or '-'} | {res} | {r.failure or '-'} | {r.tool_calls} | {r.repair_attempts} "
881
+ f"| {r.prompt_tokens + r.completion_tokens} | {r.seconds:g} |"
882
+ )
883
+ lines.append("")
884
+ return "\n".join(lines).rstrip("\n") + "\n"
885
+
886
+
887
+ def _verdicts(ci: dict[tuple[str, str], tuple[float, float, float]]) -> list[str]:
888
+ out = []
889
+ models = sorted({m for m, _ in ci})
890
+ for m in models:
891
+ arms = {a: v for (mm, a), v in ci.items() if mm == m}
892
+ for a, b in (("B", "A"), ("C", "B")):
893
+ if a in arms and b in arms:
894
+ _, lo_a, hi_a = arms[a]
895
+ _, lo_b, hi_b = arms[b]
896
+ if lo_a > hi_b:
897
+ out.append(f"- {m}: {a}, {b}'den belirgin şekilde yüksek.")
898
+ elif lo_b > hi_a:
899
+ out.append(f"- {m}: {b}, {a}'den belirgin şekilde yüksek.")
900
+ else:
901
+ out.append(
902
+ f"- {m}: {a} ve {b} arasında belirgin fark yok (aralıklar örtüşüyor)."
903
+ )
904
+ return out or ["- Karşılaştırılacak kol çifti yok."]