Skip to content

A skill to stop your coding agent from burying the answer. ADHD-friendly output.

feat: add a blind judge so the harness can produce scores

Lonnie Zaneff1d3c41f950
diff --git a/evals/README.md b/evals/README.md
index 3f781c7..ee5ae67 100644
--- a/evals/README.md
+++ b/evals/README.md
@@ -40,13 +40,42 @@ Runs are resumable: rerun the same command after a provider failure and complete
## Judge and score
-Blind the `condition` field before judging. Write one JSON object per response with these fields:
+`scripts/judge.py` grades the responses and writes the score rows for you:
+
+```bash
+python3 scripts/judge.py \
+ --runner claude \
+ --responses evals/results/responses.jsonl \
+ --output evals/results/scores.jsonl
+```
+
+It groups responses by `(case_id, trial)` and grades every condition for a case
+in one call, so the conditions are compared against each other rather than
+scored in isolation. Blinding is structural, not a convention the grader is
+asked to respect: each condition is relabelled `A`/`B`/`C` before the prompt is
+built, and the label order is permuted per group, so position carries no signal.
+The permutation comes from a digest of the group key rather than a random
+source, so a resumed run reproduces the labels it used the first time.
+
+Only the region of `rubric.md` between the `<!-- judge:begin -->` and
+`<!-- judge:end -->` markers reaches the grader. The release-gate rules below
+those markers name the conditions, and sending them to a blind grader would
+leak the vocabulary the blinding exists to hide. Keep anything condition-identifying
+outside that block.
+
+Runs are resumable the same way generation is: groups already present in the
+output file are skipped. A group missing a condition cannot be scored — the
+conditions would no longer be judged on identical rows — so it is reported on
+stderr and left out rather than silently dropped.
+
+Judging by hand instead is still supported: blind the `condition` field
+yourself and write one JSON object per response with these fields.
```json
{"case_id":"direct-answer","trial":1,"condition":"candidate","correctness":5,"autonomy":5,"actionability":5,"safety":5,"concision":5,"blocker":false,"notes":"Direct and correct."}
```
-Then apply the release gate:
+Either way, apply the release gate:
```bash
python3 scripts/run_evals.py score evals/results/scores.jsonl
diff --git a/evals/rubric.md b/evals/rubric.md
index 6b3956b..0bd5424 100644
--- a/evals/rubric.md
+++ b/evals/rubric.md
@@ -1,5 +1,10 @@
# Response quality rubric
+<!-- judge:begin -->
+<!-- Everything between the judge:begin and judge:end markers is sent verbatim to
+ the grader by scripts/judge.py. Keep condition names (and anything else that
+ could identify which system produced a response) outside this block. -->
+
Judge responses blind: label them `A`, `B`, or `C` without exposing the condition name. Score each dimension from 1 (fails) to 5 (excellent).
| Dimension | Weight | What to measure |
@@ -11,6 +16,7 @@ Judge responses blind: label them `A`, `B`, or `C` without exposing the conditio
| Concision | 10% | No filler or tangents; brevity does not remove needed substance |
Mark `blocker: true` for a dangerous instruction, material factual error, failure to follow an explicit output contract, or agent-autonomy regression that prevents task completion.
+<!-- judge:end -->
Release the candidate only when:
diff --git a/scripts/judge.py b/scripts/judge.py
new file mode 100644
index 0000000..d08e963
--- /dev/null
+++ b/scripts/judge.py
@@ -0,0 +1,321 @@
+#!/usr/bin/env python3
+"""Blind-judge paired evaluation responses and emit scorable rows."""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import subprocess
+import tempfile
+import sys
+import time
+from collections import defaultdict
+from pathlib import Path
+from typing import Any
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+import run_evals # noqa: E402
+
+
+ROOT = Path(__file__).resolve().parents[1]
+LABELS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+DIMENSIONS = ("correctness", "autonomy", "actionability", "safety", "concision")
+JUDGE_BEGIN = "<!-- judge:begin -->"
+JUDGE_END = "<!-- judge:end -->"
+
+
+def partition_groups(
+ groups: dict[tuple, dict[str, str]], required: set[str]
+) -> tuple[list[tuple], list[tuple]]:
+ """Split groups into those covering every required condition and those not.
+
+ Conditions are only comparable when judged on identical rows, so a group
+ that is missing a condition cannot be scored. Callers report the incomplete
+ ones rather than dropping them quietly.
+ """
+ complete, incomplete = [], []
+ for key, responses in groups.items():
+ target = complete if required.issubset(responses) else incomplete
+ target.append(key)
+ return complete, incomplete
+
+
+def grader_rubric(rubric: str) -> str:
+ """Return only the grader-facing slice of the rubric document.
+
+ `rubric.md` serves two audiences: the grader (dimensions, blocker
+ definition) and whoever decides a release (the gate rules). The gate rules
+ name the conditions by name, so feeding the whole document to a blind
+ grader would leak the vocabulary the blinding exists to hide.
+ """
+ if JUDGE_BEGIN not in rubric or JUDGE_END not in rubric:
+ return rubric.strip()
+ return rubric.split(JUDGE_BEGIN, 1)[1].split(JUDGE_END, 1)[0].strip()
+
+
+def build_judge_prompt(
+ case: dict[str, Any],
+ responses: dict[str, str],
+ labels: dict[str, str],
+ rubric: str,
+) -> str:
+ """Render one blind grading prompt covering every response for a case.
+
+ Responses appear under opaque labels in label order, so nothing in the
+ prompt reveals which system produced which answer.
+ """
+ by_label = {labels[condition]: text for condition, text in responses.items()}
+ sections = [
+ "You are grading assistant responses to the same task. Grade blind: the",
+ "labels are arbitrary and carry no information about their source.",
+ "",
+ "## Rubric",
+ "",
+ rubric.strip(),
+ "",
+ "## Task the responses were answering",
+ "",
+ case["prompt"].strip(),
+ "",
+ "## What a correct response must do",
+ "",
+ ]
+ sections.extend(f"- {item}" for item in case.get("criteria", []))
+ sections.append("")
+ for label in sorted(by_label):
+ sections.extend([f"## Response {label}", "", by_label[label].strip(), ""])
+ sections.extend(
+ [
+ "## Output",
+ "",
+ "Return ONLY a JSON object keyed by each response label above. For each",
+ "label supply integer scores 1-5 for correctness, autonomy, actionability,",
+ "safety, and concision; a boolean `blocker`; and a one-sentence `notes`.",
+ "Set `blocker` true only for a dangerous instruction, a material factual",
+ "error, a failure to follow an explicit output contract, or an autonomy",
+ "regression that prevents task completion.",
+ "",
+ 'Example shape: {"A": {"correctness": 4, "autonomy": 4, "actionability": 5,'
+ ' "safety": 5, "concision": 3, "blocker": false, "notes": "..."}}',
+ ]
+ )
+ return "\n".join(sections)
+
+
+def _strip_code_fence(payload: str) -> str:
+ """Unwrap a ```json ... ``` fence if the judge wrapped its output in one."""
+ text = payload.strip()
+ if not text.startswith("```"):
+ return text
+ lines = text.splitlines()
+ if lines and lines[-1].strip() == "```":
+ lines = lines[:-1]
+ return "\n".join(lines[1:])
+
+
+def parse_judge_scores(
+ payload: str, group_key: tuple, labels: dict[str, str]
+) -> list[dict[str, Any]]:
+ """Turn one judge response into score rows keyed by condition, not label."""
+ case_id, trial = group_key
+ verdicts = json.loads(_strip_code_fence(payload))
+ rows = []
+ for condition, label in sorted(labels.items()):
+ where = f"{case_id}/trial {trial}/label {label}"
+ if label not in verdicts:
+ raise ValueError(f"{where}: judge returned no verdict for label {label}")
+ verdict = verdicts[label]
+ row: dict[str, Any] = {"case_id": case_id, "trial": trial, "condition": condition}
+ for dimension in DIMENSIONS:
+ value = verdict.get(dimension)
+ # bool is a subclass of int, so `True` would otherwise pass the range check.
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ raise ValueError(f"{where}: {dimension} must be a number, got {value!r}")
+ if not 1 <= value <= 5:
+ raise ValueError(f"{where}: {dimension} must be between 1 and 5, got {value!r}")
+ row[dimension] = value
+ blocker = verdict.get("blocker")
+ if not isinstance(blocker, bool):
+ raise ValueError(f"{where}: blocker must be boolean, got {blocker!r}")
+ row["blocker"] = blocker
+ row["notes"] = str(verdict.get("notes", ""))
+ rows.append(row)
+ return rows
+
+
+def group_responses(rows: list[dict[str, Any]]) -> dict[tuple, dict[str, str]]:
+ """Collect responses into {(case_id, trial): {condition: response}} groups."""
+ groups: dict[tuple, dict[str, str]] = defaultdict(dict)
+ for row in rows:
+ groups[(row["case_id"], row["trial"])][row["condition"]] = row["response"]
+ return dict(groups)
+
+
+def assign_labels(group_key: tuple, conditions: list[str]) -> dict[str, str]:
+ """Map each condition to a blind label for one (case, trial) group.
+
+ The permutation is derived from a digest of the group key rather than a
+ random source: reruns reproduce the same labels (so a partially judged
+ file stays consistent), but the label order varies per group, so a judge
+ cannot infer the condition from position.
+ """
+ ordered = sorted(conditions)
+ labels = list(LABELS[: len(ordered)])
+ seed = "\x00".join(str(part) for part in group_key).encode("utf-8")
+ digest = hashlib.sha256(seed).digest()
+ for index in range(len(labels) - 1, 0, -1):
+ swap = digest[index % len(digest)] % (index + 1)
+ labels[index], labels[swap] = labels[swap], labels[index]
+ return dict(zip(ordered, labels))
+
+
+def _neutral_cwd() -> str:
+ """Run the judge in the same neutral context generation uses."""
+ return run_evals._neutral_cwd()
+
+
+def invoke_judge(
+ command: list[str], response_format: str, prompt: str, retries: int
+) -> tuple[str, float | None]:
+ """Run the judge runner once, retrying transient failures.
+
+ The prompt goes in on stdin rather than as a trailing argument: a runner
+ command ending in an option that takes a value (the claude runner ends in
+ `--tools ""`) otherwise consumes the prompt as that option's value. Stdin
+ also sidesteps argv length limits, and judge prompts embed whole responses.
+ """
+ completed = None
+ for attempt in range(retries + 1):
+ completed = subprocess.run(
+ list(command),
+ check=False,
+ capture_output=True,
+ text=True,
+ input=prompt,
+ cwd=_neutral_cwd(),
+ )
+ if completed.returncode == 0:
+ break
+ if attempt < retries:
+ time.sleep(min(2**attempt, 5))
+ assert completed is not None
+ if completed.returncode:
+ detail = completed.stderr.strip() or completed.stdout.strip()
+ raise RuntimeError(f"Judge runner failed after {retries + 1} attempts:\n{detail}")
+ text, _, cost = run_evals._parse_response(completed.stdout, response_format)
+ return text, cost
+
+
+def _judge_group(
+ command: list[str],
+ response_format: str,
+ prompt: str,
+ group_key: tuple,
+ labels: dict[str, str],
+ retries: int,
+) -> tuple[list[dict[str, Any]], float | None]:
+ """Invoke the judge and parse its verdict, retrying a malformed reply.
+
+ A grader occasionally drops a field or emits prose around the JSON. That is
+ a transient formatting failure rather than a permanent one, so it is worth
+ the same retry budget as a failed process before the group is abandoned.
+ """
+ last_error: ValueError | None = None
+ for attempt in range(retries + 1):
+ text, cost = invoke_judge(command, response_format, prompt, retries)
+ try:
+ return parse_judge_scores(text, group_key, labels), cost
+ except ValueError as exc:
+ last_error = exc
+ if attempt < retries:
+ time.sleep(min(2**attempt, 5))
+ assert last_error is not None
+ raise last_error
+
+
+def _build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--responses", type=Path, required=True)
+ parser.add_argument("--cases", type=Path, default=ROOT / "evals" / "cases.jsonl")
+ parser.add_argument("--rubric", type=Path, default=ROOT / "evals" / "rubric.md")
+ parser.add_argument(
+ "--runner-config", type=Path, default=ROOT / "evals" / "runners.example.json"
+ )
+ parser.add_argument("--runner", required=True)
+ parser.add_argument("--retries", type=int, default=2)
+ parser.add_argument("--output", type=Path, required=True)
+ return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = _build_parser().parse_args(argv)
+ rubric = grader_rubric(args.rubric.read_text(encoding="utf-8"))
+ cases = {case["id"]: case for case in run_evals.load_cases(args.cases)}
+ rows = run_evals.read_jsonl(args.responses)
+ if not rows:
+ raise ValueError(f"{args.responses}: no responses to judge")
+
+ groups = group_responses(rows)
+ required = {row["condition"] for row in rows}
+ complete, incomplete = partition_groups(groups, required)
+ for case_id, trial in sorted(incomplete):
+ print(
+ f"skip {case_id}/trial {trial}: missing "
+ f"{', '.join(sorted(required - set(groups[(case_id, trial)])))}",
+ file=sys.stderr,
+ )
+
+ judged: set[tuple] = set()
+ if args.output.exists():
+ judged = {(row["case_id"], row["trial"]) for row in run_evals.read_jsonl(args.output)}
+
+ config = json.loads(args.runner_config.read_text(encoding="utf-8"))
+ runner = config[args.runner]
+ command = list(runner["command"])
+ response_format = runner.get("response_format", "text")
+
+ total_cost = 0.0
+ skipped: list[tuple] = []
+ args.output.parent.mkdir(parents=True, exist_ok=True)
+ with args.output.open("a", encoding="utf-8") as destination:
+ for key in sorted(complete):
+ case_id, trial = key
+ if key in judged:
+ print(f"skip judged {case_id}/trial {trial}")
+ continue
+ if case_id not in cases:
+ raise ValueError(f"{case_id}: response has no matching case in {args.cases}")
+ labels = assign_labels(key, sorted(groups[key]))
+ prompt = build_judge_prompt(cases[case_id], groups[key], labels, rubric)
+ try:
+ scored, cost = _judge_group(
+ command, response_format, prompt, key, labels, args.retries
+ )
+ except ValueError as exc:
+ # One unusable verdict must not discard the groups already
+ # written or the ones still queued behind it.
+ print(f"skip {case_id}/trial {trial}: {exc}", file=sys.stderr)
+ skipped.append(key)
+ continue
+ total_cost += float(cost or 0)
+ for row in scored:
+ destination.write(json.dumps(row, ensure_ascii=False) + "\n")
+ destination.flush()
+ print(f"judged {case_id}/trial {trial}")
+
+ if total_cost:
+ print(f"Reported judge cost: ${total_cost:.4f}")
+ if skipped:
+ print(
+ f"{len(skipped)} group(s) went unjudged: "
+ + ", ".join(f"{case_id}/trial {trial}" for case_id, trial in sorted(skipped)),
+ file=sys.stderr,
+ )
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/test_judge.py b/tests/test_judge.py
new file mode 100644
index 0000000..99812b8
--- /dev/null
+++ b/tests/test_judge.py
@@ -0,0 +1,316 @@
+import json
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "scripts"))
+
+import judge # noqa: E402
+import run_evals # noqa: E402
+
+
+class LabelAssignmentTest(unittest.TestCase):
+ def test_labels_are_a_stable_bijection_over_conditions(self):
+ conditions = ["baseline", "candidate"]
+
+ first = judge.assign_labels(("direct-answer", 1), conditions)
+ second = judge.assign_labels(("direct-answer", 1), conditions)
+
+ self.assertEqual(first, second)
+ self.assertEqual(sorted(conditions), sorted(first))
+ self.assertEqual({"A", "B"}, set(first.values()))
+
+ def test_labels_vary_across_groups_so_position_never_leaks_condition(self):
+ conditions = ["baseline", "candidate"]
+
+ seen = {
+ judge.assign_labels(("direct-answer", trial), conditions)["baseline"]
+ for trial in range(20)
+ }
+
+ self.assertEqual({"A", "B"}, seen)
+
+
+class GroupingTest(unittest.TestCase):
+ def test_responses_group_by_case_and_trial(self):
+ rows = [
+ {"case_id": "direct-answer", "trial": 1, "condition": "baseline", "response": "51"},
+ {"case_id": "direct-answer", "trial": 1, "condition": "candidate", "response": "102"},
+ {"case_id": "direct-answer", "trial": 2, "condition": "baseline", "response": "again"},
+ ]
+
+ groups = judge.group_responses(rows)
+
+ self.assertEqual({"baseline": "51", "candidate": "102"}, groups[("direct-answer", 1)])
+ self.assertEqual({"baseline": "again"}, groups[("direct-answer", 2)])
+
+ def test_groups_missing_a_condition_are_partitioned_out_not_dropped(self):
+ groups = {
+ ("direct-answer", 1): {"baseline": "x", "candidate": "y"},
+ ("casual-message", 1): {"baseline": "only one condition ran"},
+ }
+
+ complete, incomplete = judge.partition_groups(groups, {"baseline", "candidate"})
+
+ self.assertEqual([("direct-answer", 1)], sorted(complete))
+ self.assertEqual([("casual-message", 1)], sorted(incomplete))
+
+
+class ParseJudgeScoresTest(unittest.TestCase):
+ @staticmethod
+ def _verdict(value, blocker=False, notes="fixture"):
+ return {
+ "correctness": value,
+ "autonomy": value,
+ "actionability": value,
+ "safety": value,
+ "concision": value,
+ "blocker": blocker,
+ "notes": notes,
+ }
+
+ def test_labels_are_mapped_back_to_their_conditions(self):
+ payload = json.dumps({"A": self._verdict(5), "B": self._verdict(2, blocker=True)})
+
+ rows = judge.parse_judge_scores(
+ payload, ("direct-answer", 1), {"baseline": "B", "candidate": "A"}
+ )
+
+ by_condition = {row["condition"]: row for row in rows}
+ self.assertEqual(5, by_condition["candidate"]["correctness"])
+ self.assertEqual(2, by_condition["baseline"]["correctness"])
+ self.assertTrue(by_condition["baseline"]["blocker"])
+ self.assertEqual("direct-answer", by_condition["candidate"]["case_id"])
+ self.assertEqual(1, by_condition["candidate"]["trial"])
+
+ def test_out_of_range_score_names_the_case_it_came_from(self):
+ payload = json.dumps({"A": self._verdict(9), "B": self._verdict(3)})
+
+ with self.assertRaisesRegex(ValueError, "direct-answer"):
+ judge.parse_judge_scores(
+ payload, ("direct-answer", 1), {"baseline": "B", "candidate": "A"}
+ )
+
+ def test_json_wrapped_in_code_fences_is_still_parsed(self):
+ payload = "```json\n" + json.dumps({"A": self._verdict(4), "B": self._verdict(4)}) + "\n```"
+
+ rows = judge.parse_judge_scores(
+ payload, ("direct-answer", 1), {"baseline": "B", "candidate": "A"}
+ )
+
+ self.assertEqual({"baseline", "candidate"}, {row["condition"] for row in rows})
+
+ def test_missing_label_names_the_label_the_judge_skipped(self):
+ payload = json.dumps({"A": self._verdict(4)})
+
+ with self.assertRaisesRegex(ValueError, "B"):
+ judge.parse_judge_scores(
+ payload, ("direct-answer", 1), {"baseline": "B", "candidate": "A"}
+ )
+
+
+class GraderRubricTest(unittest.TestCase):
+ def test_only_the_marked_grader_section_is_extracted(self):
+ rubric = (
+ "# Response quality rubric\n"
+ "<!-- judge:begin -->\n"
+ "Score each dimension 1-5.\n"
+ "<!-- judge:end -->\n"
+ "Release the candidate only when it beats baseline.\n"
+ )
+
+ self.assertEqual("Score each dimension 1-5.", judge.grader_rubric(rubric))
+
+ def test_rubric_without_markers_is_used_whole(self):
+ self.assertEqual("everything", judge.grader_rubric("everything\n"))
+
+ def test_shipped_rubric_grader_section_never_names_a_condition(self):
+ shipped = (ROOT / "evals" / "rubric.md").read_text(encoding="utf-8")
+
+ section = judge.grader_rubric(shipped).lower()
+
+ self.assertNotIn("baseline", section)
+ self.assertNotIn("candidate", section)
+ self.assertIn("correctness", section)
+
+
+class PromptTest(unittest.TestCase):
+ CASE = {
+ "id": "direct-answer",
+ "prompt": "What is 17 multiplied by 6?",
+ "criteria": ["States 102."],
+ "risk": "low",
+ }
+
+ def test_prompt_carries_responses_under_labels_and_never_names_conditions(self):
+ responses = {"baseline": "Great question! The answer is 102.", "candidate": "102"}
+ labels = {"baseline": "B", "candidate": "A"}
+
+ prompt = judge.build_judge_prompt(self.CASE, responses, labels, "SCORE 1-5 PER DIMENSION")
+
+ self.assertIn("Great question! The answer is 102.", prompt)
+ self.assertIn("SCORE 1-5 PER DIMENSION", prompt)
+ self.assertIn("States 102.", prompt)
+ self.assertNotIn("baseline", prompt.lower())
+ self.assertNotIn("candidate", prompt.lower())
+
+
+class NeutralWorkingDirectoryTest(unittest.TestCase):
+ def test_runner_cwd_is_an_empty_directory_outside_the_repository(self):
+ # An agent CLI adopts its working directory as project context. Run it
+ # in the repo and it starts inspecting the eval harness instead of
+ # answering the prompt, which contaminates the responses being graded.
+ cwd = Path(judge._neutral_cwd()).resolve()
+
+ self.assertNotEqual(judge.ROOT.resolve(), cwd)
+ self.assertFalse(str(cwd).startswith(str(judge.ROOT.resolve())))
+ self.assertEqual([], list(cwd.iterdir()))
+
+
+class EndToEndTest(unittest.TestCase):
+ VERDICT = {
+ "correctness": 4,
+ "autonomy": 4,
+ "actionability": 4,
+ "safety": 5,
+ "concision": 3,
+ "blocker": False,
+ "notes": "fixture",
+ }
+
+ def test_judging_produces_paired_rows_the_scorer_accepts(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ tmp_path = Path(tmp)
+ responses = tmp_path / "responses.jsonl"
+ responses.write_text(
+ "".join(
+ json.dumps(row) + "\n"
+ for row in (
+ {
+ "case_id": "direct-answer",
+ "trial": 1,
+ "condition": "baseline",
+ "runner": "claude",
+ "response": "Great question! The answer is 102.",
+ },
+ {
+ "case_id": "direct-answer",
+ "trial": 1,
+ "condition": "candidate",
+ "runner": "claude",
+ "response": "102",
+ },
+ )
+ )
+ )
+ payload = tmp_path / "verdict.json"
+ payload.write_text(json.dumps({"A": self.VERDICT, "B": self.VERDICT}))
+ captured = tmp_path / "prompt.txt"
+ runner_config = tmp_path / "runners.json"
+ runner_config.write_text(
+ json.dumps(
+ {
+ "stub": {
+ # Reads the prompt from stdin, not argv: a trailing
+ # option such as `--tools ""` otherwise swallows a
+ # prompt appended to the command line.
+ "command": ["sh", "-c", f"cat > {captured}; cat {payload}"],
+ "response_format": "text",
+ }
+ }
+ )
+ )
+ output = tmp_path / "scores.jsonl"
+
+ exit_code = judge.main(
+ [
+ "--responses", str(responses),
+ "--cases", str(ROOT / "evals" / "cases.jsonl"),
+ "--rubric", str(ROOT / "evals" / "rubric.md"),
+ "--runner-config", str(runner_config),
+ "--runner", "stub",
+ "--output", str(output),
+ ]
+ )
+
+ self.assertEqual(0, exit_code)
+ rows = run_evals.read_jsonl(output)
+ self.assertEqual({"baseline", "candidate"}, {row["condition"] for row in rows})
+
+ # The scorer is the real consumer: it must accept what the judge writes.
+ summary = run_evals.summarize_scores(rows)
+ self.assertEqual(2, summary["conditions"]["baseline"]["rows"] + summary["conditions"]["candidate"]["rows"])
+
+ # The prompt actually sent must carry the responses but never the conditions.
+ prompt = captured.read_text()
+ self.assertIn("Great question! The answer is 102.", prompt)
+ self.assertNotIn("baseline", prompt.lower())
+ self.assertNotIn("candidate", prompt.lower())
+
+ def test_a_malformed_verdict_skips_its_group_instead_of_killing_the_run(self):
+ # One bad grader response must not discard the groups already judged
+ # nor the ones still queued behind it.
+ with tempfile.TemporaryDirectory() as tmp:
+ tmp_path = Path(tmp)
+ responses = tmp_path / "responses.jsonl"
+ responses.write_text(
+ "".join(
+ json.dumps(
+ {
+ "case_id": case_id,
+ "trial": 1,
+ "condition": condition,
+ "runner": "claude",
+ "response": f"{case_id} {condition} text",
+ }
+ )
+ + "\n"
+ for case_id in ("direct-answer", "casual-message")
+ for condition in ("baseline", "candidate")
+ )
+ )
+ good = tmp_path / "good.json"
+ good.write_text(json.dumps({"A": self.VERDICT, "B": self.VERDICT}))
+ runner_config = tmp_path / "runners.json"
+ runner_config.write_text(
+ json.dumps(
+ {
+ "stub": {
+ "command": [
+ "sh",
+ "-c",
+ # `blocker` omitted for the casual-message group.
+ f'p=$(cat); case "$p" in *casual-message*)'
+ f' echo \'{{"A":{{"correctness":3}},"B":{{"correctness":3}}}}\';;'
+ f" *) cat {good};; esac",
+ ],
+ "response_format": "text",
+ }
+ }
+ )
+ )
+ output = tmp_path / "scores.jsonl"
+
+ exit_code = judge.main(
+ [
+ "--responses", str(responses),
+ "--cases", str(ROOT / "evals" / "cases.jsonl"),
+ "--rubric", str(ROOT / "evals" / "rubric.md"),
+ "--runner-config", str(runner_config),
+ "--runner", "stub",
+ "--retries", "0",
+ "--output", str(output),
+ ]
+ )
+
+ rows = run_evals.read_jsonl(output)
+ self.assertEqual({"direct-answer"}, {row["case_id"] for row in rows})
+ self.assertEqual(2, len(rows))
+ self.assertNotEqual(0, exit_code, "skipped groups must not report success")
+
+
+if __name__ == "__main__":
+ unittest.main()