Repository navigation
Expand file tree
/
Copy pathjudge.py
More file actions
797 lines (725 loc) · 36 KB
/
Copy pathjudge.py
File metadata and controls
797 lines (725 loc) · 36 KB
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
#!/usr/bin/env python3
"""
judge.py — frontier reference + LLM-as-judge (off-node, stdlib only).
Two backends (JUDGE_BACKEND):
copilot — the official GitHub Copilot CLI (`npm i -g @github/copilot`), the
supported "Copilot SDK" path. Drives `claude-opus-4.8` (Claude
4.8 Max, CONFIRMED live 2026-06-16) and gpt-5.5 etc. through the
account's Copilot subscription — NO Anthropic key, NO GitHub
Models. Auth is whatever the CLI already has (keychain). Note:
batch judging consumes Copilot AI Credits (measured ~7.7/call for
claude-opus-4.8 via the CLI, dominated by the cached system/tool
context). judge.py now PARSES the footer's Tokens/AI-Credits line
(cache read = 'cached', cache write = 'written') and records exact
per-call billing into judged.jsonl + a cost summary.
github — GitHub Models, OpenAI-compatible (GITHUB_TOKEN, PAT models:read).
VERIFIED 2026-06-16 via `gh models list`: GitHub Models hosts NO
Anthropic/Claude models (only openai/meta/microsoft/mistral/
cohere/deepseek), so the strongest judge here is openai/gpt-5 or
o3 — NOT Claude.
anthropic — Anthropic API (ANTHROPIC_API_KEY) — alternative Claude path if you
have a key instead of Copilot.
# discover the EXACT judge model id for your backend, then exit:
JUDGE_BACKEND=copilot python3 judge.py --list-models # finds claude-opus-4.8
JUDGE_BACKEND=anthropic ANTHROPIC_API_KEY=... python3 judge.py --list-models
JUDGE_BACKEND=github GITHUB_TOKEN=... python3 judge.py --list-models
export JUDGE_BACKEND=copilot JUDGE_MODEL=claude-opus-4.8
python3 judge.py --reference --scenarios scenarios.json --out reference.jsonl
python3 judge.py --judge --results results.jsonl --out judged.jsonl
# ensemble (bias control, 2nd family): adds a second judge per answer
python3 judge.py --judge --ensemble copilot:gpt-5.5 --results r.jsonl --out judged.jsonl
The judge/reference is EVAL SCAFFOLDING — the small local model under test never
calls it. It runs on the Mac, never the node, so offline/breakglass purity holds.
Bias controls (MT-Bench/AlpacaEval, see MARKET.md): blind to author, must cite
evidence, grades vs frozen gold+rubric, 1-5; hand-validate a κ subset.
"""
from __future__ import annotations
import argparse
import concurrent.futures as cf
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import time
import urllib.request
import analysis_metrics
GITHUB_ENDPOINT = os.environ.get("GITHUB_MODELS_ENDPOINT", "https://models.github.ai/inference")
GITHUB_CATALOG = os.environ.get("GITHUB_MODELS_CATALOG", "https://models.github.ai/catalog/models")
ANTHROPIC_ENDPOINT = os.environ.get("ANTHROPIC_ENDPOINT", "https://api.anthropic.com")
ANTHROPIC_VERSION = os.environ.get("ANTHROPIC_VERSION", "2023-06-01")
COPILOT_BIN = os.environ.get("COPILOT_BIN", "copilot")
# Defaults are env-overridable; confirm copilot ids via --list-models.
DEFAULT_MODEL = {"copilot": "claude-opus-4.8", "github": "openai/gpt-5",
"anthropic": "claude-opus-4-8"}
BACKENDS = ("copilot", "github", "anthropic")
_FOOTER_RE = re.compile(r"^(Changes|AI Credits|Tokens)\b")
_ANSI_RE = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")
def analysis_condition_identity(result_row, evaluation_policy):
"""Return one normalized identity for stamping, indexing, and resume."""
normalized = analysis_metrics.normalize_condition_provenance(result_row)
return analysis_metrics.analysis_condition(
normalized,
evaluation_policy=evaluation_policy,
)
def analysis_condition_fields(result_row, evaluation_policy):
"""Canonical condition provenance copied from an inference row."""
identity = analysis_condition_identity(result_row, evaluation_policy)
if identity.incomplete:
raise ValueError(
"cannot judge an incomplete analysis condition: "
+ ", ".join(identity.missing_fields)
)
return {
"analysis_schema_version": analysis_metrics.ANALYSIS_SCHEMA_VERSION,
"analysis_condition_key_sha256": identity.sha256,
"condition_identity_incomplete": identity.incomplete,
"evaluation_policy": evaluation_policy,
}
def judgement_resume_keys(
row,
*,
condition_sha=None,
judge_backend=None,
judge_model=None,
):
"""Exact and historical resume keys for one result/judgement pair."""
condition_sha = condition_sha or row.get("analysis_condition_key_sha256")
judge_backend = judge_backend or row.get("judge_backend")
judge_model = judge_model or row.get("judge_model")
scenario = row.get("scenario")
rep = str(row.get("rep", 0))
exact = (
str(condition_sha) if condition_sha else None,
scenario,
rep,
judge_backend,
judge_model,
)
legacy_base = list(analysis_metrics.legacy_judge_join_key(row))
legacy_base[2] = rep
return exact, (*legacy_base, judge_backend, judge_model)
def judgement_is_done(
row,
*,
condition_sha,
judge_backend,
judge_model,
done_exact,
done_legacy,
legacy_resume_safe,
allow_legacy_resume,
):
exact, legacy = judgement_resume_keys(
row,
condition_sha=condition_sha,
judge_backend=judge_backend,
judge_model=judge_model,
)
return exact in done_exact or (
allow_legacy_resume
and legacy_resume_safe
and legacy in done_legacy
)
def _http_json(url, *, headers, data=None, timeout=180, method=None):
req = urllib.request.Request(
url, data=(json.dumps(data).encode() if data is not None else None),
headers=headers, method=method or ("POST" if data is not None else "GET"))
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read().decode())
class Judge:
"""Backend-agnostic frontier client. backend in {github, anthropic}."""
def __init__(self, backend=None, model=None):
self.backend = (backend or os.environ.get("JUDGE_BACKEND", "copilot")).lower()
if self.backend not in BACKENDS:
sys.exit(f"unknown JUDGE_BACKEND={self.backend!r} (use one of {BACKENDS})")
self.model = model or os.environ.get("JUDGE_MODEL") or DEFAULT_MODEL[self.backend]
self._tok = None
self.last_usage = None # token / credit / cache billing of the most recent call
if self.backend == "github":
self._tok = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
if not self._tok:
sys.exit("set GITHUB_TOKEN (PAT with models:read). NOTE: GitHub Models has NO "
"Claude — use JUDGE_BACKEND=copilot for Claude 4.8.")
elif self.backend == "anthropic":
self._tok = os.environ.get("ANTHROPIC_API_KEY")
if not self._tok:
sys.exit("set ANTHROPIC_API_KEY for the Anthropic Claude judge.")
else: # copilot
self._bin = shutil.which(COPILOT_BIN) or COPILOT_BIN
if not shutil.which(COPILOT_BIN):
sys.exit("Copilot CLI not found. Install: brew install --cask copilot-cli "
"(or npm i -g @github/copilot), then run `copilot login`.")
def list_models(self):
"""Return [(id, label)] of judge models available on this backend."""
if self.backend == "copilot":
# the CLI caches the ids it has accepted under ~/.copilot; harvest them.
ids = set()
root = os.path.expanduser("~/.copilot")
for dp, _, fns in os.walk(root):
for fn in fns:
try:
with open(os.path.join(dp, fn), "rb") as fh:
blob = fh.read().decode("utf-8", "ignore")
except OSError:
continue
for m in re.findall(r'"model"\s*:\s*"([^"]+)"', blob):
ids.add(m)
return sorted((i, "copilot") for i in ids)
if self.backend == "github":
data = _http_json(GITHUB_CATALOG, headers={
"Authorization": f"Bearer {self._tok}", "Accept": "application/json"})
items = data if isinstance(data, list) else data.get("data", data.get("models", []))
return [(m.get("id") or m.get("name"),
m.get("publisher") or m.get("vendor") or "") for m in items]
data = _http_json(f"{ANTHROPIC_ENDPOINT}/v1/models", headers={
"x-api-key": self._tok, "anthropic-version": ANTHROPIC_VERSION})
return [(m.get("id"), m.get("display_name", "")) for m in data.get("data", [])]
@staticmethod
def _strip_copilot_footer(out):
lines = [_ANSI_RE.sub("", ln) for ln in (out or "").splitlines()]
while lines and (not lines[-1].strip() or _FOOTER_RE.match(lines[-1].strip())):
lines.pop()
return "\n".join(lines).strip()
@staticmethod
def _parse_copilot_footer(out):
"""Billing from the Copilot CLI footer (the lines we otherwise drop), e.g.
AI Credits 7.69 (6s)
Tokens ↑ 27.6k (16.7k cached, 11.0k written) • ↓ 4
'cached' = prompt-cache READ (a hit), 'written' = cache CREATION (a miss)."""
def _n(s):
s = s.strip().lower().replace(",", "")
mult = 1
if s.endswith("k"):
mult, s = 1000, s[:-1]
elif s.endswith("m"):
mult, s = 1_000_000, s[:-1]
try:
return int(float(s) * mult)
except ValueError:
return None
u = {}
for ln in (out or "").splitlines():
ln = _ANSI_RE.sub("", ln).strip()
m = re.match(r"AI Credits\s+([\d.]+)", ln)
if m:
u["ai_credits"] = float(m.group(1))
if ln.startswith("Tokens"):
for key, pat in (("tokens_in", r"\u2191\s*([\d.,km]+)"),
("tokens_out", r"\u2193\s*([\d.,km]+)"),
("cache_read", r"([\d.,km]+)\s*cached"),
("cache_write", r"([\d.,km]+)\s*written")):
mm = re.search(pat, ln, re.I)
if mm:
u[key] = _n(mm.group(1))
return u or None
@staticmethod
def _norm_usage(u):
"""Normalize an OpenAI/Anthropic usage object to the same keys as the
Copilot footer (tokens_in/out, cache_read/write). Anthropic splits cache
read vs creation; OpenAI reports only cached (read)."""
if not u:
return None
det = u.get("prompt_tokens_details") or {}
out = {
"tokens_in": u.get("prompt_tokens", u.get("input_tokens")),
"tokens_out": u.get("completion_tokens", u.get("output_tokens")),
"cache_read": u.get("cache_read_input_tokens", det.get("cached_tokens")),
"cache_write": u.get("cache_creation_input_tokens"),
}
return {k: v for k, v in out.items() if v is not None} or None
def complete(self, system, user, *, json_mode=False, temperature=0):
if self.backend == "copilot":
prompt = f"{system}\n\n{user}"
env = dict(os.environ)
env.pop("COPILOT_ALLOW_ALL", None)
p = subprocess.run(
[self._bin, "--model", self.model, "--no-color", "--available-tools=",
"--no-custom-instructions", "--no-remote", "--no-remote-export", "-p", prompt],
capture_output=True, text=True, timeout=300, env=env)
if p.returncode != 0 and not p.stdout.strip():
raise RuntimeError(f"copilot CLI failed: {p.stderr.strip()[:200]}")
self.last_usage = self._parse_copilot_footer(p.stdout)
return self._strip_copilot_footer(p.stdout)
if self.backend == "github":
body = {"model": self.model, "temperature": temperature,
"messages": [{"role": "system", "content": system},
{"role": "user", "content": user}]}
if json_mode:
body["response_format"] = {"type": "json_object"}
d = _http_json(f"{GITHUB_ENDPOINT}/chat/completions", headers={
"Authorization": f"Bearer {self._tok}", "Content-Type": "application/json"}, data=body)
self.last_usage = self._norm_usage(d.get("usage"))
return d["choices"][0]["message"]["content"]
# anthropic messages API (stdlib HTTP — no SDK dependency)
body = {"model": self.model, "max_tokens": 1024, "temperature": temperature,
"system": system, "messages": [{"role": "user", "content": user}]}
d = _http_json(f"{ANTHROPIC_ENDPOINT}/v1/messages", headers={
"x-api-key": self._tok, "anthropic-version": ANTHROPIC_VERSION,
"content-type": "application/json"}, data=body)
self.last_usage = self._norm_usage(d.get("usage"))
return "".join(b.get("text", "") for b in d.get("content", []) if b.get("type") == "text")
JUDGE_SYS = (
"You are a strict, fair evaluator of homelab operations answers. "
"You are given the CONTEXT an assistant saw, the TASK, a GOLD reference "
"answer, a RUBRIC, and the assistant's ANSWER. Score the ANSWER 1-5:\n"
"5=matches gold intent, correct + actionable + safe; 3=partially correct or "
"missing a key point; 1=wrong, unsafe, or non-responsive.\n"
"You MUST cite the specific evidence from CONTEXT that justifies your score. "
"Judge correctness and safety, NOT verbosity or style. If the rubric names a "
"HARD FAIL condition and the answer meets it, score 1.\n"
'Reply as JSON: {"score": <1-5>, "evidence": "<quote/why>", "verdict": "<one line>", '
'"criteria_met": ["<rubric points the answer satisfied>"], '
'"criteria_missed": ["<rubric points the answer missed>"]}'
)
def _as_list(value):
if value is None:
return []
if isinstance(value, list):
return value
return [str(value)]
def normalize_judgement(judgement, *, fallback_score=None, fallback_verdict=None,
fallback_evidence=None, fallback_criteria_missed=None):
"""Return a schema-stable judge payload.
Some legitimate paths do not involve a model judge at all: a DNF/stall can
produce no answer text, so judge.py assigns score=1/verdict=empty locally.
Those rows still need the same detail fields as normal judge rows so the JSONL
artifact is complete and reportable.
"""
if not isinstance(judgement, dict):
judgement = {}
out = dict(judgement)
if out.get("score") is None and fallback_score is not None:
out["score"] = fallback_score
out["verdict"] = str(out.get("verdict") or fallback_verdict or "missing verdict")
out["evidence"] = str(
out.get("evidence")
or out.get("reason")
or out.get("rationale")
or fallback_evidence
or "Judge did not return evidence."
)
out["criteria_met"] = _as_list(out.get("criteria_met"))
missed = _as_list(out.get("criteria_missed"))
if not missed and fallback_criteria_missed:
missed = _as_list(fallback_criteria_missed)
out["criteria_missed"] = missed
return out
class EmptyJudgeResponse(Exception):
"""The judge backend returned no text — transient (retryable), unlike a parse error."""
def recover_jsonl_tail(path):
"""Remove only a torn final fragment; reject malformed durable interior rows."""
if not os.path.exists(path):
return
with open(path, "r+b") as handle:
payload = handle.read()
if payload and not payload.endswith(b"\n"):
boundary = payload.rfind(b"\n") + 1
handle.seek(boundary)
handle.truncate()
handle.flush()
os.fsync(handle.fileno())
payload = payload[:boundary]
for line_number, raw in enumerate(payload.splitlines(), 1):
if not raw.strip():
continue
try:
value = json.loads(raw)
except json.JSONDecodeError as exc:
raise ValueError(f"{path}:{line_number} contains malformed durable JSON") from exc
if not isinstance(value, dict):
raise ValueError(f"{path}:{line_number} is not a JSON object")
def append_jsonl_durable(path, row):
payload = json.dumps(row, separators=(",", ":")).encode() + b"\n"
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
try:
written = os.write(descriptor, payload)
if written != len(payload):
raise OSError(f"short JSONL append: {written}/{len(payload)} bytes")
os.fsync(descriptor)
finally:
os.close(descriptor)
def load_judgement_resume_state(path):
"""Return only canonical successful attempts as resumable judge keys."""
recover_jsonl_tail(path)
done_exact = set()
done_legacy = set()
if not os.path.exists(path):
return done_exact, done_legacy
for line in open(path):
try:
row = json.loads(line)
except json.JSONDecodeError:
continue
if not analysis_metrics.judgement_success(row):
continue
condition_sha = row.get("analysis_condition_key_sha256")
exact_key, legacy_key = judgement_resume_keys(row)
if condition_sha:
done_exact.add(exact_key)
else:
done_legacy.add(legacy_key)
return done_exact, done_legacy
# A scenario set without a per-scenario `judge_rubric` must NOT make every judge call
# KeyError -> retry -> SKIP (which yields 0 judged rows); fall back to a generic rubric.
_DEFAULT_RUBRIC = (
"Grade the ANSWER against the GOLD REFERENCE: reward correctness, completeness, "
"and following the task's requested output format; penalize hallucination, missing "
"required elements, and ignoring the requested format."
)
def judge_one(judge, scen, answer):
user = (f"--- CONTEXT ---\n{scen['context']}\n\n--- TASK ---\n{scen['question']}\n\n"
f"--- GOLD REFERENCE ---\n{scen['gold_answer']}\n\n"
f"--- RUBRIC ---\n{scen.get('judge_rubric') or _DEFAULT_RUBRIC}\n\n"
f"--- ANSWER (author hidden) ---\n{answer}\n\n"
"Score now as the specified JSON.")
raw = judge.complete(JUDGE_SYS, user, json_mode=True)
if not (raw or "").strip():
# An EMPTY completion (Copilot-CLI hiccup) is transient, not a parse
# error: signal a retry so _judge_task's attempt loop re-issues it,
# instead of recording a score=None "empty" verdict that resume can't heal.
raise EmptyJudgeResponse("judge backend returned no text")
try:
return normalize_judgement(json.loads(raw))
except (json.JSONDecodeError, TypeError):
m = re.search(r"\{.*\}", raw or "", re.S) # tolerate prose-wrapped JSON (anthropic)
if m:
try:
return normalize_judgement(json.loads(m.group(0)))
except json.JSONDecodeError:
pass
return normalize_judgement(
{"score": None, "verdict": (raw or "")[:200]},
fallback_evidence="parse_error",
fallback_criteria_missed=["judge response could not be parsed"],
)
def _message_text(message):
if not isinstance(message, dict):
return str(message or "")
parts = message.get("parts")
if isinstance(parts, list):
return "\n".join(
str(part.get("content") or part.get("text") or "") if isinstance(part, dict) else str(part)
for part in parts
)
content = message.get("content")
if isinstance(content, list):
return "\n".join(
str(part.get("text") or part.get("content") or "") if isinstance(part, dict) else str(part)
for part in content
)
return str(content or message.get("text") or message.get("message") or "")
def answer_from_result_row(row):
for key in ("gen_ai.completion", "answer", "response_text", "text", "output"):
value = row.get(key)
if value:
return str(value)
messages = row.get("gen_ai.output.messages")
if isinstance(messages, list):
answer = "\n".join(_message_text(message) for message in messages).strip()
if answer:
return answer
output_message = row.get("distill.output_message")
if isinstance(output_message, dict):
answer = str(output_message.get("content") or "").strip()
if answer:
return answer
return ""
def reference_one(judge, scen):
user = (f"--- CONTEXT ---\n{scen['context']}\n\n--- TASK ---\n{scen['question']}\n\n"
"Answer as the ideal homelab operator would: correct, concise, actionable, safe.")
return judge.complete("You are an expert homelab SRE.", user)
GOLD_REVIEW_SYS = (
"You are an ADVERSARIAL reviewer of a benchmark's gold answers and scoring "
"(option-C de-biasing). Given the CONTEXT, TASK, the PROPOSED GOLD answer, the "
"RUBRIC, and the DETERMINISTIC CHECKS, find anything wrong: a gold that is "
"factually wrong, incomplete, or over-specified; a rubric that rewards the wrong "
"thing; or deterministic checks that are gameable, too loose, or too strict "
"(would pass a wrong answer or fail a correct one). Be skeptical, specific, and "
"concise. If the gold and scoring are sound, say so.\n"
'Reply as JSON: {"agree": true|false, "severity": "none|minor|major", '
'"issues": ["..."], "suggested_fix": "..."}'
)
def gold_review_one(judge, scen):
checks = "\n".join(
f"- {c['type']}: {c.get('desc', '')} "
f"{c.get('patterns', c.get('value', c.get('allowed', '')))}"
for c in scen.get("deterministic_checks", []))
user = (f"--- CONTEXT ---\n{scen['context']}\n\n--- TASK ---\n{scen['question']}\n\n"
f"--- PROPOSED GOLD ---\n{scen['gold_answer']}\n\n"
f"--- RUBRIC ---\n{scen.get('judge_rubric') or _DEFAULT_RUBRIC}\n\n"
f"--- DETERMINISTIC CHECKS ---\n{checks}\n\nReview now as the specified JSON.")
raw = judge.complete(GOLD_REVIEW_SYS, user, json_mode=True)
try:
return json.loads(raw)
except (json.JSONDecodeError, TypeError):
m = re.search(r"\{.*\}", raw or "", re.S)
if m:
try:
return json.loads(m.group(0))
except json.JSONDecodeError:
pass
return {"agree": None, "severity": "parse_error", "issues": [(raw or "")[:200]]}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--scenarios", default="data/scenarios.json")
ap.add_argument("--results", default="results.jsonl")
ap.add_argument("--out")
ap.add_argument("--judge", action="store_true")
ap.add_argument("--reference", action="store_true")
ap.add_argument("--gold-review", action="store_true",
help="frontier adversarially reviews every gold+rubric+checks "
"(option-C); writes a disagreement list to --out for you to adjudicate")
ap.add_argument("--list-models", action="store_true",
help="list judge models on the selected backend (find the Claude id), then exit")
ap.add_argument("--check-backends", action="store_true",
help="make one minimal authenticated request to every declared judge, then exit")
ap.add_argument("--backend", help="copilot | github | anthropic (overrides JUDGE_BACKEND)")
ap.add_argument("--model", help="judge model id (overrides JUDGE_MODEL)")
ap.add_argument("--ensemble",
help="comma list of extra judges as backend:model for bias control, "
"e.g. 'copilot:gpt-5.5'. Each answer is scored by every judge.")
ap.add_argument("--allow-legacy-resume", action="store_true",
help="explicitly reuse unique historical judged rows without "
"canonical condition hashes")
ap.add_argument("--outputs-dir", default="outputs", help="where run.py wrote model answers")
ap.add_argument("--workers", type=int, default=int(os.environ.get("JUDGE_WORKERS", "8")),
help="parallel judge calls (default 8 = the Copilot-CLI concurrency ceiling; "
"set 1 for serial). Each call is an independent Copilot agent.")
args = ap.parse_args()
primary = Judge(backend=args.backend, model=args.model)
judges = [primary]
if args.ensemble:
for spec in args.ensemble.split(","):
spec = spec.strip()
if not spec:
continue
be, _, mo = spec.partition(":")
judges.append(Judge(backend=be or None, model=mo or None))
specs = [(judge.backend, judge.model) for judge in judges]
evaluation_policy = analysis_metrics.evaluation_policy_id([
{"judge_backend": backend, "judge_model": model}
for backend, model in specs
])
if args.list_models:
for mid, who in sorted(primary.list_models(), key=lambda x: (x[0] or "")):
tag = " <-- CLAUDE" if "claude" in (mid or "").lower() else ""
print(f"{mid}\t{who}{tag}")
return
if args.check_backends:
for judge in judges:
response = judge.complete(
"This is an authentication and model-entitlement check. Do not use tools.",
"Reply with exactly: COPILOT_BACKEND_OK",
)
if response.strip() != "COPILOT_BACKEND_OK":
sys.exit(
f"judge backend check failed for {judge.backend}:{judge.model}: "
f"unexpected response {response[:80]!r}"
)
print(json.dumps({
"backend": judge.backend,
"model": judge.model,
"ok": True,
"usage": judge.last_usage,
}, sort_keys=True))
return
scen_path = args.scenarios
scen_sha = hashlib.sha256(open(scen_path, "rb").read()).hexdigest()
scen = {s["id"]: s for s in json.load(open(scen_path))["scenarios"]}
if args.reference:
if not args.out:
sys.exit("--reference needs --out")
with open(args.out, "w") as f:
for sid, s in scen.items():
ans = reference_one(primary, s)
f.write(json.dumps({"scenario": sid, "frontier_model": primary.model,
"reference_answer": ans}) + "\n")
sys.stderr.write(f"ref {sid} done\n")
return
if args.gold_review:
if not args.out:
sys.exit("--gold-review needs --out")
flagged = 0
with open(args.out, "w") as f:
for sid, s in scen.items():
r = gold_review_one(primary, s)
bad = (r.get("agree") is False) or (r.get("severity") in ("minor", "major"))
flagged += bool(bad)
f.write(json.dumps({"scenario": sid, "judge_model": primary.model, **r}) + "\n")
sys.stderr.write(f"review {sid}: agree={r.get('agree')} sev={r.get('severity')}\n")
sys.stderr.write(f"\n{flagged}/{len(scen)} scenario(s) flagged for your "
f"adjudication. See {args.out}.\n")
return
if args.judge:
if not args.out:
sys.exit("--judge needs --out")
# resume: skip (model, scenario, rep, memory_context, inference_strategy, judge_model) already
# written to --out, so paired no-memory/memory runs can be judged together
# without one condition suppressing the other.
# so a long ensemble run that dies (sleep/network) continues instead of
# re-judging from scratch. Output is opened in APPEND mode.
done_exact, done_legacy = load_judgement_resume_state(args.out)
if os.path.exists(args.out):
if done_exact or done_legacy:
legacy_mode = "eligible" if args.allow_legacy_resume else "ignored (no opt-in)"
sys.stderr.write(
f"resume: {len(done_exact)} exact + {len(done_legacy)} legacy judged rows "
f"({legacy_mode}) already in {args.out}\n"
)
cost = {"calls": 0, "ai_credits": 0.0, "tokens_in": 0, "tokens_out": 0,
"cache_read": 0, "cache_write": 0}
# Build the task list (one per pending model x judge), then run them through a
# bounded pool. 8 parallel Copilot agents is the historical ceiling before the
# CLI rate-limits (docs/archive/CONSOLIDATION-PLAN.md). Each task builds its OWN Judge
# so the per-call `last_usage` is never shared across threads.
result_rows = []
for line in open(args.results):
line = line.strip()
if not line:
continue
try:
row = json.loads(line)
except json.JSONDecodeError:
continue # tolerate a partial last line (mid-rsync snapshot)
sid = row.get("scenario")
if not sid or sid not in scen:
continue
row_sha = row.get("env.scenarios_sha")
if row_sha != scen_sha:
sys.stderr.write(f"skip {row.get('model')} {sid}: result scenario hash {row_sha!r} != selected {scen_sha[:12]}…\n")
continue
result_rows.append(analysis_metrics.normalize_condition_provenance(row))
identities = {
id(row): analysis_condition_identity(row, evaluation_policy)
for row in result_rows
}
_, legacy_conditions = analysis_metrics.judge_condition_index(
(identities[id(row)], row) for row in result_rows
)
tasks = []
for row in result_rows:
sid = row.get("scenario")
rep = row.get("rep", 0)
memory_context = row.get("env.memory_context") or "none"
inference_strategy = row.get("env.inference_strategy") or row.get("strategy.id") or "baseline"
inference_runtime = row.get("env.inference_runtime") or row.get("adapter") or "ollama"
identity = identities[id(row)]
try:
condition_fields = analysis_condition_fields(row, evaluation_policy)
except ValueError as exc:
sys.exit(f"cannot judge {row.get('model')} {sid} r{rep}: {exc}")
legacy_key = analysis_metrics.legacy_judge_join_key(row)
legacy_resume_safe = len(legacy_conditions.get(legacy_key, frozenset())) == 1
if all(
judgement_is_done(
row,
condition_sha=identity.sha256,
judge_backend=backend,
judge_model=model,
done_exact=done_exact,
done_legacy=done_legacy,
legacy_resume_safe=legacy_resume_safe,
allow_legacy_resume=args.allow_legacy_resume,
)
for backend, model in specs
):
continue
base = f"{row['model'].replace('/', '_').replace(':', '_')}__{sid}"
answer = answer_from_result_row(row)
if not answer:
# run.py suffixes __r{rep} only when repeats>1; try both. This is
# legacy fallback only; embedded completions avoid filename
# collisions when concatenating memory/no-memory twin runs.
for cand in (f"{base}__r{rep}.txt", f"{base}.txt"):
fp = os.path.join(args.outputs_dir, cand)
if os.path.exists(fp):
answer = open(fp).read()
break
for be, mo in specs:
if judgement_is_done(
row,
condition_sha=identity.sha256,
judge_backend=be,
judge_model=mo,
done_exact=done_exact,
done_legacy=done_legacy,
legacy_resume_safe=legacy_resume_safe,
allow_legacy_resume=args.allow_legacy_resume,
):
continue
tasks.append((row["model"], sid, rep, memory_context, inference_strategy,
inference_runtime, condition_fields, answer, be, mo))
def _judge_task(t):
(model, sid, rep, memory_context, inference_strategy, inference_runtime,
condition_fields, answer, be, mo) = t
if not answer:
return (model, sid, rep, memory_context, inference_strategy, inference_runtime,
condition_fields, be, mo, normalize_judgement(
{},
fallback_score=1,
fallback_verdict="no_answer",
fallback_evidence="No answer text was available for judging; the inference row did not produce a completion.",
fallback_criteria_missed=["answer was empty or unavailable"],
) | {"deterministic_no_answer": True}, None)
jg = Judge(backend=be, model=mo) # fresh per task -> thread-safe usage
for attempt in range(4):
try:
j = normalize_judgement(judge_one(jg, scen[sid], answer))
if not analysis_metrics.judgement_success(j):
missed = list(j.get("criteria_missed") or [])
if "judge response violated the judgement contract" not in missed:
missed.append("judge response violated the judgement contract")
j.update({
"score": None,
"evidence": "invalid_contract",
"criteria_missed": missed,
})
return (model, sid, rep, memory_context, inference_strategy, inference_runtime,
condition_fields, be, mo, j, jg.last_usage)
except Exception as e: # noqa: BLE001
if attempt == 3:
sys.stderr.write(f"judge[{mo}] {model} {sid} r{rep} "
f"SKIP after 4 tries: {str(e)[:120]}\n")
else:
time.sleep(5 * (attempt + 1))
return None # leave unjudged; a resume pass re-judges it
workers = max(1, args.workers)
sys.stderr.write(f"judging {len(tasks)} (answer x judge) calls, {workers}-wide\n")
# single durable writer (the main thread); each row is one fsynced append.
with cf.ThreadPoolExecutor(max_workers=workers) as ex:
for fut in cf.as_completed([ex.submit(_judge_task, t) for t in tasks]):
res = fut.result()
if res is None:
continue
(model, sid, rep, memory_context, inference_strategy, inference_runtime,
condition_fields, be, mo, j, u) = res
if u:
cost["calls"] += 1
for k in ("ai_credits", "tokens_in", "tokens_out", "cache_read", "cache_write"):
cost[k] += u.get(k) or 0
append_jsonl_durable(args.out, {
"model": model, "scenario": sid, "rep": rep,
**condition_fields,
"memory_context": memory_context,
"inference_strategy": inference_strategy,
"inference_runtime": inference_runtime,
"adapter": inference_runtime,
"scenarios_path": scen_path,
"scenarios_sha256": scen_sha,
"judge_backend": be, "judge_model": mo,
"usage": u, **j,
})
sys.stderr.write(f"judge[{mo}] {model} {sid} r{rep} -> {j.get('score')}\n")
ci = cost["tokens_in"]
hit = round(100 * cost["cache_read"] / ci, 1) if ci else None
sys.stderr.write(
f"\n== judge cost: {cost['calls']} calls · {cost['ai_credits']:.1f} AI credits · "
f"in={ci} out={cost['tokens_out']} · cache_read={cost['cache_read']} "
f"({hit}% of input cached) · cache_write={cost['cache_write']} ==\n")
return
sys.exit("pass --judge, --reference, or --list-models")
if __name__ == "__main__":
main()