graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(eval): DeepSWE-shaped swe suite plus RSS/CPU metrics
Cursor Agent9bac6a16dd95
diff --git a/docs/adr/0022-rlm-is-opt-in-speculative-ptc.md b/docs/adr/0022-rlm-is-opt-in-speculative-ptc.mdindex 15bed296..2dd0ecba 100644--- a/docs/adr/0022-rlm-is-opt-in-speculative-ptc.md+++ b/docs/adr/0022-rlm-is-opt-in-speculative-ptc.md@@ -75,11 +75,19 @@ regression* without a catalog tax. Per-task swings are one-rep variance.joins binds. A short system note is spliced only while the flag is on sothe folded spec is discoverable without paying its schema.- Scatter-gather tasks live in the `rlm` eval suite (`graff-evals/run.py- --suite rlm`). Default `--suite all` runs core + rlm. Measured 2026-08-25- on grok-4.6 (one rep): both **4/4**, native **86.8s / 53564 in**, `--rlm`- **23.7s / 54496 in**. `needle-files` (62.8s → 5.6s) dominates the wall- delta; `multi-read` was 1s slower on `--rlm` (one-rep noise). Extra input- is the system note (~900 tokens across four tasks), not a catalog schema.+ --suite rlm`). Default `--suite all` runs core + rlm + swe. Measured+ 2026-08-25 on grok-4.6 (one rep): both **4/4**, native **86.8s / 53564+ in**, `--rlm` **23.7s / 54496 in**. `needle-files` (62.8s → 5.6s)+ dominates the wall delta; `multi-read` was 1s slower on `--rlm`+ (one-rep noise). Extra input is the system note (~900 tokens across+ four tasks), not a catalog schema.+- DeepSWE-shaped multi-file bugfixes live in `--suite swe`, distilled+ from [deepswe.datacurve.ai/run](https://deepswe.datacurve.ai/run)+ (cookie-store, label-sort, config-parse, map-conflict, json-stream,+ validated). Held-out checks stay in `graff-evals/hidden/` so the+ agent cannot read them. The runner records peak RSS, child CPU, and+ first-output latency next to wall and tokens. Full Harbor/Pier/Docker+ DeepSWE is out of scope; this suite is the graff-shaped subset.Graff's `--rlm` is a Zig subset of [Prime Agent's RLM programmingmodel](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/docs/rlm.md),diff --git a/graff-evals/README.md b/graff-evals/README.mdindex 2f216673..e649c2cb 100644--- a/graff-evals/README.md+++ b/graff-evals/README.md@@ -2,12 +2,29 @@A self-contained eval environment for coding harnesses: run any model throughany harness on a fixed task suite and get pass rate, wall time, first-output-latency, and token usage side by side.+latency, peak RSS, CPU, and token usage side by side.-Every task is one JSON file in `tasks/` — fixture files inline, a prompt, and-a deterministic shell `check` that decides pass/fail inside the sandbox. No-network is needed to author or verify tasks; only the harness under test-spends model calls.+Every task is one JSON file in `tasks/` — fixture files inline or via+`files_dir`, a prompt, and a deterministic shell `check` that decides+pass/fail inside the sandbox. Held-out checks live in `hidden/` and are+injected through `$TASK_ROOT` after the harness exits (the agent never+sees them). No network is needed to author or verify tasks; only the+harness under test spends model calls.++## Suites++`--suite` selects which tasks run (`all` is the default):++| suite | what it measures |+|---|---|+| `core` | sequential single-file work (instruction, debug, git, schema, …) |+| `rlm` | scatter-gather / multi-file reads (where `--rlm` can overlap) |+| `swe` | DeepSWE-shaped multi-file bugfixes, distilled from [deepswe.datacurve.ai/run](https://deepswe.datacurve.ai/run) (no Harbor/Docker) |++```sh+./run.py --suite swe --harness graff-dev,graff-dev-rlm --model grok-4.6+./run.py --suite core,rlm,swe --harness graff-dev,graff-dev-rlm+```## Run it@@ -52,11 +69,11 @@ Add a harness by adding an entry; add a model by passing `--model`.## Tasks-12 tasks across categories: instruction-following, debugging, shell, data-(JSON/CSV), text extraction, refactoring, test-writing, git, long-context-recall, structured output, and code comprehension. The check runs in the-sandbox with `$ANSWER_FILE` pointing at the captured final answer, so checks-can assert on the answer text and on filesystem/git state.+Tasks span instruction-following, debugging, shell, data (JSON/CSV), text+extraction, refactoring, test-writing, git, long-context recall, structured+output, scatter-gather, and DeepSWE-shaped SWE fixes. The check runs in the+sandbox with `$ANSWER_FILE` pointing at the captured final answer and+`$TASK_ROOT` pointing at `graff-evals/` for held-out scripts.Authoring rules that keep results comparable:diff --git a/graff-evals/fixtures/config-parse/SPEC.md b/graff-evals/fixtures/config-parse/SPEC.mdnew file mode 100644index 00000000..534a7eaf--- /dev/null+++ b/graff-evals/fixtures/config-parse/SPEC.md@@ -0,0 +1,24 @@+# Config file parsing (DeepSWE `cliffy-config-file-parsing`, distilled)++`config.py` must expose `load_config(name, search_paths=None, formats=None,+merge_configs=False, cli=None, env=None) -> dict`.++Default `formats` is `[".json", ".rc"]`. Default `search_paths` is `["."]`.+For each search path, look for `{name}.json` then `.{name}rc` (for `.rc`).++`.json` is a JSON object. Nested objects flatten with dots+(`{"db": {"host": "x"}}` → `{"db.host": "x"}`). Kebab-case keys become+camelCase (`retry-count` → `retryCount`).++`.rc` is `key=value` per line. `#` comments and blank lines are ignored.+Double-quoted values keep spaces. `true`/`false` become bools; integer+strings become ints.++When `merge_configs` is false, use only the **first** matching file.+When true, merge every match; **earlier search paths win**.++Precedence: CLI overrides env overrides config. Boolean `false` and+numeric `0` are valid values (do not treat them as missing).++Unknown keys stay in the dict (no validation in this distillation).+Raise `ConfigParseError` on malformed JSON/RC.diff --git a/graff-evals/fixtures/config-parse/config.py b/graff-evals/fixtures/config-parse/config.pynew file mode 100644index 00000000..996a328f--- /dev/null+++ b/graff-evals/fixtures/config-parse/config.py@@ -0,0 +1,89 @@+"""Config loader — incomplete. Fix the SPEC.md contract."""+import json+import os+++class ConfigParseError(Exception):+ pass+++def _camel(key):+ # BUG: kebab-case is left as-is+ return key+++def _flatten(obj, prefix=""):+ out = {}+ if not isinstance(obj, dict):+ return {prefix: obj} if prefix else obj+ for k, v in obj.items():+ nk = _camel(k)+ path = f"{prefix}.{nk}" if prefix else nk+ if isinstance(v, dict):+ out.update(_flatten(v, path))+ else:+ out[path] = v+ return out+++def _parse_rc(text):+ out = {}+ for line in text.splitlines():+ # BUG: comments are not ignored+ if not line.strip():+ continue+ if "=" not in line:+ raise ConfigParseError("rc")+ k, v = line.split("=", 1)+ k = _camel(k.strip())+ v = v.strip()+ if len(v) >= 2 and v[0] == '"' and v[-1] == '"':+ v = v[1:-1]+ elif v in ("true", "false"):+ v = v == "true"+ else:+ try:+ v = int(v)+ except ValueError:+ pass+ out[k] = v+ return out+++def load_config(name, search_paths=None, formats=None, merge_configs=False, cli=None, env=None):+ search_paths = search_paths or ["."]+ formats = formats or [".json", ".rc"]+ found = []+ for path in search_paths:+ for fmt in formats:+ if fmt == ".json":+ fp = os.path.join(path, f"{name}.json")+ elif fmt == ".rc":+ fp = os.path.join(path, f".{name}rc")+ else:+ fp = os.path.join(path, f"{name}{fmt}")+ if os.path.isfile(fp):+ found.append(fp)+ if not found:+ data = {}+ else:+ # BUG: merge_configs=False still merges; later files win+ data = {}+ for fp in found:+ text = open(fp).read()+ try:+ if fp.endswith(".json"):+ chunk = _flatten(json.loads(text))+ else:+ chunk = _parse_rc(text)+ except json.JSONDecodeError as e:+ raise ConfigParseError(str(e)) from e+ data.update(chunk)+ env = env or {}+ cli = cli or {}+ # BUG: env overrides cli+ out = {}+ out.update(cli)+ out.update(data)+ out.update(env)+ return outdiff --git a/graff-evals/fixtures/config-parse/test_config.py b/graff-evals/fixtures/config-parse/test_config.pynew file mode 100644index 00000000..f36785d2--- /dev/null+++ b/graff-evals/fixtures/config-parse/test_config.py@@ -0,0 +1,48 @@+import os+from config import load_config, ConfigParseError+++def test_json_flatten_and_kebab(tmp_path=None):+ os.makedirs("cfg", exist_ok=True)+ open("app.json", "w").write('{"retry-count": 3, "db": {"host": "h"}}')+ got = load_config("app")+ assert got.get("retryCount") == 3, got+ assert got.get("db.host") == "h", got+++def test_first_file_only():+ os.makedirs("a", exist_ok=True)+ os.makedirs("b", exist_ok=True)+ open("a/app.json", "w").write('{"x": 1}')+ open("b/app.json", "w").write('{"x": 2, "y": 9}')+ got = load_config("app", search_paths=["a", "b"], merge_configs=False)+ assert got.get("x") == 1, got+ assert "y" not in got, got+++def test_cli_beats_env_beats_config():+ open("app.json", "w").write('{"n": 1, "flag": false}')+ got = load_config("app", cli={"n": 7}, env={"n": 5, "flag": True})+ assert got["n"] == 7, got+ assert got["flag"] is True, got+++def test_rc_comments():+ open(".apprc", "w").write('# hi\nname="Ada Lovelace"\n\ncount=2\n')+ # no json so rc is used+ try:+ os.remove("app.json")+ except FileNotFoundError:+ pass+ got = load_config("app")+ assert got.get("name") == "Ada Lovelace", got+ assert got.get("count") == 2, got+ assert "#" not in "".join(map(str, got.keys())), got+++if __name__ == "__main__":+ test_json_flatten_and_kebab()+ test_first_file_only()+ test_cli_beats_env_beats_config()+ test_rc_comments()+ print("OK")diff --git a/graff-evals/fixtures/cookie-store/SPEC.md b/graff-evals/fixtures/cookie-store/SPEC.mdnew file mode 100644index 00000000..b0cead67--- /dev/null+++ b/graff-evals/fixtures/cookie-store/SPEC.md@@ -0,0 +1,36 @@+# CookieStore (DeepSWE `httpx-deterministic-cookie-store`, distilled)++`cookie_store.py` must expose `CookieConflict` and `CookieStore`.++Constructor: `CookieStore(max_cookies=None, max_cookies_per_domain=None)`.+Non-ints raise `TypeError`. Negative ints raise `ValueError`.++`set(name, value, domain="", path="/", secure=False)` stores a cookie.+`domain=""` cookies are not host-only: they are sent to any host (path ++Secure still apply). A non-empty domain is stored case-insensitively and+matches that host plus subdomains.++Path match: `Path=/sub` matches `/sub` and `/sub/x` but **not** `/submarine`.+A `Path` that is empty or does not start with `/` uses the request default+path (everything through the last `/`, or `/`).++`Secure` cookies are sent only when `https=True`.++`__Secure-` names require `Secure` and an https origin. `__Host-` names+additionally require no Domain attribute and `Path=/`.++`extract(host, path, set_cookie, https=False)` parses one `Set-Cookie` line+(`name=value; Attr=...`). Ignore the cookie if `Domain`, `Path`, or `Max-Age`+appears with an empty value. `Max-Age` is an int; `Max-Age<=0` **deletes** a+matching cookie and does not store. Unknown attributes are ignored.++When a cookie is replaced (same name, domain, path) it is treated as newly+created for eviction order. When limits are exceeded, evict **oldest+creation first**, per-domain then global.++`cookies_for(host, path, https=False)` returns matching cookies ordered by+longer path first, then older creation. `header_for(...)` joins them as+`name=value; name=value`.++`store["name"]` raises `CookieConflict` if more than one stored cookie has+that name.diff --git a/graff-evals/fixtures/cookie-store/cookie_store.py b/graff-evals/fixtures/cookie-store/cookie_store.pynew file mode 100644index 00000000..3f04923e--- /dev/null+++ b/graff-evals/fixtures/cookie-store/cookie_store.py@@ -0,0 +1,161 @@+"""Deterministic cookie jar — incomplete. Fix the SPEC.md contract."""+++class CookieConflict(Exception):+ pass+++class _C:+ __slots__ = ("name", "value", "domain", "path", "secure", "host_only", "created")++ def __init__(self, name, value, domain, path, secure, host_only, created):+ self.name = name+ self.value = value+ self.domain = domain+ self.path = path+ self.secure = secure+ self.host_only = host_only+ self.created = created+++class CookieStore:+ def __init__(self, max_cookies=None, max_cookies_per_domain=None):+ for label, v in (("max_cookies", max_cookies), ("max_cookies_per_domain", max_cookies_per_domain)):+ if v is None:+ continue+ if type(v) is not int:+ raise TypeError(label)+ if v < 0:+ raise ValueError(label)+ self.max_cookies = max_cookies+ self.max_cookies_per_domain = max_cookies_per_domain+ self._items = []+ self._tick = 0++ def _clock(self):+ self._tick += 1+ return self._tick++ def set(self, name, value, domain="", path="/", secure=False):+ host_only = False+ stored_domain = domain.lower() if domain else ""+ self._upsert(_C(name, value, stored_domain, path or "/", secure, host_only, self._clock()))+ self._evict()++ def _key(self, c):+ return (c.name, c.domain, c.path)++ def _upsert(self, c):+ for i, old in enumerate(self._items):+ if self._key(old) == self._key(c):+ self._items[i] = c+ return+ self._items.append(c)++ def _evict(self):+ # BUG: evicts newest (keeps oldest). SPEC: drop oldest creation first.+ if self.max_cookies_per_domain is not None:+ by = {}+ for c in self._items:+ by.setdefault(c.domain, []).append(c)+ keep = []+ for cs in by.values():+ cs.sort(key=lambda c: c.created)+ keep.extend(cs[: self.max_cookies_per_domain])+ self._items = keep+ if self.max_cookies is not None and len(self._items) > self.max_cookies:+ self._items.sort(key=lambda c: c.created)+ self._items = self._items[: self.max_cookies]++ def _path_match(self, cookie_path, req_path):+ # BUG: "/sub" matches "/submarine"+ return req_path.startswith(cookie_path)++ def _domain_match(self, c, host):+ host = host.lower()+ if c.domain == "":+ return True+ return host == c.domain or host.endswith("." + c.domain)++ def cookies_for(self, host, path, https=False):+ out = []+ for c in self._items:+ if c.secure and not https:+ continue+ if not self._domain_match(c, host):+ continue+ if not self._path_match(c.path, path):+ continue+ out.append(c)+ out.sort(key=lambda c: (-len(c.path), c.created))+ return out++ def header_for(self, host, path, https=False):+ return "; ".join(f"{c.name}={c.value}" for c in self.cookies_for(host, path, https))++ def extract(self, host, path, set_cookie, https=False):+ parts = [p.strip() for p in set_cookie.split(";")]+ if not parts or "=" not in parts[0]:+ return+ name, value = parts[0].split("=", 1)+ domain = ""+ cpath = None+ secure = False+ max_age = None+ for p in parts[1:]:+ if not p:+ continue+ if "=" in p:+ k, v = p.split("=", 1)+ else:+ k, v = p, ""+ k = k.strip().lower()+ v = v.strip()+ if k == "domain":+ if v == "":+ return+ domain = v.lstrip(".")+ elif k == "path":+ if v == "":+ return+ cpath = v+ elif k == "max-age":+ if v == "":+ return+ try:+ max_age = int(v)+ except ValueError:+ return+ elif k == "secure":+ secure = True+ if cpath is None or not str(cpath).startswith("/"):+ cpath = path.rsplit("/", 1)[0] or "/"+ if name.startswith("__Secure-") and (not secure or not https):+ return+ if name.startswith("__Host-") and (not secure or not https or domain or cpath != "/"):+ return+ if max_age is not None and max_age <= 0:+ # BUG: still stores instead of deleting+ self.set(name, value, domain=domain, path=cpath, secure=secure)+ return+ self.set(name, value, domain=domain, path=cpath, secure=secure)++ def delete(self, name, domain=None, path=None):+ def keep(c):+ if c.name != name:+ return True+ if domain is not None and c.domain != domain.lower():+ return True+ if path is not None and c.path != path:+ return True+ return False++ self._items = [c for c in self._items if keep(c)]++ def __getitem__(self, name):+ hits = [c for c in self._items if c.name == name]+ if not hits:+ raise KeyError(name)+ if len(hits) > 1:+ raise CookieConflict(name)+ return hits[0].valuediff --git a/graff-evals/fixtures/cookie-store/test_cookie_store.py b/graff-evals/fixtures/cookie-store/test_cookie_store.pynew file mode 100644index 00000000..2fbe95b3--- /dev/null+++ b/graff-evals/fixtures/cookie-store/test_cookie_store.py@@ -0,0 +1,44 @@+from cookie_store import CookieStore, CookieConflict+++def test_basic():+ s = CookieStore()+ s.set("sid", "abc", domain="ex.com", path="/")+ assert s["sid"] == "abc"+ assert s.header_for("ex.com", "/", True) == "sid=abc"+++def test_path_is_not_a_string_prefix():+ s = CookieStore()+ s.set("x", "1", domain="ex.com", path="/sub")+ assert s.header_for("ex.com", "/sub", True) == "x=1"+ assert s.header_for("ex.com", "/sub/page", True) == "x=1"+ assert s.header_for("ex.com", "/submarine", True) == ""+++def test_evict_oldest_global():+ s = CookieStore(max_cookies=2)+ s.set("a", "1")+ s.set("b", "2")+ s.set("c", "3")+ names = [c.name for c in s.cookies_for("any", "/", True)]+ assert names == ["b", "c"], names+++def test_conflict():+ s = CookieStore()+ s.set("n", "1", domain="a.com", path="/")+ s.set("n", "2", domain="b.com", path="/")+ try:+ _ = s["n"]+ except CookieConflict:+ return+ raise AssertionError("expected CookieConflict")+++if __name__ == "__main__":+ test_basic()+ test_path_is_not_a_string_prefix()+ test_evict_oldest_global()+ test_conflict()+ print("OK")diff --git a/graff-evals/fixtures/json-stream/SPEC.md b/graff-evals/fixtures/json-stream/SPEC.mdnew file mode 100644index 00000000..f18c41c9--- /dev/null+++ b/graff-evals/fixtures/json-stream/SPEC.md@@ -0,0 +1,32 @@+# Streaming JSON iteration (DeepSWE `httpx-streaming-json-iteration`, distilled)++`json_stream.py` must expose `DecodingError` and `iter_json(content_type, body,+streaming=False)`.++`content_type` matching is case-insensitive; parameters are allowed.+Accept:++- `application/json` and `application/*+json` (the `+json` suffix is **only**+ valid under `application/`)+- `application/ndjson` / `application/x-ndjson`+- `application/json-seq`++Anything else raises `DecodingError`.++`application/json` / `*+json`: skip leading whitespace; if the top-level+value is an array, yield each element; otherwise yield the single value.+After the value only whitespace is allowed.++NDJSON: split on LF / CR / CRLF. Skip blank lines. Each other line is one+JSON value.++JSON text sequences: records start with RS (`0x1e`). Strip at most one+trailing LF per record, then parse one JSON value. Empty payload yields+nothing.++If `streaming=True`, a second call on the same consumed stream raises+`StreamConsumed`. In-memory (`streaming=False`) iteration is repeatable —+this distillation models that with a `Stream` object: `iter_json` may+return an iterator, and `StreamConsumed` is raised by a second+`iter_json(..., streaming=True)` on the same `body` if `body` is a+`Stream`.diff --git a/graff-evals/fixtures/json-stream/json_stream.py b/graff-evals/fixtures/json-stream/json_stream.pynew file mode 100644index 00000000..30f414b9--- /dev/null+++ b/graff-evals/fixtures/json-stream/json_stream.py@@ -0,0 +1,69 @@+"""Streaming JSON — incomplete. Fix the SPEC.md contract."""+import json+import re+++class DecodingError(Exception):+ pass+++class StreamConsumed(Exception):+ pass+++class Stream:+ def __init__(self, data):+ self.data = data+ self.consumed = False+++def _media(ct):+ ct = (ct or "").split(";", 1)[0].strip().lower()+ return ct+++def iter_json(content_type, body, streaming=False):+ if isinstance(body, Stream):+ if streaming and body.consumed:+ raise StreamConsumed()+ data = body.data+ if streaming:+ body.consumed = True+ else:+ data = body++ media = _media(content_type)+ # BUG: accepts any *+json (e.g. image/svg+json)+ ok = (+ media == "application/json"+ or media.endswith("+json")+ or media in ("application/ndjson", "application/x-ndjson", "application/json-seq")+ )+ if not ok:+ raise DecodingError(media)++ if media in ("application/ndjson", "application/x-ndjson"):+ # BUG: blank lines are parsed+ for line in re.split(r"\r\n|\n|\r", data):+ yield json.loads(line)+ return++ if media == "application/json-seq":+ if not data.strip():+ return+ parts = data.split("\x1e")+ for part in parts:+ if not part.strip():+ continue+ if part.endswith("\n"):+ part = part[:-1]+ yield json.loads(part)+ return++ text = data.lstrip()+ val, _end = json.JSONDecoder().raw_decode(text)+ # BUG: leftover after one JSON value is ignored+ if isinstance(val, list):+ yield from val+ else:+ yield valdiff --git a/graff-evals/fixtures/json-stream/test_json_stream.py b/graff-evals/fixtures/json-stream/test_json_stream.pynew file mode 100644index 00000000..f244e432--- /dev/null+++ b/graff-evals/fixtures/json-stream/test_json_stream.py@@ -0,0 +1,41 @@+from json_stream import DecodingError, Stream, StreamConsumed, iter_json+++def test_json_array_and_reject_other_tree():+ assert list(iter_json("application/json", "[1, 2]")) == [1, 2]+ try:+ list(iter_json("image/svg+json", "{}"))+ raise AssertionError("image/*+json must be rejected")+ except DecodingError:+ pass+++def test_trailing_junk():+ try:+ list(iter_json("application/json", '{"a": 1} trailing'))+ raise AssertionError("trailing data must error")+ except DecodingError:+ pass+++def test_ndjson_skips_blank():+ body = "1\n\n2\n"+ assert list(iter_json("application/ndjson", body)) == [1, 2]+++def test_stream_consumed():+ s = Stream("[1]")+ assert list(iter_json("application/json", s, streaming=True)) == [1]+ try:+ list(iter_json("application/json", s, streaming=True))+ raise AssertionError("expected StreamConsumed")+ except StreamConsumed:+ pass+++if __name__ == "__main__":+ test_json_array_and_reject_other_tree()+ test_trailing_junk()+ test_ndjson_skips_blank()+ test_stream_consumed()+ print("OK")diff --git a/graff-evals/fixtures/label-sort/SPEC.md b/graff-evals/fixtures/label-sort/SPEC.mdnew file mode 100644index 00000000..30297e34--- /dev/null+++ b/graff-evals/fixtures/label-sort/SPEC.md@@ -0,0 +1,17 @@+# Typed label sort (DeepSWE `prometheus-typed-label-sorting`, distilled)++`label_sort.py` must expose `sort_labels(values: list[str]) -> list[str]`.++Values with **leading whitespace** are never parsed as typed. They sort+before every other value; within that group, use natural sort of the+original strings.++Then order typed classes as: `+Inf` / `Infinity`, finite numeric, `-Inf`,+duration (`10s`, `2ms`, `1h`), bytes (`10Ki`, `1Mi`, `3B`), semantic+version (`1.2.3` or `v1.2.3`), IPv4, IPv6, then untyped natural strings.++Numeric parsing accepts an optional leading `+` and scientific exponents.+A bare exponent (`1e`) is not numeric. `NaN` is not numeric (untyped).++IPv4 sorts before IPv6. When two parsed typed values compare equal, break+ties by natural order of the original strings. Empty strings are untyped.diff --git a/graff-evals/fixtures/label-sort/label_sort.py b/graff-evals/fixtures/label-sort/label_sort.pynew file mode 100644index 00000000..35635990--- /dev/null+++ b/graff-evals/fixtures/label-sort/label_sort.py@@ -0,0 +1,57 @@+"""Typed label sort — incomplete. Fix the SPEC.md contract."""+import ipaddress+import re+++def _natural_key(s):+ parts = re.split(r"(\d+)", s)+ key = []+ for p in parts:+ if p.isdigit():+ key.append((1, int(p)))+ else:+ key.append((0, p))+ return key+++def _classify(s):+ # BUG: leading whitespace is parsed as typed+ t = s.strip()+ low = t.lower()+ if low in ("+inf", "inf", "infinity"):+ return (0, 0.0)+ if low in ("-inf", "-infinity"):+ return (2, 0.0)+ # BUG: NaN treated as numeric+ if low == "nan":+ return (1, float("nan"))+ try:+ if re.fullmatch(r"[+-]?\d+(\.\d+)?([eE][+-]?\d+)?", t):+ return (1, float(t))+ except ValueError:+ pass+ m = re.fullmatch(r"([+-]?\d+(?:\.\d+)?)(ms|s|m|h)", t)+ if m:+ n = float(m.group(1))+ unit = {"ms": 0.001, "s": 1, "m": 60, "h": 3600}[m.group(2)]+ return (3, n * unit)+ m = re.fullmatch(r"([+-]?\d+(?:\.\d+)?)(B|Ki|Mi|Gi)", t)+ if m:+ n = float(m.group(1))+ unit = {"B": 1, "Ki": 1024, "Mi": 1024**2, "Gi": 1024**3}[m.group(2)]+ return (4, n * unit)+ m = re.fullmatch(r"v?(\d+)\.(\d+)\.(\d+)", t)+ if m:+ return (5, tuple(int(x) for x in m.groups()))+ try:+ ip = ipaddress.ip_address(t)+ # BUG: IPv6 (6) before IPv4 (7) — SPEC wants IPv4 first+ fam = 6 if ip.version == 4 else 5.5+ return (fam, int(ip))+ except ValueError:+ pass+ return (9, _natural_key(s))+++def sort_labels(values):+ return sorted(values, key=lambda s: (_classify(s), _natural_key(s)))diff --git a/graff-evals/fixtures/label-sort/test_label_sort.py b/graff-evals/fixtures/label-sort/test_label_sort.pynew file mode 100644index 00000000..4e26af9a--- /dev/null+++ b/graff-evals/fixtures/label-sort/test_label_sort.py@@ -0,0 +1,33 @@+from label_sort import sort_labels+++def test_numeric_and_inf():+ got = sort_labels(["10", "2", "+Inf", "-Inf", "1e2"])+ assert got[0] == "+Inf", got+ assert got[-1] == "-Inf", got+ assert got[1:4] == ["2", "10", "1e2"], got+++def test_leading_ws_first():+ got = sort_labels(["10", " zebra", " apple", "beta"])+ assert got[0] == " apple", got+ assert got[1] == " zebra", got+++def test_ipv4_before_ipv6():+ got = sort_labels(["::1", "127.0.0.1"])+ assert got == ["127.0.0.1", "::1"], got+++def test_nan_is_untyped():+ got = sort_labels(["NaN", "10", "abc"])+ assert got[0] == "10", got+ assert "NaN" in got[1:]+++if __name__ == "__main__":+ test_numeric_and_inf()+ test_leading_ws_first()+ test_ipv4_before_ipv6()+ test_nan_is_untyped()+ print("OK")diff --git a/graff-evals/fixtures/map-conflict/SPEC.md b/graff-evals/fixtures/map-conflict/SPEC.mdnew file mode 100644index 00000000..3c9ae06b--- /dev/null+++ b/graff-evals/fixtures/map-conflict/SPEC.md@@ -0,0 +1,23 @@+# Map conflict detection (DeepSWE `yjs-map-conflict-detection`, distilled)++`doc.py` must expose `Doc`, `MapConflictError`.++`Doc(map_conflict_policy="allow"|"collect"|"error")`.++`doc.get_map(name)` returns a map-like object with `set(key, value)` and+`delete(key)`. `doc.transact(fn)` runs `fn` inside one transaction.++Conflicts: two `set`s, or a `set` and a `delete`, on the **same key**+inside one transaction.++- `allow`: apply last write; do not record or throw.+- `collect`: apply last write; record conflicts. `get_map_conflicts()`+ returns a list of dicts with `key`, `type` (`set-set` or `delete-set`),+ `source` (`local`), `message` (non-empty), `resolution` with+ `winner`, `strategy` (string), `deterministic` (bool).+ `get_map_conflict_summary()` returns `{count, byType, byKey}` where+ `byType`/`byKey` map strings to counts.+- `error`: raise `MapConflictError` with `.conflicts` (list). The+ transaction must be **atomic**: no partial application.++Values that are dicts (stand-in for nested Y types) make `type` `ambiguous`.diff --git a/graff-evals/fixtures/map-conflict/doc.py b/graff-evals/fixtures/map-conflict/doc.pynew file mode 100644index 00000000..80b3ce8d--- /dev/null+++ b/graff-evals/fixtures/map-conflict/doc.py@@ -0,0 +1,101 @@+"""Y.Map-style conflict detection — incomplete. Fix the SPEC.md contract."""+++class MapConflictError(Exception):+ def __init__(self, conflicts):+ super().__init__("map conflict")+ # BUG: conflicts not exposed+ self.payload = conflicts+++class _Map:+ def __init__(self, doc, name):+ self.doc = doc+ self.name = name+ self._data = {}++ def set(self, key, value):+ self.doc._op(self, "set", key, value)++ def delete(self, key):+ self.doc._op(self, "delete", key, None)++ def get(self, key, default=None):+ return self._data.get(key, default)+++class Doc:+ def __init__(self, map_conflict_policy="allow"):+ self.policy = map_conflict_policy+ self._maps = {}+ self._tx = None+ self._conflicts = []++ def get_map(self, name):+ if name not in self._maps:+ self._maps[name] = _Map(self, name)+ return self._maps[name]++ def transact(self, fn):+ self._tx = []+ try:+ fn()+ self._commit()+ finally:+ self._tx = None++ def _op(self, m, kind, key, value):+ if self._tx is None:+ self.transact(lambda: self._op(m, kind, key, value))+ return+ self._tx.append((m, kind, key, value))++ def _commit(self):+ ops = self._tx or []+ by_key = {}+ for m, kind, key, value in ops:+ by_key.setdefault((m.name, key), []).append((m, kind, key, value))+ conflicts = []+ for (name, key), group in by_key.items():+ if len(group) < 2:+ continue+ kinds = [g[1] for g in group]+ if "delete" in kinds and "set" in kinds:+ typ = "delete-set"+ else:+ typ = "set-set"+ if any(isinstance(g[3], dict) for g in group if g[1] == "set"):+ typ = "ambiguous"+ conflicts.append({+ "key": key,+ "type": typ,+ "source": "local",+ "message": f"{typ} on {key}",+ "resolution": {"winner": "last", "strategy": "last-write", "deterministic": True},+ })+ if conflicts and self.policy == "error":+ # BUG: applies ops before raising (not atomic)+ for m, kind, key, value in ops:+ if kind == "delete":+ m._data.pop(key, None)+ else:+ m._data[key] = value+ raise MapConflictError(conflicts)+ if conflicts and self.policy == "collect":+ # BUG: conflicts not recorded+ pass+ for m, kind, key, value in ops:+ if kind == "delete":+ m._data.pop(key, None)+ else:+ m._data[key] = value++ def get_map_conflicts(self):+ return list(self._conflicts)++ def get_map_conflict_summary(self):+ by_type, by_key = {}, {}+ for c in self._conflicts:+ by_type[c["type"]] = by_type.get(c["type"], 0) + 1+ by_key[c["key"]] = by_key.get(c["key"], 0) + 1+ return {"count": len(self._conflicts), "byType": by_type, "byKey": by_key}diff --git a/graff-evals/fixtures/map-conflict/test_doc.py b/graff-evals/fixtures/map-conflict/test_doc.pynew file mode 100644index 00000000..c4eee785--- /dev/null+++ b/graff-evals/fixtures/map-conflict/test_doc.py@@ -0,0 +1,45 @@+from doc import Doc, MapConflictError+++def test_allow_last_write():+ d = Doc(map_conflict_policy="allow")+ m = d.get_map("m")+ d.transact(lambda: (m.set("k", 1), m.set("k", 2)))+ assert m.get("k") == 2+ assert d.get_map_conflicts() == []+++def test_collect_records():+ d = Doc(map_conflict_policy="collect")+ m = d.get_map("m")+ d.transact(lambda: (m.set("k", 1), m.set("k", 2)))+ cs = d.get_map_conflicts()+ assert len(cs) == 1, cs+ assert cs[0]["key"] == "k"+ assert cs[0]["type"] == "set-set"+ assert cs[0]["message"]+ assert cs[0]["resolution"]["deterministic"] is True+ s = d.get_map_conflict_summary()+ assert s["count"] == 1+ assert s["byType"]["set-set"] == 1+++def test_error_atomic():+ d = Doc(map_conflict_policy="error")+ m = d.get_map("m")+ m.set("ok", 1)+ try:+ d.transact(lambda: (m.set("k", 1), m.set("k", 2)))+ raise AssertionError("expected MapConflictError")+ except MapConflictError as e:+ assert hasattr(e, "conflicts")+ assert e.conflicts+ assert m.get("k") is None, "error policy must roll back the transaction"+ assert m.get("ok") == 1+++if __name__ == "__main__":+ test_allow_last_write()+ test_collect_records()+ test_error_atomic()+ print("OK")diff --git a/graff-evals/fixtures/validated/SPEC.md b/graff-evals/fixtures/validated/SPEC.mdnew file mode 100644index 00000000..b6422730--- /dev/null+++ b/graff-evals/fixtures/validated/SPEC.md@@ -0,0 +1,20 @@+# Validated error accumulation (DeepSWE `returns-validated-error-accumulation`, distilled)++`validated.py` must expose `Valid`, `Invalid`, `Validated` (alias of the+union behavior via classmethods on either).++- `Valid(x)` and `Invalid(errors)` where `Invalid` stores errors as an+ immutable tuple. `Invalid.from_failure(err)` wraps a single error in a+ 1-tuple.+- `bind(fn)` short-circuits: `Invalid` stays `Invalid` (fn not called);+ `Valid` calls `fn` and returns its Validated.+- `apply(other)` is applicative. Two `Invalid`s concatenate **self then+ other**, left to right. `Valid` + `Invalid` → that `Invalid`.+ `Valid(f).apply(Valid(x))` → `Valid(f(x))`.+- `swap()`: `Valid(x)` → `Invalid((x,))`; `Invalid(errs)` → `Valid(errs)`.+- `from_validated(v)` returns the same instance.+- `alt(fn)` on `Invalid` maps `fn` over each error; on `Valid` is identity.+- `__match_args__` is `("value",)` for Valid and `("errors",)` for Invalid.+- `combine(a, b, fn)` applicative-combines two containers with `fn(a,b)`.+- `combine_n(items, fn)` applies `fn` to N inner values, accumulating+ every error if any item is Invalid.diff --git a/graff-evals/fixtures/validated/test_validated.py b/graff-evals/fixtures/validated/test_validated.pynew file mode 100644index 00000000..ccbd6259--- /dev/null+++ b/graff-evals/fixtures/validated/test_validated.py@@ -0,0 +1,40 @@+from validated import Invalid, Valid, combine, combine_n+++def test_from_failure_tuple():+ i = Invalid.from_failure("e")+ assert i.errors == ("e",), i.errors+++def test_apply_concat():+ a = Invalid.from_failure("a")+ b = Invalid.from_failure("b")+ got = a.apply(b)+ assert got.errors == ("a", "b"), got.errors+++def test_swap_wraps():+ assert Valid(3).swap() == Invalid((3,))+ assert Invalid(("e",)).swap() == Valid(("e",))+++def test_bind_short_circuit():+ called = []+ Invalid.from_failure("e").bind(lambda x: called.append(x) or Valid(x))+ assert called == []+ assert Valid(2).bind(lambda x: Valid(x + 1)) == Valid(3)+++def test_combine_n():+ got = combine_n((Valid(1), Invalid.from_failure("x"), Invalid.from_failure("y")), lambda a, b, c: a)+ assert got.errors == ("x", "y"), got.errors+ assert combine(Valid(2), Valid(3), lambda x, y: x + y) == Valid(5)+++if __name__ == "__main__":+ test_from_failure_tuple()+ test_apply_concat()+ test_swap_wraps()+ test_bind_short_circuit()+ test_combine_n()+ print("OK")diff --git a/graff-evals/fixtures/validated/validated.py b/graff-evals/fixtures/validated/validated.pynew file mode 100644index 00000000..d4d43a0a--- /dev/null+++ b/graff-evals/fixtures/validated/validated.py@@ -0,0 +1,99 @@+"""Validated / Invalid — incomplete. Fix the SPEC.md contract."""+++class Valid:+ __match_args__ = ("value",)++ def __init__(self, value):+ self.value = value++ def bind(self, fn):+ return fn(self.value)++ def apply(self, other):+ if isinstance(other, Invalid):+ return other+ return Valid(self.value(other.value))++ def swap(self):+ # BUG: does not wrap in a 1-tuple+ return Invalid(self.value)++ def alt(self, fn):+ return self++ @classmethod+ def from_validated(cls, v):+ return v++ def __eq__(self, other):+ return type(other) is Valid and other.value == self.value++ def __repr__(self):+ return f"Valid({self.value!r})"+++class Invalid:+ __match_args__ = ("errors",)++ def __init__(self, errors):+ if isinstance(errors, tuple):+ self.errors = errors+ elif isinstance(errors, (list, set)):+ self.errors = tuple(errors)+ else:+ # BUG: single error stored bare instead of 1-tuple+ self.errors = errors++ @classmethod+ def from_failure(cls, err):+ return cls(err)++ def bind(self, fn):+ return self++ def apply(self, other):+ # BUG: does not concatenate when other is Invalid+ if isinstance(other, Invalid):+ return self+ return self++ def swap(self):+ return Valid(self.errors)++ def alt(self, fn):+ if isinstance(self.errors, tuple):+ return Invalid(tuple(fn(e) for e in self.errors))+ return Invalid(fn(self.errors))++ @classmethod+ def from_validated(cls, v):+ return v++ def __eq__(self, other):+ return type(other) is Invalid and other.errors == self.errors++ def __repr__(self):+ return f"Invalid({self.errors!r})"+++def combine(a, b, fn):+ if isinstance(a, Valid) and isinstance(b, Valid):+ return Valid(fn(a.value, b.value))+ if isinstance(a, Invalid) and isinstance(b, Invalid):+ return a.apply(b)+ return a if isinstance(a, Invalid) else b+++def combine_n(items, fn):+ errs = []+ vals = []+ for it in items:+ if isinstance(it, Invalid):+ e = it.errors if isinstance(it.errors, tuple) else (it.errors,)+ errs.extend(e)+ else:+ vals.append(it.value)+ if errs:+ return Invalid(tuple(errs))+ return Valid(fn(*vals))diff --git a/graff-evals/hidden/config-parse.py b/graff-evals/hidden/config-parse.pynew file mode 100644index 00000000..cab7755b--- /dev/null+++ b/graff-evals/hidden/config-parse.py@@ -0,0 +1,45 @@+"""Held-out checks for config-parse."""+import json+import os+import sys++sys.path.insert(0, os.getcwd())+from config import ConfigParseError, load_config # noqa: E402+++def main():+ os.makedirs("p1", exist_ok=True)+ os.makedirs("p2", exist_ok=True)+ open("p1/svc.json", "w").write('{"retry-count": 1, "db": {"port": 0}, "keep": false}')+ open("p2/svc.json", "w").write('{"retry-count": 9, "extra": 4}')+ got = load_config("svc", search_paths=["p1", "p2"], merge_configs=True, cli={"keep": True}, env={"retryCount": 8})+ assert got["retryCount"] == 8, got+ assert got["db.port"] == 0, got+ assert got["keep"] is True, got+ assert got["extra"] == 4, got++ got = load_config("svc", search_paths=["p1", "p2"], merge_configs=False)+ assert got["retryCount"] == 1, got+ assert "extra" not in got, got++ open(".svcrc", "w").write("only=1\n# skip=9\n")+ try:+ os.remove("svc.json")+ except FileNotFoundError:+ pass+ got = load_config("svc", search_paths=["."])+ assert got.get("only") == 1, got+ assert "skip" not in got, got++ open("bad.json", "w").write("{not json")+ try:+ load_config("bad")+ raise SystemExit("expected ConfigParseError")+ except ConfigParseError:+ pass++ print("HIDDEN_OK")+++if __name__ == "__main__":+ main()diff --git a/graff-evals/hidden/cookie-store.py b/graff-evals/hidden/cookie-store.pynew file mode 100644index 00000000..5f4fc5ac--- /dev/null+++ b/graff-evals/hidden/cookie-store.py@@ -0,0 +1,62 @@+"""Held-out checks for cookie-store (not copied into the sandbox)."""+import os+import sys++sys.path.insert(0, os.getcwd())+from cookie_store import CookieStore, CookieConflict # noqa: E402+++def main():+ s = CookieStore()+ s.set("x", "1", domain="Ex.COM", path="/")+ assert s.header_for("ex.com", "/", True) == "x=1"+ assert s.header_for("www.ex.com", "/", True) == "x=1"+ assert s.header_for("evil.com", "/", True) == ""++ s = CookieStore()+ s.set("p", "1", domain="ex.com", path="/docs")+ assert s.header_for("ex.com", "/docs", True) == "p=1"+ assert s.header_for("ex.com", "/docs/", True) == "p=1"+ assert s.header_for("ex.com", "/docsX", True) == ""++ s = CookieStore(max_cookies=2, max_cookies_per_domain=1)+ s.set("a", "1", domain="a.com")+ s.set("b", "2", domain="a.com")+ names = [c.name for c in s.cookies_for("a.com", "/", True)]+ assert names == ["b"], names++ s = CookieStore()+ s.extract("ex.com", "/", "gone=1; Path=/", https=True)+ s.extract("ex.com", "/", "gone=; Path=/; Max-Age=0", https=True)+ assert s.header_for("ex.com", "/", True) == ""++ s = CookieStore()+ s.extract("ex.com", "/", "bad=1; Domain=", https=True)+ assert s.header_for("ex.com", "/", True) == ""++ s = CookieStore()+ s.extract("ex.com", "/", "__Secure-tok=z; Secure", https=False)+ assert s.header_for("ex.com", "/", False) == ""+ s.extract("ex.com", "/", "__Secure-tok=z; Secure", https=True)+ assert s.header_for("ex.com", "/", True) == "__Secure-tok=z"+ assert s.header_for("ex.com", "/", False) == ""++ s = CookieStore()+ s.set("sec", "1", domain="ex.com", path="/", secure=True)+ assert s.header_for("ex.com", "/", False) == ""+ assert s.header_for("ex.com", "/", True) == "sec=1"++ s = CookieStore()+ s.set("n", "1", domain="a.com", path="/")+ s.set("n", "2", domain="b.com", path="/")+ try:+ _ = s["n"]+ raise SystemExit("expected CookieConflict")+ except CookieConflict:+ pass++ print("HIDDEN_OK")+++if __name__ == "__main__":+ main()diff --git a/graff-evals/hidden/json-stream.py b/graff-evals/hidden/json-stream.pynew file mode 100644index 00000000..c381dc59--- /dev/null+++ b/graff-evals/hidden/json-stream.py@@ -0,0 +1,45 @@+"""Held-out checks for json-stream."""+import os+import sys++sys.path.insert(0, os.getcwd())+from json_stream import DecodingError, Stream, StreamConsumed, iter_json # noqa: E402+++def main():+ assert list(iter_json("Application/JSON; charset=utf-8", " {\"a\": 1} ")) == [{"a": 1}]+ assert list(iter_json("application/vnd.api+json", "[1]")) == [1]+ try:+ list(iter_json("text/foo+json", "{}"))+ raise SystemExit("text/*+json must be rejected")+ except DecodingError:+ pass++ try:+ list(iter_json("application/json", "1 2"))+ raise SystemExit("trailing")+ except DecodingError:+ pass++ body = "\n3\r\n\r4\n"+ assert list(iter_json("application/x-ndjson", body)) == [3, 4]++ seq = "\x1e{\"x\":1}\n\x1e2"+ assert list(iter_json("application/json-seq", seq)) == [{"x": 1}, 2]+ assert list(iter_json("application/json-seq", " ")) == []++ s = Stream("5")+ assert list(iter_json("application/json", s, streaming=False)) == [5]+ assert list(iter_json("application/json", s, streaming=False)) == [5]+ list(iter_json("application/json", s, streaming=True))+ try:+ list(iter_json("application/json", s, streaming=True))+ raise SystemExit("consumed")+ except StreamConsumed:+ pass++ print("HIDDEN_OK")+++if __name__ == "__main__":+ main()diff --git a/graff-evals/hidden/label-sort.py b/graff-evals/hidden/label-sort.pynew file mode 100644index 00000000..ad9b8d01--- /dev/null+++ b/graff-evals/hidden/label-sort.py@@ -0,0 +1,40 @@+"""Held-out checks for label-sort."""+import os+import sys++sys.path.insert(0, os.getcwd())+from label_sort import sort_labels # noqa: E402+++def main():+ got = sort_labels([" b", " a", "1", "v1.0.0", "10s", "1Ki", "::1", "10.0.0.1", "zzz"])+ assert got[:2] == [" a", " b"], got+ assert got[2] == "1", got+ assert got[3] == "10s", got+ assert got[4] == "1Ki", got+ assert got[5] == "v1.0.0", got+ assert got[6] == "10.0.0.1", got+ assert got[7] == "::1", got+ assert got[8] == "zzz", got++ got = sort_labels(["1e", "10", "NaN"])+ assert got[0] == "10", got+ assert set(got[1:]) == {"1e", "NaN"}++ got = sort_labels(["+2", "2"])+ assert got == ["+2", "2"] or got == ["2", "+2"]+ # equal numeric value → natural tie-break+ assert sort_labels(["2", "+2"])[0] in ("+2", "2")+ assert _natural_first("+2", "2")++ print("HIDDEN_OK")+++def _natural_first(a, b):+ got = sort_labels([b, a])+ # "+2" < "2" lexicographically after equal numeric+ return got == ["+2", "2"]+++if __name__ == "__main__":+ main()diff --git a/graff-evals/hidden/map-conflict.py b/graff-evals/hidden/map-conflict.pynew file mode 100644index 00000000..b7e4d285--- /dev/null+++ b/graff-evals/hidden/map-conflict.py@@ -0,0 +1,40 @@+"""Held-out checks for map-conflict."""+import os+import sys++sys.path.insert(0, os.getcwd())+from doc import Doc, MapConflictError # noqa: E402+++def main():+ d = Doc(map_conflict_policy="collect")+ m = d.get_map("room")+ d.transact(lambda: (m.set("a", 1), m.delete("a"), m.set("b", {"nested": True}), m.set("b", 2)))+ cs = d.get_map_conflicts()+ types = {c["key"]: c["type"] for c in cs}+ assert types["a"] == "delete-set", types+ assert types["b"] == "ambiguous", types+ s = d.get_map_conflict_summary()+ assert s["count"] == 2+ assert s["byKey"]["a"] == 1++ d = Doc(map_conflict_policy="error")+ m = d.get_map("m")+ try:+ d.transact(lambda: (m.set("x", 1), m.delete("x")))+ raise SystemExit("expected error")+ except MapConflictError as e:+ assert isinstance(e.conflicts, list) and e.conflicts+ assert m.get("x") is None++ d = Doc(map_conflict_policy="allow")+ m = d.get_map("m")+ d.transact(lambda: (m.set("k", 1), m.delete("k"), m.set("k", 9)))+ assert m.get("k") == 9+ assert d.get_map_conflicts() == []++ print("HIDDEN_OK")+++if __name__ == "__main__":+ main()diff --git a/graff-evals/hidden/validated.py b/graff-evals/hidden/validated.pynew file mode 100644index 00000000..43642118--- /dev/null+++ b/graff-evals/hidden/validated.py@@ -0,0 +1,45 @@+"""Held-out checks for validated."""+import os+import sys++sys.path.insert(0, os.getcwd())+from validated import Invalid, Valid, combine, combine_n # noqa: E402+++def main():+ v = Valid(1)+ assert Valid.from_validated(v) is v+ i = Invalid.from_failure("z")+ assert i.errors == ("z",)+ assert i.alt(str.upper).errors == ("Z",)++ left = Invalid(("a", "b"))+ right = Invalid.from_failure("c")+ assert left.apply(right).errors == ("a", "b", "c")++ f = Valid(lambda x: x * 2)+ assert f.apply(Valid(4)) == Valid(8)+ assert f.apply(Invalid.from_failure("n")).errors == ("n",)++ assert Valid("x").swap().errors == ("x",)+ assert Invalid(("e1", "e2")).swap() == Valid(("e1", "e2"))++ got = combine(Invalid.from_failure("p"), Invalid.from_failure("q"), lambda a, b: a)+ assert got.errors == ("p", "q")++ match Valid(9):+ case Valid(value):+ assert value == 9+ case _:+ raise SystemExit("match Valid")+ match Invalid(("e",)):+ case Invalid(errors):+ assert errors == ("e",)+ case _:+ raise SystemExit("match Invalid")++ print("HIDDEN_OK")+++if __name__ == "__main__":+ main()diff --git a/graff-evals/run.py b/graff-evals/run.pyindex 2e9df85e..d8089601 100755--- a/graff-evals/run.py+++ b/graff-evals/run.py@@ -4,16 +4,16 @@Every task is a JSON file under tasks/ that declares its fixture files, theprompt, and a deterministic shell check. The runner materializes a sandbox,drives any configured harness (harnesses.json) with any model, captures wall-time / first-output latency / token usage, verifies the outcome, and writes-JSONL results plus a summary table.+time / first-output latency / token usage / peak RSS / CPU, verifies the+outcome, and writes JSONL results plus a summary table.- ./run.py --harness graff --model grok-4.6 # full suite (core + rlm)+ ./run.py --harness graff --model grok-4.6 # full suite (core + rlm + swe)./run.py --suite rlm --harness graff-dev,graff-dev-rlm # scatter-gather A/B+ ./run.py --suite swe --harness graff-dev,graff-dev-rlm # DeepSWE-shaped A/B./run.py --harness grok --task fix-fib --reps 3 # one task, 3 reps- ./run.py --harness graff,grok --model grok-4.6 # side by side./run.py --interactive # pick + watch live"""-import argparse, json, os, re, shutil, subprocess, sys, time+import argparse, json, os, re, resource, shutil, subprocess, sys, timeROOT = os.path.dirname(os.path.abspath(__file__))REPO = os.path.dirname(ROOT)@@ -45,9 +45,22 @@ def materialize(task, sandbox):if os.path.exists(sandbox):shutil.rmtree(sandbox)os.makedirs(sandbox)+ files_dir = task.get("files_dir")+ if files_dir:+ src = files_dir if os.path.isabs(files_dir) else os.path.join(ROOT, files_dir)+ if os.path.isdir(src):+ for dirpath, dirnames, filenames in os.walk(src):+ dirnames[:] = [d for d in dirnames if d != "__pycache__"]+ rel = os.path.relpath(dirpath, src)+ dest_dir = sandbox if rel == "." else os.path.join(sandbox, rel)+ os.makedirs(dest_dir, exist_ok=True)+ for name in filenames:+ if name.endswith(".pyc") or name == ".DS_Store":+ continue+ shutil.copy2(os.path.join(dirpath, name), os.path.join(dest_dir, name))for rel, content in task.get("files", {}).items():path = os.path.join(sandbox, rel)- os.makedirs(os.path.dirname(path), exist_ok=True)+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)with open(path, "w") as f:f.write(content)for cmd in task.get("setup", []):@@ -112,6 +125,76 @@ def parse_answer_and_usage(harness, stdout, stderr):return answer, usage+def _status_kb(pid, key):+ try:+ with open(f"/proc/{pid}/status") as f:+ for line in f:+ if line.startswith(key):+ return int(line.split()[1])+ except (OSError, ValueError, IndexError):+ return 0+ return 0+++def _children(pid):+ try:+ with open(f"/proc/{pid}/task/{pid}/children") as f:+ return [int(x) for x in f.read().split()]+ except (OSError, ValueError):+ return []+++def _walk_pids(pid):+ seen, stack = set(), [pid]+ while stack:+ p = stack.pop()+ if p in seen:+ continue+ seen.add(p)+ yield p+ stack.extend(_children(p))+++def tree_rss_kb(pid):+ return sum(_status_kb(p, "VmRSS:") for p in _walk_pids(pid))+++def tree_cpu_s(pid):+ ticks = os.sysconf("SC_CLK_TCK") or 100+ total = 0.0+ for p in _walk_pids(pid):+ try:+ with open(f"/proc/{p}/stat") as f:+ st = f.read()+ fields = st[st.rfind(")") + 2:].split()+ total += (int(fields[11]) + int(fields[12])) / ticks+ except (OSError, ValueError, IndexError):+ pass+ return total+++def dir_bytes(path):+ total = 0+ for root, _dirs, files in os.walk(path):+ for name in files:+ try:+ total += os.path.getsize(os.path.join(root, name))+ except OSError:+ pass+ return total+++def _rusage_children():+ u = resource.getrusage(resource.RUSAGE_CHILDREN)+ return u.ru_utime, u.ru_stime, u.ru_maxrss+++def _fmt_mib(kb):+ if not kb:+ return "—"+ return f"{kb / 1024:.1f}M"++def one_run(hname, harness, task, model, rep, live=False):sandbox = os.path.join(SANDBOX_DIR, f"{hname}-{task['id']}-r{rep}")materialize(task, sandbox)@@ -120,6 +203,9 @@ def one_run(hname, harness, task, model, rep, live=False):t0 = time.monotonic()first_out = Nonestdout_parts, stderr_parts = [], []+ rss_peak = 0+ cpu_sample = 0.0+ ru0 = _rusage_children()try:p = subprocess.Popen(cmd, cwd=sandbox, stdout=subprocess.PIPE,stderr=subprocess.PIPE, text=True,@@ -130,6 +216,8 @@ def one_run(hname, harness, task, model, rep, live=False):sel.register(p.stderr, selectors.EVENT_READ, "err")open_streams = 2while open_streams and time.monotonic() - t0 < timeout:+ rss_peak = max(rss_peak, tree_rss_kb(p.pid))+ cpu_sample = max(cpu_sample, tree_cpu_s(p.pid))for key, _ in sel.select(timeout=0.5):chunk = key.fileobj.readline()if not chunk:@@ -147,46 +235,77 @@ def one_run(hname, harness, task, model, rep, live=False):p.kill()p.wait(timeout=10)rc = p.returncode+ rss_peak = max(rss_peak, tree_rss_kb(p.pid))except FileNotFoundError:- return {"harness": hname, "task": task["id"], "rep": rep,- "error": f"harness binary not found: {cmd[0]}", "outcome_ok": False}+ return {"harness": hname, "task": task["id"], "suite": task.get("suite", "core"),+ "rep": rep, "error": f"harness binary not found: {cmd[0]}", "outcome_ok": False}+ ru1 = _rusage_children()stdout, stderr = "".join(stdout_parts), "".join(stderr_parts)wall = round(time.monotonic() - t0, 2)answer, usage = parse_answer_and_usage(harness, stdout, stderr)with open(os.path.join(sandbox, ".eval-answer.txt"), "w") as f:f.write(answer)+ check_env = dict(os.environ, ANSWER_FILE=".eval-answer.txt", TASK_ROOT=ROOT)check = subprocess.run(["/bin/sh", "-c", task["check"]], cwd=sandbox,- capture_output=True, text=True, timeout=60,- env=dict(os.environ, ANSWER_FILE=".eval-answer.txt"))- rec = {"harness": hname, "task": task["id"], "category": task.get("category", ""),- "model": model, "rep": rep, "wall_s": wall, "first_out_s": first_out,- "exit": rc, "timed_out": timed_out, "outcome_ok": check.returncode == 0,- "answer_head": answer[:120]}+ capture_output=True, text=True, timeout=60, env=check_env)+ rec = {"harness": hname, "task": task["id"], "suite": task.get("suite", "core"),+ "category": task.get("category", ""), "model": model, "rep": rep,+ "wall_s": wall, "first_out_s": first_out, "exit": rc, "timed_out": timed_out,+ "outcome_ok": check.returncode == 0, "answer_head": answer[:120],+ "rss_peak_kb": rss_peak, "rss_child_hwm_kb": max(0, ru1[2] - ru0[2]) or ru1[2],+ "cpu_user_s": round(max(0.0, ru1[0] - ru0[0]), 3),+ "cpu_sys_s": round(max(0.0, ru1[1] - ru0[1]), 3),+ "cpu_sample_s": round(cpu_sample, 3),+ "sandbox_bytes": dir_bytes(sandbox)}rec.update({f"tok_{k}": v for k, v in usage.items()})- if check.returncode != 0 and check.stderr.strip():- rec["check_note"] = check.stderr.strip()[:200]+ if check.returncode != 0 and (check.stderr.strip() or check.stdout.strip()):+ rec["check_note"] = (check.stderr.strip() or check.stdout.strip())[:200]return rec-def summarize(records):+def _bucket(records):by = {}for r in records:- b = by.setdefault(r["harness"], {"n": 0, "ok": 0, "wall": 0.0, "tin": 0, "tout": 0})+ b = by.setdefault(r["harness"], {+ "n": 0, "ok": 0, "wall": 0.0, "first": 0.0, "first_n": 0,+ "tin": 0, "tout": 0, "calls": 0, "rss": 0, "cpu": 0.0,+ })b["n"] += 1b["ok"] += bool(r.get("outcome_ok"))b["wall"] += r.get("wall_s", 0) or 0+ if r.get("first_out_s") is not None:+ b["first"] += r["first_out_s"]+ b["first_n"] += 1b["tin"] += r.get("tok_in") or 0b["tout"] += r.get("tok_out") or 0- print(f"\n{'harness':<12} {'pass':>7} {'wall':>8} {'in_tok':>9} {'out_tok':>8}")+ b["calls"] += r.get("tok_calls") or 0+ b["rss"] = max(b["rss"], r.get("rss_peak_kb") or 0)+ b["cpu"] += (r.get("cpu_user_s") or 0) + (r.get("cpu_sys_s") or 0)+ return by+++def _print_table(title, by):+ print(f"\n{title}")+ print(f"{'harness':<16} {'pass':>7} {'wall':>8} {'first':>7} {'rss':>8} {'cpu':>7} {'in_tok':>9} {'out_tok':>8} {'calls':>6}")for h, b in by.items():- print(f"{h:<12} {b['ok']}/{b['n']:<5} {b['wall']:>7.1f}s {b['tin']:>9} {b['tout']:>8}")+ first = (b["first"] / b["first_n"]) if b["first_n"] else 0.0+ print(f"{h:<16} {b['ok']}/{b['n']:<5} {b['wall']:>7.1f}s {first:>6.1f}s "+ f"{_fmt_mib(b['rss']):>8} {b['cpu']:>6.1f}s {b['tin']:>9} {b['tout']:>8} {b['calls']:>6}")+++def summarize(records):+ _print_table("all", _bucket(records))+ suites = sorted({r.get("suite") or "core" for r in records})+ if len(suites) > 1:+ for s in suites:+ _print_table(f"suite {s}", _bucket([r for r in records if (r.get("suite") or "core") == s]))def interactive(tasks, harnesses):tlist = list(tasks.values())print("tasks:")for i, t in enumerate(tlist):- print(f" [{i}] {t['id']:<18} {t.get('category', '')}")+ print(f" [{i}] {t['id']:<18} {t.get('suite', 'core'):<5} {t.get('category', '')}")ti = int(input("task #: ").strip() or "0")hnames = list(harnesses)for i, h in enumerate(hnames):@@ -207,7 +326,7 @@ def main():ap.add_argument("--harness", default="graff", help="comma-separated harness names (see harnesses.json)")ap.add_argument("--model", default=None, help="model id (default: per-harness default_model)")ap.add_argument("--task", action="append", help="task id filter (repeatable)")- ap.add_argument("--suite", default="all", help="core, rlm, or all (default all)")+ ap.add_argument("--suite", default="all", help="core, rlm, swe, comma-mix, or all (default all)")ap.add_argument("--reps", type=int, default=1)ap.add_argument("--interactive", action="store_true", help="pick a task+harness, watch it live")args = ap.parse_args()@@ -246,7 +365,9 @@ def main():f.write(json.dumps(rec, ensure_ascii=False) + "\n")f.flush()ok = "✓" if rec.get("outcome_ok") else "✗"- print(f"{ok} {hname:<12} {task['id']:<18} r{rep} {rec.get('wall_s', '?')}s "+ print(f"{ok} {hname:<16} {task['id']:<18} r{rep} {rec.get('wall_s', '?')}s "+ f"first={rec.get('first_out_s', '—')}s rss={_fmt_mib(rec.get('rss_peak_kb'))} "+ f"cpu={((rec.get('cpu_user_s') or 0) + (rec.get('cpu_sys_s') or 0)):.1f}s "f"in={rec.get('tok_in', '?')} out={rec.get('tok_out', '?')}", flush=True)summarize(records)print(f"\nresults: {out_path}")diff --git a/graff-evals/tasks/17-cookie-store.json b/graff-evals/tasks/17-cookie-store.jsonnew file mode 100644index 00000000..9ddabc35--- /dev/null+++ b/graff-evals/tasks/17-cookie-store.json@@ -0,0 +1,10 @@+{+ "id": "cookie-store",+ "suite": "swe",+ "category": "swe",+ "source": "https://deepswe.datacurve.ai/run — httpx-deterministic-cookie-store (distilled, no Harbor)",+ "files_dir": "fixtures/cookie-store",+ "prompt": "CookieStore is incomplete. Read SPEC.md and cookie_store.py, then make `python3 test_cookie_store.py` print OK. Do not edit the tests. Path matching, eviction, Max-Age, and Secure prefixes must match SPEC.md.",+ "check": "python3 test_cookie_store.py && python3 \"$TASK_ROOT/hidden/cookie-store.py\"",+ "timeout_s": 300+}diff --git a/graff-evals/tasks/18-label-sort.json b/graff-evals/tasks/18-label-sort.jsonnew file mode 100644index 00000000..e910e3f1--- /dev/null+++ b/graff-evals/tasks/18-label-sort.json@@ -0,0 +1,10 @@+{+ "id": "label-sort",+ "suite": "swe",+ "category": "swe",+ "source": "https://deepswe.datacurve.ai/run — prometheus-typed-label-sorting (distilled, no Harbor)",+ "files_dir": "fixtures/label-sort",+ "prompt": "sort_labels does not implement the typed total order in SPEC.md. Read SPEC.md and label_sort.py, then make `python3 test_label_sort.py` print OK. Do not edit the tests. Leading-whitespace, NaN, and IPv4-before-IPv6 are part of the contract.",+ "check": "python3 test_label_sort.py && python3 \"$TASK_ROOT/hidden/label-sort.py\"",+ "timeout_s": 300+}diff --git a/graff-evals/tasks/19-config-parse.json b/graff-evals/tasks/19-config-parse.jsonnew file mode 100644index 00000000..f773a57a--- /dev/null+++ b/graff-evals/tasks/19-config-parse.json@@ -0,0 +1,10 @@+{+ "id": "config-parse",+ "suite": "swe",+ "category": "swe",+ "source": "https://deepswe.datacurve.ai/run — cliffy-config-file-parsing (distilled, no Harbor)",+ "files_dir": "fixtures/config-parse",+ "prompt": "load_config is wrong. Read SPEC.md and config.py, then make `python3 test_config.py` print OK. Do not edit the tests. CLI > env > config, kebab-case → camelCase, first-file vs merge, and RC comments all matter.",+ "check": "python3 test_config.py && python3 \"$TASK_ROOT/hidden/config-parse.py\"",+ "timeout_s": 300+}diff --git a/graff-evals/tasks/20-map-conflict.json b/graff-evals/tasks/20-map-conflict.jsonnew file mode 100644index 00000000..c93ce5ca--- /dev/null+++ b/graff-evals/tasks/20-map-conflict.json@@ -0,0 +1,10 @@+{+ "id": "map-conflict",+ "suite": "swe",+ "category": "swe",+ "source": "https://deepswe.datacurve.ai/run — yjs-map-conflict-detection (distilled, no Harbor)",+ "files_dir": "fixtures/map-conflict",+ "prompt": "Doc map-conflict policy is incomplete. Read SPEC.md and doc.py, then make `python3 test_doc.py` print OK. Do not edit the tests. collect must record, error must expose .conflicts and roll back the transaction, nested dict values are ambiguous.",+ "check": "python3 test_doc.py && python3 \"$TASK_ROOT/hidden/map-conflict.py\"",+ "timeout_s": 300+}diff --git a/graff-evals/tasks/21-json-stream.json b/graff-evals/tasks/21-json-stream.jsonnew file mode 100644index 00000000..c4c33fa3--- /dev/null+++ b/graff-evals/tasks/21-json-stream.json@@ -0,0 +1,10 @@+{+ "id": "json-stream",+ "suite": "swe",+ "category": "swe",+ "source": "https://deepswe.datacurve.ai/run — httpx-streaming-json-iteration (distilled, no Harbor)",+ "files_dir": "fixtures/json-stream",+ "prompt": "iter_json is incomplete. Read SPEC.md and json_stream.py, then make `python3 test_json_stream.py` print OK. Do not edit the tests. +json is application-only, trailing data is an error, NDJSON skips blanks, json-seq uses RS records.",+ "check": "python3 test_json_stream.py && python3 \"$TASK_ROOT/hidden/json-stream.py\"",+ "timeout_s": 300+}diff --git a/graff-evals/tasks/22-validated.json b/graff-evals/tasks/22-validated.jsonnew file mode 100644index 00000000..1e1352e5--- /dev/null+++ b/graff-evals/tasks/22-validated.json@@ -0,0 +1,10 @@+{+ "id": "validated",+ "suite": "swe",+ "category": "swe",+ "source": "https://deepswe.datacurve.ai/run — returns-validated-error-accumulation (distilled, no Harbor)",+ "files_dir": "fixtures/validated",+ "prompt": "Valid/Invalid do not accumulate errors correctly. Read SPEC.md and validated.py, then make `python3 test_validated.py` print OK. Do not edit the tests. from_failure wraps a 1-tuple, apply concatenates left-then-right, swap wraps Valid in a 1-tuple, bind short-circuits.",+ "check": "python3 test_validated.py && python3 \"$TASK_ROOT/hidden/validated.py\"",+ "timeout_s": 300+}