ckb/tests/run_evals.py
Michał Kopeć dad2264a65 Template 1.26.0: release 3 batch 3, capture module, skill evals, multi-agent docs
- F11 new opt-in module `capture` (skill ckb-capture, capture_url.py):
  stdlib fetch with readable-text extraction, Wayback only over a failed
  or thinner live page, --from-file for the agent's own fetch, PDFs saved
  as files, --media via yt-dlp with consent, untrusted: true marking,
  dedup at capture time; dedup_inbox.py now compares source_url (D-0017)
- F22 tests/run_evals.py (list/prepare/check/validate) and five
  structural eval cases; reference run for ckb-decide/record
- F18 manual section with untested setups for Codex CLI, Cursor,
  OpenCode and Gemini CLI, plus the Claude Code-only feature table;
  AGENTS.md tells agents without skill loading to read SKILL.md

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 20:44:05 +01:00

174 lines
7.1 KiB
Python

#!/usr/bin/env python3
"""Skill evals: structural checks of what an agent run left behind.
run_evals.py list # every case, with its prompt
run_evals.py prepare CASE DIR # copy the fixture + setup into DIR, print the prompt
run_evals.py check CASE DIR # score DIR after the agent ran there; exit 1 on a failure
run_evals.py validate # every case parses and names known assertion kinds
CASE is a path under tests/evals/, e.g. `ckb-decide/record`. The agent run
itself is manual or a CI job with a token budget: open DIR in the agent and
give it the prompt. Model output varies, so every assertion is structural —
files created or moved, frontmatter values, log entries, pages left alone,
lint checks clean — never the wording.
Assertion kinds (each one an object in the case's "assert" list):
file_exists: GLOB file_absent: GLOB
file_contains: {path: GLOB, regex: RE} some matching file matches RE
file_lacks: {path: GLOB, regex: RE} no matching file matches RE
frontmatter: {path: GLOB, keys: {k: v}} some matching file has every key;
v is exact, "*" (present) or "~RE"
unchanged: GLOB same bytes as when prepared
lint_clean: [check, ...] lint_report.py --json: these wiki checks have no findings
Python 3.8+, standard library only.
"""
import hashlib
import json
import re
import shutil
import subprocess
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
EVALS = HERE / "evals"
FIXTURES = HERE / "fixtures"
LINT = HERE.parent / ".agents" / "skills" / "ckb-lint" / "scripts" / "lint_report.py"
BASELINE = ".eval-baseline.json"
KINDS = {"file_exists", "file_absent", "file_contains", "file_lacks", "frontmatter", "unchanged", "lint_clean"}
def load(case):
path = EVALS / case / "case.json"
if not path.is_file():
sys.exit(f"error: no case at {path}")
return json.loads(path.read_text(encoding="utf-8"))
def cases():
return sorted(p.parent.relative_to(EVALS).as_posix() for p in EVALS.glob("*/*/case.json"))
def files(root, pattern):
return sorted(p for p in root.glob(pattern) if p.is_file() and BASELINE not in p.name)
def frontmatter(text):
if not text.startswith("---\n"):
return {}
end = text.find("\n---\n", 4)
out = {}
for line in text[4:end if end != -1 else 0].split("\n"):
k, sep, v = line.partition(":")
if sep and not line[:1].isspace():
out[k.strip()] = v.strip().strip("\"'")
return out
def value_ok(want, got):
if got is None:
return False
if want == "*":
return True
if isinstance(want, str) and want.startswith("~"):
return re.search(want[1:], got) is not None
return str(want) == got
def prepare(case, target):
c, root = load(case), Path(target).resolve()
if root.exists() and any(root.iterdir()):
sys.exit(f"error: {root} is not empty")
shutil.copytree(FIXTURES / c["fixture"], root, dirs_exist_ok=True)
for step in c.get("setup", []):
f = root / step["write"]
f.parent.mkdir(parents=True, exist_ok=True)
f.write_text(step["content"], encoding="utf-8")
base = {p.relative_to(root).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest()
for p in root.rglob("*") if p.is_file()}
(root / BASELINE).write_text(json.dumps(base, indent=1), encoding="utf-8")
print(f"prepared {root} from fixtures/{c['fixture']}\nprompt ({c['skill']}):\n\n{c['prompt']}")
def check(case, target):
c, root = load(case), Path(target).resolve()
base = json.loads((root / BASELINE).read_text(encoding="utf-8")) if (root / BASELINE).is_file() else {}
lint = None
results = []
for a in c["assert"]:
(kind, arg), = a.items()
if kind == "file_exists":
ok, why = bool(files(root, arg)), arg
elif kind == "file_absent":
ok, why = not files(root, arg), arg
elif kind in ("file_contains", "file_lacks"):
hit = any(re.search(arg["regex"], f.read_text(encoding="utf-8", errors="replace"), re.M) for f in files(root, arg["path"]))
ok, why = (hit if kind == "file_contains" else not hit), f"{arg['path']} /{arg['regex']}/"
elif kind == "frontmatter":
ok = any(all(value_ok(v, frontmatter(f.read_text(encoding="utf-8", errors="replace")).get(k)) for k, v in arg["keys"].items())
for f in files(root, arg["path"]))
why = f"{arg['path']} {arg['keys']}"
elif kind == "unchanged":
bad = [f.relative_to(root).as_posix() for f in files(root, arg)
if base.get(f.relative_to(root).as_posix()) != hashlib.sha256(f.read_bytes()).hexdigest()]
gone = [p for p in base if Path(p).match(arg) and not (root / p).exists()]
ok, why = not bad and not gone, arg + (f" (changed: {', '.join(bad + gone)})" if bad or gone else "")
elif kind == "lint_clean":
if lint is None:
out = subprocess.run([sys.executable, "-I", str(LINT), "--json", "--scope", "wiki"], cwd=str(root),
capture_output=True, text=True).stdout
lint = json.loads(out)["trees"][0]
dirty = {k: lint.get(k, []) for k in arg if lint.get(k)}
ok, why = not dirty, ", ".join(arg) + (f" ({dirty})" if dirty else "")
else:
ok, why = False, f"unknown assertion kind {kind}"
results.append((ok, kind, why))
for ok, kind, why in results:
print(f"{'PASS' if ok else 'FAIL'} {kind}: {why}")
passed = sum(ok for ok, _, _ in results)
print(f"{case}: {passed}/{len(results)} passed")
return 0 if passed == len(results) else 1
def validate():
problems = []
for case in cases():
try:
c = load(case)
except ValueError as e:
problems.append(f"{case}: invalid JSON ({e})")
continue
for key in ("skill", "fixture", "prompt", "assert"):
if key not in c:
problems.append(f"{case}: missing `{key}`")
if not (FIXTURES / c.get("fixture", "?")).is_dir():
problems.append(f"{case}: fixture `{c.get('fixture')}` does not exist")
for a in c.get("assert", []):
if not isinstance(a, dict) or len(a) != 1 or next(iter(a)) not in KINDS:
problems.append(f"{case}: bad assertion {a}")
for p in problems:
print(p)
print(f"evals: {len(cases())} case(s), {len(problems)} problem(s)")
return 1 if problems else 0
def main(argv):
if not argv or argv[0] not in ("list", "prepare", "check", "validate"):
print(__doc__)
return 2
if argv[0] == "list":
for case in cases():
print(f"{case}: {load(case)['prompt'].splitlines()[0][:90]}")
return 0
if argv[0] == "validate":
return validate()
if len(argv) != 3:
sys.exit(f"usage: run_evals.py {argv[0]} CASE DIR")
if argv[0] == "prepare":
prepare(argv[1], argv[2])
return 0
return check(argv[1], argv[2])
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))