Spaces:
Running
Running
SilverElixir commited on
Commit ·
ecde1bf
1
Parent(s): 109b907
Add harness-eval: measure whether auto-edited AGENTS.md helps the agent
Browse filesTasks come from repo history (fix-commit code + tests), the judge is the repo gate (pytest + pyflakes). Artifacts live outside %TEMP%\opencode because OpenCode wipes that scratch dir.
- eval/README.md +47 -0
- eval/harness_eval.py +702 -0
- eval/tasks.json +47 -0
eval/README.md
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Harness-eval: проверяем, помогает ли автоправка AGENTS.md
|
| 2 |
+
|
| 3 |
+
Эксперимент в духе [google-research/harness2](https://github.com/google-research/harness2):
|
| 4 |
+
не берём фреймворк, берём метод. Задачи из истории репозитория гоняются агентом
|
| 5 |
+
(OpenCode CLI) с текущим `AGENTS.md`, потом модель-редактор предлагает правку
|
| 6 |
+
`AGENTS.md`, и те же задачи гоняются снова. Судья — гейт репозитория.
|
| 7 |
+
|
| 8 |
+
## Что измеряем
|
| 9 |
+
|
| 10 |
+
- Главное: доля задач, решённых агентом (целевые тесты прошли и новых падений нет).
|
| 11 |
+
- Побочное: нарушения правил проекта (правил тесты, не запустил гейт, юникс-команды
|
| 12 |
+
в PowerShell).
|
| 13 |
+
|
| 14 |
+
## Устройство замера
|
| 15 |
+
|
| 16 |
+
1. **Задача** — fix-коммит из истории: меняет код и тесты. Песочница собирается на
|
| 17 |
+
`fix^` (код до правки), тесты берутся из `fix` — целевые тесты падают, остальные
|
| 18 |
+
проходят. Список целевых (FAIL_TO_PASS) считается эмпирически: `compute_targets`
|
| 19 |
+
смотрит, что падает на базе и что после настоящей правки.
|
| 20 |
+
2. **Песочница** — клон репозитория без remote, с `opencode.json`, где опасные команды
|
| 21 |
+
запрещены, и с нужным вариантом `AGENTS.md`.
|
| 22 |
+
3. **Прогон** — `opencode run --standalone --auto --model <модель> <задача>`.
|
| 23 |
+
Сразу после агента снимается слепок песочницы: содержимое может быть снесено
|
| 24 |
+
(OpenCode чистит `%TEMP%\opencode`, а туда нельзя класть артефакты).
|
| 25 |
+
4. **Судья** — `pytest -q` и `pyflakes` на слепке.
|
| 26 |
+
|
| 27 |
+
## Команды
|
| 28 |
+
|
| 29 |
+
```bash
|
| 30 |
+
python eval/harness_eval.py check # задачи валидны (целевые падают на базе)
|
| 31 |
+
python eval/harness_eval.py probe <fix-sha>:<tests> # разведка кандидатов из истории
|
| 32 |
+
python eval/harness_eval.py run --task <id> --variant base
|
| 33 |
+
python eval/harness_eval.py run --task <id> --variant candidate --agents-md <файл>
|
| 34 |
+
python eval/harness_eval.py propose --base-dir <каталог с базовыми прогонами>
|
| 35 |
+
python eval/harness_eval.py report --out <каталог>
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
Артефакты пишутся в `%LOCALAPPDATA%\Lumen\harness-eval` (важно: не в `%TEMP%\opencode`).
|
| 39 |
+
|
| 40 |
+
## Ограничения
|
| 41 |
+
|
| 42 |
+
- Выборка маленькая (7 задач, по одному прогону на вариант) — это сигнал
|
| 43 |
+
«есть/нет эффекта», а не статистика.
|
| 44 |
+
- Один и тот же агент решает задачи один раз: разброс между прогонами не измерен.
|
| 45 |
+
- Судья — гейт, он не ловит нарушения правил, если тесты всё равно прошли.
|
| 46 |
+
- MCP-серверы в песочнице отключены: прогоны быстрее и без сети, но это не ровно
|
| 47 |
+
твоя обычная обстановка.
|
eval/harness_eval.py
ADDED
|
@@ -0,0 +1,702 @@
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Эксперимент: помогает ли автоматическая правка AGENTS.md агенту решать задачи.
|
| 2 |
+
|
| 3 |
+
Идея из google-research/harness2, но без фреймворка: берём реальные задачи из
|
| 4 |
+
истории репозитория, гоняем агента (OpenCode CLI) в песочнице с текущим
|
| 5 |
+
AGENTS.md, затем модель предлагает правку AGENTS.md, и те же задачи гоняются
|
| 6 |
+
с новым файлом. Судья — гейт репозитория: pytest и pyflakes.
|
| 7 |
+
|
| 8 |
+
Подкоманды: run (одна задача и вариант), propose (кандидатная правка AGENTS.md),
|
| 9 |
+
report (сводка), check (проверка задач без агента).
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
import re
|
| 18 |
+
import shutil
|
| 19 |
+
import subprocess
|
| 20 |
+
import sys
|
| 21 |
+
import time
|
| 22 |
+
from dataclasses import dataclass, field
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
|
| 25 |
+
REPO = Path(__file__).resolve().parent.parent
|
| 26 |
+
TASKS_FILE = Path(__file__).resolve().parent / "tasks.json"
|
| 27 |
+
# Артефакты держим вне %TEMP%\opencode: эту папку OpenCode чистит сам, и
|
| 28 |
+
# прогоны вместе с песочницей исчезали бы, не оставив следа.
|
| 29 |
+
OUT_ROOT = Path(
|
| 30 |
+
os.environ.get(
|
| 31 |
+
"EVAL_OUT",
|
| 32 |
+
str(Path(os.environ.get("LOCALAPPDATA", "")) / "Lumen" / "harness-eval"),
|
| 33 |
+
)
|
| 34 |
+
)
|
| 35 |
+
OPENCODE_DB = Path(os.environ.get("USERPROFILE", ".")) / ".local" / "share" / "opencode" / "opencode.db"
|
| 36 |
+
|
| 37 |
+
AGENT_MODEL = os.environ.get("EVAL_AGENT_MODEL", "opencode/glm-5.3-flash-free")
|
| 38 |
+
PROPOSER_MODEL = os.environ.get("EVAL_PROPOSER_MODEL", "google/gemini-3.5-flash")
|
| 39 |
+
AGENT_TIMEOUT = int(os.environ.get("EVAL_AGENT_TIMEOUT", "1200"))
|
| 40 |
+
|
| 41 |
+
# Команды, которые агент в песочнице запускать не должен: часть из них ломает
|
| 42 |
+
# песочницу, часть — хост (формат диска, удаление файлов, push в origin).
|
| 43 |
+
DENY_PATTERNS = {
|
| 44 |
+
"git push*": "deny",
|
| 45 |
+
"git remote*": "deny",
|
| 46 |
+
"git gc*": "deny",
|
| 47 |
+
"rm -rf *": "deny",
|
| 48 |
+
"rmdir*": "deny",
|
| 49 |
+
"del *": "deny",
|
| 50 |
+
"Remove-Item*": "deny",
|
| 51 |
+
"Move-Item*": "deny",
|
| 52 |
+
"format *": "deny",
|
| 53 |
+
"shutdown*": "deny",
|
| 54 |
+
"reg delete*": "deny",
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
# Признаки unix-команд в песочнице: хост под Windows, шелл — PowerShell.
|
| 58 |
+
UNIX_SHELL_PATTERNS = [
|
| 59 |
+
r"\bls -[a-zA-Z]",
|
| 60 |
+
r"\bcat \S",
|
| 61 |
+
r"\bgrep -[a-zA-Z]",
|
| 62 |
+
r"\bhead -",
|
| 63 |
+
r"\btail -",
|
| 64 |
+
r"\brm -rf",
|
| 65 |
+
r"\bchmod \+",
|
| 66 |
+
r"\bexport [A-Z_]+=",
|
| 67 |
+
]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@dataclass
|
| 71 |
+
class Task:
|
| 72 |
+
id: str
|
| 73 |
+
fix: str
|
| 74 |
+
tests: list[str]
|
| 75 |
+
subject: str
|
| 76 |
+
base: str = ""
|
| 77 |
+
|
| 78 |
+
def prompt(self) -> str:
|
| 79 |
+
return (
|
| 80 |
+
f"Задача: {self.subject}\n\n"
|
| 81 |
+
"В репозитории уже есть падающие тесты под это поведение. "
|
| 82 |
+
"Почини код так, чтобы все тесты проходили.\n"
|
| 83 |
+
"Тесты не менять. Работай по AGENTS.md."
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@dataclass
|
| 88 |
+
class RunResult:
|
| 89 |
+
task: str
|
| 90 |
+
variant: str
|
| 91 |
+
model: str
|
| 92 |
+
solved: bool = False
|
| 93 |
+
pre_fail: list[str] = field(default_factory=list)
|
| 94 |
+
post_fail: list[str] = field(default_factory=list)
|
| 95 |
+
target_tests: list[str] = field(default_factory=list)
|
| 96 |
+
target_failed: list[str] = field(default_factory=list)
|
| 97 |
+
new_failures: list[str] = field(default_factory=list)
|
| 98 |
+
pyflakes_ok: bool = True
|
| 99 |
+
pyflakes_out: str = ""
|
| 100 |
+
violations: dict = field(default_factory=dict)
|
| 101 |
+
final_message: str = ""
|
| 102 |
+
duration_s: float = 0.0
|
| 103 |
+
error: str = ""
|
| 104 |
+
transcript: str = ""
|
| 105 |
+
sandbox: str = ""
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def log(msg: str) -> None:
|
| 109 |
+
print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def run_cmd(args: list[str], cwd: Path | None = None, timeout: int = 600) -> subprocess.CompletedProcess:
|
| 113 |
+
return subprocess.run(
|
| 114 |
+
args,
|
| 115 |
+
cwd=str(cwd) if cwd else None,
|
| 116 |
+
capture_output=True,
|
| 117 |
+
text=True,
|
| 118 |
+
encoding="utf-8",
|
| 119 |
+
errors="replace",
|
| 120 |
+
timeout=timeout,
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def git(repo: Path, *args: str) -> str:
|
| 125 |
+
proc = run_cmd(["git", "-C", str(repo), *args])
|
| 126 |
+
if proc.returncode != 0:
|
| 127 |
+
raise RuntimeError(f"git {' '.join(args)} failed: {proc.stderr.strip()}")
|
| 128 |
+
return proc.stdout
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def find_cli() -> str:
|
| 132 |
+
env = os.environ.get("OPENCODE_CLI")
|
| 133 |
+
if env and Path(env).exists():
|
| 134 |
+
return env
|
| 135 |
+
local = Path(os.environ.get("LOCALAPPDATA", "")) / "Programs" / "@opencodedesktop" / "resources" / "opencode-cli.exe"
|
| 136 |
+
if local.exists():
|
| 137 |
+
return str(local)
|
| 138 |
+
found = shutil.which("opencode")
|
| 139 |
+
if found:
|
| 140 |
+
return found
|
| 141 |
+
raise RuntimeError("opencode CLI не найден: задай OPENCODE_CLI или проверь %LOCALAPPDATA%\\Programs\\@opencodedesktop")
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def load_tasks() -> list[Task]:
|
| 145 |
+
data = json.loads(TASKS_FILE.read_text(encoding="utf-8"))
|
| 146 |
+
tasks = [Task(**item) for item in data["tasks"]]
|
| 147 |
+
for task in tasks:
|
| 148 |
+
task.base = git(REPO, "rev-parse", f"{task.fix}^").strip()
|
| 149 |
+
return tasks
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def sandbox_config() -> dict:
|
| 153 |
+
return {
|
| 154 |
+
"$schema": "https://opencode.ai/config.json",
|
| 155 |
+
"share": "disabled",
|
| 156 |
+
"permission": {
|
| 157 |
+
"read": {"*.env": "deny", "*.env.*": "deny"},
|
| 158 |
+
"edit": {"*": "allow"},
|
| 159 |
+
"bash": {"*": "allow", **DENY_PATTERNS},
|
| 160 |
+
},
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def prepare(task: Task, sandbox: Path, agents_md: Path | None, apply_fix: bool = False) -> None:
|
| 165 |
+
"""Клонирует репозиторий на состояние до правки и ставит тесты из fix-коммита."""
|
| 166 |
+
if sandbox.exists():
|
| 167 |
+
shutil.rmtree(sandbox, ignore_errors=True)
|
| 168 |
+
sandbox.mkdir(parents=True)
|
| 169 |
+
run_cmd(["git", "clone", "--no-hardlinks", "--quiet", str(REPO), str(sandbox)])
|
| 170 |
+
git(sandbox, "checkout", "--quiet", "--detach", task.base)
|
| 171 |
+
git(sandbox, "remote", "remove", "origin")
|
| 172 |
+
git(sandbox, "config", "user.email", "eval@localhost")
|
| 173 |
+
git(sandbox, "config", "user.name", "harness-eval")
|
| 174 |
+
git(sandbox, "config", "commit.gpgsign", "false")
|
| 175 |
+
git(sandbox, "checkout", task.fix, "--", *task.tests)
|
| 176 |
+
if apply_fix:
|
| 177 |
+
source_files = source_files_of(task)
|
| 178 |
+
if source_files:
|
| 179 |
+
git(sandbox, "checkout", task.fix, "--", *source_files)
|
| 180 |
+
(sandbox / "opencode.json").write_text(
|
| 181 |
+
json.dumps(sandbox_config(), ensure_ascii=False, indent=2), encoding="utf-8"
|
| 182 |
+
)
|
| 183 |
+
target = sandbox / "AGENTS.md"
|
| 184 |
+
if agents_md and agents_md.exists():
|
| 185 |
+
shutil.copyfile(agents_md, target)
|
| 186 |
+
else:
|
| 187 |
+
shutil.copyfile(REPO / "AGENTS.md", target)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def source_files_of(task: Task) -> list[str]:
|
| 191 |
+
"""Файлы, которые менял fix-коммит, кроме тестов: без них задача не собирается."""
|
| 192 |
+
changed = git(REPO, "diff", "--name-only", task.base, task.fix).splitlines()
|
| 193 |
+
return [f for f in changed if f and not f.startswith("tests/")]
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def targets_cache_path() -> Path:
|
| 197 |
+
return OUT_ROOT / "targets.json"
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def compute_targets(task: Task) -> dict:
|
| 201 |
+
"""FAIL_TO_PASS: тесты, что падают на базе и проходят после правки.
|
| 202 |
+
|
| 203 |
+
Считаем эмпирически, а не по diff: fix-коммит мог менять ожидания существующих
|
| 204 |
+
тестов, а не только добавлять новые.
|
| 205 |
+
"""
|
| 206 |
+
cache = {}
|
| 207 |
+
cache_file = targets_cache_path()
|
| 208 |
+
if cache_file.exists():
|
| 209 |
+
cache = json.loads(cache_file.read_text(encoding="utf-8"))
|
| 210 |
+
key = f"{task.id}@{task.fix}"
|
| 211 |
+
if key in cache:
|
| 212 |
+
return cache[key]
|
| 213 |
+
|
| 214 |
+
work = OUT_ROOT / "targets"
|
| 215 |
+
sandbox = work / task.id
|
| 216 |
+
prepare(task, sandbox, None)
|
| 217 |
+
failed_base, _ = pytest_state(sandbox)
|
| 218 |
+
git(sandbox, "checkout", task.fix, "--", *source_files_of(task))
|
| 219 |
+
failed_fix, _ = pytest_state(sandbox)
|
| 220 |
+
shutil.rmtree(sandbox, ignore_errors=True)
|
| 221 |
+
|
| 222 |
+
entry = {
|
| 223 |
+
"fail_to_pass": sorted(failed_base - failed_fix),
|
| 224 |
+
"broken_at_fix": sorted(failed_base & failed_fix),
|
| 225 |
+
"failed_base": sorted(failed_base),
|
| 226 |
+
}
|
| 227 |
+
cache[key] = entry
|
| 228 |
+
cache_file.parent.mkdir(parents=True, exist_ok=True)
|
| 229 |
+
cache_file.write_text(json.dumps(cache, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 230 |
+
return entry
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def target_tests(task: Task) -> list[str]:
|
| 234 |
+
"""Тесты, добавленные fix-коммитом (по diff). Точный список падающих — compute_targets."""
|
| 235 |
+
diff = git(REPO, "diff", task.base, task.fix, "--", *task.tests)
|
| 236 |
+
ids: list[str] = []
|
| 237 |
+
current_file = ""
|
| 238 |
+
for line in diff.splitlines():
|
| 239 |
+
if line.startswith("+++ b/"):
|
| 240 |
+
current_file = line[6:].strip()
|
| 241 |
+
elif line.startswith("+") and not line.startswith("+++"):
|
| 242 |
+
match = re.match(r"\+\s*def (test_\w+)", line)
|
| 243 |
+
if match and current_file:
|
| 244 |
+
ids.append(f"{current_file}::{match.group(1)}")
|
| 245 |
+
return ids
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def pytest_state(sandbox: Path) -> tuple[set[str], str]:
|
| 249 |
+
proc = run_cmd([sys.executable, "-m", "pytest", "-q", "--tb=no", "-rf"], cwd=sandbox, timeout=900)
|
| 250 |
+
failed = set()
|
| 251 |
+
for line in proc.stdout.splitlines():
|
| 252 |
+
match = re.match(r"^(FAILED|ERROR)\s+(\S+)", line.strip())
|
| 253 |
+
if match:
|
| 254 |
+
failed.add(match.group(2))
|
| 255 |
+
return failed, proc.stdout[-4000:]
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def pyflakes_state(sandbox: Path) -> tuple[bool, str]:
|
| 259 |
+
# список модулей lumen_*.py собираем отдельно: гейт в CI так же собирает список
|
| 260 |
+
modules = sorted(p.name for p in sandbox.glob("lumen_*.py"))
|
| 261 |
+
proc = run_cmd(
|
| 262 |
+
[sys.executable, "-m", "pyflakes", "bot.py", "system_prompt.py", *modules], cwd=sandbox, timeout=300
|
| 263 |
+
)
|
| 264 |
+
return proc.returncode == 0, (proc.stdout + proc.stderr)[-2000:]
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def agent_env(sandbox: Path) -> dict:
|
| 268 |
+
env = dict(os.environ)
|
| 269 |
+
env["PIP_TARGET"] = str(sandbox / ".pip-target")
|
| 270 |
+
env["PIP_DISABLE_PIP_VERSION_CHECK"] = "1"
|
| 271 |
+
env["PYTHONDONTWRITEBYTECODE"] = "1"
|
| 272 |
+
return env
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def session_from_db(sandbox: Path, retries: int = 10) -> dict | None:
|
| 276 |
+
"""Достаёт сессию агента из базы OpenCode: лог в stdout может пропасть, база нет."""
|
| 277 |
+
import sqlite3
|
| 278 |
+
|
| 279 |
+
if not OPENCODE_DB.exists():
|
| 280 |
+
return None
|
| 281 |
+
target = str(sandbox).replace("\\", "/")
|
| 282 |
+
for attempt in range(retries):
|
| 283 |
+
try:
|
| 284 |
+
con = sqlite3.connect(f"file:{OPENCODE_DB}?mode=ro", uri=True)
|
| 285 |
+
cur = con.cursor()
|
| 286 |
+
row = cur.execute(
|
| 287 |
+
"select id from session_v2 where directory = ? order by time_created desc limit 1",
|
| 288 |
+
(target,),
|
| 289 |
+
).fetchone()
|
| 290 |
+
if row is None:
|
| 291 |
+
row = cur.execute(
|
| 292 |
+
"select id from session where directory = ? order by time_created desc limit 1",
|
| 293 |
+
(target,),
|
| 294 |
+
).fetchone()
|
| 295 |
+
if row is None:
|
| 296 |
+
con.close()
|
| 297 |
+
time.sleep(2)
|
| 298 |
+
continue
|
| 299 |
+
session_id = row[0]
|
| 300 |
+
messages = list(
|
| 301 |
+
cur.execute(
|
| 302 |
+
"select data from session_message where session_id=? order by seq", (session_id,)
|
| 303 |
+
)
|
| 304 |
+
)
|
| 305 |
+
con.close()
|
| 306 |
+
except sqlite3.Error:
|
| 307 |
+
time.sleep(2)
|
| 308 |
+
continue
|
| 309 |
+
if not messages:
|
| 310 |
+
time.sleep(2)
|
| 311 |
+
continue
|
| 312 |
+
|
| 313 |
+
tool_calls: list[dict] = []
|
| 314 |
+
final_text = ""
|
| 315 |
+
for (data,) in messages:
|
| 316 |
+
try:
|
| 317 |
+
obj = json.loads(data)
|
| 318 |
+
except json.JSONDecodeError:
|
| 319 |
+
continue
|
| 320 |
+
for item in obj.get("content") or []:
|
| 321 |
+
kind = item.get("type")
|
| 322 |
+
if kind == "text" and item.get("text"):
|
| 323 |
+
final_text = item["text"]
|
| 324 |
+
elif kind == "tool":
|
| 325 |
+
state = item.get("state") or {}
|
| 326 |
+
output = ""
|
| 327 |
+
for chunk in state.get("content") or []:
|
| 328 |
+
if isinstance(chunk, dict) and chunk.get("text"):
|
| 329 |
+
output += chunk["text"]
|
| 330 |
+
tool_calls.append(
|
| 331 |
+
{
|
| 332 |
+
"name": item.get("name"),
|
| 333 |
+
"input": state.get("input") or {},
|
| 334 |
+
"output": output[-4000:],
|
| 335 |
+
}
|
| 336 |
+
)
|
| 337 |
+
return {
|
| 338 |
+
"session_id": session_id,
|
| 339 |
+
"final_text": final_text,
|
| 340 |
+
"tool_calls": tool_calls,
|
| 341 |
+
"shell_commands": [
|
| 342 |
+
(call.get("input") or {}).get("command", "")
|
| 343 |
+
for call in tool_calls
|
| 344 |
+
if call.get("name") in ("shell", "bash")
|
| 345 |
+
],
|
| 346 |
+
}
|
| 347 |
+
return None
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
def keep_sandbox(sandbox: Path, kept: Path) -> dict:
|
| 351 |
+
"""Снимает слепок песочницы: после прогона содержимое могут снести."""
|
| 352 |
+
info = {"changed_files": [], "diff": ""}
|
| 353 |
+
if not sandbox.exists():
|
| 354 |
+
return info
|
| 355 |
+
try:
|
| 356 |
+
info["changed_files"] = [line for line in git(sandbox, "status", "--porcelain").splitlines() if line]
|
| 357 |
+
except RuntimeError:
|
| 358 |
+
info["changed_files"] = []
|
| 359 |
+
if kept.exists():
|
| 360 |
+
shutil.rmtree(kept, ignore_errors=True)
|
| 361 |
+
shutil.copytree(sandbox, kept, ignore=shutil.ignore_patterns(".pip-target"), dirs_exist_ok=True)
|
| 362 |
+
try:
|
| 363 |
+
info["diff"] = git(kept, "diff", "HEAD")
|
| 364 |
+
except RuntimeError:
|
| 365 |
+
info["diff"] = ""
|
| 366 |
+
return info
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def run_agent(sandbox: Path, prompt: str, model: str, transcript: Path, timeout: int) -> tuple[str, str]:
|
| 370 |
+
"""Гоняет агента в песочнице. Возвращает (последнее сообщение, путь к логу)."""
|
| 371 |
+
cli = find_cli()
|
| 372 |
+
args = [cli, "run", "--standalone", "--auto", "--model", model, "--format", "json", prompt]
|
| 373 |
+
with transcript.open("w", encoding="utf-8", errors="replace") as out:
|
| 374 |
+
proc = subprocess.Popen(
|
| 375 |
+
args,
|
| 376 |
+
cwd=str(sandbox),
|
| 377 |
+
stdout=out,
|
| 378 |
+
stderr=subprocess.STDOUT,
|
| 379 |
+
env=agent_env(sandbox),
|
| 380 |
+
text=True,
|
| 381 |
+
encoding="utf-8",
|
| 382 |
+
errors="replace",
|
| 383 |
+
)
|
| 384 |
+
try:
|
| 385 |
+
proc.wait(timeout=timeout)
|
| 386 |
+
except subprocess.TimeoutExpired:
|
| 387 |
+
subprocess.run(["taskkill", "/T", "/F", "/PID", str(proc.pid)], capture_output=True)
|
| 388 |
+
proc.wait(timeout=60)
|
| 389 |
+
session = session_from_db(sandbox)
|
| 390 |
+
if session:
|
| 391 |
+
final = session["final_text"]
|
| 392 |
+
else:
|
| 393 |
+
texts = []
|
| 394 |
+
if transcript.exists():
|
| 395 |
+
for line in transcript.read_text(encoding="utf-8", errors="replace").splitlines():
|
| 396 |
+
line = line.strip()
|
| 397 |
+
if not line.startswith("{"):
|
| 398 |
+
continue
|
| 399 |
+
try:
|
| 400 |
+
event = json.loads(line)
|
| 401 |
+
except json.JSONDecodeError:
|
| 402 |
+
continue
|
| 403 |
+
part = event.get("part") or {}
|
| 404 |
+
if part.get("type") == "text" and part.get("text"):
|
| 405 |
+
texts.append(part["text"])
|
| 406 |
+
final = texts[-1] if texts else ""
|
| 407 |
+
return final, str(transcript)
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def check_violations(session: dict | None, changed_files: list[str]) -> dict:
|
| 411 |
+
"""Грубые нарушения правил проекта: по командам агента и по изменённым файлам."""
|
| 412 |
+
commands = (session or {}).get("shell_commands") or []
|
| 413 |
+
joined = "\n".join(commands)
|
| 414 |
+
unix_hits = sorted({p for p in UNIX_SHELL_PATTERNS if re.search(p, joined)})
|
| 415 |
+
touched_tests = [f for f in changed_files if "tests/" in f]
|
| 416 |
+
return {
|
| 417 |
+
"tests_touched": touched_tests,
|
| 418 |
+
"unix_shell_commands": unix_hits,
|
| 419 |
+
"ran_pytest": "pytest" in joined,
|
| 420 |
+
"ran_pyflakes": "pyflakes" in joined,
|
| 421 |
+
"shell_calls": len(commands),
|
| 422 |
+
"changed_files": changed_files,
|
| 423 |
+
}
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def score(task: Task, result: RunResult, targets: list[str]) -> None:
|
| 427 |
+
result.target_tests = targets
|
| 428 |
+
result.target_failed = [
|
| 429 |
+
t for t in targets if any(f == t or f.startswith(t + "[") for f in result.post_fail)
|
| 430 |
+
]
|
| 431 |
+
result.new_failures = sorted(set(result.post_fail) - set(result.pre_fail))
|
| 432 |
+
result.solved = not result.target_failed and not result.new_failures
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
def cmd_run(args: argparse.Namespace) -> int:
|
| 436 |
+
tasks = {t.id: t for t in load_tasks()}
|
| 437 |
+
task = tasks[args.task]
|
| 438 |
+
out_dir = Path(args.out) if args.out else OUT_ROOT / time.strftime("%Y%m%d-%H%M%S")
|
| 439 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 440 |
+
sandbox = out_dir / f"sandbox-{task.id}-{args.variant}"
|
| 441 |
+
kept = out_dir / f"kept-{task.id}-{args.variant}"
|
| 442 |
+
agents_md = Path(args.agents_md) if args.agents_md else None
|
| 443 |
+
model = args.model or AGENT_MODEL
|
| 444 |
+
|
| 445 |
+
log(f"песочница {task.id} ({args.variant}) на {task.base[:8]}")
|
| 446 |
+
prepare(task, sandbox, agents_md)
|
| 447 |
+
|
| 448 |
+
pre_fail, _ = pytest_state(sandbox)
|
| 449 |
+
targets = compute_targets(task)["fail_to_pass"]
|
| 450 |
+
log(f"до агента падают {len(pre_fail)} тестов, целевых (FAIL_TO_PASS): {len(targets)}")
|
| 451 |
+
|
| 452 |
+
transcript = out_dir / f"{task.id}.{args.variant}.jsonl"
|
| 453 |
+
log(f"агент: {model}, таймаут {AGENT_TIMEOUT}с")
|
| 454 |
+
started = time.time()
|
| 455 |
+
final, _ = run_agent(sandbox, task.prompt(), model, transcript, AGENT_TIMEOUT)
|
| 456 |
+
duration = round(time.time() - started, 1)
|
| 457 |
+
|
| 458 |
+
# Слепок снимаем сразу: содержимое песочницы могут снести (чистка temp, OpenCode).
|
| 459 |
+
snapshot = keep_sandbox(sandbox, kept)
|
| 460 |
+
session = session_from_db(sandbox)
|
| 461 |
+
if session:
|
| 462 |
+
(out_dir / f"{task.id}.{args.variant}.session.json").write_text(
|
| 463 |
+
json.dumps(session, ensure_ascii=False, indent=2), encoding="utf-8"
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
result = RunResult(
|
| 467 |
+
task=task.id,
|
| 468 |
+
variant=args.variant,
|
| 469 |
+
model=model,
|
| 470 |
+
duration_s=duration,
|
| 471 |
+
final_message=final,
|
| 472 |
+
transcript=str(transcript),
|
| 473 |
+
sandbox=str(sandbox),
|
| 474 |
+
)
|
| 475 |
+
result.post_fail, post_out = pytest_state(kept)
|
| 476 |
+
result.pyflakes_ok, result.pyflakes_out = pyflakes_state(kept)
|
| 477 |
+
result.violations = check_violations(session, snapshot["changed_files"])
|
| 478 |
+
result.pre_fail = sorted(pre_fail)
|
| 479 |
+
score(task, result, targets)
|
| 480 |
+
|
| 481 |
+
payload = {
|
| 482 |
+
"task": task.id,
|
| 483 |
+
"variant": args.variant,
|
| 484 |
+
"model": model,
|
| 485 |
+
"solved": result.solved,
|
| 486 |
+
"pre_fail": result.pre_fail,
|
| 487 |
+
"post_fail": sorted(result.post_fail),
|
| 488 |
+
"target_tests": result.target_tests,
|
| 489 |
+
"target_failed": result.target_failed,
|
| 490 |
+
"new_failures": result.new_failures,
|
| 491 |
+
"pyflakes_ok": result.pyflakes_ok,
|
| 492 |
+
"violations": result.violations,
|
| 493 |
+
"final_message": result.final_message,
|
| 494 |
+
"session_id": (session or {}).get("session_id", ""),
|
| 495 |
+
"duration_s": duration,
|
| 496 |
+
"diff": snapshot["diff"][-8000:],
|
| 497 |
+
"post_pytest_tail": post_out[-1500:],
|
| 498 |
+
}
|
| 499 |
+
result_file = out_dir / f"{task.id}.{args.variant}.json"
|
| 500 |
+
result_file.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 501 |
+
log(f"итог: {'решено' if result.solved else 'не решено'} ({duration}с) -> {result_file}")
|
| 502 |
+
check_repo_untouched()
|
| 503 |
+
return 0
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
def check_repo_untouched() -> None:
|
| 507 |
+
"""Сторож: настоящий репозиторий не должен меняться во время прогона."""
|
| 508 |
+
try:
|
| 509 |
+
status = git(REPO, "status", "--porcelain")
|
| 510 |
+
except RuntimeError as exc:
|
| 511 |
+
log(f"ВНИМАНИЕ: не смог проверить состояние репозитория: {exc}")
|
| 512 |
+
return
|
| 513 |
+
unexpected = [line for line in status.splitlines() if line and not line.startswith("?? eval/")]
|
| 514 |
+
if unexpected:
|
| 515 |
+
log(f"ВНИМАНИЕ: репозиторий изменён во время прогона: {unexpected[:5]}")
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
def cmd_check(args: argparse.Namespace) -> int:
|
| 519 |
+
"""Проверяет, что задачи валидны: на базе падают только целевые тесты."""
|
| 520 |
+
out_dir = Path(args.out) if args.out else OUT_ROOT / "check"
|
| 521 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 522 |
+
for task in load_tasks():
|
| 523 |
+
entry = compute_targets(task)
|
| 524 |
+
broken = entry["broken_at_fix"]
|
| 525 |
+
targets = entry["fail_to_pass"]
|
| 526 |
+
status = "ok" if targets and not broken else "проблема"
|
| 527 |
+
log(f"{task.id}: {status}; целевых {len(targets)}, ломаных даже после правки {len(broken)}")
|
| 528 |
+
for item in broken[:5]:
|
| 529 |
+
log(f" ломается и после правки: {item}")
|
| 530 |
+
if not targets:
|
| 531 |
+
log(" на базе нет падающих целевых тестов — задача негодная")
|
| 532 |
+
return 0
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
def cmd_propose(args: argparse.Namespace) -> int:
|
| 536 |
+
"""Собирает кандидатную правку AGENTS.md по провалам базовых прогонов."""
|
| 537 |
+
base_dir = Path(args.base_dir)
|
| 538 |
+
runs = sorted(base_dir.glob("*.base.json"))
|
| 539 |
+
if not runs:
|
| 540 |
+
log(f"нет базовых прогонов в {base_dir}")
|
| 541 |
+
return 1
|
| 542 |
+
work = base_dir / "propose"
|
| 543 |
+
if work.exists():
|
| 544 |
+
shutil.rmtree(work)
|
| 545 |
+
work.mkdir(parents=True)
|
| 546 |
+
shutil.copyfile(REPO / "AGENTS.md", work / "AGENTS.md")
|
| 547 |
+
reports = work / "failures"
|
| 548 |
+
reports.mkdir()
|
| 549 |
+
for run_file in runs:
|
| 550 |
+
data = json.loads(run_file.read_text(encoding="utf-8"))
|
| 551 |
+
if data.get("solved") and not data.get("violations", {}).get("tests_touched"):
|
| 552 |
+
continue
|
| 553 |
+
body = [
|
| 554 |
+
f"Задача: {data['task']}",
|
| 555 |
+
f"Целевые тесты: {', '.join(data.get('target_tests') or [])}",
|
| 556 |
+
f"Целевые тесты после прогона упали: {', '.join(data.get('target_failed') or [])}",
|
| 557 |
+
f"Новые падения: {', '.join(data.get('new_failures') or [])}",
|
| 558 |
+
f"Нарушения правил: {json.dumps(data.get('violations') or {}, ensure_ascii=False)}",
|
| 559 |
+
f"pyflakes: {'ok' if data.get('pyflakes_ok') else 'ошибка'}",
|
| 560 |
+
"",
|
| 561 |
+
"Последнее сообщение агента:",
|
| 562 |
+
(data.get("final_message") or "")[:3000],
|
| 563 |
+
"",
|
| 564 |
+
"Падения тестов после прогона:",
|
| 565 |
+
"\n".join(data.get("post_fail") or [])[:2000],
|
| 566 |
+
]
|
| 567 |
+
(reports / f"{data['task']}.md").write_text("\n".join(body), encoding="utf-8")
|
| 568 |
+
if not any(reports.iterdir()):
|
| 569 |
+
log("базовые прогоны без провалов — править нечего")
|
| 570 |
+
return 0
|
| 571 |
+
|
| 572 |
+
prompt = (
|
| 573 |
+
"Ты редактор правил проекта. Посмотри AGENTS.md и отчёты о провалах в папке failures.\n"
|
| 574 |
+
"Составь новый AGENTS.md: добавь правила, которые предотвратили бы эти провалы "
|
| 575 |
+
"(конкретные, в стиле существующих разделов).\n"
|
| 576 |
+
"Существующие правила не удаляй и не переписывай, только дополняй.\n"
|
| 577 |
+
"Сохрани результат в файл AGENTS.candidate.md в этой же папке. Больше ничего не меняй."
|
| 578 |
+
)
|
| 579 |
+
transcript = base_dir / "propose.jsonl"
|
| 580 |
+
log(f"модель-редактор: {args.model}")
|
| 581 |
+
run_agent(work, prompt, args.model, transcript, AGENT_TIMEOUT)
|
| 582 |
+
candidate = work / "AGENTS.candidate.md"
|
| 583 |
+
if not candidate.exists():
|
| 584 |
+
log("модель не создала AGENTS.candidate.md")
|
| 585 |
+
return 1
|
| 586 |
+
|
| 587 |
+
original = (REPO / "AGENTS.md").read_text(encoding="utf-8")
|
| 588 |
+
new = candidate.read_text(encoding="utf-8")
|
| 589 |
+
missing = [line for line in original.splitlines() if line.strip() and line not in new]
|
| 590 |
+
diff = run_cmd(
|
| 591 |
+
["git", "diff", "--no-index", "--unified=3", str(REPO / "AGENTS.md"), str(candidate)], cwd=REPO
|
| 592 |
+
)
|
| 593 |
+
diff_text = diff.stdout or diff.stderr
|
| 594 |
+
(base_dir / "agents_candidate.diff").write_text(diff_text, encoding="utf-8")
|
| 595 |
+
(base_dir / "AGENTS.candidate.md").write_text(new, encoding="utf-8")
|
| 596 |
+
log(f"кандидат записан: {base_dir / 'AGENTS.candidate.md'}")
|
| 597 |
+
log(f"удалённых строк из оригинала: {len(missing)}")
|
| 598 |
+
for line in missing[:10]:
|
| 599 |
+
log(f" пропала строка: {line[:90]}")
|
| 600 |
+
return 0
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
def cmd_report(args: argparse.Namespace) -> int:
|
| 604 |
+
out_dir = Path(args.out) if args.out else OUT_ROOT
|
| 605 |
+
files = sorted(out_dir.glob("*.json"))
|
| 606 |
+
files = [f for f in files if f.name not in {"propose.json"}]
|
| 607 |
+
rows = []
|
| 608 |
+
for file in files:
|
| 609 |
+
try:
|
| 610 |
+
data = json.loads(file.read_text(encoding="utf-8"))
|
| 611 |
+
except json.JSONDecodeError:
|
| 612 |
+
continue
|
| 613 |
+
if "task" not in data or "variant" not in data:
|
| 614 |
+
continue
|
| 615 |
+
rows.append(data)
|
| 616 |
+
by_task: dict[str, dict[str, dict]] = {}
|
| 617 |
+
for row in rows:
|
| 618 |
+
by_task.setdefault(row["task"], {})[row["variant"]] = row
|
| 619 |
+
|
| 620 |
+
lines = [
|
| 621 |
+
"# Harness-eval: базовый AGENTS.md против кандидатного",
|
| 622 |
+
"",
|
| 623 |
+
f"Модель агента: {AGENT_MODEL} · Модель-редактор: {PROPOSER_MODEL}",
|
| 624 |
+
"",
|
| 625 |
+
"| Задача | База | Кандидат | Тесты (база) | Тесты (кандидат) | Нарушения (база) | Нарушения (кандидат) |",
|
| 626 |
+
"|---|---|---|---|---|---|---|",
|
| 627 |
+
]
|
| 628 |
+
base_score = cand_score = 0
|
| 629 |
+
for task_id, variants in sorted(by_task.items()):
|
| 630 |
+
base = variants.get("base", {})
|
| 631 |
+
cand = variants.get("candidate", {})
|
| 632 |
+
base_ok = bool(base.get("solved"))
|
| 633 |
+
cand_ok = bool(cand.get("solved"))
|
| 634 |
+
base_score += base_ok
|
| 635 |
+
cand_score += cand_ok
|
| 636 |
+
lines.append(
|
| 637 |
+
f"| {task_id} | {'решено' if base_ok else 'нет'} | "
|
| 638 |
+
f"{'решено' if cand_ok else 'нет'} | {len(base.get('target_failed') or [])} | "
|
| 639 |
+
f"{len(cand.get('target_failed') or [])} | "
|
| 640 |
+
f"{len(base.get('violations', {}).get('tests_touched') or [])} | "
|
| 641 |
+
f"{len(cand.get('violations', {}).get('tests_touched') or [])} |"
|
| 642 |
+
)
|
| 643 |
+
lines += ["", f"Решено базой: {base_score}/{len(by_task)} · Кандидатом: {cand_score}/{len(by_task)}", ""]
|
| 644 |
+
text = "\n".join(lines)
|
| 645 |
+
print(text)
|
| 646 |
+
if args.out:
|
| 647 |
+
(Path(args.out) / "report.md").write_text(text, encoding="utf-8")
|
| 648 |
+
return 0
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
def cmd_probe(args: argparse.Namespace) -> int:
|
| 652 |
+
"""Разведка: какие кандидаты в истории дают годные задачи."""
|
| 653 |
+
for spec in args.commits:
|
| 654 |
+
fix, _, files = spec.partition(":")
|
| 655 |
+
tests = files.split(";") if files else []
|
| 656 |
+
task = Task(id=f"probe-{fix}", fix=fix.strip(), tests=[t for t in tests if t], subject="probe")
|
| 657 |
+
task.base = git(REPO, "rev-parse", f"{task.fix}^").strip()
|
| 658 |
+
entry = compute_targets(task)
|
| 659 |
+
log(
|
| 660 |
+
f"{fix}: целевых {len(entry['fail_to_pass'])}, "
|
| 661 |
+
f"ломаных после правки {len(entry['broken_at_fix'])} -> {entry['fail_to_pass']}"
|
| 662 |
+
)
|
| 663 |
+
return 0
|
| 664 |
+
|
| 665 |
+
|
| 666 |
+
def main() -> int:
|
| 667 |
+
if hasattr(sys.stdout, "reconfigure"):
|
| 668 |
+
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
| 669 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 670 |
+
sub = parser.add_subparsers(dest="cmd", required=True)
|
| 671 |
+
|
| 672 |
+
run = sub.add_parser("run", help="прогнать одну задачу одним вариантом AGENTS.md")
|
| 673 |
+
run.add_argument("--task", required=True)
|
| 674 |
+
run.add_argument("--variant", default="base", choices=["base", "candidate"])
|
| 675 |
+
run.add_argument("--agents-md", default=None, help="файл AGENTS.md (кандидат)")
|
| 676 |
+
run.add_argument("--model", default=None)
|
| 677 |
+
run.add_argument("--out", default=None)
|
| 678 |
+
run.set_defaults(func=cmd_run)
|
| 679 |
+
|
| 680 |
+
check = sub.add_parser("check", help="проверить, что задачи валидны на базе")
|
| 681 |
+
check.add_argument("--out", default=None)
|
| 682 |
+
check.set_defaults(func=cmd_check)
|
| 683 |
+
|
| 684 |
+
probe = sub.add_parser("probe", help="разведка кандидатов из истории")
|
| 685 |
+
probe.add_argument("commits", nargs="+", help="<fix-sha>[:<tests>;...>]")
|
| 686 |
+
probe.set_defaults(func=cmd_probe)
|
| 687 |
+
|
| 688 |
+
propose = sub.add_parser("propose", help="собрать кандидатную правку AGENTS.md")
|
| 689 |
+
propose.add_argument("--base-dir", required=True)
|
| 690 |
+
propose.add_argument("--model", default=PROPOSER_MODEL)
|
| 691 |
+
propose.set_defaults(func=cmd_propose)
|
| 692 |
+
|
| 693 |
+
report = sub.add_parser("report", help="сводка по прогонам")
|
| 694 |
+
report.add_argument("--out", default=None)
|
| 695 |
+
report.set_defaults(func=cmd_report)
|
| 696 |
+
|
| 697 |
+
args = parser.parse_args()
|
| 698 |
+
return args.func(args)
|
| 699 |
+
|
| 700 |
+
|
| 701 |
+
if __name__ == "__main__":
|
| 702 |
+
sys.exit(main())
|
eval/tasks.json
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_comment": "Задачи взяты из истории репозитория: fix-коммит меняет код и тесты. Песочница собирается на fix^ (код до правки) + тесты из fix, поэтому целевые тесты падают, а остальные проходят. Целевые (FAIL_TO_PASS) считаются эмпирически: harness_eval.py compute_targets.",
|
| 3 |
+
"tasks": [
|
| 4 |
+
{
|
| 5 |
+
"id": "format-newlines-br",
|
| 6 |
+
"fix": "aa3af88",
|
| 7 |
+
"tests": ["tests/test_lumen_formatting.py"],
|
| 8 |
+
"subject": "Convert newlines to br in rich path so lists stop collapsing"
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"id": "format-table-separator-bound",
|
| 12 |
+
"fix": "e89951a",
|
| 13 |
+
"tests": ["tests/test_lumen_formatting.py"],
|
| 14 |
+
"subject": "Bound table separator match length for pathological lines"
|
| 15 |
+
},
|
| 16 |
+
{
|
| 17 |
+
"id": "presplit-glued-bullets",
|
| 18 |
+
"fix": "1dfad36",
|
| 19 |
+
"tests": ["tests/test_lumen_formatting.py"],
|
| 20 |
+
"subject": "Presplit glued bullets before chunking so lists survive cutting"
|
| 21 |
+
},
|
| 22 |
+
{
|
| 23 |
+
"id": "state-corrupt-index",
|
| 24 |
+
"fix": "2111b5d",
|
| 25 |
+
"tests": ["tests/test_bot_state.py"],
|
| 26 |
+
"subject": "Fail closed when the chat index is corrupt without legacy"
|
| 27 |
+
},
|
| 28 |
+
{
|
| 29 |
+
"id": "state-dirty-counters",
|
| 30 |
+
"fix": "909b840",
|
| 31 |
+
"tests": ["tests/test_bot_state.py"],
|
| 32 |
+
"subject": "Guard state dirty flags with generation counters"
|
| 33 |
+
},
|
| 34 |
+
{
|
| 35 |
+
"id": "tiktok-dns-private-ips",
|
| 36 |
+
"fix": "6309600",
|
| 37 |
+
"tests": ["tests/test_bot_tiktok.py"],
|
| 38 |
+
"subject": "Filter non-public IPs on every DNS resolve"
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"id": "streaming-catchup-throttle",
|
| 42 |
+
"fix": "c019423",
|
| 43 |
+
"tests": ["tests/test_bot_streaming.py"],
|
| 44 |
+
"subject": "Throttle streaming catch-up edits and pace chunk sends"
|
| 45 |
+
}
|
| 46 |
+
]
|
| 47 |
+
}
|