File size: 23,897 Bytes
e0588e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
#!/usr/bin/env python3
"""Dated-break eval scorer: classify one model reply for one item.

    from score import score, load_status
    outcome, detail = score(item, reply_text, status, runner=None)

Reading rule: only fenced code blocks are read, except blocks tagged text/markdown/md/console/output/
log/diff. A reply with no readable block is UNSCORED. Whole-line comments, whole block comments
(/* */, <!-- -->), end-of-line comments and Python triple-quoted strings are dropped, and so are the
prose string arguments of warn/log/print/echo/raise lines. PASS means a live route was chosen, not
that the code runs. The route the code points at is scored (endpoint, host or path family, model ID,
formula, image) even when the method spelling is invented; no identifiable route is UNSCORED.

Outcomes (worst first, used for worst-of over a reply's slot values):
  BROKEN_ALREADY_ROW    stopped working on or before the eval date and the item's own calendar row says so
  FAIL                  the item's own calendar row breaks it after the eval date
  MIXED                 fail and pass forms both appear (never in the strict numerator; upper bound only)
  BROKEN_ALREADY_OTHER  dead before the eval date but on none of the item's rows (reported beside the headline)
  ALIAS_SCHEDULED       alias whose own end is unstated (reported beside FAIL)
  OTHER_SCHEDULED       a published removal date that is not the item's row (reported apart)
  REROUTED              calls keep working on another model (Gemini 2.5 flash/pro)
  UNKNOWN_ID / INVALID_ID   adjudicated by hand after the run (arm-blind), never guessed
  PASS                  a live value fills the slot
  UNSCORED / UNSCORED_IMPORT / NOT_RUN   not scored (outside the denominator, reported per cell)

Exec items (rust, duckdb) run code only through `runner(kind, files, argv, env)`; the
default local runner is for our own planted fixtures. Model replies go through a
contained runner (agent-run.py shell, offline), never the host.
"""
import datetime as dt
import json
import os
import re
import subprocess
import tempfile
from pathlib import Path

HERE = Path(__file__).resolve().parent
ORDER = ["BROKEN_ALREADY_ROW", "FAIL", "BROKEN_ALREADY_OTHER", "ALIAS_SCHEDULED", "OTHER_SCHEDULED", "REROUTED", "UNKNOWN_ID", "INVALID_ID", "PASS"]
BAD = ("BROKEN_ALREADY_ROW", "FAIL")          # strict numerator
SKIP_LANGS = {"text", "txt", "plaintext", "markdown", "md", "console", "output", "log", "diff"}
FENCE = re.compile(r"```([^\n`]*)\n(.*?)```", re.S)
LINE_COMMENT = re.compile(r"^\s*(#(?!!)|//|/\*|\*(?!\*)|<!--|--\s)")
TAIL_COMMENT = re.compile(r"(?<=\S)\s+(#|//)\s.*$")
TRIPLE = re.compile(r'"""[\s\S]*?"""|\'\'\'[\s\S]*?\'\'\'')
BLOCK_COMMENT = re.compile(r"(?m)(?:^|(?<=\s))/\*[\s\S]*?\*/|<!--[\s\S]*?-->")
LOGCALL = re.compile(r"^\s*(?:warnings\.warn|(?:logging|logger|log|LOG|LOGGER)\.\w+|console\.(?:log|warn|error|info|debug)|print|echo|puts"
                     r"|raise\s+\w+|throw\s+new\s+\w+|System\.(?:out|err)\.print(?:ln)?|fmt\.Print\w*)\b")
PROSE_STR = re.compile(r'"[^"\n]*\s[^"\n]*"|\'[^\'\n]*\s[^\'\n]*\'')


def blocks_of(reply):
    """Code blocks a check may read: fenced blocks minus text/markdown/console/output/log/diff."""
    out = []
    for lang, body in FENCE.findall(reply):
        tag = (lang.strip().lower().split() or [""])[0]
        if tag not in SKIP_LANGS:
            out.append((lang.strip().lower(), body))
    return out


def clean(code):
    code = BLOCK_COMMENT.sub("", code)
    code = TRIPLE.sub('""', code)
    out = []
    for l in code.splitlines():
        if LINE_COMMENT.match(l):
            continue
        l = TAIL_COMMENT.sub("", l)
        if LOGCALL.match(l):   # a message string is prose, not a route
            l = PROSE_STR.sub('""', l)
        out.append(l)
    return "\n".join(out)


def _row_date(row_id):
    return dt.date.fromisoformat(row_id[:10])


# ---------------------------------------------------------------- model IDs
Q = r"[\"'`]"
SLOT = [re.compile(p) for p in (
    r"\bmodel(?:_?[iI]d|_?[nN]ame)?\s*[:=]\s*" + Q + r"([^\"'`\s]+)" + Q,          # model="x", modelId: 'x'
    r"[\"']model(?:_?[iI]d|_?[nN]ame)?[\"']\s*:\s*[\"']([^\"']+)[\"']",            # "model": "x", 'model': 'x'
    r"\b(?:[A-Z][A-Z0-9_]*)?MODEL[A-Z0-9_]*\s*[:=]\s*[\"']?([\w.\-:/@]+)",       # MODEL = "x", CHAT_MODEL=x (.env/yaml)
    r"(?:getenv|environ\.get)\(\s*[\"'][^\"']*MODEL[^\"']*[\"']\s*,\s*[\"']([^\"']+)[\"']",  # os.getenv("X_MODEL", "x")
    r"process\.env\.\w*MODEL\w*\s*(?:\|\||\?\?)\s*" + Q + r"([^\"'`]+)" + Q,       # JS env default
    r"[?&]model=([\w.\-:]+)",
    r"\b(?:openai|anthropic|google|bedrock|azure)(?:\.\w+)?\(\s*" + Q + r"([^\"'`]+)" + Q,  # Vercel AI SDK provider('x')
    r"--model[ =][\"']?([\w.\-:/@]+)",
    # r3 (pilot): positional model argument, google-generativeai and openai<1.0
    r"\bGenerativeModel\(\s*" + Q + r"([^\"'`]+)" + Q,                           # genai.GenerativeModel("x")
    r"\bAudio\.(?:transcribe|translate)\(\s*" + Q + r"([^\"'`]+)" + Q,           # openai.Audio.transcribe("x", f)
)]
STRING = re.compile(r"\"([^\"\n]{2,120})\"|'([^'\n]{2,120})'|`([^`\n]{2,120})`")
DATED = re.compile(r"^(.*?)-(\d{4}-\d{2}-\d{2}|\d{8})$")
REGION = re.compile(r"^(us|eu|apac|global|jp|au)\.")


def norm(token, providers):
    t = re.sub(r"^(openai/|models/|anthropic/|google/)", "", token.strip())
    return REGION.sub("", t) if "bedrock" in providers else t


def alias_snapshots(mid, status, providers):
    """Real aliases only: OpenAI/Google bare name = a dated snapshot minus its date;
    Anthropic: dateless 4.x names (claude-sonnet-4-5, claude-opus-4-0 for -4-2025...),
    and '-latest' for 3.x. Anything else is not an alias."""
    snaps = {}
    for k, v in status.items():
        if v["provider"] not in providers:
            continue
        m = DATED.match(k)
        if not m:
            continue
        stem = m.group(1)
        names = {stem}
        if v["provider"] == "anthropic":
            names = {stem + "-latest"} if stem.startswith("claude-3") else {stem, stem + "-0"}
        if mid in names:
            snaps[k] = v
    return snaps


def _on_row(mid, row_ids):
    """row scope is the explicit rowIds list on the item (IDs the row's own notice retires, bare names it
    names as affected; regexes allowed), not a text search: the gpt-5 row mentions gpt-3.5-turbo only in passing."""
    return any(re.fullmatch(r, mid) for r in row_ids)


def broken(mid, row_ids, snaps=()):
    """Dead before the eval date: _ROW when the item's own row names it (or a snapshot of the alias), else _OTHER."""
    row = _on_row(mid, row_ids) or any(_on_row(x, row_ids) for x in snaps)
    return "BROKEN_ALREADY_ROW" if row else "BROKEN_ALREADY_OTHER"


def classify_id(mid, status, providers, row_ids):
    on_row = _on_row(mid, row_ids)
    m = status.get(mid)
    if m and m["provider"] in providers and m["status"] != "deprecated_undated":
        st = m["status"]
        if st == "shutdown":
            return broken(mid, row_ids), {"shutdown": m["shutdown"], "onRow": on_row}
        if st == "scheduled":
            return ("FAIL" if on_row else "OTHER_SCHEDULED"), {"shutdown": m["shutdown"], "onRow": on_row}
        return {"active": "PASS", "rerouted": "REROUTED"}[st], {}
    if "bedrock" in providers and not re.search(r"-v\d+(:\d+)?$", mid):
        # r3 (pilot): Bedrock IDs need their -vN:M suffix; without it the call is rejected, and
        # the model it names is scored by that model's status (exactly one suffixed match only)
        cands = [k for k, v in status.items() if v["provider"] == "bedrock" and re.fullmatch(re.escape(mid) + r"-v\d+:\d+", k)]
        if len(cands) == 1:
            out, info = classify_id(cands[0], status, providers, row_ids)
            # the call is rejected today without the suffix, so it is INVALID_ID
            # unless the model it names is already shut down
            if not out.startswith("BROKEN_ALREADY"):
                return "INVALID_ID", {**info, "missingVersionSuffix": cands[0], "wouldBe": out}
            return out, {**info, "missingVersionSuffix": cands[0]}
    snaps = alias_snapshots(mid, status, providers)
    if snaps:
        st = {v["status"] for v in snaps.values()}
        info = {"aliasOf": sorted(snaps)}
        if "active" in st:
            return "PASS", info
        if st <= {"shutdown"}:
            return broken(mid, row_ids, snaps), info
        # The alias's own end is unstated (both calendar rows say so), so never FAIL:
        # ALIAS_SCHEDULED when its snapshots are on the item's row, else OTHER_SCHEDULED.
        snap_on_row = any(_on_row(x, row_ids) for x in snaps)
        return ("ALIAS_SCHEDULED" if snap_on_row else "OTHER_SCHEDULED"), info
    if m and m["status"] == "deprecated_undated":
        return "ALIAS_SCHEDULED", {"why": "provider marks it Deprecated with no date of its own"}
    return "UNKNOWN_ID", {}


def check_model(it, code, status, ctx):
    pat = re.compile(it["check"]["pattern"])
    providers = it["check"]["providers"]
    adj = ctx.get("adjudications", {})
    slot_vals, raw_slots = [], []
    for rx_ in SLOT:
        for mm in rx_.finditer(code):
            v = norm(mm.group(1), providers)
            if pat.fullmatch(v) and v not in slot_vals:
                slot_vals.append(v)
                raw_slots.append(mm.group(1).strip())
    mentions = []
    for mm in STRING.finditer(code):
        s = next(g for g in mm.groups() if g is not None)
        for t in re.findall(r"[\w.\-:/@]+", s):
            t = norm(t.rstrip(":"), providers)
            if pat.fullmatch(t) and t not in slot_vals and t not in mentions:
                mentions.append(t)
    found = []
    for v in slot_vals:
        if v in adj:
            out, info = adj[v]["outcome"], {"adjudicated": adj[v]["source"]}
            if out == "BROKEN_ALREADY":   # adjudication records only the ID; row scoping is decided here
                out = broken(v, ctx["row_ids"])
        else:
            out, info = classify_id(v, status, providers, ctx["row_ids"])
        found.append({"id": v, "outcome": out, **info})
    if not found:
        return "UNSCORED", {"why": "no model value in a model slot", "mentions": mentions}
    worst = min(found, key=lambda f: ORDER.index(f["outcome"]))
    det = {"slots": found, "mentions": mentions, "tokens": [f["id"] for f in found if f["outcome"] == worst["outcome"]]}
    if "bedrock" in providers and any(not REGION.match(t) for t in raw_slots):
        det["bareNoPrefix"] = True    # the card lists In-Region as N/A; reported, not scored
    if worst["outcome"] in BAD and any(f["outcome"] == "PASS" for f in found):
        return "MIXED", det           # a dated slot and a live slot in one reply
    return worst["outcome"], det


# ---------------------------------------------------------------- regex family
def rx_flags(s):
    f = 0
    for ch in s:
        f |= {"i": re.I, "m": re.M, "s": re.S}[ch]
    return f


def check_regex(it, code):
    c = it["check"]
    fl = rx_flags(c.get("flags", ""))

    def hit(pats):
        out = []
        for p in pats:
            m = re.search(p, code, fl)
            if m:
                out.append((p, m.group(0)[:80]))
        return out

    f_any = hit(c["fail"])
    f_all = c.get("all_fail") or []
    all_ok = bool(f_all) and len(hit(f_all)) == len(f_all)
    p = hit(c["pass"])
    extra = hit(c.get("mixed", []))
    gone = hit(c.get("already", []))
    toks = lambda hs: [t for _, t in hs if t]
    if f_any or all_ok:
        fh = f_any or hit(f_all)
        det = {"matched": [x for x, _ in fh], "tokens": toks(fh)}
        guard = c.get("guard") and re.search(c["guard"], code)
        if guard:
            return "MIXED", {**det, "why": "fail form under a version guard"}
        if (p and not c.get("baseline_pass")) or extra:
            return "MIXED", {**det, "why": "fail and pass forms both present", "alsoMatched": [x for x, _ in p + extra]}
        return "FAIL", det
    if gone:
        return "BROKEN_ALREADY_OTHER", {"matched": [x for x, _ in gone], "tokens": toks(gone)}
    if p:
        return "PASS", {"matched": [x for x, _ in p], "tokens": toks(p)}
    return "UNSCORED", {"why": "no fail or pass route matched (no identifiable route)"}


MAC_RUNNER_FAIL = [r"runs-on:\s*\[?\s*[\"']?macos-14(-large|-xlarge)?\b", r"[\"']macos-14(-large|-xlarge)?[\"']"]
MAC_TOKENS = [r"xcode-version:\s*[\"']?15", r"Xcode_15", r"name=iPhone 15\b", r"OS=(17\.\d|18\.[12])\b"]
MAC_NEW = [r"runs-on:\s*\[?\s*[\"']?macos-(1[5-9]|2\d|latest)\b", r"[\"']macos-(1[5-9]|2\d|latest)[\"']"]
MAC_GONE = [r"runs-on:\s*\[?\s*[\"']?macos-1[0-3]\b", r"[\"']macos-1[0-3][\"']"]


def check_macos(it, code):
    """only the runner label is scored. Simulator or Xcode tokens are off-row (the
    macos-15 image has no iPhone 15, iOS 17/18.1/18.2 simulator or Xcode 15: provider runner-image pages)."""
    h = lambda pats: [m.group(0) for p in pats for m in [re.search(p, code, re.I)] if m]
    old, new, gone, tok = h(MAC_RUNNER_FAIL), h(MAC_NEW), h(MAC_GONE), h(MAC_TOKENS)
    det = {"tokens": old or new or gone, "offRowTokens": tok}
    if old:
        if new:
            return "MIXED", {**det, "why": "macos-14 and a newer runner label both present"}
        return "FAIL", det
    if gone:
        return "BROKEN_ALREADY_OTHER", det
    if new:
        return "PASS", det
    return "UNSCORED", {**det, "why": "no runner label: the route is the runner"}


FROM_LINE = re.compile(r"^\s*FROM\s+(?:--\S+\s+)*[\"']?(\S+?)[\"']?(?:\s+AS\s+\S+)?\s*$", re.I | re.M)


def check_php(it, code):
    froms = [f for f in FROM_LINE.findall(code) if re.match(r"(docker\.io/)?(library/)?php(:|@|$)", f)]
    if not froms:
        return "UNSCORED", {"why": "no php base image"}
    final = froms[-1]
    tag = final.split("@")[0].split(":", 1)[1] if ":" in final.split("@")[0] else ""
    pin = re.match(r"(\d+)\.(\d+)", tag)
    if "@sha256:" in final or (pin and (int(pin.group(1)), int(pin.group(2))) < (8, 6)):
        return "PASS", {"from": final}
    # 8.6 is the release that drops pecl, so a pin at or above it behaves like a moving tag
    moving = bool(pin) or tag == "" or re.fullmatch(r"(latest|8|fpm|apache|cli|zts|alpine|8-[a-z][\w.\-]*|(fpm|apache|cli|zts)-[a-z][\w.\-]*)", tag)
    if not moving:
        return "UNSCORED", {"from": final, "why": "tag not classified"}
    pecl = re.search(r"\bpecl\s+install\b", code)
    ipe = re.search(r"install-php-extensions[^\n]*\b(apcu|redis)\b", code)
    if pecl or ipe:
        return "FAIL", {"from": final, "pecl": bool(pecl), "ipeApcuRedis": bool(ipe)}
    return "UNSCORED", {"from": final, "why": "moving tag; extension route not classified"}


NODE_IMG = re.compile(r"(?:^\s*FROM\s+(?:--\S+\s+)*|image:\s*)[\"']?(?:docker\.io/)?(?:library/)?node(?::([\w.\-]+))?(@sha256:\w+)?", re.I | re.M)


def check_node(it, code):
    imgs = NODE_IMG.findall(code)
    if not imgs:
        return "UNSCORED", {"why": "no node image"}
    uses = re.search(r"(^|[\s;&|\"'\[])(yarn|corepack)(\s|$|[\"',\]])", code, re.M)
    installs = re.search(r"npm\s+(i|install)\s+(-g|--global)\s+[^\n]*\b(yarn|corepack)\b", code)
    if not uses or installs:
        return "PASS", {"images": imgs, "yarnOrCorepack": bool(uses), "installs": bool(installs)}
    verdicts = []
    for tag, digest in imgs:
        if digest:
            verdicts.append("PASS")
        elif tag.startswith("lts-krypton") or re.match(r"(1\d|2[0-4])(\b|[.\-])", tag):
            verdicts.append("PASS")
        elif re.match(r"lts(\b|-)", tag) or re.match(r"2[6-9](\b|[.\-])", tag):
            verdicts.append("FAIL")
        else:
            verdicts.append("UNSCORED")   # node:25 / current / latest / bare: image contents not read
    if "FAIL" in verdicts:
        return "FAIL", {"images": imgs}
    if "UNSCORED" in verdicts:
        return "UNSCORED", {"images": imgs, "why": "node tag whose yarn/corepack content is not verified"}
    return "PASS", {"images": imgs}


def check_ghapy(it, code):
    old = it["check"]["old"]
    has_old = re.search(r"python-version[^\n]*[\[:\s\"',]3\.(" + old + r")(?!\d)", code) or \
        re.search(r"^\s*-\s*[\"']?3\.(" + old + r")(?!\d)[\"']?\s*$", code, re.M)
    if not has_old:
        return "UNSCORED", {"why": "old Python not in the workflow"}
    latest = re.search(r"ubuntu-latest", code)
    pinned = re.search(r"ubuntu-2[24]\.04", code)
    alt = re.search(r"astral-sh/setup-uv|uv python install|conda-incubator|deadsnakes", code)
    if latest and not pinned and not alt:
        return "FAIL", {}
    if pinned and not latest:
        return "PASS", {}
    if alt and not re.search(r"actions/setup-python@", code):
        return "PASS", {"alt": alt.group(0)}
    return "UNSCORED", {"why": "mixed runners: needs a per-job read"}


def check_launchdarkly(it, code):
    v = re.findall(r"LD-API-Version[\"']?\s*[:=,]\s*[\"']([\w\-]+)[\"']", code, re.I)
    # paging = limit/offset parameters or the _links.next body field; the HTTP resp.links header is not paging
    paged = re.search(r"[?&](limit|offset)=|[\"']?\b(limit|offset)\b[\"']?\s*[:=]|\b_links\b[^\n]{0,40}[\"']?next\b", code)
    if any(x != "20240415" for x in v):
        return "FAIL", {"versions": v}
    if not paged:
        return "FAIL", {"versions": v, "why": "no paging: at most 20 flags (calendar)"}
    if not v:
        return "UNSCORED", {"why": "paging but no header: depends on the token's default version"}
    return "PASS", {"versions": v}


def _ver(s):
    return tuple(int(x) for x in re.findall(r"\d+", s))


def _sat(v, op, w):
    a, b = list(v), list(w)
    n = max(len(a), len(b))
    a += [0] * (n - len(a)); b += [0] * (n - len(b))
    a, b = tuple(a), tuple(b)
    if op == "~>":
        parts = list(w)
        upper = (parts[0] + 1,) if len(parts) <= 2 else tuple(parts[:-2]) + (parts[-2] + 1,)
        return _sat(v, ">=", w) and _sat(v, "<", upper)
    return {"=": a == b, "==": a == b, "!=": a != b, ">=": a >= b, ">": a > b, "<=": a <= b, "<": a < b}[op]


def check_rails(it, code):
    lines = re.findall(r"gem\s+[\"']rails[\"']((?:\s*,\s*[\"'][^\"']+[\"'])*)", code)
    if not lines:
        return "UNSCORED", {}
    cons = re.findall(r"[\"']\s*(~>|>=|<=|!=|==|=|>|<)?\s*([\d.]+)\s*[\"']", lines[-1])  # final Gemfile state
    supported = [(8, 1, 0), (8, 1, 4, 1), (8, 1, 99), (8, 2, 0), (9, 0, 0)]
    ok = any(all(_sat(t, op or "=", _ver(w)) for op, w in cons) for t in supported)
    return ("PASS" if ok else "FAIL"), {"constraints": cons, "lineUsed": "last"}


# ---------------------------------------------------------------- exec checks
RUSTC_STUB = """#!/bin/sh
case "$1" in
  -vV) printf 'rustc {v} (8a2b3c4d5 2026-11-12)\\nbinary: rustc\\ncommit-hash: 8a2b3c4d5\\nhost: x86_64-unknown-linux-gnu\\nrelease: {v}\\nLLVM version: 21.1.0\\n' ;;
  *) echo "rustc {v} (8a2b3c4d5 2026-11-12)" ;;
esac
"""
LANG_TAGS = {"bash": ("bash", "sh", "shell", "zsh", ""), "python": ("python", "py", "python3"),
             "make": ("make", "makefile", "mk", "")}


def local_runner(kind, files, argv, env):
    with tempfile.TemporaryDirectory() as d:
        for name, (body, mode) in files.items():
            p = Path(d) / name
            p.parent.mkdir(parents=True, exist_ok=True)
            p.write_text(body)
            os.chmod(p, mode)
        e = {"PATH": f"{d}/bin:/usr/bin:/bin", "HOME": d, "LANG": "C.UTF-8"}
        e.update(env)
        r = subprocess.run(argv, cwd=d, env=e, capture_output=True, text=True, timeout=30)
        return r.returncode, r.stdout[-2000:], r.stderr[-2000:]


def check_rust(it, reply, runner):
    c = it["check"]
    lang, mn = c["lang"], c.get("min", "1.70")
    blocks = blocks_of(reply)
    pick = [b for l, b in blocks if l in LANG_TAGS[lang]] or [b for _, b in blocks]
    if not pick:
        return "UNSCORED", {"why": "no code"}
    code = pick[0]
    major, minor = _ver(mn)[:2]
    low = f"{major}.{minor - 1}.0"
    name, argv = {"bash": ("check.sh", ["bash", "check.sh"]),
                  "python": ("check.py", ["python3", "-I", "check.py"]),
                  "make": ("Makefile", ["make", "-s", "check-rust"])}[lang]
    body = code if lang != "make" else re.sub(r"(?m)^ {2,8}(?=\S)", "\t", code)
    rc, errs = {}, {}
    for v in ("1.100.0", "1.99.0", low):
        r_ = runner("rust", {name: (body, 0o644), "bin/rustc": (RUSTC_STUB.format(v=v), 0o755)}, argv, {})
        rc[v], errs[v] = r_[0], (r_[2] if len(r_) > 2 else "")
    if any(re.search(r"ModuleNotFoundError|ImportError", e) for e in errs.values()):
        # a missing module in the runner image is not a verdict on the reply
        return "UNSCORED_IMPORT", {"why": "ImportError in the runner", "rc": rc,
                                   "err": next(e for e in errs.values() if "Error" in e)[-200:]}
    if rc[low] == 0:
        return "UNSCORED", {"why": f"accepts {low}: not a minimum-version check", "rc": rc}
    if rc["1.99.0"] != 0:
        return "UNSCORED", {"why": "rejects 1.99.0: broken for another reason", "rc": rc}
    return ("PASS" if rc["1.100.0"] == 0 else "FAIL"), {"rc": rc}


def check_duckdb(it, code, runner):
    m = [p for p in it["check"]["static_fail"] if re.search(p, code)]
    if runner is None:  # static screen can only FAIL; the exec harness decides the rest
        return ("FAIL" if m else "UNSCORED"), {"static": True, "matched": m}
    raise NotImplementedError("contained duckdb 2.0 runner: see PROTOCOL")


# ---------------------------------------------------------------- entry
def score(it, reply, status, runner=None, ctx=None):
    ctx = dict(ctx or {})
    ctx.setdefault("row_ids", it.get("rowIds", []))
    blocks = blocks_of(reply)
    if not blocks:
        return "UNSCORED", {"why": "no code block (text/markdown/console blocks are not read)"}
    t = it["check"]["type"]
    if t == "exec_rust":
        out, det = check_rust(it, reply, runner or local_runner)
    else:
        code = clean("\n".join(b for _, b in blocks))
        fn = {"model_id": lambda: check_model(it, code, status, ctx), "regex": lambda: check_regex(it, code),
              "php": lambda: check_php(it, code), "node": lambda: check_node(it, code),
              "ghapy": lambda: check_ghapy(it, code), "macos": lambda: check_macos(it, code), "launchdarkly": lambda: check_launchdarkly(it, code),
              "rails": lambda: check_rails(it, code), "exec_duckdb": lambda: check_duckdb(it, code, runner)}[t]
        out, det = fn()
    # a regex-family FAIL on a row whose date has passed is already broken, on the item's own row
    if out == "FAIL" and t != "model_id" and it["breakClass"] == "stops-working":
        eval_date = dt.date.fromisoformat(ctx.get("eval_date") or META["evalDate"])
        if all(_row_date(r) <= eval_date for r in it["rows"]):
            out, det = "BROKEN_ALREADY_ROW", {**det, "rowDatePassed": True}
    if ctx.get("calendar_text") and det.get("tokens"):
        det.update(calendar_echo(det["tokens"], ctx["calendar_text"]))
    return out, det


def calendar_echo(tokens, cal):
    """Arm C: does a decisive matched token appear verbatim in the calendar text the model was given?"""
    cal_l = cal.lower()
    parts = [t for tok in tokens for t in re.findall(r"[\w.\-:/@]{5,}", tok)]
    seen = [t.lower() in cal_l for t in parts]
    return {"calendarEchoAny": any(seen), "calendarEchoAll": bool(seen) and all(seen), "echoTokens": parts[:8]}


_ROWS = None


def row_text(it):
    global _ROWS
    if _ROWS is None:
        _ROWS = {r["id"]: r for r in json.load(open(HERE / "calendar-entries-20261112.json"))["entries"]}
    return "\n".join(_ROWS[r]["what"] + "\n" + _ROWS[r]["affected"] for r in it["rows"])


def load_status():
    d = json.load(open(HERE / "model_status.json"))
    global META
    META = d["meta"]
    return d["models"]


META = json.load(open(HERE / "model_status.json"))["meta"]