Python
fix(lab): reject conflicting fenced judge verdicts (#24)
Rudy Mizrahi Celekli591554dd2518
diff --git a/dependencies/ASSETS.json b/dependencies/ASSETS.jsonindex 64c838f..17a7fd5 100644--- a/dependencies/ASSETS.json+++ b/dependencies/ASSETS.json@@ -27,7 +27,7 @@"third_party/licenses/job-bench-eval.LICENSE": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4","third_party/licenses/opencode.LICENSE": "625f0f619133f89bbbb2abe37369613dfa1885eba1e50d02170deb62bb42cb6b","third_party/licenses/workbuddy-bench.LICENSE": "b466fc7a63acc5cac4275fc4b0f1e22f332ad188ea600b217076ea3a8e040956",- "third_party/patches/harvey-labs-judge-vertex-anthropic.diff": "7fc4385025916054be504b98f063e2a161515b8b4dc3bcc5cd6f4272b707ed6d",+ "third_party/patches/harvey-labs-judge-vertex-anthropic.diff": "a6e8f7c5025f8a02ef5c654df2b3607ef7df5019d0d8b612938bc72f001a4848","third_party/patches/job-bench-eval-judge.diff": "b5878bce91f6322c9fd1fa777b3a5dd3866922f704173a658d007c62456c5728","third_party/patches/opencode-compat.diff": "c9a8a0e826d48f3fcfc7d818321d128c28e1f7f7c594954c19453dfca4946dc8","third_party/patches/workbuddy-bench-runtime.diff": "1d581ee0c23a9a5574ce0f9317d0bda17f6c3a2556898c89b34ccbdbd5b87b3f",diff --git a/tests/fixtures/harvey-labs/.gitattributes b/tests/fixtures/harvey-labs/.gitattributesnew file mode 100644index 0000000..5ce0424--- /dev/null+++ b/tests/fixtures/harvey-labs/.gitattributes@@ -0,0 +1,2 @@+# Exact upstream source snapshots retain their original whitespace.+*.py.txt -whitespacediff --git a/tests/fixtures/harvey-labs/LICENSE b/tests/fixtures/harvey-labs/LICENSEnew file mode 100644index 0000000..e040426--- /dev/null+++ b/tests/fixtures/harvey-labs/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Harvey AI++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/tests/fixtures/harvey-labs/PROVENANCE.json b/tests/fixtures/harvey-labs/PROVENANCE.jsonnew file mode 100644index 0000000..6bb1307--- /dev/null+++ b/tests/fixtures/harvey-labs/PROVENANCE.json@@ -0,0 +1,14 @@+{+ "repository": "https://github.com/harveyai/harvey-labs",+ "commit": "b58a28ae9fde5ee4b810e53b4fd0a1915325a35d",+ "license": "MIT; see LICENSE",+ "purpose": "Exact pinned parser and grading consumer fixture for offline validation of the distributed patch; SDK imports are not executed.",+ "sha256": {+ "evaluation/judge.py.txt": "0506e459bc2e05f77b2c1a745d02482cd6933b972a58766a8cf66dbffaf5bbf6",+ "evaluation/scoring.py.txt": "2c9e266ad0c148a599637fe05b0ba98c798c4de6c2fc987d0406dcfae9071cde",+ "evaluation/run_eval.py.txt": "386f3c71e78220a407b94dcc4391b1df45cb96f83dcd463e8fc65c86166c0721",+ "evaluation/prompts/rubric_criterion.txt": "fcd53795c434163070053c156cb14eccc781db8018e3af8beae3834bca8bd5b1",+ "LICENSE": "f92627d2ebe80fc0add3b171b2d7eee5e28a98dd0d0a4a5ee5829314243bb3b9"+ },+ "fixture_data": "Python snapshots use an additional .txt suffix; original pinned source paths omit that suffix. Tests restore the upstream filenames before applying the bundled patch."+}diff --git a/tests/fixtures/harvey-labs/evaluation/judge.py.txt b/tests/fixtures/harvey-labs/evaluation/judge.py.txtnew file mode 100644index 0000000..ffad89d--- /dev/null+++ b/tests/fixtures/harvey-labs/evaluation/judge.py.txt@@ -0,0 +1,259 @@+"""Generic LLM judge — wraps any ModelAdapter to evaluate outputs.++The judge formats a prompt template with variables, sends it to the model,+and parses the structured response. Used by all scoring functions.+"""++import json+import os+import re+from pathlib import Path++import anthropic+import openai+from google import genai+from google.genai import types+from mistralai.client import Mistral++PROMPTS_DIR = Path(__file__).parent / "prompts"++_VERDICT_SCHEMA = {+ "type": "object",+ "properties": {+ "verdict": {"type": "string", "enum": ["pass", "fail"]},+ "reasoning": {"type": "string"},+ },+ "required": ["verdict", "reasoning"],+ "additionalProperties": False,+}++def _detect_provider(model: str) -> str:+ """Return 'anthropic', 'google', 'openai', or 'mistral' from the model name."""+ name = model.lower()+ if name.startswith("claude"):+ return "anthropic"+ if name.startswith("gemini"):+ return "google"+ if name.startswith(("gpt", "o1", "o3", "o4", "o5")):+ return "openai"+ if name.startswith("mistral"):+ return "mistral"+ raise ValueError(f"Unknown judge provider for model: {model!r}")++class Judge:+ """LLM-as-judge that evaluates agent outputs against rubric criteria."""++ def __init__(self, model: str = "claude-sonnet-4-6"):+ """Initialize with a model ID. Picks the SDK client based on the model prefix.++ Args:+ model: Model ID (e.g. 'claude-sonnet-4-6', 'gemini-3-flash-preview',+ 'gpt-5.4', 'mistral-medium-3.5').+ """+ self.model = model+ self.provider = _detect_provider(model)+ if self.provider == "anthropic":+ self.client = anthropic.Anthropic(max_retries=1)+ elif self.provider == "google":+ self.client = genai.Client()+ elif self.provider == "openai":+ self.client = openai.OpenAI()+ else: # mistral+ self.client = Mistral(+ api_key=os.environ["MISTRAL_API_KEY"],+ timeout_ms=600_000,+ )++ def evaluate(+ self, prompt_template: str, variables: dict, temperature: float = 0.0, _retries: int = 2,+ ) -> dict:+ """Send a formatted prompt to the judge and parse the JSON response.++ Args:+ prompt_template: A prompt string with {variable} placeholders.+ variables: Dict of values to format into the template.+ temperature: Sampling temperature (default 0.0).++ Returns:+ Parsed JSON dict from the judge's response.+ """+ prompt = prompt_template.format(**variables)+ if self.provider == "anthropic":+ return self._evaluate_anthropic(prompt, temperature, _retries)+ if self.provider == "google":+ return self._evaluate_google(prompt, temperature, _retries)+ if self.provider == "openai":+ return self._evaluate_openai(prompt, temperature, _retries)+ return self._evaluate_mistral(prompt, temperature, _retries)++ def _evaluate_anthropic(self, prompt: str, temperature: float, _retries: int) -> dict:+ last_err: Exception | None = None+ for attempt in range(_retries):+ kwargs = {+ "model": self.model,+ "max_tokens": 16384,+ "temperature": temperature,+ "messages": [{"role": "user", "content": prompt}],+ }+ # Use output_config on every attempt except the last.+ if attempt < _retries - 1:+ kwargs["output_config"] = {+ "format": {+ "type": "json_schema",+ "schema": _VERDICT_SCHEMA,+ }+ }+ try:+ response = self.client.messages.create(**kwargs)+ except anthropic.InternalServerError as e:+ # 500s on the structured-output path have been observed to+ # succeed when retried without output_config.+ last_err = e+ continue++ if response.stop_reason == "max_tokens":+ input_tokens = response.usage.input_tokens if response.usage else "unknown"+ raise ValueError(+ f"Judge response truncated (stop_reason=max_tokens, "+ f"input_tokens={input_tokens}, max_tokens={16384}). "+ f"The agent output is likely too large for the judge context window. "+ f"Ensure criteria have deliverables lists to scope output."+ )++ text = response.content[0].text+ try:+ return self._parse_json(text)+ except (ValueError, json.JSONDecodeError) as e:+ last_err = e+ raise ValueError(+ f"Judge returned unparseable response after {_retries} attempts: {last_err}"+ )++ def _evaluate_google(self, prompt: str, temperature: float, _retries: int) -> dict:+ last_err: Exception | None = None+ for attempt in range(_retries):+ config_kwargs = dict(+ temperature=temperature,+ max_output_tokens=16384,+ response_mime_type="application/json",+ )+ # Constrain to the verdict schema on early attempts; drop it on the last.+ if attempt < _retries - 1:+ config_kwargs["response_schema"] = _VERDICT_SCHEMA+ try:+ response = self.client.models.generate_content(+ model=self.model,+ contents=prompt,+ config=types.GenerateContentConfig(**config_kwargs),+ )+ except Exception as e:+ last_err = e+ continue+ text = response.text or ""+ try:+ return self._parse_json(text)+ except (ValueError, json.JSONDecodeError) as e:+ last_err = e+ raise ValueError(+ f"Judge returned unparseable response after {_retries} attempts: {last_err}"+ )++ def _evaluate_openai(self, prompt: str, temperature: float, _retries: int) -> dict:+ last_err: Exception | None = None+ for attempt in range(_retries):+ kwargs = {+ "model": self.model,+ "input": prompt,+ "max_output_tokens": 16384,+ "temperature": temperature,+ }+ if attempt < _retries - 1:+ kwargs["text"] = {+ "format": {+ "type": "json_schema",+ "name": "verdict",+ "schema": _VERDICT_SCHEMA,+ "strict": True,+ }+ }+ try:+ response = self.client.responses.create(**kwargs)+ except Exception as e:+ last_err = e+ continue+ text = response.output_text or ""+ try:+ return self._parse_json(text)+ except (ValueError, json.JSONDecodeError) as e:+ last_err = e+ raise ValueError(+ f"Judge returned unparseable response after {_retries} attempts: {last_err}"+ )++ def _evaluate_mistral(self, prompt: str, temperature: float, _retries: int) -> dict:+ last_err: Exception | None = None+ for attempt in range(_retries):+ kwargs = {+ "model": self.model,+ "messages": [{"role": "user", "content": prompt}],+ "temperature": temperature,+ "max_tokens": 16384,+ }+ if attempt < _retries - 1:+ kwargs["response_format"] = {"type": "json_object"}+ try:+ response = self.client.chat.complete(**kwargs)+ except Exception as e:+ last_err = e+ continue+ text = response.choices[0].message.content or ""+ try:+ return self._parse_json(text)+ except (ValueError, json.JSONDecodeError) as e:+ last_err = e+ raise ValueError(+ f"Judge returned unparseable response after {_retries} attempts: {last_err}"+ )++ def evaluate_from_file(self, prompt_name: str, variables: dict) -> dict:+ """Load a prompt template from prompts/ dir and evaluate.++ Args:+ prompt_name: Filename (without .md) in the prompts directory.+ variables: Dict of values to format into the template.++ Returns:+ Parsed JSON dict from the judge's response.+ """+ path = PROMPTS_DIR / f"{prompt_name}.txt"+ template = path.read_text(encoding="utf-8")+ return self.evaluate(prompt_template=template, variables=variables)++ @staticmethod+ def _parse_json(text: str) -> dict:+ """Extract JSON from model response, handling markdown fences."""+ # Try to find JSON in code fences first+ match = re.search(r"```(?:json)?\s*\n?(.*?)\n?```", text, re.DOTALL)+ if match:+ try:+ return json.loads(match.group(1).strip())+ except json.JSONDecodeError:+ pass # Fall through to brace matching++ # Try to find a JSON object by matching balanced braces+ for i, ch in enumerate(text):+ if ch == '{':+ depth = 0+ for j in range(i, len(text)):+ if text[j] == '{':+ depth += 1+ elif text[j] == '}':+ depth -= 1+ if depth == 0:+ try:+ return json.loads(text[i:j + 1])+ except json.JSONDecodeError:+ break # Try next opening brace+ break++ raise ValueError(f"No JSON found in judge response: {text[:200]}")diff --git a/tests/fixtures/harvey-labs/evaluation/prompts/rubric_criterion.txt b/tests/fixtures/harvey-labs/evaluation/prompts/rubric_criterion.txtnew file mode 100644index 0000000..9e6a77b--- /dev/null+++ b/tests/fixtures/harvey-labs/evaluation/prompts/rubric_criterion.txt@@ -0,0 +1,26 @@+You are evaluating a legal AI agent's work product against a specific quality criterion.++## Task+{task_description}++## Agent's Output+{agent_output}++## Criterion+**{criterion_title}**++{match_criteria}++## Instructions+Evaluate the agent's output against the criterion above.+- **PASS**: The agent's output satisfies the criterion as described+- **FAIL**: The agent's output does not satisfy the criterion as described++Respond with JSON only:++```json+{{+ "verdict": "pass" | "fail",+ "reasoning": "Brief explanation"+}}+```diff --git a/tests/fixtures/harvey-labs/evaluation/run_eval.py.txt b/tests/fixtures/harvey-labs/evaluation/run_eval.py.txtnew file mode 100644index 0000000..6db35dd--- /dev/null+++ b/tests/fixtures/harvey-labs/evaluation/run_eval.py.txt@@ -0,0 +1,330 @@+"""CLI entry point for the evaluation pipeline.++Scores agent output against rubric criteria defined in task.json using+an LLM judge. Each criterion is graded individually with only its+relevant deliverable files in context.++Usage:+ uv run python -m evaluation.run_eval --run-id <id> --task real-estate/extract-psa-key-terms/scenario-01 --judge-model claude-sonnet-4-6+ uv run python -m evaluation.run_eval --run-id <id> --task real-estate/extract-psa-key-terms/scenario-01 --dual+"""++import argparse+import json+import os+from datetime import datetime, timezone+from pathlib import Path++from evaluation.judge import Judge+from evaluation.report import generate_report+from evaluation.scoring import score_rubric+from utils.stdio import force_utf8_stdio+++BENCH_ROOT = Path(__file__).resolve().parent.parent+RESULTS_DIR = BENCH_ROOT / "results"++REQUIRED_TASK_KEYS = {"title", "instructions", "criteria"}+REQUIRED_CRITERION_KEYS = {"id", "title", "match_criteria"}+JUDGE_MODELS = ("claude-sonnet-4-6", "gpt-5.5")+++def validate_task_config(config: dict, task_path: Path) -> None:+ """Validate that task.json has all required fields for running and grading.++ Raises ValueError with a specific message for any missing or malformed field.+ """+ for key in REQUIRED_TASK_KEYS:+ if key not in config:+ raise ValueError(f"{task_path}: missing required key '{key}'")++ criteria = config["criteria"]+ if not isinstance(criteria, list) or not criteria:+ raise ValueError(f"{task_path}: 'criteria' must be a non-empty list")++ for i, criterion in enumerate(criteria):+ for key in REQUIRED_CRITERION_KEYS:+ if key not in criterion:+ raise ValueError(+ f"{task_path}: criterion {i} ('{criterion.get('id', '?')}') missing required key '{key}'"+ )+ # Validate deliverables is a list of strings when present+ criterion_deliverables = criterion.get("deliverables", [])+ if criterion_deliverables and not isinstance(criterion_deliverables, list):+ raise ValueError(+ f"{task_path}: criterion '{criterion['id']}' deliverables must be a list of filenames"+ )+++def _resolve_task_dir(task: str) -> Path:+ """Map a task name to its directory under tasks/."""+ parts = task.split("/")+ if len(parts) < 2:+ raise ValueError(+ f"Task name must have at least 2 parts (e.g., 'practice-area/task-slug'), got: {task}"+ )+ return BENCH_ROOT / "tasks" / Path(*parts)+++def _load_env():+ """Auto-load .env if it exists and keys aren't already set."""+ env_path = BENCH_ROOT / ".env"+ if not env_path.exists():+ return+ with open(env_path) as f:+ for line in f:+ line = line.strip()+ if line and not line.startswith("#") and "=" in line:+ key, _, value = line.partition("=")+ key, value = key.strip(), value.strip().strip('"').strip("'")+ if key and value:+ os.environ.setdefault(key, value)+++def evaluate_run(run_id: str, task: str, judge: Judge, parallel: int = 6) -> dict:+ """Score a run against the rubric defined in task.json.++ Returns a scores dict with: run_id, task, score, max_score,+ criteria_results, summary, cost, doc_coverage.+ """+ task_dir = _resolve_task_dir(task)+ run_dir = RESULTS_DIR / run_id++ # Load task config+ config_path = task_dir / "task.json"+ if not config_path.exists():+ raise FileNotFoundError(f"task.json not found: {config_path}")+ config = json.loads(config_path.read_text(encoding="utf-8"))++ # Validate and extract required fields+ validate_task_config(config=config, task_path=config_path)++ if not run_dir.exists():+ raise FileNotFoundError(f"run directory not found: {run_dir}")++ criteria = config["criteria"]+ task_desc = config["title"]++ result = score_rubric(+ criteria=criteria,+ run_dir=run_dir,+ judge=judge,+ task_desc=task_desc,+ parallel=parallel,+ )++ n_criteria = len(result.criteria_results)+ n_passed = sum(1 for c in result.criteria_results if c["verdict"] == "pass")+ all_pass = n_criteria > 0 and n_passed == n_criteria++ summary = (+ f"{n_passed}/{n_criteria} criteria passed."+ + (" ALL-PASS." if all_pass else f" Missed {n_criteria - n_passed} — task FAIL.")+ )++ scores = {+ "score": result.score,+ "max_score": result.max_score,+ "summary": summary,+ "all_pass": all_pass,+ "n_criteria": n_criteria,+ "n_passed": n_passed,+ "criteria_results": result.criteria_results,+ "run_id": run_id,+ "task": task,+ "judge_model": judge.model,+ "scored_at": datetime.now(timezone.utc).isoformat(),+ }++ # Load cost info and doc coverage from metrics.json+ metrics_path = run_dir / "metrics.json"+ if metrics_path.exists():+ metrics = json.loads(metrics_path.read_text(encoding="utf-8"))+ scores["cost"] = {+ "input_tokens": metrics.get("input_tokens", 0),+ "output_tokens": metrics.get("output_tokens", 0),+ "wall_clock_seconds": metrics.get("wall_clock_seconds", 0),+ }+ scores["doc_coverage"] = {+ "documents_read": metrics.get("documents_read", 0),+ "total_documents": metrics.get("total_documents", 0),+ "documents_skipped": metrics.get("documents_skipped", 0),+ "documents_read_list": metrics.get("documents_read_list", []),+ "documents_skipped_list": metrics.get("documents_skipped_list", []),+ }++ # Write scores.json+ scores_path = run_dir / "scores.json"+ scores_path.write_text(json.dumps(scores, indent=2))++ return scores+++def evaluate_run_dual(+ run_id: str,+ task: str,+ parallel: int = 6,+) -> dict:+ """Score a run with both standard LAB judges and average the result.++ Mirrors the dual-grading methodology used by the internal standard+ evaluator, but for a single arbitrary task. Each judge grades every+ criterion independently. Per-judge results are preserved alongside the+ aggregate so single-judge artifacts are not overwritten.+ """+ per_judge: dict[str, dict] = {}+ run_dir = RESULTS_DIR / run_id+ out_path = run_dir / "scores_dual.json"+ # A failed re-grade must not leave an earlier complete aggregate in place.+ out_path.unlink(missing_ok=True)++ for judge_model in JUDGE_MODELS:+ judge = Judge(model=judge_model)+ scores = evaluate_run(+ run_id=run_id,+ task=task,+ judge=judge,+ parallel=parallel,+ )+ per_judge[judge_model] = scores+ # Move the just-written scores.json to a per-judge filename so+ # subsequent judges do not clobber it.+ scores_path = run_dir / "scores.json"+ if scores_path.exists():+ scores_path.rename(run_dir / f"scores_{judge_model}.json")++ def crit_frac(scores: dict) -> float:+ return (+ scores["n_passed"] / scores["n_criteria"]+ if scores.get("n_criteria")+ else 0.0+ )++ dual_crit = sum(crit_frac(scores) for scores in per_judge.values()) / len(+ per_judge+ )+ dual_ap = sum(+ 1.0 if scores.get("all_pass") else 0.0+ for scores in per_judge.values()+ ) / len(per_judge)++ aggregate = {+ "run_id": run_id,+ "task": task,+ "scored_at": datetime.now(timezone.utc).isoformat(),+ "judges": list(JUDGE_MODELS),+ "per_judge": per_judge,+ "dual_criterion_pass": dual_crit,+ "dual_all_pass_rate": dual_ap,+ "all_pass": dual_ap == 1.0,+ }+ out_path.write_text(+ json.dumps(aggregate, indent=2),+ encoding="utf-8",+ )+ return aggregate+++def _print_summary(scores: dict):+ """Print a concise score summary."""+ print(f" {scores['summary']}")+ print(f" Score: {scores['score']:.2f}")++ cov = scores.get("doc_coverage", {})+ if cov.get("total_documents"):+ print(f" Doc coverage: {cov['documents_read']}/{cov['total_documents']} files read")++ cost = scores.get("cost", {})+ if cost.get("input_tokens"):+ print(f" Tokens: {cost['input_tokens'] + cost['output_tokens']:,}")++ print()+ print(f" Scores written to results/{scores['run_id']}/scores.json")+++def _print_dual_summary(aggregate: dict) -> None:+ """Print a concise summary of a complete dual-judge evaluation."""+ print(f" Judges: {', '.join(aggregate['judges'])}")+ print()+ for judge_model, scores in aggregate["per_judge"].items():+ print(f" {judge_model}:")+ print(f" {scores['summary']}")+ print()+ print(f" Dual criterion-pass: {aggregate['dual_criterion_pass'] * 100:.1f}%")+ print(f" Dual all-pass: {aggregate['dual_all_pass_rate'] * 100:.1f}%")+ print()+ print(+ f" Per-judge scores: results/{aggregate['run_id']}/scores_<judge>.json"+ )+ print(f" Aggregate scores: results/{aggregate['run_id']}/scores_dual.json")+++def main():+ force_utf8_stdio()+ parser = argparse.ArgumentParser(+ description="Score a benchmark run against rubric criteria"+ )+ parser.add_argument("--run-id", required=True, help="Run ID to evaluate")+ parser.add_argument(+ "--task",+ required=True,+ help="Task ID (e.g., real-estate/extract-psa-key-terms/scenario-01)",+ )+ parser.add_argument(+ "--judge-model",+ default="claude-sonnet-4-6",+ help="Model to use as LLM judge (single-judge mode). Ignored with --dual.",+ )+ parser.add_argument(+ "--dual",+ action="store_true",+ help=(+ "Grade with the standard LAB judge pair "+ "(claude-sonnet-4-6 + gpt-5.5) and average their scores"+ ),+ )+ parser.add_argument(+ "--parallel",+ type=int,+ default=6,+ help="Number of judge calls to run concurrently.",+ )+ parser.add_argument("--verbose", action="store_true", help="Print detailed output")+ args = parser.parse_args()++ _load_env()++ print(f"Evaluating run '{args.run_id}' on task '{args.task}'")+ if args.dual:+ print(f"Dual-judge mode: {', '.join(JUDGE_MODELS)}")+ print()+ scores = evaluate_run_dual(+ run_id=args.run_id,+ task=args.task,+ parallel=args.parallel,+ )+ if args.verbose:+ print(json.dumps(scores, indent=2))+ else:+ _print_dual_summary(scores)+ else:+ print(f"Judge model: {args.judge_model}")+ print()+ judge = Judge(model=args.judge_model)+ scores = evaluate_run(+ run_id=args.run_id,+ task=args.task,+ judge=judge,+ parallel=args.parallel,+ )+ if args.verbose:+ print(json.dumps(scores, indent=2))+ else:+ _print_summary(scores)++ report_path = generate_report(run_id=args.run_id)+ print(f" Report written to: {report_path}")+++if __name__ == "__main__":+ main()diff --git a/tests/fixtures/harvey-labs/evaluation/scoring.py.txt b/tests/fixtures/harvey-labs/evaluation/scoring.py.txtnew file mode 100644index 0000000..4eb9743--- /dev/null+++ b/tests/fixtures/harvey-labs/evaluation/scoring.py.txt@@ -0,0 +1,392 @@+"""Scoring functions for evaluating agent output against rubric criteria.++Each criterion is graded individually by an LLM judge, with only the+relevant deliverable files included in context.+"""++from __future__ import annotations++import json+import subprocess+from concurrent.futures import ThreadPoolExecutor+from enum import StrEnum++import anthropic+from dataclasses import dataclass, field, asdict+from pathlib import Path++import pandas as pd+import pdfplumber+from markitdown import MarkItDown+++# ── File reading helpers ──────────────────────────────────────────────+++class DocxTrackChanges(StrEnum):+ ACCEPT = "accept"+ ALL = "all"+++def _read_file_as_text(path: Path, *, track_changes: DocxTrackChanges = DocxTrackChanges.ACCEPT) -> str:+ """Read a file and return its content as plain text.++ Uses the same extraction methods as the agent harness (harness/tools.py):+ pandoc for .docx, pandas for .xlsx, markitdown for .pptx, pdfplumber for .pdf.+ """+ suffix = path.suffix.lower()+ try:+ if suffix == ".docx":+ result = subprocess.run(+ ["pandoc", str(path), "-t", "markdown", "--wrap=none", f"--track-changes={track_changes.value}"],+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=30,+ )+ if result.returncode != 0:+ raise RuntimeError(f"pandoc failed: {result.stderr}")+ return result.stdout+ if suffix == ".xlsx":+ sheets = pd.read_excel(path, sheet_name=None)+ parts = []+ for sheet_name, df in sheets.items():+ parts.append(f"=== Sheet: {sheet_name} ===")+ parts.append(df.to_string(index=False))+ return "\n".join(parts)+ if suffix == ".pptx":+ md = MarkItDown()+ result = md.convert(str(path))+ return result.text_content+ if suffix == ".pdf":+ parts = []+ with pdfplumber.open(path) as pdf:+ for page in pdf.pages:+ text = page.extract_text()+ if text:+ parts.append(text)+ for table in page.extract_tables():+ for row in table:+ parts.append("\t".join(cell if cell else "" for cell in row))+ parts.append("")+ return "\n".join(parts)+ return path.read_text(encoding="utf-8")+ except UnicodeDecodeError:+ return f"(binary file: {path.name})"+ except Exception as e:+ return f"(error reading {path.name}: {e})"+++# ── Result dataclasses ────────────────────────────────────────────────++@dataclass+class CriterionResult:+ id: str+ title: str+ verdict: str # "pass" or "fail"+ reasoning: str = ""++ def to_dict(self) -> dict:+ return asdict(self)++@dataclass+class RubricResult:+ score: float+ max_score: float+ criteria_results: list[dict] = field(default_factory=list)++ def to_dict(self) -> dict:+ return asdict(self)+++# ── File matching ────────────────────────────────────────────────++def _is_thread_export(filename: str) -> bool:+ """Check if a file is the thread export (output.docx, output.md, etc.)."""+ return Path(filename).stem.lower() == "output"+++def _fuzzy_match_filename(expected: str, candidates: list[str]) -> tuple[str | None, int]:+ """Find the best fuzzy match for an expected filename among candidates.++ Splits filenames into keywords (replacing hyphens and underscores with spaces)+ and returns the candidate with the highest keyword overlap.++ Args:+ expected: The expected filename (e.g., "case-chronology.xlsx").+ candidates: List of candidate filenames to match against.++ Returns:+ Tuple of (best matching filename or None, overlap score).+ """+ expected_stem = Path(expected).stem.lower().replace("-", " ").replace("_", " ")+ expected_words = set(expected_stem.split())++ best_match = None+ best_score = 0+ for candidate in candidates:+ candidate_stem = Path(candidate).stem.lower().replace("-", " ").replace("_", " ")+ candidate_words = set(candidate_stem.split())+ overlap = len(expected_words & candidate_words)+ if overlap > best_score:+ best_score = overlap+ best_match = candidate++ return best_match, best_score+++def _match_deliverables(deliverables_map: dict, actual_files: list[str], output_dir: Path | None = None) -> dict:+ """Best-effort match expected deliverable filenames to actual output files.++ For each deliverable, if the expected filename exists exactly, use it.+ Otherwise, try to find the best match by:+ 1. Matching by file extension (e.g., .xlsx → .xlsx)+ 2. Fuzzy substring matching on the stem+ 3. If only one file of the matching extension exists, use it+ 4. LLM-based matching for any remaining unmatched deliverables++ Returns a new map with the same keys but resolved filenames.+ """+ resolved = {}+ used = set()++ for name, expected in deliverables_map.items():+ if expected in actual_files:+ resolved[name] = expected+ used.add(expected)+ continue++ expected_ext = Path(expected).suffix.lower()++ # Candidates with matching extension (exclude thread export)+ candidates = [+ f for f in actual_files+ if f not in used and not _is_thread_export(f) and Path(f).suffix.lower() == expected_ext+ ]++ if len(candidates) == 1:+ resolved[name] = candidates[0]+ used.add(candidates[0])+ print(f" Matched deliverable '{name}': {expected} -> {candidates[0]} (only file with {expected_ext})")+ continue++ best_match, best_score = _fuzzy_match_filename(expected, candidates)++ if best_match:+ resolved[name] = best_match+ used.add(best_match)+ print(f" Matched deliverable '{name}': {expected} -> {best_match} (fuzzy match, {best_score} words)")+ else:+ resolved[name] = expected+ print(f" No fuzzy match for deliverable '{name}': {expected}")++ # LLM-based matching for any unresolved deliverables+ unresolved = {name: expected for name, expected in resolved.items()+ if expected not in actual_files and expected == deliverables_map[name]}+ remaining_files = [f for f in actual_files if f not in used and not _is_thread_export(f)]++ if unresolved and remaining_files and output_dir:+ llm_matches = _llm_match_deliverables(unresolved, remaining_files, output_dir)+ for name, matched_file in llm_matches.items():+ if matched_file and matched_file in actual_files:+ resolved[name] = matched_file+ used.add(matched_file)+ print(f" Matched deliverable '{name}': {deliverables_map[name]} -> {matched_file} (LLM match)")++ return resolved+++def _llm_match_deliverables(+ unresolved: dict[str, str],+ available_files: list[str],+ output_dir: Path,+) -> dict[str, str | None]:+ """Use an LLM to match unresolved deliverables to available output files.++ Provides the model with deliverable names, expected filenames, available+ filenames, and a preview of each file's content.+ """+ # Build file previews+ file_previews = []+ for filename in available_files:+ filepath = output_dir / filename+ if filepath.exists():+ try:+ content = _read_file_as_text(filepath)[:500]+ except Exception:+ content = "(could not read file)"+ else:+ content = "(file not found)"+ file_previews.append(f"Filename: {filename}\nPreview: {content}\n")++ # Build deliverable descriptions+ deliverable_descriptions = []+ for name, expected in unresolved.items():+ deliverable_descriptions.append(f"Deliverable key: {name}\nExpected filename: {expected}")++ deliverables_text = "\n".join(deliverable_descriptions)+ files_text = "\n".join(file_previews)+ deliverable_keys = list(unresolved.keys())++ prompt = f"""Match each unresolved deliverable to the most likely output file.++## Unresolved Deliverables+{deliverables_text}++## Available Output Files+{files_text}++For each deliverable, provide the matching filename from the available files, or null if no file matches."""++ # Build JSON schema with the exact deliverable keys as properties+ schema_properties = {key: {"type": ["string", "null"]} for key in deliverable_keys}+ output_schema = {+ "type": "object",+ "properties": schema_properties,+ "required": deliverable_keys,+ "additionalProperties": False,+ }++ try:+ client = anthropic.Anthropic()+ response = client.messages.create(+ model="claude-sonnet-4-6",+ max_tokens=1024,+ temperature=0.0,+ messages=[{"role": "user", "content": prompt}],+ output_config={+ "format": {+ "type": "json_schema",+ "schema": output_schema,+ }+ },+ )+ return json.loads(response.content[0].text)+ except Exception as e:+ print(f" LLM matching failed: {e}")++ return {}+++# ── Rubric Scoring ───────────────────────────────────────────────++# Directories and extensions to skip when loading all output (build artifacts)+_SKIP_DIRS = {"node_modules", ".npm", "__pycache__", ".git", "venv", ".venv"}+_SKIP_EXTENSIONS = {".lock", ".map"}+_SKIP_FILES = {"package-lock.json"}+++def _load_all_output(output_dir: Path) -> str:+ """Read all files in the output directory as a single text block.++ Skips build artifacts (node_modules, lockfiles, etc.) to avoid+ blowing up the judge context window.+ """+ sections = []+ if output_dir.exists():+ for f in sorted(output_dir.rglob("*")):+ if not f.is_file():+ continue+ # Skip build artifact directories+ if any(part in _SKIP_DIRS for part in f.relative_to(output_dir).parts):+ continue+ # Skip lockfiles and sourcemaps+ if f.suffix in _SKIP_EXTENSIONS or f.name in _SKIP_FILES:+ continue+ content = _read_file_as_text(f)+ sections.append(f"## {f.relative_to(output_dir)}\n{content}")+ return "\n\n".join(sections) if sections else "(No agent output found)"+++def score_rubric(+ criteria: list[dict],+ run_dir,+ judge,+ task_desc: str,+ parallel: int,+) -> RubricResult:+ """Score agent output against rubric criteria with deliverable-aware file loading.++ Each criterion declares which output files (deliverables) are relevant to it+ via its 'deliverables' list. Only those files are loaded into context for+ the judge. Criteria without a 'deliverables' list fall back to loading all+ output files.++ Args:+ criteria: List of criterion dicts from task.json.+ run_dir: Path to the run directory (contains output/ folder).+ judge: Judge instance for LLM evaluation.+ task_desc: Task title for context in the judge prompt.+ parallel: Number of judge calls to run concurrently.+ """+ run_dir = Path(run_dir)+ output_dir = run_dir / "output"++ # Build deliverable map from criterion-level deliverables lists.+ # Each criterion lists expected output filenames directly (e.g., "nda-term-sheet.docx").+ filenames = set()+ for c in criteria:+ for d in c.get("deliverables", []):+ filenames.add(d)+ deliverables_map = {f: f for f in filenames} if filenames else None++ # Match expected deliverable filenames to actual output files+ if deliverables_map and output_dir.exists():+ actual_files = [f.name for f in output_dir.rglob("*") if f.is_file()]+ resolved_map = _match_deliverables(deliverables_map, actual_files, output_dir=output_dir)+ else:+ resolved_map = None++ # Pre-load full output for tasks without per-criterion deliverables+ full_output = None+ if any(not (c.get("deliverables") and resolved_map) for c in criteria):+ full_output = _load_all_output(output_dir)++ def _score_one(criterion: dict) -> CriterionResult:+ criterion_deliverables = criterion.get("deliverables", [])+ if criterion_deliverables and resolved_map:+ sections = []+ for name in criterion_deliverables:+ filename = resolved_map[name]+ filepath = output_dir / filename+ if not filepath.exists():+ sections.append(f"## Agent Output: {name}\n(File not found: {filename})")+ continue+ include_redlines = criterion.get("evaluation_options", {}).get("include_docx_redlines", False)+ track_changes = DocxTrackChanges.ALL if include_redlines else DocxTrackChanges.ACCEPT+ content = _read_file_as_text(filepath, track_changes=track_changes)+ sections.append(f"## Agent Output: {name}\n{content}")+ agent_output = "\n\n".join(sections) if sections else "(No agent output found)"+ else:+ agent_output = full_output++ result = judge.evaluate_from_file(+ prompt_name="rubric_criterion",+ variables={+ "task_description": task_desc,+ "agent_output": agent_output,+ "criterion_title": criterion["title"],+ "match_criteria": criterion["match_criteria"],+ },+ )++ verdict = result.get("verdict", "fail").lower()+ reasoning = result.get("reasoning", "")++ return CriterionResult(+ id=criterion["id"],+ title=criterion["title"],+ verdict=verdict,+ reasoning=reasoning,+ )++ with ThreadPoolExecutor(max_workers=max(parallel, 1)) as pool:+ criteria_results = list(pool.map(_score_one, criteria))++ # All-pass grading: task scores 1.0 only if every criterion passed.+ n_total = len(criteria_results)+ n_passed = sum(1 for c in criteria_results if c.verdict == "pass")+ score = 1.0 if n_total > 0 and n_passed == n_total else 0.0++ return RubricResult(+ score=score,+ max_score=1.0,+ criteria_results=[c.to_dict() for c in criteria_results],+ )diff --git a/tests/test_lab_judge_patch.py b/tests/test_lab_judge_patch.pynew file mode 100644index 0000000..217d45d--- /dev/null+++ b/tests/test_lab_judge_patch.py@@ -0,0 +1,206 @@+# Copyright 2026 Google LLC+# SPDX-License-Identifier: Apache-2.0+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# https://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""Apply the shipped LAB patch to its exact MIT upstream and replay grading offline."""++import ast+import contextlib+import hashlib+import io+import json+import os+import re+import shutil+import subprocess+import tempfile+import unittest+from concurrent.futures import ThreadPoolExecutor+from dataclasses import asdict, dataclass, field+from datetime import datetime, timezone+from enum import StrEnum+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import Mock++from harness2 import config+from harness2.benchmarks.lab import LabAdapter+from harness2.core.judge import judge_one++ROOT = Path(__file__).resolve().parents[1]+FIXTURE = ROOT / "tests/fixtures/harvey-labs"+PATCH = ROOT / "third_party/patches/harvey-labs-judge-vertex-anthropic.diff"+++def load_nodes(path, names, scope):+ """Execute exact upstream definitions, excluding dependency/client imports."""+ tree = ast.parse(path.read_text(encoding="utf-8"))+ nodes = []+ for node in tree.body:+ if isinstance(node, (ast.FunctionDef, ast.ClassDef)) and node.name in names:+ nodes.append(node)+ elif isinstance(node, ast.Assign) and any(+ isinstance(target, ast.Name) and target.id in names for target in node.targets+ ):+ nodes.append(node)+ exec(compile(ast.Module(body=nodes, type_ignores=[]), str(path), "exec"), scope)+++class LabJudgePatchTests(unittest.TestCase):+ def setUp(self):+ temporary = tempfile.TemporaryDirectory()+ self.addCleanup(temporary.cleanup)+ self.root = Path(temporary.name)+ provenance = json.loads((FIXTURE / "PROVENANCE.json").read_text())+ self.assertEqual(provenance["commit"], config.DEPENDENCY_PINS["harvey-labs"])+ for name, expected in provenance["sha256"].items():+ self.assertEqual(hashlib.sha256((FIXTURE / name).read_bytes()).hexdigest(), expected)+ assets = json.loads((ROOT / "dependencies/ASSETS.json").read_text())+ self.assertEqual(+ hashlib.sha256(PATCH.read_bytes()).hexdigest(),+ assets[PATCH.relative_to(ROOT).as_posix()],+ )+ upstream = self.root / "upstream"+ shutil.copytree(FIXTURE, upstream)+ for path in upstream.rglob("*.py.txt"):+ path.rename(path.with_suffix(""))+ subprocess.run(["git", "apply", str(PATCH)], cwd=upstream, check=True, capture_output=True)+ self.scope = {+ "__name__": __name__,+ "Path": Path,+ "json": json,+ "os": os,+ "re": re,+ "dataclass": dataclass,+ "field": field,+ "asdict": asdict,+ "StrEnum": StrEnum,+ "ThreadPoolExecutor": ThreadPoolExecutor,+ "subprocess": subprocess,+ "datetime": datetime,+ "timezone": timezone,+ "PROMPTS_DIR": upstream / "evaluation/prompts",+ "BENCH_ROOT": self.root,+ "RESULTS_DIR": self.root / "results",+ }+ load_nodes(upstream / "evaluation/judge.py", {"Judge"}, self.scope)+ load_nodes(+ upstream / "evaluation/scoring.py",+ {+ "DocxTrackChanges",+ "CriterionResult",+ "RubricResult",+ "_read_file_as_text",+ "_SKIP_DIRS",+ "_SKIP_EXTENSIONS",+ "_SKIP_FILES",+ "_load_all_output",+ "score_rubric",+ },+ self.scope,+ )+ load_nodes(+ upstream / "evaluation/run_eval.py",+ {+ "REQUIRED_TASK_KEYS",+ "REQUIRED_CRITERION_KEYS",+ "validate_task_config",+ "_resolve_task_dir",+ "evaluate_run",+ },+ self.scope,+ )+ task = self.root / "tasks/contracts/task-1"+ task.mkdir(parents=True)+ (task / "task.json").write_text(+ json.dumps(+ {+ "title": "Review the local report",+ "instructions": "Write report.txt",+ "criteria": [+ {+ "id": "c1",+ "title": "Correct report",+ "match_criteria": "Review the report",+ }+ ],+ }+ )+ )+ self.run = self.root / "results/run-1"+ (self.run / "output").mkdir(parents=True)+ (self.run / "output/report.txt").write_text("The locally produced report.\n")++ def score(self, responses):+ transport = Mock(+ side_effect=[+ SimpleNamespace(+ content=[SimpleNamespace(type="text", text=text)],+ stop_reason="end_turn",+ )+ for text in responses+ ]+ )+ judge = object.__new__(self.scope["Judge"])+ judge.provider = "vertex-anthropic"+ judge.model = "fixture-judge"+ judge.client = SimpleNamespace(messages=SimpleNamespace(create=transport))+ with contextlib.redirect_stdout(io.StringIO()):+ scores = self.scope["evaluate_run"]("run-1", "contracts/task-1", judge, parallel=1)+ self.assertTrue((self.run / "scores.json").is_file())+ cached = judge_one(LabAdapter(), "contracts/task-1", "agg", 1, "agg1", "run-1", self.run)+ self.assertEqual(cached.all_pass, scores["all_pass"])+ return scores, cached, transport++ def test_conflicting_fenced_verdicts_retry_before_writing_a_score(self):+ response = 'Format:\n```json\n{"verdict":"pass","reasoning":"example"}\n```\nAnswer:\n```json\n{"verdict":"fail","reasoning":"actual verdict"}\n```'+ scores, cached, transport = self.score([response, '{"verdict":"fail","reasoning":"retry"}'])+ self.assertFalse(scores["all_pass"])+ self.assertEqual(transport.call_count, 2)+ self.assertEqual(cached.frac, 0)++ def test_ambiguity_exhaustion_never_writes_a_score(self):+ response = '```json\n{"verdict":"pass"}\n```\n```json\n{"verdict":"fail"}\n```'+ with self.assertRaisesRegex(ValueError, "Ambiguous judge response"):+ self.score([response] * 4)+ self.assertFalse((self.run / "scores.json").exists())++ def test_agreeing_repeated_fences_are_a_valid_grade(self):+ response = '```json\n{"verdict":"pass","reasoning":"one"}\n```\n```json\n{"verdict":"pass","reasoning":"same"}\n```'+ scores, cached, transport = self.score([response])+ self.assertEqual(transport.call_count, 1)+ self.assertTrue(scores["all_pass"])+ self.assertEqual(cached.frac, 1)++ def test_fail_verdict_controls(self):+ for response in (+ '{"verdict":"fail","reasoning":"not correct"}',+ 'Review complete.\n```json\n{"verdict":"fail","reasoning":"not correct"}\n```',+ ):+ with self.subTest(response=response):+ scores, cached, transport = self.score([response])+ self.assertEqual(transport.call_count, 1)+ self.assertFalse(scores["all_pass"])+ self.assertEqual(cached.frac, 0)++ def test_existing_unfenced_ambiguity_guard_remains_active(self):+ response = '{"verdict":"pass"}\nAnswer: {"verdict":"fail"}'+ scores, cached, transport = self.score([response, '{"verdict":"fail","reasoning":"retry"}'])+ self.assertFalse(scores["all_pass"])+ self.assertEqual(transport.call_count, 2)+ self.assertEqual(cached.frac, 0)+++if __name__ == "__main__":+ unittest.main()diff --git a/third_party/patches/harvey-labs-judge-vertex-anthropic.diff b/third_party/patches/harvey-labs-judge-vertex-anthropic.diffindex f1dbfe1..95f2eec 100644--- a/third_party/patches/harvey-labs-judge-vertex-anthropic.diff+++ b/third_party/patches/harvey-labs-judge-vertex-anthropic.diff@@ -136,15 +136,24 @@def _evaluate_anthropic(self, prompt: str, temperature: float, _retries: int) -> dict:last_err: Exception | None = None-@@ -236,11 +326,21 @@- match = re.search(r"```(?:json)?\s*\n?(.*?)\n?```", text, re.DOTALL)- if match:- try:+@@ -232,15 +322,25 @@+ @staticmethod+ def _parse_json(text: str) -> dict:+ """Extract JSON from model response, handling markdown fences."""+- # Try to find JSON in code fences first+- match = re.search(r"```(?:json)?\s*\n?(.*?)\n?```", text, re.DOTALL)+- if match:+- try:- return json.loads(match.group(1).strip())++ # Fenced JSON is subject to the same ambiguity check as prose objects.++ # Returning the first fence can mistake a format example for the verdict.++ objs = []++ for match in re.finditer(r"```(?:json)?\s*\n?(.*?)\n?```", text, re.DOTALL):++ try:+ # strict=False tolerates raw control characters (notably literal+ # newlines) inside strings — the judge quotes multi-line document+ # excerpts into `reasoning`, and strict parsing rejects those.-+ return json.loads(match.group(1).strip(), strict=False)++ objs.append(json.loads(match.group(1).strip(), strict=False))except json.JSONDecodeError:pass # Fall through to brace matching@@ -156,7 +165,6 @@+ # ('Format: {"verdict": "pass"} ... Answer: {"verdict": "fail", ...}')+ # would otherwise be scored on the echo, which is the same manufactured+ # verdict the last-resort branch below guards against -- just one layer up.-+ objs = []for i, ch in enumerate(text):if ch == '{':depth = 0