diff --git a/.gitattributes b/.gitattributes index bed0738c7eeb449bca98b5d2f33c89a1ee56349a..2fcbdfcbea694b09ade0339eecee206cd14dccb1 100644 --- a/.gitattributes +++ b/.gitattributes @@ -58,3 +58,28 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text # Video files - compressed *.mp4 filter=lfs diff=lfs merge=lfs -text *.webm filter=lfs diff=lfs merge=lfs -text +tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/workdir/attachments/1774361815-lcu-project.pdf filter=lfs diff=lfs merge=lfs -text +tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/workdir/attachments/1774361815-orderpdf.docx filter=lfs diff=lfs merge=lfs -text +tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/workdir/attachments/1774361815-petition.docx filter=lfs diff=lfs merge=lfs -text +tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/workdir/attachments/1774361815-resolution.docx filter=lfs diff=lfs merge=lfs -text +tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/workdir/attachments/dcmr_title6b_1606.pdf filter=lfs diff=lfs merge=lfs -text +tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/workdir/attachments/douglas_v_veterans_admin.pdf filter=lfs diff=lfs merge=lfs -text +tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/workdir/attachments/dc_code_1-605.02.pdf filter=lfs diff=lfs merge=lfs -text +tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/workdir/attachments/fop_doc_labor_comm_v_perb_2009.pdf filter=lfs diff=lfs merge=lfs -text +tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/workdir/attachments/paperworkers_v_misco.pdf filter=lfs diff=lfs merge=lfs -text +tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/workdir/attachments/wr_grace_v_rubber_workers.pdf filter=lfs diff=lfs merge=lfs -text +tasks/lrb-forum-non-conveniens-response/steps/assignment-1/workdir/attachments/2023[[:space:]]Annual[[:space:]]Report[[:space:]]Statistical[[:space:]]Summary.pdf filter=lfs diff=lfs merge=lfs -text +tasks/lrb-forum-non-conveniens-response/steps/assignment-1/workdir/attachments/Bradbury[[:space:]]v.[[:space:]]St.[[:space:]]Mary's[[:space:]]Hospital.pdf filter=lfs diff=lfs merge=lfs -text +tasks/lrb-forum-non-conveniens-response/steps/assignment-1/workdir/attachments/Defendants[[:space:]]Motion[[:space:]]to[[:space:]]Transfer.pdf filter=lfs diff=lfs merge=lfs -text +tasks/lrb-forum-non-conveniens-response/steps/assignment-1/workdir/attachments/First[[:space:]]Am[[:space:]]Bank[[:space:]]v.[[:space:]]Guerine.pdf filter=lfs diff=lfs merge=lfs -text +tasks/lrb-forum-non-conveniens-response/steps/assignment-1/workdir/attachments/Langenhorst[[:space:]]v.[[:space:]]Norfolk[[:space:]]Southern.pdf filter=lfs diff=lfs merge=lfs -text +tasks/lrb-forum-non-conveniens-response/steps/assignment-2/workdir/attachments/2023[[:space:]]Annual[[:space:]]Report[[:space:]]Statistical[[:space:]]Summary.pdf filter=lfs diff=lfs merge=lfs -text +tasks/lrb-forum-non-conveniens-response/steps/assignment-2/workdir/attachments/Bradbury[[:space:]]v.[[:space:]]St.[[:space:]]Mary's[[:space:]]Hospital.pdf filter=lfs diff=lfs merge=lfs -text +tasks/lrb-forum-non-conveniens-response/steps/assignment-2/workdir/attachments/Defendants[[:space:]]Motion[[:space:]]to[[:space:]]Transfer.pdf filter=lfs diff=lfs merge=lfs -text +tasks/lrb-forum-non-conveniens-response/steps/assignment-2/workdir/attachments/First[[:space:]]Am[[:space:]]Bank[[:space:]]v.[[:space:]]Guerine.pdf filter=lfs diff=lfs merge=lfs -text +tasks/lrb-forum-non-conveniens-response/steps/assignment-2/workdir/attachments/Langenhorst[[:space:]]v.[[:space:]]Norfolk[[:space:]]Southern.pdf filter=lfs diff=lfs merge=lfs -text +tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/Ellison.pdf filter=lfs diff=lfs merge=lfs -text +tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/Facts.pdf filter=lfs diff=lfs merge=lfs -text +tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/Patton[[:space:]]State[[:space:]]Plea.pdf filter=lfs diff=lfs merge=lfs -text +tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/workdir/attachments/Facts.pdf filter=lfs diff=lfs merge=lfs -text +tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/workdir/attachments/Kuhse.pdf filter=lfs diff=lfs merge=lfs -text diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..619f6bb2ca3b3d639c67750a9c548d9e38f4a70a --- /dev/null +++ b/README.md @@ -0,0 +1,145 @@ +--- +license: cc-by-4.0 +language: + - en +pretty_name: LegalReasonBench (sample) +task_categories: + - text-generation +annotations_creators: + - expert-generated +language_creators: + - expert-generated +source_datasets: + - original +size_categories: + - n<1K +tags: + - legal + - legal-reasoning + - agents + - long-horizon + - benchmark +configs: + - config_name: assignments + data_files: + - split: test + path: data/assignments/*.parquet +--- + +# LegalReasonBench (micro1): Sample Release + +LegalReasonBench measures how well AI agents carry a legal matter through a sequence of +assignments the way a practicing lawyer would: reading a case file, researching the law, +applying it to the facts, and producing court filings and memoranda, where each assignment +builds on the work before it. Every deliverable is graded against attorney-authored +rubrics that reward required legal points and penalize specific errors. + +**Published report:** https://www.micro1.ai/benchmark/legal-reason-bench + +## Citation + +Please cite as: **"LegalReasonBench (micro1). Available at: https://www.micro1.ai/benchmark/legal-reason-bench"** + +## Scope of this release + +This is a sample of **5 matters (10% of LegalReasonBench)**, released for evaluation and +benchmarking. The remaining matters are held out. To request access to the full dataset, +contact isabel@micro1.ai. + +| Matter | Practice area | Assignments | Criteria (penalties) | Research | +|---|---|---:|---:|---| +| `lrb-certiorari-quasi-judicial-land-use` · Petition for Writ of Certiorari for Quasi-judicial Proceeding | Real estate and land use | 2 | 37 (5) | open | +| `lrb-dcca-challenge-police-discipline` · Viability of a DCCA Challenge | Employment and labor | 5 | 54 (11) | closed | +| `lrb-interim-cmo-appointment-governance` · Interim CMO Appointment: Governance and Compliance Analysis | Corporate governance | 4 | 42 (8) | closed | +| `lrb-vicar-trial-jury-instructions` · OTB Gang VICAR Trial Jury Instructions | Criminal and investigations | 2 | 35 (7) | closed | +| `lrb-forum-non-conveniens-response` · Plaintiff's Response, Forum Non Conveniens | Litigation and dispute resolution | 2 | 53 (5) | closed | + +15 assignments, 221 criteria, 40 attachments (PDF and DOCX). + +**Research universe.** In an *open-universe* matter the agent may research outside +authority on the web. In a *closed-universe* matter the prompt restricts it to the +supplied case file. + +## Contents + +A `tasks/` tree of **5 runnable [Harbor](https://harborframework.com) multi-step tasks**, +one per matter, plus a Parquet index for the Dataset Viewer. + +``` +tasks/lrb-dcca-challenge-police-discipline/ +├── task.toml # metadata, timeouts, one [[steps]] entry per assignment +├── environment/Dockerfile # sandbox: Python, pandoc, poppler-utils, LibreOffice +└── steps/ + ├── assignment-1/ + │ ├── instruction.md # role prompt + the assignment, shown to the agent + │ ├── workdir/attachments/ # case-file documents for this assignment (copied to /app/attachments/) + │ ├── tests/ # verifier, NOT visible to the agent + │ │ ├── fixtures/rubric.json # the weighted criteria for this assignment + │ │ ├── raw_correctness/*.toml # one judge criterion per rubric item + │ │ ├── m1_judge_panel.json # the three-judge panel + │ │ └── test.sh # verifier entrypoint + │ └── solution/solve.sh # no oracle solution ships + ├── assignment-2/ + └── ... +``` + +Assignments run in order in one persistent `/app` sandbox. Each assignment writes its +deliverable to `/app/response.md`, and later assignments can read earlier deliverables +and attachments. + +## Dataset Viewer columns + +The `assignments/test` split has one row per assignment. + +- `matter_id`, `matter_title`, `practice_area`, `research_universe` +- `assignment`, `num_assignments`, `assignment_title` +- `prompt`: the full assignment prompt (the instruction file adds the shared role prompt) +- `attachments`: paths of the documents introduced in this assignment +- `rubric_count`, `penalty_count`, `positive_points` +- `rubric`: JSON list of criteria with `criterion_id`, `points` (negative for penalties), + `polarity`, `irac_section` (Issue, Rule, Application, Conclusion), `criterion`, + `source` (the authority or record cite the criterion rests on) and `justification` +- `instruction_path`, `rubric_path`, `source_task_path`: paths into the Harbor bundle + +## Scoring + +- **Criteria.** Each criterion is judged pass or fail. A required criterion earns its + points when met. A penalty criterion subtracts its points when the deliverable commits + the described error. +- **Assignment reward.** Signed points earned over available positive points, clamped to + [0, 1]. +- **Matter reward.** Points-weighted across the matter's assignments: total signed points + earned over total positive points, clamped to [0, 1]. `scripts/score_matter.py` + computes it from a finished Harbor trial. Harbor's built-in `multi_step_reward_strategy + = "mean"` is diagnostic only. +- **Judges.** A strict majority of three LLM judges decides every criterion: GPT-5.6 + Terra, Claude Sonnet 5 and Gemini 3.8 Flash, each at medium reasoning effort. Each + criterion is judged in its own call, and the judge reads only the deliverable. + +## Running + +```bash +uv tool install harbor +export OPENAI_API_KEY=... ANTHROPIC_API_KEY=... GEMINI_API_KEY=... # the judge panel +harbor run -p tasks/lrb-dcca-challenge-police-discipline -a opencode -m +harbor run -p tasks -a opencode -m # all five matters +python scripts/score_matter.py +``` + +All three judge keys are required. The panel fails the assignment if any judge cannot be +reached, rather than scoring with fewer votes. The published results ran the OpenCode agent +with a three-hour limit per assignment. + +## Important notes + +- **Sources.** The case files combine public legal authority (court opinions, statutes, + regulations and pattern jury instructions), public court records reproduced as filed, + and matter documents that legal experts wrote or adapted for the benchmark. Some matters + are built on real, publicly filed cases, so public records can name real parties. +- **No professional use.** This dataset does not provide legal advice and should not be + used for production decision-making without independent validation. +- **No endorsement.** Use of this dataset does not imply endorsement by micro1. + +## License + +CC-BY-4.0. diff --git a/data/assignments/test-00000-of-00001.parquet b/data/assignments/test-00000-of-00001.parquet new file mode 100644 index 0000000000000000000000000000000000000000..e4e275594cde603b2aa9b38dce7a0000fa8bd67a --- /dev/null +++ b/data/assignments/test-00000-of-00001.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:75895d086e365475284e6c4f65eb921a5b299632b82d6472205127c8e335d0f7 +size 85282 diff --git a/scripts/score_matter.py b/scripts/score_matter.py new file mode 100644 index 0000000000000000000000000000000000000000..8777b9f68e96fec4e942ae1f0ea225240c9bd61c --- /dev/null +++ b/scripts/score_matter.py @@ -0,0 +1,40 @@ +"""Score one LegalReasonBench matter from a finished Harbor trial. + +The matter reward is points-weighted across its assignments: the sum of signed +points earned (penalties subtract) over the sum of available positive points, +clamped to [0, 1]. Harbor's own multi_step_reward_strategy = "mean" averages the +per-assignment rewards instead and is diagnostic only. + +Usage: python score_matter.py +""" +import json +import sys +from pathlib import Path + + +def score(trial_dir: Path) -> dict: + earned = positive = 0.0 + steps = [] + # Each assignment's verifier writes reward-details.json; the raw RewardKit copy + # under raw/ has no aggregation block and is skipped. + for details in sorted(trial_dir.rglob("reward-details.json")): + correctness = json.loads(details.read_text()).get("correctness") + aggregation = correctness.get("aggregation") if isinstance(correctness, dict) else None + if not isinstance(aggregation, dict) or "earned" not in aggregation or "positive_total" not in aggregation: + continue + earned += float(aggregation["earned"]) + positive += float(aggregation["positive_total"]) + steps.append({ + "file": str(details.relative_to(trial_dir)), + "assignment_reward": correctness.get("score"), + "earned": aggregation["earned"], + "positive_total": aggregation["positive_total"], + }) + if not steps: + raise SystemExit(f"no assignment reward-details.json under {trial_dir}") + overall = max(0.0, min(1.0, earned / positive)) if positive > 0 else 0.0 + return {"matter_reward": overall, "earned": earned, "positive_total": positive, "assignments": steps} + + +if __name__ == "__main__": + print(json.dumps(score(Path(sys.argv[1])), indent=2)) diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/environment/Dockerfile b/tasks/lrb-certiorari-quasi-judicial-land-use/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c481aae22685617adcf60d0de6e473ce9019975a --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/environment/Dockerfile @@ -0,0 +1,29 @@ +FROM python:3.13-slim-bookworm + +RUN apt-get update && apt-get install -y --no-install-recommends \ + bash \ + ca-certificates \ + curl \ + file \ + git \ + libreoffice-calc \ + libreoffice-impress \ + libreoffice-writer \ + pandoc \ + poppler-utils \ + unzip \ + fonts-dejavu \ + && rm -rf /var/lib/apt/lists/* + +RUN python -m pip install --no-cache-dir \ + uv \ + openpyxl \ + pandas \ + pdfplumber \ + pypdf \ + python-docx \ + python-pptx \ + xlrd + +WORKDIR /app +RUN ln -s . /app/app diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/instruction.md b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..48862deeb0d56e348325ddccc5fe655d8657a883 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/instruction.md @@ -0,0 +1,54 @@ +# Petition for Writ of Certiorari for Quasi-judicial Proceeding — Legal Memorandum to Board of County Commissioners + +Domain: Legal + +Matter: Petition for Writ of Certiorari for Quasi-judicial Proceeding + +You are a senior legal analyst operating autonomously. You are completing a multi-step legal reasoning task. Follow the role, factual record, instructions, and deliverable requirements provided in the Task and each Assignment. + +Each Assignment may require a different legal deliverable. Follow the requirements specific to that Assignment. + +## Word limits for court briefs + +- A brief in support of or in response to a motion may not exceed **8,750 words**. +- A reply brief may not exceed **3,500 words**. +- For a motion for reconsideration, a brief in support of or in response to the motion may not exceed **3,500 words**, and a reply brief may not exceed **1,750 words**. +- If an Assignment specifies a stricter word limit, follow the stricter limit. + +These word limits do not apply to legal memoranda or other non-court-filing deliverables unless the Assignment expressly provides otherwise. + +Complete the task end-to-end without asking for confirmation, permission, or clarification. + +Use the uploaded matter documents in `/app/attachments/` as your primary case file. You also have internet access via OpenCode's `websearch` tool; use it to research any statutes, regulations, cases, administrative guidance, or secondary authorities that are not supplied as attachments. Cite any authority you rely on in the format requested by the prompt. + +For document inspection: +- PDF: `pdftotext /app/attachments/.pdf -` +- DOCX: `pandoc /app/attachments/.docx -t markdown` +- XLSX/CSV: use Python with `openpyxl` or `pandas` +- If extraction is unreliable, inspect the raw file with Python libraries or convert/render the relevant pages. + +Write the final complete legal deliverable for this assignment to `/app/response1.md`. The verifier reads only that file. + +## Attachments + +- `/app/attachments/1774361815-lcu-project.pdf`: LCU Project Detail +- `/app/attachments/1774361815-orderpdf.docx`: Order Granting Petition +- `/app/attachments/1774361815-petition.docx`: Petition for Writ of Certiorari +- `/app/attachments/1774361815-resolution.docx`: Resolution Z-23-035 + + +## Prompt + +1st ASSIGNMENT +TO: Denise Swarek, Assistant County Attorney +FROM: Thomas Rowe, County Attorney +RE: PETER SPAHN, ET. AL., V. LEE COUNTY; Case No. 24-CA-1479 +DATE: October 27, 2025 +________________________________________ +We received the attached Order Granting Petition for Writ of Certiorari. +You are initially provided with the following record as uploaded files. Limit your review to these documents and what legal research is necessary to identify applicable rules and case law relevant to these documents. Do not conduct legal research beyond that. All legal analysis should be based on the versions of statutes, regulations, and ordinances in effect as of January 1, 2025. +• Resolution Z-23-035 (Resolution.docx) +• Petition for Writ of Certiorari (Petition.docx) +• Order Granting Petition (Orderpdf.docx) +• LCU Project Detail (LCU Project.pdf) +Review only these documents and draft a structured legal memorandum to the Board of County Commissioners that 1) outlines the Order and case history, 2) explains the implications of the Order, 3) identifies options and available actions for Lee County, 4) recommends a legal course of action to the Board. Use full Bluebook citation format. diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/solution/solve.sh b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7710414a6da6d0ad740717c8c85a9af850d5da33 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/solution/solve.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# No oracle solution ships with LegalReasonBench. The verifier grades the +# agent's own legal deliverable for this assignment against the rubric. +echo "no oracle solution" diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/fixtures/config.json b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/fixtures/config.json new file mode 100644 index 0000000000000000000000000000000000000000..5ae21048065a46246e8d65beed01c6099441e329 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/fixtures/config.json @@ -0,0 +1,466 @@ +{ + "task_id": "lrb-certiorari-quasi-judicial-land-use", + "title": "Petition for Writ of Certiorari for Quasi-judicial Proceeding", + "domain": "Legal", + "matter": "Petition for Writ of Certiorari for Quasi-judicial Proceeding", + "judge": { + "max_concurrent_llm": 12, + "mode": "panel", + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ], + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + "step_index": 1, + "step_name": "assignment-1", + "step_title": "Legal Memorandum to Board of County Commissioners", + "prompt": "1st ASSIGNMENT\nTO: Denise Swarek, Assistant County Attorney\nFROM: Thomas Rowe, County Attorney\nRE: PETER SPAHN, ET. AL., V. LEE COUNTY; Case No. 24-CA-1479\nDATE: October 27, 2025\n________________________________________\nWe received the attached Order Granting Petition for Writ of Certiorari. \nYou are initially provided with the following record as uploaded files. Limit your review to these documents and what legal research is necessary to identify applicable rules and case law relevant to these documents. Do not conduct legal research beyond that. All legal analysis should be based on the versions of statutes, regulations, and ordinances in effect as of January 1, 2025.\n\u2022\tResolution Z-23-035 (Resolution.docx)\n\u2022\tPetition for Writ of Certiorari (Petition.docx)\n\u2022\tOrder Granting Petition (Orderpdf.docx)\n\u2022\tLCU Project Detail (LCU Project.pdf)\nReview only these documents and draft a structured legal memorandum to the Board of County Commissioners that 1) outlines the Order and case history, 2) explains the implications of the Order, 3) identifies options and available actions for Lee County, 4) recommends a legal course of action to the Board. Use full Bluebook citation format.", + "attachments": [ + { + "filename": "1774361815-lcu-project.pdf", + "description": "LCU Project Detail", + "metadata": {}, + "path": "/app/attachments/1774361815-lcu-project.pdf" + }, + { + "filename": "1774361815-orderpdf.docx", + "description": "Order Granting Petition", + "metadata": {}, + "path": "/app/attachments/1774361815-orderpdf.docx" + }, + { + "filename": "1774361815-petition.docx", + "description": "Petition for Writ of Certiorari", + "metadata": {}, + "path": "/app/attachments/1774361815-petition.docx" + }, + { + "filename": "1774361815-resolution.docx", + "description": "Resolution Z-23-035", + "metadata": {}, + "path": "/app/attachments/1774361815-resolution.docx" + } + ], + "rubric": [ + { + "name": "states_in_the_first_assignment_that_the_order_granting_petition", + "description": "States in the first assignment that the Order Granting Petition for Writ of Certiorari quashes Lee County, Fla., Res. No. Z-23-035 (2024).", + "source": "Order.docx at 1. \"the petition for writ of certiorari is hereby GRANTED and the rezoning is QUASHED for the reasons discussed below.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that 1) outlines the Order and case history.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_order_granting_petition_for_writ_of_cert", + "original_index": 1, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_circuit_court_found_that", + "description": "States in the first assignment that the circuit court found that the Petitioners had standing to bring the petition based on proximity of the Petitioners' property to the proposed facility.", + "source": "Order.docx at 2. \"The court finds that Petitioners have standing to bring this petition for writ of certiorari based on their proximity of Petitioners' property.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that 1) outlines the Order and case history.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_circuit_court_found_that_the_petitioners", + "original_index": 2, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_circuit_court_found_th_2", + "description": "States in the first assignment that the circuit court found that the Lee County Board of County Commissioners \"improperly departed from the record created at the quasi-judicial hearings held below.\"", + "source": "Order.docx at 2. \"[t]he Lee County Board of County Commissioners (\"BOCC\") improperly departed from the record created at the quasi-judicial hearings held below.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that 1) outlines the Order and case history.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_circuit_court_found_that_the_lee_county", + "original_index": 3, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_circuit_court_found_th_3", + "description": "States in the first assignment that the circuit court found that Lee County's conduct \"created prejudice and bias\" surrounding the rezoning.", + "source": "Order.docx at 3. \"Lee county further prejudiced the quasi-judicial process surrounding the quasi-judicial hearing required for rezoning for this wastewater facility by its conduct which predetermined, or at very least created prejudice and bias, the decision to approve this quasi-judicial rezoning.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that 1) outlines the Order and case history.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_circuit_court_found_that_lee_county_s_co", + "original_index": 4, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_circuit_court_found_th_4", + "description": "States in the first assignment that the circuit court found that certain Federal Aviation Administration regulations \"were not fully considered below.\"", + "source": "Order.docx at 5. \"The decision below violated the essential requirements of law contained in the substantive provisions of the Land Development Code (LDC), adopting by reference \"protective\" regulatory guidance such as issued by the FAA regulating Land Use and Compatibility Advisories that were not fully considered below.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that 1) outlines the Order and case history.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_circuit_court_found_that_certain_federal", + "original_index": 5, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "mentions_in_the_first_assignment_that_the_county_s_prior_rezonin", + "description": "Mentions in the first assignment that the county's prior rezoning request in DCI2018-10023 was remanded by the Hearing Examiner to staff for further evaluation and analysis on August 13, 2019.", + "source": "Petition.docx at 17-18. \"LEE COUNTY planner Dirk Danley read into the record the August \n13, 2019 Remand (Tr5 p.2-3): \nFollowing the coordination between the applicant and staff we jointly request that DCI2018-10023 be remanded back to the staff for further evaluation and analysis to include public outreach sessions to address the concerns presented by the public participants during hearing pursuant to comprehensive plan amendments for the proposed public facility and the protection of environmental resources, evaluation and development for a more detailed site plan and to ensure that all alternatives have been fully reviewed and analyzed. The case will be re-analyzed, and future hearings will be noticed in compliance with the Land Development Code and Administrative Code. \"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that 1) outlines the Order and case history.\u201d", + "metadata": { + "review_flag": false, + "original_name": "mentions_in_the_first_assignment_that_the_county_s_prior_rezoning_request_in_dci", + "original_index": 6, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_under_lee_county_fla_admin_c", + "description": "States in the first assignment that under Lee County, Fla. Admin. Code \u00a7 2-6, 4.1 B. (2025), DCI2018-10023 was considered withdrawn on February 13, 2020.", + "source": "Lee County, Fla. Admin. Code \u00a7 2-6, 4.1 B. (2025); https://www.leegov.com/bocc/Administrative%20Codes/AC-2-6.pdf\n\"If the six month deadline is not met because of action or inaction of the Applicant/Appellant, the\napplication/appeal will be considered withdrawn.\"\nRemand occurred on August 13, 2029, and six months after that is February 13, 2020.", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that 1) outlines the Order and case history.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_under_lee_county_fla_admin_code_2_6_4_1_b_20", + "original_index": 7, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_dci2018_10023_remained_activ", + "description": "States in the first assignment that DCI2018-10023 remained active until September 13, 2023.", + "source": "Petition.docx at 19. \"Procedurally, the 2019 zoning case was left open until September 13, 2023.\" This is incorrect because under Lee County Administrative Code 2-6, sec. 4.1 B., the case was considered withdrawn for not meeting the 6 month remand hearing deadline.", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that 1) outlines the Order and case history.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_dci2018_10023_remained_active_until_septembe", + "original_index": 8, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": -15.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "mentions_in_the_first_assignment_that_the_subject_property_was_p", + "description": "Mentions in the first assignment that the subject property was placed into the Public Facilities future land use category of the Lee County Comprehensive Plan pursuant to Lee County, Fla. Ordinance 23-28 (2023).", + "source": "Lee County Fla. Ordinance 23-28 (2023); https://results.leegov.com/Home/DownloadFile/KT0000348490\n\"WHEREAS , the Board held a public hearing for the adoption of the proposed amendment on October 18 , 2023. At that hearing , the Board approved a motion to adopt proposed amendment CPA2023-00003 pertaining to Southeast Advanced Water\nReclamation Facility, amending Map 1-A of the Lee Plan , the Future Land Use Map. \"\nThe future land use category dictates permissible zoning districts, which dictate permitted uses.", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that 1) outlines the Order and case history.\u201d", + "metadata": { + "review_flag": false, + "original_name": "mentions_in_the_first_assignment_that_the_subject_property_was_placed_into_the_p", + "original_index": 9, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_effect_of_the_order_gran", + "description": "States in the first assignment that the effect of the Order Granting Writ of Certiorari is that the Board's decision is overturned.", + "source": "Florida law is unequivocal that when a circuit court finds error in a local government\u2019s quasi-judicial land use decision, its power is limited to quashing the decision and remanding the matter \u201cas if no order had been entered.\u201d See Broward County v. G.B.V. Int\u2019l, Ltd., 787 So. 2d 838, 845 (Fla. 2001) (\u201cWhen a circuit court grants certiorari relief, it quashes the order and leaves the matter pending before the lower tribunal as if no order had been entered.\u201d).\nhttps://caselaw.findlaw.com/court/fl-supreme-court/1495364.html#:~:text=When,judgment,-%2E", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .2) explains the implications of the Order.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_effect_of_the_order_granting_writ_of_cer", + "original_index": 10, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": -10.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_county_must_stop_constru", + "description": "States in the first assignment that the county must stop construction activities as a result of the Order Granting Writ of Certiorari.", + "source": "LCU Project.pdf at 1 shows that construction has started.\n\"Construction of the Southeast Advanced Water Reclamation Facility started on October 6, 2025.\"\nInjunctive relief is not an available remedy in a writ of certiorari of a quasi-judicial decision. See City of Fort Pierce v. Dickerson, 588 So.2d 1080, 1082 (Fla. 4th DCA 1991). https://www.casemine.com/judgement/us/59148822add7b049344ef125#:~:text=Since,injunction \n\"Since review of the resolution should have been by certiorari, the trial court was without jurisdiction to entertain a complaint for declaratory and injunctive relief and should not have granted the Dickersons' motion for a temporary injunction.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .2) explains the implications of the Order.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_county_must_stop_construction_activities", + "original_index": 11, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": -20.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_exclusive_method_of_revi", + "description": "States in the first assignment that the exclusive method of review of a quasi-judicial decision is by petition for writ of certiorari under Fla. R. App. P. 9.100(c) (2025) within 30 days of the written decision.", + "source": "Fla. R. App. P. 9.100(c) (2025); https://rules.floridaappellate.com/rule-9-100/#:~:text=Petitions,by%20certiorari\n\"Petitions for Certiorari; Review of NonFinal Agency Action; Review of Prisoner Disciplinary Action. The following shall be filed within 30 days of rendition of the order to be reviewed:\n\n(1) a petition for certiorari;\n\n(2) a petition to review quasi-judicial action of agencies, boards, and commissions of local government, which action is not directly appealable under any other provision of general law but may be subject to review by certiorari;\"\nSee City of Fort Pierce v. Dickerson, 588 So.2d 1080, 1082 (Fla. 4th DCA 1991).\nhttps://www.casemine.com/judgement/us/59148822add7b049344ef125#:~:text=Thus,relief\n\"Thus, we conclude that the resolution by the Ft. Pierce City Commission was quasi-judicial. Consequently, we agree with Ft. Pierce's assertion that since the resolution was a quasi-judicial decision rendered by the Commission, it was reviewable only by petition for writ of certiorari, and not by a complaint for declaratory and injunctive relief.\"", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .2) explains the implications of the Order.\u201d This is important in responding to the prompt question about implications of the order because it explains why injunctive relief is not available in a writ of certiorari of a quasi-judicial decision.", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_exclusive_method_of_review_of_a_quasi_ju", + "original_index": 12, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 15.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_exclusive_method_of_chal", + "description": "States in the first assignment that the exclusive method of challenging the issuance of a development order that materially alters the use or density or intensity of use on a particular piece of property is by filing a petition for writ of certiorari under Fla. Stat. \u00a7 163.3215(4) (2025) within 30 days of rendition of the development order.", + "source": "Fla. Stat. 163.3215(4) (2025); https://www.leg.state.fl.us/Statutes/index.cfm?App_mode=Display_Statute&URL=0100-0199/0163/Sections/0163.3215.html#:~:text=the%20sole,for%20certiorari\n\"the sole method by which an aggrieved and adversely affected party may challenge any decision of local government granting or denying an application for a development order, as defined in s. 163.3164, which materially alters the use or density or intensity of use on a particular piece of property, is by an appeal filed by a petition for writ of certiorari filed in circuit court no later than 30 days following rendition of a development order or other written decision of the local government, or when all local administrative appeals, if any, are exhausted, whichever occurs later. An action for injunctive or other relief may be joined with the petition for certiorari.\"\nA challenge to issuance of a development order, which is an executive function, is a separate cause of action from appeal of a quasi-judicial decision.", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .2) explains the implications of the Order.\u201d This is crucial because challenging a development order is the sole method to seek injunctive relief under Fla. Stat. 163.3215(4).", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_exclusive_method_of_challenging_the_issu", + "original_index": 13, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_under_fla_stat_163_3167_10_2", + "description": "States in the first assignment that under Fla. Stat \u00a7 163.3167(10) (2025) the development order issued for the project may not be invalidated by a subsequent judicial determination because the timeframe for filing an appeal of the development order has expired.", + "source": "Fla. Stat 163.3167(10) (2025); https://www.leg.state.fl.us/statutes/index.cfm?App_mode=Display_Statute&URL=0100-0199/0163/Sections/0163.3167.html#:~:text=If,standards\n\"If a local government grants a development order pursuant to its adopted land development regulations and the order is not the subject of a pending appeal and the timeframe for filing an appeal has expired, the development order may not be invalidated by a subsequent judicial determination that such land development regulations, or any portion thereof that is relevant to the development order, are invalid because of a deficiency in the approval standards\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .2) explains the implications of the Order.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_under_fla_stat_163_3167_10_2025_the_developm", + "original_index": 14, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_petitioners_may_file_a_s", + "description": "States in the first assignment that the Petitioners may file a separate cause of action for injunction to stop construction activities.", + "source": "See City of Fort Pierce v. Dickerson, 588 So.2d 1080, 1082 (Fla. 4th DCA 1991). https://www.casemine.com/judgement/us/59148822add7b049344ef125#:~:text=Since,injunction \n\"Since review of the resolution should have been by certiorari, the trial court was without jurisdiction to entertain a complaint for declaratory and injunctive relief and should not have granted the Dickersons' motion for a temporary injunction.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .2) explains the implications of the Order.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_petitioners_may_file_a_separate_cause_of", + "original_index": 15, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": -15.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_county_could_appeal_the", + "description": "States in the first assignment that the county could appeal the Order Granting Writ of Certiorari to the Sixth District Court of Appeals pursuant to Fla. R. App. P. 9.030(b)(2)(B).", + "source": "Florida Rule of Appellate Procedure 9.030(b)(2)(B); https://rules.floridaappellate.com/rule-9-030/#:~:text=b%29-,Jurisdiction,capacity\n\"Jurisdiction of District Courts of Appeal.\n\"b) Jurisdiction of District Courts of Appeal.\n. . .\n(2) Certiorari Jurisdiction.8 The certiorari jurisdiction of district courts of appeal may be sought to review:\n(A) nonfinal orders of lower tribunals other than as prescribed by rule 9.130; or\n(B) final orders of circuit courts acting in their review capacity.\"\nSee also Map of Florida\u2019s Court Jurisdictions, available at https://flcourts-media.flcourts.gov/content/download/426177/file/ar-17-18-map-of-floridas-court-jurisdictions.pdf (last accessed Mar. 25, 2026).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .3) identifies options and available actions for the county.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_county_could_appeal_the_order_granting_w", + "original_index": 16, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_county_could_remand_the", + "description": "States in the first assignment that the county could remand the case back to the Hearing Examiner for an evidentiary hearing to address the deficiencies identified in the Order Granting Petition for Writ of Certiorari under Lee County Fla. Land Development Code \u00a7 34-83(a)(6) (2025).", + "source": "Lee County Fla. Land Development Code \u00a7 34-83(a)(6) (2025); https://library.municode.com/fl/lee_county/codes/land_development_code?nodeId=LADECO_CH34ZO_ARTIIAD_DIV2BOCOCO_S34-83FUAU#:~:text=The%20Board%20may%20remand%20a%20case%20back%20to%20the%20Hearing%20Examiner%20for%20further%20review%20of%20specific%20issues%2E%20The%20scope%20of%20the%20remanded%20hearing%20will%20be%20limited%20to%20the%20specific%20issues%20identified%20by%20the%20Board\n\"The Board may remand a case back to the Hearing Examiner for further review of specific issues. The scope of the remanded hearing will be limited to the specific issues identified by the Board.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .3) identifies options and available actions for the county.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_county_could_remand_the_case_back_to_the", + "original_index": 17, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_county_could_file_a_new", + "description": "States in the first assignment that the County could file a new application for rezoning.", + "source": "The Lee County Department of Community Development website has a link to an application for \"Continuance, Deferral, or Withdrawal\" which can be filed at any time by the county; https://www.leegov.com/dcd/zoning/apps#:~:text=Continuance%2C%20Deferral%2C%20OR%20Withdrawal,-%E2%80%8B", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .3) identifies options and available actions for the county.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_county_could_file_a_new_application_for", + "original_index": 18, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_county_could_voluntarily", + "description": "States in the first assignment that the County could voluntarily cease construction activities pending resolution of the challenge.", + "source": "LCU Project.pdf at 1. Construction has started, but could be stopped at the direction of the Board, though the costs would be extremely high.", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .3) identifies options and available actions for the county.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_county_could_voluntarily_cease_construct", + "original_index": 19, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_county_could_take_the_po", + "description": "States in the first assignment that the County could take the position that the rezoning is not necessary because the county is not bound by its local zoning laws in carrying out a governmental function.", + "source": "See Sandra G. Smith, Immunity of State and State Related Activities from Local Municipal Zoning Regulations: Florida Focus, 28 Fla. L. Rev. 800 (1967).\nAvailable at: https://scholarship.law.ufl.edu/flr/vol28/iss3/9 \nhttps://scholarship.law.ufl.edu/cgi/viewcontent.cgi?article=2881&context=flr\n\"The Fourth District Court of Appeal relied\non Nichols for the premise that in the performance of a governmental activity the county should not be subject to its own zoning restrictions. 2 In a 1978\ndecision Dade County was challenged by private property owners when it attempted to violate its own zoning restrictions by building a jail facility on\nproperty reserved for another use under a comprehensive zoning ordinance. 28\nThe Third District Court of Appeal recognized a right under common law and under Florida law for \"a governmental entity to place a governmental\nfacility without regard to a comprehensive zoning ordinance or its procedures.\"\nThe article quotes Metropolitan Dade County v. Parkway Towers Condominium Ass'n, 281 So. 2d 68\n(Fla. 3d DCA 1973), a 3rd DCA case establishing immunity from zoning for governmental purposes. The case is not found publicly available, however the FL Supreme Court accepted, but then discharged), a petition for writ. Note that the FL Supreme Court expressed a \"prospective opinion\" that local governments \"should\" go through rezonings if not in compliance, this is dicta and not binding as the court upheld the district court's decision on immunity. \nParkway Towers Con. Ass'n v. Metropolitan Dade Cnty., 295 So.2d 295 (Fla. 1974); https://law.justia.com/cases/florida/supreme-court/1974/44260-0.html#:~:text=Although,ordinances,-%2E\n\"Although we now consider our issuance of the writ of certiorari to have been improvident in this case, which results in our discharge thereof, it is nevertheless our view prospectively that zoning variations to accommodate county or municipal facility purposes should either have been anticipated in zoning ordinances before construction or operation of such facilities is commenced *296 or, if this has not been done, construction should not be undertaken thereof until after due modification or change therefor is made in existing zoning ordinances.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .3) identifies options and available actions for the county.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_county_could_take_the_position_that_the", + "original_index": 20, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_county_could_negotiate_f", + "description": "States in the first assignment that the County could negotiate for additional conditions protecting wildlife that address Petitioners' concerns.", + "source": "Petitioners' concerns are outlined in Petition.docx at pages 3-13. These include concerns about protection of wild life.", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .3) identifies options and available actions for the county.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_county_could_negotiate_for_additional_co", + "original_index": 21, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_county_could_negotiate_2", + "description": "States in the first assignment that the County could negotiate for additional conditions protecting water quality that address Petitioners' concerns.", + "source": "Petitioners' concerns are outlined in Petition.docx at pages 3-13. These include concerns about protection of water quality.", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .3) identifies options and available actions for the county.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_county_could_negotiate_for_additional_co_2", + "original_index": 22, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_county_should_file_a_tim", + "description": "States in the first assignment that the County should file a timely appeal with the 6th District Court of Appeals.", + "source": "Because the Order contains reversible errors, and because an appeal can be pursued parallel to a remand, this is the best recommendation.\nFlorida Rule of Appellate Procedure 9.030(b)(2)(B); https://rules.floridaappellate.com/rule-9-030/#:~:text=b%29-,Jurisdiction,capacity\n\"Jurisdiction of District Courts of Appeal.\n\"b) Jurisdiction of District Courts of Appeal.\n. . .\n(2) Certiorari Jurisdiction.8 The certiorari jurisdiction of district courts of appeal may be sought to review:\n(A) nonfinal orders of lower tribunals other than as prescribed by rule 9.130; or\n(B) final orders of circuit courts acting in their review capacity.\"\nSee also Map of Florida\u2019s Court Jurisdictions, available at https://flcourts-media.flcourts.gov/content/download/426177/file/ar-17-18-map-of-floridas-court-jurisdictions.pdf (last accessed Mar. 25, 2026).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .4) recommends a legal course of action to the Board.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_county_should_file_a_timely_appeal_with", + "original_index": 23, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 20.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_county_should_remand_the", + "description": "States in the first assignment that the County should remand the case to the Hearing Examiner to address the deficiencies identified in the Order Granting Writ of Certiorari while an appeal is pending.", + "source": "Because the Order contains reversible errors, and because an appeal can be pursued parallel to a remand, this is the best recommendation.\nLee County Fla. Land Development Code \u00a7 34-83(a)(6) (2025); https://library.municode.com/fl/lee_county/codes/land_development_code?nodeId=LADECO_CH34ZO_ARTIIAD_DIV2BOCOCO_S34-83FUAU#:~:text=The%20Board%20may%20remand%20a%20case%20back%20to%20the%20Hearing%20Examiner%20for%20further%20review%20of%20specific%20issues%2E%20The%20scope%20of%20the%20remanded%20hearing%20will%20be%20limited%20to%20the%20specific%20issues%20identified%20by%20the%20Board\n\"The Board may remand a case back to the Hearing Examiner for further review of specific issues. The scope of the remanded hearing will be limited to the specific issues identified by the Board.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .4) recommends a legal course of action to the Board.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_county_should_remand_the_case_to_the_hea", + "original_index": 24, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 20.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_county_should_cease_cons", + "description": "States in the first assignment that the County should cease construction activities at the subject property.", + "source": "LCU Project.pdf at 1 shows that construction has started, which means the county has spent time and money on design, permitting, procurement of contractors, etc. The facility is also necessary to serve increased demand for water and sewer service caused by population growth and has been planned since 2010 (LCU Project.pdf at 4.)\nIn a similar case, the FL Supreme Court declined to delay construction of a public project based on zoning.\nSee Parkway Towers Con. Ass'n v. Metropolitan Dade Cty., 295 So.2d 295 (Fla. 1974); https://law.justia.com/cases/florida/supreme-court/1974/44260-0.html#:~:text=This%20being,result\n\"In this case it appears that on at least two occasions public hearings were held by the Metro County Commission on the question whether the construction of the subject holding facility for prisoners and the work release facility should go forward in the absence of a waiver therefor in the zoning ordinance and in each instance it was agreed by the Commission the construction should proceed. This being so, we feel no useful or practical purpose would be served in interrupting and delaying the construction until a zoning change is effected retroactively to accommodate the Commission's expressly resolved purpose when considered in connection with the fact that no direct conflict of decisions appears. To interrupt the construction now would cause needless expense and damage with no prospect or likelihood that the Commission would reach a different final result.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .4) recommends a legal course of action to the Board.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_county_should_cease_construction_activit", + "original_index": 25, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": -30.0, + "polarity": "negative", + "raw_weight": 1.0 + } + ], + "answer_path": "/app/response1.md", + "answer_relative_path": "response1.md", + "is_followon": false, + "prev_answer_path": "" +} diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/fixtures/rubric.json b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/fixtures/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..0a873b87a8deb768b00897d3f7372138c70ade91 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/fixtures/rubric.json @@ -0,0 +1,404 @@ +{ + "criteria": [ + { + "name": "states_in_the_first_assignment_that_the_order_granting_petition", + "description": "States in the first assignment that the Order Granting Petition for Writ of Certiorari quashes Lee County, Fla., Res. No. Z-23-035 (2024).", + "source": "Order.docx at 1. \"the petition for writ of certiorari is hereby GRANTED and the rezoning is QUASHED for the reasons discussed below.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that 1) outlines the Order and case history.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_order_granting_petition_for_writ_of_cert", + "original_index": 1, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_circuit_court_found_that", + "description": "States in the first assignment that the circuit court found that the Petitioners had standing to bring the petition based on proximity of the Petitioners' property to the proposed facility.", + "source": "Order.docx at 2. \"The court finds that Petitioners have standing to bring this petition for writ of certiorari based on their proximity of Petitioners' property.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that 1) outlines the Order and case history.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_circuit_court_found_that_the_petitioners", + "original_index": 2, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_circuit_court_found_th_2", + "description": "States in the first assignment that the circuit court found that the Lee County Board of County Commissioners \"improperly departed from the record created at the quasi-judicial hearings held below.\"", + "source": "Order.docx at 2. \"[t]he Lee County Board of County Commissioners (\"BOCC\") improperly departed from the record created at the quasi-judicial hearings held below.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that 1) outlines the Order and case history.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_circuit_court_found_that_the_lee_county", + "original_index": 3, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_circuit_court_found_th_3", + "description": "States in the first assignment that the circuit court found that Lee County's conduct \"created prejudice and bias\" surrounding the rezoning.", + "source": "Order.docx at 3. \"Lee county further prejudiced the quasi-judicial process surrounding the quasi-judicial hearing required for rezoning for this wastewater facility by its conduct which predetermined, or at very least created prejudice and bias, the decision to approve this quasi-judicial rezoning.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that 1) outlines the Order and case history.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_circuit_court_found_that_lee_county_s_co", + "original_index": 4, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_circuit_court_found_th_4", + "description": "States in the first assignment that the circuit court found that certain Federal Aviation Administration regulations \"were not fully considered below.\"", + "source": "Order.docx at 5. \"The decision below violated the essential requirements of law contained in the substantive provisions of the Land Development Code (LDC), adopting by reference \"protective\" regulatory guidance such as issued by the FAA regulating Land Use and Compatibility Advisories that were not fully considered below.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that 1) outlines the Order and case history.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_circuit_court_found_that_certain_federal", + "original_index": 5, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "mentions_in_the_first_assignment_that_the_county_s_prior_rezonin", + "description": "Mentions in the first assignment that the county's prior rezoning request in DCI2018-10023 was remanded by the Hearing Examiner to staff for further evaluation and analysis on August 13, 2019.", + "source": "Petition.docx at 17-18. \"LEE COUNTY planner Dirk Danley read into the record the August \n13, 2019 Remand (Tr5 p.2-3): \nFollowing the coordination between the applicant and staff we jointly request that DCI2018-10023 be remanded back to the staff for further evaluation and analysis to include public outreach sessions to address the concerns presented by the public participants during hearing pursuant to comprehensive plan amendments for the proposed public facility and the protection of environmental resources, evaluation and development for a more detailed site plan and to ensure that all alternatives have been fully reviewed and analyzed. The case will be re-analyzed, and future hearings will be noticed in compliance with the Land Development Code and Administrative Code. \"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that 1) outlines the Order and case history.\u201d", + "metadata": { + "review_flag": false, + "original_name": "mentions_in_the_first_assignment_that_the_county_s_prior_rezoning_request_in_dci", + "original_index": 6, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_under_lee_county_fla_admin_c", + "description": "States in the first assignment that under Lee County, Fla. Admin. Code \u00a7 2-6, 4.1 B. (2025), DCI2018-10023 was considered withdrawn on February 13, 2020.", + "source": "Lee County, Fla. Admin. Code \u00a7 2-6, 4.1 B. (2025); https://www.leegov.com/bocc/Administrative%20Codes/AC-2-6.pdf\n\"If the six month deadline is not met because of action or inaction of the Applicant/Appellant, the\napplication/appeal will be considered withdrawn.\"\nRemand occurred on August 13, 2029, and six months after that is February 13, 2020.", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that 1) outlines the Order and case history.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_under_lee_county_fla_admin_code_2_6_4_1_b_20", + "original_index": 7, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_dci2018_10023_remained_activ", + "description": "States in the first assignment that DCI2018-10023 remained active until September 13, 2023.", + "source": "Petition.docx at 19. \"Procedurally, the 2019 zoning case was left open until September 13, 2023.\" This is incorrect because under Lee County Administrative Code 2-6, sec. 4.1 B., the case was considered withdrawn for not meeting the 6 month remand hearing deadline.", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that 1) outlines the Order and case history.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_dci2018_10023_remained_active_until_septembe", + "original_index": 8, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": -15.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "mentions_in_the_first_assignment_that_the_subject_property_was_p", + "description": "Mentions in the first assignment that the subject property was placed into the Public Facilities future land use category of the Lee County Comprehensive Plan pursuant to Lee County, Fla. Ordinance 23-28 (2023).", + "source": "Lee County Fla. Ordinance 23-28 (2023); https://results.leegov.com/Home/DownloadFile/KT0000348490\n\"WHEREAS , the Board held a public hearing for the adoption of the proposed amendment on October 18 , 2023. At that hearing , the Board approved a motion to adopt proposed amendment CPA2023-00003 pertaining to Southeast Advanced Water\nReclamation Facility, amending Map 1-A of the Lee Plan , the Future Land Use Map. \"\nThe future land use category dictates permissible zoning districts, which dictate permitted uses.", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that 1) outlines the Order and case history.\u201d", + "metadata": { + "review_flag": false, + "original_name": "mentions_in_the_first_assignment_that_the_subject_property_was_placed_into_the_p", + "original_index": 9, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_effect_of_the_order_gran", + "description": "States in the first assignment that the effect of the Order Granting Writ of Certiorari is that the Board's decision is overturned.", + "source": "Florida law is unequivocal that when a circuit court finds error in a local government\u2019s quasi-judicial land use decision, its power is limited to quashing the decision and remanding the matter \u201cas if no order had been entered.\u201d See Broward County v. G.B.V. Int\u2019l, Ltd., 787 So. 2d 838, 845 (Fla. 2001) (\u201cWhen a circuit court grants certiorari relief, it quashes the order and leaves the matter pending before the lower tribunal as if no order had been entered.\u201d).\nhttps://caselaw.findlaw.com/court/fl-supreme-court/1495364.html#:~:text=When,judgment,-%2E", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .2) explains the implications of the Order.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_effect_of_the_order_granting_writ_of_cer", + "original_index": 10, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": -10.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_county_must_stop_constru", + "description": "States in the first assignment that the county must stop construction activities as a result of the Order Granting Writ of Certiorari.", + "source": "LCU Project.pdf at 1 shows that construction has started.\n\"Construction of the Southeast Advanced Water Reclamation Facility started on October 6, 2025.\"\nInjunctive relief is not an available remedy in a writ of certiorari of a quasi-judicial decision. See City of Fort Pierce v. Dickerson, 588 So.2d 1080, 1082 (Fla. 4th DCA 1991). https://www.casemine.com/judgement/us/59148822add7b049344ef125#:~:text=Since,injunction \n\"Since review of the resolution should have been by certiorari, the trial court was without jurisdiction to entertain a complaint for declaratory and injunctive relief and should not have granted the Dickersons' motion for a temporary injunction.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .2) explains the implications of the Order.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_county_must_stop_construction_activities", + "original_index": 11, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": -20.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_exclusive_method_of_revi", + "description": "States in the first assignment that the exclusive method of review of a quasi-judicial decision is by petition for writ of certiorari under Fla. R. App. P. 9.100(c) (2025) within 30 days of the written decision.", + "source": "Fla. R. App. P. 9.100(c) (2025); https://rules.floridaappellate.com/rule-9-100/#:~:text=Petitions,by%20certiorari\n\"Petitions for Certiorari; Review of NonFinal Agency Action; Review of Prisoner Disciplinary Action. The following shall be filed within 30 days of rendition of the order to be reviewed:\n\n(1) a petition for certiorari;\n\n(2) a petition to review quasi-judicial action of agencies, boards, and commissions of local government, which action is not directly appealable under any other provision of general law but may be subject to review by certiorari;\"\nSee City of Fort Pierce v. Dickerson, 588 So.2d 1080, 1082 (Fla. 4th DCA 1991).\nhttps://www.casemine.com/judgement/us/59148822add7b049344ef125#:~:text=Thus,relief\n\"Thus, we conclude that the resolution by the Ft. Pierce City Commission was quasi-judicial. Consequently, we agree with Ft. Pierce's assertion that since the resolution was a quasi-judicial decision rendered by the Commission, it was reviewable only by petition for writ of certiorari, and not by a complaint for declaratory and injunctive relief.\"", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .2) explains the implications of the Order.\u201d This is important in responding to the prompt question about implications of the order because it explains why injunctive relief is not available in a writ of certiorari of a quasi-judicial decision.", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_exclusive_method_of_review_of_a_quasi_ju", + "original_index": 12, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 15.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_exclusive_method_of_chal", + "description": "States in the first assignment that the exclusive method of challenging the issuance of a development order that materially alters the use or density or intensity of use on a particular piece of property is by filing a petition for writ of certiorari under Fla. Stat. \u00a7 163.3215(4) (2025) within 30 days of rendition of the development order.", + "source": "Fla. Stat. 163.3215(4) (2025); https://www.leg.state.fl.us/Statutes/index.cfm?App_mode=Display_Statute&URL=0100-0199/0163/Sections/0163.3215.html#:~:text=the%20sole,for%20certiorari\n\"the sole method by which an aggrieved and adversely affected party may challenge any decision of local government granting or denying an application for a development order, as defined in s. 163.3164, which materially alters the use or density or intensity of use on a particular piece of property, is by an appeal filed by a petition for writ of certiorari filed in circuit court no later than 30 days following rendition of a development order or other written decision of the local government, or when all local administrative appeals, if any, are exhausted, whichever occurs later. An action for injunctive or other relief may be joined with the petition for certiorari.\"\nA challenge to issuance of a development order, which is an executive function, is a separate cause of action from appeal of a quasi-judicial decision.", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .2) explains the implications of the Order.\u201d This is crucial because challenging a development order is the sole method to seek injunctive relief under Fla. Stat. 163.3215(4).", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_exclusive_method_of_challenging_the_issu", + "original_index": 13, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_under_fla_stat_163_3167_10_2", + "description": "States in the first assignment that under Fla. Stat \u00a7 163.3167(10) (2025) the development order issued for the project may not be invalidated by a subsequent judicial determination because the timeframe for filing an appeal of the development order has expired.", + "source": "Fla. Stat 163.3167(10) (2025); https://www.leg.state.fl.us/statutes/index.cfm?App_mode=Display_Statute&URL=0100-0199/0163/Sections/0163.3167.html#:~:text=If,standards\n\"If a local government grants a development order pursuant to its adopted land development regulations and the order is not the subject of a pending appeal and the timeframe for filing an appeal has expired, the development order may not be invalidated by a subsequent judicial determination that such land development regulations, or any portion thereof that is relevant to the development order, are invalid because of a deficiency in the approval standards\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .2) explains the implications of the Order.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_under_fla_stat_163_3167_10_2025_the_developm", + "original_index": 14, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_petitioners_may_file_a_s", + "description": "States in the first assignment that the Petitioners may file a separate cause of action for injunction to stop construction activities.", + "source": "See City of Fort Pierce v. Dickerson, 588 So.2d 1080, 1082 (Fla. 4th DCA 1991). https://www.casemine.com/judgement/us/59148822add7b049344ef125#:~:text=Since,injunction \n\"Since review of the resolution should have been by certiorari, the trial court was without jurisdiction to entertain a complaint for declaratory and injunctive relief and should not have granted the Dickersons' motion for a temporary injunction.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .2) explains the implications of the Order.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_petitioners_may_file_a_separate_cause_of", + "original_index": 15, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": -15.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_county_could_appeal_the", + "description": "States in the first assignment that the county could appeal the Order Granting Writ of Certiorari to the Sixth District Court of Appeals pursuant to Fla. R. App. P. 9.030(b)(2)(B).", + "source": "Florida Rule of Appellate Procedure 9.030(b)(2)(B); https://rules.floridaappellate.com/rule-9-030/#:~:text=b%29-,Jurisdiction,capacity\n\"Jurisdiction of District Courts of Appeal.\n\"b) Jurisdiction of District Courts of Appeal.\n. . .\n(2) Certiorari Jurisdiction.8 The certiorari jurisdiction of district courts of appeal may be sought to review:\n(A) nonfinal orders of lower tribunals other than as prescribed by rule 9.130; or\n(B) final orders of circuit courts acting in their review capacity.\"\nSee also Map of Florida\u2019s Court Jurisdictions, available at https://flcourts-media.flcourts.gov/content/download/426177/file/ar-17-18-map-of-floridas-court-jurisdictions.pdf (last accessed Mar. 25, 2026).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .3) identifies options and available actions for the county.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_county_could_appeal_the_order_granting_w", + "original_index": 16, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_county_could_remand_the", + "description": "States in the first assignment that the county could remand the case back to the Hearing Examiner for an evidentiary hearing to address the deficiencies identified in the Order Granting Petition for Writ of Certiorari under Lee County Fla. Land Development Code \u00a7 34-83(a)(6) (2025).", + "source": "Lee County Fla. Land Development Code \u00a7 34-83(a)(6) (2025); https://library.municode.com/fl/lee_county/codes/land_development_code?nodeId=LADECO_CH34ZO_ARTIIAD_DIV2BOCOCO_S34-83FUAU#:~:text=The%20Board%20may%20remand%20a%20case%20back%20to%20the%20Hearing%20Examiner%20for%20further%20review%20of%20specific%20issues%2E%20The%20scope%20of%20the%20remanded%20hearing%20will%20be%20limited%20to%20the%20specific%20issues%20identified%20by%20the%20Board\n\"The Board may remand a case back to the Hearing Examiner for further review of specific issues. The scope of the remanded hearing will be limited to the specific issues identified by the Board.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .3) identifies options and available actions for the county.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_county_could_remand_the_case_back_to_the", + "original_index": 17, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_county_could_file_a_new", + "description": "States in the first assignment that the County could file a new application for rezoning.", + "source": "The Lee County Department of Community Development website has a link to an application for \"Continuance, Deferral, or Withdrawal\" which can be filed at any time by the county; https://www.leegov.com/dcd/zoning/apps#:~:text=Continuance%2C%20Deferral%2C%20OR%20Withdrawal,-%E2%80%8B", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .3) identifies options and available actions for the county.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_county_could_file_a_new_application_for", + "original_index": 18, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_county_could_voluntarily", + "description": "States in the first assignment that the County could voluntarily cease construction activities pending resolution of the challenge.", + "source": "LCU Project.pdf at 1. Construction has started, but could be stopped at the direction of the Board, though the costs would be extremely high.", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .3) identifies options and available actions for the county.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_county_could_voluntarily_cease_construct", + "original_index": 19, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_county_could_take_the_po", + "description": "States in the first assignment that the County could take the position that the rezoning is not necessary because the county is not bound by its local zoning laws in carrying out a governmental function.", + "source": "See Sandra G. Smith, Immunity of State and State Related Activities from Local Municipal Zoning Regulations: Florida Focus, 28 Fla. L. Rev. 800 (1967).\nAvailable at: https://scholarship.law.ufl.edu/flr/vol28/iss3/9 \nhttps://scholarship.law.ufl.edu/cgi/viewcontent.cgi?article=2881&context=flr\n\"The Fourth District Court of Appeal relied\non Nichols for the premise that in the performance of a governmental activity the county should not be subject to its own zoning restrictions. 2 In a 1978\ndecision Dade County was challenged by private property owners when it attempted to violate its own zoning restrictions by building a jail facility on\nproperty reserved for another use under a comprehensive zoning ordinance. 28\nThe Third District Court of Appeal recognized a right under common law and under Florida law for \"a governmental entity to place a governmental\nfacility without regard to a comprehensive zoning ordinance or its procedures.\"\nThe article quotes Metropolitan Dade County v. Parkway Towers Condominium Ass'n, 281 So. 2d 68\n(Fla. 3d DCA 1973), a 3rd DCA case establishing immunity from zoning for governmental purposes. The case is not found publicly available, however the FL Supreme Court accepted, but then discharged), a petition for writ. Note that the FL Supreme Court expressed a \"prospective opinion\" that local governments \"should\" go through rezonings if not in compliance, this is dicta and not binding as the court upheld the district court's decision on immunity. \nParkway Towers Con. Ass'n v. Metropolitan Dade Cnty., 295 So.2d 295 (Fla. 1974); https://law.justia.com/cases/florida/supreme-court/1974/44260-0.html#:~:text=Although,ordinances,-%2E\n\"Although we now consider our issuance of the writ of certiorari to have been improvident in this case, which results in our discharge thereof, it is nevertheless our view prospectively that zoning variations to accommodate county or municipal facility purposes should either have been anticipated in zoning ordinances before construction or operation of such facilities is commenced *296 or, if this has not been done, construction should not be undertaken thereof until after due modification or change therefor is made in existing zoning ordinances.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .3) identifies options and available actions for the county.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_county_could_take_the_position_that_the", + "original_index": 20, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_county_could_negotiate_f", + "description": "States in the first assignment that the County could negotiate for additional conditions protecting wildlife that address Petitioners' concerns.", + "source": "Petitioners' concerns are outlined in Petition.docx at pages 3-13. These include concerns about protection of wild life.", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .3) identifies options and available actions for the county.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_county_could_negotiate_for_additional_co", + "original_index": 21, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_county_could_negotiate_2", + "description": "States in the first assignment that the County could negotiate for additional conditions protecting water quality that address Petitioners' concerns.", + "source": "Petitioners' concerns are outlined in Petition.docx at pages 3-13. These include concerns about protection of water quality.", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .3) identifies options and available actions for the county.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_county_could_negotiate_for_additional_co_2", + "original_index": 22, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_county_should_file_a_tim", + "description": "States in the first assignment that the County should file a timely appeal with the 6th District Court of Appeals.", + "source": "Because the Order contains reversible errors, and because an appeal can be pursued parallel to a remand, this is the best recommendation.\nFlorida Rule of Appellate Procedure 9.030(b)(2)(B); https://rules.floridaappellate.com/rule-9-030/#:~:text=b%29-,Jurisdiction,capacity\n\"Jurisdiction of District Courts of Appeal.\n\"b) Jurisdiction of District Courts of Appeal.\n. . .\n(2) Certiorari Jurisdiction.8 The certiorari jurisdiction of district courts of appeal may be sought to review:\n(A) nonfinal orders of lower tribunals other than as prescribed by rule 9.130; or\n(B) final orders of circuit courts acting in their review capacity.\"\nSee also Map of Florida\u2019s Court Jurisdictions, available at https://flcourts-media.flcourts.gov/content/download/426177/file/ar-17-18-map-of-floridas-court-jurisdictions.pdf (last accessed Mar. 25, 2026).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .4) recommends a legal course of action to the Board.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_county_should_file_a_timely_appeal_with", + "original_index": 23, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 20.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_county_should_remand_the", + "description": "States in the first assignment that the County should remand the case to the Hearing Examiner to address the deficiencies identified in the Order Granting Writ of Certiorari while an appeal is pending.", + "source": "Because the Order contains reversible errors, and because an appeal can be pursued parallel to a remand, this is the best recommendation.\nLee County Fla. Land Development Code \u00a7 34-83(a)(6) (2025); https://library.municode.com/fl/lee_county/codes/land_development_code?nodeId=LADECO_CH34ZO_ARTIIAD_DIV2BOCOCO_S34-83FUAU#:~:text=The%20Board%20may%20remand%20a%20case%20back%20to%20the%20Hearing%20Examiner%20for%20further%20review%20of%20specific%20issues%2E%20The%20scope%20of%20the%20remanded%20hearing%20will%20be%20limited%20to%20the%20specific%20issues%20identified%20by%20the%20Board\n\"The Board may remand a case back to the Hearing Examiner for further review of specific issues. The scope of the remanded hearing will be limited to the specific issues identified by the Board.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .4) recommends a legal course of action to the Board.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_county_should_remand_the_case_to_the_hea", + "original_index": 24, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": 20.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_first_assignment_that_the_county_should_cease_cons", + "description": "States in the first assignment that the County should cease construction activities at the subject property.", + "source": "LCU Project.pdf at 1 shows that construction has started, which means the county has spent time and money on design, permitting, procurement of contractors, etc. The facility is also necessary to serve increased demand for water and sewer service caused by population growth and has been planned since 2010 (LCU Project.pdf at 4.)\nIn a similar case, the FL Supreme Court declined to delay construction of a public project based on zoning.\nSee Parkway Towers Con. Ass'n v. Metropolitan Dade Cty., 295 So.2d 295 (Fla. 1974); https://law.justia.com/cases/florida/supreme-court/1974/44260-0.html#:~:text=This%20being,result\n\"In this case it appears that on at least two occasions public hearings were held by the Metro County Commission on the question whether the construction of the subject holding facility for prisoners and the work release facility should go forward in the absence of a waiver therefor in the zoning ordinance and in each instance it was agreed by the Commission the construction should proceed. This being so, we feel no useful or practical purpose would be served in interrupting and delaying the construction until a zoning change is effected retroactively to accommodate the Commission's expressly resolved purpose when considered in connection with the fact that no direct conflict of decisions appears. To interrupt the construction now would cause needless expense and damage with no prospect or likelihood that the Commission would reach a different final result.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReview only these documents and draft a legal memorandum to the Board of County Commissioners that . . .4) recommends a legal course of action to the Board.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_first_assignment_that_the_county_should_cease_construction_activit", + "original_index": 25, + "classifier_reason": "Names first assignment", + "classifier_confidence": "high" + }, + "score": -30.0, + "polarity": "negative", + "raw_weight": 1.0 + } + ] +} diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/m1_judge_panel.json b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/m1_judge_panel.json new file mode 100644 index 0000000000000000000000000000000000000000..a8041f6781a899f9083fe4a1a95f51bc78d35601 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/m1_judge_panel.json @@ -0,0 +1,21 @@ +{ + "mode": "panel", + "max_concurrent_llm": 12, + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ] +} diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/m1_rewardkit_accounting.py b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/m1_rewardkit_accounting.py new file mode 100644 index 0000000000000000000000000000000000000000..406dc5e7c675b222d94514e71bf5fad6ae141d8f --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/m1_rewardkit_accounting.py @@ -0,0 +1,490 @@ +import asyncio +import json +import math +import os +from pathlib import Path +import random +import sys +import time + +class JudgeReceiptError(OSError): + pass +_LLM_ROUTES = frozenset({'vertex', 'anthropic fallback', 'aistudio', 'direct'}) +_LLM_ROUTE_HEADERS = ('x-m1-llm-route', 'llm_provider-x-m1-llm-route') + +def _canonical_llm_route(value): + return value if isinstance(value, str) and value in _LLM_ROUTES else None + +def _llm_route_from_headers(headers): + if not isinstance(headers, dict): + return None + folded = {str(key).lower(): value for key, value in headers.items()} + for name in _LLM_ROUTE_HEADERS: + route = _canonical_llm_route(folded.get(name)) + if route is not None: + return route + return None + +def _llm_route_from_response(response): + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + route = _llm_route_from_headers(headers) + if route is not None: + return route + return _llm_route_from_headers(getattr(response, 'headers', None)) + +def _token_field_status(values, key): + if not isinstance(values, dict) or key not in values: + return 'missing' + value = values[key] + if value is None: + return 'null' + return 'valid' if type(value) is int and value >= 0 else 'invalid' + +def _gemini_capture(kwargs, model): + if not model.startswith('gemini/') or kwargs.get('stream') or kwargs.get('tools') or kwargs.get('functions'): + return (kwargs, None) + from litellm.integrations.custom_logger import CustomLogger + from urllib.parse import urlsplit + + class Capture(CustomLogger): + evidence = None + prompt_status = 'not_observed' + llm_route = None + + def log_post_api_call(self, kwargs, response_obj, start_time, end_time): + self.evidence = None + self.prompt_status = 'not_observed' + try: + params = kwargs.get('litellm_params') or {} + route = urlsplit(params.get('api_base') or '') + bare = model.removeprefix('gemini/') + gemini = params.get('custom_llm_provider') == 'gemini' + ai_studio = gemini and route.hostname == 'generativelanguage.googleapis.com' and (route.path in {'/' + version + '/models/' + bare + ':generateContent' for version in ('v1alpha', 'v1beta')}) + broker = urlsplit(os.environ.get('GEMINI_API_BASE') or '') + brokered = gemini and bool(broker.netloc) and (route.netloc == broker.netloc) and (broker.path.rstrip('/').rsplit('/', 1)[-1] in ('v1alpha', 'v1beta')) and (route.path == broker.path.rstrip('/') + '/models/' + bare + ':generateContent') + vertex = params.get('custom_llm_provider') == 'vertex_ai' and route.hostname == 'aiplatform.googleapis.com' and route.path.startswith('/v1/projects/') and route.path.endswith('/locations/global/publishers/google/models/' + bare + ':generateContent') + if route.scheme != 'https' or not (ai_studio or brokered or vertex) or kwargs.get('stream'): + return + self.llm_route = 'vertex' if vertex else 'aistudio' if ai_studio else None + raw = kwargs.get('original_response') + raw = json.loads(raw) if isinstance(raw, str) else raw + if not isinstance(raw, dict): + return + candidates = raw.get('candidates') + if not isinstance(candidates, list) or not candidates or any((not isinstance(c, dict) or not c.get('finishReason') for c in candidates)) or (not isinstance(raw.get('modelVersion'), str)) or (not raw['modelVersion']): + return + usage = raw.get('usageMetadata') + self.prompt_status = _token_field_status(usage, 'promptTokenCount') + if not isinstance(usage, dict): + return + fields = ('promptTokenCount', 'candidatesTokenCount', 'thoughtsTokenCount', 'cachedContentTokenCount', 'totalTokenCount', 'toolUsePromptTokenCount') + counts = {key: usage.get(key, 0) for key in fields} + if not {'promptTokenCount', 'totalTokenCount'} <= usage.keys() or any((type(n) is not int or n < 0 for n in counts.values())) or counts['toolUsePromptTokenCount'] != 0 or (counts['cachedContentTokenCount'] > counts['promptTokenCount']) or (counts['totalTokenCount'] != counts['promptTokenCount'] + counts['candidatesTokenCount'] + counts['thoughtsTokenCount']): + return + self.evidence = {'protocol': 'gemini-generate-content-' + ('vertex-v1' if vertex else route.path.split('/')[-3]), 'model_version': raw['modelVersion'], 'usage_metadata': {key: usage[key] for key in fields if key in usage}, 'defaulted_fields': [key for key in fields if key not in usage]} + except (TypeError, ValueError, AttributeError): + return + capture = Capture() + return ({**kwargs, 'callbacks': [*(kwargs.get('callbacks') or []), capture]}, capture) + +def _record_judge_usage(response, model: str, *, target: Path | None=None, native_usage: dict | None=None, native_prompt_status: str | None=None, llm_route: str | None=None) -> None: + import fcntl + from datetime import datetime, timezone + data = response.model_dump() if hasattr(response, 'model_dump') else response + usage = data.get('usage') if isinstance(data, dict) else None + granularity = data.get('usage_granularity') if isinstance(data, dict) else None + if not isinstance(usage, dict): + usage = {} + granularity = 'missing_provider_receipt' + prompt, completion = (usage.get('prompt_tokens'), usage.get('completion_tokens')) + native_fresh = usage.get('input_uncached_tokens') + prompt = prompt if type(prompt) is int and prompt >= 0 else None + native_fresh = native_fresh if type(native_fresh) is int and native_fresh >= 0 else None + if type(completion) is not int or completion < 0 or (prompt is None and native_fresh is None): + completion = completion if type(completion) is int and completion >= 0 else 0 + granularity = granularity or 'invalid_provider_receipt' + details = usage.get('prompt_tokens_details') + if details is not None and (not isinstance(details, dict)): + granularity = 'invalid_provider_receipt' + details = details if isinstance(details, dict) else {} + cached = details.get('cached_tokens') + if native_usage is not None: + native = native_usage['usage_metadata'] + native_output = native.get('candidatesTokenCount', 0) + native.get('thoughtsTokenCount', 0) + if prompt == native['promptTokenCount'] and completion == native_output: + cached = native.get('cachedContentTokenCount', 0) + else: + native_usage = None + written = next((value for value in (usage.get('input_cache_write_tokens'), usage.get('cache_creation_input_tokens'), details.get('cache_creation_tokens'), details.get('cache_write_tokens')) if value is not None), None) + invalid = any((value is not None and (type(value) is not int or value < 0) for value in (cached, written))) + cached = cached if type(cached) is int and cached >= 0 else None + written = written if type(written) is int and written >= 0 else None + fresh = native_fresh + if fresh is None and prompt is not None and (cached is not None) and (written is not None): + fresh = prompt - cached - written + if fresh is not None and (fresh < 0 or (prompt is not None and cached is not None and (written is not None) and (fresh + cached + written != prompt))): + invalid, fresh = (True, None) + provider, _, slug = model.partition('/') + event: dict = {'type': 'step_finish', 'part': {'providerID': provider if slug else 'openai', 'modelID': slug or model, 'tokens': {'input': fresh, 'output': completion, 'cache': {'read': cached, 'write': written}}}} + field_status = {'prompt_tokens': _token_field_status(usage, 'prompt_tokens'), 'completion_tokens': _token_field_status(usage, 'completion_tokens'), 'input_uncached_tokens': _token_field_status(usage, 'input_uncached_tokens')} + field_status['native_prompt_token_count'] = native_prompt_status if native_prompt_status in {'missing', 'null', 'invalid', 'valid', 'not_observed'} else 'unsupported' + part: dict = event['part'] + part['usage_field_status'] = field_status + if native_usage is not None: + event['part']['native_usage'] = native_usage + event['part']['token_categories_provenance'] = 'explicit_presence_v1' + if fresh is None and prompt is not None: + event['part']['prompt_tokens_inclusive'] = prompt + if invalid or any((value is None for value in (fresh, cached, written))): + granularity = granularity if granularity not in (None, 'request') else 'invalid_provider_receipt' if invalid else 'incomplete_token_categories' + if granularity: + event['part']['usage_granularity'] = granularity + if provider == 'openrouter': + cost = usage.get('cost') + if cost is None: + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + if isinstance(headers, dict): + cost = headers.get('llm_provider-x-litellm-response-cost') + if isinstance(cost, (int, float)) and (not isinstance(cost, bool)) and math.isfinite(cost) and (cost >= 0): + event['part']['cost'] = cost + data = data if isinstance(data, dict) else {} + if isinstance(data.get('id'), str) and data['id']: + event['part']['provider_request_id'] = data['id'] + for key in ('service_tier', 'cache_ttl'): + if data.get(key): + event['part'][key] = data[key] + route = _llm_route_from_response(response) or _canonical_llm_route(llm_route) + if route is not None: + event['part']['llm_route'] = route + created = data.get('created') + stamp = datetime.now(timezone.utc) + try: + if isinstance(created, str): + parsed = datetime.fromisoformat(created.replace('Z', '+00:00')) + if parsed.tzinfo is not None: + stamp = parsed + elif isinstance(created, (int, float)) and (not isinstance(created, bool)) and math.isfinite(created): + stamp = datetime.fromtimestamp(created, timezone.utc) + except (ValueError, OverflowError, OSError): + pass + pair = json.dumps({'type': 'step_start', 'timestamp': stamp.isoformat()}) + '\n' + pair += json.dumps(event) + '\n' + try: + receipt_path = target or Path(os.environ.get('M1_JUDGE_USAGE_PATH', '/logs/verifier/judge-trajectory.jsonl')) + receipt_path.parent.mkdir(parents=True, exist_ok=True) + with receipt_path.open('a') as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + handle.write(pair) + handle.flush() + os.fsync(handle.fileno()) + except OSError as exc: + if target is not None: + raise JudgeReceiptError(f'judge receipt write failed: {exc}') from exc + print(f'judge accounting: write failed ({type(exc).__name__})', file=sys.stderr) + +def openrouter_judge_pins() -> dict[str, dict]: + raw = os.environ.get('M1_OPENROUTER_JUDGE_PROVIDER_PINS', '').strip() + if not raw: + return {} + try: + pins = json.loads(raw) + except json.JSONDecodeError: + print('judge provider pins: invalid JSON in M1_OPENROUTER_JUDGE_PROVIDER_PINS', file=sys.stderr) + return {} + return {model: pin for model, pin in pins.items() if isinstance(pin, dict) and pin.get('order')} if isinstance(pins, dict) else {} + +def apply_judge_provider_pin(kwargs: dict, pins: dict[str, dict]) -> dict: + model = kwargs.get('model') + pin = pins.get(model) if isinstance(model, str) else None + if pin is None: + return kwargs + extra_body = dict(kwargs.get('extra_body') or {}) + provider = dict(extra_body.get('provider') or {}) + provider['order'] = list(pin['order']) + if pin.get('allow_fallbacks') is False: + provider['allow_fallbacks'] = False + if pin.get('zdr'): + provider['zdr'] = True + extra_body['provider'] = provider + return {**kwargs, 'extra_body': extra_body} +_TRANSIENT_ERROR_NAMES = ('RateLimitError', 'ServiceUnavailableError', 'InternalServerError', 'BadGatewayError', 'APIConnectionError') +_RETRYABLE_STATUS_CODES = frozenset({408, 409, 425, 429, 500, 502, 503, 504}) +_AUTH_ERROR_NAMES = ('AuthenticationError', 'PermissionDeniedError') +_AUTH_STATUS_CODES = frozenset({401, 403}) +_AUTH_RETRIES = 4 +_DEFAULT_TRANSIENT_RETRIES = 6 +_MAX_TRANSIENT_RETRIES = 20 +_MAX_RETRY_DELAY_SECONDS = 60.0 +_DEFAULT_EMPTY_RESPONSE_RETRIES = 3 +_DEFAULT_RETRY_BUDGET_SECONDS = 900.0 +_MAX_RETRY_BUDGET_SECONDS = 86400.0 + +def transient_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_TRANSIENT_RETRIES', '').strip() + if not raw: + return _DEFAULT_TRANSIENT_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_TRANSIENT_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_TRANSIENT_RETRIES + +def empty_response_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_EMPTY_RESPONSE_RETRIES', '').strip() + if not raw: + return _DEFAULT_EMPTY_RESPONSE_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_EMPTY_RESPONSE_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_EMPTY_RESPONSE_RETRIES + +def retry_budget_seconds() -> float: + raw = os.environ.get('M1_JUDGE_RETRY_BUDGET_SECONDS', '').strip() + if not raw: + return _DEFAULT_RETRY_BUDGET_SECONDS + try: + value = float(raw) + except ValueError: + value = math.nan + if not math.isfinite(value) or value < 0: + print('judge retries: invalid M1_JUDGE_RETRY_BUDGET_SECONDS, using the default', file=sys.stderr) + return _DEFAULT_RETRY_BUDGET_SECONDS + return min(value, _MAX_RETRY_BUDGET_SECONDS) + +def _within_budget(deadline: float, delay: float, model) -> bool: + remaining = deadline - time.monotonic() + if delay <= remaining: + return True + print(f'judge call retry budget spent: {model} would wait {delay:.1f}s with {max(remaining, 0.0):.1f}s left of M1_JUDGE_RETRY_BUDGET_SECONDS, failing now', file=sys.stderr) + return False + +def is_empty_verdict(response) -> bool: + data = response.model_dump() if hasattr(response, 'model_dump') else response + if not isinstance(data, dict): + return False + choices = data.get('choices') + if not isinstance(choices, list) or not choices: + return True + first = choices[0] + message = first.get('message') if isinstance(first, dict) else None + if not isinstance(message, dict): + return True + if message.get('tool_calls') or message.get('function_call'): + return False + content = message.get('content') + if isinstance(content, list): + content = ''.join((part.get('text') or '' for part in content if isinstance(part, dict))) + return not (isinstance(content, str) and content.strip()) + +def _matches(exc: BaseException, litellm, names: tuple[str, ...], statuses: frozenset[int]) -> bool: + classes = tuple((cls for cls in (getattr(litellm, name, None) for name in names) if isinstance(cls, type))) + if classes and isinstance(exc, classes): + return True + status = getattr(exc, 'status_code', None) + return type(status) is int and status in statuses + +def is_transient_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _TRANSIENT_ERROR_NAMES, _RETRYABLE_STATUS_CODES) + +def is_auth_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _AUTH_ERROR_NAMES, _AUTH_STATUS_CODES) + +def should_retry(exc: BaseException, litellm, attempt: int, limit: int) -> bool: + if attempt < limit and is_transient_error(exc, litellm): + return True + return attempt < min(limit, _AUTH_RETRIES) and is_auth_error(exc, litellm) + +def _retry_after_seconds(exc: BaseException) -> float | None: + headers = getattr(exc, 'headers', None) + if headers is None: + headers = getattr(getattr(exc, 'response', None), 'headers', None) + if headers is None: + return None + try: + raw = headers.get('retry-after') + if raw is None: + raw = headers.get('Retry-After') + value = float(raw) + except (AttributeError, TypeError, ValueError): + return None + return value if math.isfinite(value) and value >= 0 else None + +def retry_delay(exc: BaseException | None, attempt: int) -> float: + base = min(_MAX_RETRY_DELAY_SECONDS, 2.0 ** (attempt + 1)) + delay = base * (0.5 + random.random()) + retry_after = _retry_after_seconds(exc) if exc is not None else None + if retry_after is not None: + delay = max(delay, min(_MAX_RETRY_DELAY_SECONDS, retry_after)) + return delay + +def _note_retry(model, exc: BaseException, attempt: int, limit: int, delay: float) -> None: + status = getattr(exc, 'status_code', None) + print(f"judge call retry {attempt}/{limit}: {model} {type(exc).__name__} status={(status if type(status) is int else 'n/a')}, waiting {delay:.1f}s", file=sys.stderr) + +def _note_empty(model, response, attempt: int, limit: int, delay: float) -> None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + reason = None + if isinstance(data, dict) and isinstance(data.get('choices'), list) and data['choices']: + first = data['choices'][0] + reason = first.get('finish_reason') if isinstance(first, dict) else None + print(f'judge call retry {attempt}/{limit}: {model} empty verdict (finish_reason={reason}), waiting {delay:.1f}s', file=sys.stderr) + +def install(litellm, *, synchronous: bool=False) -> None: + pins = openrouter_judge_pins() + limit = transient_retry_limit() + empty_limit = empty_response_retry_limit() + deadline = time.monotonic() + retry_budget_seconds() + if synchronous: + original = litellm.completion + + def accounted(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = original(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + time.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + time.sleep(delay) + continue + return response + litellm.completion = accounted + return + original_async = litellm.acompletion + + async def accounted_async(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = await original_async(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + await asyncio.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + await asyncio.sleep(delay) + continue + return response + litellm.acompletion = accounted_async + +def record_agent_usage(attempt, *, model: str, provider: str) -> None: + records: dict[str, tuple[str, dict]] = {} + current_model = model + for filename in getattr(attempt, 'logs', []): + try: + with Path(filename).open() as stream: + for line in stream: + try: + event = json.loads(line) + except (ValueError, TypeError): + continue + if not isinstance(event, dict): + continue + message = event.get('message') or {} + if event.get('type') == 'assistant' and isinstance(message, dict) and isinstance(message.get('usage'), dict): + raw = message['usage'] + cached, written = (raw.get('cache_read_input_tokens'), raw.get('cache_creation_input_tokens')) + if all((type(value) is int and value >= 0 for value in (raw.get('input_tokens'), raw.get('output_tokens')))) and all((value is None or (type(value) is int and value >= 0) for value in (cached, written))): + receipt: dict = {'usage': {'input_uncached_tokens': raw['input_tokens'], 'prompt_tokens': raw['input_tokens'] + cached + written if cached is not None and written is not None else None, 'completion_tokens': raw['output_tokens'], 'prompt_tokens_details': {'cached_tokens': cached, 'cache_creation_tokens': written}}} + receipt['created'] = event.get('timestamp') + creation = raw.get('cache_creation') or {} + hour = creation.get('ephemeral_1h_input_tokens', 0) if isinstance(creation, dict) else 0 + if type(hour) is int and hour > 0: + if hour == written: + receipt['cache_ttl'] = '1h' + else: + receipt['usage_granularity'] = 'mixed_cache_ttl' + records[message.get('id') or json.dumps(raw, sort_keys=True)] = (message.get('model') or current_model, receipt) + payload = event.get('payload') or {} + if not isinstance(payload, dict): + continue + if event.get('type') == 'turn_context' and payload.get('model'): + current_model = payload['model'] + if event.get('type') == 'event_msg' and payload.get('type') == 'token_count': + info = payload.get('info') or {} + raw, total = (info.get('last_token_usage'), info.get('total_token_usage')) + if isinstance(raw, dict) and isinstance(total, dict) and all((type(raw.get(key)) is int and raw.get(key) >= 0 for key in ('input_tokens', 'output_tokens'))): + receipt = {'usage': {'prompt_tokens': raw.get('input_tokens'), 'input_uncached_tokens': raw.get('input_uncached_tokens'), 'input_cache_write_tokens': raw.get('input_cache_write_tokens'), 'completion_tokens': raw.get('output_tokens'), 'prompt_tokens_details': {'cached_tokens': raw.get('cached_input_tokens')}}} + receipt['created'] = event.get('timestamp') + records[json.dumps(total, sort_keys=True)] = (current_model, receipt) + except OSError: + continue + captured_input = captured_output = 0 + input_complete = True + for requested, receipt in records.values(): + requested = requested if '/' in requested else f'{provider}/{requested}' + _record_judge_usage(receipt, requested) + receipt_input = receipt['usage'].get('prompt_tokens') + if receipt_input is None: + input_complete = False + else: + captured_input += receipt_input + captured_output += receipt['usage'].get('completion_tokens') or 0 + total = getattr(attempt, 'usage', {}) or {} + if not records or (input_complete and total.get('input_tokens') != captured_input) or total.get('output_tokens') != captured_output: + _record_judge_usage({'usage': {'prompt_tokens': 0, 'completion_tokens': 0}, 'usage_granularity': 'incomplete_agent_receipts'}, model if '/' in model else f'{provider}/{model}') + +def install_rewardkit_agents() -> None: + import rewardkit.judges as judges + original = judges.get_agent + + def get_accounted_agent(judge, cwd=None): + backend = original(judge, cwd) + run = backend.run + + async def accounted_run(*args, **kwargs): + attempt = await run(*args, **kwargs) + record_agent_usage(attempt, model=judge.model or 'unknown', provider='anthropic' if judge.agent == 'claude-code' else 'openai') + return attempt + setattr(backend, 'run', accounted_run) + return backend + setattr(judges, 'get_agent', get_accounted_agent) +if __name__ == '__main__': + import litellm + if len(sys.argv) > 2 and sys.argv[1] == '--script': + import runpy + install(litellm, synchronous=True) + sys.argv = sys.argv[2:] + runpy.run_path(sys.argv[0], run_name='__main__') + else: + install(litellm) + install_rewardkit_agents() + if Path(__file__).with_name('m1_judge_panel.json').is_file(): + from m1_rewardkit_panel import install_panel + install_panel(Path(__file__).with_name('m1_judge_panel.json')) + if Path(__file__).with_name('m1_judge_jev.json').is_file(): + from m1_rewardkit_jev import install_jev + install_jev(Path(__file__).with_name('m1_judge_jev.json')) + from rewardkit.__main__ import main + main() diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/m1_rewardkit_panel.py b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/m1_rewardkit_panel.py new file mode 100644 index 0000000000000000000000000000000000000000..164cc2ae521cdd368c2e1749d7ed8fe09f4545eb --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/m1_rewardkit_panel.py @@ -0,0 +1,169 @@ +from __future__ import annotations +import asyncio +from contextvars import ContextVar +import json +import math +import os +import sys +from pathlib import Path +from typing import Any +import uuid +_request_audit: ContextVar[tuple[Path, list[str]] | None] = ContextVar('panel_request_audit', default=None) + +class PanelIncompleteError(RuntimeError): + pass + +def _audit_warning(exc: Exception, warnings: list[str]) -> None: + message = f'judge panel audit: diagnostic capture failed ({type(exc).__name__})' + if message not in warnings: + warnings.append(message) + print(message, file=sys.stderr) + +def _write_audit(path: Path, record: dict[str, Any], warnings: list[str], *, append: bool=False) -> None: + try: + text = json.dumps(record, allow_nan=False, default=str) + '\n' + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('a' if append else 'w') as stream: + stream.write(text) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + +def _binary(raw: Any) -> int: + if isinstance(raw, bool): + return int(raw) + if isinstance(raw, int | float) and math.isfinite(raw) and (raw in (0, 1)): + return int(raw) + if isinstance(raw, str): + value = raw.strip().lower() + if value in {'yes', 'true', '1'}: + return 1 + if value in {'no', 'false', '0'}: + return 0 + raise PanelIncompleteError('m1_judge_panel_incomplete: invalid binary vote') + +def validate_votes(scores: list[Any], criteria: list[Any]) -> None: + names = [criterion.name for criterion in criteria] + if len(set(names)) != len(names) or [score.name for score in scores] != names: + raise PanelIncompleteError('m1_judge_panel_incomplete: criterion membership mismatch') + for score, criterion in zip(scores, criteria, strict=True): + if score.error: + raise PanelIncompleteError('m1_judge_panel_incomplete: judge returned an error') + raw = _binary(score.raw) + expected = 1 - raw if criterion.negate else raw + if not math.isfinite(score.value) or score.value != expected: + raise PanelIncompleteError('m1_judge_panel_incomplete: inconsistent binary score') + +async def run_panel(judge: Any, criteria: list[Any], weights: list[float] | None, system_prompt: str | None, *, config: dict[str, Any], run_llm: Any, score_type: Any, audit_dir: Path) -> tuple[list[Any], str, list[str]]: + from rewardkit.models import Binary + if not criteria or any((not isinstance(criterion.output_format, Binary) for criterion in criteria)): + raise ValueError('panel majority voting requires nonempty binary criteria') + group_dir = audit_dir / uuid.uuid4().hex + warnings_out: list[str] = [] + + async def member_call(index: int, member: dict[str, Any]): + member_judge = judge.model_copy(update=member) + evidence: dict[str, Any] = {'member': index + 1, 'judge': member, 'criteria': [criterion.name for criterion in criteria], 'status': 'started'} + path = group_dir / f'judge-{index + 1}.json' + _write_audit(path, evidence, warnings_out) + token = _request_audit.set((group_dir / f'judge-{index + 1}-requests.jsonl', warnings_out)) + try: + scores, output, warnings = await run_llm(member_judge, criteria, weights, system_prompt) + evidence.update(output=output, warnings=warnings) + validate_votes(scores, criteria) + evidence['scores'] = [score.to_dict() for score in scores] + evidence['status'] = 'completed' + return (scores, output, warnings) + except BaseException as exc: + evidence.update(status='failed', error_class=type(exc).__name__) + if isinstance(exc, PanelIncompleteError): + evidence['error'] = str(exc) + raise + finally: + _request_audit.reset(token) + _write_audit(path, evidence, warnings_out) + outcomes = await asyncio.gather(*(member_call(index, member) for index, member in enumerate(config['members'])), return_exceptions=True) + failed = [index + 1 for index, result in enumerate(outcomes) if isinstance(result, BaseException)] + if failed: + _write_audit(group_dir / 'panel.json', {'status': 'incomplete', 'failed_members': failed}, warnings_out) + raise PanelIncompleteError(f'm1_judge_panel_incomplete: failed members {failed}; see panel audit artifacts') + completed = [outcome for outcome in outcomes if not isinstance(outcome, BaseException)] + combined = [] + for index, criterion in enumerate(criteria): + votes = [{'judge': config['members'][member_index], **outcome[0][index].to_dict()} for member_index, outcome in enumerate(completed)] + passes = sum((vote['value'] == 1 for vote in votes)) + value = int(passes >= 2) + combined.append(score_type(name=criterion.name, value=value, raw=bool(1 - value if criterion.negate else value), weight=weights[index] if weights is not None else 1.0, reasoning=f'{passes}/3 judges passed; strict majority requires 2/3.', description=criterion.description, id=criterion.id, negate=criterion.negate, optional=criterion.optional, votes=votes)) + for outcome in completed: + warnings_out.extend(outcome[2]) + audit = {'status': 'completed', 'mode': 'panel', 'aggregation': 'majority', 'required_votes': 2, 'members': config['members'], 'criteria': [score.to_dict() for score in combined]} + output = json.dumps(audit, indent=2, allow_nan=False) + _write_audit(group_dir / 'panel.json', audit, warnings_out) + return (combined, output, warnings_out) + +def install_panel(config_path: Path, *, audit_dir: Path=Path('/logs/verifier/judge-panel')) -> None: + import rewardkit.judges as judges + import rewardkit.reward as reward + from rewardkit.models import LLMJudge, Score + import litellm + config = json.loads(config_path.read_text()) + members = config.get('members') + concurrency = config.get('max_concurrent_llm') + if config.get('mode') != 'panel' or not isinstance(members, list) or len(members) != 3 or (len({member['model'] for member in members}) != 3) or (type(concurrency) is not int) or (not 1 <= concurrency <= 64): + raise ValueError('invalid materialized panel configuration') + if os.environ.get('REWARDKIT_JUDGE') or os.environ.get('REWARDKIT_MODEL'): + raise ValueError('RewardKit environment overrides cannot replace a frozen panel') + + class PanelScore(Score): + votes: list[dict[str, Any]] + + def to_dict(self): + return {**super().to_dict(), 'votes': self.votes} + original_llm = judges.arun_llm + original_call = judges._arun_llm_call + original_details = reward.Reward.to_detail_dict + original_completion = litellm.acompletion + active_loop = None + semaphore = None + + async def captured_completion(*args, **kwargs): + context = _request_audit.get() + record = {'requested_model': kwargs.get('model')} + response = None + try: + response = await original_completion(*args, **kwargs) + return response + except BaseException as exc: + record['error_class'] = type(exc).__name__ + raise + finally: + if context is not None: + path, warnings = context + try: + if response is not None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + record.update(response_model=data.get('model'), choices=data.get('choices')) + _write_audit(path, record, warnings, append=True) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + + async def bounded_call(*args, **kwargs): + nonlocal active_loop, semaphore + loop = asyncio.get_running_loop() + if active_loop is not loop: + active_loop, semaphore = (loop, asyncio.Semaphore(concurrency)) + assert semaphore is not None + async with semaphore: + return await original_call(*args, **kwargs) + + async def panel_call(judge, criteria, weights=None, system_prompt=None): + return await run_panel(judge, criteria, weights, system_prompt, config=config, run_llm=original_llm, score_type=PanelScore, audit_dir=audit_dir) + + def panel_details(self, score): + detail = original_details(self, score) + if isinstance(self.judge, LLMJudge): + detail.update(kind='llm_panel', judge=config, aggregation='majority', required_votes=2) + return detail + setattr(reward, 'arun_llm', panel_call) + setattr(judges, '_arun_llm_call', bounded_call) + setattr(litellm, 'acompletion', captured_completion) + reward.Reward.to_detail_dict = panel_details diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/normalize_reward.py b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/normalize_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..91817ef00ea9152ca57f0030d8e879eb850ddff0 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/normalize_reward.py @@ -0,0 +1,71 @@ +from __future__ import annotations +import argparse +import json +from pathlib import Path +from typing import Any + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument('--raw-details', required=True) + parser.add_argument('--rubric', required=True) + parser.add_argument('--reward-out', required=True) + parser.add_argument('--details-out', required=True) + args = parser.parse_args() + raw_details = _load_json(Path(args.raw_details)) + rubric = _load_json(Path(args.rubric)) + criteria = rubric['criteria'] + raw_by_name = _raw_criteria_by_name(raw_details) + positive_total = sum((float(item['score']) for item in criteria if float(item['score']) > 0)) + if positive_total <= 0: + raise ValueError('rubric must contain at least one positive score') + earned = 0.0 + normalized_criteria: list[dict[str, Any]] = [] + for item in criteria: + signed_score = float(item['score']) + raw = raw_by_name.get(item['name'], {}) + value = _coerce_score(raw.get('value', 0.0)) + contribution = value * signed_score + earned += contribution + normalized_criteria.append({'name': item['name'], 'value': value, 'raw': raw.get('raw'), 'weight': signed_score, 'signed_score': signed_score, 'polarity': item['polarity'], 'contribution': contribution, 'description': item['description'], 'source': item.get('source', ''), 'justification': item.get('justification', ''), 'metadata': item.get('metadata', {}), 'reasoning': raw.get('reasoning'), 'judge_reasoning': raw.get('reasoning'), 'judge_error': raw.get('error'), **({'votes': raw['votes']} if 'votes' in raw else {})}) + unclamped = earned / positive_total + reward = max(0.0, min(1.0, unclamped)) + reward_out = {'correctness': reward} + details_out = {'correctness': {'score': reward, 'kind': 'signed_score', 'criteria': normalized_criteria, 'aggregation': {'method': 'signed_score_ratio_clamped', 'earned': earned, 'positive_total': positive_total, 'unclamped': unclamped, 'clamped': reward}, 'raw_rewardkit': raw_details}} + _write_json(Path(args.reward_out), reward_out) + _write_json(Path(args.details_out), details_out) + +def _load_json(path: Path) -> Any: + return json.loads(path.read_text()) + +def _write_json(path: Path, data: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data, indent=2) + '\n') + +def _raw_criteria_by_name(details: dict[str, Any]) -> dict[str, dict[str, Any]]: + out: dict[str, dict[str, Any]] = {} + for reward in details.values(): + for item in _iter_raw_criteria(reward): + name = item.get('name') + if isinstance(name, str): + out[name] = item + return out + +def _iter_raw_criteria(value: Any): + if isinstance(value, list): + for item in value: + yield from _iter_raw_criteria(item) + return + if not isinstance(value, dict): + return + for item in value.get('criteria') or []: + if isinstance(item, dict): + yield item + +def _coerce_score(value: Any) -> float: + if isinstance(value, bool): + return 1.0 if value else 0.0 + if isinstance(value, int | float): + return max(0.0, min(1.0, float(value))) + return 0.0 +if __name__ == '__main__': + main() diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/agent_prompt.md b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/agent_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..ca489c065bafd5d10e764f033c9dfd1195933db3 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/agent_prompt.md @@ -0,0 +1,10 @@ +You are grading the submitted legal analysis against the criteria below. + +Read `/logs/artifacts/answer.md`, the answer captured by the verifier, before +assigning any scores. Evaluate that file as the submission. Other files in +`/app` may supply context, but must not replace the submitted answer. Do not +modify the submission. If it is missing or empty, state that in your reasoning +and apply the criteria to that missing or empty submission. Preserve each +criterion's stated positive or penalty polarity. + +{criteria} diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/mentions_in_the_first_assignment_that_the_county_s_prior_rezonin.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/mentions_in_the_first_assignment_that_the_county_s_prior_rezonin.toml new file mode 100644 index 0000000000000000000000000000000000000000..f08cf2b9b7b5f42831a56cfe4069608c28965f23 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/mentions_in_the_first_assignment_that_the_county_s_prior_rezonin.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "mentions_in_the_first_assignment_that_the_county_s_prior_rezonin" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions in the first assignment that the county's prior rezoning request in DCI2018-10023 was remanded by the Hearing Examiner to staff for further evaluation and analysis on August 13, 2019." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/mentions_in_the_first_assignment_that_the_subject_property_was_p.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/mentions_in_the_first_assignment_that_the_subject_property_was_p.toml new file mode 100644 index 0000000000000000000000000000000000000000..c57a04bc8c8264442419514a0ede835057fbffef --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/mentions_in_the_first_assignment_that_the_subject_property_was_p.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "mentions_in_the_first_assignment_that_the_subject_property_was_p" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions in the first assignment that the subject property was placed into the Public Facilities future land use category of the Lee County Comprehensive Plan pursuant to Lee County, Fla. Ordinance 23-28 (2023)." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_dci2018_10023_remained_activ.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_dci2018_10023_remained_activ.toml new file mode 100644 index 0000000000000000000000000000000000000000..3d65721de135d0056c4adc1d8a25c9d6e385c39f --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_dci2018_10023_remained_activ.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_first_assignment_that_dci2018_10023_remained_activ" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: States in the first assignment that DCI2018-10023 remained active until September 13, 2023." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_circuit_court_found_th_2.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_circuit_court_found_th_2.toml new file mode 100644 index 0000000000000000000000000000000000000000..75dad7b2ba1bedacf417d45fbc29ae92cde16ad5 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_circuit_court_found_th_2.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_first_assignment_that_the_circuit_court_found_th_2" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the first assignment that the circuit court found that the Lee County Board of County Commissioners \"improperly departed from the record created at the quasi-judicial hearings held below.\"" +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_circuit_court_found_th_3.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_circuit_court_found_th_3.toml new file mode 100644 index 0000000000000000000000000000000000000000..1afb8b49da89cbee1de20c1aa5cdabb2b5bfc72d --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_circuit_court_found_th_3.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_first_assignment_that_the_circuit_court_found_th_3" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the first assignment that the circuit court found that Lee County's conduct \"created prejudice and bias\" surrounding the rezoning." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_circuit_court_found_th_4.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_circuit_court_found_th_4.toml new file mode 100644 index 0000000000000000000000000000000000000000..97fd2fceceb4f545674c5d6150552a27d896818d --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_circuit_court_found_th_4.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_first_assignment_that_the_circuit_court_found_th_4" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the first assignment that the circuit court found that certain Federal Aviation Administration regulations \"were not fully considered below.\"" +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_circuit_court_found_that.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_circuit_court_found_that.toml new file mode 100644 index 0000000000000000000000000000000000000000..90fad0363cedc80a7e30692c70a5526fcd15af9e --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_circuit_court_found_that.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_first_assignment_that_the_circuit_court_found_that" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the first assignment that the circuit court found that the Petitioners had standing to bring the petition based on proximity of the Petitioners' property to the proposed facility." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_could_appeal_the.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_could_appeal_the.toml new file mode 100644 index 0000000000000000000000000000000000000000..b59b504bcd2e096757218c3a227b61107d3e5a46 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_could_appeal_the.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_first_assignment_that_the_county_could_appeal_the" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the first assignment that the county could appeal the Order Granting Writ of Certiorari to the Sixth District Court of Appeals pursuant to Fla. R. App. P. 9.030(b)(2)(B)." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_could_file_a_new.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_could_file_a_new.toml new file mode 100644 index 0000000000000000000000000000000000000000..dde7ac3a475cee2b85b225be7d8096b151695633 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_could_file_a_new.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_first_assignment_that_the_county_could_file_a_new" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the first assignment that the County could file a new application for rezoning." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_could_negotiate_2.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_could_negotiate_2.toml new file mode 100644 index 0000000000000000000000000000000000000000..d5e42a9f77e5f53899ff310b0cca28c4b1a45e7f --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_could_negotiate_2.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_first_assignment_that_the_county_could_negotiate_2" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the first assignment that the County could negotiate for additional conditions protecting water quality that address Petitioners' concerns." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_could_negotiate_f.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_could_negotiate_f.toml new file mode 100644 index 0000000000000000000000000000000000000000..923b68d9c840d0491189520c53e39a12ab499787 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_could_negotiate_f.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_first_assignment_that_the_county_could_negotiate_f" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the first assignment that the County could negotiate for additional conditions protecting wildlife that address Petitioners' concerns." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_could_remand_the.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_could_remand_the.toml new file mode 100644 index 0000000000000000000000000000000000000000..1ecc66cd045fa7193a67cfc5fc2a56b8c1370744 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_could_remand_the.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_first_assignment_that_the_county_could_remand_the" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the first assignment that the county could remand the case back to the Hearing Examiner for an evidentiary hearing to address the deficiencies identified in the Order Granting Petition for Writ of Certiorari under Lee County Fla. Land Development Code § 34-83(a)(6) (2025)." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_could_take_the_po.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_could_take_the_po.toml new file mode 100644 index 0000000000000000000000000000000000000000..60756232e8907c00a679beb0f5967f5e68ad2b91 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_could_take_the_po.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_first_assignment_that_the_county_could_take_the_po" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the first assignment that the County could take the position that the rezoning is not necessary because the county is not bound by its local zoning laws in carrying out a governmental function." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_could_voluntarily.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_could_voluntarily.toml new file mode 100644 index 0000000000000000000000000000000000000000..3ed9954f7d221fe520709fb27d639ef6c1a189ee --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_could_voluntarily.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_first_assignment_that_the_county_could_voluntarily" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the first assignment that the County could voluntarily cease construction activities pending resolution of the challenge." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_must_stop_constru.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_must_stop_constru.toml new file mode 100644 index 0000000000000000000000000000000000000000..8d0972d20bcf304b8016488d59839a01771edfaa --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_must_stop_constru.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_first_assignment_that_the_county_must_stop_constru" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: States in the first assignment that the county must stop construction activities as a result of the Order Granting Writ of Certiorari." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_should_cease_cons.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_should_cease_cons.toml new file mode 100644 index 0000000000000000000000000000000000000000..1eb187268fe59268620f249179862626404a06ad --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_should_cease_cons.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_first_assignment_that_the_county_should_cease_cons" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: States in the first assignment that the County should cease construction activities at the subject property." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_should_file_a_tim.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_should_file_a_tim.toml new file mode 100644 index 0000000000000000000000000000000000000000..5f9bb2f4904e3f67ca4a24723af4284ab20ec3aa --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_should_file_a_tim.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_first_assignment_that_the_county_should_file_a_tim" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the first assignment that the County should file a timely appeal with the 6th District Court of Appeals." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_should_remand_the.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_should_remand_the.toml new file mode 100644 index 0000000000000000000000000000000000000000..359e61c155650b915e6206ad1941f546afa0c29d --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_county_should_remand_the.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_first_assignment_that_the_county_should_remand_the" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the first assignment that the County should remand the case to the Hearing Examiner to address the deficiencies identified in the Order Granting Writ of Certiorari while an appeal is pending." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_effect_of_the_order_gran.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_effect_of_the_order_gran.toml new file mode 100644 index 0000000000000000000000000000000000000000..bc4279368fb8cde001c2f9b0404d4f8beceafdcf --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_effect_of_the_order_gran.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_first_assignment_that_the_effect_of_the_order_gran" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: States in the first assignment that the effect of the Order Granting Writ of Certiorari is that the Board's decision is overturned." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_exclusive_method_of_chal.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_exclusive_method_of_chal.toml new file mode 100644 index 0000000000000000000000000000000000000000..1ba193bdbeb60d9920c0b2a9975710fd7f780d3e --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_exclusive_method_of_chal.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_first_assignment_that_the_exclusive_method_of_chal" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the first assignment that the exclusive method of challenging the issuance of a development order that materially alters the use or density or intensity of use on a particular piece of property is by filing a petition for writ of certiorari under Fla. Stat. § 163.3215(4) (2025) within 30 days of rendition of the development order." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_exclusive_method_of_revi.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_exclusive_method_of_revi.toml new file mode 100644 index 0000000000000000000000000000000000000000..59f3307a75e605265d75ef59d104055b3d5588c9 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_exclusive_method_of_revi.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_first_assignment_that_the_exclusive_method_of_revi" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the first assignment that the exclusive method of review of a quasi-judicial decision is by petition for writ of certiorari under Fla. R. App. P. 9.100(c) (2025) within 30 days of the written decision." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_order_granting_petition.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_order_granting_petition.toml new file mode 100644 index 0000000000000000000000000000000000000000..4a8edec6866a274688e3bc6cf0d63824455c33c3 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_order_granting_petition.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_first_assignment_that_the_order_granting_petition" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the first assignment that the Order Granting Petition for Writ of Certiorari quashes Lee County, Fla., Res. No. Z-23-035 (2024)." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_petitioners_may_file_a_s.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_petitioners_may_file_a_s.toml new file mode 100644 index 0000000000000000000000000000000000000000..a6ea20b9941dbfa49d9281f096bb3155e1ef84c9 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_the_petitioners_may_file_a_s.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_first_assignment_that_the_petitioners_may_file_a_s" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: States in the first assignment that the Petitioners may file a separate cause of action for injunction to stop construction activities." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_under_fla_stat_163_3167_10_2.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_under_fla_stat_163_3167_10_2.toml new file mode 100644 index 0000000000000000000000000000000000000000..fd416fad67e8a1e6ba24c638596ea00e17c927ab --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_under_fla_stat_163_3167_10_2.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_first_assignment_that_under_fla_stat_163_3167_10_2" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the first assignment that under Fla. Stat § 163.3167(10) (2025) the development order issued for the project may not be invalidated by a subsequent judicial determination because the timeframe for filing an appeal of the development order has expired." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_under_lee_county_fla_admin_c.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_under_lee_county_fla_admin_c.toml new file mode 100644 index 0000000000000000000000000000000000000000..08846aa08b347a9e14a528cf7b7f931aeae7fc1b --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/raw_correctness/states_in_the_first_assignment_that_under_lee_county_fla_admin_c.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_first_assignment_that_under_lee_county_fla_admin_c" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the first assignment that under Lee County, Fla. Admin. Code § 2-6, 4.1 B. (2025), DCI2018-10023 was considered withdrawn on February 13, 2020." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/test.sh b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..66a509a7bcdbe412851f3a012a5ba7b16cf0925b --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/tests/test.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +set -euo pipefail + +mkdir -p /logs/artifacts /logs/verifier/raw + +python3 - <<'PYEOF' +import json +import shutil +from pathlib import Path + + +def has_text(path: Path) -> bool: + return path.exists() and path.is_file() and bool(path.read_text(errors="replace").strip()) + + +def fallback_paths(answer_path: Path) -> list[Path]: + paths = [] + try: + relative = answer_path.relative_to("/app") + paths.append(Path("/app/app") / relative) + except ValueError: + pass + return [path for path in paths if path != answer_path] + + +config = json.loads(Path("/tests/fixtures/config.json").read_text()) +answer_path = Path(config["answer_path"]) +artifact_answer = Path("/logs/artifacts/answer.md") +artifact_answer.parent.mkdir(parents=True, exist_ok=True) +if has_text(answer_path): + shutil.copyfile(answer_path, artifact_answer) +else: + for candidate in fallback_paths(answer_path): + if has_text(candidate): + shutil.copyfile(candidate, artifact_answer) + break + else: + artifact_answer.write_text("") + +# Harbor collects /logs/artifacts when the agent step ends, which is before this +# script runs, so the copy above never reaches the uploaded artifacts. /logs/verifier +# is uploaded after the verifier phase, so persist the graded answer there too. +verifier_answer = Path("/logs/verifier/answer.md") +verifier_answer.parent.mkdir(parents=True, exist_ok=True) +shutil.copyfile(artifact_answer, verifier_answer) +PYEOF + +uv run --no-project --with 'harbor-rewardkit[all]==0.2.0' python /tests/m1_rewardkit_accounting.py /tests/raw_correctness \ + --workspace /app \ + --output /logs/verifier/raw/reward.json \ + --max-concurrent-llm "${MAX_CONCURRENT_LLM:-4}" \ + --max-concurrent-agent "${M1_MAX_CONCURRENT_AGENT:-1}" + +python /tests/normalize_reward.py \ + --raw-details /logs/verifier/raw/reward-details.json \ + --rubric /tests/fixtures/rubric.json \ + --reward-out /logs/verifier/reward.json \ + --details-out /logs/verifier/reward-details.json diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/workdir/attachments/1774361815-lcu-project.pdf b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/workdir/attachments/1774361815-lcu-project.pdf new file mode 100644 index 0000000000000000000000000000000000000000..b4de08e6d34d6d75acb1e9c4f59291cdcc658c20 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/workdir/attachments/1774361815-lcu-project.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9c5f99bdc5eaf0627b26261a422a8795559be236d23eaf80bde215659edd606b +size 1605204 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/workdir/attachments/1774361815-orderpdf.docx b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/workdir/attachments/1774361815-orderpdf.docx new file mode 100644 index 0000000000000000000000000000000000000000..55dbeb2ba68b47d9f143df2d5ded2634f8040020 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/workdir/attachments/1774361815-orderpdf.docx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f4f537e2119b85b27f1f73c72769455e7ddc56411f9c83bd52e5b25d5db8281b +size 5949313 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/workdir/attachments/1774361815-petition.docx b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/workdir/attachments/1774361815-petition.docx new file mode 100644 index 0000000000000000000000000000000000000000..a666a3f6d6b5b7079e66fcce9a5b4aaf830d0d3e --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/workdir/attachments/1774361815-petition.docx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:823d81b96ebd48a0b45f9353645ea5276ec83d6561a6963ee404478e3e0e4c4d +size 4633006 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/workdir/attachments/1774361815-resolution.docx b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/workdir/attachments/1774361815-resolution.docx new file mode 100644 index 0000000000000000000000000000000000000000..4d5ed824ed858f5d31880e072fd0ff015672bb78 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-1/workdir/attachments/1774361815-resolution.docx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4345fd5cc85c6e38d988164b512b4cf8d2c9347c21e96ebc18dd714b53ca6e0f +size 629762 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/instruction.md b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..401215ecc29748678057dc6dafd434d3d508fbdb --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/instruction.md @@ -0,0 +1,46 @@ +# Petition for Writ of Certiorari for Quasi-judicial Proceeding — Brief Requesting Second-Tier Review + +Domain: Legal + +Matter: Petition for Writ of Certiorari for Quasi-judicial Proceeding + +You are a senior legal analyst operating autonomously. You are completing a multi-step legal reasoning task. Follow the role, factual record, instructions, and deliverable requirements provided in the Task and each Assignment. + +Each Assignment may require a different legal deliverable. Follow the requirements specific to that Assignment. + +## Word limits for court briefs + +- A brief in support of or in response to a motion may not exceed **8,750 words**. +- A reply brief may not exceed **3,500 words**. +- For a motion for reconsideration, a brief in support of or in response to the motion may not exceed **3,500 words**, and a reply brief may not exceed **1,750 words**. +- If an Assignment specifies a stricter word limit, follow the stricter limit. + +These word limits do not apply to legal memoranda or other non-court-filing deliverables unless the Assignment expressly provides otherwise. + +Complete the task end-to-end without asking for confirmation, permission, or clarification. + +Use the uploaded matter documents in `/app/attachments/` as your primary case file. You also have internet access via OpenCode's `websearch` tool; use it to research any statutes, regulations, cases, administrative guidance, or secondary authorities that are not supplied as attachments. Cite any authority you rely on in the format requested by the prompt. + +For document inspection: +- PDF: `pdftotext /app/attachments/.pdf -` +- DOCX: `pandoc /app/attachments/.docx -t markdown` +- XLSX/CSV: use Python with `openpyxl` or `pandas` +- If extraction is unreliable, inspect the raw file with Python libraries or convert/render the relevant pages. + +Write the final complete legal deliverable for this assignment to `/app/response2.md`. The verifier reads only that file. + +This is a follow-on assignment. The documents from the previous assignment(s) remain available in `/app/attachments/`, and your prior deliverable `/app/response1.md` is also on disk. Build on that analysis as the prompt directs. + +## Attachments + +_No new documents for this assignment. The documents from the previous assignment(s) remain available in `/app/attachments/`._ + +## Prompt + +2nd ASSIGNMENT +TO: Denise Swarek, Assistant County Attorney +FROM: Thomas Rowe, County Attorney +RE: PETER SPAHN, ET. AL., V. LEE COUNTY; Case No. 24-CA-1479 +DATE: November 10, 2025 +________________________________________ +The Board has decided to appeal the Order Granting Petition for Certiorari. Draft a ready-to-file brief requesting second-tier review. All legal analysis should be based on the versions of statutes, regulations, and ordinances in effect as of January 1, 2025. Use full Bluebook citation format. diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/solution/solve.sh b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7710414a6da6d0ad740717c8c85a9af850d5da33 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/solution/solve.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# No oracle solution ships with LegalReasonBench. The verifier grades the +# agent's own legal deliverable for this assignment against the rubric. +echo "no oracle solution" diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/fixtures/config.json b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/fixtures/config.json new file mode 100644 index 0000000000000000000000000000000000000000..8b181f991e2e7858e57b2864832911934e8a88f1 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/fixtures/config.json @@ -0,0 +1,233 @@ +{ + "task_id": "lrb-certiorari-quasi-judicial-land-use", + "title": "Petition for Writ of Certiorari for Quasi-judicial Proceeding", + "domain": "Legal", + "matter": "Petition for Writ of Certiorari for Quasi-judicial Proceeding", + "judge": { + "max_concurrent_llm": 12, + "mode": "panel", + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ], + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + "step_index": 2, + "step_name": "assignment-2", + "step_title": "Brief Requesting Second-Tier Review", + "prompt": "2nd ASSIGNMENT\nTO: Denise Swarek, Assistant County Attorney\nFROM: Thomas Rowe, County Attorney\nRE: PETER SPAHN, ET. AL., V. LEE COUNTY; Case No. 24-CA-1479\nDATE: November 10, 2025\n________________________________________\nThe Board has decided to appeal the Order Granting Petition for Certiorari. Draft a ready-to-file brief requesting second-tier review. All legal analysis should be based on the versions of statutes, regulations, and ordinances in effect as of January 1, 2025. Use full Bluebook citation format.", + "attachments": [], + "rubric": [ + { + "name": "identifies_in_the_second_assignment_that_the_appropriate_mechani", + "description": "Identifies in the second assignment that the appropriate mechanism to appeal the Order Granting Writ of Certiorari is a Petition for Writ of Certiorari to the 6th District Court of Appeals.", + "source": "Florida Rule of Appellate Procedure 9.030(b)(2)(B); https://rules.floridaappellate.com/rule-9-030/#:~:text=b%29-,Jurisdiction,capacity\n\"Jurisdiction of District Courts of Appeal.\n\"b) Jurisdiction of District Courts of Appeal.\n. . .\n(2) Certiorari Jurisdiction.8 The certiorari jurisdiction of district courts of appeal may be sought to review:\n(A) nonfinal orders of lower tribunals other than as prescribed by rule 9.130; or\n(B) final orders of circuit courts acting in their review capacity.\"\nSee also Map of Florida\u2019s Court Jurisdictions, available at https://flcourts-media.flcourts.gov/content/download/426177/file/ar-17-18-map-of-floridas-court-jurisdictions.pdf (last accessed Mar. 25, 2026)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cDraft a ready-to-file brief requesting second-tier review.\u201d", + "metadata": { + "review_flag": false, + "original_name": "identifies_in_the_second_assignment_that_the_appropriate_mechanism_to_appeal_the", + "original_index": 26, + "classifier_reason": "Names second assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_second_assignment_that_the_circuit_court_erred_by", + "description": "States in the second assignment that the circuit court erred by ignoring the competent substantial evidence on the record that supported the approval contrary to Dusseau v. Metro. Dade Cnty. Bd. of Cnty. Comm\u2019rs, 794 So.2d 1270 (Fla. 2001).", + "source": "Dusseau v. Metro. Dade Cnty. Bd. of Cnty. Comm\u2019rs, 794 So.2d 1270 (Fla. 2001), is the preeminent FL Supreme court case on the limited review of quasi-judicial. \nhttps://caselaw.findlaw.com/court/fl-supreme-court/1489002.html#:~:text=Notably,ended\n\"Notably, when applying the third prong, the court should review the record to determine simply whether the Commission's decision is supported by competent substantial evidence.\n\nWe reiterate that the \u201ccompetent substantial evidence\u201d standard cannot be used by a reviewing court as a mechanism for exerting covert control over the policy determinations and factual findings of the local agency. \u2002 Rather, this standard requires the reviewing court to defer to the agency's superior technical expertise and special vantage point in such matters. \u2002 The issue before the court is not whether the agency's decision is the \u201cbest\u201d decision or the \u201cright\u201d decision or even a \u201cwise\u201d decision, for these are technical and policy-based determinations properly within the purview of the agency. \u2002 The circuit court has no training or experience-and is inherently unsuited-to sit as a roving \u201csuper agency\u201d with plenary oversight in such matters.\n\nThe sole issue before the court on first-tier certiorari review is whether the agency's decision is lawful. \u2002 The court's task vis-a-vis the third prong of Vaillant is simple: \u2009The court must review the record to assess the evidentiary support for the agency's decision. \u2002 Evidence contrary to the agency's decision is outside the scope of the inquiry at this point, for the reviewing court above all cannot reweigh the \u201cpros and cons\u201d of conflicting evidence. \u2002 While contrary evidence may be relevant to the wisdom of the decision, it is irrelevant to the lawfulness of the decision. \u2002 As long as the record contains competent substantial evidence to support the agency's decision, the decision is presumed lawful and the court's job is ended.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cDraft a ready-to-file brief requesting second-tier review.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_second_assignment_that_the_circuit_court_erred_by_ignoring_the_com", + "original_index": 27, + "classifier_reason": "Names second assignment", + "classifier_confidence": "high" + }, + "score": 20.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_second_assignment_that_the_staff_report_recommendi", + "description": "States in the second assignment that the staff report recommending approval is competent substantial evidence that supports the Board's approval of the rezoning.", + "source": "City of Hialeah Gardens v. Miami-Dade Charter Found., Inc., 857 So.2d 202, 204-5 (Fla. 3d DCA 2003); https://caselaw.findlaw.com/court/fl-district-court-of-appeal/1254782.html#:~:text=Here%2C%20the,reached%2E%E2%80%9D\n\"Here, the testifying staff members utilized their professional experiences and personal observations, as well as Machado's application, site plan, and traffic study, as the basis for their testimony. \u2002 These record materials, along with the staff presentations, combined to provide evidence \u201csufficiently relevant and material that a reasonable mind would accept it as adequate to support the conclusion reached.\u201d", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cDraft a ready-to-file brief requesting second-tier review.\u201d The primary argument on appeal is that the court failed to apply the standard of review under Dusseau v. Metro. Dade Cnty. Bd. of Cnty. Comm\u2019rs, 794 So.2d 1270 (Fla. 2001), by ignoring the competent substantial evidence on the record that supported the Board's approval. Identifying the competent substantial evidence on the record supports this argument.", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_second_assignment_that_the_staff_report_recommending_approval_is_c", + "original_index": 28, + "classifier_reason": "Names second assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_second_assignment_that_expert_testimony_on_the_rec", + "description": "States in the second assignment that expert testimony on the record is competent substantial evidence that supports the Board's approval of the rezoning.", + "source": "City of Hialeah Gardens v. Miami-Dade Charter Found., Inc., 857 So.2d 202, 204-5 (Fla. 3d DCA 2003); https://caselaw.findlaw.com/court/fl-district-court-of-appeal/1254782.html#:~:text=Here%2C%20the,reached%2E%E2%80%9D\n\"Here, the testifying staff members utilized their professional experiences and personal observations, as well as Machado's application, site plan, and traffic study, as the basis for their testimony. \u2002 These record materials, along with the staff presentations, combined to provide evidence \u201csufficiently relevant and material that a reasonable mind would accept it as adequate to support the conclusion reached.\u201d", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cDraft a ready-to-file brief requesting second-tier review.\u201d The primary argument on appeal is that the court failed to apply the standard of review under Dusseau v. Metro. Dade Cnty. Bd. of Cnty. Comm\u2019rs, 794 So.2d 1270 (Fla. 2001), by ignoring the competent substantial evidence on the record that supported the Board's approval. Identifying the competent substantial evidence on the record supports this argument.", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_second_assignment_that_expert_testimony_on_the_record_is_competent", + "original_index": 29, + "classifier_reason": "Names second assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_second_assignment_that_the_hearing_examiner_s_reco", + "description": "States in the second assignment that the Hearing Examiner's recommendation of approval is competent substantial evidence that supports the Board's approval of the rezoning.", + "source": "City of Hialeah Gardens v. Miami-Dade Charter Found., Inc., 857 So.2d 202, 204-5 (Fla. 3d DCA 2003); https://caselaw.findlaw.com/court/fl-district-court-of-appeal/1254782.html#:~:text=Here%2C%20the,reached%2E%E2%80%9D\n\"Here, the testifying staff members utilized their professional experiences and personal observations, as well as Machado's application, site plan, and traffic study, as the basis for their testimony. \u2002 These record materials, along with the staff presentations, combined to provide evidence \u201csufficiently relevant and material that a reasonable mind would accept it as adequate to support the conclusion reached.\u201d", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cDraft a ready-to-file brief requesting second-tier review.\u201d The primary argument on appeal is that the court failed to apply the standard of review under Dusseau v. Metro. Dade Cnty. Bd. of Cnty. Comm\u2019rs, 794 So.2d 1270 (Fla. 2001), by ignoring the competent substantial evidence on the record that supported the Board's approval. Identifying the competent substantial evidence on the record supports this argument.", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_second_assignment_that_the_hearing_examiner_s_recommendation_of_ap", + "original_index": 30, + "classifier_reason": "Names second assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_second_assignment_that_the_circuit_court_erred_b_2", + "description": "States in the second assignment that the circuit court erred by failing to apply the fairly debatable standard of review to the county's legislative decision to construct a water treatment plant on its own property.", + "source": "Martin County v. Yusem, 690 So. 2d 1288, 1295 (Fla. 1997), is the controlling FL supreme court case on the limited judicial review of local government legislative functions. https://caselaw.findlaw.com/court/fl-supreme-court/1459273.html#:~:text=-,The%20fairly,1996%29%2E\n \"The fairly debatable standard of review is a highly deferential standard requiring approval of a planning action if reasonable persons could differ as to its propriety.\"\nSee also Modlin v. City of Miami Beach, 201 So.2d 70 (Fla. 1967); https://law.justia.com/cases/florida/supreme-court/1967/34865-0.html#:~:text=liability%2E-,The,persons \n\"The distinction between legislative action, on the one hand, and executive and judicial action, on the other, is not difficult to define. It is sufficient for present purposes to say that the former is typically prospective and nondiscriminatory, whereas the latter operate retroactively and discriminatorily. In other words, legislative action prescribes a general rule for future operation, whereas judicial and executive action is typically concerned with applying the general rule to specific situations or persons.\"\nThis is a landmark FL supreme court case defining the separate functions of government.", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cDraft a ready-to-file brief requesting second-tier review.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_second_assignment_that_the_circuit_court_erred_by_failing_to_apply", + "original_index": 31, + "classifier_reason": "Names second assignment", + "classifier_confidence": "high" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_second_assignment_that_the_circuit_court_erred_in", + "description": "States in the second assignment that the circuit court erred in finding that communications with staff are ex parte communications pursuant to Lee County Fla. Land Development Code \u00a7 2-191 (2025).", + "source": "Lee County Fla. Land Development Code \u00a7 2-191 (2025); https://library.municode.com/fl/lee_county/codes/land_development_code?nodeId=LADECO_CH2AD_ARTVUNCO_S2-191PRLIUNCO#:~:text=This%20section%20does%20not%20prohibit%20the%20informational%20discussion%20of%20pending%20or%20proposed%20cases%20or%20appeals%20by%20and%20between%20a%20County%20Commissioner%20and%20any%20employee%20of%20the%20Board%20of%20County%20Commissioners%2E\n\"Unauthorized communications with a County Commissioner prohibited. . . . This section does not prohibit the informational discussion of pending or proposed cases or appeals by and between a County Commissioner and any employee of the Board of County Commissioners. \"\nSee also Fla. Stat \u00a7 286.0115(3) (2025); https://www.leg.state.fl.us/Statutes/index.cfm?App_mode=Display_Statute&URL=0200-0299/0286/Sections/0286.0115.html#:~:text=%283%29%E2%80%83This%20section%20does%20not%20restrict%20the%20authority%20of%20any%20board%20or%20commission%20to%20establish%20rules%20or%20procedures%20governing%20public%20hearings%20or%20contacts%20with%20local%20public%20officials\n\"286.0115\u2003Access to local public officials; quasi-judicial proceedings on local government land use matters.\u2014 (3)\u2003This section does not restrict the authority of any board or commission to establish rules or procedures governing public hearings or contacts with local public officials.", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cDraft a ready-to-file brief requesting second-tier review.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_second_assignment_that_the_circuit_court_erred_in_finding_that_com", + "original_index": 32, + "classifier_reason": "Names second assignment", + "classifier_confidence": "high" + }, + "score": 20.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_second_assignment_that_the_circuit_court_erred_b_3", + "description": "States in the second assignment that the circuit court erred by failing to apply the fairly debatable standard of review to the county's legislative decision to enter into the Kingston Settlement to resolve pending litigation.", + "source": "Martin County v. Yusem, 690 So. 2d 1288, 1295 (Fla. 1997), is the controlling FL supreme court case on the limited judicial review of local government legislative functions. https://caselaw.findlaw.com/court/fl-supreme-court/1459273.html#:~:text=-,The%20fairly,1996%29%2E\n \"The fairly debatable standard of review is a highly deferential standard requiring approval of a planning action if reasonable persons could differ as to its propriety.\"\nSee also Modlin v. City of Miami Beach, 201 So.2d 70 (Fla. 1967); https://law.justia.com/cases/florida/supreme-court/1967/34865-0.html#:~:text=liability%2E-,The,persons \n\"The distinction between legislative action, on the one hand, and executive and judicial action, on the other, is not difficult to define. It is sufficient for present purposes to say that the former is typically prospective and nondiscriminatory, whereas the latter operate retroactively and discriminatorily. In other words, legislative action prescribes a general rule for future operation, whereas judicial and executive action is typically concerned with applying the general rule to specific situations or persons.\"\nThis is a landmark FL supreme court case defining the separate functions of government.\nSee also Williams v. Public Util. Protective League, 178 So. 286 (Fla. 1938); https://hallapproved.com/fl/cases/supreme/1938/3402391/#:~:text=As%20an,inadequate\n\"As an abstract proposition of law, the power of the City to compromise, settle, and compose litigation of any kind to which it is a party is an incident to and implied from its power to sue and be sued. Like the power to legislate and negotiate it will not be restrained from exercising such power by a court of equity on a mere showing of belief, fear, or apprehension that some wrong or injury will be done, or when the injury is conjectural or speculative. Relief under such circumstances will be granted only in cases where the pleadings and the proof show clearly that the resulting injury will be irreparable and the remedy at law inadequate.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cDraft a ready-to-file brief requesting second-tier review.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_second_assignment_that_the_circuit_court_erred_by_failing_to_apply_2", + "original_index": 33, + "classifier_reason": "Names second assignment", + "classifier_confidence": "high" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_second_assignment_that_the_circuit_court_erred_b_4", + "description": "States in the second assignment that the circuit court erred by finding that Fed. Aviation Admin., Advisory Circular No. 150/5190-7, Minimum Standards for Commercial Aeronautical Activities (Dec. 7, 2023), is incorporated into Lee County Fla. Land Development Code \u00a7 34-1102 (2025).", + "source": "The circuit court found that the County had failed to comply with Fed. Aviation Admin., Advisory Circular 150/5190-7 Minimum Standards for Commercial Aeronautical Activities (Dec. 7, 2023) requirements for airport compatibility, concluding that the most current and restrictive regulations should have been fully considered. This was legal error. Lee County, Fla. Land Development Code \u00a7 34-1102 (2025) incorporates only Fed. Aviation Admin., Advisory Circular No. 150/5300-13B, Airport Design (2022) and 150/5200-30D Airport Field Condition Assessments and Winter Operations Safety (July 29, 2016), not Fed. Aviation Admin., Advisory CircularNo. 150/5190-7, Minimum Standards for Commercial Aeronautical Activities (Dec. 7, 2023), which the order treats as controlling. Lee County, Fla. Land Development Code \u00a7 34-1102 (2025); https://library.municode.com/fl/lee_county/codes/land_development_code?nodeId=LADECO_CH34ZO_ARTVIDIRE_DIV12AICODI_S34-1102PUIN\n\"The purpose of this division is to establish protections around SWFIA and Page Field in accordance with the provisions of F.S. Chs. 330 and 333, as amended, as well as Federal regulations, as amended, including 14 CFR Parts 77, 150 and 151 and FAA Advisory Circulars 150/5300-13A, as amended, renumbered or replaced, and 150/5200-33B, as amended, renumbered or replaced, which address height obstructions, airport hazards, wildlife attractants, noise, runway protection zones, light emissions, reflectivity and power interference, aircraft overflights, and the public investment in air transportation facilities.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cDraft a ready-to-file brief requesting second-tier review.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_second_assignment_that_the_circuit_court_erred_by_finding_that_fed", + "original_index": 34, + "classifier_reason": "Names second assignment", + "classifier_confidence": "high" + }, + "score": 20.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_second_assignment_that_the_circuit_court_erred_i_2", + "description": "States in the second assignment that the circuit court erred in treating Federal Aviation Authority Advisory Circulars as binding law.", + "source": "Fed. Aviation Admin., Advisory Circular No. 150/5190-4B, Airport Land Use Compatibility Planning (Sept. 16, 2022) at page 2 confirms that \u201cThis AC does not constitute a regulation, and is not legally binding in its own right\u2026 Conformity with this AC is voluntary, and nonconformity will not affect rights and obligations under existing statutes and regulations,\u201d https://www.faa.gov/documentLibrary/media/Advisory_Circular/150_5190_4b_Land_Use_Compatibility.pdf", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cDraft a ready-to-file brief requesting second-tier review.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_second_assignment_that_the_circuit_court_erred_in_treating_federal", + "original_index": 35, + "classifier_reason": "Names second assignment", + "classifier_confidence": "high" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_second_assignment_that_the_circuit_court_erred_b_5", + "description": "States in the second assignment that the circuit court erred by purporting to reverse the Board\u2019s rezoning decision.", + "source": "Florida law is unequivocal that when a circuit court finds error in a local government\u2019s quasi-judicial land use decision, its power is limited to quashing the decision and remanding the matter \u201cas if no order had been entered.\u201d Broward County v. G.B.V. Int\u2019l, Ltd., 787 So. 2d 838, 845 (Fla. 2001) (\u201cWhen a circuit court grants certiorari relief, it quashes the order and leaves the matter pending before the lower tribunal as if no order had been entered.\u201d). https://caselaw.findlaw.com/court/fl-supreme-court/1495364.html#:~:text=When,entered,-%2E\nThe Board's decision is not reversed resulting in a denial, it is quashed resulting in a return to the status quo prior to the decision.", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cDraft a ready-to-file brief requesting second-tier review.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_second_assignment_that_the_circuit_court_erred_by_purporting_to_re", + "original_index": 36, + "classifier_reason": "Names second assignment", + "classifier_confidence": "high" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_second_assignment_that_the_circuit_court_s_erred_b", + "description": "States in the second assignment that the circuit court's erred by violating the separation of powers under Fla. Const. art. III, \u00a7 3, when it substituted its judgement for that of the Board in exercising its legislative functions.", + "source": "Fla. Const. art. III, \u00a7 3; https://www.flsenate.gov/laws/constitution#A2S03:~:text=The,herein\n\"The powers of the state government shall be divided into legislative, executive and judicial branches. No person belonging to one branch shall exercise any powers appertaining to either of the other branches unless expressly provided herein\"\nSee also Modlin v. City of Miami Beach, 201 So.2d 70 (Fla. 1967); https://law.justia.com/cases/florida/supreme-court/1967/34865-0.html#:~:text=liability%2E-,The,persons \n\"The distinction between legislative action, on the one hand, and executive and judicial action, on the other, is not difficult to define. It is sufficient for present purposes to say that the former is typically prospective and nondiscriminatory, whereas the latter operate retroactively and discriminatorily. In other words, legislative action prescribes a general rule for future operation, whereas judicial and executive action is typically concerned with applying the general rule to specific situations or persons.\"\nThis is a landmark FL supreme court case defining the separate functions of government.", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cDraft a ready-to-file brief requesting second-tier review.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_second_assignment_that_the_circuit_court_s_erred_by_violating_the", + "original_index": 37, + "classifier_reason": "Names second assignment", + "classifier_confidence": "high" + }, + "score": 30.0, + "polarity": "positive", + "raw_weight": 1.0 + } + ], + "answer_path": "/app/response2.md", + "answer_relative_path": "response2.md", + "is_followon": true, + "prev_answer_path": "/app/response1.md" +} diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/fixtures/rubric.json b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/fixtures/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..794c762a798f680cbf51c21412d0ffaf56e90b4a --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/fixtures/rubric.json @@ -0,0 +1,196 @@ +{ + "criteria": [ + { + "name": "identifies_in_the_second_assignment_that_the_appropriate_mechani", + "description": "Identifies in the second assignment that the appropriate mechanism to appeal the Order Granting Writ of Certiorari is a Petition for Writ of Certiorari to the 6th District Court of Appeals.", + "source": "Florida Rule of Appellate Procedure 9.030(b)(2)(B); https://rules.floridaappellate.com/rule-9-030/#:~:text=b%29-,Jurisdiction,capacity\n\"Jurisdiction of District Courts of Appeal.\n\"b) Jurisdiction of District Courts of Appeal.\n. . .\n(2) Certiorari Jurisdiction.8 The certiorari jurisdiction of district courts of appeal may be sought to review:\n(A) nonfinal orders of lower tribunals other than as prescribed by rule 9.130; or\n(B) final orders of circuit courts acting in their review capacity.\"\nSee also Map of Florida\u2019s Court Jurisdictions, available at https://flcourts-media.flcourts.gov/content/download/426177/file/ar-17-18-map-of-floridas-court-jurisdictions.pdf (last accessed Mar. 25, 2026)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cDraft a ready-to-file brief requesting second-tier review.\u201d", + "metadata": { + "review_flag": false, + "original_name": "identifies_in_the_second_assignment_that_the_appropriate_mechanism_to_appeal_the", + "original_index": 26, + "classifier_reason": "Names second assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_second_assignment_that_the_circuit_court_erred_by", + "description": "States in the second assignment that the circuit court erred by ignoring the competent substantial evidence on the record that supported the approval contrary to Dusseau v. Metro. Dade Cnty. Bd. of Cnty. Comm\u2019rs, 794 So.2d 1270 (Fla. 2001).", + "source": "Dusseau v. Metro. Dade Cnty. Bd. of Cnty. Comm\u2019rs, 794 So.2d 1270 (Fla. 2001), is the preeminent FL Supreme court case on the limited review of quasi-judicial. \nhttps://caselaw.findlaw.com/court/fl-supreme-court/1489002.html#:~:text=Notably,ended\n\"Notably, when applying the third prong, the court should review the record to determine simply whether the Commission's decision is supported by competent substantial evidence.\n\nWe reiterate that the \u201ccompetent substantial evidence\u201d standard cannot be used by a reviewing court as a mechanism for exerting covert control over the policy determinations and factual findings of the local agency. \u2002 Rather, this standard requires the reviewing court to defer to the agency's superior technical expertise and special vantage point in such matters. \u2002 The issue before the court is not whether the agency's decision is the \u201cbest\u201d decision or the \u201cright\u201d decision or even a \u201cwise\u201d decision, for these are technical and policy-based determinations properly within the purview of the agency. \u2002 The circuit court has no training or experience-and is inherently unsuited-to sit as a roving \u201csuper agency\u201d with plenary oversight in such matters.\n\nThe sole issue before the court on first-tier certiorari review is whether the agency's decision is lawful. \u2002 The court's task vis-a-vis the third prong of Vaillant is simple: \u2009The court must review the record to assess the evidentiary support for the agency's decision. \u2002 Evidence contrary to the agency's decision is outside the scope of the inquiry at this point, for the reviewing court above all cannot reweigh the \u201cpros and cons\u201d of conflicting evidence. \u2002 While contrary evidence may be relevant to the wisdom of the decision, it is irrelevant to the lawfulness of the decision. \u2002 As long as the record contains competent substantial evidence to support the agency's decision, the decision is presumed lawful and the court's job is ended.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cDraft a ready-to-file brief requesting second-tier review.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_second_assignment_that_the_circuit_court_erred_by_ignoring_the_com", + "original_index": 27, + "classifier_reason": "Names second assignment", + "classifier_confidence": "high" + }, + "score": 20.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_second_assignment_that_the_staff_report_recommendi", + "description": "States in the second assignment that the staff report recommending approval is competent substantial evidence that supports the Board's approval of the rezoning.", + "source": "City of Hialeah Gardens v. Miami-Dade Charter Found., Inc., 857 So.2d 202, 204-5 (Fla. 3d DCA 2003); https://caselaw.findlaw.com/court/fl-district-court-of-appeal/1254782.html#:~:text=Here%2C%20the,reached%2E%E2%80%9D\n\"Here, the testifying staff members utilized their professional experiences and personal observations, as well as Machado's application, site plan, and traffic study, as the basis for their testimony. \u2002 These record materials, along with the staff presentations, combined to provide evidence \u201csufficiently relevant and material that a reasonable mind would accept it as adequate to support the conclusion reached.\u201d", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cDraft a ready-to-file brief requesting second-tier review.\u201d The primary argument on appeal is that the court failed to apply the standard of review under Dusseau v. Metro. Dade Cnty. Bd. of Cnty. Comm\u2019rs, 794 So.2d 1270 (Fla. 2001), by ignoring the competent substantial evidence on the record that supported the Board's approval. Identifying the competent substantial evidence on the record supports this argument.", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_second_assignment_that_the_staff_report_recommending_approval_is_c", + "original_index": 28, + "classifier_reason": "Names second assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_second_assignment_that_expert_testimony_on_the_rec", + "description": "States in the second assignment that expert testimony on the record is competent substantial evidence that supports the Board's approval of the rezoning.", + "source": "City of Hialeah Gardens v. Miami-Dade Charter Found., Inc., 857 So.2d 202, 204-5 (Fla. 3d DCA 2003); https://caselaw.findlaw.com/court/fl-district-court-of-appeal/1254782.html#:~:text=Here%2C%20the,reached%2E%E2%80%9D\n\"Here, the testifying staff members utilized their professional experiences and personal observations, as well as Machado's application, site plan, and traffic study, as the basis for their testimony. \u2002 These record materials, along with the staff presentations, combined to provide evidence \u201csufficiently relevant and material that a reasonable mind would accept it as adequate to support the conclusion reached.\u201d", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cDraft a ready-to-file brief requesting second-tier review.\u201d The primary argument on appeal is that the court failed to apply the standard of review under Dusseau v. Metro. Dade Cnty. Bd. of Cnty. Comm\u2019rs, 794 So.2d 1270 (Fla. 2001), by ignoring the competent substantial evidence on the record that supported the Board's approval. Identifying the competent substantial evidence on the record supports this argument.", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_second_assignment_that_expert_testimony_on_the_record_is_competent", + "original_index": 29, + "classifier_reason": "Names second assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_second_assignment_that_the_hearing_examiner_s_reco", + "description": "States in the second assignment that the Hearing Examiner's recommendation of approval is competent substantial evidence that supports the Board's approval of the rezoning.", + "source": "City of Hialeah Gardens v. Miami-Dade Charter Found., Inc., 857 So.2d 202, 204-5 (Fla. 3d DCA 2003); https://caselaw.findlaw.com/court/fl-district-court-of-appeal/1254782.html#:~:text=Here%2C%20the,reached%2E%E2%80%9D\n\"Here, the testifying staff members utilized their professional experiences and personal observations, as well as Machado's application, site plan, and traffic study, as the basis for their testimony. \u2002 These record materials, along with the staff presentations, combined to provide evidence \u201csufficiently relevant and material that a reasonable mind would accept it as adequate to support the conclusion reached.\u201d", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cDraft a ready-to-file brief requesting second-tier review.\u201d The primary argument on appeal is that the court failed to apply the standard of review under Dusseau v. Metro. Dade Cnty. Bd. of Cnty. Comm\u2019rs, 794 So.2d 1270 (Fla. 2001), by ignoring the competent substantial evidence on the record that supported the Board's approval. Identifying the competent substantial evidence on the record supports this argument.", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_second_assignment_that_the_hearing_examiner_s_recommendation_of_ap", + "original_index": 30, + "classifier_reason": "Names second assignment", + "classifier_confidence": "high" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_second_assignment_that_the_circuit_court_erred_b_2", + "description": "States in the second assignment that the circuit court erred by failing to apply the fairly debatable standard of review to the county's legislative decision to construct a water treatment plant on its own property.", + "source": "Martin County v. Yusem, 690 So. 2d 1288, 1295 (Fla. 1997), is the controlling FL supreme court case on the limited judicial review of local government legislative functions. https://caselaw.findlaw.com/court/fl-supreme-court/1459273.html#:~:text=-,The%20fairly,1996%29%2E\n \"The fairly debatable standard of review is a highly deferential standard requiring approval of a planning action if reasonable persons could differ as to its propriety.\"\nSee also Modlin v. City of Miami Beach, 201 So.2d 70 (Fla. 1967); https://law.justia.com/cases/florida/supreme-court/1967/34865-0.html#:~:text=liability%2E-,The,persons \n\"The distinction between legislative action, on the one hand, and executive and judicial action, on the other, is not difficult to define. It is sufficient for present purposes to say that the former is typically prospective and nondiscriminatory, whereas the latter operate retroactively and discriminatorily. In other words, legislative action prescribes a general rule for future operation, whereas judicial and executive action is typically concerned with applying the general rule to specific situations or persons.\"\nThis is a landmark FL supreme court case defining the separate functions of government.", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cDraft a ready-to-file brief requesting second-tier review.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_second_assignment_that_the_circuit_court_erred_by_failing_to_apply", + "original_index": 31, + "classifier_reason": "Names second assignment", + "classifier_confidence": "high" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_second_assignment_that_the_circuit_court_erred_in", + "description": "States in the second assignment that the circuit court erred in finding that communications with staff are ex parte communications pursuant to Lee County Fla. Land Development Code \u00a7 2-191 (2025).", + "source": "Lee County Fla. Land Development Code \u00a7 2-191 (2025); https://library.municode.com/fl/lee_county/codes/land_development_code?nodeId=LADECO_CH2AD_ARTVUNCO_S2-191PRLIUNCO#:~:text=This%20section%20does%20not%20prohibit%20the%20informational%20discussion%20of%20pending%20or%20proposed%20cases%20or%20appeals%20by%20and%20between%20a%20County%20Commissioner%20and%20any%20employee%20of%20the%20Board%20of%20County%20Commissioners%2E\n\"Unauthorized communications with a County Commissioner prohibited. . . . This section does not prohibit the informational discussion of pending or proposed cases or appeals by and between a County Commissioner and any employee of the Board of County Commissioners. \"\nSee also Fla. Stat \u00a7 286.0115(3) (2025); https://www.leg.state.fl.us/Statutes/index.cfm?App_mode=Display_Statute&URL=0200-0299/0286/Sections/0286.0115.html#:~:text=%283%29%E2%80%83This%20section%20does%20not%20restrict%20the%20authority%20of%20any%20board%20or%20commission%20to%20establish%20rules%20or%20procedures%20governing%20public%20hearings%20or%20contacts%20with%20local%20public%20officials\n\"286.0115\u2003Access to local public officials; quasi-judicial proceedings on local government land use matters.\u2014 (3)\u2003This section does not restrict the authority of any board or commission to establish rules or procedures governing public hearings or contacts with local public officials.", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cDraft a ready-to-file brief requesting second-tier review.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_second_assignment_that_the_circuit_court_erred_in_finding_that_com", + "original_index": 32, + "classifier_reason": "Names second assignment", + "classifier_confidence": "high" + }, + "score": 20.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_second_assignment_that_the_circuit_court_erred_b_3", + "description": "States in the second assignment that the circuit court erred by failing to apply the fairly debatable standard of review to the county's legislative decision to enter into the Kingston Settlement to resolve pending litigation.", + "source": "Martin County v. Yusem, 690 So. 2d 1288, 1295 (Fla. 1997), is the controlling FL supreme court case on the limited judicial review of local government legislative functions. https://caselaw.findlaw.com/court/fl-supreme-court/1459273.html#:~:text=-,The%20fairly,1996%29%2E\n \"The fairly debatable standard of review is a highly deferential standard requiring approval of a planning action if reasonable persons could differ as to its propriety.\"\nSee also Modlin v. City of Miami Beach, 201 So.2d 70 (Fla. 1967); https://law.justia.com/cases/florida/supreme-court/1967/34865-0.html#:~:text=liability%2E-,The,persons \n\"The distinction between legislative action, on the one hand, and executive and judicial action, on the other, is not difficult to define. It is sufficient for present purposes to say that the former is typically prospective and nondiscriminatory, whereas the latter operate retroactively and discriminatorily. In other words, legislative action prescribes a general rule for future operation, whereas judicial and executive action is typically concerned with applying the general rule to specific situations or persons.\"\nThis is a landmark FL supreme court case defining the separate functions of government.\nSee also Williams v. Public Util. Protective League, 178 So. 286 (Fla. 1938); https://hallapproved.com/fl/cases/supreme/1938/3402391/#:~:text=As%20an,inadequate\n\"As an abstract proposition of law, the power of the City to compromise, settle, and compose litigation of any kind to which it is a party is an incident to and implied from its power to sue and be sued. Like the power to legislate and negotiate it will not be restrained from exercising such power by a court of equity on a mere showing of belief, fear, or apprehension that some wrong or injury will be done, or when the injury is conjectural or speculative. Relief under such circumstances will be granted only in cases where the pleadings and the proof show clearly that the resulting injury will be irreparable and the remedy at law inadequate.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cDraft a ready-to-file brief requesting second-tier review.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_second_assignment_that_the_circuit_court_erred_by_failing_to_apply_2", + "original_index": 33, + "classifier_reason": "Names second assignment", + "classifier_confidence": "high" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_second_assignment_that_the_circuit_court_erred_b_4", + "description": "States in the second assignment that the circuit court erred by finding that Fed. Aviation Admin., Advisory Circular No. 150/5190-7, Minimum Standards for Commercial Aeronautical Activities (Dec. 7, 2023), is incorporated into Lee County Fla. Land Development Code \u00a7 34-1102 (2025).", + "source": "The circuit court found that the County had failed to comply with Fed. Aviation Admin., Advisory Circular 150/5190-7 Minimum Standards for Commercial Aeronautical Activities (Dec. 7, 2023) requirements for airport compatibility, concluding that the most current and restrictive regulations should have been fully considered. This was legal error. Lee County, Fla. Land Development Code \u00a7 34-1102 (2025) incorporates only Fed. Aviation Admin., Advisory Circular No. 150/5300-13B, Airport Design (2022) and 150/5200-30D Airport Field Condition Assessments and Winter Operations Safety (July 29, 2016), not Fed. Aviation Admin., Advisory CircularNo. 150/5190-7, Minimum Standards for Commercial Aeronautical Activities (Dec. 7, 2023), which the order treats as controlling. Lee County, Fla. Land Development Code \u00a7 34-1102 (2025); https://library.municode.com/fl/lee_county/codes/land_development_code?nodeId=LADECO_CH34ZO_ARTVIDIRE_DIV12AICODI_S34-1102PUIN\n\"The purpose of this division is to establish protections around SWFIA and Page Field in accordance with the provisions of F.S. Chs. 330 and 333, as amended, as well as Federal regulations, as amended, including 14 CFR Parts 77, 150 and 151 and FAA Advisory Circulars 150/5300-13A, as amended, renumbered or replaced, and 150/5200-33B, as amended, renumbered or replaced, which address height obstructions, airport hazards, wildlife attractants, noise, runway protection zones, light emissions, reflectivity and power interference, aircraft overflights, and the public investment in air transportation facilities.\"", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cDraft a ready-to-file brief requesting second-tier review.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_second_assignment_that_the_circuit_court_erred_by_finding_that_fed", + "original_index": 34, + "classifier_reason": "Names second assignment", + "classifier_confidence": "high" + }, + "score": 20.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_second_assignment_that_the_circuit_court_erred_i_2", + "description": "States in the second assignment that the circuit court erred in treating Federal Aviation Authority Advisory Circulars as binding law.", + "source": "Fed. Aviation Admin., Advisory Circular No. 150/5190-4B, Airport Land Use Compatibility Planning (Sept. 16, 2022) at page 2 confirms that \u201cThis AC does not constitute a regulation, and is not legally binding in its own right\u2026 Conformity with this AC is voluntary, and nonconformity will not affect rights and obligations under existing statutes and regulations,\u201d https://www.faa.gov/documentLibrary/media/Advisory_Circular/150_5190_4b_Land_Use_Compatibility.pdf", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cDraft a ready-to-file brief requesting second-tier review.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_second_assignment_that_the_circuit_court_erred_in_treating_federal", + "original_index": 35, + "classifier_reason": "Names second assignment", + "classifier_confidence": "high" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_second_assignment_that_the_circuit_court_erred_b_5", + "description": "States in the second assignment that the circuit court erred by purporting to reverse the Board\u2019s rezoning decision.", + "source": "Florida law is unequivocal that when a circuit court finds error in a local government\u2019s quasi-judicial land use decision, its power is limited to quashing the decision and remanding the matter \u201cas if no order had been entered.\u201d Broward County v. G.B.V. Int\u2019l, Ltd., 787 So. 2d 838, 845 (Fla. 2001) (\u201cWhen a circuit court grants certiorari relief, it quashes the order and leaves the matter pending before the lower tribunal as if no order had been entered.\u201d). https://caselaw.findlaw.com/court/fl-supreme-court/1495364.html#:~:text=When,entered,-%2E\nThe Board's decision is not reversed resulting in a denial, it is quashed resulting in a return to the status quo prior to the decision.", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cDraft a ready-to-file brief requesting second-tier review.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_second_assignment_that_the_circuit_court_erred_by_purporting_to_re", + "original_index": 36, + "classifier_reason": "Names second assignment", + "classifier_confidence": "high" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "states_in_the_second_assignment_that_the_circuit_court_s_erred_b", + "description": "States in the second assignment that the circuit court's erred by violating the separation of powers under Fla. Const. art. III, \u00a7 3, when it substituted its judgement for that of the Board in exercising its legislative functions.", + "source": "Fla. Const. art. III, \u00a7 3; https://www.flsenate.gov/laws/constitution#A2S03:~:text=The,herein\n\"The powers of the state government shall be divided into legislative, executive and judicial branches. No person belonging to one branch shall exercise any powers appertaining to either of the other branches unless expressly provided herein\"\nSee also Modlin v. City of Miami Beach, 201 So.2d 70 (Fla. 1967); https://law.justia.com/cases/florida/supreme-court/1967/34865-0.html#:~:text=liability%2E-,The,persons \n\"The distinction between legislative action, on the one hand, and executive and judicial action, on the other, is not difficult to define. It is sufficient for present purposes to say that the former is typically prospective and nondiscriminatory, whereas the latter operate retroactively and discriminatorily. In other words, legislative action prescribes a general rule for future operation, whereas judicial and executive action is typically concerned with applying the general rule to specific situations or persons.\"\nThis is a landmark FL supreme court case defining the separate functions of government.", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cDraft a ready-to-file brief requesting second-tier review.\u201d", + "metadata": { + "review_flag": false, + "original_name": "states_in_the_second_assignment_that_the_circuit_court_s_erred_by_violating_the", + "original_index": 37, + "classifier_reason": "Names second assignment", + "classifier_confidence": "high" + }, + "score": 30.0, + "polarity": "positive", + "raw_weight": 1.0 + } + ] +} diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/m1_judge_panel.json b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/m1_judge_panel.json new file mode 100644 index 0000000000000000000000000000000000000000..a8041f6781a899f9083fe4a1a95f51bc78d35601 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/m1_judge_panel.json @@ -0,0 +1,21 @@ +{ + "mode": "panel", + "max_concurrent_llm": 12, + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ] +} diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/m1_rewardkit_accounting.py b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/m1_rewardkit_accounting.py new file mode 100644 index 0000000000000000000000000000000000000000..406dc5e7c675b222d94514e71bf5fad6ae141d8f --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/m1_rewardkit_accounting.py @@ -0,0 +1,490 @@ +import asyncio +import json +import math +import os +from pathlib import Path +import random +import sys +import time + +class JudgeReceiptError(OSError): + pass +_LLM_ROUTES = frozenset({'vertex', 'anthropic fallback', 'aistudio', 'direct'}) +_LLM_ROUTE_HEADERS = ('x-m1-llm-route', 'llm_provider-x-m1-llm-route') + +def _canonical_llm_route(value): + return value if isinstance(value, str) and value in _LLM_ROUTES else None + +def _llm_route_from_headers(headers): + if not isinstance(headers, dict): + return None + folded = {str(key).lower(): value for key, value in headers.items()} + for name in _LLM_ROUTE_HEADERS: + route = _canonical_llm_route(folded.get(name)) + if route is not None: + return route + return None + +def _llm_route_from_response(response): + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + route = _llm_route_from_headers(headers) + if route is not None: + return route + return _llm_route_from_headers(getattr(response, 'headers', None)) + +def _token_field_status(values, key): + if not isinstance(values, dict) or key not in values: + return 'missing' + value = values[key] + if value is None: + return 'null' + return 'valid' if type(value) is int and value >= 0 else 'invalid' + +def _gemini_capture(kwargs, model): + if not model.startswith('gemini/') or kwargs.get('stream') or kwargs.get('tools') or kwargs.get('functions'): + return (kwargs, None) + from litellm.integrations.custom_logger import CustomLogger + from urllib.parse import urlsplit + + class Capture(CustomLogger): + evidence = None + prompt_status = 'not_observed' + llm_route = None + + def log_post_api_call(self, kwargs, response_obj, start_time, end_time): + self.evidence = None + self.prompt_status = 'not_observed' + try: + params = kwargs.get('litellm_params') or {} + route = urlsplit(params.get('api_base') or '') + bare = model.removeprefix('gemini/') + gemini = params.get('custom_llm_provider') == 'gemini' + ai_studio = gemini and route.hostname == 'generativelanguage.googleapis.com' and (route.path in {'/' + version + '/models/' + bare + ':generateContent' for version in ('v1alpha', 'v1beta')}) + broker = urlsplit(os.environ.get('GEMINI_API_BASE') or '') + brokered = gemini and bool(broker.netloc) and (route.netloc == broker.netloc) and (broker.path.rstrip('/').rsplit('/', 1)[-1] in ('v1alpha', 'v1beta')) and (route.path == broker.path.rstrip('/') + '/models/' + bare + ':generateContent') + vertex = params.get('custom_llm_provider') == 'vertex_ai' and route.hostname == 'aiplatform.googleapis.com' and route.path.startswith('/v1/projects/') and route.path.endswith('/locations/global/publishers/google/models/' + bare + ':generateContent') + if route.scheme != 'https' or not (ai_studio or brokered or vertex) or kwargs.get('stream'): + return + self.llm_route = 'vertex' if vertex else 'aistudio' if ai_studio else None + raw = kwargs.get('original_response') + raw = json.loads(raw) if isinstance(raw, str) else raw + if not isinstance(raw, dict): + return + candidates = raw.get('candidates') + if not isinstance(candidates, list) or not candidates or any((not isinstance(c, dict) or not c.get('finishReason') for c in candidates)) or (not isinstance(raw.get('modelVersion'), str)) or (not raw['modelVersion']): + return + usage = raw.get('usageMetadata') + self.prompt_status = _token_field_status(usage, 'promptTokenCount') + if not isinstance(usage, dict): + return + fields = ('promptTokenCount', 'candidatesTokenCount', 'thoughtsTokenCount', 'cachedContentTokenCount', 'totalTokenCount', 'toolUsePromptTokenCount') + counts = {key: usage.get(key, 0) for key in fields} + if not {'promptTokenCount', 'totalTokenCount'} <= usage.keys() or any((type(n) is not int or n < 0 for n in counts.values())) or counts['toolUsePromptTokenCount'] != 0 or (counts['cachedContentTokenCount'] > counts['promptTokenCount']) or (counts['totalTokenCount'] != counts['promptTokenCount'] + counts['candidatesTokenCount'] + counts['thoughtsTokenCount']): + return + self.evidence = {'protocol': 'gemini-generate-content-' + ('vertex-v1' if vertex else route.path.split('/')[-3]), 'model_version': raw['modelVersion'], 'usage_metadata': {key: usage[key] for key in fields if key in usage}, 'defaulted_fields': [key for key in fields if key not in usage]} + except (TypeError, ValueError, AttributeError): + return + capture = Capture() + return ({**kwargs, 'callbacks': [*(kwargs.get('callbacks') or []), capture]}, capture) + +def _record_judge_usage(response, model: str, *, target: Path | None=None, native_usage: dict | None=None, native_prompt_status: str | None=None, llm_route: str | None=None) -> None: + import fcntl + from datetime import datetime, timezone + data = response.model_dump() if hasattr(response, 'model_dump') else response + usage = data.get('usage') if isinstance(data, dict) else None + granularity = data.get('usage_granularity') if isinstance(data, dict) else None + if not isinstance(usage, dict): + usage = {} + granularity = 'missing_provider_receipt' + prompt, completion = (usage.get('prompt_tokens'), usage.get('completion_tokens')) + native_fresh = usage.get('input_uncached_tokens') + prompt = prompt if type(prompt) is int and prompt >= 0 else None + native_fresh = native_fresh if type(native_fresh) is int and native_fresh >= 0 else None + if type(completion) is not int or completion < 0 or (prompt is None and native_fresh is None): + completion = completion if type(completion) is int and completion >= 0 else 0 + granularity = granularity or 'invalid_provider_receipt' + details = usage.get('prompt_tokens_details') + if details is not None and (not isinstance(details, dict)): + granularity = 'invalid_provider_receipt' + details = details if isinstance(details, dict) else {} + cached = details.get('cached_tokens') + if native_usage is not None: + native = native_usage['usage_metadata'] + native_output = native.get('candidatesTokenCount', 0) + native.get('thoughtsTokenCount', 0) + if prompt == native['promptTokenCount'] and completion == native_output: + cached = native.get('cachedContentTokenCount', 0) + else: + native_usage = None + written = next((value for value in (usage.get('input_cache_write_tokens'), usage.get('cache_creation_input_tokens'), details.get('cache_creation_tokens'), details.get('cache_write_tokens')) if value is not None), None) + invalid = any((value is not None and (type(value) is not int or value < 0) for value in (cached, written))) + cached = cached if type(cached) is int and cached >= 0 else None + written = written if type(written) is int and written >= 0 else None + fresh = native_fresh + if fresh is None and prompt is not None and (cached is not None) and (written is not None): + fresh = prompt - cached - written + if fresh is not None and (fresh < 0 or (prompt is not None and cached is not None and (written is not None) and (fresh + cached + written != prompt))): + invalid, fresh = (True, None) + provider, _, slug = model.partition('/') + event: dict = {'type': 'step_finish', 'part': {'providerID': provider if slug else 'openai', 'modelID': slug or model, 'tokens': {'input': fresh, 'output': completion, 'cache': {'read': cached, 'write': written}}}} + field_status = {'prompt_tokens': _token_field_status(usage, 'prompt_tokens'), 'completion_tokens': _token_field_status(usage, 'completion_tokens'), 'input_uncached_tokens': _token_field_status(usage, 'input_uncached_tokens')} + field_status['native_prompt_token_count'] = native_prompt_status if native_prompt_status in {'missing', 'null', 'invalid', 'valid', 'not_observed'} else 'unsupported' + part: dict = event['part'] + part['usage_field_status'] = field_status + if native_usage is not None: + event['part']['native_usage'] = native_usage + event['part']['token_categories_provenance'] = 'explicit_presence_v1' + if fresh is None and prompt is not None: + event['part']['prompt_tokens_inclusive'] = prompt + if invalid or any((value is None for value in (fresh, cached, written))): + granularity = granularity if granularity not in (None, 'request') else 'invalid_provider_receipt' if invalid else 'incomplete_token_categories' + if granularity: + event['part']['usage_granularity'] = granularity + if provider == 'openrouter': + cost = usage.get('cost') + if cost is None: + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + if isinstance(headers, dict): + cost = headers.get('llm_provider-x-litellm-response-cost') + if isinstance(cost, (int, float)) and (not isinstance(cost, bool)) and math.isfinite(cost) and (cost >= 0): + event['part']['cost'] = cost + data = data if isinstance(data, dict) else {} + if isinstance(data.get('id'), str) and data['id']: + event['part']['provider_request_id'] = data['id'] + for key in ('service_tier', 'cache_ttl'): + if data.get(key): + event['part'][key] = data[key] + route = _llm_route_from_response(response) or _canonical_llm_route(llm_route) + if route is not None: + event['part']['llm_route'] = route + created = data.get('created') + stamp = datetime.now(timezone.utc) + try: + if isinstance(created, str): + parsed = datetime.fromisoformat(created.replace('Z', '+00:00')) + if parsed.tzinfo is not None: + stamp = parsed + elif isinstance(created, (int, float)) and (not isinstance(created, bool)) and math.isfinite(created): + stamp = datetime.fromtimestamp(created, timezone.utc) + except (ValueError, OverflowError, OSError): + pass + pair = json.dumps({'type': 'step_start', 'timestamp': stamp.isoformat()}) + '\n' + pair += json.dumps(event) + '\n' + try: + receipt_path = target or Path(os.environ.get('M1_JUDGE_USAGE_PATH', '/logs/verifier/judge-trajectory.jsonl')) + receipt_path.parent.mkdir(parents=True, exist_ok=True) + with receipt_path.open('a') as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + handle.write(pair) + handle.flush() + os.fsync(handle.fileno()) + except OSError as exc: + if target is not None: + raise JudgeReceiptError(f'judge receipt write failed: {exc}') from exc + print(f'judge accounting: write failed ({type(exc).__name__})', file=sys.stderr) + +def openrouter_judge_pins() -> dict[str, dict]: + raw = os.environ.get('M1_OPENROUTER_JUDGE_PROVIDER_PINS', '').strip() + if not raw: + return {} + try: + pins = json.loads(raw) + except json.JSONDecodeError: + print('judge provider pins: invalid JSON in M1_OPENROUTER_JUDGE_PROVIDER_PINS', file=sys.stderr) + return {} + return {model: pin for model, pin in pins.items() if isinstance(pin, dict) and pin.get('order')} if isinstance(pins, dict) else {} + +def apply_judge_provider_pin(kwargs: dict, pins: dict[str, dict]) -> dict: + model = kwargs.get('model') + pin = pins.get(model) if isinstance(model, str) else None + if pin is None: + return kwargs + extra_body = dict(kwargs.get('extra_body') or {}) + provider = dict(extra_body.get('provider') or {}) + provider['order'] = list(pin['order']) + if pin.get('allow_fallbacks') is False: + provider['allow_fallbacks'] = False + if pin.get('zdr'): + provider['zdr'] = True + extra_body['provider'] = provider + return {**kwargs, 'extra_body': extra_body} +_TRANSIENT_ERROR_NAMES = ('RateLimitError', 'ServiceUnavailableError', 'InternalServerError', 'BadGatewayError', 'APIConnectionError') +_RETRYABLE_STATUS_CODES = frozenset({408, 409, 425, 429, 500, 502, 503, 504}) +_AUTH_ERROR_NAMES = ('AuthenticationError', 'PermissionDeniedError') +_AUTH_STATUS_CODES = frozenset({401, 403}) +_AUTH_RETRIES = 4 +_DEFAULT_TRANSIENT_RETRIES = 6 +_MAX_TRANSIENT_RETRIES = 20 +_MAX_RETRY_DELAY_SECONDS = 60.0 +_DEFAULT_EMPTY_RESPONSE_RETRIES = 3 +_DEFAULT_RETRY_BUDGET_SECONDS = 900.0 +_MAX_RETRY_BUDGET_SECONDS = 86400.0 + +def transient_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_TRANSIENT_RETRIES', '').strip() + if not raw: + return _DEFAULT_TRANSIENT_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_TRANSIENT_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_TRANSIENT_RETRIES + +def empty_response_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_EMPTY_RESPONSE_RETRIES', '').strip() + if not raw: + return _DEFAULT_EMPTY_RESPONSE_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_EMPTY_RESPONSE_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_EMPTY_RESPONSE_RETRIES + +def retry_budget_seconds() -> float: + raw = os.environ.get('M1_JUDGE_RETRY_BUDGET_SECONDS', '').strip() + if not raw: + return _DEFAULT_RETRY_BUDGET_SECONDS + try: + value = float(raw) + except ValueError: + value = math.nan + if not math.isfinite(value) or value < 0: + print('judge retries: invalid M1_JUDGE_RETRY_BUDGET_SECONDS, using the default', file=sys.stderr) + return _DEFAULT_RETRY_BUDGET_SECONDS + return min(value, _MAX_RETRY_BUDGET_SECONDS) + +def _within_budget(deadline: float, delay: float, model) -> bool: + remaining = deadline - time.monotonic() + if delay <= remaining: + return True + print(f'judge call retry budget spent: {model} would wait {delay:.1f}s with {max(remaining, 0.0):.1f}s left of M1_JUDGE_RETRY_BUDGET_SECONDS, failing now', file=sys.stderr) + return False + +def is_empty_verdict(response) -> bool: + data = response.model_dump() if hasattr(response, 'model_dump') else response + if not isinstance(data, dict): + return False + choices = data.get('choices') + if not isinstance(choices, list) or not choices: + return True + first = choices[0] + message = first.get('message') if isinstance(first, dict) else None + if not isinstance(message, dict): + return True + if message.get('tool_calls') or message.get('function_call'): + return False + content = message.get('content') + if isinstance(content, list): + content = ''.join((part.get('text') or '' for part in content if isinstance(part, dict))) + return not (isinstance(content, str) and content.strip()) + +def _matches(exc: BaseException, litellm, names: tuple[str, ...], statuses: frozenset[int]) -> bool: + classes = tuple((cls for cls in (getattr(litellm, name, None) for name in names) if isinstance(cls, type))) + if classes and isinstance(exc, classes): + return True + status = getattr(exc, 'status_code', None) + return type(status) is int and status in statuses + +def is_transient_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _TRANSIENT_ERROR_NAMES, _RETRYABLE_STATUS_CODES) + +def is_auth_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _AUTH_ERROR_NAMES, _AUTH_STATUS_CODES) + +def should_retry(exc: BaseException, litellm, attempt: int, limit: int) -> bool: + if attempt < limit and is_transient_error(exc, litellm): + return True + return attempt < min(limit, _AUTH_RETRIES) and is_auth_error(exc, litellm) + +def _retry_after_seconds(exc: BaseException) -> float | None: + headers = getattr(exc, 'headers', None) + if headers is None: + headers = getattr(getattr(exc, 'response', None), 'headers', None) + if headers is None: + return None + try: + raw = headers.get('retry-after') + if raw is None: + raw = headers.get('Retry-After') + value = float(raw) + except (AttributeError, TypeError, ValueError): + return None + return value if math.isfinite(value) and value >= 0 else None + +def retry_delay(exc: BaseException | None, attempt: int) -> float: + base = min(_MAX_RETRY_DELAY_SECONDS, 2.0 ** (attempt + 1)) + delay = base * (0.5 + random.random()) + retry_after = _retry_after_seconds(exc) if exc is not None else None + if retry_after is not None: + delay = max(delay, min(_MAX_RETRY_DELAY_SECONDS, retry_after)) + return delay + +def _note_retry(model, exc: BaseException, attempt: int, limit: int, delay: float) -> None: + status = getattr(exc, 'status_code', None) + print(f"judge call retry {attempt}/{limit}: {model} {type(exc).__name__} status={(status if type(status) is int else 'n/a')}, waiting {delay:.1f}s", file=sys.stderr) + +def _note_empty(model, response, attempt: int, limit: int, delay: float) -> None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + reason = None + if isinstance(data, dict) and isinstance(data.get('choices'), list) and data['choices']: + first = data['choices'][0] + reason = first.get('finish_reason') if isinstance(first, dict) else None + print(f'judge call retry {attempt}/{limit}: {model} empty verdict (finish_reason={reason}), waiting {delay:.1f}s', file=sys.stderr) + +def install(litellm, *, synchronous: bool=False) -> None: + pins = openrouter_judge_pins() + limit = transient_retry_limit() + empty_limit = empty_response_retry_limit() + deadline = time.monotonic() + retry_budget_seconds() + if synchronous: + original = litellm.completion + + def accounted(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = original(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + time.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + time.sleep(delay) + continue + return response + litellm.completion = accounted + return + original_async = litellm.acompletion + + async def accounted_async(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = await original_async(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + await asyncio.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + await asyncio.sleep(delay) + continue + return response + litellm.acompletion = accounted_async + +def record_agent_usage(attempt, *, model: str, provider: str) -> None: + records: dict[str, tuple[str, dict]] = {} + current_model = model + for filename in getattr(attempt, 'logs', []): + try: + with Path(filename).open() as stream: + for line in stream: + try: + event = json.loads(line) + except (ValueError, TypeError): + continue + if not isinstance(event, dict): + continue + message = event.get('message') or {} + if event.get('type') == 'assistant' and isinstance(message, dict) and isinstance(message.get('usage'), dict): + raw = message['usage'] + cached, written = (raw.get('cache_read_input_tokens'), raw.get('cache_creation_input_tokens')) + if all((type(value) is int and value >= 0 for value in (raw.get('input_tokens'), raw.get('output_tokens')))) and all((value is None or (type(value) is int and value >= 0) for value in (cached, written))): + receipt: dict = {'usage': {'input_uncached_tokens': raw['input_tokens'], 'prompt_tokens': raw['input_tokens'] + cached + written if cached is not None and written is not None else None, 'completion_tokens': raw['output_tokens'], 'prompt_tokens_details': {'cached_tokens': cached, 'cache_creation_tokens': written}}} + receipt['created'] = event.get('timestamp') + creation = raw.get('cache_creation') or {} + hour = creation.get('ephemeral_1h_input_tokens', 0) if isinstance(creation, dict) else 0 + if type(hour) is int and hour > 0: + if hour == written: + receipt['cache_ttl'] = '1h' + else: + receipt['usage_granularity'] = 'mixed_cache_ttl' + records[message.get('id') or json.dumps(raw, sort_keys=True)] = (message.get('model') or current_model, receipt) + payload = event.get('payload') or {} + if not isinstance(payload, dict): + continue + if event.get('type') == 'turn_context' and payload.get('model'): + current_model = payload['model'] + if event.get('type') == 'event_msg' and payload.get('type') == 'token_count': + info = payload.get('info') or {} + raw, total = (info.get('last_token_usage'), info.get('total_token_usage')) + if isinstance(raw, dict) and isinstance(total, dict) and all((type(raw.get(key)) is int and raw.get(key) >= 0 for key in ('input_tokens', 'output_tokens'))): + receipt = {'usage': {'prompt_tokens': raw.get('input_tokens'), 'input_uncached_tokens': raw.get('input_uncached_tokens'), 'input_cache_write_tokens': raw.get('input_cache_write_tokens'), 'completion_tokens': raw.get('output_tokens'), 'prompt_tokens_details': {'cached_tokens': raw.get('cached_input_tokens')}}} + receipt['created'] = event.get('timestamp') + records[json.dumps(total, sort_keys=True)] = (current_model, receipt) + except OSError: + continue + captured_input = captured_output = 0 + input_complete = True + for requested, receipt in records.values(): + requested = requested if '/' in requested else f'{provider}/{requested}' + _record_judge_usage(receipt, requested) + receipt_input = receipt['usage'].get('prompt_tokens') + if receipt_input is None: + input_complete = False + else: + captured_input += receipt_input + captured_output += receipt['usage'].get('completion_tokens') or 0 + total = getattr(attempt, 'usage', {}) or {} + if not records or (input_complete and total.get('input_tokens') != captured_input) or total.get('output_tokens') != captured_output: + _record_judge_usage({'usage': {'prompt_tokens': 0, 'completion_tokens': 0}, 'usage_granularity': 'incomplete_agent_receipts'}, model if '/' in model else f'{provider}/{model}') + +def install_rewardkit_agents() -> None: + import rewardkit.judges as judges + original = judges.get_agent + + def get_accounted_agent(judge, cwd=None): + backend = original(judge, cwd) + run = backend.run + + async def accounted_run(*args, **kwargs): + attempt = await run(*args, **kwargs) + record_agent_usage(attempt, model=judge.model or 'unknown', provider='anthropic' if judge.agent == 'claude-code' else 'openai') + return attempt + setattr(backend, 'run', accounted_run) + return backend + setattr(judges, 'get_agent', get_accounted_agent) +if __name__ == '__main__': + import litellm + if len(sys.argv) > 2 and sys.argv[1] == '--script': + import runpy + install(litellm, synchronous=True) + sys.argv = sys.argv[2:] + runpy.run_path(sys.argv[0], run_name='__main__') + else: + install(litellm) + install_rewardkit_agents() + if Path(__file__).with_name('m1_judge_panel.json').is_file(): + from m1_rewardkit_panel import install_panel + install_panel(Path(__file__).with_name('m1_judge_panel.json')) + if Path(__file__).with_name('m1_judge_jev.json').is_file(): + from m1_rewardkit_jev import install_jev + install_jev(Path(__file__).with_name('m1_judge_jev.json')) + from rewardkit.__main__ import main + main() diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/m1_rewardkit_panel.py b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/m1_rewardkit_panel.py new file mode 100644 index 0000000000000000000000000000000000000000..164cc2ae521cdd368c2e1749d7ed8fe09f4545eb --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/m1_rewardkit_panel.py @@ -0,0 +1,169 @@ +from __future__ import annotations +import asyncio +from contextvars import ContextVar +import json +import math +import os +import sys +from pathlib import Path +from typing import Any +import uuid +_request_audit: ContextVar[tuple[Path, list[str]] | None] = ContextVar('panel_request_audit', default=None) + +class PanelIncompleteError(RuntimeError): + pass + +def _audit_warning(exc: Exception, warnings: list[str]) -> None: + message = f'judge panel audit: diagnostic capture failed ({type(exc).__name__})' + if message not in warnings: + warnings.append(message) + print(message, file=sys.stderr) + +def _write_audit(path: Path, record: dict[str, Any], warnings: list[str], *, append: bool=False) -> None: + try: + text = json.dumps(record, allow_nan=False, default=str) + '\n' + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('a' if append else 'w') as stream: + stream.write(text) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + +def _binary(raw: Any) -> int: + if isinstance(raw, bool): + return int(raw) + if isinstance(raw, int | float) and math.isfinite(raw) and (raw in (0, 1)): + return int(raw) + if isinstance(raw, str): + value = raw.strip().lower() + if value in {'yes', 'true', '1'}: + return 1 + if value in {'no', 'false', '0'}: + return 0 + raise PanelIncompleteError('m1_judge_panel_incomplete: invalid binary vote') + +def validate_votes(scores: list[Any], criteria: list[Any]) -> None: + names = [criterion.name for criterion in criteria] + if len(set(names)) != len(names) or [score.name for score in scores] != names: + raise PanelIncompleteError('m1_judge_panel_incomplete: criterion membership mismatch') + for score, criterion in zip(scores, criteria, strict=True): + if score.error: + raise PanelIncompleteError('m1_judge_panel_incomplete: judge returned an error') + raw = _binary(score.raw) + expected = 1 - raw if criterion.negate else raw + if not math.isfinite(score.value) or score.value != expected: + raise PanelIncompleteError('m1_judge_panel_incomplete: inconsistent binary score') + +async def run_panel(judge: Any, criteria: list[Any], weights: list[float] | None, system_prompt: str | None, *, config: dict[str, Any], run_llm: Any, score_type: Any, audit_dir: Path) -> tuple[list[Any], str, list[str]]: + from rewardkit.models import Binary + if not criteria or any((not isinstance(criterion.output_format, Binary) for criterion in criteria)): + raise ValueError('panel majority voting requires nonempty binary criteria') + group_dir = audit_dir / uuid.uuid4().hex + warnings_out: list[str] = [] + + async def member_call(index: int, member: dict[str, Any]): + member_judge = judge.model_copy(update=member) + evidence: dict[str, Any] = {'member': index + 1, 'judge': member, 'criteria': [criterion.name for criterion in criteria], 'status': 'started'} + path = group_dir / f'judge-{index + 1}.json' + _write_audit(path, evidence, warnings_out) + token = _request_audit.set((group_dir / f'judge-{index + 1}-requests.jsonl', warnings_out)) + try: + scores, output, warnings = await run_llm(member_judge, criteria, weights, system_prompt) + evidence.update(output=output, warnings=warnings) + validate_votes(scores, criteria) + evidence['scores'] = [score.to_dict() for score in scores] + evidence['status'] = 'completed' + return (scores, output, warnings) + except BaseException as exc: + evidence.update(status='failed', error_class=type(exc).__name__) + if isinstance(exc, PanelIncompleteError): + evidence['error'] = str(exc) + raise + finally: + _request_audit.reset(token) + _write_audit(path, evidence, warnings_out) + outcomes = await asyncio.gather(*(member_call(index, member) for index, member in enumerate(config['members'])), return_exceptions=True) + failed = [index + 1 for index, result in enumerate(outcomes) if isinstance(result, BaseException)] + if failed: + _write_audit(group_dir / 'panel.json', {'status': 'incomplete', 'failed_members': failed}, warnings_out) + raise PanelIncompleteError(f'm1_judge_panel_incomplete: failed members {failed}; see panel audit artifacts') + completed = [outcome for outcome in outcomes if not isinstance(outcome, BaseException)] + combined = [] + for index, criterion in enumerate(criteria): + votes = [{'judge': config['members'][member_index], **outcome[0][index].to_dict()} for member_index, outcome in enumerate(completed)] + passes = sum((vote['value'] == 1 for vote in votes)) + value = int(passes >= 2) + combined.append(score_type(name=criterion.name, value=value, raw=bool(1 - value if criterion.negate else value), weight=weights[index] if weights is not None else 1.0, reasoning=f'{passes}/3 judges passed; strict majority requires 2/3.', description=criterion.description, id=criterion.id, negate=criterion.negate, optional=criterion.optional, votes=votes)) + for outcome in completed: + warnings_out.extend(outcome[2]) + audit = {'status': 'completed', 'mode': 'panel', 'aggregation': 'majority', 'required_votes': 2, 'members': config['members'], 'criteria': [score.to_dict() for score in combined]} + output = json.dumps(audit, indent=2, allow_nan=False) + _write_audit(group_dir / 'panel.json', audit, warnings_out) + return (combined, output, warnings_out) + +def install_panel(config_path: Path, *, audit_dir: Path=Path('/logs/verifier/judge-panel')) -> None: + import rewardkit.judges as judges + import rewardkit.reward as reward + from rewardkit.models import LLMJudge, Score + import litellm + config = json.loads(config_path.read_text()) + members = config.get('members') + concurrency = config.get('max_concurrent_llm') + if config.get('mode') != 'panel' or not isinstance(members, list) or len(members) != 3 or (len({member['model'] for member in members}) != 3) or (type(concurrency) is not int) or (not 1 <= concurrency <= 64): + raise ValueError('invalid materialized panel configuration') + if os.environ.get('REWARDKIT_JUDGE') or os.environ.get('REWARDKIT_MODEL'): + raise ValueError('RewardKit environment overrides cannot replace a frozen panel') + + class PanelScore(Score): + votes: list[dict[str, Any]] + + def to_dict(self): + return {**super().to_dict(), 'votes': self.votes} + original_llm = judges.arun_llm + original_call = judges._arun_llm_call + original_details = reward.Reward.to_detail_dict + original_completion = litellm.acompletion + active_loop = None + semaphore = None + + async def captured_completion(*args, **kwargs): + context = _request_audit.get() + record = {'requested_model': kwargs.get('model')} + response = None + try: + response = await original_completion(*args, **kwargs) + return response + except BaseException as exc: + record['error_class'] = type(exc).__name__ + raise + finally: + if context is not None: + path, warnings = context + try: + if response is not None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + record.update(response_model=data.get('model'), choices=data.get('choices')) + _write_audit(path, record, warnings, append=True) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + + async def bounded_call(*args, **kwargs): + nonlocal active_loop, semaphore + loop = asyncio.get_running_loop() + if active_loop is not loop: + active_loop, semaphore = (loop, asyncio.Semaphore(concurrency)) + assert semaphore is not None + async with semaphore: + return await original_call(*args, **kwargs) + + async def panel_call(judge, criteria, weights=None, system_prompt=None): + return await run_panel(judge, criteria, weights, system_prompt, config=config, run_llm=original_llm, score_type=PanelScore, audit_dir=audit_dir) + + def panel_details(self, score): + detail = original_details(self, score) + if isinstance(self.judge, LLMJudge): + detail.update(kind='llm_panel', judge=config, aggregation='majority', required_votes=2) + return detail + setattr(reward, 'arun_llm', panel_call) + setattr(judges, '_arun_llm_call', bounded_call) + setattr(litellm, 'acompletion', captured_completion) + reward.Reward.to_detail_dict = panel_details diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/normalize_reward.py b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/normalize_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..91817ef00ea9152ca57f0030d8e879eb850ddff0 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/normalize_reward.py @@ -0,0 +1,71 @@ +from __future__ import annotations +import argparse +import json +from pathlib import Path +from typing import Any + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument('--raw-details', required=True) + parser.add_argument('--rubric', required=True) + parser.add_argument('--reward-out', required=True) + parser.add_argument('--details-out', required=True) + args = parser.parse_args() + raw_details = _load_json(Path(args.raw_details)) + rubric = _load_json(Path(args.rubric)) + criteria = rubric['criteria'] + raw_by_name = _raw_criteria_by_name(raw_details) + positive_total = sum((float(item['score']) for item in criteria if float(item['score']) > 0)) + if positive_total <= 0: + raise ValueError('rubric must contain at least one positive score') + earned = 0.0 + normalized_criteria: list[dict[str, Any]] = [] + for item in criteria: + signed_score = float(item['score']) + raw = raw_by_name.get(item['name'], {}) + value = _coerce_score(raw.get('value', 0.0)) + contribution = value * signed_score + earned += contribution + normalized_criteria.append({'name': item['name'], 'value': value, 'raw': raw.get('raw'), 'weight': signed_score, 'signed_score': signed_score, 'polarity': item['polarity'], 'contribution': contribution, 'description': item['description'], 'source': item.get('source', ''), 'justification': item.get('justification', ''), 'metadata': item.get('metadata', {}), 'reasoning': raw.get('reasoning'), 'judge_reasoning': raw.get('reasoning'), 'judge_error': raw.get('error'), **({'votes': raw['votes']} if 'votes' in raw else {})}) + unclamped = earned / positive_total + reward = max(0.0, min(1.0, unclamped)) + reward_out = {'correctness': reward} + details_out = {'correctness': {'score': reward, 'kind': 'signed_score', 'criteria': normalized_criteria, 'aggregation': {'method': 'signed_score_ratio_clamped', 'earned': earned, 'positive_total': positive_total, 'unclamped': unclamped, 'clamped': reward}, 'raw_rewardkit': raw_details}} + _write_json(Path(args.reward_out), reward_out) + _write_json(Path(args.details_out), details_out) + +def _load_json(path: Path) -> Any: + return json.loads(path.read_text()) + +def _write_json(path: Path, data: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data, indent=2) + '\n') + +def _raw_criteria_by_name(details: dict[str, Any]) -> dict[str, dict[str, Any]]: + out: dict[str, dict[str, Any]] = {} + for reward in details.values(): + for item in _iter_raw_criteria(reward): + name = item.get('name') + if isinstance(name, str): + out[name] = item + return out + +def _iter_raw_criteria(value: Any): + if isinstance(value, list): + for item in value: + yield from _iter_raw_criteria(item) + return + if not isinstance(value, dict): + return + for item in value.get('criteria') or []: + if isinstance(item, dict): + yield item + +def _coerce_score(value: Any) -> float: + if isinstance(value, bool): + return 1.0 if value else 0.0 + if isinstance(value, int | float): + return max(0.0, min(1.0, float(value))) + return 0.0 +if __name__ == '__main__': + main() diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/agent_prompt.md b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/agent_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..ca489c065bafd5d10e764f033c9dfd1195933db3 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/agent_prompt.md @@ -0,0 +1,10 @@ +You are grading the submitted legal analysis against the criteria below. + +Read `/logs/artifacts/answer.md`, the answer captured by the verifier, before +assigning any scores. Evaluate that file as the submission. Other files in +`/app` may supply context, but must not replace the submitted answer. Do not +modify the submission. If it is missing or empty, state that in your reasoning +and apply the criteria to that missing or empty submission. Preserve each +criterion's stated positive or penalty polarity. + +{criteria} diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/identifies_in_the_second_assignment_that_the_appropriate_mechani.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/identifies_in_the_second_assignment_that_the_appropriate_mechani.toml new file mode 100644 index 0000000000000000000000000000000000000000..b3e1559ce81aad6021971932ad09c720fd064952 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/identifies_in_the_second_assignment_that_the_appropriate_mechani.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "identifies_in_the_second_assignment_that_the_appropriate_mechani" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies in the second assignment that the appropriate mechanism to appeal the Order Granting Writ of Certiorari is a Petition for Writ of Certiorari to the 6th District Court of Appeals." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_expert_testimony_on_the_rec.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_expert_testimony_on_the_rec.toml new file mode 100644 index 0000000000000000000000000000000000000000..a0a8cb020ecd20bd4ca5f146d50a49c9e1d3b153 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_expert_testimony_on_the_rec.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_second_assignment_that_expert_testimony_on_the_rec" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the second assignment that expert testimony on the record is competent substantial evidence that supports the Board's approval of the rezoning." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_circuit_court_erred_b_2.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_circuit_court_erred_b_2.toml new file mode 100644 index 0000000000000000000000000000000000000000..b6002360e423bd17f6d463c950c30cef928c8c82 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_circuit_court_erred_b_2.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_second_assignment_that_the_circuit_court_erred_b_2" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the second assignment that the circuit court erred by failing to apply the fairly debatable standard of review to the county's legislative decision to construct a water treatment plant on its own property." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_circuit_court_erred_b_3.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_circuit_court_erred_b_3.toml new file mode 100644 index 0000000000000000000000000000000000000000..5e0501eb7734921930cd8f0f1513ae6a6e53c0a9 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_circuit_court_erred_b_3.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_second_assignment_that_the_circuit_court_erred_b_3" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the second assignment that the circuit court erred by failing to apply the fairly debatable standard of review to the county's legislative decision to enter into the Kingston Settlement to resolve pending litigation." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_circuit_court_erred_b_4.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_circuit_court_erred_b_4.toml new file mode 100644 index 0000000000000000000000000000000000000000..9329d345ea45eeba977e3fc6a9361676948c8850 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_circuit_court_erred_b_4.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_second_assignment_that_the_circuit_court_erred_b_4" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the second assignment that the circuit court erred by finding that Fed. Aviation Admin., Advisory Circular No. 150/5190-7, Minimum Standards for Commercial Aeronautical Activities (Dec. 7, 2023), is incorporated into Lee County Fla. Land Development Code § 34-1102 (2025)." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_circuit_court_erred_b_5.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_circuit_court_erred_b_5.toml new file mode 100644 index 0000000000000000000000000000000000000000..d6e2c81bbb08376451b0cecc683a9c0f30bfefd4 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_circuit_court_erred_b_5.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_second_assignment_that_the_circuit_court_erred_b_5" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the second assignment that the circuit court erred by purporting to reverse the Board’s rezoning decision." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_circuit_court_erred_by.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_circuit_court_erred_by.toml new file mode 100644 index 0000000000000000000000000000000000000000..4d449bf94278d97bd81d2c874f652a27779c4fc7 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_circuit_court_erred_by.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_second_assignment_that_the_circuit_court_erred_by" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the second assignment that the circuit court erred by ignoring the competent substantial evidence on the record that supported the approval contrary to Dusseau v. Metro. Dade Cnty. Bd. of Cnty. Comm’rs, 794 So.2d 1270 (Fla. 2001)." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_circuit_court_erred_i_2.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_circuit_court_erred_i_2.toml new file mode 100644 index 0000000000000000000000000000000000000000..05a4894c6224bf0333703ad272b946751e0ce5cb --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_circuit_court_erred_i_2.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_second_assignment_that_the_circuit_court_erred_i_2" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the second assignment that the circuit court erred in treating Federal Aviation Authority Advisory Circulars as binding law." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_circuit_court_erred_in.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_circuit_court_erred_in.toml new file mode 100644 index 0000000000000000000000000000000000000000..bfab274ca8a701d0e404a92d1e9fa1be6047ac06 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_circuit_court_erred_in.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_second_assignment_that_the_circuit_court_erred_in" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the second assignment that the circuit court erred in finding that communications with staff are ex parte communications pursuant to Lee County Fla. Land Development Code § 2-191 (2025)." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_circuit_court_s_erred_b.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_circuit_court_s_erred_b.toml new file mode 100644 index 0000000000000000000000000000000000000000..00e5d0a97b1d28e399346864a707824a723cd792 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_circuit_court_s_erred_b.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_second_assignment_that_the_circuit_court_s_erred_b" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the second assignment that the circuit court's erred by violating the separation of powers under Fla. Const. art. III, § 3, when it substituted its judgement for that of the Board in exercising its legislative functions." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_hearing_examiner_s_reco.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_hearing_examiner_s_reco.toml new file mode 100644 index 0000000000000000000000000000000000000000..f370f86678140643066eef89c95237c3742f07aa --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_hearing_examiner_s_reco.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_second_assignment_that_the_hearing_examiner_s_reco" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the second assignment that the Hearing Examiner's recommendation of approval is competent substantial evidence that supports the Board's approval of the rezoning." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_staff_report_recommendi.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_staff_report_recommendi.toml new file mode 100644 index 0000000000000000000000000000000000000000..b79b2090022294aee419c3300b13e2a045dc3108 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/raw_correctness/states_in_the_second_assignment_that_the_staff_report_recommendi.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "states_in_the_second_assignment_that_the_staff_report_recommendi" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in the second assignment that the staff report recommending approval is competent substantial evidence that supports the Board's approval of the rezoning." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/test.sh b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..66a509a7bcdbe412851f3a012a5ba7b16cf0925b --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/steps/assignment-2/tests/test.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +set -euo pipefail + +mkdir -p /logs/artifacts /logs/verifier/raw + +python3 - <<'PYEOF' +import json +import shutil +from pathlib import Path + + +def has_text(path: Path) -> bool: + return path.exists() and path.is_file() and bool(path.read_text(errors="replace").strip()) + + +def fallback_paths(answer_path: Path) -> list[Path]: + paths = [] + try: + relative = answer_path.relative_to("/app") + paths.append(Path("/app/app") / relative) + except ValueError: + pass + return [path for path in paths if path != answer_path] + + +config = json.loads(Path("/tests/fixtures/config.json").read_text()) +answer_path = Path(config["answer_path"]) +artifact_answer = Path("/logs/artifacts/answer.md") +artifact_answer.parent.mkdir(parents=True, exist_ok=True) +if has_text(answer_path): + shutil.copyfile(answer_path, artifact_answer) +else: + for candidate in fallback_paths(answer_path): + if has_text(candidate): + shutil.copyfile(candidate, artifact_answer) + break + else: + artifact_answer.write_text("") + +# Harbor collects /logs/artifacts when the agent step ends, which is before this +# script runs, so the copy above never reaches the uploaded artifacts. /logs/verifier +# is uploaded after the verifier phase, so persist the graded answer there too. +verifier_answer = Path("/logs/verifier/answer.md") +verifier_answer.parent.mkdir(parents=True, exist_ok=True) +shutil.copyfile(artifact_answer, verifier_answer) +PYEOF + +uv run --no-project --with 'harbor-rewardkit[all]==0.2.0' python /tests/m1_rewardkit_accounting.py /tests/raw_correctness \ + --workspace /app \ + --output /logs/verifier/raw/reward.json \ + --max-concurrent-llm "${MAX_CONCURRENT_LLM:-4}" \ + --max-concurrent-agent "${M1_MAX_CONCURRENT_AGENT:-1}" + +python /tests/normalize_reward.py \ + --raw-details /logs/verifier/raw/reward-details.json \ + --rubric /tests/fixtures/rubric.json \ + --reward-out /logs/verifier/reward.json \ + --details-out /logs/verifier/reward-details.json diff --git a/tasks/lrb-certiorari-quasi-judicial-land-use/task.toml b/tasks/lrb-certiorari-quasi-judicial-land-use/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fef698a86626e1f9595c6598f1a73b48ac96c455 --- /dev/null +++ b/tasks/lrb-certiorari-quasi-judicial-land-use/task.toml @@ -0,0 +1,76 @@ +schema_version = "1.1" +multi_step_reward_strategy = "mean" + +[task] +name = "micro1/lrb-certiorari-quasi-judicial-land-use" + +[metadata] +benchmark = "LegalReasonBench" +title = "Petition for Writ of Certiorari for Quasi-judicial Proceeding" +practice_area = "Real estate and land use" +research_universe = "open-universe" +task_version = "7" +overall_reward = "points-weighted across assignments: sum of earned signed points over sum of positive points, clamped to [0, 1]. Harbor multi_step_reward_strategy=mean is diagnostic only. See scripts/score_matter.py." + +[agent] +timeout_sec = 10800.0 + +[environment] +build_timeout_sec = 900.0 +cpus = 2 +memory_mb = 4096 +storage_mb = 8192 +workdir = "/app" +allow_internet = true + +[environment.env] +OPENCODE_ENABLE_EXA = "${OPENCODE_ENABLE_EXA:-1}" + +[[steps]] +name = "assignment-1" +artifacts = ["/app/response1.md"] + +[steps.agent] +timeout_sec = 10800.0 + +[steps.verifier] +timeout_sec = 1800.0 + +[steps.verifier.env] +OPENAI_API_KEY = "${OPENAI_API_KEY:-}" +ANTHROPIC_API_KEY = "${ANTHROPIC_API_KEY:-}" +GOOGLE_API_KEY = "${GOOGLE_API_KEY:-}" +GEMINI_API_KEY = "${GEMINI_API_KEY:-}" +JUDGE_MODEL = "openai/gpt-5.6-terra" +JUDGE_REASONING_EFFORT = "medium" +JUDGE_TIMEOUT = "1500" +MAX_CONCURRENT_LLM = "12" +M1_MAX_CONCURRENT_AGENT = "1" +M1_JUDGE_TRANSIENT_RETRIES = "12" +M1_JUDGE_EMPTY_RESPONSE_RETRIES = "3" +M1_JUDGE_RETRY_BUDGET_SECONDS = "900" + +[[steps]] +name = "assignment-2" +artifacts = ["/app/response2.md"] + +[steps.agent] +timeout_sec = 10800.0 + +[steps.verifier] +timeout_sec = 1800.0 + +[steps.verifier.env] +OPENAI_API_KEY = "${OPENAI_API_KEY:-}" +ANTHROPIC_API_KEY = "${ANTHROPIC_API_KEY:-}" +GOOGLE_API_KEY = "${GOOGLE_API_KEY:-}" +GEMINI_API_KEY = "${GEMINI_API_KEY:-}" +JUDGE_MODEL = "openai/gpt-5.6-terra" +JUDGE_REASONING_EFFORT = "medium" +JUDGE_TIMEOUT = "1500" +MAX_CONCURRENT_LLM = "12" +M1_MAX_CONCURRENT_AGENT = "1" +M1_JUDGE_TRANSIENT_RETRIES = "12" +M1_JUDGE_EMPTY_RESPONSE_RETRIES = "3" +M1_JUDGE_RETRY_BUDGET_SECONDS = "900" + diff --git a/tasks/lrb-dcca-challenge-police-discipline/environment/Dockerfile b/tasks/lrb-dcca-challenge-police-discipline/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c481aae22685617adcf60d0de6e473ce9019975a --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/environment/Dockerfile @@ -0,0 +1,29 @@ +FROM python:3.13-slim-bookworm + +RUN apt-get update && apt-get install -y --no-install-recommends \ + bash \ + ca-certificates \ + curl \ + file \ + git \ + libreoffice-calc \ + libreoffice-impress \ + libreoffice-writer \ + pandoc \ + poppler-utils \ + unzip \ + fonts-dejavu \ + && rm -rf /var/lib/apt/lists/* + +RUN python -m pip install --no-cache-dir \ + uv \ + openpyxl \ + pandas \ + pdfplumber \ + pypdf \ + python-docx \ + python-pptx \ + xlrd + +WORKDIR /app +RUN ln -s . /app/app diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/instruction.md b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5c5b99f3480d8200da35bcef3349107461cefe00 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/instruction.md @@ -0,0 +1,54 @@ +# Viability of a DCCA Challenge — Record Mapping: Final Notice Against Award + +Domain: Litigation + +Matter: MPD v. PERB + +You are a senior legal analyst operating autonomously. You are completing a multi-step legal reasoning task. Follow the role, factual record, instructions, and deliverable requirements provided in the Task and each Assignment. + +Each Assignment may require a different legal deliverable. Follow the requirements specific to that Assignment. + +## Word limits for court briefs + +- A brief in support of or in response to a motion may not exceed **8,750 words**. +- A reply brief may not exceed **3,500 words**. +- For a motion for reconsideration, a brief in support of or in response to the motion may not exceed **3,500 words**, and a reply brief may not exceed **1,750 words**. +- If an Assignment specifies a stricter word limit, follow the stricter limit. + +These word limits do not apply to legal memoranda or other non-court-filing deliverables unless the Assignment expressly provides otherwise. + +Complete the task end-to-end without asking for confirmation, permission, or clarification. + +Use the uploaded matter documents in `/app/attachments/` as your primary case file. You also have internet access via OpenCode's `websearch` tool; use it to research any statutes, regulations, cases, administrative guidance, or secondary authorities that are not supplied as attachments. Cite any authority you rely on in the format requested by the prompt. + +For document inspection: +- PDF: `pdftotext /app/attachments/.pdf -` +- DOCX: `pandoc /app/attachments/.docx -t markdown` +- XLSX/CSV: use Python with `openpyxl` or `pandas` +- If extraction is unreliable, inspect the raw file with Python libraries or convert/render the relevant pages. + +Write the final complete legal deliverable for this assignment to `/app/response1.md`. The verifier reads only that file. + +## Attachments + +- `/app/attachments/final_notice_adverse_action_braddock.pdf` +- `/app/attachments/comparator_discipline_cases.pdf` +- `/app/attachments/braddock_arbitration_award.pdf` + + +## Prompt + +Our firm represents the District of Columbia Metropolitan Police Department (“MPD�). MPD terminated Officer Colin Braddock after its Internal Affairs Division and Use of Force Review Board found that he used excessive force in an off-duty shooting. On the evening of October 3, 2023, Braddock was at his home in Virginia when his car alarm went off. He saw a man, later identified as Devon Pryor, crouched beside his personal vehicle. Braddock went inside, retrieved his service pistol, and confronted Pryor without calling 911. Pryor, who had dropped his phone under the car while walking home and had hit his head on the frame while reaching for it, stumbled toward Braddock with his hands in his jacket pockets. Braddock fired twice, striking Pryor in the chest and shoulder. Pryor survived after three surgeries and eight months of treatment. MPD issued a Final Notice of Adverse Action on May 22, 2024, finding all twelve Douglas factors aggravating and terminating Braddock. Braddock grieved the termination. On March 14, 2025, an arbitrator reduced the penalty to a 45-day suspension based solely on his findings regarding Douglas factors six and twelve. The D.C. Public Employee Relations Board (“PERB�) affirmed the award in all respects on November 6, 2025. MPD wants to challenge the award at the District of Columbia Court of Appeals (“DCCA�) and has asked us to assess its options. You are the associate assigned to this matter. + +The following documents have been uploaded for this Step: +D.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117 (May 22, 2024) (final_notice_adverse_action_braddock.pdf) +In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf) +Memorandum from Yolanda Britt, Director, Disciplinary Review Division, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Sandra M. Delgado, Assistant Chief, Professional Development Bureau, re: Comparator Discipline Cases, Adverse Action Case No. IS-23-002841 (Braddock) (Apr. 11, 2024) (comparator_discipline_cases.pdf) + +The documents listed above constitute the complete and exclusive universe of materials for this Step. Limit your review to the attached documents. Do not rely on, reference, or infer any legal authority, factual information, or data beyond what is contained in these uploaded files. If a document is not uploaded, it does not exist for purposes of this analysis. All citations must reference the document by its exact name as listed above, followed by the page and paragraph number. Do not cite external websites, databases, or any source outside the uploaded materials. + +Complete the following: + +1. Reconstruct MPD’s penalty determination as set out in the Final Notice. For each of the twelve Douglas factors, state MPD’s finding and whether MPD treated the factor as aggravating or mitigating, citing the page and paragraph of the Final Notice that supports each answer. + +2. Identify every respect in which the Award departs from the Final Notice. For each departure, state the arbitrator’s finding, the standard of review the arbitrator stated he was applying, and the page and paragraph of the Award where each appears. State which Douglas factors the arbitrator left undisturbed. diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/solution/solve.sh b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7710414a6da6d0ad740717c8c85a9af850d5da33 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/solution/solve.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# No oracle solution ships with LegalReasonBench. The verifier grades the +# agent's own legal deliverable for this assignment against the rubric. +echo "no oracle solution" diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/fixtures/config.json b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/fixtures/config.json new file mode 100644 index 0000000000000000000000000000000000000000..60b4bee025057021b5f16d5415a67f239ca14d21 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/fixtures/config.json @@ -0,0 +1,168 @@ +{ + "task_id": "lrb-dcca-challenge-police-discipline", + "title": "Viability of a DCCA Challenge", + "domain": "Litigation", + "matter": "MPD v. PERB", + "judge": { + "max_concurrent_llm": 12, + "mode": "panel", + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ], + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + "step_index": 1, + "step_name": "assignment-1", + "step_title": "Record Mapping: Final Notice Against Award", + "prompt": "Our firm represents the District of Columbia Metropolitan Police Department (\u201cMPD\u201d). MPD terminated Officer Colin Braddock after its Internal Affairs Division and Use of Force Review Board found that he used excessive force in an off-duty shooting. On the evening of October 3, 2023, Braddock was at his home in Virginia when his car alarm went off. He saw a man, later identified as Devon Pryor, crouched beside his personal vehicle. Braddock went inside, retrieved his service pistol, and confronted Pryor without calling 911. Pryor, who had dropped his phone under the car while walking home and had hit his head on the frame while reaching for it, stumbled toward Braddock with his hands in his jacket pockets. Braddock fired twice, striking Pryor in the chest and shoulder. Pryor survived after three surgeries and eight months of treatment. MPD issued a Final Notice of Adverse Action on May 22, 2024, finding all twelve Douglas factors aggravating and terminating Braddock. Braddock grieved the termination. On March 14, 2025, an arbitrator reduced the penalty to a 45-day suspension based solely on his findings regarding Douglas factors six and twelve. The D.C. Public Employee Relations Board (\u201cPERB\u201d) affirmed the award in all respects on November 6, 2025. MPD wants to challenge the award at the District of Columbia Court of Appeals (\u201cDCCA\u201d) and has asked us to assess its options. You are the associate assigned to this matter.\n\nThe following documents have been uploaded for this Step:\nD.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117 (May 22, 2024) (final_notice_adverse_action_braddock.pdf)\nIn re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)\nMemorandum from Yolanda Britt, Director, Disciplinary Review Division, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Sandra M. Delgado, Assistant Chief, Professional Development Bureau, re: Comparator Discipline Cases, Adverse Action Case No. IS-23-002841 (Braddock) (Apr. 11, 2024) (comparator_discipline_cases.pdf)\n\nThe documents listed above constitute the complete and exclusive universe of materials for this Step. Limit your review to the attached documents. Do not rely on, reference, or infer any legal authority, factual information, or data beyond what is contained in these uploaded files. If a document is not uploaded, it does not exist for purposes of this analysis. All citations must reference the document by its exact name as listed above, followed by the page and paragraph number. Do not cite external websites, databases, or any source outside the uploaded materials.\n\nComplete the following:\n\n1. Reconstruct MPD\u2019s penalty determination as set out in the Final Notice. For each of the twelve Douglas factors, state MPD\u2019s finding and whether MPD treated the factor as aggravating or mitigating, citing the page and paragraph of the Final Notice that supports each answer.\n\n2. Identify every respect in which the Award departs from the Final Notice. For each departure, state the arbitrator\u2019s finding, the standard of review the arbitrator stated he was applying, and the page and paragraph of the Award where each appears. State which Douglas factors the arbitrator left undisturbed.", + "attachments": [ + { + "filename": "final_notice_adverse_action_braddock.pdf", + "description": "", + "metadata": {}, + "path": "/app/attachments/final_notice_adverse_action_braddock.pdf" + }, + { + "filename": "comparator_discipline_cases.pdf", + "description": "", + "metadata": {}, + "path": "/app/attachments/comparator_discipline_cases.pdf" + }, + { + "filename": "braddock_arbitration_award.pdf", + "description": "", + "metadata": {}, + "path": "/app/attachments/braddock_arbitration_award.pdf" + } + ], + "rubric": [ + { + "name": "criterion_1", + "description": "Mentions that the Final Notice of Adverse Action found all twelve Douglas factors to be aggravating.", + "source": "D.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117, \u00b6 26 (May 22, 2024) (final_notice_adverse_action_braddock.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReconstruct MPD\u2019s penalty determination as set out in the Final Notice. For each of the twelve Douglas factors, state MPD\u2019s finding and whether MPD treated the factor as aggravating or mitigating, citing the page and paragraph of the Final Notice that supports each answer.\u201d", + "metadata": { + "irac_section": "Issue" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_2", + "description": "Identifies that the four comparator cases relied on by MPD, specifically Guzman, Sadler, Pietrzak, and Voss, resulted in termination.", + "source": "Memorandum from Yolanda Britt, Director, Disciplinary Review Division, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Sandra M. Delgado, Assistant Chief, Professional Development Bureau, re: Comparator Discipline Cases, Adverse Action Case No. IS-23-002841 (Braddock), \u00b6\u00b6 2-5 (Apr. 11, 2024) (comparator_discipline_cases.pdf); D.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117, \u00b6 19 (May 22, 2024) (final_notice_adverse_action_braddock.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"1. Reconstruct MPD's penalty determination as set out in the Final Notice. For each of the twelve Douglas factors, state MPD's finding and whether MPD treated the factor as aggravating or mitigating, citing the page and paragraph of the Final Notice that supports each answer.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_3", + "description": "Mentions that the arbitrator sustained the finding of cause on the Conduct Unbecoming charge.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 4 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"2. Identify every respect in which the Award departs from the Final Notice. For each departure, state the arbitrator's finding, the standard of review the arbitrator stated he was applying, and the page and paragraph of the Award where each appears. State which Douglas factors the arbitrator left undisturbed.\"", + "metadata": { + "irac_section": "Conclusion" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_4", + "description": "States that the arbitrator reviewed MPD\u2019s penalty selection under a tolerable limits of reasonableness standard rather than de novo.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 5 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"2. Identify every respect in which the Award departs from the Final Notice. For each departure, state the arbitrator's finding, the standard of review the arbitrator stated he was applying, and the page and paragraph of the Award where each appears. State which Douglas factors the arbitrator left undisturbed.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 4.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_5", + "description": "States that the arbitrator overturned the finding of cause.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 4 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"2. Identify every respect in which the Award departs from the Final Notice. For each departure, state the arbitrator's finding, the standard of review the arbitrator stated he was applying, and the page and paragraph of the Award where each appears. State which Douglas factors the arbitrator left undisturbed.\" Misreading the scope of the arbitrator's departures poisons every later Step so the plausible misread is penalized here.", + "metadata": { + "irac_section": "Conclusion" + }, + "score": -20.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_6", + "description": "States that the arbitrator reduced the penalty based on a Douglas factor he left undisturbed.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6\u00b6 6-9 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"2. Identify every respect in which the Award departs from the Final Notice. For each departure, state the arbitrator's finding, the standard of review the arbitrator stated he was applying, and the page and paragraph of the Award where each appears. State which Douglas factors the arbitrator left undisturbed.\" A reduction attributed to an undisturbed factor is the plausible misread of the Award's structure.", + "metadata": { + "irac_section": "Application" + }, + "score": -16.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_7", + "description": "Identifies that the Award's citation to the Final Notice's findings of fact does not match the paragraphs where those findings appear.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 3 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf); D.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117, \u00b6\u00b6 4-11 (May 22, 2024) (final_notice_adverse_action_braddock.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"1. Reconstruct MPD's penalty determination as set out in the Final Notice. For each of the twelve Douglas factors, state MPD's finding and whether MPD treated the factor as aggravating or mitigating, citing the page and paragraph of the Final Notice that supports each answer.\" Reconstructing the factors against the actual paragraphs exposes the Award's miscitation.", + "metadata": { + "irac_section": "Application" + }, + "score": 30.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_8", + "description": "Identifies that the comparator memorandum's stated coverage years conflict with the dates of the cases it summarizes.", + "source": "Memorandum from Yolanda Britt, Director, Disciplinary Review Division, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Sandra M. Delgado, Assistant Chief, Professional Development Bureau, re: Comparator Discipline Cases, Adverse Action Case No. IS-23-002841 (Braddock), \u00b6\u00b6 1, 3 (Apr. 11, 2024) (comparator_discipline_cases.pdf); D.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117, \u00b6 19 (May 22, 2024) (final_notice_adverse_action_braddock.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"2. Identify every respect in which the Award departs from the Final Notice. For each departure, state the arbitrator's finding, the standard of review the arbitrator stated he was applying, and the page and paragraph of the Award where each appears. State which Douglas factors the arbitrator left undisturbed.\" The comparator memorandum's stated coverage window is part of the record the departures are mapped against.", + "metadata": { + "irac_section": "Issue" + }, + "score": 28.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_9", + "description": "Identifies that the arbitrator left Douglas factors one through five and seven through eleven undisturbed.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6\u00b6 6-9 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"2. Identify every respect in which the Award departs from the Final Notice. For each departure, state the arbitrator's finding, the standard of review the arbitrator stated he was applying, and the page and paragraph of the Award where each appears. State which Douglas factors the arbitrator left undisturbed.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + } + ], + "answer_path": "/app/response1.md", + "answer_relative_path": "response1.md", + "is_followon": false, + "prev_answer_path": "" +} diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/fixtures/rubric.json b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/fixtures/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..209ba602511c3a2c44d27e5e4c2c0a8d4f0d13b6 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/fixtures/rubric.json @@ -0,0 +1,112 @@ +{ + "criteria": [ + { + "name": "criterion_1", + "description": "Mentions that the Final Notice of Adverse Action found all twelve Douglas factors to be aggravating.", + "source": "D.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117, \u00b6 26 (May 22, 2024) (final_notice_adverse_action_braddock.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cReconstruct MPD\u2019s penalty determination as set out in the Final Notice. For each of the twelve Douglas factors, state MPD\u2019s finding and whether MPD treated the factor as aggravating or mitigating, citing the page and paragraph of the Final Notice that supports each answer.\u201d", + "metadata": { + "irac_section": "Issue" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_2", + "description": "Identifies that the four comparator cases relied on by MPD, specifically Guzman, Sadler, Pietrzak, and Voss, resulted in termination.", + "source": "Memorandum from Yolanda Britt, Director, Disciplinary Review Division, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Sandra M. Delgado, Assistant Chief, Professional Development Bureau, re: Comparator Discipline Cases, Adverse Action Case No. IS-23-002841 (Braddock), \u00b6\u00b6 2-5 (Apr. 11, 2024) (comparator_discipline_cases.pdf); D.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117, \u00b6 19 (May 22, 2024) (final_notice_adverse_action_braddock.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"1. Reconstruct MPD's penalty determination as set out in the Final Notice. For each of the twelve Douglas factors, state MPD's finding and whether MPD treated the factor as aggravating or mitigating, citing the page and paragraph of the Final Notice that supports each answer.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_3", + "description": "Mentions that the arbitrator sustained the finding of cause on the Conduct Unbecoming charge.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 4 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"2. Identify every respect in which the Award departs from the Final Notice. For each departure, state the arbitrator's finding, the standard of review the arbitrator stated he was applying, and the page and paragraph of the Award where each appears. State which Douglas factors the arbitrator left undisturbed.\"", + "metadata": { + "irac_section": "Conclusion" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_4", + "description": "States that the arbitrator reviewed MPD\u2019s penalty selection under a tolerable limits of reasonableness standard rather than de novo.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 5 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"2. Identify every respect in which the Award departs from the Final Notice. For each departure, state the arbitrator's finding, the standard of review the arbitrator stated he was applying, and the page and paragraph of the Award where each appears. State which Douglas factors the arbitrator left undisturbed.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 4.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_5", + "description": "States that the arbitrator overturned the finding of cause.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 4 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"2. Identify every respect in which the Award departs from the Final Notice. For each departure, state the arbitrator's finding, the standard of review the arbitrator stated he was applying, and the page and paragraph of the Award where each appears. State which Douglas factors the arbitrator left undisturbed.\" Misreading the scope of the arbitrator's departures poisons every later Step so the plausible misread is penalized here.", + "metadata": { + "irac_section": "Conclusion" + }, + "score": -20.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_6", + "description": "States that the arbitrator reduced the penalty based on a Douglas factor he left undisturbed.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6\u00b6 6-9 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"2. Identify every respect in which the Award departs from the Final Notice. For each departure, state the arbitrator's finding, the standard of review the arbitrator stated he was applying, and the page and paragraph of the Award where each appears. State which Douglas factors the arbitrator left undisturbed.\" A reduction attributed to an undisturbed factor is the plausible misread of the Award's structure.", + "metadata": { + "irac_section": "Application" + }, + "score": -16.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_7", + "description": "Identifies that the Award's citation to the Final Notice's findings of fact does not match the paragraphs where those findings appear.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 3 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf); D.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117, \u00b6\u00b6 4-11 (May 22, 2024) (final_notice_adverse_action_braddock.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"1. Reconstruct MPD's penalty determination as set out in the Final Notice. For each of the twelve Douglas factors, state MPD's finding and whether MPD treated the factor as aggravating or mitigating, citing the page and paragraph of the Final Notice that supports each answer.\" Reconstructing the factors against the actual paragraphs exposes the Award's miscitation.", + "metadata": { + "irac_section": "Application" + }, + "score": 30.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_8", + "description": "Identifies that the comparator memorandum's stated coverage years conflict with the dates of the cases it summarizes.", + "source": "Memorandum from Yolanda Britt, Director, Disciplinary Review Division, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Sandra M. Delgado, Assistant Chief, Professional Development Bureau, re: Comparator Discipline Cases, Adverse Action Case No. IS-23-002841 (Braddock), \u00b6\u00b6 1, 3 (Apr. 11, 2024) (comparator_discipline_cases.pdf); D.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117, \u00b6 19 (May 22, 2024) (final_notice_adverse_action_braddock.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"2. Identify every respect in which the Award departs from the Final Notice. For each departure, state the arbitrator's finding, the standard of review the arbitrator stated he was applying, and the page and paragraph of the Award where each appears. State which Douglas factors the arbitrator left undisturbed.\" The comparator memorandum's stated coverage window is part of the record the departures are mapped against.", + "metadata": { + "irac_section": "Issue" + }, + "score": 28.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_9", + "description": "Identifies that the arbitrator left Douglas factors one through five and seven through eleven undisturbed.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6\u00b6 6-9 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"2. Identify every respect in which the Award departs from the Final Notice. For each departure, state the arbitrator's finding, the standard of review the arbitrator stated he was applying, and the page and paragraph of the Award where each appears. State which Douglas factors the arbitrator left undisturbed.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + } + ] +} diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/m1_judge_panel.json b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/m1_judge_panel.json new file mode 100644 index 0000000000000000000000000000000000000000..a8041f6781a899f9083fe4a1a95f51bc78d35601 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/m1_judge_panel.json @@ -0,0 +1,21 @@ +{ + "mode": "panel", + "max_concurrent_llm": 12, + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ] +} diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/m1_rewardkit_accounting.py b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/m1_rewardkit_accounting.py new file mode 100644 index 0000000000000000000000000000000000000000..406dc5e7c675b222d94514e71bf5fad6ae141d8f --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/m1_rewardkit_accounting.py @@ -0,0 +1,490 @@ +import asyncio +import json +import math +import os +from pathlib import Path +import random +import sys +import time + +class JudgeReceiptError(OSError): + pass +_LLM_ROUTES = frozenset({'vertex', 'anthropic fallback', 'aistudio', 'direct'}) +_LLM_ROUTE_HEADERS = ('x-m1-llm-route', 'llm_provider-x-m1-llm-route') + +def _canonical_llm_route(value): + return value if isinstance(value, str) and value in _LLM_ROUTES else None + +def _llm_route_from_headers(headers): + if not isinstance(headers, dict): + return None + folded = {str(key).lower(): value for key, value in headers.items()} + for name in _LLM_ROUTE_HEADERS: + route = _canonical_llm_route(folded.get(name)) + if route is not None: + return route + return None + +def _llm_route_from_response(response): + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + route = _llm_route_from_headers(headers) + if route is not None: + return route + return _llm_route_from_headers(getattr(response, 'headers', None)) + +def _token_field_status(values, key): + if not isinstance(values, dict) or key not in values: + return 'missing' + value = values[key] + if value is None: + return 'null' + return 'valid' if type(value) is int and value >= 0 else 'invalid' + +def _gemini_capture(kwargs, model): + if not model.startswith('gemini/') or kwargs.get('stream') or kwargs.get('tools') or kwargs.get('functions'): + return (kwargs, None) + from litellm.integrations.custom_logger import CustomLogger + from urllib.parse import urlsplit + + class Capture(CustomLogger): + evidence = None + prompt_status = 'not_observed' + llm_route = None + + def log_post_api_call(self, kwargs, response_obj, start_time, end_time): + self.evidence = None + self.prompt_status = 'not_observed' + try: + params = kwargs.get('litellm_params') or {} + route = urlsplit(params.get('api_base') or '') + bare = model.removeprefix('gemini/') + gemini = params.get('custom_llm_provider') == 'gemini' + ai_studio = gemini and route.hostname == 'generativelanguage.googleapis.com' and (route.path in {'/' + version + '/models/' + bare + ':generateContent' for version in ('v1alpha', 'v1beta')}) + broker = urlsplit(os.environ.get('GEMINI_API_BASE') or '') + brokered = gemini and bool(broker.netloc) and (route.netloc == broker.netloc) and (broker.path.rstrip('/').rsplit('/', 1)[-1] in ('v1alpha', 'v1beta')) and (route.path == broker.path.rstrip('/') + '/models/' + bare + ':generateContent') + vertex = params.get('custom_llm_provider') == 'vertex_ai' and route.hostname == 'aiplatform.googleapis.com' and route.path.startswith('/v1/projects/') and route.path.endswith('/locations/global/publishers/google/models/' + bare + ':generateContent') + if route.scheme != 'https' or not (ai_studio or brokered or vertex) or kwargs.get('stream'): + return + self.llm_route = 'vertex' if vertex else 'aistudio' if ai_studio else None + raw = kwargs.get('original_response') + raw = json.loads(raw) if isinstance(raw, str) else raw + if not isinstance(raw, dict): + return + candidates = raw.get('candidates') + if not isinstance(candidates, list) or not candidates or any((not isinstance(c, dict) or not c.get('finishReason') for c in candidates)) or (not isinstance(raw.get('modelVersion'), str)) or (not raw['modelVersion']): + return + usage = raw.get('usageMetadata') + self.prompt_status = _token_field_status(usage, 'promptTokenCount') + if not isinstance(usage, dict): + return + fields = ('promptTokenCount', 'candidatesTokenCount', 'thoughtsTokenCount', 'cachedContentTokenCount', 'totalTokenCount', 'toolUsePromptTokenCount') + counts = {key: usage.get(key, 0) for key in fields} + if not {'promptTokenCount', 'totalTokenCount'} <= usage.keys() or any((type(n) is not int or n < 0 for n in counts.values())) or counts['toolUsePromptTokenCount'] != 0 or (counts['cachedContentTokenCount'] > counts['promptTokenCount']) or (counts['totalTokenCount'] != counts['promptTokenCount'] + counts['candidatesTokenCount'] + counts['thoughtsTokenCount']): + return + self.evidence = {'protocol': 'gemini-generate-content-' + ('vertex-v1' if vertex else route.path.split('/')[-3]), 'model_version': raw['modelVersion'], 'usage_metadata': {key: usage[key] for key in fields if key in usage}, 'defaulted_fields': [key for key in fields if key not in usage]} + except (TypeError, ValueError, AttributeError): + return + capture = Capture() + return ({**kwargs, 'callbacks': [*(kwargs.get('callbacks') or []), capture]}, capture) + +def _record_judge_usage(response, model: str, *, target: Path | None=None, native_usage: dict | None=None, native_prompt_status: str | None=None, llm_route: str | None=None) -> None: + import fcntl + from datetime import datetime, timezone + data = response.model_dump() if hasattr(response, 'model_dump') else response + usage = data.get('usage') if isinstance(data, dict) else None + granularity = data.get('usage_granularity') if isinstance(data, dict) else None + if not isinstance(usage, dict): + usage = {} + granularity = 'missing_provider_receipt' + prompt, completion = (usage.get('prompt_tokens'), usage.get('completion_tokens')) + native_fresh = usage.get('input_uncached_tokens') + prompt = prompt if type(prompt) is int and prompt >= 0 else None + native_fresh = native_fresh if type(native_fresh) is int and native_fresh >= 0 else None + if type(completion) is not int or completion < 0 or (prompt is None and native_fresh is None): + completion = completion if type(completion) is int and completion >= 0 else 0 + granularity = granularity or 'invalid_provider_receipt' + details = usage.get('prompt_tokens_details') + if details is not None and (not isinstance(details, dict)): + granularity = 'invalid_provider_receipt' + details = details if isinstance(details, dict) else {} + cached = details.get('cached_tokens') + if native_usage is not None: + native = native_usage['usage_metadata'] + native_output = native.get('candidatesTokenCount', 0) + native.get('thoughtsTokenCount', 0) + if prompt == native['promptTokenCount'] and completion == native_output: + cached = native.get('cachedContentTokenCount', 0) + else: + native_usage = None + written = next((value for value in (usage.get('input_cache_write_tokens'), usage.get('cache_creation_input_tokens'), details.get('cache_creation_tokens'), details.get('cache_write_tokens')) if value is not None), None) + invalid = any((value is not None and (type(value) is not int or value < 0) for value in (cached, written))) + cached = cached if type(cached) is int and cached >= 0 else None + written = written if type(written) is int and written >= 0 else None + fresh = native_fresh + if fresh is None and prompt is not None and (cached is not None) and (written is not None): + fresh = prompt - cached - written + if fresh is not None and (fresh < 0 or (prompt is not None and cached is not None and (written is not None) and (fresh + cached + written != prompt))): + invalid, fresh = (True, None) + provider, _, slug = model.partition('/') + event: dict = {'type': 'step_finish', 'part': {'providerID': provider if slug else 'openai', 'modelID': slug or model, 'tokens': {'input': fresh, 'output': completion, 'cache': {'read': cached, 'write': written}}}} + field_status = {'prompt_tokens': _token_field_status(usage, 'prompt_tokens'), 'completion_tokens': _token_field_status(usage, 'completion_tokens'), 'input_uncached_tokens': _token_field_status(usage, 'input_uncached_tokens')} + field_status['native_prompt_token_count'] = native_prompt_status if native_prompt_status in {'missing', 'null', 'invalid', 'valid', 'not_observed'} else 'unsupported' + part: dict = event['part'] + part['usage_field_status'] = field_status + if native_usage is not None: + event['part']['native_usage'] = native_usage + event['part']['token_categories_provenance'] = 'explicit_presence_v1' + if fresh is None and prompt is not None: + event['part']['prompt_tokens_inclusive'] = prompt + if invalid or any((value is None for value in (fresh, cached, written))): + granularity = granularity if granularity not in (None, 'request') else 'invalid_provider_receipt' if invalid else 'incomplete_token_categories' + if granularity: + event['part']['usage_granularity'] = granularity + if provider == 'openrouter': + cost = usage.get('cost') + if cost is None: + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + if isinstance(headers, dict): + cost = headers.get('llm_provider-x-litellm-response-cost') + if isinstance(cost, (int, float)) and (not isinstance(cost, bool)) and math.isfinite(cost) and (cost >= 0): + event['part']['cost'] = cost + data = data if isinstance(data, dict) else {} + if isinstance(data.get('id'), str) and data['id']: + event['part']['provider_request_id'] = data['id'] + for key in ('service_tier', 'cache_ttl'): + if data.get(key): + event['part'][key] = data[key] + route = _llm_route_from_response(response) or _canonical_llm_route(llm_route) + if route is not None: + event['part']['llm_route'] = route + created = data.get('created') + stamp = datetime.now(timezone.utc) + try: + if isinstance(created, str): + parsed = datetime.fromisoformat(created.replace('Z', '+00:00')) + if parsed.tzinfo is not None: + stamp = parsed + elif isinstance(created, (int, float)) and (not isinstance(created, bool)) and math.isfinite(created): + stamp = datetime.fromtimestamp(created, timezone.utc) + except (ValueError, OverflowError, OSError): + pass + pair = json.dumps({'type': 'step_start', 'timestamp': stamp.isoformat()}) + '\n' + pair += json.dumps(event) + '\n' + try: + receipt_path = target or Path(os.environ.get('M1_JUDGE_USAGE_PATH', '/logs/verifier/judge-trajectory.jsonl')) + receipt_path.parent.mkdir(parents=True, exist_ok=True) + with receipt_path.open('a') as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + handle.write(pair) + handle.flush() + os.fsync(handle.fileno()) + except OSError as exc: + if target is not None: + raise JudgeReceiptError(f'judge receipt write failed: {exc}') from exc + print(f'judge accounting: write failed ({type(exc).__name__})', file=sys.stderr) + +def openrouter_judge_pins() -> dict[str, dict]: + raw = os.environ.get('M1_OPENROUTER_JUDGE_PROVIDER_PINS', '').strip() + if not raw: + return {} + try: + pins = json.loads(raw) + except json.JSONDecodeError: + print('judge provider pins: invalid JSON in M1_OPENROUTER_JUDGE_PROVIDER_PINS', file=sys.stderr) + return {} + return {model: pin for model, pin in pins.items() if isinstance(pin, dict) and pin.get('order')} if isinstance(pins, dict) else {} + +def apply_judge_provider_pin(kwargs: dict, pins: dict[str, dict]) -> dict: + model = kwargs.get('model') + pin = pins.get(model) if isinstance(model, str) else None + if pin is None: + return kwargs + extra_body = dict(kwargs.get('extra_body') or {}) + provider = dict(extra_body.get('provider') or {}) + provider['order'] = list(pin['order']) + if pin.get('allow_fallbacks') is False: + provider['allow_fallbacks'] = False + if pin.get('zdr'): + provider['zdr'] = True + extra_body['provider'] = provider + return {**kwargs, 'extra_body': extra_body} +_TRANSIENT_ERROR_NAMES = ('RateLimitError', 'ServiceUnavailableError', 'InternalServerError', 'BadGatewayError', 'APIConnectionError') +_RETRYABLE_STATUS_CODES = frozenset({408, 409, 425, 429, 500, 502, 503, 504}) +_AUTH_ERROR_NAMES = ('AuthenticationError', 'PermissionDeniedError') +_AUTH_STATUS_CODES = frozenset({401, 403}) +_AUTH_RETRIES = 4 +_DEFAULT_TRANSIENT_RETRIES = 6 +_MAX_TRANSIENT_RETRIES = 20 +_MAX_RETRY_DELAY_SECONDS = 60.0 +_DEFAULT_EMPTY_RESPONSE_RETRIES = 3 +_DEFAULT_RETRY_BUDGET_SECONDS = 900.0 +_MAX_RETRY_BUDGET_SECONDS = 86400.0 + +def transient_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_TRANSIENT_RETRIES', '').strip() + if not raw: + return _DEFAULT_TRANSIENT_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_TRANSIENT_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_TRANSIENT_RETRIES + +def empty_response_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_EMPTY_RESPONSE_RETRIES', '').strip() + if not raw: + return _DEFAULT_EMPTY_RESPONSE_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_EMPTY_RESPONSE_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_EMPTY_RESPONSE_RETRIES + +def retry_budget_seconds() -> float: + raw = os.environ.get('M1_JUDGE_RETRY_BUDGET_SECONDS', '').strip() + if not raw: + return _DEFAULT_RETRY_BUDGET_SECONDS + try: + value = float(raw) + except ValueError: + value = math.nan + if not math.isfinite(value) or value < 0: + print('judge retries: invalid M1_JUDGE_RETRY_BUDGET_SECONDS, using the default', file=sys.stderr) + return _DEFAULT_RETRY_BUDGET_SECONDS + return min(value, _MAX_RETRY_BUDGET_SECONDS) + +def _within_budget(deadline: float, delay: float, model) -> bool: + remaining = deadline - time.monotonic() + if delay <= remaining: + return True + print(f'judge call retry budget spent: {model} would wait {delay:.1f}s with {max(remaining, 0.0):.1f}s left of M1_JUDGE_RETRY_BUDGET_SECONDS, failing now', file=sys.stderr) + return False + +def is_empty_verdict(response) -> bool: + data = response.model_dump() if hasattr(response, 'model_dump') else response + if not isinstance(data, dict): + return False + choices = data.get('choices') + if not isinstance(choices, list) or not choices: + return True + first = choices[0] + message = first.get('message') if isinstance(first, dict) else None + if not isinstance(message, dict): + return True + if message.get('tool_calls') or message.get('function_call'): + return False + content = message.get('content') + if isinstance(content, list): + content = ''.join((part.get('text') or '' for part in content if isinstance(part, dict))) + return not (isinstance(content, str) and content.strip()) + +def _matches(exc: BaseException, litellm, names: tuple[str, ...], statuses: frozenset[int]) -> bool: + classes = tuple((cls for cls in (getattr(litellm, name, None) for name in names) if isinstance(cls, type))) + if classes and isinstance(exc, classes): + return True + status = getattr(exc, 'status_code', None) + return type(status) is int and status in statuses + +def is_transient_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _TRANSIENT_ERROR_NAMES, _RETRYABLE_STATUS_CODES) + +def is_auth_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _AUTH_ERROR_NAMES, _AUTH_STATUS_CODES) + +def should_retry(exc: BaseException, litellm, attempt: int, limit: int) -> bool: + if attempt < limit and is_transient_error(exc, litellm): + return True + return attempt < min(limit, _AUTH_RETRIES) and is_auth_error(exc, litellm) + +def _retry_after_seconds(exc: BaseException) -> float | None: + headers = getattr(exc, 'headers', None) + if headers is None: + headers = getattr(getattr(exc, 'response', None), 'headers', None) + if headers is None: + return None + try: + raw = headers.get('retry-after') + if raw is None: + raw = headers.get('Retry-After') + value = float(raw) + except (AttributeError, TypeError, ValueError): + return None + return value if math.isfinite(value) and value >= 0 else None + +def retry_delay(exc: BaseException | None, attempt: int) -> float: + base = min(_MAX_RETRY_DELAY_SECONDS, 2.0 ** (attempt + 1)) + delay = base * (0.5 + random.random()) + retry_after = _retry_after_seconds(exc) if exc is not None else None + if retry_after is not None: + delay = max(delay, min(_MAX_RETRY_DELAY_SECONDS, retry_after)) + return delay + +def _note_retry(model, exc: BaseException, attempt: int, limit: int, delay: float) -> None: + status = getattr(exc, 'status_code', None) + print(f"judge call retry {attempt}/{limit}: {model} {type(exc).__name__} status={(status if type(status) is int else 'n/a')}, waiting {delay:.1f}s", file=sys.stderr) + +def _note_empty(model, response, attempt: int, limit: int, delay: float) -> None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + reason = None + if isinstance(data, dict) and isinstance(data.get('choices'), list) and data['choices']: + first = data['choices'][0] + reason = first.get('finish_reason') if isinstance(first, dict) else None + print(f'judge call retry {attempt}/{limit}: {model} empty verdict (finish_reason={reason}), waiting {delay:.1f}s', file=sys.stderr) + +def install(litellm, *, synchronous: bool=False) -> None: + pins = openrouter_judge_pins() + limit = transient_retry_limit() + empty_limit = empty_response_retry_limit() + deadline = time.monotonic() + retry_budget_seconds() + if synchronous: + original = litellm.completion + + def accounted(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = original(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + time.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + time.sleep(delay) + continue + return response + litellm.completion = accounted + return + original_async = litellm.acompletion + + async def accounted_async(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = await original_async(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + await asyncio.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + await asyncio.sleep(delay) + continue + return response + litellm.acompletion = accounted_async + +def record_agent_usage(attempt, *, model: str, provider: str) -> None: + records: dict[str, tuple[str, dict]] = {} + current_model = model + for filename in getattr(attempt, 'logs', []): + try: + with Path(filename).open() as stream: + for line in stream: + try: + event = json.loads(line) + except (ValueError, TypeError): + continue + if not isinstance(event, dict): + continue + message = event.get('message') or {} + if event.get('type') == 'assistant' and isinstance(message, dict) and isinstance(message.get('usage'), dict): + raw = message['usage'] + cached, written = (raw.get('cache_read_input_tokens'), raw.get('cache_creation_input_tokens')) + if all((type(value) is int and value >= 0 for value in (raw.get('input_tokens'), raw.get('output_tokens')))) and all((value is None or (type(value) is int and value >= 0) for value in (cached, written))): + receipt: dict = {'usage': {'input_uncached_tokens': raw['input_tokens'], 'prompt_tokens': raw['input_tokens'] + cached + written if cached is not None and written is not None else None, 'completion_tokens': raw['output_tokens'], 'prompt_tokens_details': {'cached_tokens': cached, 'cache_creation_tokens': written}}} + receipt['created'] = event.get('timestamp') + creation = raw.get('cache_creation') or {} + hour = creation.get('ephemeral_1h_input_tokens', 0) if isinstance(creation, dict) else 0 + if type(hour) is int and hour > 0: + if hour == written: + receipt['cache_ttl'] = '1h' + else: + receipt['usage_granularity'] = 'mixed_cache_ttl' + records[message.get('id') or json.dumps(raw, sort_keys=True)] = (message.get('model') or current_model, receipt) + payload = event.get('payload') or {} + if not isinstance(payload, dict): + continue + if event.get('type') == 'turn_context' and payload.get('model'): + current_model = payload['model'] + if event.get('type') == 'event_msg' and payload.get('type') == 'token_count': + info = payload.get('info') or {} + raw, total = (info.get('last_token_usage'), info.get('total_token_usage')) + if isinstance(raw, dict) and isinstance(total, dict) and all((type(raw.get(key)) is int and raw.get(key) >= 0 for key in ('input_tokens', 'output_tokens'))): + receipt = {'usage': {'prompt_tokens': raw.get('input_tokens'), 'input_uncached_tokens': raw.get('input_uncached_tokens'), 'input_cache_write_tokens': raw.get('input_cache_write_tokens'), 'completion_tokens': raw.get('output_tokens'), 'prompt_tokens_details': {'cached_tokens': raw.get('cached_input_tokens')}}} + receipt['created'] = event.get('timestamp') + records[json.dumps(total, sort_keys=True)] = (current_model, receipt) + except OSError: + continue + captured_input = captured_output = 0 + input_complete = True + for requested, receipt in records.values(): + requested = requested if '/' in requested else f'{provider}/{requested}' + _record_judge_usage(receipt, requested) + receipt_input = receipt['usage'].get('prompt_tokens') + if receipt_input is None: + input_complete = False + else: + captured_input += receipt_input + captured_output += receipt['usage'].get('completion_tokens') or 0 + total = getattr(attempt, 'usage', {}) or {} + if not records or (input_complete and total.get('input_tokens') != captured_input) or total.get('output_tokens') != captured_output: + _record_judge_usage({'usage': {'prompt_tokens': 0, 'completion_tokens': 0}, 'usage_granularity': 'incomplete_agent_receipts'}, model if '/' in model else f'{provider}/{model}') + +def install_rewardkit_agents() -> None: + import rewardkit.judges as judges + original = judges.get_agent + + def get_accounted_agent(judge, cwd=None): + backend = original(judge, cwd) + run = backend.run + + async def accounted_run(*args, **kwargs): + attempt = await run(*args, **kwargs) + record_agent_usage(attempt, model=judge.model or 'unknown', provider='anthropic' if judge.agent == 'claude-code' else 'openai') + return attempt + setattr(backend, 'run', accounted_run) + return backend + setattr(judges, 'get_agent', get_accounted_agent) +if __name__ == '__main__': + import litellm + if len(sys.argv) > 2 and sys.argv[1] == '--script': + import runpy + install(litellm, synchronous=True) + sys.argv = sys.argv[2:] + runpy.run_path(sys.argv[0], run_name='__main__') + else: + install(litellm) + install_rewardkit_agents() + if Path(__file__).with_name('m1_judge_panel.json').is_file(): + from m1_rewardkit_panel import install_panel + install_panel(Path(__file__).with_name('m1_judge_panel.json')) + if Path(__file__).with_name('m1_judge_jev.json').is_file(): + from m1_rewardkit_jev import install_jev + install_jev(Path(__file__).with_name('m1_judge_jev.json')) + from rewardkit.__main__ import main + main() diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/m1_rewardkit_panel.py b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/m1_rewardkit_panel.py new file mode 100644 index 0000000000000000000000000000000000000000..164cc2ae521cdd368c2e1749d7ed8fe09f4545eb --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/m1_rewardkit_panel.py @@ -0,0 +1,169 @@ +from __future__ import annotations +import asyncio +from contextvars import ContextVar +import json +import math +import os +import sys +from pathlib import Path +from typing import Any +import uuid +_request_audit: ContextVar[tuple[Path, list[str]] | None] = ContextVar('panel_request_audit', default=None) + +class PanelIncompleteError(RuntimeError): + pass + +def _audit_warning(exc: Exception, warnings: list[str]) -> None: + message = f'judge panel audit: diagnostic capture failed ({type(exc).__name__})' + if message not in warnings: + warnings.append(message) + print(message, file=sys.stderr) + +def _write_audit(path: Path, record: dict[str, Any], warnings: list[str], *, append: bool=False) -> None: + try: + text = json.dumps(record, allow_nan=False, default=str) + '\n' + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('a' if append else 'w') as stream: + stream.write(text) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + +def _binary(raw: Any) -> int: + if isinstance(raw, bool): + return int(raw) + if isinstance(raw, int | float) and math.isfinite(raw) and (raw in (0, 1)): + return int(raw) + if isinstance(raw, str): + value = raw.strip().lower() + if value in {'yes', 'true', '1'}: + return 1 + if value in {'no', 'false', '0'}: + return 0 + raise PanelIncompleteError('m1_judge_panel_incomplete: invalid binary vote') + +def validate_votes(scores: list[Any], criteria: list[Any]) -> None: + names = [criterion.name for criterion in criteria] + if len(set(names)) != len(names) or [score.name for score in scores] != names: + raise PanelIncompleteError('m1_judge_panel_incomplete: criterion membership mismatch') + for score, criterion in zip(scores, criteria, strict=True): + if score.error: + raise PanelIncompleteError('m1_judge_panel_incomplete: judge returned an error') + raw = _binary(score.raw) + expected = 1 - raw if criterion.negate else raw + if not math.isfinite(score.value) or score.value != expected: + raise PanelIncompleteError('m1_judge_panel_incomplete: inconsistent binary score') + +async def run_panel(judge: Any, criteria: list[Any], weights: list[float] | None, system_prompt: str | None, *, config: dict[str, Any], run_llm: Any, score_type: Any, audit_dir: Path) -> tuple[list[Any], str, list[str]]: + from rewardkit.models import Binary + if not criteria or any((not isinstance(criterion.output_format, Binary) for criterion in criteria)): + raise ValueError('panel majority voting requires nonempty binary criteria') + group_dir = audit_dir / uuid.uuid4().hex + warnings_out: list[str] = [] + + async def member_call(index: int, member: dict[str, Any]): + member_judge = judge.model_copy(update=member) + evidence: dict[str, Any] = {'member': index + 1, 'judge': member, 'criteria': [criterion.name for criterion in criteria], 'status': 'started'} + path = group_dir / f'judge-{index + 1}.json' + _write_audit(path, evidence, warnings_out) + token = _request_audit.set((group_dir / f'judge-{index + 1}-requests.jsonl', warnings_out)) + try: + scores, output, warnings = await run_llm(member_judge, criteria, weights, system_prompt) + evidence.update(output=output, warnings=warnings) + validate_votes(scores, criteria) + evidence['scores'] = [score.to_dict() for score in scores] + evidence['status'] = 'completed' + return (scores, output, warnings) + except BaseException as exc: + evidence.update(status='failed', error_class=type(exc).__name__) + if isinstance(exc, PanelIncompleteError): + evidence['error'] = str(exc) + raise + finally: + _request_audit.reset(token) + _write_audit(path, evidence, warnings_out) + outcomes = await asyncio.gather(*(member_call(index, member) for index, member in enumerate(config['members'])), return_exceptions=True) + failed = [index + 1 for index, result in enumerate(outcomes) if isinstance(result, BaseException)] + if failed: + _write_audit(group_dir / 'panel.json', {'status': 'incomplete', 'failed_members': failed}, warnings_out) + raise PanelIncompleteError(f'm1_judge_panel_incomplete: failed members {failed}; see panel audit artifacts') + completed = [outcome for outcome in outcomes if not isinstance(outcome, BaseException)] + combined = [] + for index, criterion in enumerate(criteria): + votes = [{'judge': config['members'][member_index], **outcome[0][index].to_dict()} for member_index, outcome in enumerate(completed)] + passes = sum((vote['value'] == 1 for vote in votes)) + value = int(passes >= 2) + combined.append(score_type(name=criterion.name, value=value, raw=bool(1 - value if criterion.negate else value), weight=weights[index] if weights is not None else 1.0, reasoning=f'{passes}/3 judges passed; strict majority requires 2/3.', description=criterion.description, id=criterion.id, negate=criterion.negate, optional=criterion.optional, votes=votes)) + for outcome in completed: + warnings_out.extend(outcome[2]) + audit = {'status': 'completed', 'mode': 'panel', 'aggregation': 'majority', 'required_votes': 2, 'members': config['members'], 'criteria': [score.to_dict() for score in combined]} + output = json.dumps(audit, indent=2, allow_nan=False) + _write_audit(group_dir / 'panel.json', audit, warnings_out) + return (combined, output, warnings_out) + +def install_panel(config_path: Path, *, audit_dir: Path=Path('/logs/verifier/judge-panel')) -> None: + import rewardkit.judges as judges + import rewardkit.reward as reward + from rewardkit.models import LLMJudge, Score + import litellm + config = json.loads(config_path.read_text()) + members = config.get('members') + concurrency = config.get('max_concurrent_llm') + if config.get('mode') != 'panel' or not isinstance(members, list) or len(members) != 3 or (len({member['model'] for member in members}) != 3) or (type(concurrency) is not int) or (not 1 <= concurrency <= 64): + raise ValueError('invalid materialized panel configuration') + if os.environ.get('REWARDKIT_JUDGE') or os.environ.get('REWARDKIT_MODEL'): + raise ValueError('RewardKit environment overrides cannot replace a frozen panel') + + class PanelScore(Score): + votes: list[dict[str, Any]] + + def to_dict(self): + return {**super().to_dict(), 'votes': self.votes} + original_llm = judges.arun_llm + original_call = judges._arun_llm_call + original_details = reward.Reward.to_detail_dict + original_completion = litellm.acompletion + active_loop = None + semaphore = None + + async def captured_completion(*args, **kwargs): + context = _request_audit.get() + record = {'requested_model': kwargs.get('model')} + response = None + try: + response = await original_completion(*args, **kwargs) + return response + except BaseException as exc: + record['error_class'] = type(exc).__name__ + raise + finally: + if context is not None: + path, warnings = context + try: + if response is not None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + record.update(response_model=data.get('model'), choices=data.get('choices')) + _write_audit(path, record, warnings, append=True) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + + async def bounded_call(*args, **kwargs): + nonlocal active_loop, semaphore + loop = asyncio.get_running_loop() + if active_loop is not loop: + active_loop, semaphore = (loop, asyncio.Semaphore(concurrency)) + assert semaphore is not None + async with semaphore: + return await original_call(*args, **kwargs) + + async def panel_call(judge, criteria, weights=None, system_prompt=None): + return await run_panel(judge, criteria, weights, system_prompt, config=config, run_llm=original_llm, score_type=PanelScore, audit_dir=audit_dir) + + def panel_details(self, score): + detail = original_details(self, score) + if isinstance(self.judge, LLMJudge): + detail.update(kind='llm_panel', judge=config, aggregation='majority', required_votes=2) + return detail + setattr(reward, 'arun_llm', panel_call) + setattr(judges, '_arun_llm_call', bounded_call) + setattr(litellm, 'acompletion', captured_completion) + reward.Reward.to_detail_dict = panel_details diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/normalize_reward.py b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/normalize_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..91817ef00ea9152ca57f0030d8e879eb850ddff0 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/normalize_reward.py @@ -0,0 +1,71 @@ +from __future__ import annotations +import argparse +import json +from pathlib import Path +from typing import Any + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument('--raw-details', required=True) + parser.add_argument('--rubric', required=True) + parser.add_argument('--reward-out', required=True) + parser.add_argument('--details-out', required=True) + args = parser.parse_args() + raw_details = _load_json(Path(args.raw_details)) + rubric = _load_json(Path(args.rubric)) + criteria = rubric['criteria'] + raw_by_name = _raw_criteria_by_name(raw_details) + positive_total = sum((float(item['score']) for item in criteria if float(item['score']) > 0)) + if positive_total <= 0: + raise ValueError('rubric must contain at least one positive score') + earned = 0.0 + normalized_criteria: list[dict[str, Any]] = [] + for item in criteria: + signed_score = float(item['score']) + raw = raw_by_name.get(item['name'], {}) + value = _coerce_score(raw.get('value', 0.0)) + contribution = value * signed_score + earned += contribution + normalized_criteria.append({'name': item['name'], 'value': value, 'raw': raw.get('raw'), 'weight': signed_score, 'signed_score': signed_score, 'polarity': item['polarity'], 'contribution': contribution, 'description': item['description'], 'source': item.get('source', ''), 'justification': item.get('justification', ''), 'metadata': item.get('metadata', {}), 'reasoning': raw.get('reasoning'), 'judge_reasoning': raw.get('reasoning'), 'judge_error': raw.get('error'), **({'votes': raw['votes']} if 'votes' in raw else {})}) + unclamped = earned / positive_total + reward = max(0.0, min(1.0, unclamped)) + reward_out = {'correctness': reward} + details_out = {'correctness': {'score': reward, 'kind': 'signed_score', 'criteria': normalized_criteria, 'aggregation': {'method': 'signed_score_ratio_clamped', 'earned': earned, 'positive_total': positive_total, 'unclamped': unclamped, 'clamped': reward}, 'raw_rewardkit': raw_details}} + _write_json(Path(args.reward_out), reward_out) + _write_json(Path(args.details_out), details_out) + +def _load_json(path: Path) -> Any: + return json.loads(path.read_text()) + +def _write_json(path: Path, data: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data, indent=2) + '\n') + +def _raw_criteria_by_name(details: dict[str, Any]) -> dict[str, dict[str, Any]]: + out: dict[str, dict[str, Any]] = {} + for reward in details.values(): + for item in _iter_raw_criteria(reward): + name = item.get('name') + if isinstance(name, str): + out[name] = item + return out + +def _iter_raw_criteria(value: Any): + if isinstance(value, list): + for item in value: + yield from _iter_raw_criteria(item) + return + if not isinstance(value, dict): + return + for item in value.get('criteria') or []: + if isinstance(item, dict): + yield item + +def _coerce_score(value: Any) -> float: + if isinstance(value, bool): + return 1.0 if value else 0.0 + if isinstance(value, int | float): + return max(0.0, min(1.0, float(value))) + return 0.0 +if __name__ == '__main__': + main() diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/agent_prompt.md b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/agent_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..ca489c065bafd5d10e764f033c9dfd1195933db3 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/agent_prompt.md @@ -0,0 +1,10 @@ +You are grading the submitted legal analysis against the criteria below. + +Read `/logs/artifacts/answer.md`, the answer captured by the verifier, before +assigning any scores. Evaluate that file as the submission. Other files in +`/app` may supply context, but must not replace the submitted answer. Do not +modify the submission. If it is missing or empty, state that in your reasoning +and apply the criteria to that missing or empty submission. Preserve each +criterion's stated positive or penalty polarity. + +{criteria} diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/criterion_1.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/criterion_1.toml new file mode 100644 index 0000000000000000000000000000000000000000..8156d34c84aead5427a1aae64da58a1934321a90 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/criterion_1.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_1" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions that the Final Notice of Adverse Action found all twelve Douglas factors to be aggravating." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/criterion_2.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/criterion_2.toml new file mode 100644 index 0000000000000000000000000000000000000000..2fee1607d6fdbf9b6c0c21caeb0044288db5b7ba --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/criterion_2.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_2" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that the four comparator cases relied on by MPD, specifically Guzman, Sadler, Pietrzak, and Voss, resulted in termination." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/criterion_3.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/criterion_3.toml new file mode 100644 index 0000000000000000000000000000000000000000..4fc169a6c4c8d7e3891b97b2a84405af032a5b14 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/criterion_3.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_3" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions that the arbitrator sustained the finding of cause on the Conduct Unbecoming charge." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/criterion_4.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/criterion_4.toml new file mode 100644 index 0000000000000000000000000000000000000000..7811d9797175a87563d7678418efd301dec2b34f --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/criterion_4.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_4" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that the arbitrator reviewed MPD’s penalty selection under a tolerable limits of reasonableness standard rather than de novo." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/criterion_5.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/criterion_5.toml new file mode 100644 index 0000000000000000000000000000000000000000..ccc439d3f520d96ab466469732ab02979437c4be --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/criterion_5.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_5" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: States that the arbitrator overturned the finding of cause." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/criterion_6.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/criterion_6.toml new file mode 100644 index 0000000000000000000000000000000000000000..e52e966f8771d5a72e2517d37cd972ea0922406e --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/criterion_6.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_6" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: States that the arbitrator reduced the penalty based on a Douglas factor he left undisturbed." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/criterion_7.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/criterion_7.toml new file mode 100644 index 0000000000000000000000000000000000000000..0250ceeffa90f776b58788379af92207ee2ab352 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/criterion_7.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_7" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that the Award's citation to the Final Notice's findings of fact does not match the paragraphs where those findings appear." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/criterion_8.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/criterion_8.toml new file mode 100644 index 0000000000000000000000000000000000000000..1497c4fa5438f2df748cfaf95c633f4c5b5814c7 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/criterion_8.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_8" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that the comparator memorandum's stated coverage years conflict with the dates of the cases it summarizes." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/criterion_9.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/criterion_9.toml new file mode 100644 index 0000000000000000000000000000000000000000..fe4ebca17c914fea9e1282c97799c00268483391 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/raw_correctness/criterion_9.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_9" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that the arbitrator left Douglas factors one through five and seven through eleven undisturbed." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/test.sh b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..66a509a7bcdbe412851f3a012a5ba7b16cf0925b --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/tests/test.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +set -euo pipefail + +mkdir -p /logs/artifacts /logs/verifier/raw + +python3 - <<'PYEOF' +import json +import shutil +from pathlib import Path + + +def has_text(path: Path) -> bool: + return path.exists() and path.is_file() and bool(path.read_text(errors="replace").strip()) + + +def fallback_paths(answer_path: Path) -> list[Path]: + paths = [] + try: + relative = answer_path.relative_to("/app") + paths.append(Path("/app/app") / relative) + except ValueError: + pass + return [path for path in paths if path != answer_path] + + +config = json.loads(Path("/tests/fixtures/config.json").read_text()) +answer_path = Path(config["answer_path"]) +artifact_answer = Path("/logs/artifacts/answer.md") +artifact_answer.parent.mkdir(parents=True, exist_ok=True) +if has_text(answer_path): + shutil.copyfile(answer_path, artifact_answer) +else: + for candidate in fallback_paths(answer_path): + if has_text(candidate): + shutil.copyfile(candidate, artifact_answer) + break + else: + artifact_answer.write_text("") + +# Harbor collects /logs/artifacts when the agent step ends, which is before this +# script runs, so the copy above never reaches the uploaded artifacts. /logs/verifier +# is uploaded after the verifier phase, so persist the graded answer there too. +verifier_answer = Path("/logs/verifier/answer.md") +verifier_answer.parent.mkdir(parents=True, exist_ok=True) +shutil.copyfile(artifact_answer, verifier_answer) +PYEOF + +uv run --no-project --with 'harbor-rewardkit[all]==0.2.0' python /tests/m1_rewardkit_accounting.py /tests/raw_correctness \ + --workspace /app \ + --output /logs/verifier/raw/reward.json \ + --max-concurrent-llm "${MAX_CONCURRENT_LLM:-4}" \ + --max-concurrent-agent "${M1_MAX_CONCURRENT_AGENT:-1}" + +python /tests/normalize_reward.py \ + --raw-details /logs/verifier/raw/reward-details.json \ + --rubric /tests/fixtures/rubric.json \ + --reward-out /logs/verifier/reward.json \ + --details-out /logs/verifier/reward-details.json diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/workdir/attachments/braddock_arbitration_award.pdf b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/workdir/attachments/braddock_arbitration_award.pdf new file mode 100644 index 0000000000000000000000000000000000000000..ea39767edf0dbb2ed221e93265c9fad3181978ec Binary files /dev/null and b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/workdir/attachments/braddock_arbitration_award.pdf differ diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/workdir/attachments/comparator_discipline_cases.pdf b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/workdir/attachments/comparator_discipline_cases.pdf new file mode 100644 index 0000000000000000000000000000000000000000..f6571ca65284295d4d83be006baa982d1fa90ce0 Binary files /dev/null and b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/workdir/attachments/comparator_discipline_cases.pdf differ diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/workdir/attachments/final_notice_adverse_action_braddock.pdf b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/workdir/attachments/final_notice_adverse_action_braddock.pdf new file mode 100644 index 0000000000000000000000000000000000000000..4d2dbc6fab78a69bfd0e4e593449f17cb6ccd6ff Binary files /dev/null and b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-1/workdir/attachments/final_notice_adverse_action_braddock.pdf differ diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/instruction.md b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1effb58dbdcc425a3ce4ab9a982701bd81083b0d --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/instruction.md @@ -0,0 +1,61 @@ +# Viability of a DCCA Challenge — Scope of Review + +Domain: Litigation + +Matter: MPD v. PERB + +You are a senior legal analyst operating autonomously. You are completing a multi-step legal reasoning task. Follow the role, factual record, instructions, and deliverable requirements provided in the Task and each Assignment. + +Each Assignment may require a different legal deliverable. Follow the requirements specific to that Assignment. + +## Word limits for court briefs + +- A brief in support of or in response to a motion may not exceed **8,750 words**. +- A reply brief may not exceed **3,500 words**. +- For a motion for reconsideration, a brief in support of or in response to the motion may not exceed **3,500 words**, and a reply brief may not exceed **1,750 words**. +- If an Assignment specifies a stricter word limit, follow the stricter limit. + +These word limits do not apply to legal memoranda or other non-court-filing deliverables unless the Assignment expressly provides otherwise. + +Complete the task end-to-end without asking for confirmation, permission, or clarification. + +Use the uploaded matter documents in `/app/attachments/` as your primary case file. You also have internet access via OpenCode's `websearch` tool; use it to research any statutes, regulations, cases, administrative guidance, or secondary authorities that are not supplied as attachments. Cite any authority you rely on in the format requested by the prompt. + +For document inspection: +- PDF: `pdftotext /app/attachments/.pdf -` +- DOCX: `pandoc /app/attachments/.docx -t markdown` +- XLSX/CSV: use Python with `openpyxl` or `pandas` +- If extraction is unreliable, inspect the raw file with Python libraries or convert/render the relevant pages. + +Write the final complete legal deliverable for this assignment to `/app/response2.md`. The verifier reads only that file. + +This is a follow-on assignment. The documents from the previous assignment(s) remain available in `/app/attachments/`, and your prior deliverable `/app/response1.md` is also on disk. Build on that analysis as the prompt directs. + +## Attachments + +- `/app/attachments/douglas_v_veterans_admin.pdf` +- `/app/attachments/dcmr_title6b_1606.pdf` + + +## Prompt + +Our firm represents the District of Columbia Metropolitan Police Department (“MPD�) in connection with an arbitration award that reduced Officer Colin Braddock’s termination for excessive force to a 45-day suspension based solely on the arbitrator’s findings regarding Douglas factors six and twelve. The D.C. Public Employee Relations Board (“PERB�) affirmed the award. MPD is weighing a challenge at the District of Columbia Court of Appeals (“DCCA�). Assume today is March 2, 2026. You are the associate assigned to this matter. The partner has asked you to draft the scope-of-review and preservation analysis for our advice memorandum, based solely on the uploaded materials. + +Treat the following as true for all purposes in this matter, whether or not separately memorialized in the record: (a) reasonable minds can disagree as to how comparable the four comparator cases are to Braddock’s case; (b) at no point before the arbitration hearing did Braddock or his union allege that MPD treated similarly situated employees differently; and (c) Braddock knew that MPD intended to rely on the four comparator cases before MPD found him guilty of the excessive force charge. +The following documents have been uploaded for this Step: + +D.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117 (May 22, 2024) (final_notice_adverse_action_braddock.pdf) +In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf) +Memorandum from Yolanda Britt, Director, Disciplinary Review Division, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Sandra M. Delgado, Assistant Chief, Professional Development Bureau, re: Comparator Discipline Cases, Adverse Action Case No. IS-23-002841 (Braddock) (Apr. 11, 2024) (comparator_discipline_cases.pdf) +Douglas v. Veterans Administration, 5 M.S.P.R. 280 (1981) (douglas_v_veterans_admin.pdf) +D.C. Mun. Regs. tit. 6-B, § 1606 (2017) (dcmr_title6b_1606.pdf) + +The documents listed above constitute the complete and exclusive universe of materials for this Step. Limit your review to the attached documents. Do not rely on, reference, or infer any legal authority, factual information, or data beyond what is contained in these uploaded files. If a document is not uploaded, it does not exist for purposes of this analysis. All citations must reference the document by its exact name as listed above, followed by the page and paragraph number. Do not cite external websites, databases, or any source outside the uploaded materials. + +Complete the following: + +1. State the scope of review the arbitrator was required to apply to MPD’s penalty selection under Douglas and D.C. Mun. Regs. tit. 6-B, § 1606.2 (2017), and assess whether the arbitrator’s treatment of Douglas factors six and twelve stayed within that scope. Address the arbitrator’s requirement that MPD “prove� the comparability of the comparator cases on factor six, and the arbitrator’s finding that a suspension would “likely" have sufficed to deter future misconduct on factor twelve. Support every point with page and paragraph citations to the uploaded materials. + +2. State which party bore the burden of production and persuasion on the comparator evidence at each stage of the proceedings, and assess the legal consequence of Braddock’s failure to raise disparate treatment before the arbitration hearing. Identify the strongest position MPD can take on this record and the weakest point in that position, with page and paragraph citations. + +Present both analyses as a draft memorandum section that resolves each question with a definite conclusion supported by page and paragraph citations to the uploaded materials. diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/solution/solve.sh b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7710414a6da6d0ad740717c8c85a9af850d5da33 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/solution/solve.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# No oracle solution ships with LegalReasonBench. The verifier grades the +# agent's own legal deliverable for this assignment against the rubric. +echo "no oracle solution" diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/fixtures/config.json b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/fixtures/config.json new file mode 100644 index 0000000000000000000000000000000000000000..b02b8f2749c350668933c48cb33149b6db523119 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/fixtures/config.json @@ -0,0 +1,190 @@ +{ + "task_id": "lrb-dcca-challenge-police-discipline", + "title": "Viability of a DCCA Challenge", + "domain": "Litigation", + "matter": "MPD v. PERB", + "judge": { + "max_concurrent_llm": 12, + "mode": "panel", + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ], + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + "step_index": 2, + "step_name": "assignment-2", + "step_title": "Scope of Review", + "prompt": "Our firm represents the District of Columbia Metropolitan Police Department (\u201cMPD\u201d) in connection with an arbitration award that reduced Officer Colin Braddock\u2019s termination for excessive force to a 45-day suspension based solely on the arbitrator\u2019s findings regarding Douglas factors six and twelve. The D.C. Public Employee Relations Board (\u201cPERB\u201d) affirmed the award. MPD is weighing a challenge at the District of Columbia Court of Appeals (\u201cDCCA\u201d). Assume today is March 2, 2026. You are the associate assigned to this matter. The partner has asked you to draft the scope-of-review and preservation analysis for our advice memorandum, based solely on the uploaded materials.\n\nTreat the following as true for all purposes in this matter, whether or not separately memorialized in the record: (a) reasonable minds can disagree as to how comparable the four comparator cases are to Braddock\u2019s case; (b) at no point before the arbitration hearing did Braddock or his union allege that MPD treated similarly situated employees differently; and (c) Braddock knew that MPD intended to rely on the four comparator cases before MPD found him guilty of the excessive force charge.\nThe following documents have been uploaded for this Step:\n\nD.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117 (May 22, 2024) (final_notice_adverse_action_braddock.pdf)\nIn re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)\nMemorandum from Yolanda Britt, Director, Disciplinary Review Division, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Sandra M. Delgado, Assistant Chief, Professional Development Bureau, re: Comparator Discipline Cases, Adverse Action Case No. IS-23-002841 (Braddock) (Apr. 11, 2024) (comparator_discipline_cases.pdf)\nDouglas v. Veterans Administration, 5 M.S.P.R. 280 (1981) (douglas_v_veterans_admin.pdf)\nD.C. Mun. Regs. tit. 6-B, \u00a7 1606 (2017) (dcmr_title6b_1606.pdf)\n\nThe documents listed above constitute the complete and exclusive universe of materials for this Step. Limit your review to the attached documents. Do not rely on, reference, or infer any legal authority, factual information, or data beyond what is contained in these uploaded files. If a document is not uploaded, it does not exist for purposes of this analysis. All citations must reference the document by its exact name as listed above, followed by the page and paragraph number. Do not cite external websites, databases, or any source outside the uploaded materials.\n\nComplete the following:\n\n1. State the scope of review the arbitrator was required to apply to MPD\u2019s penalty selection under Douglas and D.C. Mun. Regs. tit. 6-B, \u00a7 1606.2 (2017), and assess whether the arbitrator\u2019s treatment of Douglas factors six and twelve stayed within that scope. Address the arbitrator\u2019s requirement that MPD \u201cprove\u201d the comparability of the comparator cases on factor six, and the arbitrator\u2019s finding that a suspension would \u201clikely\" have sufficed to deter future misconduct on factor twelve. Support every point with page and paragraph citations to the uploaded materials.\n\n2. State which party bore the burden of production and persuasion on the comparator evidence at each stage of the proceedings, and assess the legal consequence of Braddock\u2019s failure to raise disparate treatment before the arbitration hearing. Identify the strongest position MPD can take on this record and the weakest point in that position, with page and paragraph citations.\n\nPresent both analyses as a draft memorandum section that resolves each question with a definite conclusion supported by page and paragraph citations to the uploaded materials.", + "attachments": [ + { + "filename": "douglas_v_veterans_admin.pdf", + "description": "", + "metadata": {}, + "path": "/app/attachments/douglas_v_veterans_admin.pdf" + }, + { + "filename": "dcmr_title6b_1606.pdf", + "description": "", + "metadata": {}, + "path": "/app/attachments/dcmr_title6b_1606.pdf" + } + ], + "rubric": [ + { + "name": "criterion_1", + "description": "Mentions that under Douglas an agency-selected penalty stands unless the agency failed to weigh the relevant factors or the penalty exceeded the tolerable limits of reasonableness.", + "source": "Douglas v. Veterans Administration, 5 M.S.P.R. 280, 305-06 (1981) (douglas_v_veterans_admin.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"1. State the scope of review the arbitrator was required to apply to MPD's penalty selection under Douglas and D.C. Mun. Regs. tit. 6-B, \u00a7 1606.2 (2017), and assess whether the arbitrator's treatment of Douglas factors six and twelve stayed within that scope. Address the arbitrator's requirement that MPD 'prove' the comparability of the comparator cases on factor six, and the arbitrator's finding that a suspension would 'likely' have sufficed to deter future misconduct on factor twelve. Support every point with page and paragraph citations to the uploaded materials.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 4.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_2", + "description": "Identifies that the arbitrator required MPD to prove that the comparator officers were similarly situated under Douglas factor six.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 7 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"1. State the scope of review the arbitrator was required to apply to MPD's penalty selection under Douglas and D.C. Mun. Regs. tit. 6-B, \u00a7 1606.2 (2017), and assess whether the arbitrator's treatment of Douglas factors six and twelve stayed within that scope. Address the arbitrator's requirement that MPD 'prove' the comparability of the comparator cases on factor six, and the arbitrator's finding that a suspension would 'likely' have sufficed to deter future misconduct on factor twelve. Support every point with page and paragraph citations to the uploaded materials.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 6.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_3", + "description": "Identifies that the arbitrator\u2019s factor twelve finding rested on his conclusion that a suspension would likely have sufficed to deter future misconduct.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 8 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"1. State the scope of review the arbitrator was required to apply to MPD's penalty selection under Douglas and D.C. Mun. Regs. tit. 6-B, \u00a7 1606.2 (2017), and assess whether the arbitrator's treatment of Douglas factors six and twelve stayed within that scope. Address the arbitrator's requirement that MPD 'prove' the comparability of the comparator cases on factor six, and the arbitrator's finding that a suspension would 'likely' have sufficed to deter future misconduct on factor twelve. Support every point with page and paragraph citations to the uploaded materials.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 6.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_4", + "description": "Identifies that no uploaded authority requires MPD to prove the comparability of its comparator cases.", + "source": "D.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117, \u00b6 19 (May 22, 2024) (final_notice_adverse_action_braddock.pdf); In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 7 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf); Memorandum from Yolanda Britt, Director, Disciplinary Review Division, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Sandra M. Delgado, Assistant Chief, Professional Development Bureau, re: Comparator Discipline Cases, Adverse Action Case No. IS-23-002841 (Braddock), \u00b6\u00b6 2-5 (Apr. 11, 2024) (comparator_discipline_cases.pdf); Douglas v. Veterans Administration, 5 M.S.P.R. 280, 305-06 (1981) (douglas_v_veterans_admin.pdf); D.C. Mun. Regs. tit. 6-B, \u00a7 1606.2 (2017) (dcmr_title6b_1606.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"2. State which party bore the burden of production and persuasion on the comparator evidence at each stage of the proceedings, and assess the legal consequence of Braddock's failure to raise disparate treatment before the arbitration hearing. Identify the strongest position MPD can take on this record and the weakest point in that position, with page and paragraph citations.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 26.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_5", + "description": "States that the employee must make an initial showing of disparate treatment before the agency bears a comparator burden", + "source": "D.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117, \u00b6 19 (May 22, 2024) (final_notice_adverse_action_braddock.pdf); In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 7 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf); Memorandum from Yolanda Britt, Director, Disciplinary Review Division, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Sandra M. Delgado, Assistant Chief, Professional Development Bureau, re: Comparator Discipline Cases, Adverse Action Case No. IS-23-002841 (Braddock), \u00b6\u00b6 2-5 (Apr. 11, 2024) (comparator_discipline_cases.pdf); Douglas v. Veterans Administration, 5 M.S.P.R. 280, 305-06 (1981) (douglas_v_veterans_admin.pdf); D.C. Mun. Regs. tit. 6-B, \u00a7 1606.2 (2017) (dcmr_title6b_1606.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cState which party bore the burden of production and persuasion on the comparator evidence at each stage of the proceedings.\u201d Stating the initial-showing rule as settled law relies on authority outside the uploaded materials.", + "metadata": { + "irac_section": "Application" + }, + "score": -18.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_6", + "description": "Mentions that D.C. Mun. Regs. tit. 6-B, \u00a7 1606.2 (2017) requires the deciding official to balance the Douglas-type factors when selecting a penalty.", + "source": "D.C. Mun. Regs. tit. 6-B, \u00a7 1606.2 (2017) (dcmr_title6b_1606.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"1. State the scope of review the arbitrator was required to apply to MPD's penalty selection under Douglas and D.C. Mun. Regs. tit. 6-B, \u00a7 1606.2 (2017), and assess whether the arbitrator's treatment of Douglas factors six and twelve stayed within that scope. Address the arbitrator's requirement that MPD 'prove' the comparability of the comparator cases on factor six, and the arbitrator's finding that a suspension would 'likely' have sufficed to deter future misconduct on factor twelve. Support every point with page and paragraph citations to the uploaded materials.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 4.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_7", + "description": "States that the arbitrator was entitled to select whatever penalty he considered most appropriate without deference to MPD\u2019s penalty selection", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 5 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf); Douglas v. Veterans Administration, 5 M.S.P.R. 280, 305-06 (1981) (douglas_v_veterans_admin.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"1. State the scope of review the arbitrator was required to apply to MPD's penalty selection under Douglas and D.C. Mun. Regs. tit. 6-B, \u00a7 1606.2 (2017), and assess whether the arbitrator's treatment of Douglas factors six and twelve stayed within that scope. Address the arbitrator's requirement that MPD 'prove' the comparability of the comparator cases on factor six, and the arbitrator's finding that a suspension would 'likely' have sufficed to deter future misconduct on factor twelve. Support every point with page and paragraph citations to the uploaded materials.\" Entitlement to an unconstrained penalty choice is the scope error the instruction tests.", + "metadata": { + "irac_section": "Rule" + }, + "score": -24.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_8", + "description": "Mentions authority absent from the uploaded materials in support of the burden allocation.", + "source": "D.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117, \u00b6 19 (May 22, 2024) (final_notice_adverse_action_braddock.pdf); In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 7 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf); Memorandum from Yolanda Britt, Director, Disciplinary Review Division, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Sandra M. Delgado, Assistant Chief, Professional Development Bureau, re: Comparator Discipline Cases, Adverse Action Case No. IS-23-002841 (Braddock), \u00b6\u00b6 2-5 (Apr. 11, 2024) (comparator_discipline_cases.pdf); Douglas v. Veterans Administration, 5 M.S.P.R. 280, 305-06 (1981) (douglas_v_veterans_admin.pdf); D.C. Mun. Regs. tit. 6-B, \u00a7 1606.2 (2017) (dcmr_title6b_1606.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cDo not rely on, reference, or infer any legal authority, factual information, or data beyond what is contained in these uploaded files.\u201d", + "metadata": {}, + "score": -22.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_9", + "description": "Identifies that the Award\u2019s citation to Douglas v. Veterans Administration, 5 M.S.P.R. 280, 306 (1981) does not correspond to any page of the uploaded Douglas opinion.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 5 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf); Douglas v. Veterans Administration, 5 M.S.P.R. 280 (1981) (douglas_v_veterans_admin.pdf), paginated 313 to 346", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cSupport every point with page and paragraph citations to the uploaded materials.\u201d Verifying the Award\u2019s own citations against the uploaded opinion is part of citation-supported analysis.", + "metadata": { + "irac_section": "Application" + }, + "score": 30.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_10", + "description": "Identifies that one ground the arbitrator gave for distinguishing the comparator cases was on-duty status.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 7 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"1. State the scope of review the arbitrator was required to apply to MPD's penalty selection under Douglas and D.C. Mun. Regs. tit. 6-B, \u00a7 1606.2 (2017), and assess whether the arbitrator's treatment of Douglas factors six and twelve stayed within that scope. Address the arbitrator's requirement that MPD 'prove' the comparability of the comparator cases on factor six, and the arbitrator's finding that a suspension would 'likely' have sufficed to deter future misconduct on factor twelve. Support every point with page and paragraph citations to the uploaded materials.\"", + "metadata": {}, + "score": 4.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_11", + "description": "Identifies that one ground the arbitrator gave for distinguishing the comparator cases was that the comparator incident involved a fatality.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 7 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"1. State the scope of review the arbitrator was required to apply to MPD's penalty selection under Douglas and D.C. Mun. Regs. tit. 6-B, \u00a7 1606.2 (2017), and assess whether the arbitrator's treatment of Douglas factors six and twelve stayed within that scope. Address the arbitrator's requirement that MPD 'prove' the comparability of the comparator cases on factor six, and the arbitrator's finding that a suspension would 'likely' have sufficed to deter future misconduct on factor twelve. Support every point with page and paragraph citations to the uploaded materials.\"", + "metadata": {}, + "score": 4.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_12", + "description": "Identifies that one ground the arbitrator gave for distinguishing the comparator cases was prior force history.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 7 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"1. State the scope of review the arbitrator was required to apply to MPD's penalty selection under Douglas and D.C. Mun. Regs. tit. 6-B, \u00a7 1606.2 (2017), and assess whether the arbitrator's treatment of Douglas factors six and twelve stayed within that scope. Address the arbitrator's requirement that MPD 'prove' the comparability of the comparator cases on factor six, and the arbitrator's finding that a suspension would 'likely' have sufficed to deter future misconduct on factor twelve. Support every point with page and paragraph citations to the uploaded materials.\"", + "metadata": {}, + "score": 4.0, + "polarity": "positive", + "raw_weight": 1.0 + } + ], + "answer_path": "/app/response2.md", + "answer_relative_path": "response2.md", + "is_followon": true, + "prev_answer_path": "/app/response1.md" +} diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/fixtures/rubric.json b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/fixtures/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..48d073f43cf63a54e1ef964261b128f5349c0b17 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/fixtures/rubric.json @@ -0,0 +1,140 @@ +{ + "criteria": [ + { + "name": "criterion_1", + "description": "Mentions that under Douglas an agency-selected penalty stands unless the agency failed to weigh the relevant factors or the penalty exceeded the tolerable limits of reasonableness.", + "source": "Douglas v. Veterans Administration, 5 M.S.P.R. 280, 305-06 (1981) (douglas_v_veterans_admin.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"1. State the scope of review the arbitrator was required to apply to MPD's penalty selection under Douglas and D.C. Mun. Regs. tit. 6-B, \u00a7 1606.2 (2017), and assess whether the arbitrator's treatment of Douglas factors six and twelve stayed within that scope. Address the arbitrator's requirement that MPD 'prove' the comparability of the comparator cases on factor six, and the arbitrator's finding that a suspension would 'likely' have sufficed to deter future misconduct on factor twelve. Support every point with page and paragraph citations to the uploaded materials.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 4.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_2", + "description": "Identifies that the arbitrator required MPD to prove that the comparator officers were similarly situated under Douglas factor six.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 7 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"1. State the scope of review the arbitrator was required to apply to MPD's penalty selection under Douglas and D.C. Mun. Regs. tit. 6-B, \u00a7 1606.2 (2017), and assess whether the arbitrator's treatment of Douglas factors six and twelve stayed within that scope. Address the arbitrator's requirement that MPD 'prove' the comparability of the comparator cases on factor six, and the arbitrator's finding that a suspension would 'likely' have sufficed to deter future misconduct on factor twelve. Support every point with page and paragraph citations to the uploaded materials.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 6.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_3", + "description": "Identifies that the arbitrator\u2019s factor twelve finding rested on his conclusion that a suspension would likely have sufficed to deter future misconduct.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 8 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"1. State the scope of review the arbitrator was required to apply to MPD's penalty selection under Douglas and D.C. Mun. Regs. tit. 6-B, \u00a7 1606.2 (2017), and assess whether the arbitrator's treatment of Douglas factors six and twelve stayed within that scope. Address the arbitrator's requirement that MPD 'prove' the comparability of the comparator cases on factor six, and the arbitrator's finding that a suspension would 'likely' have sufficed to deter future misconduct on factor twelve. Support every point with page and paragraph citations to the uploaded materials.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 6.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_4", + "description": "Identifies that no uploaded authority requires MPD to prove the comparability of its comparator cases.", + "source": "D.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117, \u00b6 19 (May 22, 2024) (final_notice_adverse_action_braddock.pdf); In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 7 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf); Memorandum from Yolanda Britt, Director, Disciplinary Review Division, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Sandra M. Delgado, Assistant Chief, Professional Development Bureau, re: Comparator Discipline Cases, Adverse Action Case No. IS-23-002841 (Braddock), \u00b6\u00b6 2-5 (Apr. 11, 2024) (comparator_discipline_cases.pdf); Douglas v. Veterans Administration, 5 M.S.P.R. 280, 305-06 (1981) (douglas_v_veterans_admin.pdf); D.C. Mun. Regs. tit. 6-B, \u00a7 1606.2 (2017) (dcmr_title6b_1606.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"2. State which party bore the burden of production and persuasion on the comparator evidence at each stage of the proceedings, and assess the legal consequence of Braddock's failure to raise disparate treatment before the arbitration hearing. Identify the strongest position MPD can take on this record and the weakest point in that position, with page and paragraph citations.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 26.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_5", + "description": "States that the employee must make an initial showing of disparate treatment before the agency bears a comparator burden", + "source": "D.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117, \u00b6 19 (May 22, 2024) (final_notice_adverse_action_braddock.pdf); In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 7 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf); Memorandum from Yolanda Britt, Director, Disciplinary Review Division, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Sandra M. Delgado, Assistant Chief, Professional Development Bureau, re: Comparator Discipline Cases, Adverse Action Case No. IS-23-002841 (Braddock), \u00b6\u00b6 2-5 (Apr. 11, 2024) (comparator_discipline_cases.pdf); Douglas v. Veterans Administration, 5 M.S.P.R. 280, 305-06 (1981) (douglas_v_veterans_admin.pdf); D.C. Mun. Regs. tit. 6-B, \u00a7 1606.2 (2017) (dcmr_title6b_1606.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cState which party bore the burden of production and persuasion on the comparator evidence at each stage of the proceedings.\u201d Stating the initial-showing rule as settled law relies on authority outside the uploaded materials.", + "metadata": { + "irac_section": "Application" + }, + "score": -18.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_6", + "description": "Mentions that D.C. Mun. Regs. tit. 6-B, \u00a7 1606.2 (2017) requires the deciding official to balance the Douglas-type factors when selecting a penalty.", + "source": "D.C. Mun. Regs. tit. 6-B, \u00a7 1606.2 (2017) (dcmr_title6b_1606.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"1. State the scope of review the arbitrator was required to apply to MPD's penalty selection under Douglas and D.C. Mun. Regs. tit. 6-B, \u00a7 1606.2 (2017), and assess whether the arbitrator's treatment of Douglas factors six and twelve stayed within that scope. Address the arbitrator's requirement that MPD 'prove' the comparability of the comparator cases on factor six, and the arbitrator's finding that a suspension would 'likely' have sufficed to deter future misconduct on factor twelve. Support every point with page and paragraph citations to the uploaded materials.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 4.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_7", + "description": "States that the arbitrator was entitled to select whatever penalty he considered most appropriate without deference to MPD\u2019s penalty selection", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 5 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf); Douglas v. Veterans Administration, 5 M.S.P.R. 280, 305-06 (1981) (douglas_v_veterans_admin.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"1. State the scope of review the arbitrator was required to apply to MPD's penalty selection under Douglas and D.C. Mun. Regs. tit. 6-B, \u00a7 1606.2 (2017), and assess whether the arbitrator's treatment of Douglas factors six and twelve stayed within that scope. Address the arbitrator's requirement that MPD 'prove' the comparability of the comparator cases on factor six, and the arbitrator's finding that a suspension would 'likely' have sufficed to deter future misconduct on factor twelve. Support every point with page and paragraph citations to the uploaded materials.\" Entitlement to an unconstrained penalty choice is the scope error the instruction tests.", + "metadata": { + "irac_section": "Rule" + }, + "score": -24.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_8", + "description": "Mentions authority absent from the uploaded materials in support of the burden allocation.", + "source": "D.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117, \u00b6 19 (May 22, 2024) (final_notice_adverse_action_braddock.pdf); In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 7 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf); Memorandum from Yolanda Britt, Director, Disciplinary Review Division, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Sandra M. Delgado, Assistant Chief, Professional Development Bureau, re: Comparator Discipline Cases, Adverse Action Case No. IS-23-002841 (Braddock), \u00b6\u00b6 2-5 (Apr. 11, 2024) (comparator_discipline_cases.pdf); Douglas v. Veterans Administration, 5 M.S.P.R. 280, 305-06 (1981) (douglas_v_veterans_admin.pdf); D.C. Mun. Regs. tit. 6-B, \u00a7 1606.2 (2017) (dcmr_title6b_1606.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cDo not rely on, reference, or infer any legal authority, factual information, or data beyond what is contained in these uploaded files.\u201d", + "metadata": {}, + "score": -22.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_9", + "description": "Identifies that the Award\u2019s citation to Douglas v. Veterans Administration, 5 M.S.P.R. 280, 306 (1981) does not correspond to any page of the uploaded Douglas opinion.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 5 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf); Douglas v. Veterans Administration, 5 M.S.P.R. 280 (1981) (douglas_v_veterans_admin.pdf), paginated 313 to 346", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cSupport every point with page and paragraph citations to the uploaded materials.\u201d Verifying the Award\u2019s own citations against the uploaded opinion is part of citation-supported analysis.", + "metadata": { + "irac_section": "Application" + }, + "score": 30.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_10", + "description": "Identifies that one ground the arbitrator gave for distinguishing the comparator cases was on-duty status.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 7 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"1. State the scope of review the arbitrator was required to apply to MPD's penalty selection under Douglas and D.C. Mun. Regs. tit. 6-B, \u00a7 1606.2 (2017), and assess whether the arbitrator's treatment of Douglas factors six and twelve stayed within that scope. Address the arbitrator's requirement that MPD 'prove' the comparability of the comparator cases on factor six, and the arbitrator's finding that a suspension would 'likely' have sufficed to deter future misconduct on factor twelve. Support every point with page and paragraph citations to the uploaded materials.\"", + "metadata": {}, + "score": 4.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_11", + "description": "Identifies that one ground the arbitrator gave for distinguishing the comparator cases was that the comparator incident involved a fatality.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 7 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"1. State the scope of review the arbitrator was required to apply to MPD's penalty selection under Douglas and D.C. Mun. Regs. tit. 6-B, \u00a7 1606.2 (2017), and assess whether the arbitrator's treatment of Douglas factors six and twelve stayed within that scope. Address the arbitrator's requirement that MPD 'prove' the comparability of the comparator cases on factor six, and the arbitrator's finding that a suspension would 'likely' have sufficed to deter future misconduct on factor twelve. Support every point with page and paragraph citations to the uploaded materials.\"", + "metadata": {}, + "score": 4.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_12", + "description": "Identifies that one ground the arbitrator gave for distinguishing the comparator cases was prior force history.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 7 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"1. State the scope of review the arbitrator was required to apply to MPD's penalty selection under Douglas and D.C. Mun. Regs. tit. 6-B, \u00a7 1606.2 (2017), and assess whether the arbitrator's treatment of Douglas factors six and twelve stayed within that scope. Address the arbitrator's requirement that MPD 'prove' the comparability of the comparator cases on factor six, and the arbitrator's finding that a suspension would 'likely' have sufficed to deter future misconduct on factor twelve. Support every point with page and paragraph citations to the uploaded materials.\"", + "metadata": {}, + "score": 4.0, + "polarity": "positive", + "raw_weight": 1.0 + } + ] +} diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/m1_judge_panel.json b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/m1_judge_panel.json new file mode 100644 index 0000000000000000000000000000000000000000..a8041f6781a899f9083fe4a1a95f51bc78d35601 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/m1_judge_panel.json @@ -0,0 +1,21 @@ +{ + "mode": "panel", + "max_concurrent_llm": 12, + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ] +} diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/m1_rewardkit_accounting.py b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/m1_rewardkit_accounting.py new file mode 100644 index 0000000000000000000000000000000000000000..406dc5e7c675b222d94514e71bf5fad6ae141d8f --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/m1_rewardkit_accounting.py @@ -0,0 +1,490 @@ +import asyncio +import json +import math +import os +from pathlib import Path +import random +import sys +import time + +class JudgeReceiptError(OSError): + pass +_LLM_ROUTES = frozenset({'vertex', 'anthropic fallback', 'aistudio', 'direct'}) +_LLM_ROUTE_HEADERS = ('x-m1-llm-route', 'llm_provider-x-m1-llm-route') + +def _canonical_llm_route(value): + return value if isinstance(value, str) and value in _LLM_ROUTES else None + +def _llm_route_from_headers(headers): + if not isinstance(headers, dict): + return None + folded = {str(key).lower(): value for key, value in headers.items()} + for name in _LLM_ROUTE_HEADERS: + route = _canonical_llm_route(folded.get(name)) + if route is not None: + return route + return None + +def _llm_route_from_response(response): + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + route = _llm_route_from_headers(headers) + if route is not None: + return route + return _llm_route_from_headers(getattr(response, 'headers', None)) + +def _token_field_status(values, key): + if not isinstance(values, dict) or key not in values: + return 'missing' + value = values[key] + if value is None: + return 'null' + return 'valid' if type(value) is int and value >= 0 else 'invalid' + +def _gemini_capture(kwargs, model): + if not model.startswith('gemini/') or kwargs.get('stream') or kwargs.get('tools') or kwargs.get('functions'): + return (kwargs, None) + from litellm.integrations.custom_logger import CustomLogger + from urllib.parse import urlsplit + + class Capture(CustomLogger): + evidence = None + prompt_status = 'not_observed' + llm_route = None + + def log_post_api_call(self, kwargs, response_obj, start_time, end_time): + self.evidence = None + self.prompt_status = 'not_observed' + try: + params = kwargs.get('litellm_params') or {} + route = urlsplit(params.get('api_base') or '') + bare = model.removeprefix('gemini/') + gemini = params.get('custom_llm_provider') == 'gemini' + ai_studio = gemini and route.hostname == 'generativelanguage.googleapis.com' and (route.path in {'/' + version + '/models/' + bare + ':generateContent' for version in ('v1alpha', 'v1beta')}) + broker = urlsplit(os.environ.get('GEMINI_API_BASE') or '') + brokered = gemini and bool(broker.netloc) and (route.netloc == broker.netloc) and (broker.path.rstrip('/').rsplit('/', 1)[-1] in ('v1alpha', 'v1beta')) and (route.path == broker.path.rstrip('/') + '/models/' + bare + ':generateContent') + vertex = params.get('custom_llm_provider') == 'vertex_ai' and route.hostname == 'aiplatform.googleapis.com' and route.path.startswith('/v1/projects/') and route.path.endswith('/locations/global/publishers/google/models/' + bare + ':generateContent') + if route.scheme != 'https' or not (ai_studio or brokered or vertex) or kwargs.get('stream'): + return + self.llm_route = 'vertex' if vertex else 'aistudio' if ai_studio else None + raw = kwargs.get('original_response') + raw = json.loads(raw) if isinstance(raw, str) else raw + if not isinstance(raw, dict): + return + candidates = raw.get('candidates') + if not isinstance(candidates, list) or not candidates or any((not isinstance(c, dict) or not c.get('finishReason') for c in candidates)) or (not isinstance(raw.get('modelVersion'), str)) or (not raw['modelVersion']): + return + usage = raw.get('usageMetadata') + self.prompt_status = _token_field_status(usage, 'promptTokenCount') + if not isinstance(usage, dict): + return + fields = ('promptTokenCount', 'candidatesTokenCount', 'thoughtsTokenCount', 'cachedContentTokenCount', 'totalTokenCount', 'toolUsePromptTokenCount') + counts = {key: usage.get(key, 0) for key in fields} + if not {'promptTokenCount', 'totalTokenCount'} <= usage.keys() or any((type(n) is not int or n < 0 for n in counts.values())) or counts['toolUsePromptTokenCount'] != 0 or (counts['cachedContentTokenCount'] > counts['promptTokenCount']) or (counts['totalTokenCount'] != counts['promptTokenCount'] + counts['candidatesTokenCount'] + counts['thoughtsTokenCount']): + return + self.evidence = {'protocol': 'gemini-generate-content-' + ('vertex-v1' if vertex else route.path.split('/')[-3]), 'model_version': raw['modelVersion'], 'usage_metadata': {key: usage[key] for key in fields if key in usage}, 'defaulted_fields': [key for key in fields if key not in usage]} + except (TypeError, ValueError, AttributeError): + return + capture = Capture() + return ({**kwargs, 'callbacks': [*(kwargs.get('callbacks') or []), capture]}, capture) + +def _record_judge_usage(response, model: str, *, target: Path | None=None, native_usage: dict | None=None, native_prompt_status: str | None=None, llm_route: str | None=None) -> None: + import fcntl + from datetime import datetime, timezone + data = response.model_dump() if hasattr(response, 'model_dump') else response + usage = data.get('usage') if isinstance(data, dict) else None + granularity = data.get('usage_granularity') if isinstance(data, dict) else None + if not isinstance(usage, dict): + usage = {} + granularity = 'missing_provider_receipt' + prompt, completion = (usage.get('prompt_tokens'), usage.get('completion_tokens')) + native_fresh = usage.get('input_uncached_tokens') + prompt = prompt if type(prompt) is int and prompt >= 0 else None + native_fresh = native_fresh if type(native_fresh) is int and native_fresh >= 0 else None + if type(completion) is not int or completion < 0 or (prompt is None and native_fresh is None): + completion = completion if type(completion) is int and completion >= 0 else 0 + granularity = granularity or 'invalid_provider_receipt' + details = usage.get('prompt_tokens_details') + if details is not None and (not isinstance(details, dict)): + granularity = 'invalid_provider_receipt' + details = details if isinstance(details, dict) else {} + cached = details.get('cached_tokens') + if native_usage is not None: + native = native_usage['usage_metadata'] + native_output = native.get('candidatesTokenCount', 0) + native.get('thoughtsTokenCount', 0) + if prompt == native['promptTokenCount'] and completion == native_output: + cached = native.get('cachedContentTokenCount', 0) + else: + native_usage = None + written = next((value for value in (usage.get('input_cache_write_tokens'), usage.get('cache_creation_input_tokens'), details.get('cache_creation_tokens'), details.get('cache_write_tokens')) if value is not None), None) + invalid = any((value is not None and (type(value) is not int or value < 0) for value in (cached, written))) + cached = cached if type(cached) is int and cached >= 0 else None + written = written if type(written) is int and written >= 0 else None + fresh = native_fresh + if fresh is None and prompt is not None and (cached is not None) and (written is not None): + fresh = prompt - cached - written + if fresh is not None and (fresh < 0 or (prompt is not None and cached is not None and (written is not None) and (fresh + cached + written != prompt))): + invalid, fresh = (True, None) + provider, _, slug = model.partition('/') + event: dict = {'type': 'step_finish', 'part': {'providerID': provider if slug else 'openai', 'modelID': slug or model, 'tokens': {'input': fresh, 'output': completion, 'cache': {'read': cached, 'write': written}}}} + field_status = {'prompt_tokens': _token_field_status(usage, 'prompt_tokens'), 'completion_tokens': _token_field_status(usage, 'completion_tokens'), 'input_uncached_tokens': _token_field_status(usage, 'input_uncached_tokens')} + field_status['native_prompt_token_count'] = native_prompt_status if native_prompt_status in {'missing', 'null', 'invalid', 'valid', 'not_observed'} else 'unsupported' + part: dict = event['part'] + part['usage_field_status'] = field_status + if native_usage is not None: + event['part']['native_usage'] = native_usage + event['part']['token_categories_provenance'] = 'explicit_presence_v1' + if fresh is None and prompt is not None: + event['part']['prompt_tokens_inclusive'] = prompt + if invalid or any((value is None for value in (fresh, cached, written))): + granularity = granularity if granularity not in (None, 'request') else 'invalid_provider_receipt' if invalid else 'incomplete_token_categories' + if granularity: + event['part']['usage_granularity'] = granularity + if provider == 'openrouter': + cost = usage.get('cost') + if cost is None: + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + if isinstance(headers, dict): + cost = headers.get('llm_provider-x-litellm-response-cost') + if isinstance(cost, (int, float)) and (not isinstance(cost, bool)) and math.isfinite(cost) and (cost >= 0): + event['part']['cost'] = cost + data = data if isinstance(data, dict) else {} + if isinstance(data.get('id'), str) and data['id']: + event['part']['provider_request_id'] = data['id'] + for key in ('service_tier', 'cache_ttl'): + if data.get(key): + event['part'][key] = data[key] + route = _llm_route_from_response(response) or _canonical_llm_route(llm_route) + if route is not None: + event['part']['llm_route'] = route + created = data.get('created') + stamp = datetime.now(timezone.utc) + try: + if isinstance(created, str): + parsed = datetime.fromisoformat(created.replace('Z', '+00:00')) + if parsed.tzinfo is not None: + stamp = parsed + elif isinstance(created, (int, float)) and (not isinstance(created, bool)) and math.isfinite(created): + stamp = datetime.fromtimestamp(created, timezone.utc) + except (ValueError, OverflowError, OSError): + pass + pair = json.dumps({'type': 'step_start', 'timestamp': stamp.isoformat()}) + '\n' + pair += json.dumps(event) + '\n' + try: + receipt_path = target or Path(os.environ.get('M1_JUDGE_USAGE_PATH', '/logs/verifier/judge-trajectory.jsonl')) + receipt_path.parent.mkdir(parents=True, exist_ok=True) + with receipt_path.open('a') as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + handle.write(pair) + handle.flush() + os.fsync(handle.fileno()) + except OSError as exc: + if target is not None: + raise JudgeReceiptError(f'judge receipt write failed: {exc}') from exc + print(f'judge accounting: write failed ({type(exc).__name__})', file=sys.stderr) + +def openrouter_judge_pins() -> dict[str, dict]: + raw = os.environ.get('M1_OPENROUTER_JUDGE_PROVIDER_PINS', '').strip() + if not raw: + return {} + try: + pins = json.loads(raw) + except json.JSONDecodeError: + print('judge provider pins: invalid JSON in M1_OPENROUTER_JUDGE_PROVIDER_PINS', file=sys.stderr) + return {} + return {model: pin for model, pin in pins.items() if isinstance(pin, dict) and pin.get('order')} if isinstance(pins, dict) else {} + +def apply_judge_provider_pin(kwargs: dict, pins: dict[str, dict]) -> dict: + model = kwargs.get('model') + pin = pins.get(model) if isinstance(model, str) else None + if pin is None: + return kwargs + extra_body = dict(kwargs.get('extra_body') or {}) + provider = dict(extra_body.get('provider') or {}) + provider['order'] = list(pin['order']) + if pin.get('allow_fallbacks') is False: + provider['allow_fallbacks'] = False + if pin.get('zdr'): + provider['zdr'] = True + extra_body['provider'] = provider + return {**kwargs, 'extra_body': extra_body} +_TRANSIENT_ERROR_NAMES = ('RateLimitError', 'ServiceUnavailableError', 'InternalServerError', 'BadGatewayError', 'APIConnectionError') +_RETRYABLE_STATUS_CODES = frozenset({408, 409, 425, 429, 500, 502, 503, 504}) +_AUTH_ERROR_NAMES = ('AuthenticationError', 'PermissionDeniedError') +_AUTH_STATUS_CODES = frozenset({401, 403}) +_AUTH_RETRIES = 4 +_DEFAULT_TRANSIENT_RETRIES = 6 +_MAX_TRANSIENT_RETRIES = 20 +_MAX_RETRY_DELAY_SECONDS = 60.0 +_DEFAULT_EMPTY_RESPONSE_RETRIES = 3 +_DEFAULT_RETRY_BUDGET_SECONDS = 900.0 +_MAX_RETRY_BUDGET_SECONDS = 86400.0 + +def transient_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_TRANSIENT_RETRIES', '').strip() + if not raw: + return _DEFAULT_TRANSIENT_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_TRANSIENT_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_TRANSIENT_RETRIES + +def empty_response_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_EMPTY_RESPONSE_RETRIES', '').strip() + if not raw: + return _DEFAULT_EMPTY_RESPONSE_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_EMPTY_RESPONSE_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_EMPTY_RESPONSE_RETRIES + +def retry_budget_seconds() -> float: + raw = os.environ.get('M1_JUDGE_RETRY_BUDGET_SECONDS', '').strip() + if not raw: + return _DEFAULT_RETRY_BUDGET_SECONDS + try: + value = float(raw) + except ValueError: + value = math.nan + if not math.isfinite(value) or value < 0: + print('judge retries: invalid M1_JUDGE_RETRY_BUDGET_SECONDS, using the default', file=sys.stderr) + return _DEFAULT_RETRY_BUDGET_SECONDS + return min(value, _MAX_RETRY_BUDGET_SECONDS) + +def _within_budget(deadline: float, delay: float, model) -> bool: + remaining = deadline - time.monotonic() + if delay <= remaining: + return True + print(f'judge call retry budget spent: {model} would wait {delay:.1f}s with {max(remaining, 0.0):.1f}s left of M1_JUDGE_RETRY_BUDGET_SECONDS, failing now', file=sys.stderr) + return False + +def is_empty_verdict(response) -> bool: + data = response.model_dump() if hasattr(response, 'model_dump') else response + if not isinstance(data, dict): + return False + choices = data.get('choices') + if not isinstance(choices, list) or not choices: + return True + first = choices[0] + message = first.get('message') if isinstance(first, dict) else None + if not isinstance(message, dict): + return True + if message.get('tool_calls') or message.get('function_call'): + return False + content = message.get('content') + if isinstance(content, list): + content = ''.join((part.get('text') or '' for part in content if isinstance(part, dict))) + return not (isinstance(content, str) and content.strip()) + +def _matches(exc: BaseException, litellm, names: tuple[str, ...], statuses: frozenset[int]) -> bool: + classes = tuple((cls for cls in (getattr(litellm, name, None) for name in names) if isinstance(cls, type))) + if classes and isinstance(exc, classes): + return True + status = getattr(exc, 'status_code', None) + return type(status) is int and status in statuses + +def is_transient_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _TRANSIENT_ERROR_NAMES, _RETRYABLE_STATUS_CODES) + +def is_auth_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _AUTH_ERROR_NAMES, _AUTH_STATUS_CODES) + +def should_retry(exc: BaseException, litellm, attempt: int, limit: int) -> bool: + if attempt < limit and is_transient_error(exc, litellm): + return True + return attempt < min(limit, _AUTH_RETRIES) and is_auth_error(exc, litellm) + +def _retry_after_seconds(exc: BaseException) -> float | None: + headers = getattr(exc, 'headers', None) + if headers is None: + headers = getattr(getattr(exc, 'response', None), 'headers', None) + if headers is None: + return None + try: + raw = headers.get('retry-after') + if raw is None: + raw = headers.get('Retry-After') + value = float(raw) + except (AttributeError, TypeError, ValueError): + return None + return value if math.isfinite(value) and value >= 0 else None + +def retry_delay(exc: BaseException | None, attempt: int) -> float: + base = min(_MAX_RETRY_DELAY_SECONDS, 2.0 ** (attempt + 1)) + delay = base * (0.5 + random.random()) + retry_after = _retry_after_seconds(exc) if exc is not None else None + if retry_after is not None: + delay = max(delay, min(_MAX_RETRY_DELAY_SECONDS, retry_after)) + return delay + +def _note_retry(model, exc: BaseException, attempt: int, limit: int, delay: float) -> None: + status = getattr(exc, 'status_code', None) + print(f"judge call retry {attempt}/{limit}: {model} {type(exc).__name__} status={(status if type(status) is int else 'n/a')}, waiting {delay:.1f}s", file=sys.stderr) + +def _note_empty(model, response, attempt: int, limit: int, delay: float) -> None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + reason = None + if isinstance(data, dict) and isinstance(data.get('choices'), list) and data['choices']: + first = data['choices'][0] + reason = first.get('finish_reason') if isinstance(first, dict) else None + print(f'judge call retry {attempt}/{limit}: {model} empty verdict (finish_reason={reason}), waiting {delay:.1f}s', file=sys.stderr) + +def install(litellm, *, synchronous: bool=False) -> None: + pins = openrouter_judge_pins() + limit = transient_retry_limit() + empty_limit = empty_response_retry_limit() + deadline = time.monotonic() + retry_budget_seconds() + if synchronous: + original = litellm.completion + + def accounted(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = original(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + time.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + time.sleep(delay) + continue + return response + litellm.completion = accounted + return + original_async = litellm.acompletion + + async def accounted_async(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = await original_async(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + await asyncio.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + await asyncio.sleep(delay) + continue + return response + litellm.acompletion = accounted_async + +def record_agent_usage(attempt, *, model: str, provider: str) -> None: + records: dict[str, tuple[str, dict]] = {} + current_model = model + for filename in getattr(attempt, 'logs', []): + try: + with Path(filename).open() as stream: + for line in stream: + try: + event = json.loads(line) + except (ValueError, TypeError): + continue + if not isinstance(event, dict): + continue + message = event.get('message') or {} + if event.get('type') == 'assistant' and isinstance(message, dict) and isinstance(message.get('usage'), dict): + raw = message['usage'] + cached, written = (raw.get('cache_read_input_tokens'), raw.get('cache_creation_input_tokens')) + if all((type(value) is int and value >= 0 for value in (raw.get('input_tokens'), raw.get('output_tokens')))) and all((value is None or (type(value) is int and value >= 0) for value in (cached, written))): + receipt: dict = {'usage': {'input_uncached_tokens': raw['input_tokens'], 'prompt_tokens': raw['input_tokens'] + cached + written if cached is not None and written is not None else None, 'completion_tokens': raw['output_tokens'], 'prompt_tokens_details': {'cached_tokens': cached, 'cache_creation_tokens': written}}} + receipt['created'] = event.get('timestamp') + creation = raw.get('cache_creation') or {} + hour = creation.get('ephemeral_1h_input_tokens', 0) if isinstance(creation, dict) else 0 + if type(hour) is int and hour > 0: + if hour == written: + receipt['cache_ttl'] = '1h' + else: + receipt['usage_granularity'] = 'mixed_cache_ttl' + records[message.get('id') or json.dumps(raw, sort_keys=True)] = (message.get('model') or current_model, receipt) + payload = event.get('payload') or {} + if not isinstance(payload, dict): + continue + if event.get('type') == 'turn_context' and payload.get('model'): + current_model = payload['model'] + if event.get('type') == 'event_msg' and payload.get('type') == 'token_count': + info = payload.get('info') or {} + raw, total = (info.get('last_token_usage'), info.get('total_token_usage')) + if isinstance(raw, dict) and isinstance(total, dict) and all((type(raw.get(key)) is int and raw.get(key) >= 0 for key in ('input_tokens', 'output_tokens'))): + receipt = {'usage': {'prompt_tokens': raw.get('input_tokens'), 'input_uncached_tokens': raw.get('input_uncached_tokens'), 'input_cache_write_tokens': raw.get('input_cache_write_tokens'), 'completion_tokens': raw.get('output_tokens'), 'prompt_tokens_details': {'cached_tokens': raw.get('cached_input_tokens')}}} + receipt['created'] = event.get('timestamp') + records[json.dumps(total, sort_keys=True)] = (current_model, receipt) + except OSError: + continue + captured_input = captured_output = 0 + input_complete = True + for requested, receipt in records.values(): + requested = requested if '/' in requested else f'{provider}/{requested}' + _record_judge_usage(receipt, requested) + receipt_input = receipt['usage'].get('prompt_tokens') + if receipt_input is None: + input_complete = False + else: + captured_input += receipt_input + captured_output += receipt['usage'].get('completion_tokens') or 0 + total = getattr(attempt, 'usage', {}) or {} + if not records or (input_complete and total.get('input_tokens') != captured_input) or total.get('output_tokens') != captured_output: + _record_judge_usage({'usage': {'prompt_tokens': 0, 'completion_tokens': 0}, 'usage_granularity': 'incomplete_agent_receipts'}, model if '/' in model else f'{provider}/{model}') + +def install_rewardkit_agents() -> None: + import rewardkit.judges as judges + original = judges.get_agent + + def get_accounted_agent(judge, cwd=None): + backend = original(judge, cwd) + run = backend.run + + async def accounted_run(*args, **kwargs): + attempt = await run(*args, **kwargs) + record_agent_usage(attempt, model=judge.model or 'unknown', provider='anthropic' if judge.agent == 'claude-code' else 'openai') + return attempt + setattr(backend, 'run', accounted_run) + return backend + setattr(judges, 'get_agent', get_accounted_agent) +if __name__ == '__main__': + import litellm + if len(sys.argv) > 2 and sys.argv[1] == '--script': + import runpy + install(litellm, synchronous=True) + sys.argv = sys.argv[2:] + runpy.run_path(sys.argv[0], run_name='__main__') + else: + install(litellm) + install_rewardkit_agents() + if Path(__file__).with_name('m1_judge_panel.json').is_file(): + from m1_rewardkit_panel import install_panel + install_panel(Path(__file__).with_name('m1_judge_panel.json')) + if Path(__file__).with_name('m1_judge_jev.json').is_file(): + from m1_rewardkit_jev import install_jev + install_jev(Path(__file__).with_name('m1_judge_jev.json')) + from rewardkit.__main__ import main + main() diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/m1_rewardkit_panel.py b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/m1_rewardkit_panel.py new file mode 100644 index 0000000000000000000000000000000000000000..164cc2ae521cdd368c2e1749d7ed8fe09f4545eb --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/m1_rewardkit_panel.py @@ -0,0 +1,169 @@ +from __future__ import annotations +import asyncio +from contextvars import ContextVar +import json +import math +import os +import sys +from pathlib import Path +from typing import Any +import uuid +_request_audit: ContextVar[tuple[Path, list[str]] | None] = ContextVar('panel_request_audit', default=None) + +class PanelIncompleteError(RuntimeError): + pass + +def _audit_warning(exc: Exception, warnings: list[str]) -> None: + message = f'judge panel audit: diagnostic capture failed ({type(exc).__name__})' + if message not in warnings: + warnings.append(message) + print(message, file=sys.stderr) + +def _write_audit(path: Path, record: dict[str, Any], warnings: list[str], *, append: bool=False) -> None: + try: + text = json.dumps(record, allow_nan=False, default=str) + '\n' + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('a' if append else 'w') as stream: + stream.write(text) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + +def _binary(raw: Any) -> int: + if isinstance(raw, bool): + return int(raw) + if isinstance(raw, int | float) and math.isfinite(raw) and (raw in (0, 1)): + return int(raw) + if isinstance(raw, str): + value = raw.strip().lower() + if value in {'yes', 'true', '1'}: + return 1 + if value in {'no', 'false', '0'}: + return 0 + raise PanelIncompleteError('m1_judge_panel_incomplete: invalid binary vote') + +def validate_votes(scores: list[Any], criteria: list[Any]) -> None: + names = [criterion.name for criterion in criteria] + if len(set(names)) != len(names) or [score.name for score in scores] != names: + raise PanelIncompleteError('m1_judge_panel_incomplete: criterion membership mismatch') + for score, criterion in zip(scores, criteria, strict=True): + if score.error: + raise PanelIncompleteError('m1_judge_panel_incomplete: judge returned an error') + raw = _binary(score.raw) + expected = 1 - raw if criterion.negate else raw + if not math.isfinite(score.value) or score.value != expected: + raise PanelIncompleteError('m1_judge_panel_incomplete: inconsistent binary score') + +async def run_panel(judge: Any, criteria: list[Any], weights: list[float] | None, system_prompt: str | None, *, config: dict[str, Any], run_llm: Any, score_type: Any, audit_dir: Path) -> tuple[list[Any], str, list[str]]: + from rewardkit.models import Binary + if not criteria or any((not isinstance(criterion.output_format, Binary) for criterion in criteria)): + raise ValueError('panel majority voting requires nonempty binary criteria') + group_dir = audit_dir / uuid.uuid4().hex + warnings_out: list[str] = [] + + async def member_call(index: int, member: dict[str, Any]): + member_judge = judge.model_copy(update=member) + evidence: dict[str, Any] = {'member': index + 1, 'judge': member, 'criteria': [criterion.name for criterion in criteria], 'status': 'started'} + path = group_dir / f'judge-{index + 1}.json' + _write_audit(path, evidence, warnings_out) + token = _request_audit.set((group_dir / f'judge-{index + 1}-requests.jsonl', warnings_out)) + try: + scores, output, warnings = await run_llm(member_judge, criteria, weights, system_prompt) + evidence.update(output=output, warnings=warnings) + validate_votes(scores, criteria) + evidence['scores'] = [score.to_dict() for score in scores] + evidence['status'] = 'completed' + return (scores, output, warnings) + except BaseException as exc: + evidence.update(status='failed', error_class=type(exc).__name__) + if isinstance(exc, PanelIncompleteError): + evidence['error'] = str(exc) + raise + finally: + _request_audit.reset(token) + _write_audit(path, evidence, warnings_out) + outcomes = await asyncio.gather(*(member_call(index, member) for index, member in enumerate(config['members'])), return_exceptions=True) + failed = [index + 1 for index, result in enumerate(outcomes) if isinstance(result, BaseException)] + if failed: + _write_audit(group_dir / 'panel.json', {'status': 'incomplete', 'failed_members': failed}, warnings_out) + raise PanelIncompleteError(f'm1_judge_panel_incomplete: failed members {failed}; see panel audit artifacts') + completed = [outcome for outcome in outcomes if not isinstance(outcome, BaseException)] + combined = [] + for index, criterion in enumerate(criteria): + votes = [{'judge': config['members'][member_index], **outcome[0][index].to_dict()} for member_index, outcome in enumerate(completed)] + passes = sum((vote['value'] == 1 for vote in votes)) + value = int(passes >= 2) + combined.append(score_type(name=criterion.name, value=value, raw=bool(1 - value if criterion.negate else value), weight=weights[index] if weights is not None else 1.0, reasoning=f'{passes}/3 judges passed; strict majority requires 2/3.', description=criterion.description, id=criterion.id, negate=criterion.negate, optional=criterion.optional, votes=votes)) + for outcome in completed: + warnings_out.extend(outcome[2]) + audit = {'status': 'completed', 'mode': 'panel', 'aggregation': 'majority', 'required_votes': 2, 'members': config['members'], 'criteria': [score.to_dict() for score in combined]} + output = json.dumps(audit, indent=2, allow_nan=False) + _write_audit(group_dir / 'panel.json', audit, warnings_out) + return (combined, output, warnings_out) + +def install_panel(config_path: Path, *, audit_dir: Path=Path('/logs/verifier/judge-panel')) -> None: + import rewardkit.judges as judges + import rewardkit.reward as reward + from rewardkit.models import LLMJudge, Score + import litellm + config = json.loads(config_path.read_text()) + members = config.get('members') + concurrency = config.get('max_concurrent_llm') + if config.get('mode') != 'panel' or not isinstance(members, list) or len(members) != 3 or (len({member['model'] for member in members}) != 3) or (type(concurrency) is not int) or (not 1 <= concurrency <= 64): + raise ValueError('invalid materialized panel configuration') + if os.environ.get('REWARDKIT_JUDGE') or os.environ.get('REWARDKIT_MODEL'): + raise ValueError('RewardKit environment overrides cannot replace a frozen panel') + + class PanelScore(Score): + votes: list[dict[str, Any]] + + def to_dict(self): + return {**super().to_dict(), 'votes': self.votes} + original_llm = judges.arun_llm + original_call = judges._arun_llm_call + original_details = reward.Reward.to_detail_dict + original_completion = litellm.acompletion + active_loop = None + semaphore = None + + async def captured_completion(*args, **kwargs): + context = _request_audit.get() + record = {'requested_model': kwargs.get('model')} + response = None + try: + response = await original_completion(*args, **kwargs) + return response + except BaseException as exc: + record['error_class'] = type(exc).__name__ + raise + finally: + if context is not None: + path, warnings = context + try: + if response is not None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + record.update(response_model=data.get('model'), choices=data.get('choices')) + _write_audit(path, record, warnings, append=True) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + + async def bounded_call(*args, **kwargs): + nonlocal active_loop, semaphore + loop = asyncio.get_running_loop() + if active_loop is not loop: + active_loop, semaphore = (loop, asyncio.Semaphore(concurrency)) + assert semaphore is not None + async with semaphore: + return await original_call(*args, **kwargs) + + async def panel_call(judge, criteria, weights=None, system_prompt=None): + return await run_panel(judge, criteria, weights, system_prompt, config=config, run_llm=original_llm, score_type=PanelScore, audit_dir=audit_dir) + + def panel_details(self, score): + detail = original_details(self, score) + if isinstance(self.judge, LLMJudge): + detail.update(kind='llm_panel', judge=config, aggregation='majority', required_votes=2) + return detail + setattr(reward, 'arun_llm', panel_call) + setattr(judges, '_arun_llm_call', bounded_call) + setattr(litellm, 'acompletion', captured_completion) + reward.Reward.to_detail_dict = panel_details diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/normalize_reward.py b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/normalize_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..91817ef00ea9152ca57f0030d8e879eb850ddff0 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/normalize_reward.py @@ -0,0 +1,71 @@ +from __future__ import annotations +import argparse +import json +from pathlib import Path +from typing import Any + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument('--raw-details', required=True) + parser.add_argument('--rubric', required=True) + parser.add_argument('--reward-out', required=True) + parser.add_argument('--details-out', required=True) + args = parser.parse_args() + raw_details = _load_json(Path(args.raw_details)) + rubric = _load_json(Path(args.rubric)) + criteria = rubric['criteria'] + raw_by_name = _raw_criteria_by_name(raw_details) + positive_total = sum((float(item['score']) for item in criteria if float(item['score']) > 0)) + if positive_total <= 0: + raise ValueError('rubric must contain at least one positive score') + earned = 0.0 + normalized_criteria: list[dict[str, Any]] = [] + for item in criteria: + signed_score = float(item['score']) + raw = raw_by_name.get(item['name'], {}) + value = _coerce_score(raw.get('value', 0.0)) + contribution = value * signed_score + earned += contribution + normalized_criteria.append({'name': item['name'], 'value': value, 'raw': raw.get('raw'), 'weight': signed_score, 'signed_score': signed_score, 'polarity': item['polarity'], 'contribution': contribution, 'description': item['description'], 'source': item.get('source', ''), 'justification': item.get('justification', ''), 'metadata': item.get('metadata', {}), 'reasoning': raw.get('reasoning'), 'judge_reasoning': raw.get('reasoning'), 'judge_error': raw.get('error'), **({'votes': raw['votes']} if 'votes' in raw else {})}) + unclamped = earned / positive_total + reward = max(0.0, min(1.0, unclamped)) + reward_out = {'correctness': reward} + details_out = {'correctness': {'score': reward, 'kind': 'signed_score', 'criteria': normalized_criteria, 'aggregation': {'method': 'signed_score_ratio_clamped', 'earned': earned, 'positive_total': positive_total, 'unclamped': unclamped, 'clamped': reward}, 'raw_rewardkit': raw_details}} + _write_json(Path(args.reward_out), reward_out) + _write_json(Path(args.details_out), details_out) + +def _load_json(path: Path) -> Any: + return json.loads(path.read_text()) + +def _write_json(path: Path, data: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data, indent=2) + '\n') + +def _raw_criteria_by_name(details: dict[str, Any]) -> dict[str, dict[str, Any]]: + out: dict[str, dict[str, Any]] = {} + for reward in details.values(): + for item in _iter_raw_criteria(reward): + name = item.get('name') + if isinstance(name, str): + out[name] = item + return out + +def _iter_raw_criteria(value: Any): + if isinstance(value, list): + for item in value: + yield from _iter_raw_criteria(item) + return + if not isinstance(value, dict): + return + for item in value.get('criteria') or []: + if isinstance(item, dict): + yield item + +def _coerce_score(value: Any) -> float: + if isinstance(value, bool): + return 1.0 if value else 0.0 + if isinstance(value, int | float): + return max(0.0, min(1.0, float(value))) + return 0.0 +if __name__ == '__main__': + main() diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/agent_prompt.md b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/agent_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..ca489c065bafd5d10e764f033c9dfd1195933db3 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/agent_prompt.md @@ -0,0 +1,10 @@ +You are grading the submitted legal analysis against the criteria below. + +Read `/logs/artifacts/answer.md`, the answer captured by the verifier, before +assigning any scores. Evaluate that file as the submission. Other files in +`/app` may supply context, but must not replace the submitted answer. Do not +modify the submission. If it is missing or empty, state that in your reasoning +and apply the criteria to that missing or empty submission. Preserve each +criterion's stated positive or penalty polarity. + +{criteria} diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_1.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_1.toml new file mode 100644 index 0000000000000000000000000000000000000000..354f997421bd159d8635315f60ef701ca831f226 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_1.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_1" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions that under Douglas an agency-selected penalty stands unless the agency failed to weigh the relevant factors or the penalty exceeded the tolerable limits of reasonableness." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_10.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_10.toml new file mode 100644 index 0000000000000000000000000000000000000000..3f49bb3b0d7d1a288113635d09cb0ad6da216d75 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_10.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_10" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that one ground the arbitrator gave for distinguishing the comparator cases was on-duty status." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_11.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_11.toml new file mode 100644 index 0000000000000000000000000000000000000000..4f7a2292ad54f6ffebf8e0a861ecb790677dd437 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_11.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_11" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that one ground the arbitrator gave for distinguishing the comparator cases was that the comparator incident involved a fatality." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_12.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_12.toml new file mode 100644 index 0000000000000000000000000000000000000000..7df93ca2e81b8904133bf0ff5472057084aefe60 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_12.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_12" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that one ground the arbitrator gave for distinguishing the comparator cases was prior force history." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_2.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_2.toml new file mode 100644 index 0000000000000000000000000000000000000000..b200907d60a51ff99c13783a1c3b076e6a9e6b13 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_2.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_2" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that the arbitrator required MPD to prove that the comparator officers were similarly situated under Douglas factor six." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_3.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_3.toml new file mode 100644 index 0000000000000000000000000000000000000000..7f9fdf2947220bd317065451a9ee1daeef3efbfc --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_3.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_3" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that the arbitrator’s factor twelve finding rested on his conclusion that a suspension would likely have sufficed to deter future misconduct." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_4.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_4.toml new file mode 100644 index 0000000000000000000000000000000000000000..60970b1a064dcb8fcdc548475f3742b7ff6a3151 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_4.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_4" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that no uploaded authority requires MPD to prove the comparability of its comparator cases." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_5.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_5.toml new file mode 100644 index 0000000000000000000000000000000000000000..9071cbcc23996def5523a255750159dede4e3015 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_5.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_5" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: States that the employee must make an initial showing of disparate treatment before the agency bears a comparator burden" +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_6.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_6.toml new file mode 100644 index 0000000000000000000000000000000000000000..d74d332b839001f21387065b01198c19382aea93 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_6.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_6" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions that D.C. Mun. Regs. tit. 6-B, § 1606.2 (2017) requires the deciding official to balance the Douglas-type factors when selecting a penalty." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_7.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_7.toml new file mode 100644 index 0000000000000000000000000000000000000000..df4154522861ac99ff6dd8d6c3775659197c15ce --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_7.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_7" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: States that the arbitrator was entitled to select whatever penalty he considered most appropriate without deference to MPD’s penalty selection" +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_8.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_8.toml new file mode 100644 index 0000000000000000000000000000000000000000..34d83579de168137d4bfd1b5cf31321b88c26639 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_8.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_8" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: Mentions authority absent from the uploaded materials in support of the burden allocation." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_9.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_9.toml new file mode 100644 index 0000000000000000000000000000000000000000..1f431cd88b35b157c294c0b2fce38dbca403af2a --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/raw_correctness/criterion_9.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_9" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that the Award’s citation to Douglas v. Veterans Administration, 5 M.S.P.R. 280, 306 (1981) does not correspond to any page of the uploaded Douglas opinion." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/test.sh b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..66a509a7bcdbe412851f3a012a5ba7b16cf0925b --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/tests/test.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +set -euo pipefail + +mkdir -p /logs/artifacts /logs/verifier/raw + +python3 - <<'PYEOF' +import json +import shutil +from pathlib import Path + + +def has_text(path: Path) -> bool: + return path.exists() and path.is_file() and bool(path.read_text(errors="replace").strip()) + + +def fallback_paths(answer_path: Path) -> list[Path]: + paths = [] + try: + relative = answer_path.relative_to("/app") + paths.append(Path("/app/app") / relative) + except ValueError: + pass + return [path for path in paths if path != answer_path] + + +config = json.loads(Path("/tests/fixtures/config.json").read_text()) +answer_path = Path(config["answer_path"]) +artifact_answer = Path("/logs/artifacts/answer.md") +artifact_answer.parent.mkdir(parents=True, exist_ok=True) +if has_text(answer_path): + shutil.copyfile(answer_path, artifact_answer) +else: + for candidate in fallback_paths(answer_path): + if has_text(candidate): + shutil.copyfile(candidate, artifact_answer) + break + else: + artifact_answer.write_text("") + +# Harbor collects /logs/artifacts when the agent step ends, which is before this +# script runs, so the copy above never reaches the uploaded artifacts. /logs/verifier +# is uploaded after the verifier phase, so persist the graded answer there too. +verifier_answer = Path("/logs/verifier/answer.md") +verifier_answer.parent.mkdir(parents=True, exist_ok=True) +shutil.copyfile(artifact_answer, verifier_answer) +PYEOF + +uv run --no-project --with 'harbor-rewardkit[all]==0.2.0' python /tests/m1_rewardkit_accounting.py /tests/raw_correctness \ + --workspace /app \ + --output /logs/verifier/raw/reward.json \ + --max-concurrent-llm "${MAX_CONCURRENT_LLM:-4}" \ + --max-concurrent-agent "${M1_MAX_CONCURRENT_AGENT:-1}" + +python /tests/normalize_reward.py \ + --raw-details /logs/verifier/raw/reward-details.json \ + --rubric /tests/fixtures/rubric.json \ + --reward-out /logs/verifier/reward.json \ + --details-out /logs/verifier/reward-details.json diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/workdir/attachments/dcmr_title6b_1606.pdf b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/workdir/attachments/dcmr_title6b_1606.pdf new file mode 100644 index 0000000000000000000000000000000000000000..728cbb9d3b319467880364bcf3a2215ebf62bb55 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/workdir/attachments/dcmr_title6b_1606.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ac3c2652e42ed1bd0dc74bc470cd66ae2a6c44a2c1f43e19a64c7dc92645a308 +size 3428457 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/workdir/attachments/douglas_v_veterans_admin.pdf b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/workdir/attachments/douglas_v_veterans_admin.pdf new file mode 100644 index 0000000000000000000000000000000000000000..49d4955c38b09b67ead8381ab666fb335ef3b730 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-2/workdir/attachments/douglas_v_veterans_admin.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7d6fb6107594d500a4b9a4feacc876c65c66372f05c32b9425d092104ffbadb8 +size 822272 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/instruction.md b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..472a7fcbf973987d2ce3a5d8d0775a345c38b4ea --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/instruction.md @@ -0,0 +1,67 @@ +# Viability of a DCCA Challenge — Statutory Exceptions + +Domain: Litigation + +Matter: MPD v. PERB + +You are a senior legal analyst operating autonomously. You are completing a multi-step legal reasoning task. Follow the role, factual record, instructions, and deliverable requirements provided in the Task and each Assignment. + +Each Assignment may require a different legal deliverable. Follow the requirements specific to that Assignment. + +## Word limits for court briefs + +- A brief in support of or in response to a motion may not exceed **8,750 words**. +- A reply brief may not exceed **3,500 words**. +- For a motion for reconsideration, a brief in support of or in response to the motion may not exceed **3,500 words**, and a reply brief may not exceed **1,750 words**. +- If an Assignment specifies a stricter word limit, follow the stricter limit. + +These word limits do not apply to legal memoranda or other non-court-filing deliverables unless the Assignment expressly provides otherwise. + +Complete the task end-to-end without asking for confirmation, permission, or clarification. + +Use the uploaded matter documents in `/app/attachments/` as your primary case file. You also have internet access via OpenCode's `websearch` tool; use it to research any statutes, regulations, cases, administrative guidance, or secondary authorities that are not supplied as attachments. Cite any authority you rely on in the format requested by the prompt. + +For document inspection: +- PDF: `pdftotext /app/attachments/.pdf -` +- DOCX: `pandoc /app/attachments/.docx -t markdown` +- XLSX/CSV: use Python with `openpyxl` or `pandas` +- If extraction is unreliable, inspect the raw file with Python libraries or convert/render the relevant pages. + +Write the final complete legal deliverable for this assignment to `/app/response3.md`. The verifier reads only that file. + +This is a follow-on assignment. The documents from the previous assignment(s) remain available in `/app/attachments/`, and your prior deliverable `/app/response2.md` is also on disk. Build on that analysis as the prompt directs. + +## Attachments + +- `/app/attachments/paperworkers_v_misco.pdf` +- `/app/attachments/wr_grace_v_rubber_workers.pdf` +- `/app/attachments/dc_code_1-605.02.pdf` +- `/app/attachments/fop_doc_labor_comm_v_perb_2009.pdf` +- `/app/attachments/perb_decision_braddock.pdf` + + +## Prompt + +Our firm represents MPD in connection with an arbitration award that reduced Officer Colin Braddock’s termination for excessive force to a 45-day suspension based solely on the arbitrator’s findings regarding Douglas factors six and twelve. PERB affirmed the award in all respects. MPD has been largely unsuccessful in past attempts to persuade the DCCA to set aside PERB decisions affirming arbitration awards, and it is uncertain whether a petition for review is viable here. MPD is extremely dissatisfied with the arbitrator’s handling of Douglas, and it separately believes that being forced to reinstate an officer who shot an unarmed, non-threatening man contravenes a dominant public policy. + +Treat the following as true for all purposes in this matter, whether or not separately memorialized in the record: (a) reasonable minds can disagree as to how comparable the four comparator cases are to Braddock’s case; (b) at no point before the arbitration hearing did Braddock or his union allege that MPD treated similarly situated employees differently; and (c) Braddock knew that MPD intended to rely on the four comparator cases before MPD found him guilty of the excessive force charge. +The following documents have been uploaded for this Step: + +D.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117 (May 22, 2024) (final_notice_adverse_action_braddock.pdf) +In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf) +Memorandum from Yolanda Britt, Director, Disciplinary Review Division, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Sandra M. Delgado, Assistant Chief, Professional Development Bureau, re: Comparator Discipline Cases, Adverse Action Case No. IS-23-002841 (Braddock) (Apr. 11, 2024) (comparator_discipline_cases.pdf) +Douglas v. Veterans Administration, 5 M.S.P.R. 280 (1981) (douglas_v_veterans_admin.pdf) +D.C. Mun. Regs. tit. 6-B, § 1606 (2017) (dcmr_title6b_1606.pdf) +Opinion No. 1904, PERB Case No. 25-A-09 (D.C. Pub. Emp. Rels. Bd. Nov. 6, 2025) (perb_decision_braddock.pdf) +D.C. Code § 1-605.02 (2016) (dc_code_1-605.02.pdf) +W.R. Grace & Co. v. Local Union 759, 461 U.S. 757 (1983) (wr_grace_v_rubber_workers.pdf) +United Paperworkers Int’l Union v. Misco, Inc., 484 U.S. 29 (1987) (paperworkers_v_misco.pdf) +Fraternal Ord. of Police/Dep’t of Corr. Lab. Comm. v. D.C. Pub. Emp. Rels. Bd., 973 A.2d 174 (D.C. 2009) (fop_doc_labor_comm_v_perb_2009.pdf) + +The documents listed above constitute the complete and exclusive universe of materials for this Step. Limit your review to the attached documents. Do not rely on, reference, or infer any legal authority, factual information, or data beyond what is contained in these uploaded files. If a document is not uploaded, it does not exist for purposes of this analysis. All citations must reference the document by its exact name as listed above, followed by the page and paragraph number. Do not cite external websites, databases, or any source outside the uploaded materials. + +Complete the following: + +1. Set out MPD’s strongest arguments that the Award is contrary to law under D.C. Code § 1-605.02(6) (2016). Anchor each argument in specific findings of the Award and the PERB Decision, with page and paragraph citations, and state the standard the DCCA applies when reviewing a PERB decision affirming an arbitration award as reflected in the uploaded opinions. + +2. Set out MPD’s strongest arguments that the Award is on its face contrary to public policy under D.C. Code § 1-605.02(6) (2016). State the test for the public policy exception as articulated in the uploaded opinions, identify the specific documented public policy MPD should invoke and the uploaded source that documents it, and apply the test to the Award. Identify the single weakest point in each of the two arguments and explain why it is the weakest. diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/solution/solve.sh b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7710414a6da6d0ad740717c8c85a9af850d5da33 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/solution/solve.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# No oracle solution ships with LegalReasonBench. The verifier grades the +# agent's own legal deliverable for this assignment against the rubric. +echo "no oracle solution" diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/fixtures/config.json b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/fixtures/config.json new file mode 100644 index 0000000000000000000000000000000000000000..8f38c3c3fd4ddda0d7c33d3b7461f3b7318e4a63 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/fixtures/config.json @@ -0,0 +1,260 @@ +{ + "task_id": "lrb-dcca-challenge-police-discipline", + "title": "Viability of a DCCA Challenge", + "domain": "Litigation", + "matter": "MPD v. PERB", + "judge": { + "max_concurrent_llm": 12, + "mode": "panel", + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ], + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + "step_index": 3, + "step_name": "assignment-3", + "step_title": "Statutory Exceptions", + "prompt": "Our firm represents MPD in connection with an arbitration award that reduced Officer Colin Braddock\u2019s termination for excessive force to a 45-day suspension based solely on the arbitrator\u2019s findings regarding Douglas factors six and twelve. PERB affirmed the award in all respects. MPD has been largely unsuccessful in past attempts to persuade the DCCA to set aside PERB decisions affirming arbitration awards, and it is uncertain whether a petition for review is viable here. MPD is extremely dissatisfied with the arbitrator\u2019s handling of Douglas, and it separately believes that being forced to reinstate an officer who shot an unarmed, non-threatening man contravenes a dominant public policy.\n\nTreat the following as true for all purposes in this matter, whether or not separately memorialized in the record: (a) reasonable minds can disagree as to how comparable the four comparator cases are to Braddock\u2019s case; (b) at no point before the arbitration hearing did Braddock or his union allege that MPD treated similarly situated employees differently; and (c) Braddock knew that MPD intended to rely on the four comparator cases before MPD found him guilty of the excessive force charge.\nThe following documents have been uploaded for this Step:\n\nD.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117 (May 22, 2024) (final_notice_adverse_action_braddock.pdf)\nIn re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)\nMemorandum from Yolanda Britt, Director, Disciplinary Review Division, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Sandra M. Delgado, Assistant Chief, Professional Development Bureau, re: Comparator Discipline Cases, Adverse Action Case No. IS-23-002841 (Braddock) (Apr. 11, 2024) (comparator_discipline_cases.pdf)\nDouglas v. Veterans Administration, 5 M.S.P.R. 280 (1981) (douglas_v_veterans_admin.pdf)\nD.C. Mun. Regs. tit. 6-B, \u00a7 1606 (2017) (dcmr_title6b_1606.pdf)\nOpinion No. 1904, PERB Case No. 25-A-09 (D.C. Pub. Emp. Rels. Bd. Nov. 6, 2025) (perb_decision_braddock.pdf)\nD.C. Code \u00a7 1-605.02 (2016) (dc_code_1-605.02.pdf)\nW.R. Grace & Co. v. Local Union 759, 461 U.S. 757 (1983) (wr_grace_v_rubber_workers.pdf)\nUnited Paperworkers Int\u2019l Union v. Misco, Inc., 484 U.S. 29 (1987) (paperworkers_v_misco.pdf)\nFraternal Ord. of Police/Dep\u2019t of Corr. Lab. Comm. v. D.C. Pub. Emp. Rels. Bd., 973 A.2d 174 (D.C. 2009) (fop_doc_labor_comm_v_perb_2009.pdf)\n\nThe documents listed above constitute the complete and exclusive universe of materials for this Step. Limit your review to the attached documents. Do not rely on, reference, or infer any legal authority, factual information, or data beyond what is contained in these uploaded files. If a document is not uploaded, it does not exist for purposes of this analysis. All citations must reference the document by its exact name as listed above, followed by the page and paragraph number. Do not cite external websites, databases, or any source outside the uploaded materials.\n\nComplete the following:\n\n1. Set out MPD\u2019s strongest arguments that the Award is contrary to law under D.C. Code \u00a7 1-605.02(6) (2016). Anchor each argument in specific findings of the Award and the PERB Decision, with page and paragraph citations, and state the standard the DCCA applies when reviewing a PERB decision affirming an arbitration award as reflected in the uploaded opinions.\n\n2. Set out MPD\u2019s strongest arguments that the Award is on its face contrary to public policy under D.C. Code \u00a7 1-605.02(6) (2016). State the test for the public policy exception as articulated in the uploaded opinions, identify the specific documented public policy MPD should invoke and the uploaded source that documents it, and apply the test to the Award. Identify the single weakest point in each of the two arguments and explain why it is the weakest.", + "attachments": [ + { + "filename": "paperworkers_v_misco.pdf", + "description": "", + "metadata": {}, + "path": "/app/attachments/paperworkers_v_misco.pdf" + }, + { + "filename": "wr_grace_v_rubber_workers.pdf", + "description": "", + "metadata": {}, + "path": "/app/attachments/wr_grace_v_rubber_workers.pdf" + }, + { + "filename": "dc_code_1-605.02.pdf", + "description": "", + "metadata": {}, + "path": "/app/attachments/dc_code_1-605.02.pdf" + }, + { + "filename": "fop_doc_labor_comm_v_perb_2009.pdf", + "description": "", + "metadata": {}, + "path": "/app/attachments/fop_doc_labor_comm_v_perb_2009.pdf" + }, + { + "filename": "perb_decision_braddock.pdf", + "description": "", + "metadata": {}, + "path": "/app/attachments/perb_decision_braddock.pdf" + } + ], + "rubric": [ + { + "name": "criterion_1", + "description": "States that under D.C. Code \u00a7 1-605.02(6) (2016) an arbitration award may be set aside where the award on its face is contrary to law.", + "source": "D.C. Code \u00a7 1-605.02 (2016) (dc_code_1-605.02.pdf), \u00a7 1-605.02(6)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"1. Set out MPD's strongest arguments that the Award is contrary to law under D.C. Code \u00a7 1-605.02(6) (2016). Anchor each argument in specific findings of the Award and the PERB Decision, with page and paragraph citations, and state the standard the DCCA applies when reviewing a PERB decision affirming an arbitration award as reflected in the uploaded opinions.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_2", + "description": "States that a decision of PERB must stand unless it is rationally indefensible", + "source": "Fraternal Ord. of Police/Dep't of Corr. Lab. Comm. v. D.C. Pub. Emp. Rels. Bd., 973 A.2d 174 (D.C. 2009) (fop_doc_labor_comm_v_perb_2009.pdf) at 3", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"1. Set out MPD's strongest arguments that the Award is contrary to law under D.C. Code \u00a7 1-605.02(6) (2016). Anchor each argument in specific findings of the Award and the PERB Decision, with page and paragraph citations, and state the standard the DCCA applies when reviewing a PERB decision affirming an arbitration award as reflected in the uploaded opinions.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_3", + "description": "Mentions that MPD\u2019s contrary-to-law argument can be framed as the arbitrator purporting to apply Douglas while overlooking its limits on penalty review.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 5 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf); Douglas v. Veterans Administration, 5 M.S.P.R. 280, 305-06 (1981) (douglas_v_veterans_admin.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"1. Set out MPD's strongest arguments that the Award is contrary to law under D.C. Code \u00a7 1-605.02(6) (2016). Anchor each argument in specific findings of the Award and the PERB Decision, with page and paragraph citations, and state the standard the DCCA applies when reviewing a PERB decision affirming an arbitration award as reflected in the uploaded opinions.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_4", + "description": "States that the invoked policy against the unjustified use of deadly force by police officers must be well defined and dominant.", + "source": "W.R. Grace & Co. v. Local Union 759, 461 U.S. 757, 766 (1983) (wr_grace_v_rubber_workers.pdf); D.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117, \u00b6 12 (May 22, 2024) (final_notice_adverse_action_braddock.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"2. Set out MPD's strongest arguments that the Award is on its face contrary to public policy under D.C. Code \u00a7 1-605.02(6) (2016). State the test for the public policy exception as articulated in the uploaded opinions, identify the specific documented public policy MPD should invoke and the uploaded source that documents it, and apply the test to the Award. Identify the single weakest point in each of the two arguments and explain why it is the weakest.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_5", + "description": "Mentions that the public policy question is whether enforcing the award would violate public policy rather than whether the misconduct did.", + "source": "W.R. Grace & Co. v. Local Union 759, 461 U.S. 757, 766 (1983) (wr_grace_v_rubber_workers.pdf); United Paperworkers Int'l Union v. Misco, Inc., 484 U.S. 29, 43 (1987) (paperworkers_v_misco.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"2. Set out MPD's strongest arguments that the Award is on its face contrary to public policy under D.C. Code \u00a7 1-605.02(6) (2016). State the test for the public policy exception as articulated in the uploaded opinions, identify the specific documented public policy MPD should invoke and the uploaded source that documents it, and apply the test to the Award. Identify the single weakest point in each of the two arguments and explain why it is the weakest.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_6", + "description": "Mentions that a violation of the properly framed public policy must be clearly shown before an award may be refused enforcement.", + "source": "United Paperworkers Int'l Union v. Misco, Inc., 484 U.S. 29, 43 (1987) (paperworkers_v_misco.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"2. Set out MPD's strongest arguments that the Award is on its face contrary to public policy under D.C. Code \u00a7 1-605.02(6) (2016). State the test for the public policy exception as articulated in the uploaded opinions, identify the specific documented public policy MPD should invoke and the uploaded source that documents it, and apply the test to the Award. Identify the single weakest point in each of the two arguments and explain why it is the weakest.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_7", + "description": "Identifies that the PERB Decision affirmed the Award without addressing MPD's specific contrary-to-law arguments", + "source": "Opinion No. 1904, PERB Case No. 25-A-09, \u00b6\u00b6 2, 4-5 (D.C. Pub. Emp. Rels. Bd. Nov. 6, 2025) (perb_decision_braddock.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"1. Set out MPD's strongest arguments that the Award is contrary to law under D.C. Code \u00a7 1-605.02(6) (2016). Anchor each argument in specific findings of the Award and the PERB Decision, with page and paragraph citations, and state the standard the DCCA applies when reviewing a PERB decision affirming an arbitration award as reflected in the uploaded opinions.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_8", + "description": "States that the DCCA applies PERB decisions under the ordinary deference owed to expert agencies rather than an unusually deferential standard in its reviews.", + "source": "Fraternal Ord. of Police/Dep't of Corr. Lab. Comm. v. D.C. Pub. Emp. Rels. Bd., 973 A.2d 174 (D.C. 2009) (fop_doc_labor_comm_v_perb_2009.pdf) at 3", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"1. Set out MPD's strongest arguments that the Award is contrary to law under D.C. Code \u00a7 1-605.02(6) (2016). Anchor each argument in specific findings of the Award and the PERB Decision, with page and paragraph citations, and state the standard the DCCA applies when reviewing a PERB decision affirming an arbitration award as reflected in the uploaded opinions.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": -20.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_9", + "description": "States that the wrongfulness of Braddock\u2019s misconduct itself establishes that the Award violates public policy.", + "source": "W.R. Grace & Co. v. Local Union 759, 461 U.S. 757, 766 (1983) (wr_grace_v_rubber_workers.pdf); United Paperworkers Int'l Union v. Misco, Inc., 484 U.S. 29, 43 (1987) (paperworkers_v_misco.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"2. Set out MPD's strongest arguments that the Award is on its face contrary to public policy under D.C. Code \u00a7 1-605.02(6) (2016). State the test for the public policy exception as articulated in the uploaded opinions, identify the specific documented public policy MPD should invoke and the uploaded source that documents it, and apply the test to the Award. Identify the single weakest point in each of the two arguments and explain why it is the weakest.\" Treating the misconduct's wrongfulness as the violation inverts the enforcement-focused test.", + "metadata": { + "irac_section": "Application" + }, + "score": -26.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_10", + "description": "States that disagreement with the arbitrator\u2019s weighing of the Douglas factors is itself sufficient to render the Award contrary to law.", + "source": "Fraternal Ord. of Police/Dep't of Corr. Lab. Comm. v. D.C. Pub. Emp. Rels. Bd., 973 A.2d 174 (D.C. 2009) (fop_doc_labor_comm_v_perb_2009.pdf) at 3", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"1. Set out MPD's strongest arguments that the Award is contrary to law under D.C. Code \u00a7 1-605.02(6) (2016). Anchor each argument in specific findings of the Award and the PERB Decision, with page and paragraph citations, and state the standard the DCCA applies when reviewing a PERB decision affirming an arbitration award as reflected in the uploaded opinions.\"", + "metadata": { + "irac_section": "Conclusion" + }, + "score": -18.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_11", + "description": "Identifies that PERB's unexplained rejection of MPD's arguments undermines the deference its interpretation would otherwise receive.", + "source": "Opinion No. 1904, PERB Case No. 25-A-09, \u00b6\u00b6 4-5 (D.C. Pub. Emp. Rels. Bd. Nov. 6, 2025) (perb_decision_braddock.pdf); Fraternal Ord. of Police/Dep't of Corr. Lab. Comm. v. D.C. Pub. Emp. Rels. Bd., 973 A.2d 174 (D.C. 2009) (fop_doc_labor_comm_v_perb_2009.pdf) at 3", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"1. Set out MPD's strongest arguments that the Award is contrary to law under D.C. Code \u00a7 1-605.02(6) (2016). Anchor each argument in specific findings of the Award and the PERB Decision, with page and paragraph citations, and state the standard the DCCA applies when reviewing a PERB decision affirming an arbitration award as reflected in the uploaded opinions.\" Deference presupposes a reasoned decision to defer to.", + "metadata": { + "irac_section": "Application" + }, + "score": 6.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_12", + "description": "Identifies that no uploaded opinion decides whether an arbitrator's penalty determination can be on its face contrary to law.", + "source": "Douglas v. Veterans Administration, 5 M.S.P.R. 280 (1981) (douglas_v_veterans_admin.pdf); W.R. Grace & Co. v. Local Union 759, 461 U.S. 757 (1983) (wr_grace_v_rubber_workers.pdf); United Paperworkers Int'l Union v. Misco, Inc., 484 U.S. 29 (1987) (paperworkers_v_misco.pdf); Fraternal Ord. of Police/Dep't of Corr. Lab. Comm. v. D.C. Pub. Emp. Rels. Bd., 973 A.2d 174 (D.C. 2009) (fop_doc_labor_comm_v_perb_2009.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"1. Set out MPD's strongest arguments that the Award is contrary to law under D.C. Code \u00a7 1-605.02(6) (2016). Anchor each argument in specific findings of the Award and the PERB Decision, with page and paragraph citations, and state the standard the DCCA applies when reviewing a PERB decision affirming an arbitration award as reflected in the uploaded opinions.\" The strongest honest framing acknowledges the open question.", + "metadata": { + "irac_section": "Conclusion" + }, + "score": 28.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_13", + "description": "Identifies that MPD's public policy argument must target enforcement of the reinstatement remedy rather than the shooting itself.", + "source": "United Paperworkers Int'l Union v. Misco, Inc., 484 U.S. 29, 42 to 45 (1987) (paperworkers_v_misco.pdf); W.R. Grace & Co. v. Local Union 759, 461 U.S. 757, 766 (1983) (wr_grace_v_rubber_workers.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"2. Set out MPD's strongest arguments that the Award is on its face contrary to public policy under D.C. Code \u00a7 1-605.02(6) (2016). State the test for the public policy exception as articulated in the uploaded opinions, identify the specific documented public policy MPD should invoke and the uploaded source that documents it, and apply the test to the Award. Identify the single weakest point in each of the two arguments and explain why it is the weakest.\"", + "metadata": {}, + "score": 4.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_14", + "description": "Identifies that the public policy MPD should invoke is a policy against the unjustified use of deadly force by police officers", + "source": "D.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117, \u00b6 12 (May 22, 2024) (final_notice_adverse_action_braddock.pdf); W.R. Grace & Co. v. Local Union 759, 461 U.S. 757, 766 (1983) (wr_grace_v_rubber_workers.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"2. Set out MPD's strongest arguments that the Award is on its face contrary to public policy under D.C. Code \u00a7 1-605.02(6) (2016). State the test for the public policy exception as articulated in the uploaded opinions, identify the specific documented public policy MPD should invoke and the uploaded source that documents it, and apply the test to the Award. Identify the single weakest point in each of the two arguments and explain why it is the weakest.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_15", + "description": "Mentions Eastern Associated Coal Corp. v. United Mine Workers as authority for the public policy analysis.", + "source": "Douglas v. Veterans Administration, 5 M.S.P.R. 280 (1981) (douglas_v_veterans_admin.pdf); W.R. Grace & Co. v. Local Union 759, 461 U.S. 757 (1983) (wr_grace_v_rubber_workers.pdf); United Paperworkers Int'l Union v. Misco, Inc., 484 U.S. 29 (1987) (paperworkers_v_misco.pdf); Fraternal Ord. of Police/Dep't of Corr. Lab. Comm. v. D.C. Pub. Emp. Rels. Bd., 973 A.2d 174 (D.C. 2009) (fop_doc_labor_comm_v_perb_2009.pdf); D.C. Code \u00a7 1-605.02(6) (2016) (dc_code_1-605.02.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cDo not rely on, reference, or infer any legal authority, factual information, or data beyond what is contained in these uploaded files.\u201d", + "metadata": {}, + "score": -26.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_16", + "description": "Identifies that the PERB Decision misstates the length of the suspension imposed by the Award.", + "source": "Opinion No. 1904, PERB Case No. 25-A-09, \u00b6 1 (D.C. Pub. Emp. Rels. Bd. Nov. 6, 2025) (perb_decision_braddock.pdf); In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 10 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"1. Set out MPD's strongest arguments that the Award is contrary to law under D.C. Code \u00a7 1-605.02(6) (2016). Anchor each argument in specific findings of the Award and the PERB Decision, with page and paragraph citations, and state the standard the DCCA applies when reviewing a PERB decision affirming an arbitration award as reflected in the uploaded opinions.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 6.0, + "polarity": "positive", + "raw_weight": 1.0 + } + ], + "answer_path": "/app/response3.md", + "answer_relative_path": "response3.md", + "is_followon": true, + "prev_answer_path": "/app/response2.md" +} diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/fixtures/rubric.json b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/fixtures/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..fa8ccd2924811cb028b699b748976adcbe13cef0 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/fixtures/rubric.json @@ -0,0 +1,192 @@ +{ + "criteria": [ + { + "name": "criterion_1", + "description": "States that under D.C. Code \u00a7 1-605.02(6) (2016) an arbitration award may be set aside where the award on its face is contrary to law.", + "source": "D.C. Code \u00a7 1-605.02 (2016) (dc_code_1-605.02.pdf), \u00a7 1-605.02(6)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"1. Set out MPD's strongest arguments that the Award is contrary to law under D.C. Code \u00a7 1-605.02(6) (2016). Anchor each argument in specific findings of the Award and the PERB Decision, with page and paragraph citations, and state the standard the DCCA applies when reviewing a PERB decision affirming an arbitration award as reflected in the uploaded opinions.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_2", + "description": "States that a decision of PERB must stand unless it is rationally indefensible", + "source": "Fraternal Ord. of Police/Dep't of Corr. Lab. Comm. v. D.C. Pub. Emp. Rels. Bd., 973 A.2d 174 (D.C. 2009) (fop_doc_labor_comm_v_perb_2009.pdf) at 3", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"1. Set out MPD's strongest arguments that the Award is contrary to law under D.C. Code \u00a7 1-605.02(6) (2016). Anchor each argument in specific findings of the Award and the PERB Decision, with page and paragraph citations, and state the standard the DCCA applies when reviewing a PERB decision affirming an arbitration award as reflected in the uploaded opinions.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_3", + "description": "Mentions that MPD\u2019s contrary-to-law argument can be framed as the arbitrator purporting to apply Douglas while overlooking its limits on penalty review.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 5 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf); Douglas v. Veterans Administration, 5 M.S.P.R. 280, 305-06 (1981) (douglas_v_veterans_admin.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"1. Set out MPD's strongest arguments that the Award is contrary to law under D.C. Code \u00a7 1-605.02(6) (2016). Anchor each argument in specific findings of the Award and the PERB Decision, with page and paragraph citations, and state the standard the DCCA applies when reviewing a PERB decision affirming an arbitration award as reflected in the uploaded opinions.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_4", + "description": "States that the invoked policy against the unjustified use of deadly force by police officers must be well defined and dominant.", + "source": "W.R. Grace & Co. v. Local Union 759, 461 U.S. 757, 766 (1983) (wr_grace_v_rubber_workers.pdf); D.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117, \u00b6 12 (May 22, 2024) (final_notice_adverse_action_braddock.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"2. Set out MPD's strongest arguments that the Award is on its face contrary to public policy under D.C. Code \u00a7 1-605.02(6) (2016). State the test for the public policy exception as articulated in the uploaded opinions, identify the specific documented public policy MPD should invoke and the uploaded source that documents it, and apply the test to the Award. Identify the single weakest point in each of the two arguments and explain why it is the weakest.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_5", + "description": "Mentions that the public policy question is whether enforcing the award would violate public policy rather than whether the misconduct did.", + "source": "W.R. Grace & Co. v. Local Union 759, 461 U.S. 757, 766 (1983) (wr_grace_v_rubber_workers.pdf); United Paperworkers Int'l Union v. Misco, Inc., 484 U.S. 29, 43 (1987) (paperworkers_v_misco.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"2. Set out MPD's strongest arguments that the Award is on its face contrary to public policy under D.C. Code \u00a7 1-605.02(6) (2016). State the test for the public policy exception as articulated in the uploaded opinions, identify the specific documented public policy MPD should invoke and the uploaded source that documents it, and apply the test to the Award. Identify the single weakest point in each of the two arguments and explain why it is the weakest.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_6", + "description": "Mentions that a violation of the properly framed public policy must be clearly shown before an award may be refused enforcement.", + "source": "United Paperworkers Int'l Union v. Misco, Inc., 484 U.S. 29, 43 (1987) (paperworkers_v_misco.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"2. Set out MPD's strongest arguments that the Award is on its face contrary to public policy under D.C. Code \u00a7 1-605.02(6) (2016). State the test for the public policy exception as articulated in the uploaded opinions, identify the specific documented public policy MPD should invoke and the uploaded source that documents it, and apply the test to the Award. Identify the single weakest point in each of the two arguments and explain why it is the weakest.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_7", + "description": "Identifies that the PERB Decision affirmed the Award without addressing MPD's specific contrary-to-law arguments", + "source": "Opinion No. 1904, PERB Case No. 25-A-09, \u00b6\u00b6 2, 4-5 (D.C. Pub. Emp. Rels. Bd. Nov. 6, 2025) (perb_decision_braddock.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"1. Set out MPD's strongest arguments that the Award is contrary to law under D.C. Code \u00a7 1-605.02(6) (2016). Anchor each argument in specific findings of the Award and the PERB Decision, with page and paragraph citations, and state the standard the DCCA applies when reviewing a PERB decision affirming an arbitration award as reflected in the uploaded opinions.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_8", + "description": "States that the DCCA applies PERB decisions under the ordinary deference owed to expert agencies rather than an unusually deferential standard in its reviews.", + "source": "Fraternal Ord. of Police/Dep't of Corr. Lab. Comm. v. D.C. Pub. Emp. Rels. Bd., 973 A.2d 174 (D.C. 2009) (fop_doc_labor_comm_v_perb_2009.pdf) at 3", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"1. Set out MPD's strongest arguments that the Award is contrary to law under D.C. Code \u00a7 1-605.02(6) (2016). Anchor each argument in specific findings of the Award and the PERB Decision, with page and paragraph citations, and state the standard the DCCA applies when reviewing a PERB decision affirming an arbitration award as reflected in the uploaded opinions.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": -20.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_9", + "description": "States that the wrongfulness of Braddock\u2019s misconduct itself establishes that the Award violates public policy.", + "source": "W.R. Grace & Co. v. Local Union 759, 461 U.S. 757, 766 (1983) (wr_grace_v_rubber_workers.pdf); United Paperworkers Int'l Union v. Misco, Inc., 484 U.S. 29, 43 (1987) (paperworkers_v_misco.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"2. Set out MPD's strongest arguments that the Award is on its face contrary to public policy under D.C. Code \u00a7 1-605.02(6) (2016). State the test for the public policy exception as articulated in the uploaded opinions, identify the specific documented public policy MPD should invoke and the uploaded source that documents it, and apply the test to the Award. Identify the single weakest point in each of the two arguments and explain why it is the weakest.\" Treating the misconduct's wrongfulness as the violation inverts the enforcement-focused test.", + "metadata": { + "irac_section": "Application" + }, + "score": -26.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_10", + "description": "States that disagreement with the arbitrator\u2019s weighing of the Douglas factors is itself sufficient to render the Award contrary to law.", + "source": "Fraternal Ord. of Police/Dep't of Corr. Lab. Comm. v. D.C. Pub. Emp. Rels. Bd., 973 A.2d 174 (D.C. 2009) (fop_doc_labor_comm_v_perb_2009.pdf) at 3", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"1. Set out MPD's strongest arguments that the Award is contrary to law under D.C. Code \u00a7 1-605.02(6) (2016). Anchor each argument in specific findings of the Award and the PERB Decision, with page and paragraph citations, and state the standard the DCCA applies when reviewing a PERB decision affirming an arbitration award as reflected in the uploaded opinions.\"", + "metadata": { + "irac_section": "Conclusion" + }, + "score": -18.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_11", + "description": "Identifies that PERB's unexplained rejection of MPD's arguments undermines the deference its interpretation would otherwise receive.", + "source": "Opinion No. 1904, PERB Case No. 25-A-09, \u00b6\u00b6 4-5 (D.C. Pub. Emp. Rels. Bd. Nov. 6, 2025) (perb_decision_braddock.pdf); Fraternal Ord. of Police/Dep't of Corr. Lab. Comm. v. D.C. Pub. Emp. Rels. Bd., 973 A.2d 174 (D.C. 2009) (fop_doc_labor_comm_v_perb_2009.pdf) at 3", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"1. Set out MPD's strongest arguments that the Award is contrary to law under D.C. Code \u00a7 1-605.02(6) (2016). Anchor each argument in specific findings of the Award and the PERB Decision, with page and paragraph citations, and state the standard the DCCA applies when reviewing a PERB decision affirming an arbitration award as reflected in the uploaded opinions.\" Deference presupposes a reasoned decision to defer to.", + "metadata": { + "irac_section": "Application" + }, + "score": 6.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_12", + "description": "Identifies that no uploaded opinion decides whether an arbitrator's penalty determination can be on its face contrary to law.", + "source": "Douglas v. Veterans Administration, 5 M.S.P.R. 280 (1981) (douglas_v_veterans_admin.pdf); W.R. Grace & Co. v. Local Union 759, 461 U.S. 757 (1983) (wr_grace_v_rubber_workers.pdf); United Paperworkers Int'l Union v. Misco, Inc., 484 U.S. 29 (1987) (paperworkers_v_misco.pdf); Fraternal Ord. of Police/Dep't of Corr. Lab. Comm. v. D.C. Pub. Emp. Rels. Bd., 973 A.2d 174 (D.C. 2009) (fop_doc_labor_comm_v_perb_2009.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"1. Set out MPD's strongest arguments that the Award is contrary to law under D.C. Code \u00a7 1-605.02(6) (2016). Anchor each argument in specific findings of the Award and the PERB Decision, with page and paragraph citations, and state the standard the DCCA applies when reviewing a PERB decision affirming an arbitration award as reflected in the uploaded opinions.\" The strongest honest framing acknowledges the open question.", + "metadata": { + "irac_section": "Conclusion" + }, + "score": 28.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_13", + "description": "Identifies that MPD's public policy argument must target enforcement of the reinstatement remedy rather than the shooting itself.", + "source": "United Paperworkers Int'l Union v. Misco, Inc., 484 U.S. 29, 42 to 45 (1987) (paperworkers_v_misco.pdf); W.R. Grace & Co. v. Local Union 759, 461 U.S. 757, 766 (1983) (wr_grace_v_rubber_workers.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"2. Set out MPD's strongest arguments that the Award is on its face contrary to public policy under D.C. Code \u00a7 1-605.02(6) (2016). State the test for the public policy exception as articulated in the uploaded opinions, identify the specific documented public policy MPD should invoke and the uploaded source that documents it, and apply the test to the Award. Identify the single weakest point in each of the two arguments and explain why it is the weakest.\"", + "metadata": {}, + "score": 4.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_14", + "description": "Identifies that the public policy MPD should invoke is a policy against the unjustified use of deadly force by police officers", + "source": "D.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117, \u00b6 12 (May 22, 2024) (final_notice_adverse_action_braddock.pdf); W.R. Grace & Co. v. Local Union 759, 461 U.S. 757, 766 (1983) (wr_grace_v_rubber_workers.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"2. Set out MPD's strongest arguments that the Award is on its face contrary to public policy under D.C. Code \u00a7 1-605.02(6) (2016). State the test for the public policy exception as articulated in the uploaded opinions, identify the specific documented public policy MPD should invoke and the uploaded source that documents it, and apply the test to the Award. Identify the single weakest point in each of the two arguments and explain why it is the weakest.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_15", + "description": "Mentions Eastern Associated Coal Corp. v. United Mine Workers as authority for the public policy analysis.", + "source": "Douglas v. Veterans Administration, 5 M.S.P.R. 280 (1981) (douglas_v_veterans_admin.pdf); W.R. Grace & Co. v. Local Union 759, 461 U.S. 757 (1983) (wr_grace_v_rubber_workers.pdf); United Paperworkers Int'l Union v. Misco, Inc., 484 U.S. 29 (1987) (paperworkers_v_misco.pdf); Fraternal Ord. of Police/Dep't of Corr. Lab. Comm. v. D.C. Pub. Emp. Rels. Bd., 973 A.2d 174 (D.C. 2009) (fop_doc_labor_comm_v_perb_2009.pdf); D.C. Code \u00a7 1-605.02(6) (2016) (dc_code_1-605.02.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cDo not rely on, reference, or infer any legal authority, factual information, or data beyond what is contained in these uploaded files.\u201d", + "metadata": {}, + "score": -26.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_16", + "description": "Identifies that the PERB Decision misstates the length of the suspension imposed by the Award.", + "source": "Opinion No. 1904, PERB Case No. 25-A-09, \u00b6 1 (D.C. Pub. Emp. Rels. Bd. Nov. 6, 2025) (perb_decision_braddock.pdf); In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 10 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"1. Set out MPD's strongest arguments that the Award is contrary to law under D.C. Code \u00a7 1-605.02(6) (2016). Anchor each argument in specific findings of the Award and the PERB Decision, with page and paragraph citations, and state the standard the DCCA applies when reviewing a PERB decision affirming an arbitration award as reflected in the uploaded opinions.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 6.0, + "polarity": "positive", + "raw_weight": 1.0 + } + ] +} diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/m1_judge_panel.json b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/m1_judge_panel.json new file mode 100644 index 0000000000000000000000000000000000000000..a8041f6781a899f9083fe4a1a95f51bc78d35601 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/m1_judge_panel.json @@ -0,0 +1,21 @@ +{ + "mode": "panel", + "max_concurrent_llm": 12, + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ] +} diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/m1_rewardkit_accounting.py b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/m1_rewardkit_accounting.py new file mode 100644 index 0000000000000000000000000000000000000000..406dc5e7c675b222d94514e71bf5fad6ae141d8f --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/m1_rewardkit_accounting.py @@ -0,0 +1,490 @@ +import asyncio +import json +import math +import os +from pathlib import Path +import random +import sys +import time + +class JudgeReceiptError(OSError): + pass +_LLM_ROUTES = frozenset({'vertex', 'anthropic fallback', 'aistudio', 'direct'}) +_LLM_ROUTE_HEADERS = ('x-m1-llm-route', 'llm_provider-x-m1-llm-route') + +def _canonical_llm_route(value): + return value if isinstance(value, str) and value in _LLM_ROUTES else None + +def _llm_route_from_headers(headers): + if not isinstance(headers, dict): + return None + folded = {str(key).lower(): value for key, value in headers.items()} + for name in _LLM_ROUTE_HEADERS: + route = _canonical_llm_route(folded.get(name)) + if route is not None: + return route + return None + +def _llm_route_from_response(response): + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + route = _llm_route_from_headers(headers) + if route is not None: + return route + return _llm_route_from_headers(getattr(response, 'headers', None)) + +def _token_field_status(values, key): + if not isinstance(values, dict) or key not in values: + return 'missing' + value = values[key] + if value is None: + return 'null' + return 'valid' if type(value) is int and value >= 0 else 'invalid' + +def _gemini_capture(kwargs, model): + if not model.startswith('gemini/') or kwargs.get('stream') or kwargs.get('tools') or kwargs.get('functions'): + return (kwargs, None) + from litellm.integrations.custom_logger import CustomLogger + from urllib.parse import urlsplit + + class Capture(CustomLogger): + evidence = None + prompt_status = 'not_observed' + llm_route = None + + def log_post_api_call(self, kwargs, response_obj, start_time, end_time): + self.evidence = None + self.prompt_status = 'not_observed' + try: + params = kwargs.get('litellm_params') or {} + route = urlsplit(params.get('api_base') or '') + bare = model.removeprefix('gemini/') + gemini = params.get('custom_llm_provider') == 'gemini' + ai_studio = gemini and route.hostname == 'generativelanguage.googleapis.com' and (route.path in {'/' + version + '/models/' + bare + ':generateContent' for version in ('v1alpha', 'v1beta')}) + broker = urlsplit(os.environ.get('GEMINI_API_BASE') or '') + brokered = gemini and bool(broker.netloc) and (route.netloc == broker.netloc) and (broker.path.rstrip('/').rsplit('/', 1)[-1] in ('v1alpha', 'v1beta')) and (route.path == broker.path.rstrip('/') + '/models/' + bare + ':generateContent') + vertex = params.get('custom_llm_provider') == 'vertex_ai' and route.hostname == 'aiplatform.googleapis.com' and route.path.startswith('/v1/projects/') and route.path.endswith('/locations/global/publishers/google/models/' + bare + ':generateContent') + if route.scheme != 'https' or not (ai_studio or brokered or vertex) or kwargs.get('stream'): + return + self.llm_route = 'vertex' if vertex else 'aistudio' if ai_studio else None + raw = kwargs.get('original_response') + raw = json.loads(raw) if isinstance(raw, str) else raw + if not isinstance(raw, dict): + return + candidates = raw.get('candidates') + if not isinstance(candidates, list) or not candidates or any((not isinstance(c, dict) or not c.get('finishReason') for c in candidates)) or (not isinstance(raw.get('modelVersion'), str)) or (not raw['modelVersion']): + return + usage = raw.get('usageMetadata') + self.prompt_status = _token_field_status(usage, 'promptTokenCount') + if not isinstance(usage, dict): + return + fields = ('promptTokenCount', 'candidatesTokenCount', 'thoughtsTokenCount', 'cachedContentTokenCount', 'totalTokenCount', 'toolUsePromptTokenCount') + counts = {key: usage.get(key, 0) for key in fields} + if not {'promptTokenCount', 'totalTokenCount'} <= usage.keys() or any((type(n) is not int or n < 0 for n in counts.values())) or counts['toolUsePromptTokenCount'] != 0 or (counts['cachedContentTokenCount'] > counts['promptTokenCount']) or (counts['totalTokenCount'] != counts['promptTokenCount'] + counts['candidatesTokenCount'] + counts['thoughtsTokenCount']): + return + self.evidence = {'protocol': 'gemini-generate-content-' + ('vertex-v1' if vertex else route.path.split('/')[-3]), 'model_version': raw['modelVersion'], 'usage_metadata': {key: usage[key] for key in fields if key in usage}, 'defaulted_fields': [key for key in fields if key not in usage]} + except (TypeError, ValueError, AttributeError): + return + capture = Capture() + return ({**kwargs, 'callbacks': [*(kwargs.get('callbacks') or []), capture]}, capture) + +def _record_judge_usage(response, model: str, *, target: Path | None=None, native_usage: dict | None=None, native_prompt_status: str | None=None, llm_route: str | None=None) -> None: + import fcntl + from datetime import datetime, timezone + data = response.model_dump() if hasattr(response, 'model_dump') else response + usage = data.get('usage') if isinstance(data, dict) else None + granularity = data.get('usage_granularity') if isinstance(data, dict) else None + if not isinstance(usage, dict): + usage = {} + granularity = 'missing_provider_receipt' + prompt, completion = (usage.get('prompt_tokens'), usage.get('completion_tokens')) + native_fresh = usage.get('input_uncached_tokens') + prompt = prompt if type(prompt) is int and prompt >= 0 else None + native_fresh = native_fresh if type(native_fresh) is int and native_fresh >= 0 else None + if type(completion) is not int or completion < 0 or (prompt is None and native_fresh is None): + completion = completion if type(completion) is int and completion >= 0 else 0 + granularity = granularity or 'invalid_provider_receipt' + details = usage.get('prompt_tokens_details') + if details is not None and (not isinstance(details, dict)): + granularity = 'invalid_provider_receipt' + details = details if isinstance(details, dict) else {} + cached = details.get('cached_tokens') + if native_usage is not None: + native = native_usage['usage_metadata'] + native_output = native.get('candidatesTokenCount', 0) + native.get('thoughtsTokenCount', 0) + if prompt == native['promptTokenCount'] and completion == native_output: + cached = native.get('cachedContentTokenCount', 0) + else: + native_usage = None + written = next((value for value in (usage.get('input_cache_write_tokens'), usage.get('cache_creation_input_tokens'), details.get('cache_creation_tokens'), details.get('cache_write_tokens')) if value is not None), None) + invalid = any((value is not None and (type(value) is not int or value < 0) for value in (cached, written))) + cached = cached if type(cached) is int and cached >= 0 else None + written = written if type(written) is int and written >= 0 else None + fresh = native_fresh + if fresh is None and prompt is not None and (cached is not None) and (written is not None): + fresh = prompt - cached - written + if fresh is not None and (fresh < 0 or (prompt is not None and cached is not None and (written is not None) and (fresh + cached + written != prompt))): + invalid, fresh = (True, None) + provider, _, slug = model.partition('/') + event: dict = {'type': 'step_finish', 'part': {'providerID': provider if slug else 'openai', 'modelID': slug or model, 'tokens': {'input': fresh, 'output': completion, 'cache': {'read': cached, 'write': written}}}} + field_status = {'prompt_tokens': _token_field_status(usage, 'prompt_tokens'), 'completion_tokens': _token_field_status(usage, 'completion_tokens'), 'input_uncached_tokens': _token_field_status(usage, 'input_uncached_tokens')} + field_status['native_prompt_token_count'] = native_prompt_status if native_prompt_status in {'missing', 'null', 'invalid', 'valid', 'not_observed'} else 'unsupported' + part: dict = event['part'] + part['usage_field_status'] = field_status + if native_usage is not None: + event['part']['native_usage'] = native_usage + event['part']['token_categories_provenance'] = 'explicit_presence_v1' + if fresh is None and prompt is not None: + event['part']['prompt_tokens_inclusive'] = prompt + if invalid or any((value is None for value in (fresh, cached, written))): + granularity = granularity if granularity not in (None, 'request') else 'invalid_provider_receipt' if invalid else 'incomplete_token_categories' + if granularity: + event['part']['usage_granularity'] = granularity + if provider == 'openrouter': + cost = usage.get('cost') + if cost is None: + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + if isinstance(headers, dict): + cost = headers.get('llm_provider-x-litellm-response-cost') + if isinstance(cost, (int, float)) and (not isinstance(cost, bool)) and math.isfinite(cost) and (cost >= 0): + event['part']['cost'] = cost + data = data if isinstance(data, dict) else {} + if isinstance(data.get('id'), str) and data['id']: + event['part']['provider_request_id'] = data['id'] + for key in ('service_tier', 'cache_ttl'): + if data.get(key): + event['part'][key] = data[key] + route = _llm_route_from_response(response) or _canonical_llm_route(llm_route) + if route is not None: + event['part']['llm_route'] = route + created = data.get('created') + stamp = datetime.now(timezone.utc) + try: + if isinstance(created, str): + parsed = datetime.fromisoformat(created.replace('Z', '+00:00')) + if parsed.tzinfo is not None: + stamp = parsed + elif isinstance(created, (int, float)) and (not isinstance(created, bool)) and math.isfinite(created): + stamp = datetime.fromtimestamp(created, timezone.utc) + except (ValueError, OverflowError, OSError): + pass + pair = json.dumps({'type': 'step_start', 'timestamp': stamp.isoformat()}) + '\n' + pair += json.dumps(event) + '\n' + try: + receipt_path = target or Path(os.environ.get('M1_JUDGE_USAGE_PATH', '/logs/verifier/judge-trajectory.jsonl')) + receipt_path.parent.mkdir(parents=True, exist_ok=True) + with receipt_path.open('a') as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + handle.write(pair) + handle.flush() + os.fsync(handle.fileno()) + except OSError as exc: + if target is not None: + raise JudgeReceiptError(f'judge receipt write failed: {exc}') from exc + print(f'judge accounting: write failed ({type(exc).__name__})', file=sys.stderr) + +def openrouter_judge_pins() -> dict[str, dict]: + raw = os.environ.get('M1_OPENROUTER_JUDGE_PROVIDER_PINS', '').strip() + if not raw: + return {} + try: + pins = json.loads(raw) + except json.JSONDecodeError: + print('judge provider pins: invalid JSON in M1_OPENROUTER_JUDGE_PROVIDER_PINS', file=sys.stderr) + return {} + return {model: pin for model, pin in pins.items() if isinstance(pin, dict) and pin.get('order')} if isinstance(pins, dict) else {} + +def apply_judge_provider_pin(kwargs: dict, pins: dict[str, dict]) -> dict: + model = kwargs.get('model') + pin = pins.get(model) if isinstance(model, str) else None + if pin is None: + return kwargs + extra_body = dict(kwargs.get('extra_body') or {}) + provider = dict(extra_body.get('provider') or {}) + provider['order'] = list(pin['order']) + if pin.get('allow_fallbacks') is False: + provider['allow_fallbacks'] = False + if pin.get('zdr'): + provider['zdr'] = True + extra_body['provider'] = provider + return {**kwargs, 'extra_body': extra_body} +_TRANSIENT_ERROR_NAMES = ('RateLimitError', 'ServiceUnavailableError', 'InternalServerError', 'BadGatewayError', 'APIConnectionError') +_RETRYABLE_STATUS_CODES = frozenset({408, 409, 425, 429, 500, 502, 503, 504}) +_AUTH_ERROR_NAMES = ('AuthenticationError', 'PermissionDeniedError') +_AUTH_STATUS_CODES = frozenset({401, 403}) +_AUTH_RETRIES = 4 +_DEFAULT_TRANSIENT_RETRIES = 6 +_MAX_TRANSIENT_RETRIES = 20 +_MAX_RETRY_DELAY_SECONDS = 60.0 +_DEFAULT_EMPTY_RESPONSE_RETRIES = 3 +_DEFAULT_RETRY_BUDGET_SECONDS = 900.0 +_MAX_RETRY_BUDGET_SECONDS = 86400.0 + +def transient_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_TRANSIENT_RETRIES', '').strip() + if not raw: + return _DEFAULT_TRANSIENT_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_TRANSIENT_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_TRANSIENT_RETRIES + +def empty_response_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_EMPTY_RESPONSE_RETRIES', '').strip() + if not raw: + return _DEFAULT_EMPTY_RESPONSE_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_EMPTY_RESPONSE_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_EMPTY_RESPONSE_RETRIES + +def retry_budget_seconds() -> float: + raw = os.environ.get('M1_JUDGE_RETRY_BUDGET_SECONDS', '').strip() + if not raw: + return _DEFAULT_RETRY_BUDGET_SECONDS + try: + value = float(raw) + except ValueError: + value = math.nan + if not math.isfinite(value) or value < 0: + print('judge retries: invalid M1_JUDGE_RETRY_BUDGET_SECONDS, using the default', file=sys.stderr) + return _DEFAULT_RETRY_BUDGET_SECONDS + return min(value, _MAX_RETRY_BUDGET_SECONDS) + +def _within_budget(deadline: float, delay: float, model) -> bool: + remaining = deadline - time.monotonic() + if delay <= remaining: + return True + print(f'judge call retry budget spent: {model} would wait {delay:.1f}s with {max(remaining, 0.0):.1f}s left of M1_JUDGE_RETRY_BUDGET_SECONDS, failing now', file=sys.stderr) + return False + +def is_empty_verdict(response) -> bool: + data = response.model_dump() if hasattr(response, 'model_dump') else response + if not isinstance(data, dict): + return False + choices = data.get('choices') + if not isinstance(choices, list) or not choices: + return True + first = choices[0] + message = first.get('message') if isinstance(first, dict) else None + if not isinstance(message, dict): + return True + if message.get('tool_calls') or message.get('function_call'): + return False + content = message.get('content') + if isinstance(content, list): + content = ''.join((part.get('text') or '' for part in content if isinstance(part, dict))) + return not (isinstance(content, str) and content.strip()) + +def _matches(exc: BaseException, litellm, names: tuple[str, ...], statuses: frozenset[int]) -> bool: + classes = tuple((cls for cls in (getattr(litellm, name, None) for name in names) if isinstance(cls, type))) + if classes and isinstance(exc, classes): + return True + status = getattr(exc, 'status_code', None) + return type(status) is int and status in statuses + +def is_transient_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _TRANSIENT_ERROR_NAMES, _RETRYABLE_STATUS_CODES) + +def is_auth_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _AUTH_ERROR_NAMES, _AUTH_STATUS_CODES) + +def should_retry(exc: BaseException, litellm, attempt: int, limit: int) -> bool: + if attempt < limit and is_transient_error(exc, litellm): + return True + return attempt < min(limit, _AUTH_RETRIES) and is_auth_error(exc, litellm) + +def _retry_after_seconds(exc: BaseException) -> float | None: + headers = getattr(exc, 'headers', None) + if headers is None: + headers = getattr(getattr(exc, 'response', None), 'headers', None) + if headers is None: + return None + try: + raw = headers.get('retry-after') + if raw is None: + raw = headers.get('Retry-After') + value = float(raw) + except (AttributeError, TypeError, ValueError): + return None + return value if math.isfinite(value) and value >= 0 else None + +def retry_delay(exc: BaseException | None, attempt: int) -> float: + base = min(_MAX_RETRY_DELAY_SECONDS, 2.0 ** (attempt + 1)) + delay = base * (0.5 + random.random()) + retry_after = _retry_after_seconds(exc) if exc is not None else None + if retry_after is not None: + delay = max(delay, min(_MAX_RETRY_DELAY_SECONDS, retry_after)) + return delay + +def _note_retry(model, exc: BaseException, attempt: int, limit: int, delay: float) -> None: + status = getattr(exc, 'status_code', None) + print(f"judge call retry {attempt}/{limit}: {model} {type(exc).__name__} status={(status if type(status) is int else 'n/a')}, waiting {delay:.1f}s", file=sys.stderr) + +def _note_empty(model, response, attempt: int, limit: int, delay: float) -> None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + reason = None + if isinstance(data, dict) and isinstance(data.get('choices'), list) and data['choices']: + first = data['choices'][0] + reason = first.get('finish_reason') if isinstance(first, dict) else None + print(f'judge call retry {attempt}/{limit}: {model} empty verdict (finish_reason={reason}), waiting {delay:.1f}s', file=sys.stderr) + +def install(litellm, *, synchronous: bool=False) -> None: + pins = openrouter_judge_pins() + limit = transient_retry_limit() + empty_limit = empty_response_retry_limit() + deadline = time.monotonic() + retry_budget_seconds() + if synchronous: + original = litellm.completion + + def accounted(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = original(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + time.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + time.sleep(delay) + continue + return response + litellm.completion = accounted + return + original_async = litellm.acompletion + + async def accounted_async(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = await original_async(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + await asyncio.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + await asyncio.sleep(delay) + continue + return response + litellm.acompletion = accounted_async + +def record_agent_usage(attempt, *, model: str, provider: str) -> None: + records: dict[str, tuple[str, dict]] = {} + current_model = model + for filename in getattr(attempt, 'logs', []): + try: + with Path(filename).open() as stream: + for line in stream: + try: + event = json.loads(line) + except (ValueError, TypeError): + continue + if not isinstance(event, dict): + continue + message = event.get('message') or {} + if event.get('type') == 'assistant' and isinstance(message, dict) and isinstance(message.get('usage'), dict): + raw = message['usage'] + cached, written = (raw.get('cache_read_input_tokens'), raw.get('cache_creation_input_tokens')) + if all((type(value) is int and value >= 0 for value in (raw.get('input_tokens'), raw.get('output_tokens')))) and all((value is None or (type(value) is int and value >= 0) for value in (cached, written))): + receipt: dict = {'usage': {'input_uncached_tokens': raw['input_tokens'], 'prompt_tokens': raw['input_tokens'] + cached + written if cached is not None and written is not None else None, 'completion_tokens': raw['output_tokens'], 'prompt_tokens_details': {'cached_tokens': cached, 'cache_creation_tokens': written}}} + receipt['created'] = event.get('timestamp') + creation = raw.get('cache_creation') or {} + hour = creation.get('ephemeral_1h_input_tokens', 0) if isinstance(creation, dict) else 0 + if type(hour) is int and hour > 0: + if hour == written: + receipt['cache_ttl'] = '1h' + else: + receipt['usage_granularity'] = 'mixed_cache_ttl' + records[message.get('id') or json.dumps(raw, sort_keys=True)] = (message.get('model') or current_model, receipt) + payload = event.get('payload') or {} + if not isinstance(payload, dict): + continue + if event.get('type') == 'turn_context' and payload.get('model'): + current_model = payload['model'] + if event.get('type') == 'event_msg' and payload.get('type') == 'token_count': + info = payload.get('info') or {} + raw, total = (info.get('last_token_usage'), info.get('total_token_usage')) + if isinstance(raw, dict) and isinstance(total, dict) and all((type(raw.get(key)) is int and raw.get(key) >= 0 for key in ('input_tokens', 'output_tokens'))): + receipt = {'usage': {'prompt_tokens': raw.get('input_tokens'), 'input_uncached_tokens': raw.get('input_uncached_tokens'), 'input_cache_write_tokens': raw.get('input_cache_write_tokens'), 'completion_tokens': raw.get('output_tokens'), 'prompt_tokens_details': {'cached_tokens': raw.get('cached_input_tokens')}}} + receipt['created'] = event.get('timestamp') + records[json.dumps(total, sort_keys=True)] = (current_model, receipt) + except OSError: + continue + captured_input = captured_output = 0 + input_complete = True + for requested, receipt in records.values(): + requested = requested if '/' in requested else f'{provider}/{requested}' + _record_judge_usage(receipt, requested) + receipt_input = receipt['usage'].get('prompt_tokens') + if receipt_input is None: + input_complete = False + else: + captured_input += receipt_input + captured_output += receipt['usage'].get('completion_tokens') or 0 + total = getattr(attempt, 'usage', {}) or {} + if not records or (input_complete and total.get('input_tokens') != captured_input) or total.get('output_tokens') != captured_output: + _record_judge_usage({'usage': {'prompt_tokens': 0, 'completion_tokens': 0}, 'usage_granularity': 'incomplete_agent_receipts'}, model if '/' in model else f'{provider}/{model}') + +def install_rewardkit_agents() -> None: + import rewardkit.judges as judges + original = judges.get_agent + + def get_accounted_agent(judge, cwd=None): + backend = original(judge, cwd) + run = backend.run + + async def accounted_run(*args, **kwargs): + attempt = await run(*args, **kwargs) + record_agent_usage(attempt, model=judge.model or 'unknown', provider='anthropic' if judge.agent == 'claude-code' else 'openai') + return attempt + setattr(backend, 'run', accounted_run) + return backend + setattr(judges, 'get_agent', get_accounted_agent) +if __name__ == '__main__': + import litellm + if len(sys.argv) > 2 and sys.argv[1] == '--script': + import runpy + install(litellm, synchronous=True) + sys.argv = sys.argv[2:] + runpy.run_path(sys.argv[0], run_name='__main__') + else: + install(litellm) + install_rewardkit_agents() + if Path(__file__).with_name('m1_judge_panel.json').is_file(): + from m1_rewardkit_panel import install_panel + install_panel(Path(__file__).with_name('m1_judge_panel.json')) + if Path(__file__).with_name('m1_judge_jev.json').is_file(): + from m1_rewardkit_jev import install_jev + install_jev(Path(__file__).with_name('m1_judge_jev.json')) + from rewardkit.__main__ import main + main() diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/m1_rewardkit_panel.py b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/m1_rewardkit_panel.py new file mode 100644 index 0000000000000000000000000000000000000000..164cc2ae521cdd368c2e1749d7ed8fe09f4545eb --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/m1_rewardkit_panel.py @@ -0,0 +1,169 @@ +from __future__ import annotations +import asyncio +from contextvars import ContextVar +import json +import math +import os +import sys +from pathlib import Path +from typing import Any +import uuid +_request_audit: ContextVar[tuple[Path, list[str]] | None] = ContextVar('panel_request_audit', default=None) + +class PanelIncompleteError(RuntimeError): + pass + +def _audit_warning(exc: Exception, warnings: list[str]) -> None: + message = f'judge panel audit: diagnostic capture failed ({type(exc).__name__})' + if message not in warnings: + warnings.append(message) + print(message, file=sys.stderr) + +def _write_audit(path: Path, record: dict[str, Any], warnings: list[str], *, append: bool=False) -> None: + try: + text = json.dumps(record, allow_nan=False, default=str) + '\n' + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('a' if append else 'w') as stream: + stream.write(text) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + +def _binary(raw: Any) -> int: + if isinstance(raw, bool): + return int(raw) + if isinstance(raw, int | float) and math.isfinite(raw) and (raw in (0, 1)): + return int(raw) + if isinstance(raw, str): + value = raw.strip().lower() + if value in {'yes', 'true', '1'}: + return 1 + if value in {'no', 'false', '0'}: + return 0 + raise PanelIncompleteError('m1_judge_panel_incomplete: invalid binary vote') + +def validate_votes(scores: list[Any], criteria: list[Any]) -> None: + names = [criterion.name for criterion in criteria] + if len(set(names)) != len(names) or [score.name for score in scores] != names: + raise PanelIncompleteError('m1_judge_panel_incomplete: criterion membership mismatch') + for score, criterion in zip(scores, criteria, strict=True): + if score.error: + raise PanelIncompleteError('m1_judge_panel_incomplete: judge returned an error') + raw = _binary(score.raw) + expected = 1 - raw if criterion.negate else raw + if not math.isfinite(score.value) or score.value != expected: + raise PanelIncompleteError('m1_judge_panel_incomplete: inconsistent binary score') + +async def run_panel(judge: Any, criteria: list[Any], weights: list[float] | None, system_prompt: str | None, *, config: dict[str, Any], run_llm: Any, score_type: Any, audit_dir: Path) -> tuple[list[Any], str, list[str]]: + from rewardkit.models import Binary + if not criteria or any((not isinstance(criterion.output_format, Binary) for criterion in criteria)): + raise ValueError('panel majority voting requires nonempty binary criteria') + group_dir = audit_dir / uuid.uuid4().hex + warnings_out: list[str] = [] + + async def member_call(index: int, member: dict[str, Any]): + member_judge = judge.model_copy(update=member) + evidence: dict[str, Any] = {'member': index + 1, 'judge': member, 'criteria': [criterion.name for criterion in criteria], 'status': 'started'} + path = group_dir / f'judge-{index + 1}.json' + _write_audit(path, evidence, warnings_out) + token = _request_audit.set((group_dir / f'judge-{index + 1}-requests.jsonl', warnings_out)) + try: + scores, output, warnings = await run_llm(member_judge, criteria, weights, system_prompt) + evidence.update(output=output, warnings=warnings) + validate_votes(scores, criteria) + evidence['scores'] = [score.to_dict() for score in scores] + evidence['status'] = 'completed' + return (scores, output, warnings) + except BaseException as exc: + evidence.update(status='failed', error_class=type(exc).__name__) + if isinstance(exc, PanelIncompleteError): + evidence['error'] = str(exc) + raise + finally: + _request_audit.reset(token) + _write_audit(path, evidence, warnings_out) + outcomes = await asyncio.gather(*(member_call(index, member) for index, member in enumerate(config['members'])), return_exceptions=True) + failed = [index + 1 for index, result in enumerate(outcomes) if isinstance(result, BaseException)] + if failed: + _write_audit(group_dir / 'panel.json', {'status': 'incomplete', 'failed_members': failed}, warnings_out) + raise PanelIncompleteError(f'm1_judge_panel_incomplete: failed members {failed}; see panel audit artifacts') + completed = [outcome for outcome in outcomes if not isinstance(outcome, BaseException)] + combined = [] + for index, criterion in enumerate(criteria): + votes = [{'judge': config['members'][member_index], **outcome[0][index].to_dict()} for member_index, outcome in enumerate(completed)] + passes = sum((vote['value'] == 1 for vote in votes)) + value = int(passes >= 2) + combined.append(score_type(name=criterion.name, value=value, raw=bool(1 - value if criterion.negate else value), weight=weights[index] if weights is not None else 1.0, reasoning=f'{passes}/3 judges passed; strict majority requires 2/3.', description=criterion.description, id=criterion.id, negate=criterion.negate, optional=criterion.optional, votes=votes)) + for outcome in completed: + warnings_out.extend(outcome[2]) + audit = {'status': 'completed', 'mode': 'panel', 'aggregation': 'majority', 'required_votes': 2, 'members': config['members'], 'criteria': [score.to_dict() for score in combined]} + output = json.dumps(audit, indent=2, allow_nan=False) + _write_audit(group_dir / 'panel.json', audit, warnings_out) + return (combined, output, warnings_out) + +def install_panel(config_path: Path, *, audit_dir: Path=Path('/logs/verifier/judge-panel')) -> None: + import rewardkit.judges as judges + import rewardkit.reward as reward + from rewardkit.models import LLMJudge, Score + import litellm + config = json.loads(config_path.read_text()) + members = config.get('members') + concurrency = config.get('max_concurrent_llm') + if config.get('mode') != 'panel' or not isinstance(members, list) or len(members) != 3 or (len({member['model'] for member in members}) != 3) or (type(concurrency) is not int) or (not 1 <= concurrency <= 64): + raise ValueError('invalid materialized panel configuration') + if os.environ.get('REWARDKIT_JUDGE') or os.environ.get('REWARDKIT_MODEL'): + raise ValueError('RewardKit environment overrides cannot replace a frozen panel') + + class PanelScore(Score): + votes: list[dict[str, Any]] + + def to_dict(self): + return {**super().to_dict(), 'votes': self.votes} + original_llm = judges.arun_llm + original_call = judges._arun_llm_call + original_details = reward.Reward.to_detail_dict + original_completion = litellm.acompletion + active_loop = None + semaphore = None + + async def captured_completion(*args, **kwargs): + context = _request_audit.get() + record = {'requested_model': kwargs.get('model')} + response = None + try: + response = await original_completion(*args, **kwargs) + return response + except BaseException as exc: + record['error_class'] = type(exc).__name__ + raise + finally: + if context is not None: + path, warnings = context + try: + if response is not None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + record.update(response_model=data.get('model'), choices=data.get('choices')) + _write_audit(path, record, warnings, append=True) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + + async def bounded_call(*args, **kwargs): + nonlocal active_loop, semaphore + loop = asyncio.get_running_loop() + if active_loop is not loop: + active_loop, semaphore = (loop, asyncio.Semaphore(concurrency)) + assert semaphore is not None + async with semaphore: + return await original_call(*args, **kwargs) + + async def panel_call(judge, criteria, weights=None, system_prompt=None): + return await run_panel(judge, criteria, weights, system_prompt, config=config, run_llm=original_llm, score_type=PanelScore, audit_dir=audit_dir) + + def panel_details(self, score): + detail = original_details(self, score) + if isinstance(self.judge, LLMJudge): + detail.update(kind='llm_panel', judge=config, aggregation='majority', required_votes=2) + return detail + setattr(reward, 'arun_llm', panel_call) + setattr(judges, '_arun_llm_call', bounded_call) + setattr(litellm, 'acompletion', captured_completion) + reward.Reward.to_detail_dict = panel_details diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/normalize_reward.py b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/normalize_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..91817ef00ea9152ca57f0030d8e879eb850ddff0 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/normalize_reward.py @@ -0,0 +1,71 @@ +from __future__ import annotations +import argparse +import json +from pathlib import Path +from typing import Any + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument('--raw-details', required=True) + parser.add_argument('--rubric', required=True) + parser.add_argument('--reward-out', required=True) + parser.add_argument('--details-out', required=True) + args = parser.parse_args() + raw_details = _load_json(Path(args.raw_details)) + rubric = _load_json(Path(args.rubric)) + criteria = rubric['criteria'] + raw_by_name = _raw_criteria_by_name(raw_details) + positive_total = sum((float(item['score']) for item in criteria if float(item['score']) > 0)) + if positive_total <= 0: + raise ValueError('rubric must contain at least one positive score') + earned = 0.0 + normalized_criteria: list[dict[str, Any]] = [] + for item in criteria: + signed_score = float(item['score']) + raw = raw_by_name.get(item['name'], {}) + value = _coerce_score(raw.get('value', 0.0)) + contribution = value * signed_score + earned += contribution + normalized_criteria.append({'name': item['name'], 'value': value, 'raw': raw.get('raw'), 'weight': signed_score, 'signed_score': signed_score, 'polarity': item['polarity'], 'contribution': contribution, 'description': item['description'], 'source': item.get('source', ''), 'justification': item.get('justification', ''), 'metadata': item.get('metadata', {}), 'reasoning': raw.get('reasoning'), 'judge_reasoning': raw.get('reasoning'), 'judge_error': raw.get('error'), **({'votes': raw['votes']} if 'votes' in raw else {})}) + unclamped = earned / positive_total + reward = max(0.0, min(1.0, unclamped)) + reward_out = {'correctness': reward} + details_out = {'correctness': {'score': reward, 'kind': 'signed_score', 'criteria': normalized_criteria, 'aggregation': {'method': 'signed_score_ratio_clamped', 'earned': earned, 'positive_total': positive_total, 'unclamped': unclamped, 'clamped': reward}, 'raw_rewardkit': raw_details}} + _write_json(Path(args.reward_out), reward_out) + _write_json(Path(args.details_out), details_out) + +def _load_json(path: Path) -> Any: + return json.loads(path.read_text()) + +def _write_json(path: Path, data: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data, indent=2) + '\n') + +def _raw_criteria_by_name(details: dict[str, Any]) -> dict[str, dict[str, Any]]: + out: dict[str, dict[str, Any]] = {} + for reward in details.values(): + for item in _iter_raw_criteria(reward): + name = item.get('name') + if isinstance(name, str): + out[name] = item + return out + +def _iter_raw_criteria(value: Any): + if isinstance(value, list): + for item in value: + yield from _iter_raw_criteria(item) + return + if not isinstance(value, dict): + return + for item in value.get('criteria') or []: + if isinstance(item, dict): + yield item + +def _coerce_score(value: Any) -> float: + if isinstance(value, bool): + return 1.0 if value else 0.0 + if isinstance(value, int | float): + return max(0.0, min(1.0, float(value))) + return 0.0 +if __name__ == '__main__': + main() diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/agent_prompt.md b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/agent_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..ca489c065bafd5d10e764f033c9dfd1195933db3 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/agent_prompt.md @@ -0,0 +1,10 @@ +You are grading the submitted legal analysis against the criteria below. + +Read `/logs/artifacts/answer.md`, the answer captured by the verifier, before +assigning any scores. Evaluate that file as the submission. Other files in +`/app` may supply context, but must not replace the submitted answer. Do not +modify the submission. If it is missing or empty, state that in your reasoning +and apply the criteria to that missing or empty submission. Preserve each +criterion's stated positive or penalty polarity. + +{criteria} diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_1.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_1.toml new file mode 100644 index 0000000000000000000000000000000000000000..632bf075d589079742aa8845fbc3edb886cef6d1 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_1.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_1" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that under D.C. Code § 1-605.02(6) (2016) an arbitration award may be set aside where the award on its face is contrary to law." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_10.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_10.toml new file mode 100644 index 0000000000000000000000000000000000000000..6cbb1f7688db57e96376a4e3c075893e23a4cbbc --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_10.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_10" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: States that disagreement with the arbitrator’s weighing of the Douglas factors is itself sufficient to render the Award contrary to law." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_11.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_11.toml new file mode 100644 index 0000000000000000000000000000000000000000..da29e266affd884d2b5d2131d8157a879b17d8e9 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_11.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_11" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that PERB's unexplained rejection of MPD's arguments undermines the deference its interpretation would otherwise receive." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_12.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_12.toml new file mode 100644 index 0000000000000000000000000000000000000000..03a0fa3d4e0a80b61eee5ab3dbe288832552374d --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_12.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_12" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that no uploaded opinion decides whether an arbitrator's penalty determination can be on its face contrary to law." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_13.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_13.toml new file mode 100644 index 0000000000000000000000000000000000000000..0abb628e08ae676e5ac59abdf4ac39c879545b5e --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_13.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_13" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that MPD's public policy argument must target enforcement of the reinstatement remedy rather than the shooting itself." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_14.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_14.toml new file mode 100644 index 0000000000000000000000000000000000000000..5d66439cce54c03e4ba21577bb74bf26f2d12f78 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_14.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_14" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that the public policy MPD should invoke is a policy against the unjustified use of deadly force by police officers" +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_15.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_15.toml new file mode 100644 index 0000000000000000000000000000000000000000..8827358cd740b7d2d8694fd53cc52e34a946a54b --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_15.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_15" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: Mentions Eastern Associated Coal Corp. v. United Mine Workers as authority for the public policy analysis." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_16.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_16.toml new file mode 100644 index 0000000000000000000000000000000000000000..e567fb441c92be1cdee399faa21e8bee150b75af --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_16.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_16" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that the PERB Decision misstates the length of the suspension imposed by the Award." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_2.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_2.toml new file mode 100644 index 0000000000000000000000000000000000000000..0e7bf03c02cdf4c0de9485ea435a8a618c3b1808 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_2.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_2" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that a decision of PERB must stand unless it is rationally indefensible" +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_3.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_3.toml new file mode 100644 index 0000000000000000000000000000000000000000..43f9e563926594d2b3a74c89aa17e72f363dc712 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_3.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_3" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions that MPD’s contrary-to-law argument can be framed as the arbitrator purporting to apply Douglas while overlooking its limits on penalty review." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_4.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_4.toml new file mode 100644 index 0000000000000000000000000000000000000000..3f3b53b82ff53d747b1f22c59b021dc363ff2e6a --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_4.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_4" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that the invoked policy against the unjustified use of deadly force by police officers must be well defined and dominant." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_5.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_5.toml new file mode 100644 index 0000000000000000000000000000000000000000..075c9e3b70e5b1e19132bc0ff519ef3c27e2fcc2 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_5.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_5" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions that the public policy question is whether enforcing the award would violate public policy rather than whether the misconduct did." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_6.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_6.toml new file mode 100644 index 0000000000000000000000000000000000000000..90aa212519f06fe204a3becbacd4a87f0fb11524 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_6.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_6" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions that a violation of the properly framed public policy must be clearly shown before an award may be refused enforcement." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_7.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_7.toml new file mode 100644 index 0000000000000000000000000000000000000000..1156a85ee16fbce55b16404f4a0948e341eea8ac --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_7.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_7" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that the PERB Decision affirmed the Award without addressing MPD's specific contrary-to-law arguments" +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_8.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_8.toml new file mode 100644 index 0000000000000000000000000000000000000000..f252b9ff20de3f08f7db1d042e285dc64dacb6b8 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_8.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_8" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: States that the DCCA applies PERB decisions under the ordinary deference owed to expert agencies rather than an unusually deferential standard in its reviews." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_9.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_9.toml new file mode 100644 index 0000000000000000000000000000000000000000..49eed11ac3bd22804a156a9ac559dc2e80e5f1dd --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/raw_correctness/criterion_9.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_9" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: States that the wrongfulness of Braddock’s misconduct itself establishes that the Award violates public policy." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/test.sh b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..66a509a7bcdbe412851f3a012a5ba7b16cf0925b --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/tests/test.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +set -euo pipefail + +mkdir -p /logs/artifacts /logs/verifier/raw + +python3 - <<'PYEOF' +import json +import shutil +from pathlib import Path + + +def has_text(path: Path) -> bool: + return path.exists() and path.is_file() and bool(path.read_text(errors="replace").strip()) + + +def fallback_paths(answer_path: Path) -> list[Path]: + paths = [] + try: + relative = answer_path.relative_to("/app") + paths.append(Path("/app/app") / relative) + except ValueError: + pass + return [path for path in paths if path != answer_path] + + +config = json.loads(Path("/tests/fixtures/config.json").read_text()) +answer_path = Path(config["answer_path"]) +artifact_answer = Path("/logs/artifacts/answer.md") +artifact_answer.parent.mkdir(parents=True, exist_ok=True) +if has_text(answer_path): + shutil.copyfile(answer_path, artifact_answer) +else: + for candidate in fallback_paths(answer_path): + if has_text(candidate): + shutil.copyfile(candidate, artifact_answer) + break + else: + artifact_answer.write_text("") + +# Harbor collects /logs/artifacts when the agent step ends, which is before this +# script runs, so the copy above never reaches the uploaded artifacts. /logs/verifier +# is uploaded after the verifier phase, so persist the graded answer there too. +verifier_answer = Path("/logs/verifier/answer.md") +verifier_answer.parent.mkdir(parents=True, exist_ok=True) +shutil.copyfile(artifact_answer, verifier_answer) +PYEOF + +uv run --no-project --with 'harbor-rewardkit[all]==0.2.0' python /tests/m1_rewardkit_accounting.py /tests/raw_correctness \ + --workspace /app \ + --output /logs/verifier/raw/reward.json \ + --max-concurrent-llm "${MAX_CONCURRENT_LLM:-4}" \ + --max-concurrent-agent "${M1_MAX_CONCURRENT_AGENT:-1}" + +python /tests/normalize_reward.py \ + --raw-details /logs/verifier/raw/reward-details.json \ + --rubric /tests/fixtures/rubric.json \ + --reward-out /logs/verifier/reward.json \ + --details-out /logs/verifier/reward-details.json diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/workdir/attachments/dc_code_1-605.02.pdf b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/workdir/attachments/dc_code_1-605.02.pdf new file mode 100644 index 0000000000000000000000000000000000000000..cf0459c82d66c8bf270b540b8af4fad0f94fa8e8 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/workdir/attachments/dc_code_1-605.02.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c0dc52d0ab0e0430b8885ee37a6509ab4a61dbf20cda284d84884331dbe7905b +size 141416 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/workdir/attachments/fop_doc_labor_comm_v_perb_2009.pdf b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/workdir/attachments/fop_doc_labor_comm_v_perb_2009.pdf new file mode 100644 index 0000000000000000000000000000000000000000..da786efed08591bf0ba24cc511baed860705ce2e --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/workdir/attachments/fop_doc_labor_comm_v_perb_2009.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:da5f7c58c3f024caba3c6856231ea3e5da7bd180ba04ce5bee00b47bd5a5fd00 +size 273649 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/workdir/attachments/paperworkers_v_misco.pdf b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/workdir/attachments/paperworkers_v_misco.pdf new file mode 100644 index 0000000000000000000000000000000000000000..821511a8f46faeb7f26757ea154b883e5095e1f7 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/workdir/attachments/paperworkers_v_misco.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2601d8a6040d52afb4cbce632bddb0285c988e2e13bfd97125527a004de9d89b +size 368112 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/workdir/attachments/perb_decision_braddock.pdf b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/workdir/attachments/perb_decision_braddock.pdf new file mode 100644 index 0000000000000000000000000000000000000000..5885f09b130295978585d6fc7820103e0ff8f226 Binary files /dev/null and b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/workdir/attachments/perb_decision_braddock.pdf differ diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/workdir/attachments/wr_grace_v_rubber_workers.pdf b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/workdir/attachments/wr_grace_v_rubber_workers.pdf new file mode 100644 index 0000000000000000000000000000000000000000..43d80a2247c83a37eb8472e575b67a836e723c56 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-3/workdir/attachments/wr_grace_v_rubber_workers.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:474a810c5a287898a9f192279d82528546df5e26b0a6390612d84a1058b4eba2 +size 348231 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/instruction.md b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0ba9cbc40a1a08d0184ffa0e7d92da5f8c1b38bd --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/instruction.md @@ -0,0 +1,63 @@ +# Viability of a DCCA Challenge — Supplemental Comparator Disclosure + +Domain: Litigation + +Matter: MPD v. PERB + +You are a senior legal analyst operating autonomously. You are completing a multi-step legal reasoning task. Follow the role, factual record, instructions, and deliverable requirements provided in the Task and each Assignment. + +Each Assignment may require a different legal deliverable. Follow the requirements specific to that Assignment. + +## Word limits for court briefs + +- A brief in support of or in response to a motion may not exceed **8,750 words**. +- A reply brief may not exceed **3,500 words**. +- For a motion for reconsideration, a brief in support of or in response to the motion may not exceed **3,500 words**, and a reply brief may not exceed **1,750 words**. +- If an Assignment specifies a stricter word limit, follow the stricter limit. + +These word limits do not apply to legal memoranda or other non-court-filing deliverables unless the Assignment expressly provides otherwise. + +Complete the task end-to-end without asking for confirmation, permission, or clarification. + +Use the uploaded matter documents in `/app/attachments/` as your primary case file. You also have internet access via OpenCode's `websearch` tool; use it to research any statutes, regulations, cases, administrative guidance, or secondary authorities that are not supplied as attachments. Cite any authority you rely on in the format requested by the prompt. + +For document inspection: +- PDF: `pdftotext /app/attachments/.pdf -` +- DOCX: `pandoc /app/attachments/.docx -t markdown` +- XLSX/CSV: use Python with `openpyxl` or `pandas` +- If extraction is unreliable, inspect the raw file with Python libraries or convert/render the relevant pages. + +Write the final complete legal deliverable for this assignment to `/app/response4.md`. The verifier reads only that file. + +This is a follow-on assignment. The documents from the previous assignment(s) remain available in `/app/attachments/`, and your prior deliverable `/app/response3.md` is also on disk. Build on that analysis as the prompt directs. + +## Attachments + +- `/app/attachments/supplemental_comparator_disclosure.pdf` + + +## Prompt + +Our firm represents the District of Columbia Metropolitan Police Department ("MPD") in connection with an arbitration award that reduced Officer Colin Braddock’s termination for excessive force to a 45-day suspension based solely on the arbitrator’s findings regarding Douglas factors six and twelve. The D.C. Public Employee Relations Board ("PERB") affirmed the award, and the firm has been developing arguments for a petition to the District of Columbia Court of Appeals ("DCCA") under the contrary-to-law and public-policy exceptions in D.C. Code sec. 1-605.02(6). MPD’s labor liaison has now disclosed a fifth comparator case that was not part of the arbitration record. + +Treat the following as true for all purposes in this matter, whether or not separately memorialized in the record: (a) reasonable minds can disagree as to how comparable the four comparator cases are to Braddock’s case; (b) at no point before the arbitration hearing did Braddock or his union allege that MPD treated similarly situated employees differently; and (c) Braddock knew that MPD intended to rely on the four comparator cases before MPD found him guilty of the excessive force charge. + +The following documents have been uploaded for this Step: + +D.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117 (May 22, 2024) (final_notice_adverse_action_braddock.pdf) +In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf) +Memorandum from Yolanda Britt, Director, Disciplinary Review Division, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Sandra M. Delgado, Assistant Chief, Professional Development Bureau, re: Comparator Discipline Cases, Adverse Action Case No. IS-23-002841 (Braddock) (Apr. 11, 2024) (comparator_discipline_cases.pdf) +Douglas v. Veterans Administration, 5 M.S.P.R. 280 (1981) (douglas_v_veterans_admin.pdf) +D.C. Mun. Regs. tit. 6-B, § 1606 (2017) (dcmr_title6b_1606.pdf) +Opinion No. 1904, PERB Case No. 25-A-09 (D.C. Pub. Emp. Rels. Bd. Nov. 6, 2025) (perb_decision_braddock.pdf) +D.C. Code § 1-605.02 (2016) (dc_code_1-605.02.pdf) +W.R. Grace & Co. v. Local Union 759, 461 U.S. 757 (1983) (wr_grace_v_rubber_workers.pdf) +United Paperworkers Int’l Union v. Misco, Inc., 484 U.S. 29 (1987) (paperworkers_v_misco.pdf) +Memorandum from Marcus T. Bell, Labor Relations Liaison, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Outside Counsel, PERB Case No. 25-A-09 (Braddock), re: Supplemental Comparator Case Identified After Close of Arbitration Record (Feb. 24, 2026) (supplemental_comparator_disclosure.pdf) +Fraternal Ord. of Police/Dep’t of Corr. Lab. Comm. v. D.C. Pub. Emp. Rels. Bd., 973 A.2d 174 (D.C. 2009) (fop_doc_labor_comm_v_perb_2009.pdf) + +The documents listed above constitute the complete and exclusive universe of materials for this Step. Limit your review to the attached documents. Do not rely on, reference, or infer any legal authority, factual information, or data beyond what is contained in these uploaded files. If a document is not uploaded, it does not exist for purposes of this analysis. All citations must reference the document by its exact name as listed above, followed by the page and paragraph number. Do not cite external websites, databases, or any source outside the uploaded materials. + +Complete the following: + +1. Assess how the supplemental comparator changes the following analysis developed earlier in this matter: whether the arbitrator stayed within the required scope of review on Douglas factors six and twelve when he demanded that MPD "prove" comparability and found that a suspension would "likely" have deterred future misconduct; which party bore the burden on the comparator evidence; the consequence of Braddock's failure to raise disparate treatment before the arbitration hearing; and MPD's best arguments under the contrary-to-law and public-policy exceptions in D.C. Code sec. 1-605.02(6). State which of MPD's contrary-to-law arguments survive unchanged, which are weakened, and whether the public policy argument is affected at all. State whether the arbitrator's factor six finding looks stronger or weaker in light of the new comparator, whether the burden and preservation positions described above still hold, and whether the supplemental comparator can even be considered on a petition for review given that it sits outside the arbitration record. Support every point with page and paragraph citations. diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/solution/solve.sh b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7710414a6da6d0ad740717c8c85a9af850d5da33 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/solution/solve.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# No oracle solution ships with LegalReasonBench. The verifier grades the +# agent's own legal deliverable for this assignment against the rubric. +echo "no oracle solution" diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/fixtures/config.json b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/fixtures/config.json new file mode 100644 index 0000000000000000000000000000000000000000..46338e447506a3d17d8ace528662185912c4e8a9 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/fixtures/config.json @@ -0,0 +1,154 @@ +{ + "task_id": "lrb-dcca-challenge-police-discipline", + "title": "Viability of a DCCA Challenge", + "domain": "Litigation", + "matter": "MPD v. PERB", + "judge": { + "max_concurrent_llm": 12, + "mode": "panel", + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ], + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + "step_index": 4, + "step_name": "assignment-4", + "step_title": "Supplemental Comparator Disclosure", + "prompt": "Our firm represents the District of Columbia Metropolitan Police Department (\"MPD\") in connection with an arbitration award that reduced Officer Colin Braddock\u2019s termination for excessive force to a 45-day suspension based solely on the arbitrator\u2019s findings regarding Douglas factors six and twelve. The D.C. Public Employee Relations Board (\"PERB\") affirmed the award, and the firm has been developing arguments for a petition to the District of Columbia Court of Appeals (\"DCCA\") under the contrary-to-law and public-policy exceptions in D.C. Code sec. 1-605.02(6). MPD\u2019s labor liaison has now disclosed a fifth comparator case that was not part of the arbitration record.\n\nTreat the following as true for all purposes in this matter, whether or not separately memorialized in the record: (a) reasonable minds can disagree as to how comparable the four comparator cases are to Braddock\u2019s case; (b) at no point before the arbitration hearing did Braddock or his union allege that MPD treated similarly situated employees differently; and (c) Braddock knew that MPD intended to rely on the four comparator cases before MPD found him guilty of the excessive force charge.\n\nThe following documents have been uploaded for this Step:\n\nD.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117 (May 22, 2024) (final_notice_adverse_action_braddock.pdf)\nIn re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)\nMemorandum from Yolanda Britt, Director, Disciplinary Review Division, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Sandra M. Delgado, Assistant Chief, Professional Development Bureau, re: Comparator Discipline Cases, Adverse Action Case No. IS-23-002841 (Braddock) (Apr. 11, 2024) (comparator_discipline_cases.pdf)\nDouglas v. Veterans Administration, 5 M.S.P.R. 280 (1981) (douglas_v_veterans_admin.pdf)\nD.C. Mun. Regs. tit. 6-B, \u00a7 1606 (2017) (dcmr_title6b_1606.pdf)\nOpinion No. 1904, PERB Case No. 25-A-09 (D.C. Pub. Emp. Rels. Bd. Nov. 6, 2025) (perb_decision_braddock.pdf)\nD.C. Code \u00a7 1-605.02 (2016) (dc_code_1-605.02.pdf)\nW.R. Grace & Co. v. Local Union 759, 461 U.S. 757 (1983) (wr_grace_v_rubber_workers.pdf)\nUnited Paperworkers Int\u2019l Union v. Misco, Inc., 484 U.S. 29 (1987) (paperworkers_v_misco.pdf)\nMemorandum from Marcus T. Bell, Labor Relations Liaison, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Outside Counsel, PERB Case No. 25-A-09 (Braddock), re: Supplemental Comparator Case Identified After Close of Arbitration Record (Feb. 24, 2026) (supplemental_comparator_disclosure.pdf)\nFraternal Ord. of Police/Dep\u2019t of Corr. Lab. Comm. v. D.C. Pub. Emp. Rels. Bd., 973 A.2d 174 (D.C. 2009) (fop_doc_labor_comm_v_perb_2009.pdf)\n\nThe documents listed above constitute the complete and exclusive universe of materials for this Step. Limit your review to the attached documents. Do not rely on, reference, or infer any legal authority, factual information, or data beyond what is contained in these uploaded files. If a document is not uploaded, it does not exist for purposes of this analysis. All citations must reference the document by its exact name as listed above, followed by the page and paragraph number. Do not cite external websites, databases, or any source outside the uploaded materials.\n\nComplete the following:\n\n1. Assess how the supplemental comparator changes the following analysis developed earlier in this matter: whether the arbitrator stayed within the required scope of review on Douglas factors six and twelve when he demanded that MPD \"prove\" comparability and found that a suspension would \"likely\" have deterred future misconduct; which party bore the burden on the comparator evidence; the consequence of Braddock's failure to raise disparate treatment before the arbitration hearing; and MPD's best arguments under the contrary-to-law and public-policy exceptions in D.C. Code sec. 1-605.02(6). State which of MPD's contrary-to-law arguments survive unchanged, which are weakened, and whether the public policy argument is affected at all. State whether the arbitrator's factor six finding looks stronger or weaker in light of the new comparator, whether the burden and preservation positions described above still hold, and whether the supplemental comparator can even be considered on a petition for review given that it sits outside the arbitration record. Support every point with page and paragraph citations.", + "attachments": [ + { + "filename": "supplemental_comparator_disclosure.pdf", + "description": "", + "metadata": {}, + "path": "/app/attachments/supplemental_comparator_disclosure.pdf" + } + ], + "rubric": [ + { + "name": "criterion_1", + "description": "Mentions that the Kucera comparator described in the Supplemental Comparator Disclosure from MPD Labor Liaison involved an off-duty discharge at an unarmed person suspected of a property offense that resulted in a 40-day suspension rather than termination.", + "source": "Memorandum from Marcus T. Bell, Labor Relations Liaison, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Outside Counsel, PERB Case No. 25-A-09 (Braddock), re: Supplemental Comparator Case Identified After Close of Arbitration Record, \u00b6\u00b6 2-3 (Feb. 24, 2026) (supplemental_comparator_disclosure.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cassess how the supplemental comparator changes the following analysis developed earlier in this matter.\u201d", + "metadata": { + "irac_section": "Application" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_2", + "description": "States that the Kucera comparator described in the Supplemental Comparator Disclosure from MPD Labor Liaison weakens MPD\u2019s position that termination was consistent with discipline imposed on similarly situated members under Douglas factor six.", + "source": "Memorandum from Marcus T. Bell, Labor Relations Liaison, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Outside Counsel, PERB Case No. 25-A-09 (Braddock), re: Supplemental Comparator Case Identified After Close of Arbitration Record, \u00b6\u00b6 2-3 (Feb. 24, 2026) (supplemental_comparator_disclosure.pdf); D.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117, \u00b6 19 (May 22, 2024) (final_notice_adverse_action_braddock.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cState whether the arbitrator\u2019s factor six finding looks stronger or weaker in light of the new comparator.\u201d", + "metadata": { + "irac_section": "Application" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_3", + "description": "Identifies that MPD can distinguish the Kucera case because the discharge caused no injury", + "source": "Memorandum from Marcus T. Bell, Labor Relations Liaison, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Outside Counsel, PERB Case No. 25-A-09 (Braddock), re: Supplemental Comparator Case Identified After Close of Arbitration Record, \u00b6 2 (Feb. 24, 2026) (supplemental_comparator_disclosure.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cState which of MPD\u2019s contrary-to-law arguments survive unchanged, which are weakened.\u201d", + "metadata": { + "irac_section": "Application" + }, + "score": 4.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_4", + "description": "States that objections not first urged before the Board cannot be considered by the DCCA", + "source": "D.C. Code \u00a7 1-605.02(6) (2016) (dc_code_1-605.02.pdf); Fraternal Ord. of Police/Dep't of Corr. Lab. Comm. v. D.C. Pub. Emp. Rels. Bd., 973 A.2d 174 (D.C. 2009) (fop_doc_labor_comm_v_perb_2009.pdf) at pg 5", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cwhether the supplemental comparator can even be considered on a petition for review given that it sits outside the arbitration record.\u201d", + "metadata": { + "irac_section": "Issue" + }, + "score": 16.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_5", + "description": "Mentions that the supplemental comparator document holds each of MPD's arguments.", + "source": "Memorandum from Marcus T. Bell, Labor Relations Liaison, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Outside Counsel, PERB Case No. 25-A-09 (Braddock), re: Supplemental Comparator Case Identified After Close of Arbitration Record, \u00b6\u00b6 2-3 (Feb. 24, 2026) (supplemental_comparator_disclosure.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cState which of MPD\u2019s contrary-to-law arguments survive unchanged, which are weakened, and whether the public policy argument is affected at all.\u201d", + "metadata": { + "irac_section": "Application" + }, + "score": -16.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_6", + "description": "Identifies that MPD can distinguish the Kucera case because the penalty was set by a negotiated settlement", + "source": "Memorandum from Marcus T. Bell, Labor Relations Liaison, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Outside Counsel, PERB Case No. 25-A-09 (Braddock), re: Supplemental Comparator Case Identified After Close of Arbitration Record, \u00b6 3 (Feb. 24, 2026) (supplemental_comparator_disclosure.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cState whether the arbitrator\u2019s factor six finding looks stronger or weaker in light of the new comparator.\u201d", + "metadata": { + "irac_section": "Application" + }, + "score": 16.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_7", + "description": "Mentions that the Kucera case sat outside the record before the arbitrator.", + "source": "Memorandum from Marcus T. Bell, Labor Relations Liaison, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Outside Counsel, PERB Case No. 25-A-09 (Braddock), re: Supplemental Comparator Case Identified After Close of Arbitration Record, \u00b6 4 (Feb. 24, 2026) (supplemental_comparator_disclosure.pdf); In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 1 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cwhether the supplemental comparator can even be considered on a petition for review given that it sits outside the arbitration record.\u201d", + "metadata": { + "irac_section": "Issue" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_8", + "description": "Identifies that the Supplemental Disclosure misdates the comparator memorandum it references.", + "source": "Memorandum from Marcus T. Bell, Labor Relations Liaison, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Outside Counsel, PERB Case No. 25-A-09 (Braddock), re: Supplemental Comparator Case Identified After Close of Arbitration Record, \u00b6 1 (Feb. 24, 2026) (supplemental_comparator_disclosure.pdf); Memorandum from Yolanda Britt, Director, Disciplinary Review Division, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Sandra M. Delgado, Assistant Chief, Professional Development Bureau, re: Comparator Discipline Cases, Adverse Action Case No. IS-23-002841 (Braddock) (Apr. 11, 2024) (comparator_discipline_cases.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cSupport every point with page and paragraph citations.\u201d", + "metadata": {}, + "score": 28.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_9", + "description": "States that the public policy argument is unaffected by the supplemental comparator because it does not depend on comparator evidence.", + "source": "Memorandum from Marcus T. Bell, Labor Relations Liaison, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Outside Counsel, PERB Case No. 25-A-09 (Braddock), re: Supplemental Comparator Case Identified After Close of Arbitration Record, \u00b6\u00b6 2-3 (Feb. 24, 2026) (supplemental_comparator_disclosure.pdf); W.R. Grace & Co. v. Local Union 759, 461 U.S. 757, 766 (1983) (wr_grace_v_rubber_workers.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"State which of MPD's contrary-to-law arguments survive unchanged, which are weakened, and whether the public policy argument is affected at all.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + } + ], + "answer_path": "/app/response4.md", + "answer_relative_path": "response4.md", + "is_followon": true, + "prev_answer_path": "/app/response3.md" +} diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/fixtures/rubric.json b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/fixtures/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..5e4c5d3feabb371fff882095d2cda4aaa8f7d2e3 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/fixtures/rubric.json @@ -0,0 +1,110 @@ +{ + "criteria": [ + { + "name": "criterion_1", + "description": "Mentions that the Kucera comparator described in the Supplemental Comparator Disclosure from MPD Labor Liaison involved an off-duty discharge at an unarmed person suspected of a property offense that resulted in a 40-day suspension rather than termination.", + "source": "Memorandum from Marcus T. Bell, Labor Relations Liaison, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Outside Counsel, PERB Case No. 25-A-09 (Braddock), re: Supplemental Comparator Case Identified After Close of Arbitration Record, \u00b6\u00b6 2-3 (Feb. 24, 2026) (supplemental_comparator_disclosure.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cassess how the supplemental comparator changes the following analysis developed earlier in this matter.\u201d", + "metadata": { + "irac_section": "Application" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_2", + "description": "States that the Kucera comparator described in the Supplemental Comparator Disclosure from MPD Labor Liaison weakens MPD\u2019s position that termination was consistent with discipline imposed on similarly situated members under Douglas factor six.", + "source": "Memorandum from Marcus T. Bell, Labor Relations Liaison, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Outside Counsel, PERB Case No. 25-A-09 (Braddock), re: Supplemental Comparator Case Identified After Close of Arbitration Record, \u00b6\u00b6 2-3 (Feb. 24, 2026) (supplemental_comparator_disclosure.pdf); D.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117, \u00b6 19 (May 22, 2024) (final_notice_adverse_action_braddock.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cState whether the arbitrator\u2019s factor six finding looks stronger or weaker in light of the new comparator.\u201d", + "metadata": { + "irac_section": "Application" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_3", + "description": "Identifies that MPD can distinguish the Kucera case because the discharge caused no injury", + "source": "Memorandum from Marcus T. Bell, Labor Relations Liaison, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Outside Counsel, PERB Case No. 25-A-09 (Braddock), re: Supplemental Comparator Case Identified After Close of Arbitration Record, \u00b6 2 (Feb. 24, 2026) (supplemental_comparator_disclosure.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cState which of MPD\u2019s contrary-to-law arguments survive unchanged, which are weakened.\u201d", + "metadata": { + "irac_section": "Application" + }, + "score": 4.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_4", + "description": "States that objections not first urged before the Board cannot be considered by the DCCA", + "source": "D.C. Code \u00a7 1-605.02(6) (2016) (dc_code_1-605.02.pdf); Fraternal Ord. of Police/Dep't of Corr. Lab. Comm. v. D.C. Pub. Emp. Rels. Bd., 973 A.2d 174 (D.C. 2009) (fop_doc_labor_comm_v_perb_2009.pdf) at pg 5", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cwhether the supplemental comparator can even be considered on a petition for review given that it sits outside the arbitration record.\u201d", + "metadata": { + "irac_section": "Issue" + }, + "score": 16.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_5", + "description": "Mentions that the supplemental comparator document holds each of MPD's arguments.", + "source": "Memorandum from Marcus T. Bell, Labor Relations Liaison, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Outside Counsel, PERB Case No. 25-A-09 (Braddock), re: Supplemental Comparator Case Identified After Close of Arbitration Record, \u00b6\u00b6 2-3 (Feb. 24, 2026) (supplemental_comparator_disclosure.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cState which of MPD\u2019s contrary-to-law arguments survive unchanged, which are weakened, and whether the public policy argument is affected at all.\u201d", + "metadata": { + "irac_section": "Application" + }, + "score": -16.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_6", + "description": "Identifies that MPD can distinguish the Kucera case because the penalty was set by a negotiated settlement", + "source": "Memorandum from Marcus T. Bell, Labor Relations Liaison, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Outside Counsel, PERB Case No. 25-A-09 (Braddock), re: Supplemental Comparator Case Identified After Close of Arbitration Record, \u00b6 3 (Feb. 24, 2026) (supplemental_comparator_disclosure.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cState whether the arbitrator\u2019s factor six finding looks stronger or weaker in light of the new comparator.\u201d", + "metadata": { + "irac_section": "Application" + }, + "score": 16.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_7", + "description": "Mentions that the Kucera case sat outside the record before the arbitrator.", + "source": "Memorandum from Marcus T. Bell, Labor Relations Liaison, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Outside Counsel, PERB Case No. 25-A-09 (Braddock), re: Supplemental Comparator Case Identified After Close of Arbitration Record, \u00b6 4 (Feb. 24, 2026) (supplemental_comparator_disclosure.pdf); In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 1 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cwhether the supplemental comparator can even be considered on a petition for review given that it sits outside the arbitration record.\u201d", + "metadata": { + "irac_section": "Issue" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_8", + "description": "Identifies that the Supplemental Disclosure misdates the comparator memorandum it references.", + "source": "Memorandum from Marcus T. Bell, Labor Relations Liaison, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Outside Counsel, PERB Case No. 25-A-09 (Braddock), re: Supplemental Comparator Case Identified After Close of Arbitration Record, \u00b6 1 (Feb. 24, 2026) (supplemental_comparator_disclosure.pdf); Memorandum from Yolanda Britt, Director, Disciplinary Review Division, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Sandra M. Delgado, Assistant Chief, Professional Development Bureau, re: Comparator Discipline Cases, Adverse Action Case No. IS-23-002841 (Braddock) (Apr. 11, 2024) (comparator_discipline_cases.pdf)", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cSupport every point with page and paragraph citations.\u201d", + "metadata": {}, + "score": 28.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_9", + "description": "States that the public policy argument is unaffected by the supplemental comparator because it does not depend on comparator evidence.", + "source": "Memorandum from Marcus T. Bell, Labor Relations Liaison, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Outside Counsel, PERB Case No. 25-A-09 (Braddock), re: Supplemental Comparator Case Identified After Close of Arbitration Record, \u00b6\u00b6 2-3 (Feb. 24, 2026) (supplemental_comparator_disclosure.pdf); W.R. Grace & Co. v. Local Union 759, 461 U.S. 757, 766 (1983) (wr_grace_v_rubber_workers.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"State which of MPD's contrary-to-law arguments survive unchanged, which are weakened, and whether the public policy argument is affected at all.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + } + ] +} diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/m1_judge_panel.json b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/m1_judge_panel.json new file mode 100644 index 0000000000000000000000000000000000000000..a8041f6781a899f9083fe4a1a95f51bc78d35601 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/m1_judge_panel.json @@ -0,0 +1,21 @@ +{ + "mode": "panel", + "max_concurrent_llm": 12, + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ] +} diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/m1_rewardkit_accounting.py b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/m1_rewardkit_accounting.py new file mode 100644 index 0000000000000000000000000000000000000000..406dc5e7c675b222d94514e71bf5fad6ae141d8f --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/m1_rewardkit_accounting.py @@ -0,0 +1,490 @@ +import asyncio +import json +import math +import os +from pathlib import Path +import random +import sys +import time + +class JudgeReceiptError(OSError): + pass +_LLM_ROUTES = frozenset({'vertex', 'anthropic fallback', 'aistudio', 'direct'}) +_LLM_ROUTE_HEADERS = ('x-m1-llm-route', 'llm_provider-x-m1-llm-route') + +def _canonical_llm_route(value): + return value if isinstance(value, str) and value in _LLM_ROUTES else None + +def _llm_route_from_headers(headers): + if not isinstance(headers, dict): + return None + folded = {str(key).lower(): value for key, value in headers.items()} + for name in _LLM_ROUTE_HEADERS: + route = _canonical_llm_route(folded.get(name)) + if route is not None: + return route + return None + +def _llm_route_from_response(response): + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + route = _llm_route_from_headers(headers) + if route is not None: + return route + return _llm_route_from_headers(getattr(response, 'headers', None)) + +def _token_field_status(values, key): + if not isinstance(values, dict) or key not in values: + return 'missing' + value = values[key] + if value is None: + return 'null' + return 'valid' if type(value) is int and value >= 0 else 'invalid' + +def _gemini_capture(kwargs, model): + if not model.startswith('gemini/') or kwargs.get('stream') or kwargs.get('tools') or kwargs.get('functions'): + return (kwargs, None) + from litellm.integrations.custom_logger import CustomLogger + from urllib.parse import urlsplit + + class Capture(CustomLogger): + evidence = None + prompt_status = 'not_observed' + llm_route = None + + def log_post_api_call(self, kwargs, response_obj, start_time, end_time): + self.evidence = None + self.prompt_status = 'not_observed' + try: + params = kwargs.get('litellm_params') or {} + route = urlsplit(params.get('api_base') or '') + bare = model.removeprefix('gemini/') + gemini = params.get('custom_llm_provider') == 'gemini' + ai_studio = gemini and route.hostname == 'generativelanguage.googleapis.com' and (route.path in {'/' + version + '/models/' + bare + ':generateContent' for version in ('v1alpha', 'v1beta')}) + broker = urlsplit(os.environ.get('GEMINI_API_BASE') or '') + brokered = gemini and bool(broker.netloc) and (route.netloc == broker.netloc) and (broker.path.rstrip('/').rsplit('/', 1)[-1] in ('v1alpha', 'v1beta')) and (route.path == broker.path.rstrip('/') + '/models/' + bare + ':generateContent') + vertex = params.get('custom_llm_provider') == 'vertex_ai' and route.hostname == 'aiplatform.googleapis.com' and route.path.startswith('/v1/projects/') and route.path.endswith('/locations/global/publishers/google/models/' + bare + ':generateContent') + if route.scheme != 'https' or not (ai_studio or brokered or vertex) or kwargs.get('stream'): + return + self.llm_route = 'vertex' if vertex else 'aistudio' if ai_studio else None + raw = kwargs.get('original_response') + raw = json.loads(raw) if isinstance(raw, str) else raw + if not isinstance(raw, dict): + return + candidates = raw.get('candidates') + if not isinstance(candidates, list) or not candidates or any((not isinstance(c, dict) or not c.get('finishReason') for c in candidates)) or (not isinstance(raw.get('modelVersion'), str)) or (not raw['modelVersion']): + return + usage = raw.get('usageMetadata') + self.prompt_status = _token_field_status(usage, 'promptTokenCount') + if not isinstance(usage, dict): + return + fields = ('promptTokenCount', 'candidatesTokenCount', 'thoughtsTokenCount', 'cachedContentTokenCount', 'totalTokenCount', 'toolUsePromptTokenCount') + counts = {key: usage.get(key, 0) for key in fields} + if not {'promptTokenCount', 'totalTokenCount'} <= usage.keys() or any((type(n) is not int or n < 0 for n in counts.values())) or counts['toolUsePromptTokenCount'] != 0 or (counts['cachedContentTokenCount'] > counts['promptTokenCount']) or (counts['totalTokenCount'] != counts['promptTokenCount'] + counts['candidatesTokenCount'] + counts['thoughtsTokenCount']): + return + self.evidence = {'protocol': 'gemini-generate-content-' + ('vertex-v1' if vertex else route.path.split('/')[-3]), 'model_version': raw['modelVersion'], 'usage_metadata': {key: usage[key] for key in fields if key in usage}, 'defaulted_fields': [key for key in fields if key not in usage]} + except (TypeError, ValueError, AttributeError): + return + capture = Capture() + return ({**kwargs, 'callbacks': [*(kwargs.get('callbacks') or []), capture]}, capture) + +def _record_judge_usage(response, model: str, *, target: Path | None=None, native_usage: dict | None=None, native_prompt_status: str | None=None, llm_route: str | None=None) -> None: + import fcntl + from datetime import datetime, timezone + data = response.model_dump() if hasattr(response, 'model_dump') else response + usage = data.get('usage') if isinstance(data, dict) else None + granularity = data.get('usage_granularity') if isinstance(data, dict) else None + if not isinstance(usage, dict): + usage = {} + granularity = 'missing_provider_receipt' + prompt, completion = (usage.get('prompt_tokens'), usage.get('completion_tokens')) + native_fresh = usage.get('input_uncached_tokens') + prompt = prompt if type(prompt) is int and prompt >= 0 else None + native_fresh = native_fresh if type(native_fresh) is int and native_fresh >= 0 else None + if type(completion) is not int or completion < 0 or (prompt is None and native_fresh is None): + completion = completion if type(completion) is int and completion >= 0 else 0 + granularity = granularity or 'invalid_provider_receipt' + details = usage.get('prompt_tokens_details') + if details is not None and (not isinstance(details, dict)): + granularity = 'invalid_provider_receipt' + details = details if isinstance(details, dict) else {} + cached = details.get('cached_tokens') + if native_usage is not None: + native = native_usage['usage_metadata'] + native_output = native.get('candidatesTokenCount', 0) + native.get('thoughtsTokenCount', 0) + if prompt == native['promptTokenCount'] and completion == native_output: + cached = native.get('cachedContentTokenCount', 0) + else: + native_usage = None + written = next((value for value in (usage.get('input_cache_write_tokens'), usage.get('cache_creation_input_tokens'), details.get('cache_creation_tokens'), details.get('cache_write_tokens')) if value is not None), None) + invalid = any((value is not None and (type(value) is not int or value < 0) for value in (cached, written))) + cached = cached if type(cached) is int and cached >= 0 else None + written = written if type(written) is int and written >= 0 else None + fresh = native_fresh + if fresh is None and prompt is not None and (cached is not None) and (written is not None): + fresh = prompt - cached - written + if fresh is not None and (fresh < 0 or (prompt is not None and cached is not None and (written is not None) and (fresh + cached + written != prompt))): + invalid, fresh = (True, None) + provider, _, slug = model.partition('/') + event: dict = {'type': 'step_finish', 'part': {'providerID': provider if slug else 'openai', 'modelID': slug or model, 'tokens': {'input': fresh, 'output': completion, 'cache': {'read': cached, 'write': written}}}} + field_status = {'prompt_tokens': _token_field_status(usage, 'prompt_tokens'), 'completion_tokens': _token_field_status(usage, 'completion_tokens'), 'input_uncached_tokens': _token_field_status(usage, 'input_uncached_tokens')} + field_status['native_prompt_token_count'] = native_prompt_status if native_prompt_status in {'missing', 'null', 'invalid', 'valid', 'not_observed'} else 'unsupported' + part: dict = event['part'] + part['usage_field_status'] = field_status + if native_usage is not None: + event['part']['native_usage'] = native_usage + event['part']['token_categories_provenance'] = 'explicit_presence_v1' + if fresh is None and prompt is not None: + event['part']['prompt_tokens_inclusive'] = prompt + if invalid or any((value is None for value in (fresh, cached, written))): + granularity = granularity if granularity not in (None, 'request') else 'invalid_provider_receipt' if invalid else 'incomplete_token_categories' + if granularity: + event['part']['usage_granularity'] = granularity + if provider == 'openrouter': + cost = usage.get('cost') + if cost is None: + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + if isinstance(headers, dict): + cost = headers.get('llm_provider-x-litellm-response-cost') + if isinstance(cost, (int, float)) and (not isinstance(cost, bool)) and math.isfinite(cost) and (cost >= 0): + event['part']['cost'] = cost + data = data if isinstance(data, dict) else {} + if isinstance(data.get('id'), str) and data['id']: + event['part']['provider_request_id'] = data['id'] + for key in ('service_tier', 'cache_ttl'): + if data.get(key): + event['part'][key] = data[key] + route = _llm_route_from_response(response) or _canonical_llm_route(llm_route) + if route is not None: + event['part']['llm_route'] = route + created = data.get('created') + stamp = datetime.now(timezone.utc) + try: + if isinstance(created, str): + parsed = datetime.fromisoformat(created.replace('Z', '+00:00')) + if parsed.tzinfo is not None: + stamp = parsed + elif isinstance(created, (int, float)) and (not isinstance(created, bool)) and math.isfinite(created): + stamp = datetime.fromtimestamp(created, timezone.utc) + except (ValueError, OverflowError, OSError): + pass + pair = json.dumps({'type': 'step_start', 'timestamp': stamp.isoformat()}) + '\n' + pair += json.dumps(event) + '\n' + try: + receipt_path = target or Path(os.environ.get('M1_JUDGE_USAGE_PATH', '/logs/verifier/judge-trajectory.jsonl')) + receipt_path.parent.mkdir(parents=True, exist_ok=True) + with receipt_path.open('a') as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + handle.write(pair) + handle.flush() + os.fsync(handle.fileno()) + except OSError as exc: + if target is not None: + raise JudgeReceiptError(f'judge receipt write failed: {exc}') from exc + print(f'judge accounting: write failed ({type(exc).__name__})', file=sys.stderr) + +def openrouter_judge_pins() -> dict[str, dict]: + raw = os.environ.get('M1_OPENROUTER_JUDGE_PROVIDER_PINS', '').strip() + if not raw: + return {} + try: + pins = json.loads(raw) + except json.JSONDecodeError: + print('judge provider pins: invalid JSON in M1_OPENROUTER_JUDGE_PROVIDER_PINS', file=sys.stderr) + return {} + return {model: pin for model, pin in pins.items() if isinstance(pin, dict) and pin.get('order')} if isinstance(pins, dict) else {} + +def apply_judge_provider_pin(kwargs: dict, pins: dict[str, dict]) -> dict: + model = kwargs.get('model') + pin = pins.get(model) if isinstance(model, str) else None + if pin is None: + return kwargs + extra_body = dict(kwargs.get('extra_body') or {}) + provider = dict(extra_body.get('provider') or {}) + provider['order'] = list(pin['order']) + if pin.get('allow_fallbacks') is False: + provider['allow_fallbacks'] = False + if pin.get('zdr'): + provider['zdr'] = True + extra_body['provider'] = provider + return {**kwargs, 'extra_body': extra_body} +_TRANSIENT_ERROR_NAMES = ('RateLimitError', 'ServiceUnavailableError', 'InternalServerError', 'BadGatewayError', 'APIConnectionError') +_RETRYABLE_STATUS_CODES = frozenset({408, 409, 425, 429, 500, 502, 503, 504}) +_AUTH_ERROR_NAMES = ('AuthenticationError', 'PermissionDeniedError') +_AUTH_STATUS_CODES = frozenset({401, 403}) +_AUTH_RETRIES = 4 +_DEFAULT_TRANSIENT_RETRIES = 6 +_MAX_TRANSIENT_RETRIES = 20 +_MAX_RETRY_DELAY_SECONDS = 60.0 +_DEFAULT_EMPTY_RESPONSE_RETRIES = 3 +_DEFAULT_RETRY_BUDGET_SECONDS = 900.0 +_MAX_RETRY_BUDGET_SECONDS = 86400.0 + +def transient_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_TRANSIENT_RETRIES', '').strip() + if not raw: + return _DEFAULT_TRANSIENT_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_TRANSIENT_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_TRANSIENT_RETRIES + +def empty_response_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_EMPTY_RESPONSE_RETRIES', '').strip() + if not raw: + return _DEFAULT_EMPTY_RESPONSE_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_EMPTY_RESPONSE_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_EMPTY_RESPONSE_RETRIES + +def retry_budget_seconds() -> float: + raw = os.environ.get('M1_JUDGE_RETRY_BUDGET_SECONDS', '').strip() + if not raw: + return _DEFAULT_RETRY_BUDGET_SECONDS + try: + value = float(raw) + except ValueError: + value = math.nan + if not math.isfinite(value) or value < 0: + print('judge retries: invalid M1_JUDGE_RETRY_BUDGET_SECONDS, using the default', file=sys.stderr) + return _DEFAULT_RETRY_BUDGET_SECONDS + return min(value, _MAX_RETRY_BUDGET_SECONDS) + +def _within_budget(deadline: float, delay: float, model) -> bool: + remaining = deadline - time.monotonic() + if delay <= remaining: + return True + print(f'judge call retry budget spent: {model} would wait {delay:.1f}s with {max(remaining, 0.0):.1f}s left of M1_JUDGE_RETRY_BUDGET_SECONDS, failing now', file=sys.stderr) + return False + +def is_empty_verdict(response) -> bool: + data = response.model_dump() if hasattr(response, 'model_dump') else response + if not isinstance(data, dict): + return False + choices = data.get('choices') + if not isinstance(choices, list) or not choices: + return True + first = choices[0] + message = first.get('message') if isinstance(first, dict) else None + if not isinstance(message, dict): + return True + if message.get('tool_calls') or message.get('function_call'): + return False + content = message.get('content') + if isinstance(content, list): + content = ''.join((part.get('text') or '' for part in content if isinstance(part, dict))) + return not (isinstance(content, str) and content.strip()) + +def _matches(exc: BaseException, litellm, names: tuple[str, ...], statuses: frozenset[int]) -> bool: + classes = tuple((cls for cls in (getattr(litellm, name, None) for name in names) if isinstance(cls, type))) + if classes and isinstance(exc, classes): + return True + status = getattr(exc, 'status_code', None) + return type(status) is int and status in statuses + +def is_transient_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _TRANSIENT_ERROR_NAMES, _RETRYABLE_STATUS_CODES) + +def is_auth_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _AUTH_ERROR_NAMES, _AUTH_STATUS_CODES) + +def should_retry(exc: BaseException, litellm, attempt: int, limit: int) -> bool: + if attempt < limit and is_transient_error(exc, litellm): + return True + return attempt < min(limit, _AUTH_RETRIES) and is_auth_error(exc, litellm) + +def _retry_after_seconds(exc: BaseException) -> float | None: + headers = getattr(exc, 'headers', None) + if headers is None: + headers = getattr(getattr(exc, 'response', None), 'headers', None) + if headers is None: + return None + try: + raw = headers.get('retry-after') + if raw is None: + raw = headers.get('Retry-After') + value = float(raw) + except (AttributeError, TypeError, ValueError): + return None + return value if math.isfinite(value) and value >= 0 else None + +def retry_delay(exc: BaseException | None, attempt: int) -> float: + base = min(_MAX_RETRY_DELAY_SECONDS, 2.0 ** (attempt + 1)) + delay = base * (0.5 + random.random()) + retry_after = _retry_after_seconds(exc) if exc is not None else None + if retry_after is not None: + delay = max(delay, min(_MAX_RETRY_DELAY_SECONDS, retry_after)) + return delay + +def _note_retry(model, exc: BaseException, attempt: int, limit: int, delay: float) -> None: + status = getattr(exc, 'status_code', None) + print(f"judge call retry {attempt}/{limit}: {model} {type(exc).__name__} status={(status if type(status) is int else 'n/a')}, waiting {delay:.1f}s", file=sys.stderr) + +def _note_empty(model, response, attempt: int, limit: int, delay: float) -> None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + reason = None + if isinstance(data, dict) and isinstance(data.get('choices'), list) and data['choices']: + first = data['choices'][0] + reason = first.get('finish_reason') if isinstance(first, dict) else None + print(f'judge call retry {attempt}/{limit}: {model} empty verdict (finish_reason={reason}), waiting {delay:.1f}s', file=sys.stderr) + +def install(litellm, *, synchronous: bool=False) -> None: + pins = openrouter_judge_pins() + limit = transient_retry_limit() + empty_limit = empty_response_retry_limit() + deadline = time.monotonic() + retry_budget_seconds() + if synchronous: + original = litellm.completion + + def accounted(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = original(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + time.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + time.sleep(delay) + continue + return response + litellm.completion = accounted + return + original_async = litellm.acompletion + + async def accounted_async(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = await original_async(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + await asyncio.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + await asyncio.sleep(delay) + continue + return response + litellm.acompletion = accounted_async + +def record_agent_usage(attempt, *, model: str, provider: str) -> None: + records: dict[str, tuple[str, dict]] = {} + current_model = model + for filename in getattr(attempt, 'logs', []): + try: + with Path(filename).open() as stream: + for line in stream: + try: + event = json.loads(line) + except (ValueError, TypeError): + continue + if not isinstance(event, dict): + continue + message = event.get('message') or {} + if event.get('type') == 'assistant' and isinstance(message, dict) and isinstance(message.get('usage'), dict): + raw = message['usage'] + cached, written = (raw.get('cache_read_input_tokens'), raw.get('cache_creation_input_tokens')) + if all((type(value) is int and value >= 0 for value in (raw.get('input_tokens'), raw.get('output_tokens')))) and all((value is None or (type(value) is int and value >= 0) for value in (cached, written))): + receipt: dict = {'usage': {'input_uncached_tokens': raw['input_tokens'], 'prompt_tokens': raw['input_tokens'] + cached + written if cached is not None and written is not None else None, 'completion_tokens': raw['output_tokens'], 'prompt_tokens_details': {'cached_tokens': cached, 'cache_creation_tokens': written}}} + receipt['created'] = event.get('timestamp') + creation = raw.get('cache_creation') or {} + hour = creation.get('ephemeral_1h_input_tokens', 0) if isinstance(creation, dict) else 0 + if type(hour) is int and hour > 0: + if hour == written: + receipt['cache_ttl'] = '1h' + else: + receipt['usage_granularity'] = 'mixed_cache_ttl' + records[message.get('id') or json.dumps(raw, sort_keys=True)] = (message.get('model') or current_model, receipt) + payload = event.get('payload') or {} + if not isinstance(payload, dict): + continue + if event.get('type') == 'turn_context' and payload.get('model'): + current_model = payload['model'] + if event.get('type') == 'event_msg' and payload.get('type') == 'token_count': + info = payload.get('info') or {} + raw, total = (info.get('last_token_usage'), info.get('total_token_usage')) + if isinstance(raw, dict) and isinstance(total, dict) and all((type(raw.get(key)) is int and raw.get(key) >= 0 for key in ('input_tokens', 'output_tokens'))): + receipt = {'usage': {'prompt_tokens': raw.get('input_tokens'), 'input_uncached_tokens': raw.get('input_uncached_tokens'), 'input_cache_write_tokens': raw.get('input_cache_write_tokens'), 'completion_tokens': raw.get('output_tokens'), 'prompt_tokens_details': {'cached_tokens': raw.get('cached_input_tokens')}}} + receipt['created'] = event.get('timestamp') + records[json.dumps(total, sort_keys=True)] = (current_model, receipt) + except OSError: + continue + captured_input = captured_output = 0 + input_complete = True + for requested, receipt in records.values(): + requested = requested if '/' in requested else f'{provider}/{requested}' + _record_judge_usage(receipt, requested) + receipt_input = receipt['usage'].get('prompt_tokens') + if receipt_input is None: + input_complete = False + else: + captured_input += receipt_input + captured_output += receipt['usage'].get('completion_tokens') or 0 + total = getattr(attempt, 'usage', {}) or {} + if not records or (input_complete and total.get('input_tokens') != captured_input) or total.get('output_tokens') != captured_output: + _record_judge_usage({'usage': {'prompt_tokens': 0, 'completion_tokens': 0}, 'usage_granularity': 'incomplete_agent_receipts'}, model if '/' in model else f'{provider}/{model}') + +def install_rewardkit_agents() -> None: + import rewardkit.judges as judges + original = judges.get_agent + + def get_accounted_agent(judge, cwd=None): + backend = original(judge, cwd) + run = backend.run + + async def accounted_run(*args, **kwargs): + attempt = await run(*args, **kwargs) + record_agent_usage(attempt, model=judge.model or 'unknown', provider='anthropic' if judge.agent == 'claude-code' else 'openai') + return attempt + setattr(backend, 'run', accounted_run) + return backend + setattr(judges, 'get_agent', get_accounted_agent) +if __name__ == '__main__': + import litellm + if len(sys.argv) > 2 and sys.argv[1] == '--script': + import runpy + install(litellm, synchronous=True) + sys.argv = sys.argv[2:] + runpy.run_path(sys.argv[0], run_name='__main__') + else: + install(litellm) + install_rewardkit_agents() + if Path(__file__).with_name('m1_judge_panel.json').is_file(): + from m1_rewardkit_panel import install_panel + install_panel(Path(__file__).with_name('m1_judge_panel.json')) + if Path(__file__).with_name('m1_judge_jev.json').is_file(): + from m1_rewardkit_jev import install_jev + install_jev(Path(__file__).with_name('m1_judge_jev.json')) + from rewardkit.__main__ import main + main() diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/m1_rewardkit_panel.py b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/m1_rewardkit_panel.py new file mode 100644 index 0000000000000000000000000000000000000000..164cc2ae521cdd368c2e1749d7ed8fe09f4545eb --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/m1_rewardkit_panel.py @@ -0,0 +1,169 @@ +from __future__ import annotations +import asyncio +from contextvars import ContextVar +import json +import math +import os +import sys +from pathlib import Path +from typing import Any +import uuid +_request_audit: ContextVar[tuple[Path, list[str]] | None] = ContextVar('panel_request_audit', default=None) + +class PanelIncompleteError(RuntimeError): + pass + +def _audit_warning(exc: Exception, warnings: list[str]) -> None: + message = f'judge panel audit: diagnostic capture failed ({type(exc).__name__})' + if message not in warnings: + warnings.append(message) + print(message, file=sys.stderr) + +def _write_audit(path: Path, record: dict[str, Any], warnings: list[str], *, append: bool=False) -> None: + try: + text = json.dumps(record, allow_nan=False, default=str) + '\n' + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('a' if append else 'w') as stream: + stream.write(text) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + +def _binary(raw: Any) -> int: + if isinstance(raw, bool): + return int(raw) + if isinstance(raw, int | float) and math.isfinite(raw) and (raw in (0, 1)): + return int(raw) + if isinstance(raw, str): + value = raw.strip().lower() + if value in {'yes', 'true', '1'}: + return 1 + if value in {'no', 'false', '0'}: + return 0 + raise PanelIncompleteError('m1_judge_panel_incomplete: invalid binary vote') + +def validate_votes(scores: list[Any], criteria: list[Any]) -> None: + names = [criterion.name for criterion in criteria] + if len(set(names)) != len(names) or [score.name for score in scores] != names: + raise PanelIncompleteError('m1_judge_panel_incomplete: criterion membership mismatch') + for score, criterion in zip(scores, criteria, strict=True): + if score.error: + raise PanelIncompleteError('m1_judge_panel_incomplete: judge returned an error') + raw = _binary(score.raw) + expected = 1 - raw if criterion.negate else raw + if not math.isfinite(score.value) or score.value != expected: + raise PanelIncompleteError('m1_judge_panel_incomplete: inconsistent binary score') + +async def run_panel(judge: Any, criteria: list[Any], weights: list[float] | None, system_prompt: str | None, *, config: dict[str, Any], run_llm: Any, score_type: Any, audit_dir: Path) -> tuple[list[Any], str, list[str]]: + from rewardkit.models import Binary + if not criteria or any((not isinstance(criterion.output_format, Binary) for criterion in criteria)): + raise ValueError('panel majority voting requires nonempty binary criteria') + group_dir = audit_dir / uuid.uuid4().hex + warnings_out: list[str] = [] + + async def member_call(index: int, member: dict[str, Any]): + member_judge = judge.model_copy(update=member) + evidence: dict[str, Any] = {'member': index + 1, 'judge': member, 'criteria': [criterion.name for criterion in criteria], 'status': 'started'} + path = group_dir / f'judge-{index + 1}.json' + _write_audit(path, evidence, warnings_out) + token = _request_audit.set((group_dir / f'judge-{index + 1}-requests.jsonl', warnings_out)) + try: + scores, output, warnings = await run_llm(member_judge, criteria, weights, system_prompt) + evidence.update(output=output, warnings=warnings) + validate_votes(scores, criteria) + evidence['scores'] = [score.to_dict() for score in scores] + evidence['status'] = 'completed' + return (scores, output, warnings) + except BaseException as exc: + evidence.update(status='failed', error_class=type(exc).__name__) + if isinstance(exc, PanelIncompleteError): + evidence['error'] = str(exc) + raise + finally: + _request_audit.reset(token) + _write_audit(path, evidence, warnings_out) + outcomes = await asyncio.gather(*(member_call(index, member) for index, member in enumerate(config['members'])), return_exceptions=True) + failed = [index + 1 for index, result in enumerate(outcomes) if isinstance(result, BaseException)] + if failed: + _write_audit(group_dir / 'panel.json', {'status': 'incomplete', 'failed_members': failed}, warnings_out) + raise PanelIncompleteError(f'm1_judge_panel_incomplete: failed members {failed}; see panel audit artifacts') + completed = [outcome for outcome in outcomes if not isinstance(outcome, BaseException)] + combined = [] + for index, criterion in enumerate(criteria): + votes = [{'judge': config['members'][member_index], **outcome[0][index].to_dict()} for member_index, outcome in enumerate(completed)] + passes = sum((vote['value'] == 1 for vote in votes)) + value = int(passes >= 2) + combined.append(score_type(name=criterion.name, value=value, raw=bool(1 - value if criterion.negate else value), weight=weights[index] if weights is not None else 1.0, reasoning=f'{passes}/3 judges passed; strict majority requires 2/3.', description=criterion.description, id=criterion.id, negate=criterion.negate, optional=criterion.optional, votes=votes)) + for outcome in completed: + warnings_out.extend(outcome[2]) + audit = {'status': 'completed', 'mode': 'panel', 'aggregation': 'majority', 'required_votes': 2, 'members': config['members'], 'criteria': [score.to_dict() for score in combined]} + output = json.dumps(audit, indent=2, allow_nan=False) + _write_audit(group_dir / 'panel.json', audit, warnings_out) + return (combined, output, warnings_out) + +def install_panel(config_path: Path, *, audit_dir: Path=Path('/logs/verifier/judge-panel')) -> None: + import rewardkit.judges as judges + import rewardkit.reward as reward + from rewardkit.models import LLMJudge, Score + import litellm + config = json.loads(config_path.read_text()) + members = config.get('members') + concurrency = config.get('max_concurrent_llm') + if config.get('mode') != 'panel' or not isinstance(members, list) or len(members) != 3 or (len({member['model'] for member in members}) != 3) or (type(concurrency) is not int) or (not 1 <= concurrency <= 64): + raise ValueError('invalid materialized panel configuration') + if os.environ.get('REWARDKIT_JUDGE') or os.environ.get('REWARDKIT_MODEL'): + raise ValueError('RewardKit environment overrides cannot replace a frozen panel') + + class PanelScore(Score): + votes: list[dict[str, Any]] + + def to_dict(self): + return {**super().to_dict(), 'votes': self.votes} + original_llm = judges.arun_llm + original_call = judges._arun_llm_call + original_details = reward.Reward.to_detail_dict + original_completion = litellm.acompletion + active_loop = None + semaphore = None + + async def captured_completion(*args, **kwargs): + context = _request_audit.get() + record = {'requested_model': kwargs.get('model')} + response = None + try: + response = await original_completion(*args, **kwargs) + return response + except BaseException as exc: + record['error_class'] = type(exc).__name__ + raise + finally: + if context is not None: + path, warnings = context + try: + if response is not None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + record.update(response_model=data.get('model'), choices=data.get('choices')) + _write_audit(path, record, warnings, append=True) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + + async def bounded_call(*args, **kwargs): + nonlocal active_loop, semaphore + loop = asyncio.get_running_loop() + if active_loop is not loop: + active_loop, semaphore = (loop, asyncio.Semaphore(concurrency)) + assert semaphore is not None + async with semaphore: + return await original_call(*args, **kwargs) + + async def panel_call(judge, criteria, weights=None, system_prompt=None): + return await run_panel(judge, criteria, weights, system_prompt, config=config, run_llm=original_llm, score_type=PanelScore, audit_dir=audit_dir) + + def panel_details(self, score): + detail = original_details(self, score) + if isinstance(self.judge, LLMJudge): + detail.update(kind='llm_panel', judge=config, aggregation='majority', required_votes=2) + return detail + setattr(reward, 'arun_llm', panel_call) + setattr(judges, '_arun_llm_call', bounded_call) + setattr(litellm, 'acompletion', captured_completion) + reward.Reward.to_detail_dict = panel_details diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/normalize_reward.py b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/normalize_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..91817ef00ea9152ca57f0030d8e879eb850ddff0 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/normalize_reward.py @@ -0,0 +1,71 @@ +from __future__ import annotations +import argparse +import json +from pathlib import Path +from typing import Any + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument('--raw-details', required=True) + parser.add_argument('--rubric', required=True) + parser.add_argument('--reward-out', required=True) + parser.add_argument('--details-out', required=True) + args = parser.parse_args() + raw_details = _load_json(Path(args.raw_details)) + rubric = _load_json(Path(args.rubric)) + criteria = rubric['criteria'] + raw_by_name = _raw_criteria_by_name(raw_details) + positive_total = sum((float(item['score']) for item in criteria if float(item['score']) > 0)) + if positive_total <= 0: + raise ValueError('rubric must contain at least one positive score') + earned = 0.0 + normalized_criteria: list[dict[str, Any]] = [] + for item in criteria: + signed_score = float(item['score']) + raw = raw_by_name.get(item['name'], {}) + value = _coerce_score(raw.get('value', 0.0)) + contribution = value * signed_score + earned += contribution + normalized_criteria.append({'name': item['name'], 'value': value, 'raw': raw.get('raw'), 'weight': signed_score, 'signed_score': signed_score, 'polarity': item['polarity'], 'contribution': contribution, 'description': item['description'], 'source': item.get('source', ''), 'justification': item.get('justification', ''), 'metadata': item.get('metadata', {}), 'reasoning': raw.get('reasoning'), 'judge_reasoning': raw.get('reasoning'), 'judge_error': raw.get('error'), **({'votes': raw['votes']} if 'votes' in raw else {})}) + unclamped = earned / positive_total + reward = max(0.0, min(1.0, unclamped)) + reward_out = {'correctness': reward} + details_out = {'correctness': {'score': reward, 'kind': 'signed_score', 'criteria': normalized_criteria, 'aggregation': {'method': 'signed_score_ratio_clamped', 'earned': earned, 'positive_total': positive_total, 'unclamped': unclamped, 'clamped': reward}, 'raw_rewardkit': raw_details}} + _write_json(Path(args.reward_out), reward_out) + _write_json(Path(args.details_out), details_out) + +def _load_json(path: Path) -> Any: + return json.loads(path.read_text()) + +def _write_json(path: Path, data: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data, indent=2) + '\n') + +def _raw_criteria_by_name(details: dict[str, Any]) -> dict[str, dict[str, Any]]: + out: dict[str, dict[str, Any]] = {} + for reward in details.values(): + for item in _iter_raw_criteria(reward): + name = item.get('name') + if isinstance(name, str): + out[name] = item + return out + +def _iter_raw_criteria(value: Any): + if isinstance(value, list): + for item in value: + yield from _iter_raw_criteria(item) + return + if not isinstance(value, dict): + return + for item in value.get('criteria') or []: + if isinstance(item, dict): + yield item + +def _coerce_score(value: Any) -> float: + if isinstance(value, bool): + return 1.0 if value else 0.0 + if isinstance(value, int | float): + return max(0.0, min(1.0, float(value))) + return 0.0 +if __name__ == '__main__': + main() diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/agent_prompt.md b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/agent_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..ca489c065bafd5d10e764f033c9dfd1195933db3 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/agent_prompt.md @@ -0,0 +1,10 @@ +You are grading the submitted legal analysis against the criteria below. + +Read `/logs/artifacts/answer.md`, the answer captured by the verifier, before +assigning any scores. Evaluate that file as the submission. Other files in +`/app` may supply context, but must not replace the submitted answer. Do not +modify the submission. If it is missing or empty, state that in your reasoning +and apply the criteria to that missing or empty submission. Preserve each +criterion's stated positive or penalty polarity. + +{criteria} diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/criterion_1.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/criterion_1.toml new file mode 100644 index 0000000000000000000000000000000000000000..38f466f7c6610f0544e968543b7220e10e73fe65 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/criterion_1.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_1" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions that the Kucera comparator described in the Supplemental Comparator Disclosure from MPD Labor Liaison involved an off-duty discharge at an unarmed person suspected of a property offense that resulted in a 40-day suspension rather than termination." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/criterion_2.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/criterion_2.toml new file mode 100644 index 0000000000000000000000000000000000000000..b92654258cae1fcb101039a2bedd59d73445b99a --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/criterion_2.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_2" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that the Kucera comparator described in the Supplemental Comparator Disclosure from MPD Labor Liaison weakens MPD’s position that termination was consistent with discipline imposed on similarly situated members under Douglas factor six." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/criterion_3.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/criterion_3.toml new file mode 100644 index 0000000000000000000000000000000000000000..94f4f7352334369866740cab99026bd33d689781 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/criterion_3.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_3" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that MPD can distinguish the Kucera case because the discharge caused no injury" +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/criterion_4.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/criterion_4.toml new file mode 100644 index 0000000000000000000000000000000000000000..d86b0eb1646044767006ff9cb68d75ee1354eca8 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/criterion_4.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_4" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that objections not first urged before the Board cannot be considered by the DCCA" +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/criterion_5.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/criterion_5.toml new file mode 100644 index 0000000000000000000000000000000000000000..3de091a64c1d51802e1d5e8ce6350d0bff335b45 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/criterion_5.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_5" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: Mentions that the supplemental comparator document holds each of MPD's arguments." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/criterion_6.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/criterion_6.toml new file mode 100644 index 0000000000000000000000000000000000000000..2e97343467e6a8fdd3e5334f445d73f911d0b19a --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/criterion_6.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_6" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that MPD can distinguish the Kucera case because the penalty was set by a negotiated settlement" +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/criterion_7.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/criterion_7.toml new file mode 100644 index 0000000000000000000000000000000000000000..30fc8dcd6dd4815627f47d87e540b86653cd0d6f --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/criterion_7.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_7" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions that the Kucera case sat outside the record before the arbitrator." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/criterion_8.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/criterion_8.toml new file mode 100644 index 0000000000000000000000000000000000000000..a620832a393bc35c95ef401fafa59c3d6d56e6b3 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/criterion_8.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_8" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that the Supplemental Disclosure misdates the comparator memorandum it references." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/criterion_9.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/criterion_9.toml new file mode 100644 index 0000000000000000000000000000000000000000..ef11b99eabd3938c9a9d8f691b2bf79136d61faa --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/raw_correctness/criterion_9.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_9" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that the public policy argument is unaffected by the supplemental comparator because it does not depend on comparator evidence." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/test.sh b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..66a509a7bcdbe412851f3a012a5ba7b16cf0925b --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/tests/test.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +set -euo pipefail + +mkdir -p /logs/artifacts /logs/verifier/raw + +python3 - <<'PYEOF' +import json +import shutil +from pathlib import Path + + +def has_text(path: Path) -> bool: + return path.exists() and path.is_file() and bool(path.read_text(errors="replace").strip()) + + +def fallback_paths(answer_path: Path) -> list[Path]: + paths = [] + try: + relative = answer_path.relative_to("/app") + paths.append(Path("/app/app") / relative) + except ValueError: + pass + return [path for path in paths if path != answer_path] + + +config = json.loads(Path("/tests/fixtures/config.json").read_text()) +answer_path = Path(config["answer_path"]) +artifact_answer = Path("/logs/artifacts/answer.md") +artifact_answer.parent.mkdir(parents=True, exist_ok=True) +if has_text(answer_path): + shutil.copyfile(answer_path, artifact_answer) +else: + for candidate in fallback_paths(answer_path): + if has_text(candidate): + shutil.copyfile(candidate, artifact_answer) + break + else: + artifact_answer.write_text("") + +# Harbor collects /logs/artifacts when the agent step ends, which is before this +# script runs, so the copy above never reaches the uploaded artifacts. /logs/verifier +# is uploaded after the verifier phase, so persist the graded answer there too. +verifier_answer = Path("/logs/verifier/answer.md") +verifier_answer.parent.mkdir(parents=True, exist_ok=True) +shutil.copyfile(artifact_answer, verifier_answer) +PYEOF + +uv run --no-project --with 'harbor-rewardkit[all]==0.2.0' python /tests/m1_rewardkit_accounting.py /tests/raw_correctness \ + --workspace /app \ + --output /logs/verifier/raw/reward.json \ + --max-concurrent-llm "${MAX_CONCURRENT_LLM:-4}" \ + --max-concurrent-agent "${M1_MAX_CONCURRENT_AGENT:-1}" + +python /tests/normalize_reward.py \ + --raw-details /logs/verifier/raw/reward-details.json \ + --rubric /tests/fixtures/rubric.json \ + --reward-out /logs/verifier/reward.json \ + --details-out /logs/verifier/reward-details.json diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/workdir/attachments/supplemental_comparator_disclosure.pdf b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/workdir/attachments/supplemental_comparator_disclosure.pdf new file mode 100644 index 0000000000000000000000000000000000000000..3001d22852c562dc9b6802177237f63f56543cd1 Binary files /dev/null and b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-4/workdir/attachments/supplemental_comparator_disclosure.pdf differ diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/instruction.md b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d0f181b4015716da56e5c4854cb1c3873f651087 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/instruction.md @@ -0,0 +1,61 @@ +# Viability of a DCCA Challenge — Memo to the Client + +Domain: Litigation + +Matter: MPD v. PERB + +You are a senior legal analyst operating autonomously. You are completing a multi-step legal reasoning task. Follow the role, factual record, instructions, and deliverable requirements provided in the Task and each Assignment. + +Each Assignment may require a different legal deliverable. Follow the requirements specific to that Assignment. + +## Word limits for court briefs + +- A brief in support of or in response to a motion may not exceed **8,750 words**. +- A reply brief may not exceed **3,500 words**. +- For a motion for reconsideration, a brief in support of or in response to the motion may not exceed **3,500 words**, and a reply brief may not exceed **1,750 words**. +- If an Assignment specifies a stricter word limit, follow the stricter limit. + +These word limits do not apply to legal memoranda or other non-court-filing deliverables unless the Assignment expressly provides otherwise. + +Complete the task end-to-end without asking for confirmation, permission, or clarification. + +Use the uploaded matter documents in `/app/attachments/` as your primary case file. You also have internet access via OpenCode's `websearch` tool; use it to research any statutes, regulations, cases, administrative guidance, or secondary authorities that are not supplied as attachments. Cite any authority you rely on in the format requested by the prompt. + +For document inspection: +- PDF: `pdftotext /app/attachments/.pdf -` +- DOCX: `pandoc /app/attachments/.docx -t markdown` +- XLSX/CSV: use Python with `openpyxl` or `pandas` +- If extraction is unreliable, inspect the raw file with Python libraries or convert/render the relevant pages. + +Write the final complete legal deliverable for this assignment to `/app/response5.md`. The verifier reads only that file. + +This is a follow-on assignment. The documents from the previous assignment(s) remain available in `/app/attachments/`, and your prior deliverable `/app/response4.md` is also on disk. Build on that analysis as the prompt directs. + +## Attachments + +_No new documents for this assignment. The documents from the previous assignment(s) remain available in `/app/attachments/`._ + +## Prompt + +Our firm represents the District of Columbia Metropolitan Police Department (“MPD�) in connection with an arbitration award that reduced Officer Colin Braddock’s termination for excessive force to a 45-day suspension based solely on the arbitrator’s findings regarding Douglas factors six and twelve. The D.C. Public Employee Relations Board (“PERB�) affirmed the award. Assume today is March 2, 2026. Prepare the client deliverable based solely on the uploaded materials. +Treat the following as true for all purposes in this matter, whether or not separately memorialized in the record: (a) reasonable minds can disagree as to how comparable the four comparator cases are to Braddock’s case; (b) at no point before the arbitration hearing did Braddock or his union allege that MPD treated similarly situated employees differently; and (c) Braddock knew that MPD intended to rely on the four comparator cases before MPD found him guilty of the excessive force charge. + +The following documents have been uploaded for this Step: + +D.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117 (May 22, 2024) (final_notice_adverse_action_braddock.pdf) +In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf) +Memorandum from Yolanda Britt, Director, Disciplinary Review Division, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Sandra M. Delgado, Assistant Chief, Professional Development Bureau, re: Comparator Discipline Cases, Adverse Action Case No. IS-23-002841 (Braddock) (Apr. 11, 2024) (comparator_discipline_cases.pdf) +Douglas v. Veterans Administration, 5 M.S.P.R. 280 (1981) (douglas_v_veterans_admin.pdf) +D.C. Mun. Regs. tit. 6-B, § 1606 (2017) (dcmr_title6b_1606.pdf) +Opinion No. 1904, PERB Case No. 25-A-09 (D.C. Pub. Emp. Rels. Bd. Nov. 6, 2025) (perb_decision_braddock.pdf) +D.C. Code § 1-605.02 (2016) (dc_code_1-605.02.pdf) +W.R. Grace & Co. v. Local Union 759, 461 U.S. 757 (1983) (wr_grace_v_rubber_workers.pdf) +United Paperworkers Int'l Union v. Misco, Inc., 484 U.S. 29 (1987) (paperworkers_v_misco.pdf) +Memorandum from Marcus T. Bell, Labor Relations Liaison, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Outside Counsel, PERB Case No. 25-A-09 (Braddock), re: Supplemental Comparator Case Identified After Close of Arbitration Record (Feb. 24, 2026) (supplemental_comparator_disclosure.pdf) +Fraternal Ord. of Police/Dep’t of Corr. Lab. Comm. v. D.C. Pub. Emp. Rels. Bd., 973 A.2d 174 (D.C. 2009) (fop_doc_labor_comm_v_perb_2009.pdf) + +The documents listed above constitute the complete and exclusive universe of materials for this Step. Limit your review to the attached documents. Do not rely on, reference, or infer any legal authority, factual information, or data beyond what is contained in these uploaded files. If a document is not uploaded, it does not exist for purposes of this analysis. All citations must reference the document by its exact name as listed above, followed by the page and paragraph number. Do not cite external websites, databases, or any source outside the uploaded materials. + +Complete the following: + +1. Draft the memorandum to MPD addressing (1) the viability of challenging the Award under the public policy exception in D.C. Code sec. 1-605.02(6) and (2) the viability of challenging the Award under the law exception in D.C. Code sec. 1-605.02(6). The memorandum must state the question presented for each exception; state the governing standard for each exception with full Bluebook citations to the uploaded opinions, including pincites; apply each standard to the record, citing the record documents by exact file name with page and paragraph; account for the supplemental comparator; identify the principal weakness of each argument; and close with a recommendation on whether MPD should petition for review, stated as a definite position. diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/solution/solve.sh b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7710414a6da6d0ad740717c8c85a9af850d5da33 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/solution/solve.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# No oracle solution ships with LegalReasonBench. The verifier grades the +# agent's own legal deliverable for this assignment against the rubric. +echo "no oracle solution" diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/fixtures/config.json b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/fixtures/config.json new file mode 100644 index 0000000000000000000000000000000000000000..bdeab66ad10f4fbfcf8307055bd07699f975817b --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/fixtures/config.json @@ -0,0 +1,137 @@ +{ + "task_id": "lrb-dcca-challenge-police-discipline", + "title": "Viability of a DCCA Challenge", + "domain": "Litigation", + "matter": "MPD v. PERB", + "judge": { + "max_concurrent_llm": 12, + "mode": "panel", + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ], + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + "step_index": 5, + "step_name": "assignment-5", + "step_title": "Memo to the Client", + "prompt": "Our firm represents the District of Columbia Metropolitan Police Department (\u201cMPD\u201d) in connection with an arbitration award that reduced Officer Colin Braddock\u2019s termination for excessive force to a 45-day suspension based solely on the arbitrator\u2019s findings regarding Douglas factors six and twelve. The D.C. Public Employee Relations Board (\u201cPERB\u201d) affirmed the award. Assume today is March 2, 2026. Prepare the client deliverable based solely on the uploaded materials.\nTreat the following as true for all purposes in this matter, whether or not separately memorialized in the record: (a) reasonable minds can disagree as to how comparable the four comparator cases are to Braddock\u2019s case; (b) at no point before the arbitration hearing did Braddock or his union allege that MPD treated similarly situated employees differently; and (c) Braddock knew that MPD intended to rely on the four comparator cases before MPD found him guilty of the excessive force charge.\n\nThe following documents have been uploaded for this Step:\n\nD.C. Metro. Police Dep't, Professional Development Bureau, Final Notice of Adverse Action to Officer Colin R. Braddock, Adverse Action Case No. IS-23-002841, UFRB Case No. 23-UF-0117 (May 22, 2024) (final_notice_adverse_action_braddock.pdf)\nIn re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)\nMemorandum from Yolanda Britt, Director, Disciplinary Review Division, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Sandra M. Delgado, Assistant Chief, Professional Development Bureau, re: Comparator Discipline Cases, Adverse Action Case No. IS-23-002841 (Braddock) (Apr. 11, 2024) (comparator_discipline_cases.pdf)\nDouglas v. Veterans Administration, 5 M.S.P.R. 280 (1981) (douglas_v_veterans_admin.pdf)\nD.C. Mun. Regs. tit. 6-B, \u00a7 1606 (2017) (dcmr_title6b_1606.pdf)\nOpinion No. 1904, PERB Case No. 25-A-09 (D.C. Pub. Emp. Rels. Bd. Nov. 6, 2025) (perb_decision_braddock.pdf)\nD.C. Code \u00a7 1-605.02 (2016) (dc_code_1-605.02.pdf)\nW.R. Grace & Co. v. Local Union 759, 461 U.S. 757 (1983) (wr_grace_v_rubber_workers.pdf)\nUnited Paperworkers Int'l Union v. Misco, Inc., 484 U.S. 29 (1987) (paperworkers_v_misco.pdf)\nMemorandum from Marcus T. Bell, Labor Relations Liaison, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Outside Counsel, PERB Case No. 25-A-09 (Braddock), re: Supplemental Comparator Case Identified After Close of Arbitration Record (Feb. 24, 2026) (supplemental_comparator_disclosure.pdf)\nFraternal Ord. of Police/Dep\u2019t of Corr. Lab. Comm. v. D.C. Pub. Emp. Rels. Bd., 973 A.2d 174 (D.C. 2009) (fop_doc_labor_comm_v_perb_2009.pdf)\n\nThe documents listed above constitute the complete and exclusive universe of materials for this Step. Limit your review to the attached documents. Do not rely on, reference, or infer any legal authority, factual information, or data beyond what is contained in these uploaded files. If a document is not uploaded, it does not exist for purposes of this analysis. All citations must reference the document by its exact name as listed above, followed by the page and paragraph number. Do not cite external websites, databases, or any source outside the uploaded materials.\n\nComplete the following:\n\n1. Draft the memorandum to MPD addressing (1) the viability of challenging the Award under the public policy exception in D.C. Code sec. 1-605.02(6) and (2) the viability of challenging the Award under the law exception in D.C. Code sec. 1-605.02(6). The memorandum must state the question presented for each exception; state the governing standard for each exception with full Bluebook citations to the uploaded opinions, including pincites; apply each standard to the record, citing the record documents by exact file name with page and paragraph; account for the supplemental comparator; identify the principal weakness of each argument; and close with a recommendation on whether MPD should petition for review, stated as a definite position.", + "attachments": [], + "rubric": [ + { + "name": "criterion_1", + "description": "States that MPD should petition the DCCA for review.", + "source": "D.C. Code \u00a7 1-605.02(6) (2016) (dc_code_1-605.02.pdf); Douglas v. Veterans Administration, 5 M.S.P.R. 280 (1981) (douglas_v_veterans_admin.pdf); W.R. Grace & Co. v. Local Union 759, 461 U.S. 757 (1983) (wr_grace_v_rubber_workers.pdf); United Paperworkers Int'l Union v. Misco, Inc., 484 U.S. 29 (1987) (paperworkers_v_misco.pdf); Fraternal Ord. of Police/Dep't of Corr. Lab. Comm. v. D.C. Pub. Emp. Rels. Bd., 973 A.2d 174 (D.C. 2009) (fop_doc_labor_comm_v_perb_2009.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cclose with a recommendation on whether MPD should petition for review, stated as a definite position.\u201d", + "metadata": { + "irac_section": "Conclusion" + }, + "score": 4.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_2", + "description": "Identifies that the principal weakness of the public policy argument is that the Award imposes serious discipline rather than excusing the misconduct.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 10 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf) (the 45-day suspension and make-whole remedy establishing that the Award disciplines rather than excuses the misconduct); Opinion No. 1904, PERB Case No. 25-A-09, \u00b6 5 (D.C. Pub. Emp. Rels. Bd. Nov. 6, 2025) (perb_decision_braddock.pdf) (the Board's conclusion that no clear public policy violation appears on the face of the Award)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cidentify the principal weakness of each argument.\u201d", + "metadata": { + "irac_section": "Application" + }, + "score": 20.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_3", + "description": "Identifies that the contrary-to-law argument is weakened by the Kucera comparator\u2019s support for the arbitrator\u2019s factor six conclusion.", + "source": "Memorandum from Marcus T. Bell, Labor Relations Liaison, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Outside Counsel, PERB Case No. 25-A-09 (Braddock), re: Supplemental Comparator Case Identified After Close of Arbitration Record, \u00b6\u00b6 2-3 (Feb. 24, 2026) (supplemental_comparator_disclosure.pdf); In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 7 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201caccount for the supplemental comparator.\u201d", + "metadata": { + "irac_section": "Application" + }, + "score": 4.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_4", + "description": "States that MPD is likely to prevail because the DCCA will review the Douglas factors de novo.", + "source": "Douglas v. Veterans Administration, 5 M.S.P.R. 280, 305-06 (1981) (douglas_v_veterans_admin.pdf); Fraternal Ord. of Police/Dep't of Corr. Lab. Comm. v. D.C. Pub. Emp. Rels. Bd., 973 A.2d 174 (D.C. 2009) (fop_doc_labor_comm_v_perb_2009.pdf) at 3.", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cstate the governing standard for each exception with full Bluebook citations to the uploaded opinions, including pincites.\u201d Promising victory on de novo review misstates every governing standard in the universe at once.", + "metadata": { + "irac_section": "Conclusion" + }, + "score": -30.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_5", + "description": "States the question presented for the public policy exception as whether enforcing the Award's reinstatement of Officer Braddock would violate a well defined and dominant public policy against the unjustified use of deadly force by police officers.", + "source": "D.C. Code \u00a7 1-605.02(6) (2016) (dc_code_1-605.02.pdf); W.R. Grace & Co. v. Local Union 759, 461 U.S. 757, 766 (1983) (wr_grace_v_rubber_workers.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"The memorandum must state the question presented for each exception; state the governing standard for each exception with full Bluebook citations to the uploaded opinions, including pincites; apply each standard to the record, citing the record documents by exact file name with page and paragraph; account for the supplemental comparator; identify the principal weakness of each argument; and close with a recommendation on whether MPD should petition for review, stated as a definite position.\"", + "metadata": { + "irac_section": "Issue" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_6", + "description": "States that under the public policy standard the Award's imposition of a 45-day suspension with make-whole relief does not compel violation of the deadly-force policy.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6\u00b6 9-10 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf); W.R. Grace & Co. v. Local Union 759, 461 U.S. 757, 766 (1983) (wr_grace_v_rubber_workers.pdf); United Paperworkers Int'l Union v. Misco, Inc., 484 U.S. 29, 43 (1987) (paperworkers_v_misco.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"The memorandum must state the question presented for each exception; state the governing standard for each exception with full Bluebook citations to the uploaded opinions, including pincites; apply each standard to the record, citing the record documents by exact file name with page and paragraph; account for the supplemental comparator; identify the principal weakness of each argument; and close with a recommendation on whether MPD should petition for review, stated as a definite position.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 4.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_7", + "description": "Mentions the question presented for the law exception as whether the Award on its face is contrary to law because the arbitrator exceeded the permitted scope of review of MPD's penalty selection under Douglas.", + "source": "D.C. Code \u00a7 1-605.02(6) (2016) (dc_code_1-605.02.pdf); Douglas v. Veterans Administration, 5 M.S.P.R. 280, 305-06 (1981) (douglas_v_veterans_admin.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"The memorandum must state the question presented for each exception; state the governing standard for each exception with full Bluebook citations to the uploaded opinions, including pincites; apply each standard to the record, citing the record documents by exact file name with page and paragraph; account for the supplemental comparator; identify the principal weakness of each argument; and close with a recommendation on whether MPD should petition for review, stated as a definite position.\"", + "metadata": { + "irac_section": "Issue" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_8", + "description": "Identifies that the arbitrator's demand that MPD prove comparator comparability applied Douglas beyond the tolerable limits scope of review in the law exception application.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6\u00b6 5, 7 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf); Douglas v. Veterans Administration, 5 M.S.P.R. 280, 305-06 (1981) (douglas_v_veterans_admin.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"The memorandum must state the question presented for each exception; state the governing standard for each exception with full Bluebook citations to the uploaded opinions, including pincites; apply each standard to the record, citing the record documents by exact file name with page and paragraph; account for the supplemental comparator; identify the principal weakness of each argument; and close with a recommendation on whether MPD should petition for review, stated as a definite position.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 4.0, + "polarity": "positive", + "raw_weight": 1.0 + } + ], + "answer_path": "/app/response5.md", + "answer_relative_path": "response5.md", + "is_followon": true, + "prev_answer_path": "/app/response4.md" +} diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/fixtures/rubric.json b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/fixtures/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..adf518c019208316938adf209c9bd001d9ac773c --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/fixtures/rubric.json @@ -0,0 +1,100 @@ +{ + "criteria": [ + { + "name": "criterion_1", + "description": "States that MPD should petition the DCCA for review.", + "source": "D.C. Code \u00a7 1-605.02(6) (2016) (dc_code_1-605.02.pdf); Douglas v. Veterans Administration, 5 M.S.P.R. 280 (1981) (douglas_v_veterans_admin.pdf); W.R. Grace & Co. v. Local Union 759, 461 U.S. 757 (1983) (wr_grace_v_rubber_workers.pdf); United Paperworkers Int'l Union v. Misco, Inc., 484 U.S. 29 (1987) (paperworkers_v_misco.pdf); Fraternal Ord. of Police/Dep't of Corr. Lab. Comm. v. D.C. Pub. Emp. Rels. Bd., 973 A.2d 174 (D.C. 2009) (fop_doc_labor_comm_v_perb_2009.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cclose with a recommendation on whether MPD should petition for review, stated as a definite position.\u201d", + "metadata": { + "irac_section": "Conclusion" + }, + "score": 4.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_2", + "description": "Identifies that the principal weakness of the public policy argument is that the Award imposes serious discipline rather than excusing the misconduct.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 10 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf) (the 45-day suspension and make-whole remedy establishing that the Award disciplines rather than excuses the misconduct); Opinion No. 1904, PERB Case No. 25-A-09, \u00b6 5 (D.C. Pub. Emp. Rels. Bd. Nov. 6, 2025) (perb_decision_braddock.pdf) (the Board's conclusion that no clear public policy violation appears on the face of the Award)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201cidentify the principal weakness of each argument.\u201d", + "metadata": { + "irac_section": "Application" + }, + "score": 20.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_3", + "description": "Identifies that the contrary-to-law argument is weakened by the Kucera comparator\u2019s support for the arbitrator\u2019s factor six conclusion.", + "source": "Memorandum from Marcus T. Bell, Labor Relations Liaison, Hum. Res. Mgmt. Bureau, D.C. Metro. Police Dep't, to Outside Counsel, PERB Case No. 25-A-09 (Braddock), re: Supplemental Comparator Case Identified After Close of Arbitration Record, \u00b6\u00b6 2-3 (Feb. 24, 2026) (supplemental_comparator_disclosure.pdf); In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6 7 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \u201caccount for the supplemental comparator.\u201d", + "metadata": { + "irac_section": "Application" + }, + "score": 4.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_4", + "description": "States that MPD is likely to prevail because the DCCA will review the Douglas factors de novo.", + "source": "Douglas v. Veterans Administration, 5 M.S.P.R. 280, 305-06 (1981) (douglas_v_veterans_admin.pdf); Fraternal Ord. of Police/Dep't of Corr. Lab. Comm. v. D.C. Pub. Emp. Rels. Bd., 973 A.2d 174 (D.C. 2009) (fop_doc_labor_comm_v_perb_2009.pdf) at 3.", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \u201cstate the governing standard for each exception with full Bluebook citations to the uploaded opinions, including pincites.\u201d Promising victory on de novo review misstates every governing standard in the universe at once.", + "metadata": { + "irac_section": "Conclusion" + }, + "score": -30.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_5", + "description": "States the question presented for the public policy exception as whether enforcing the Award's reinstatement of Officer Braddock would violate a well defined and dominant public policy against the unjustified use of deadly force by police officers.", + "source": "D.C. Code \u00a7 1-605.02(6) (2016) (dc_code_1-605.02.pdf); W.R. Grace & Co. v. Local Union 759, 461 U.S. 757, 766 (1983) (wr_grace_v_rubber_workers.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"The memorandum must state the question presented for each exception; state the governing standard for each exception with full Bluebook citations to the uploaded opinions, including pincites; apply each standard to the record, citing the record documents by exact file name with page and paragraph; account for the supplemental comparator; identify the principal weakness of each argument; and close with a recommendation on whether MPD should petition for review, stated as a definite position.\"", + "metadata": { + "irac_section": "Issue" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_6", + "description": "States that under the public policy standard the Award's imposition of a 45-day suspension with make-whole relief does not compel violation of the deadly-force policy.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6\u00b6 9-10 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf); W.R. Grace & Co. v. Local Union 759, 461 U.S. 757, 766 (1983) (wr_grace_v_rubber_workers.pdf); United Paperworkers Int'l Union v. Misco, Inc., 484 U.S. 29, 43 (1987) (paperworkers_v_misco.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"The memorandum must state the question presented for each exception; state the governing standard for each exception with full Bluebook citations to the uploaded opinions, including pincites; apply each standard to the record, citing the record documents by exact file name with page and paragraph; account for the supplemental comparator; identify the principal weakness of each argument; and close with a recommendation on whether MPD should petition for review, stated as a definite position.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 4.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_7", + "description": "Mentions the question presented for the law exception as whether the Award on its face is contrary to law because the arbitrator exceeded the permitted scope of review of MPD's penalty selection under Douglas.", + "source": "D.C. Code \u00a7 1-605.02(6) (2016) (dc_code_1-605.02.pdf); Douglas v. Veterans Administration, 5 M.S.P.R. 280, 305-06 (1981) (douglas_v_veterans_admin.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"The memorandum must state the question presented for each exception; state the governing standard for each exception with full Bluebook citations to the uploaded opinions, including pincites; apply each standard to the record, citing the record documents by exact file name with page and paragraph; account for the supplemental comparator; identify the principal weakness of each argument; and close with a recommendation on whether MPD should petition for review, stated as a definite position.\"", + "metadata": { + "irac_section": "Issue" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_8", + "description": "Identifies that the arbitrator's demand that MPD prove comparator comparability applied Douglas beyond the tolerable limits scope of review in the law exception application.", + "source": "In re Arbitration Between Fraternal Ord. of Police/Metro. Police Dep't Lab. Comm. (Braddock Grievance) & D.C. Metro. Police Dep't, FMCS Case No. 24-51267, Grievance No. 24-0392, at \u00b6\u00b6 5, 7 (Mar. 14, 2025) (Larrabee, Arb.) (braddock_arbitration_award.pdf); Douglas v. Veterans Administration, 5 M.S.P.R. 280, 305-06 (1981) (douglas_v_veterans_admin.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"The memorandum must state the question presented for each exception; state the governing standard for each exception with full Bluebook citations to the uploaded opinions, including pincites; apply each standard to the record, citing the record documents by exact file name with page and paragraph; account for the supplemental comparator; identify the principal weakness of each argument; and close with a recommendation on whether MPD should petition for review, stated as a definite position.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 4.0, + "polarity": "positive", + "raw_weight": 1.0 + } + ] +} diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/m1_judge_panel.json b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/m1_judge_panel.json new file mode 100644 index 0000000000000000000000000000000000000000..a8041f6781a899f9083fe4a1a95f51bc78d35601 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/m1_judge_panel.json @@ -0,0 +1,21 @@ +{ + "mode": "panel", + "max_concurrent_llm": 12, + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ] +} diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/m1_rewardkit_accounting.py b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/m1_rewardkit_accounting.py new file mode 100644 index 0000000000000000000000000000000000000000..406dc5e7c675b222d94514e71bf5fad6ae141d8f --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/m1_rewardkit_accounting.py @@ -0,0 +1,490 @@ +import asyncio +import json +import math +import os +from pathlib import Path +import random +import sys +import time + +class JudgeReceiptError(OSError): + pass +_LLM_ROUTES = frozenset({'vertex', 'anthropic fallback', 'aistudio', 'direct'}) +_LLM_ROUTE_HEADERS = ('x-m1-llm-route', 'llm_provider-x-m1-llm-route') + +def _canonical_llm_route(value): + return value if isinstance(value, str) and value in _LLM_ROUTES else None + +def _llm_route_from_headers(headers): + if not isinstance(headers, dict): + return None + folded = {str(key).lower(): value for key, value in headers.items()} + for name in _LLM_ROUTE_HEADERS: + route = _canonical_llm_route(folded.get(name)) + if route is not None: + return route + return None + +def _llm_route_from_response(response): + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + route = _llm_route_from_headers(headers) + if route is not None: + return route + return _llm_route_from_headers(getattr(response, 'headers', None)) + +def _token_field_status(values, key): + if not isinstance(values, dict) or key not in values: + return 'missing' + value = values[key] + if value is None: + return 'null' + return 'valid' if type(value) is int and value >= 0 else 'invalid' + +def _gemini_capture(kwargs, model): + if not model.startswith('gemini/') or kwargs.get('stream') or kwargs.get('tools') or kwargs.get('functions'): + return (kwargs, None) + from litellm.integrations.custom_logger import CustomLogger + from urllib.parse import urlsplit + + class Capture(CustomLogger): + evidence = None + prompt_status = 'not_observed' + llm_route = None + + def log_post_api_call(self, kwargs, response_obj, start_time, end_time): + self.evidence = None + self.prompt_status = 'not_observed' + try: + params = kwargs.get('litellm_params') or {} + route = urlsplit(params.get('api_base') or '') + bare = model.removeprefix('gemini/') + gemini = params.get('custom_llm_provider') == 'gemini' + ai_studio = gemini and route.hostname == 'generativelanguage.googleapis.com' and (route.path in {'/' + version + '/models/' + bare + ':generateContent' for version in ('v1alpha', 'v1beta')}) + broker = urlsplit(os.environ.get('GEMINI_API_BASE') or '') + brokered = gemini and bool(broker.netloc) and (route.netloc == broker.netloc) and (broker.path.rstrip('/').rsplit('/', 1)[-1] in ('v1alpha', 'v1beta')) and (route.path == broker.path.rstrip('/') + '/models/' + bare + ':generateContent') + vertex = params.get('custom_llm_provider') == 'vertex_ai' and route.hostname == 'aiplatform.googleapis.com' and route.path.startswith('/v1/projects/') and route.path.endswith('/locations/global/publishers/google/models/' + bare + ':generateContent') + if route.scheme != 'https' or not (ai_studio or brokered or vertex) or kwargs.get('stream'): + return + self.llm_route = 'vertex' if vertex else 'aistudio' if ai_studio else None + raw = kwargs.get('original_response') + raw = json.loads(raw) if isinstance(raw, str) else raw + if not isinstance(raw, dict): + return + candidates = raw.get('candidates') + if not isinstance(candidates, list) or not candidates or any((not isinstance(c, dict) or not c.get('finishReason') for c in candidates)) or (not isinstance(raw.get('modelVersion'), str)) or (not raw['modelVersion']): + return + usage = raw.get('usageMetadata') + self.prompt_status = _token_field_status(usage, 'promptTokenCount') + if not isinstance(usage, dict): + return + fields = ('promptTokenCount', 'candidatesTokenCount', 'thoughtsTokenCount', 'cachedContentTokenCount', 'totalTokenCount', 'toolUsePromptTokenCount') + counts = {key: usage.get(key, 0) for key in fields} + if not {'promptTokenCount', 'totalTokenCount'} <= usage.keys() or any((type(n) is not int or n < 0 for n in counts.values())) or counts['toolUsePromptTokenCount'] != 0 or (counts['cachedContentTokenCount'] > counts['promptTokenCount']) or (counts['totalTokenCount'] != counts['promptTokenCount'] + counts['candidatesTokenCount'] + counts['thoughtsTokenCount']): + return + self.evidence = {'protocol': 'gemini-generate-content-' + ('vertex-v1' if vertex else route.path.split('/')[-3]), 'model_version': raw['modelVersion'], 'usage_metadata': {key: usage[key] for key in fields if key in usage}, 'defaulted_fields': [key for key in fields if key not in usage]} + except (TypeError, ValueError, AttributeError): + return + capture = Capture() + return ({**kwargs, 'callbacks': [*(kwargs.get('callbacks') or []), capture]}, capture) + +def _record_judge_usage(response, model: str, *, target: Path | None=None, native_usage: dict | None=None, native_prompt_status: str | None=None, llm_route: str | None=None) -> None: + import fcntl + from datetime import datetime, timezone + data = response.model_dump() if hasattr(response, 'model_dump') else response + usage = data.get('usage') if isinstance(data, dict) else None + granularity = data.get('usage_granularity') if isinstance(data, dict) else None + if not isinstance(usage, dict): + usage = {} + granularity = 'missing_provider_receipt' + prompt, completion = (usage.get('prompt_tokens'), usage.get('completion_tokens')) + native_fresh = usage.get('input_uncached_tokens') + prompt = prompt if type(prompt) is int and prompt >= 0 else None + native_fresh = native_fresh if type(native_fresh) is int and native_fresh >= 0 else None + if type(completion) is not int or completion < 0 or (prompt is None and native_fresh is None): + completion = completion if type(completion) is int and completion >= 0 else 0 + granularity = granularity or 'invalid_provider_receipt' + details = usage.get('prompt_tokens_details') + if details is not None and (not isinstance(details, dict)): + granularity = 'invalid_provider_receipt' + details = details if isinstance(details, dict) else {} + cached = details.get('cached_tokens') + if native_usage is not None: + native = native_usage['usage_metadata'] + native_output = native.get('candidatesTokenCount', 0) + native.get('thoughtsTokenCount', 0) + if prompt == native['promptTokenCount'] and completion == native_output: + cached = native.get('cachedContentTokenCount', 0) + else: + native_usage = None + written = next((value for value in (usage.get('input_cache_write_tokens'), usage.get('cache_creation_input_tokens'), details.get('cache_creation_tokens'), details.get('cache_write_tokens')) if value is not None), None) + invalid = any((value is not None and (type(value) is not int or value < 0) for value in (cached, written))) + cached = cached if type(cached) is int and cached >= 0 else None + written = written if type(written) is int and written >= 0 else None + fresh = native_fresh + if fresh is None and prompt is not None and (cached is not None) and (written is not None): + fresh = prompt - cached - written + if fresh is not None and (fresh < 0 or (prompt is not None and cached is not None and (written is not None) and (fresh + cached + written != prompt))): + invalid, fresh = (True, None) + provider, _, slug = model.partition('/') + event: dict = {'type': 'step_finish', 'part': {'providerID': provider if slug else 'openai', 'modelID': slug or model, 'tokens': {'input': fresh, 'output': completion, 'cache': {'read': cached, 'write': written}}}} + field_status = {'prompt_tokens': _token_field_status(usage, 'prompt_tokens'), 'completion_tokens': _token_field_status(usage, 'completion_tokens'), 'input_uncached_tokens': _token_field_status(usage, 'input_uncached_tokens')} + field_status['native_prompt_token_count'] = native_prompt_status if native_prompt_status in {'missing', 'null', 'invalid', 'valid', 'not_observed'} else 'unsupported' + part: dict = event['part'] + part['usage_field_status'] = field_status + if native_usage is not None: + event['part']['native_usage'] = native_usage + event['part']['token_categories_provenance'] = 'explicit_presence_v1' + if fresh is None and prompt is not None: + event['part']['prompt_tokens_inclusive'] = prompt + if invalid or any((value is None for value in (fresh, cached, written))): + granularity = granularity if granularity not in (None, 'request') else 'invalid_provider_receipt' if invalid else 'incomplete_token_categories' + if granularity: + event['part']['usage_granularity'] = granularity + if provider == 'openrouter': + cost = usage.get('cost') + if cost is None: + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + if isinstance(headers, dict): + cost = headers.get('llm_provider-x-litellm-response-cost') + if isinstance(cost, (int, float)) and (not isinstance(cost, bool)) and math.isfinite(cost) and (cost >= 0): + event['part']['cost'] = cost + data = data if isinstance(data, dict) else {} + if isinstance(data.get('id'), str) and data['id']: + event['part']['provider_request_id'] = data['id'] + for key in ('service_tier', 'cache_ttl'): + if data.get(key): + event['part'][key] = data[key] + route = _llm_route_from_response(response) or _canonical_llm_route(llm_route) + if route is not None: + event['part']['llm_route'] = route + created = data.get('created') + stamp = datetime.now(timezone.utc) + try: + if isinstance(created, str): + parsed = datetime.fromisoformat(created.replace('Z', '+00:00')) + if parsed.tzinfo is not None: + stamp = parsed + elif isinstance(created, (int, float)) and (not isinstance(created, bool)) and math.isfinite(created): + stamp = datetime.fromtimestamp(created, timezone.utc) + except (ValueError, OverflowError, OSError): + pass + pair = json.dumps({'type': 'step_start', 'timestamp': stamp.isoformat()}) + '\n' + pair += json.dumps(event) + '\n' + try: + receipt_path = target or Path(os.environ.get('M1_JUDGE_USAGE_PATH', '/logs/verifier/judge-trajectory.jsonl')) + receipt_path.parent.mkdir(parents=True, exist_ok=True) + with receipt_path.open('a') as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + handle.write(pair) + handle.flush() + os.fsync(handle.fileno()) + except OSError as exc: + if target is not None: + raise JudgeReceiptError(f'judge receipt write failed: {exc}') from exc + print(f'judge accounting: write failed ({type(exc).__name__})', file=sys.stderr) + +def openrouter_judge_pins() -> dict[str, dict]: + raw = os.environ.get('M1_OPENROUTER_JUDGE_PROVIDER_PINS', '').strip() + if not raw: + return {} + try: + pins = json.loads(raw) + except json.JSONDecodeError: + print('judge provider pins: invalid JSON in M1_OPENROUTER_JUDGE_PROVIDER_PINS', file=sys.stderr) + return {} + return {model: pin for model, pin in pins.items() if isinstance(pin, dict) and pin.get('order')} if isinstance(pins, dict) else {} + +def apply_judge_provider_pin(kwargs: dict, pins: dict[str, dict]) -> dict: + model = kwargs.get('model') + pin = pins.get(model) if isinstance(model, str) else None + if pin is None: + return kwargs + extra_body = dict(kwargs.get('extra_body') or {}) + provider = dict(extra_body.get('provider') or {}) + provider['order'] = list(pin['order']) + if pin.get('allow_fallbacks') is False: + provider['allow_fallbacks'] = False + if pin.get('zdr'): + provider['zdr'] = True + extra_body['provider'] = provider + return {**kwargs, 'extra_body': extra_body} +_TRANSIENT_ERROR_NAMES = ('RateLimitError', 'ServiceUnavailableError', 'InternalServerError', 'BadGatewayError', 'APIConnectionError') +_RETRYABLE_STATUS_CODES = frozenset({408, 409, 425, 429, 500, 502, 503, 504}) +_AUTH_ERROR_NAMES = ('AuthenticationError', 'PermissionDeniedError') +_AUTH_STATUS_CODES = frozenset({401, 403}) +_AUTH_RETRIES = 4 +_DEFAULT_TRANSIENT_RETRIES = 6 +_MAX_TRANSIENT_RETRIES = 20 +_MAX_RETRY_DELAY_SECONDS = 60.0 +_DEFAULT_EMPTY_RESPONSE_RETRIES = 3 +_DEFAULT_RETRY_BUDGET_SECONDS = 900.0 +_MAX_RETRY_BUDGET_SECONDS = 86400.0 + +def transient_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_TRANSIENT_RETRIES', '').strip() + if not raw: + return _DEFAULT_TRANSIENT_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_TRANSIENT_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_TRANSIENT_RETRIES + +def empty_response_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_EMPTY_RESPONSE_RETRIES', '').strip() + if not raw: + return _DEFAULT_EMPTY_RESPONSE_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_EMPTY_RESPONSE_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_EMPTY_RESPONSE_RETRIES + +def retry_budget_seconds() -> float: + raw = os.environ.get('M1_JUDGE_RETRY_BUDGET_SECONDS', '').strip() + if not raw: + return _DEFAULT_RETRY_BUDGET_SECONDS + try: + value = float(raw) + except ValueError: + value = math.nan + if not math.isfinite(value) or value < 0: + print('judge retries: invalid M1_JUDGE_RETRY_BUDGET_SECONDS, using the default', file=sys.stderr) + return _DEFAULT_RETRY_BUDGET_SECONDS + return min(value, _MAX_RETRY_BUDGET_SECONDS) + +def _within_budget(deadline: float, delay: float, model) -> bool: + remaining = deadline - time.monotonic() + if delay <= remaining: + return True + print(f'judge call retry budget spent: {model} would wait {delay:.1f}s with {max(remaining, 0.0):.1f}s left of M1_JUDGE_RETRY_BUDGET_SECONDS, failing now', file=sys.stderr) + return False + +def is_empty_verdict(response) -> bool: + data = response.model_dump() if hasattr(response, 'model_dump') else response + if not isinstance(data, dict): + return False + choices = data.get('choices') + if not isinstance(choices, list) or not choices: + return True + first = choices[0] + message = first.get('message') if isinstance(first, dict) else None + if not isinstance(message, dict): + return True + if message.get('tool_calls') or message.get('function_call'): + return False + content = message.get('content') + if isinstance(content, list): + content = ''.join((part.get('text') or '' for part in content if isinstance(part, dict))) + return not (isinstance(content, str) and content.strip()) + +def _matches(exc: BaseException, litellm, names: tuple[str, ...], statuses: frozenset[int]) -> bool: + classes = tuple((cls for cls in (getattr(litellm, name, None) for name in names) if isinstance(cls, type))) + if classes and isinstance(exc, classes): + return True + status = getattr(exc, 'status_code', None) + return type(status) is int and status in statuses + +def is_transient_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _TRANSIENT_ERROR_NAMES, _RETRYABLE_STATUS_CODES) + +def is_auth_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _AUTH_ERROR_NAMES, _AUTH_STATUS_CODES) + +def should_retry(exc: BaseException, litellm, attempt: int, limit: int) -> bool: + if attempt < limit and is_transient_error(exc, litellm): + return True + return attempt < min(limit, _AUTH_RETRIES) and is_auth_error(exc, litellm) + +def _retry_after_seconds(exc: BaseException) -> float | None: + headers = getattr(exc, 'headers', None) + if headers is None: + headers = getattr(getattr(exc, 'response', None), 'headers', None) + if headers is None: + return None + try: + raw = headers.get('retry-after') + if raw is None: + raw = headers.get('Retry-After') + value = float(raw) + except (AttributeError, TypeError, ValueError): + return None + return value if math.isfinite(value) and value >= 0 else None + +def retry_delay(exc: BaseException | None, attempt: int) -> float: + base = min(_MAX_RETRY_DELAY_SECONDS, 2.0 ** (attempt + 1)) + delay = base * (0.5 + random.random()) + retry_after = _retry_after_seconds(exc) if exc is not None else None + if retry_after is not None: + delay = max(delay, min(_MAX_RETRY_DELAY_SECONDS, retry_after)) + return delay + +def _note_retry(model, exc: BaseException, attempt: int, limit: int, delay: float) -> None: + status = getattr(exc, 'status_code', None) + print(f"judge call retry {attempt}/{limit}: {model} {type(exc).__name__} status={(status if type(status) is int else 'n/a')}, waiting {delay:.1f}s", file=sys.stderr) + +def _note_empty(model, response, attempt: int, limit: int, delay: float) -> None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + reason = None + if isinstance(data, dict) and isinstance(data.get('choices'), list) and data['choices']: + first = data['choices'][0] + reason = first.get('finish_reason') if isinstance(first, dict) else None + print(f'judge call retry {attempt}/{limit}: {model} empty verdict (finish_reason={reason}), waiting {delay:.1f}s', file=sys.stderr) + +def install(litellm, *, synchronous: bool=False) -> None: + pins = openrouter_judge_pins() + limit = transient_retry_limit() + empty_limit = empty_response_retry_limit() + deadline = time.monotonic() + retry_budget_seconds() + if synchronous: + original = litellm.completion + + def accounted(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = original(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + time.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + time.sleep(delay) + continue + return response + litellm.completion = accounted + return + original_async = litellm.acompletion + + async def accounted_async(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = await original_async(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + await asyncio.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + await asyncio.sleep(delay) + continue + return response + litellm.acompletion = accounted_async + +def record_agent_usage(attempt, *, model: str, provider: str) -> None: + records: dict[str, tuple[str, dict]] = {} + current_model = model + for filename in getattr(attempt, 'logs', []): + try: + with Path(filename).open() as stream: + for line in stream: + try: + event = json.loads(line) + except (ValueError, TypeError): + continue + if not isinstance(event, dict): + continue + message = event.get('message') or {} + if event.get('type') == 'assistant' and isinstance(message, dict) and isinstance(message.get('usage'), dict): + raw = message['usage'] + cached, written = (raw.get('cache_read_input_tokens'), raw.get('cache_creation_input_tokens')) + if all((type(value) is int and value >= 0 for value in (raw.get('input_tokens'), raw.get('output_tokens')))) and all((value is None or (type(value) is int and value >= 0) for value in (cached, written))): + receipt: dict = {'usage': {'input_uncached_tokens': raw['input_tokens'], 'prompt_tokens': raw['input_tokens'] + cached + written if cached is not None and written is not None else None, 'completion_tokens': raw['output_tokens'], 'prompt_tokens_details': {'cached_tokens': cached, 'cache_creation_tokens': written}}} + receipt['created'] = event.get('timestamp') + creation = raw.get('cache_creation') or {} + hour = creation.get('ephemeral_1h_input_tokens', 0) if isinstance(creation, dict) else 0 + if type(hour) is int and hour > 0: + if hour == written: + receipt['cache_ttl'] = '1h' + else: + receipt['usage_granularity'] = 'mixed_cache_ttl' + records[message.get('id') or json.dumps(raw, sort_keys=True)] = (message.get('model') or current_model, receipt) + payload = event.get('payload') or {} + if not isinstance(payload, dict): + continue + if event.get('type') == 'turn_context' and payload.get('model'): + current_model = payload['model'] + if event.get('type') == 'event_msg' and payload.get('type') == 'token_count': + info = payload.get('info') or {} + raw, total = (info.get('last_token_usage'), info.get('total_token_usage')) + if isinstance(raw, dict) and isinstance(total, dict) and all((type(raw.get(key)) is int and raw.get(key) >= 0 for key in ('input_tokens', 'output_tokens'))): + receipt = {'usage': {'prompt_tokens': raw.get('input_tokens'), 'input_uncached_tokens': raw.get('input_uncached_tokens'), 'input_cache_write_tokens': raw.get('input_cache_write_tokens'), 'completion_tokens': raw.get('output_tokens'), 'prompt_tokens_details': {'cached_tokens': raw.get('cached_input_tokens')}}} + receipt['created'] = event.get('timestamp') + records[json.dumps(total, sort_keys=True)] = (current_model, receipt) + except OSError: + continue + captured_input = captured_output = 0 + input_complete = True + for requested, receipt in records.values(): + requested = requested if '/' in requested else f'{provider}/{requested}' + _record_judge_usage(receipt, requested) + receipt_input = receipt['usage'].get('prompt_tokens') + if receipt_input is None: + input_complete = False + else: + captured_input += receipt_input + captured_output += receipt['usage'].get('completion_tokens') or 0 + total = getattr(attempt, 'usage', {}) or {} + if not records or (input_complete and total.get('input_tokens') != captured_input) or total.get('output_tokens') != captured_output: + _record_judge_usage({'usage': {'prompt_tokens': 0, 'completion_tokens': 0}, 'usage_granularity': 'incomplete_agent_receipts'}, model if '/' in model else f'{provider}/{model}') + +def install_rewardkit_agents() -> None: + import rewardkit.judges as judges + original = judges.get_agent + + def get_accounted_agent(judge, cwd=None): + backend = original(judge, cwd) + run = backend.run + + async def accounted_run(*args, **kwargs): + attempt = await run(*args, **kwargs) + record_agent_usage(attempt, model=judge.model or 'unknown', provider='anthropic' if judge.agent == 'claude-code' else 'openai') + return attempt + setattr(backend, 'run', accounted_run) + return backend + setattr(judges, 'get_agent', get_accounted_agent) +if __name__ == '__main__': + import litellm + if len(sys.argv) > 2 and sys.argv[1] == '--script': + import runpy + install(litellm, synchronous=True) + sys.argv = sys.argv[2:] + runpy.run_path(sys.argv[0], run_name='__main__') + else: + install(litellm) + install_rewardkit_agents() + if Path(__file__).with_name('m1_judge_panel.json').is_file(): + from m1_rewardkit_panel import install_panel + install_panel(Path(__file__).with_name('m1_judge_panel.json')) + if Path(__file__).with_name('m1_judge_jev.json').is_file(): + from m1_rewardkit_jev import install_jev + install_jev(Path(__file__).with_name('m1_judge_jev.json')) + from rewardkit.__main__ import main + main() diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/m1_rewardkit_panel.py b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/m1_rewardkit_panel.py new file mode 100644 index 0000000000000000000000000000000000000000..164cc2ae521cdd368c2e1749d7ed8fe09f4545eb --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/m1_rewardkit_panel.py @@ -0,0 +1,169 @@ +from __future__ import annotations +import asyncio +from contextvars import ContextVar +import json +import math +import os +import sys +from pathlib import Path +from typing import Any +import uuid +_request_audit: ContextVar[tuple[Path, list[str]] | None] = ContextVar('panel_request_audit', default=None) + +class PanelIncompleteError(RuntimeError): + pass + +def _audit_warning(exc: Exception, warnings: list[str]) -> None: + message = f'judge panel audit: diagnostic capture failed ({type(exc).__name__})' + if message not in warnings: + warnings.append(message) + print(message, file=sys.stderr) + +def _write_audit(path: Path, record: dict[str, Any], warnings: list[str], *, append: bool=False) -> None: + try: + text = json.dumps(record, allow_nan=False, default=str) + '\n' + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('a' if append else 'w') as stream: + stream.write(text) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + +def _binary(raw: Any) -> int: + if isinstance(raw, bool): + return int(raw) + if isinstance(raw, int | float) and math.isfinite(raw) and (raw in (0, 1)): + return int(raw) + if isinstance(raw, str): + value = raw.strip().lower() + if value in {'yes', 'true', '1'}: + return 1 + if value in {'no', 'false', '0'}: + return 0 + raise PanelIncompleteError('m1_judge_panel_incomplete: invalid binary vote') + +def validate_votes(scores: list[Any], criteria: list[Any]) -> None: + names = [criterion.name for criterion in criteria] + if len(set(names)) != len(names) or [score.name for score in scores] != names: + raise PanelIncompleteError('m1_judge_panel_incomplete: criterion membership mismatch') + for score, criterion in zip(scores, criteria, strict=True): + if score.error: + raise PanelIncompleteError('m1_judge_panel_incomplete: judge returned an error') + raw = _binary(score.raw) + expected = 1 - raw if criterion.negate else raw + if not math.isfinite(score.value) or score.value != expected: + raise PanelIncompleteError('m1_judge_panel_incomplete: inconsistent binary score') + +async def run_panel(judge: Any, criteria: list[Any], weights: list[float] | None, system_prompt: str | None, *, config: dict[str, Any], run_llm: Any, score_type: Any, audit_dir: Path) -> tuple[list[Any], str, list[str]]: + from rewardkit.models import Binary + if not criteria or any((not isinstance(criterion.output_format, Binary) for criterion in criteria)): + raise ValueError('panel majority voting requires nonempty binary criteria') + group_dir = audit_dir / uuid.uuid4().hex + warnings_out: list[str] = [] + + async def member_call(index: int, member: dict[str, Any]): + member_judge = judge.model_copy(update=member) + evidence: dict[str, Any] = {'member': index + 1, 'judge': member, 'criteria': [criterion.name for criterion in criteria], 'status': 'started'} + path = group_dir / f'judge-{index + 1}.json' + _write_audit(path, evidence, warnings_out) + token = _request_audit.set((group_dir / f'judge-{index + 1}-requests.jsonl', warnings_out)) + try: + scores, output, warnings = await run_llm(member_judge, criteria, weights, system_prompt) + evidence.update(output=output, warnings=warnings) + validate_votes(scores, criteria) + evidence['scores'] = [score.to_dict() for score in scores] + evidence['status'] = 'completed' + return (scores, output, warnings) + except BaseException as exc: + evidence.update(status='failed', error_class=type(exc).__name__) + if isinstance(exc, PanelIncompleteError): + evidence['error'] = str(exc) + raise + finally: + _request_audit.reset(token) + _write_audit(path, evidence, warnings_out) + outcomes = await asyncio.gather(*(member_call(index, member) for index, member in enumerate(config['members'])), return_exceptions=True) + failed = [index + 1 for index, result in enumerate(outcomes) if isinstance(result, BaseException)] + if failed: + _write_audit(group_dir / 'panel.json', {'status': 'incomplete', 'failed_members': failed}, warnings_out) + raise PanelIncompleteError(f'm1_judge_panel_incomplete: failed members {failed}; see panel audit artifacts') + completed = [outcome for outcome in outcomes if not isinstance(outcome, BaseException)] + combined = [] + for index, criterion in enumerate(criteria): + votes = [{'judge': config['members'][member_index], **outcome[0][index].to_dict()} for member_index, outcome in enumerate(completed)] + passes = sum((vote['value'] == 1 for vote in votes)) + value = int(passes >= 2) + combined.append(score_type(name=criterion.name, value=value, raw=bool(1 - value if criterion.negate else value), weight=weights[index] if weights is not None else 1.0, reasoning=f'{passes}/3 judges passed; strict majority requires 2/3.', description=criterion.description, id=criterion.id, negate=criterion.negate, optional=criterion.optional, votes=votes)) + for outcome in completed: + warnings_out.extend(outcome[2]) + audit = {'status': 'completed', 'mode': 'panel', 'aggregation': 'majority', 'required_votes': 2, 'members': config['members'], 'criteria': [score.to_dict() for score in combined]} + output = json.dumps(audit, indent=2, allow_nan=False) + _write_audit(group_dir / 'panel.json', audit, warnings_out) + return (combined, output, warnings_out) + +def install_panel(config_path: Path, *, audit_dir: Path=Path('/logs/verifier/judge-panel')) -> None: + import rewardkit.judges as judges + import rewardkit.reward as reward + from rewardkit.models import LLMJudge, Score + import litellm + config = json.loads(config_path.read_text()) + members = config.get('members') + concurrency = config.get('max_concurrent_llm') + if config.get('mode') != 'panel' or not isinstance(members, list) or len(members) != 3 or (len({member['model'] for member in members}) != 3) or (type(concurrency) is not int) or (not 1 <= concurrency <= 64): + raise ValueError('invalid materialized panel configuration') + if os.environ.get('REWARDKIT_JUDGE') or os.environ.get('REWARDKIT_MODEL'): + raise ValueError('RewardKit environment overrides cannot replace a frozen panel') + + class PanelScore(Score): + votes: list[dict[str, Any]] + + def to_dict(self): + return {**super().to_dict(), 'votes': self.votes} + original_llm = judges.arun_llm + original_call = judges._arun_llm_call + original_details = reward.Reward.to_detail_dict + original_completion = litellm.acompletion + active_loop = None + semaphore = None + + async def captured_completion(*args, **kwargs): + context = _request_audit.get() + record = {'requested_model': kwargs.get('model')} + response = None + try: + response = await original_completion(*args, **kwargs) + return response + except BaseException as exc: + record['error_class'] = type(exc).__name__ + raise + finally: + if context is not None: + path, warnings = context + try: + if response is not None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + record.update(response_model=data.get('model'), choices=data.get('choices')) + _write_audit(path, record, warnings, append=True) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + + async def bounded_call(*args, **kwargs): + nonlocal active_loop, semaphore + loop = asyncio.get_running_loop() + if active_loop is not loop: + active_loop, semaphore = (loop, asyncio.Semaphore(concurrency)) + assert semaphore is not None + async with semaphore: + return await original_call(*args, **kwargs) + + async def panel_call(judge, criteria, weights=None, system_prompt=None): + return await run_panel(judge, criteria, weights, system_prompt, config=config, run_llm=original_llm, score_type=PanelScore, audit_dir=audit_dir) + + def panel_details(self, score): + detail = original_details(self, score) + if isinstance(self.judge, LLMJudge): + detail.update(kind='llm_panel', judge=config, aggregation='majority', required_votes=2) + return detail + setattr(reward, 'arun_llm', panel_call) + setattr(judges, '_arun_llm_call', bounded_call) + setattr(litellm, 'acompletion', captured_completion) + reward.Reward.to_detail_dict = panel_details diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/normalize_reward.py b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/normalize_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..91817ef00ea9152ca57f0030d8e879eb850ddff0 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/normalize_reward.py @@ -0,0 +1,71 @@ +from __future__ import annotations +import argparse +import json +from pathlib import Path +from typing import Any + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument('--raw-details', required=True) + parser.add_argument('--rubric', required=True) + parser.add_argument('--reward-out', required=True) + parser.add_argument('--details-out', required=True) + args = parser.parse_args() + raw_details = _load_json(Path(args.raw_details)) + rubric = _load_json(Path(args.rubric)) + criteria = rubric['criteria'] + raw_by_name = _raw_criteria_by_name(raw_details) + positive_total = sum((float(item['score']) for item in criteria if float(item['score']) > 0)) + if positive_total <= 0: + raise ValueError('rubric must contain at least one positive score') + earned = 0.0 + normalized_criteria: list[dict[str, Any]] = [] + for item in criteria: + signed_score = float(item['score']) + raw = raw_by_name.get(item['name'], {}) + value = _coerce_score(raw.get('value', 0.0)) + contribution = value * signed_score + earned += contribution + normalized_criteria.append({'name': item['name'], 'value': value, 'raw': raw.get('raw'), 'weight': signed_score, 'signed_score': signed_score, 'polarity': item['polarity'], 'contribution': contribution, 'description': item['description'], 'source': item.get('source', ''), 'justification': item.get('justification', ''), 'metadata': item.get('metadata', {}), 'reasoning': raw.get('reasoning'), 'judge_reasoning': raw.get('reasoning'), 'judge_error': raw.get('error'), **({'votes': raw['votes']} if 'votes' in raw else {})}) + unclamped = earned / positive_total + reward = max(0.0, min(1.0, unclamped)) + reward_out = {'correctness': reward} + details_out = {'correctness': {'score': reward, 'kind': 'signed_score', 'criteria': normalized_criteria, 'aggregation': {'method': 'signed_score_ratio_clamped', 'earned': earned, 'positive_total': positive_total, 'unclamped': unclamped, 'clamped': reward}, 'raw_rewardkit': raw_details}} + _write_json(Path(args.reward_out), reward_out) + _write_json(Path(args.details_out), details_out) + +def _load_json(path: Path) -> Any: + return json.loads(path.read_text()) + +def _write_json(path: Path, data: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data, indent=2) + '\n') + +def _raw_criteria_by_name(details: dict[str, Any]) -> dict[str, dict[str, Any]]: + out: dict[str, dict[str, Any]] = {} + for reward in details.values(): + for item in _iter_raw_criteria(reward): + name = item.get('name') + if isinstance(name, str): + out[name] = item + return out + +def _iter_raw_criteria(value: Any): + if isinstance(value, list): + for item in value: + yield from _iter_raw_criteria(item) + return + if not isinstance(value, dict): + return + for item in value.get('criteria') or []: + if isinstance(item, dict): + yield item + +def _coerce_score(value: Any) -> float: + if isinstance(value, bool): + return 1.0 if value else 0.0 + if isinstance(value, int | float): + return max(0.0, min(1.0, float(value))) + return 0.0 +if __name__ == '__main__': + main() diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/raw_correctness/agent_prompt.md b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/raw_correctness/agent_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..ca489c065bafd5d10e764f033c9dfd1195933db3 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/raw_correctness/agent_prompt.md @@ -0,0 +1,10 @@ +You are grading the submitted legal analysis against the criteria below. + +Read `/logs/artifacts/answer.md`, the answer captured by the verifier, before +assigning any scores. Evaluate that file as the submission. Other files in +`/app` may supply context, but must not replace the submitted answer. Do not +modify the submission. If it is missing or empty, state that in your reasoning +and apply the criteria to that missing or empty submission. Preserve each +criterion's stated positive or penalty polarity. + +{criteria} diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/raw_correctness/criterion_1.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/raw_correctness/criterion_1.toml new file mode 100644 index 0000000000000000000000000000000000000000..bcb9bee21acf632f648c32055aacf09f18f15a97 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/raw_correctness/criterion_1.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_1" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that MPD should petition the DCCA for review." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/raw_correctness/criterion_2.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/raw_correctness/criterion_2.toml new file mode 100644 index 0000000000000000000000000000000000000000..de4e37291cde8f8be3c73666ead08f7fe2659bad --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/raw_correctness/criterion_2.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_2" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that the principal weakness of the public policy argument is that the Award imposes serious discipline rather than excusing the misconduct." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/raw_correctness/criterion_3.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/raw_correctness/criterion_3.toml new file mode 100644 index 0000000000000000000000000000000000000000..a2fdf270a3c183ca68b3f2f983d28c558fad1c84 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/raw_correctness/criterion_3.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_3" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that the contrary-to-law argument is weakened by the Kucera comparator’s support for the arbitrator’s factor six conclusion." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/raw_correctness/criterion_4.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/raw_correctness/criterion_4.toml new file mode 100644 index 0000000000000000000000000000000000000000..a633a0f9a6098becf2a9d02d9a75cd52d25a7172 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/raw_correctness/criterion_4.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_4" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: States that MPD is likely to prevail because the DCCA will review the Douglas factors de novo." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/raw_correctness/criterion_5.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/raw_correctness/criterion_5.toml new file mode 100644 index 0000000000000000000000000000000000000000..6fbf34124e9c43f9433a58f8a138f7fcf527b73b --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/raw_correctness/criterion_5.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_5" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States the question presented for the public policy exception as whether enforcing the Award's reinstatement of Officer Braddock would violate a well defined and dominant public policy against the unjustified use of deadly force by police officers." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/raw_correctness/criterion_6.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/raw_correctness/criterion_6.toml new file mode 100644 index 0000000000000000000000000000000000000000..f706012b0be4c402ee9830e20cdbf52ed4029716 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/raw_correctness/criterion_6.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_6" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that under the public policy standard the Award's imposition of a 45-day suspension with make-whole relief does not compel violation of the deadly-force policy." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/raw_correctness/criterion_7.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/raw_correctness/criterion_7.toml new file mode 100644 index 0000000000000000000000000000000000000000..644fead2b6810f499138ef326e9fc5c5ef6ace36 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/raw_correctness/criterion_7.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_7" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions the question presented for the law exception as whether the Award on its face is contrary to law because the arbitrator exceeded the permitted scope of review of MPD's penalty selection under Douglas." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/raw_correctness/criterion_8.toml b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/raw_correctness/criterion_8.toml new file mode 100644 index 0000000000000000000000000000000000000000..64574b63022e8841b3dba6e3b12d7918610de660 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/raw_correctness/criterion_8.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_8" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that the arbitrator's demand that MPD prove comparator comparability applied Douglas beyond the tolerable limits scope of review in the law exception application." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/test.sh b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..66a509a7bcdbe412851f3a012a5ba7b16cf0925b --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/steps/assignment-5/tests/test.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +set -euo pipefail + +mkdir -p /logs/artifacts /logs/verifier/raw + +python3 - <<'PYEOF' +import json +import shutil +from pathlib import Path + + +def has_text(path: Path) -> bool: + return path.exists() and path.is_file() and bool(path.read_text(errors="replace").strip()) + + +def fallback_paths(answer_path: Path) -> list[Path]: + paths = [] + try: + relative = answer_path.relative_to("/app") + paths.append(Path("/app/app") / relative) + except ValueError: + pass + return [path for path in paths if path != answer_path] + + +config = json.loads(Path("/tests/fixtures/config.json").read_text()) +answer_path = Path(config["answer_path"]) +artifact_answer = Path("/logs/artifacts/answer.md") +artifact_answer.parent.mkdir(parents=True, exist_ok=True) +if has_text(answer_path): + shutil.copyfile(answer_path, artifact_answer) +else: + for candidate in fallback_paths(answer_path): + if has_text(candidate): + shutil.copyfile(candidate, artifact_answer) + break + else: + artifact_answer.write_text("") + +# Harbor collects /logs/artifacts when the agent step ends, which is before this +# script runs, so the copy above never reaches the uploaded artifacts. /logs/verifier +# is uploaded after the verifier phase, so persist the graded answer there too. +verifier_answer = Path("/logs/verifier/answer.md") +verifier_answer.parent.mkdir(parents=True, exist_ok=True) +shutil.copyfile(artifact_answer, verifier_answer) +PYEOF + +uv run --no-project --with 'harbor-rewardkit[all]==0.2.0' python /tests/m1_rewardkit_accounting.py /tests/raw_correctness \ + --workspace /app \ + --output /logs/verifier/raw/reward.json \ + --max-concurrent-llm "${MAX_CONCURRENT_LLM:-4}" \ + --max-concurrent-agent "${M1_MAX_CONCURRENT_AGENT:-1}" + +python /tests/normalize_reward.py \ + --raw-details /logs/verifier/raw/reward-details.json \ + --rubric /tests/fixtures/rubric.json \ + --reward-out /logs/verifier/reward.json \ + --details-out /logs/verifier/reward-details.json diff --git a/tasks/lrb-dcca-challenge-police-discipline/task.toml b/tasks/lrb-dcca-challenge-police-discipline/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fd7f93a72331ccc4b2f76597335436107315d112 --- /dev/null +++ b/tasks/lrb-dcca-challenge-police-discipline/task.toml @@ -0,0 +1,148 @@ +schema_version = "1.1" +multi_step_reward_strategy = "mean" + +[task] +name = "micro1/lrb-dcca-challenge-police-discipline" + +[metadata] +benchmark = "LegalReasonBench" +title = "Viability of a DCCA Challenge" +practice_area = "Employment and labor" +research_universe = "closed-universe" +task_version = "63" +overall_reward = "points-weighted across assignments: sum of earned signed points over sum of positive points, clamped to [0, 1]. Harbor multi_step_reward_strategy=mean is diagnostic only. See scripts/score_matter.py." + +[agent] +timeout_sec = 10800.0 + +[environment] +build_timeout_sec = 900.0 +cpus = 2 +memory_mb = 4096 +storage_mb = 8192 +workdir = "/app" +allow_internet = true + +[environment.env] +OPENCODE_ENABLE_EXA = "${OPENCODE_ENABLE_EXA:-1}" + +[[steps]] +name = "assignment-1" +artifacts = ["/app/response1.md"] + +[steps.agent] +timeout_sec = 10800.0 + +[steps.verifier] +timeout_sec = 1800.0 + +[steps.verifier.env] +OPENAI_API_KEY = "${OPENAI_API_KEY:-}" +ANTHROPIC_API_KEY = "${ANTHROPIC_API_KEY:-}" +GOOGLE_API_KEY = "${GOOGLE_API_KEY:-}" +GEMINI_API_KEY = "${GEMINI_API_KEY:-}" +JUDGE_MODEL = "openai/gpt-5.6-terra" +JUDGE_REASONING_EFFORT = "medium" +JUDGE_TIMEOUT = "1500" +MAX_CONCURRENT_LLM = "12" +M1_MAX_CONCURRENT_AGENT = "1" +M1_JUDGE_TRANSIENT_RETRIES = "12" +M1_JUDGE_EMPTY_RESPONSE_RETRIES = "3" +M1_JUDGE_RETRY_BUDGET_SECONDS = "900" + +[[steps]] +name = "assignment-2" +artifacts = ["/app/response2.md"] + +[steps.agent] +timeout_sec = 10800.0 + +[steps.verifier] +timeout_sec = 1800.0 + +[steps.verifier.env] +OPENAI_API_KEY = "${OPENAI_API_KEY:-}" +ANTHROPIC_API_KEY = "${ANTHROPIC_API_KEY:-}" +GOOGLE_API_KEY = "${GOOGLE_API_KEY:-}" +GEMINI_API_KEY = "${GEMINI_API_KEY:-}" +JUDGE_MODEL = "openai/gpt-5.6-terra" +JUDGE_REASONING_EFFORT = "medium" +JUDGE_TIMEOUT = "1500" +MAX_CONCURRENT_LLM = "12" +M1_MAX_CONCURRENT_AGENT = "1" +M1_JUDGE_TRANSIENT_RETRIES = "12" +M1_JUDGE_EMPTY_RESPONSE_RETRIES = "3" +M1_JUDGE_RETRY_BUDGET_SECONDS = "900" + +[[steps]] +name = "assignment-3" +artifacts = ["/app/response3.md"] + +[steps.agent] +timeout_sec = 10800.0 + +[steps.verifier] +timeout_sec = 1800.0 + +[steps.verifier.env] +OPENAI_API_KEY = "${OPENAI_API_KEY:-}" +ANTHROPIC_API_KEY = "${ANTHROPIC_API_KEY:-}" +GOOGLE_API_KEY = "${GOOGLE_API_KEY:-}" +GEMINI_API_KEY = "${GEMINI_API_KEY:-}" +JUDGE_MODEL = "openai/gpt-5.6-terra" +JUDGE_REASONING_EFFORT = "medium" +JUDGE_TIMEOUT = "1500" +MAX_CONCURRENT_LLM = "12" +M1_MAX_CONCURRENT_AGENT = "1" +M1_JUDGE_TRANSIENT_RETRIES = "12" +M1_JUDGE_EMPTY_RESPONSE_RETRIES = "3" +M1_JUDGE_RETRY_BUDGET_SECONDS = "900" + +[[steps]] +name = "assignment-4" +artifacts = ["/app/response4.md"] + +[steps.agent] +timeout_sec = 10800.0 + +[steps.verifier] +timeout_sec = 1800.0 + +[steps.verifier.env] +OPENAI_API_KEY = "${OPENAI_API_KEY:-}" +ANTHROPIC_API_KEY = "${ANTHROPIC_API_KEY:-}" +GOOGLE_API_KEY = "${GOOGLE_API_KEY:-}" +GEMINI_API_KEY = "${GEMINI_API_KEY:-}" +JUDGE_MODEL = "openai/gpt-5.6-terra" +JUDGE_REASONING_EFFORT = "medium" +JUDGE_TIMEOUT = "1500" +MAX_CONCURRENT_LLM = "12" +M1_MAX_CONCURRENT_AGENT = "1" +M1_JUDGE_TRANSIENT_RETRIES = "12" +M1_JUDGE_EMPTY_RESPONSE_RETRIES = "3" +M1_JUDGE_RETRY_BUDGET_SECONDS = "900" + +[[steps]] +name = "assignment-5" +artifacts = ["/app/response5.md"] + +[steps.agent] +timeout_sec = 10800.0 + +[steps.verifier] +timeout_sec = 1800.0 + +[steps.verifier.env] +OPENAI_API_KEY = "${OPENAI_API_KEY:-}" +ANTHROPIC_API_KEY = "${ANTHROPIC_API_KEY:-}" +GOOGLE_API_KEY = "${GOOGLE_API_KEY:-}" +GEMINI_API_KEY = "${GEMINI_API_KEY:-}" +JUDGE_MODEL = "openai/gpt-5.6-terra" +JUDGE_REASONING_EFFORT = "medium" +JUDGE_TIMEOUT = "1500" +MAX_CONCURRENT_LLM = "12" +M1_MAX_CONCURRENT_AGENT = "1" +M1_JUDGE_TRANSIENT_RETRIES = "12" +M1_JUDGE_EMPTY_RESPONSE_RETRIES = "3" +M1_JUDGE_RETRY_BUDGET_SECONDS = "900" + diff --git a/tasks/lrb-forum-non-conveniens-response/environment/Dockerfile b/tasks/lrb-forum-non-conveniens-response/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c481aae22685617adcf60d0de6e473ce9019975a --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/environment/Dockerfile @@ -0,0 +1,29 @@ +FROM python:3.13-slim-bookworm + +RUN apt-get update && apt-get install -y --no-install-recommends \ + bash \ + ca-certificates \ + curl \ + file \ + git \ + libreoffice-calc \ + libreoffice-impress \ + libreoffice-writer \ + pandoc \ + poppler-utils \ + unzip \ + fonts-dejavu \ + && rm -rf /var/lib/apt/lists/* + +RUN python -m pip install --no-cache-dir \ + uv \ + openpyxl \ + pandas \ + pdfplumber \ + pypdf \ + python-docx \ + python-pptx \ + xlrd + +WORKDIR /app +RUN ln -s . /app/app diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/instruction.md b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..27c299148eed1a9cd1d40f1867739b2cb30d4222 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/instruction.md @@ -0,0 +1,69 @@ +# Plaintiff's Response - Forum Non Conveniens — Assignment 1 + +You are a senior legal analyst operating autonomously. You are completing a multi-step legal reasoning task. Follow the role, factual record, instructions, and deliverable requirements provided in the Task and each Assignment. + +Each Assignment may require a different legal deliverable. Follow the requirements specific to that Assignment. + +## Word limits for court briefs + +- A brief in support of or in response to a motion may not exceed **8,750 words**. +- A reply brief may not exceed **3,500 words**. +- For a motion for reconsideration, a brief in support of or in response to the motion may not exceed **3,500 words**, and a reply brief may not exceed **1,750 words**. +- If an Assignment specifies a stricter word limit, follow the stricter limit. + +These word limits do not apply to legal memoranda or other non-court-filing deliverables unless the Assignment expressly provides otherwise. + +Complete the task end-to-end without asking for confirmation, permission, or clarification. + +Use the uploaded matter documents in `/app/attachments/` as your primary case file. You also have internet access via OpenCode's `websearch` tool; use it to research any statutes, regulations, cases, administrative guidance, or secondary authorities that are not supplied as attachments. Cite any authority you rely on in the format requested by the prompt. + +For document inspection: +- PDF: `pdftotext /app/attachments/.pdf -` +- DOCX: `pandoc /app/attachments/.docx -t markdown` +- XLSX/CSV: use Python with `openpyxl` or `pandas` +- If extraction is unreliable, inspect the raw file with Python libraries or convert/render the relevant pages. + +Write the final complete legal deliverable for this assignment to `/app/response1.md`. The verifier reads only that file. + +## Attachments + +- `/app/attachments/2023 Annual Report Statistical Summary.pdf`: 2023 Annual Report Statistical Summary +- `/app/attachments/Bradbury v. St. Mary's Hospital.pdf`: Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) Case Law +- `/app/attachments/Davis Complaint.docx`: Sara Davis Complaint At Law +- `/app/attachments/Defendants Motion to Transfer.pdf`: Defendants Motion to Transfer +- `/app/attachments/First Am Bank v. Guerine.pdf`: First Nat. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002) Case Law +- `/app/attachments/Langenhorst v. Norfolk Southern.pdf`: Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006) + + +## Prompt + +To: Quinn Vivero +From: James Rogers +Re: Davis v. Smith, Forum Non Conveniens +Date: 7/20/2026 + +Mr. Vivero, + +As you are aware, we represent the Davis family for the loss their family suffered when their 23 day old baby passed away last year. We filed our case in June, 2026 in Cook County. On July 14, 2026, the Defendants filed a motion to transfer pursuant to the doctrine of forum non conveniens. + +By way of background, our client, Sara Davis, resides in Kane County, Illinois. She had received her prenatal medical care from Dr. John Smith, who practices in a group called “DuPage Health, S.C.� Both Dr. Smith and DuPage Health, S.C. are DuPage County entities. On August 24, 2024, Sara went into active later and presented to Safe Hospital, located in Naperville, Illinois – which is also DuPage County. +When Sara arrived at the hospital, she was actively bleeding and had stopped feeling movement in her stomach. The doctors and nurses at Safe Hospital hooked her up to a fetal-heart monitor and made the determination that the baby was still doing fine, and would continue to monitor. Over the next two hours as Sara was in active labor, the fetal monitoring records demonstrated decelerations, bradycardia, and tachycardia. + +Eventually, when the heart rate had dropped to a dangerously low level, the doctor began attempts to manually deliver through the use of forceps and vacuum. Ultimately he was successful in getting Baby Davis out, however, at birth, Baby Davis demonstrated low APGAR scores, need for resuscitation, and neurological intervention. + +The family was shook by the delivery process and even though Baby Davis was not in good condition, they had him transferred to the Lurie’s Children’s Hospital in Cook County, Illinois. Baby Davis underwent extensive surgical and medical intervention for the next 23 days until he almost passed away on September 16, 2024. + +We have retained an expert in this case who believes that Dr. Smith, his group, and the hospital, all deviated from the standard of care in the events leading up to the delayed delivery of Baby Davis. We have filed a wrongful death case for the untimely death and loss of Baby Davis. We have also filed a survival count, which accounts for the damages that Baby Davis sustained during his lifetime. We have spoken with 5 of the Cook County Hospital Doctors who provided care and treatment to Baby Davis. They are all willing to testify that they reviewed the records from Safe Hospital and believe that Dr. Smith deviated from the standard of care in the delivery process, they will also testify to the horrific injuries that Baby Davis sustained throughout his life and discuss how the death was a result initial delay in delivery and further complicated by the various conditions that developed over the next 23 days of his life. They have advised me that they are all Cook County residents and are willing to testify, however, it would be inconvenient for them to take time away from their practice/at the hospital to testify in DuPage rather than Cook County. + +We filed the case in Cook County, because venue is appropriate where any part of the action occurred, in a wrongful death case, it also includes the location of death, which in this case is Cook County. DuPage County is not a friendly jurisdiction for a plaintiff against a hospital, both in terms of the overall liability portion but also in the monetary damages portion. Of course, as anticipated, the Defendants are trying to transfer the case to DuPage County. + +I have attached the Defendant’s motion for your review. For Assignment #1, review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response. + +Be sure to limit your review to the attached documents. Do not rely on, reference, or infer any legal authority, factual information, or data beyond what is contained in these uploaded files. If a document is not uploaded, it does not exist for purposes of this analysis. All citations must reference the document by its exact name as listed below, followed by the page and paragraph number. Do not cite to external websites, databases, or any source outside the uploaded materials. + +Defendants Motion to Transfer.pdf +Davis Complaint.docx +Bradbury v. St. Mary’s Hospital.pdf +First Am Bank v. Guerine.pdf +Langenhorst v. Norfolk Southern.pdf +2023 Annual Report Statistical Summary.pdf diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/solution/solve.sh b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7710414a6da6d0ad740717c8c85a9af850d5da33 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/solution/solve.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# No oracle solution ships with LegalReasonBench. The verifier grades the +# agent's own legal deliverable for this assignment against the rubric. +echo "no oracle solution" diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/fixtures/config.json b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/fixtures/config.json new file mode 100644 index 0000000000000000000000000000000000000000..6f40c7852b972f489eeae47d3fe70064d14106c9 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/fixtures/config.json @@ -0,0 +1,368 @@ +{ + "task_id": "lrb-forum-non-conveniens-response", + "title": "Plaintiff's Response - Forum Non Conveniens", + "domain": "", + "matter": "", + "judge": { + "max_concurrent_llm": 12, + "mode": "panel", + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ], + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + "step_index": 1, + "step_name": "assignment-1", + "step_title": "", + "prompt": "To: Quinn Vivero\nFrom: James Rogers\nRe: Davis v. Smith, Forum Non Conveniens\nDate: 7/20/2026\n\nMr. Vivero,\n\nAs you are aware, we represent the Davis family for the loss their family suffered when their 23 day old baby passed away last year. We filed our case in June, 2026 in Cook County. On July 14, 2026, the Defendants filed a motion to transfer pursuant to the doctrine of forum non conveniens. \n\nBy way of background, our client, Sara Davis, resides in Kane County, Illinois. She had received her prenatal medical care from Dr. John Smith, who practices in a group called \u201cDuPage Health, S.C.\u201d Both Dr. Smith and DuPage Health, S.C. are DuPage County entities. On August 24, 2024, Sara went into active later and presented to Safe Hospital, located in Naperville, Illinois \u2013 which is also DuPage County.\nWhen Sara arrived at the hospital, she was actively bleeding and had stopped feeling movement in her stomach. The doctors and nurses at Safe Hospital hooked her up to a fetal-heart monitor and made the determination that the baby was still doing fine, and would continue to monitor. Over the next two hours as Sara was in active labor, the fetal monitoring records demonstrated decelerations, bradycardia, and tachycardia.\n\nEventually, when the heart rate had dropped to a dangerously low level, the doctor began attempts to manually deliver through the use of forceps and vacuum. Ultimately he was successful in getting Baby Davis out, however, at birth, Baby Davis demonstrated low APGAR scores, need for resuscitation, and neurological intervention. \n\nThe family was shook by the delivery process and even though Baby Davis was not in good condition, they had him transferred to the Lurie\u2019s Children\u2019s Hospital in Cook County, Illinois. Baby Davis underwent extensive surgical and medical intervention for the next 23 days until he almost passed away on September 16, 2024.\n\nWe have retained an expert in this case who believes that Dr. Smith, his group, and the hospital, all deviated from the standard of care in the events leading up to the delayed delivery of Baby Davis. We have filed a wrongful death case for the untimely death and loss of Baby Davis. We have also filed a survival count, which accounts for the damages that Baby Davis sustained during his lifetime. We have spoken with 5 of the Cook County Hospital Doctors who provided care and treatment to Baby Davis. They are all willing to testify that they reviewed the records from Safe Hospital and believe that Dr. Smith deviated from the standard of care in the delivery process, they will also testify to the horrific injuries that Baby Davis sustained throughout his life and discuss how the death was a result initial delay in delivery and further complicated by the various conditions that developed over the next 23 days of his life. They have advised me that they are all Cook County residents and are willing to testify, however, it would be inconvenient for them to take time away from their practice/at the hospital to testify in DuPage rather than Cook County.\n\nWe filed the case in Cook County, because venue is appropriate where any part of the action occurred, in a wrongful death case, it also includes the location of death, which in this case is Cook County. DuPage County is not a friendly jurisdiction for a plaintiff against a hospital, both in terms of the overall liability portion but also in the monetary damages portion. Of course, as anticipated, the Defendants are trying to transfer the case to DuPage County.\n\nI have attached the Defendant\u2019s motion for your review. For Assignment #1, review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\n\nBe sure to limit your review to the attached documents. Do not rely on, reference, or infer any legal authority, factual information, or data beyond what is contained in these uploaded files. If a document is not uploaded, it does not exist for purposes of this analysis. All citations must reference the document by its exact name as listed below, followed by the page and paragraph number. Do not cite to external websites, databases, or any source outside the uploaded materials.\n\nDefendants Motion to Transfer.pdf\nDavis Complaint.docx\nBradbury v. St. Mary\u2019s Hospital.pdf\nFirst Am Bank v. Guerine.pdf\nLangenhorst v. Norfolk Southern.pdf\n2023 Annual Report Statistical Summary.pdf", + "attachments": [ + { + "filename": "2023 Annual Report Statistical Summary.pdf", + "description": "2023 Annual Report Statistical Summary", + "metadata": {}, + "path": "/app/attachments/2023 Annual Report Statistical Summary.pdf" + }, + { + "filename": "Bradbury v. St. Mary's Hospital.pdf", + "description": "Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) Case Law", + "metadata": {}, + "path": "/app/attachments/Bradbury v. St. Mary's Hospital.pdf" + }, + { + "filename": "Davis Complaint.docx", + "description": "Sara Davis Complaint At Law", + "metadata": {}, + "path": "/app/attachments/Davis Complaint.docx" + }, + { + "filename": "Defendants Motion to Transfer.pdf", + "description": "Defendants Motion to Transfer", + "metadata": {}, + "path": "/app/attachments/Defendants Motion to Transfer.pdf" + }, + { + "filename": "First Am Bank v. Guerine.pdf", + "description": "First Nat. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002) Case Law", + "metadata": {}, + "path": "/app/attachments/First Am Bank v. Guerine.pdf" + }, + { + "filename": "Langenhorst v. Norfolk Southern.pdf", + "description": "Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006)", + "metadata": {}, + "path": "/app/attachments/Langenhorst v. Norfolk Southern.pdf" + } + ], + "rubric": [ + { + "name": "criterion_1", + "description": "States in Assignment #1that the Defendants motion was supported by two affidavits which was absent in Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995).", + "source": "Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) (Bradbury v. St. Mary\u2019s Hospital.pdf at p.3).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_2", + "description": "Identifies in Assignment #1 an affidavit by John Smith, M.D. does not indicate that Cook County would be an inconvenient forum for him to litigate this case as required under Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006).", + "source": "Defendants Motion to Transfer.pdf (Defendants Motion to Transfer.pdf at p.8) stating \"Trial of this matter in the Circuit Court of DuPage County would be substantially more convenient for me, both as a party and as a fact witness, than trial in the Circuit Court of Cook County.\" and Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006) (Langenhorst v. Norfolk Southern.pdf at p.10).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_3", + "description": "Identifies in Assignment #1 an affidavit by Safe Hospital representative does not indicate that Cook County would be an inconvenient forum for them to litigate this case as required under Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006).", + "source": "Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006) (Langenhorst v. Norfolk Southern.pdf at p.10).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_4", + "description": "States in Assignment #1 that the burden is on the movant to show that the balance of private interest factors with all other factors, strongly favors the proposed forum, under Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006).", + "source": "Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.7).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 1.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_30", + "description": "States in Assignment #1 that the burden is on the movant to show that the balance of public interest factors with all other factors, strongly favors the proposed forum under Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006).", + "source": "Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.7).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 1.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_5", + "description": "Mentions in Assignment #1 that the plaintiff\u2019s interest in choosing the forum receives less deference when the plaintiff\u2019s residence is located outside the chosen forum, under Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006).", + "source": "Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.7).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_6", + "description": "Identifies in Assignment #1 that in Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006) the reviewing court affirmed the denial of transfer even though the plaintiff\u2019s residence was outside the chosen forum.", + "source": "Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.12).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_7", + "description": "Identifies in Assignment #1 that in Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 the reviewing court affirmed the denial of transfer even though the plaintiff failed to establish residency in the chosen forum.", + "source": "Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) (Bradbury v. St. Mary\u2019s Hospital.pdf at p.5).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_8", + "description": "Identifies in Assignment #1 that in First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002) the reviewing court reversed a grant of transfer even though the plaintiff\u2019s residence was outside the chosen forum.", + "source": "First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002) (First Am Bank v. Guerine.pdf at p.10).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_9", + "description": "Mentions in Assignment #1 that Plaintiff, Sara Davis\u2019 residence is unknown by the Defendant in its analysis for the motion to transfer.", + "source": "Defendants Motion to Transfer.pdf at \u00b69.", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_10", + "description": "States in Assignment #1 that Plaintiff, Sara Davis should file an affidavit establishing her residence outside of DuPage County.", + "source": "\"Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) (Bradbury v. St. Mary\u2019s Hospital.pdf at p.5) and First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002) (First Am Bank v. Guerine.pdf at p.7).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_11", + "description": "States in Assignment #1 that Plaintiff, Sara Davis should file an affidavit that it would be inconvenient to proceed with this litigation in DuPage County.", + "source": "Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.10).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 15.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_12", + "description": "Mentions in Assignment #1 that 5 of the Cook County Hospital Doctors who provided care to Baby Davis are located within Cook County.", + "source": "Factual scenario given in assignment.", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 1.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_13", + "description": "States in Assignment #1 that Plaintiff should obtain affidavits from the 5 Cook County Hospital Doctors who provided care to Baby Davis that it would be inconvenient for them to testify in DuPage County.", + "source": "Factual scenario given in assignment.", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 1.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_15", + "description": "Identifies in Assignment #1 that the medical records from Cook County Hospital are important for the analysis of the Plaintiff\u2019s survival action.", + "source": "Davis Complaint.docx, Count I", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_16", + "description": "States in Assignment #1 that the medical records from Cook County Hospital are relevant for the analysis of the Plaintiff\u2019s wrongful death claim.", + "source": "Davis Complaint.docx, Count II", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_17", + "description": "Mentions in Assignment #1 that Defendants have provided no evidentiary basis regarding the burden of the compulsory process for attendance of witnesses.", + "source": "Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) (Bradbury v. St. Mary\u2019s Hospital.pdf at p.3).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_18", + "description": "Mentions in Assignment #1 that we live in a smaller world, we are connected by interstate highways, bustling airways, today, convenience - the touchstone of the forum non conveniens doctrine has a different meaning, under Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006).", + "source": "Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.10).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_19", + "description": "Identifies in Assignment #1 that the Defendants have distinguished First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002) where potential witnesses resided in multiple counties.", + "source": "First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002) (First Am Bank v. Guerine.pdf at p.7) and Defendants Motion to Transfer.pdf (Defendants Motion to Transfer.pdf at pp.7-8).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 1.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_20", + "description": "Identifies in Assignment #1 that the Defendants have distinguished Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006) where potential witnesses resided in multiple counties", + "source": "Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.13) and and Defendants Motion to Transfer.pdf (Defendants Motion to Transfer.pdf at pp.7-8).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 1.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_21", + "description": "States in Assignment #1 that Cook County has an interest in this litigation because the decedent died in Cook County, under Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995).", + "source": "Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) (Bradbury v. St. Marys Hospital.pdf, p.4).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_22", + "description": "Mentions in Assignment #1 that Cook County lacks interest in adjudicating a controversy over care rendered by its DuPage based providers.", + "source": "Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) (Bradbury v. St. Marys Hospital.pdf, p.4).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": -30.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_23", + "description": "Identifies in Assignment #1 that Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) treated the location of death alone as sufficient to give Cook County a genuine interest in the litigation.", + "source": "Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) (Bradbury v. St. Marys Hospital.pdf, p.4).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_24", + "description": "States in Assignment #1 that court congestion is a relatively insignificant factor, especially where the record does not show the other forum would resolve the case more quickly, under First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002).", + "source": "First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002) (First Am Bank v. Guerine.pdf at p.3).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_25", + "description": "Mentions in Assignment #1 that Cook County\u2019s overall clearance rate is 60.5%.", + "source": "2023 Annual Report Statistical Summary.pdf at p.21.", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\" This information is stated in the 2023 Annual Report Statistical Summary.pdf, p. 21, however, this is a statistic that refers to overall clearance, and is not applicable to Civil Cases, specifically Civil Case in excess of $50,000.00 which is the comparison necessary to assist the Court in completing the analysis to grant Defendant's Motion to Transfer.", + "metadata": {}, + "score": -30.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_26", + "description": "Identifies in Assignment #1 that in the overall Civil Category, Cook County had a clearance rate of 97.9%.", + "source": "2023 Annual Report Statistical Summary.pdf at p.22", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_27", + "description": "States in Assignment #1 that in the overall Civil Category, the 18th Judicial Circuit had a clearance rate of 96.3%.", + "source": "2023 Annual Report Statistical Summary.pdf at p.22.", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_28", + "description": "States in Assignment #1 that the Defendants cannot supply information regarding the time lapse for civil cases in excess of $50,000.00 because Cook County did not report information in 2023.", + "source": "2023 Annual Report Statistical Summary.pdf at p. 163.", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_29", + "description": "States in Assignment #1 that the Defendants have provided no evidence to show that DuPage County will resolve the case more quickly than Cook County.", + "source": "First Nat. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002) (First Am Bank v. Guerine.pdf at p.3).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + } + ], + "answer_path": "/app/response1.md", + "answer_relative_path": "response1.md", + "is_followon": false, + "prev_answer_path": "" +} diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/fixtures/rubric.json b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/fixtures/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..1a20146b9b99c4123bd1e230356cf958c317cbbb --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/fixtures/rubric.json @@ -0,0 +1,294 @@ +{ + "criteria": [ + { + "name": "criterion_1", + "description": "States in Assignment #1that the Defendants motion was supported by two affidavits which was absent in Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995).", + "source": "Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) (Bradbury v. St. Mary\u2019s Hospital.pdf at p.3).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_2", + "description": "Identifies in Assignment #1 an affidavit by John Smith, M.D. does not indicate that Cook County would be an inconvenient forum for him to litigate this case as required under Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006).", + "source": "Defendants Motion to Transfer.pdf (Defendants Motion to Transfer.pdf at p.8) stating \"Trial of this matter in the Circuit Court of DuPage County would be substantially more convenient for me, both as a party and as a fact witness, than trial in the Circuit Court of Cook County.\" and Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006) (Langenhorst v. Norfolk Southern.pdf at p.10).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_3", + "description": "Identifies in Assignment #1 an affidavit by Safe Hospital representative does not indicate that Cook County would be an inconvenient forum for them to litigate this case as required under Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006).", + "source": "Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006) (Langenhorst v. Norfolk Southern.pdf at p.10).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_4", + "description": "States in Assignment #1 that the burden is on the movant to show that the balance of private interest factors with all other factors, strongly favors the proposed forum, under Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006).", + "source": "Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.7).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 1.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_30", + "description": "States in Assignment #1 that the burden is on the movant to show that the balance of public interest factors with all other factors, strongly favors the proposed forum under Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006).", + "source": "Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.7).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 1.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_5", + "description": "Mentions in Assignment #1 that the plaintiff\u2019s interest in choosing the forum receives less deference when the plaintiff\u2019s residence is located outside the chosen forum, under Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006).", + "source": "Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.7).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_6", + "description": "Identifies in Assignment #1 that in Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006) the reviewing court affirmed the denial of transfer even though the plaintiff\u2019s residence was outside the chosen forum.", + "source": "Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.12).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_7", + "description": "Identifies in Assignment #1 that in Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 the reviewing court affirmed the denial of transfer even though the plaintiff failed to establish residency in the chosen forum.", + "source": "Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) (Bradbury v. St. Mary\u2019s Hospital.pdf at p.5).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_8", + "description": "Identifies in Assignment #1 that in First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002) the reviewing court reversed a grant of transfer even though the plaintiff\u2019s residence was outside the chosen forum.", + "source": "First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002) (First Am Bank v. Guerine.pdf at p.10).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_9", + "description": "Mentions in Assignment #1 that Plaintiff, Sara Davis\u2019 residence is unknown by the Defendant in its analysis for the motion to transfer.", + "source": "Defendants Motion to Transfer.pdf at \u00b69.", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_10", + "description": "States in Assignment #1 that Plaintiff, Sara Davis should file an affidavit establishing her residence outside of DuPage County.", + "source": "\"Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) (Bradbury v. St. Mary\u2019s Hospital.pdf at p.5) and First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002) (First Am Bank v. Guerine.pdf at p.7).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_11", + "description": "States in Assignment #1 that Plaintiff, Sara Davis should file an affidavit that it would be inconvenient to proceed with this litigation in DuPage County.", + "source": "Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.10).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 15.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_12", + "description": "Mentions in Assignment #1 that 5 of the Cook County Hospital Doctors who provided care to Baby Davis are located within Cook County.", + "source": "Factual scenario given in assignment.", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 1.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_13", + "description": "States in Assignment #1 that Plaintiff should obtain affidavits from the 5 Cook County Hospital Doctors who provided care to Baby Davis that it would be inconvenient for them to testify in DuPage County.", + "source": "Factual scenario given in assignment.", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 1.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_15", + "description": "Identifies in Assignment #1 that the medical records from Cook County Hospital are important for the analysis of the Plaintiff\u2019s survival action.", + "source": "Davis Complaint.docx, Count I", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_16", + "description": "States in Assignment #1 that the medical records from Cook County Hospital are relevant for the analysis of the Plaintiff\u2019s wrongful death claim.", + "source": "Davis Complaint.docx, Count II", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_17", + "description": "Mentions in Assignment #1 that Defendants have provided no evidentiary basis regarding the burden of the compulsory process for attendance of witnesses.", + "source": "Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) (Bradbury v. St. Mary\u2019s Hospital.pdf at p.3).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_18", + "description": "Mentions in Assignment #1 that we live in a smaller world, we are connected by interstate highways, bustling airways, today, convenience - the touchstone of the forum non conveniens doctrine has a different meaning, under Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006).", + "source": "Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.10).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_19", + "description": "Identifies in Assignment #1 that the Defendants have distinguished First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002) where potential witnesses resided in multiple counties.", + "source": "First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002) (First Am Bank v. Guerine.pdf at p.7) and Defendants Motion to Transfer.pdf (Defendants Motion to Transfer.pdf at pp.7-8).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 1.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_20", + "description": "Identifies in Assignment #1 that the Defendants have distinguished Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006) where potential witnesses resided in multiple counties", + "source": "Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.13) and and Defendants Motion to Transfer.pdf (Defendants Motion to Transfer.pdf at pp.7-8).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 1.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_21", + "description": "States in Assignment #1 that Cook County has an interest in this litigation because the decedent died in Cook County, under Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995).", + "source": "Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) (Bradbury v. St. Marys Hospital.pdf, p.4).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_22", + "description": "Mentions in Assignment #1 that Cook County lacks interest in adjudicating a controversy over care rendered by its DuPage based providers.", + "source": "Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) (Bradbury v. St. Marys Hospital.pdf, p.4).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": -30.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_23", + "description": "Identifies in Assignment #1 that Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) treated the location of death alone as sufficient to give Cook County a genuine interest in the litigation.", + "source": "Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) (Bradbury v. St. Marys Hospital.pdf, p.4).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_24", + "description": "States in Assignment #1 that court congestion is a relatively insignificant factor, especially where the record does not show the other forum would resolve the case more quickly, under First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002).", + "source": "First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002) (First Am Bank v. Guerine.pdf at p.3).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_25", + "description": "Mentions in Assignment #1 that Cook County\u2019s overall clearance rate is 60.5%.", + "source": "2023 Annual Report Statistical Summary.pdf at p.21.", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\" This information is stated in the 2023 Annual Report Statistical Summary.pdf, p. 21, however, this is a statistic that refers to overall clearance, and is not applicable to Civil Cases, specifically Civil Case in excess of $50,000.00 which is the comparison necessary to assist the Court in completing the analysis to grant Defendant's Motion to Transfer.", + "metadata": {}, + "score": -30.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_26", + "description": "Identifies in Assignment #1 that in the overall Civil Category, Cook County had a clearance rate of 97.9%.", + "source": "2023 Annual Report Statistical Summary.pdf at p.22", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_27", + "description": "States in Assignment #1 that in the overall Civil Category, the 18th Judicial Circuit had a clearance rate of 96.3%.", + "source": "2023 Annual Report Statistical Summary.pdf at p.22.", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_28", + "description": "States in Assignment #1 that the Defendants cannot supply information regarding the time lapse for civil cases in excess of $50,000.00 because Cook County did not report information in 2023.", + "source": "2023 Annual Report Statistical Summary.pdf at p. 163.", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_29", + "description": "States in Assignment #1 that the Defendants have provided no evidence to show that DuPage County will resolve the case more quickly than Cook County.", + "source": "First Nat. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002) (First Am Bank v. Guerine.pdf at p.3).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #1\"; \"Review Defendant's motion; for each argument it makes, note what's strong about it, what's weak, and flag any points we should target in our response.\"", + "metadata": {}, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + } + ] +} diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/m1_judge_panel.json b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/m1_judge_panel.json new file mode 100644 index 0000000000000000000000000000000000000000..a8041f6781a899f9083fe4a1a95f51bc78d35601 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/m1_judge_panel.json @@ -0,0 +1,21 @@ +{ + "mode": "panel", + "max_concurrent_llm": 12, + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ] +} diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/m1_rewardkit_accounting.py b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/m1_rewardkit_accounting.py new file mode 100644 index 0000000000000000000000000000000000000000..406dc5e7c675b222d94514e71bf5fad6ae141d8f --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/m1_rewardkit_accounting.py @@ -0,0 +1,490 @@ +import asyncio +import json +import math +import os +from pathlib import Path +import random +import sys +import time + +class JudgeReceiptError(OSError): + pass +_LLM_ROUTES = frozenset({'vertex', 'anthropic fallback', 'aistudio', 'direct'}) +_LLM_ROUTE_HEADERS = ('x-m1-llm-route', 'llm_provider-x-m1-llm-route') + +def _canonical_llm_route(value): + return value if isinstance(value, str) and value in _LLM_ROUTES else None + +def _llm_route_from_headers(headers): + if not isinstance(headers, dict): + return None + folded = {str(key).lower(): value for key, value in headers.items()} + for name in _LLM_ROUTE_HEADERS: + route = _canonical_llm_route(folded.get(name)) + if route is not None: + return route + return None + +def _llm_route_from_response(response): + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + route = _llm_route_from_headers(headers) + if route is not None: + return route + return _llm_route_from_headers(getattr(response, 'headers', None)) + +def _token_field_status(values, key): + if not isinstance(values, dict) or key not in values: + return 'missing' + value = values[key] + if value is None: + return 'null' + return 'valid' if type(value) is int and value >= 0 else 'invalid' + +def _gemini_capture(kwargs, model): + if not model.startswith('gemini/') or kwargs.get('stream') or kwargs.get('tools') or kwargs.get('functions'): + return (kwargs, None) + from litellm.integrations.custom_logger import CustomLogger + from urllib.parse import urlsplit + + class Capture(CustomLogger): + evidence = None + prompt_status = 'not_observed' + llm_route = None + + def log_post_api_call(self, kwargs, response_obj, start_time, end_time): + self.evidence = None + self.prompt_status = 'not_observed' + try: + params = kwargs.get('litellm_params') or {} + route = urlsplit(params.get('api_base') or '') + bare = model.removeprefix('gemini/') + gemini = params.get('custom_llm_provider') == 'gemini' + ai_studio = gemini and route.hostname == 'generativelanguage.googleapis.com' and (route.path in {'/' + version + '/models/' + bare + ':generateContent' for version in ('v1alpha', 'v1beta')}) + broker = urlsplit(os.environ.get('GEMINI_API_BASE') or '') + brokered = gemini and bool(broker.netloc) and (route.netloc == broker.netloc) and (broker.path.rstrip('/').rsplit('/', 1)[-1] in ('v1alpha', 'v1beta')) and (route.path == broker.path.rstrip('/') + '/models/' + bare + ':generateContent') + vertex = params.get('custom_llm_provider') == 'vertex_ai' and route.hostname == 'aiplatform.googleapis.com' and route.path.startswith('/v1/projects/') and route.path.endswith('/locations/global/publishers/google/models/' + bare + ':generateContent') + if route.scheme != 'https' or not (ai_studio or brokered or vertex) or kwargs.get('stream'): + return + self.llm_route = 'vertex' if vertex else 'aistudio' if ai_studio else None + raw = kwargs.get('original_response') + raw = json.loads(raw) if isinstance(raw, str) else raw + if not isinstance(raw, dict): + return + candidates = raw.get('candidates') + if not isinstance(candidates, list) or not candidates or any((not isinstance(c, dict) or not c.get('finishReason') for c in candidates)) or (not isinstance(raw.get('modelVersion'), str)) or (not raw['modelVersion']): + return + usage = raw.get('usageMetadata') + self.prompt_status = _token_field_status(usage, 'promptTokenCount') + if not isinstance(usage, dict): + return + fields = ('promptTokenCount', 'candidatesTokenCount', 'thoughtsTokenCount', 'cachedContentTokenCount', 'totalTokenCount', 'toolUsePromptTokenCount') + counts = {key: usage.get(key, 0) for key in fields} + if not {'promptTokenCount', 'totalTokenCount'} <= usage.keys() or any((type(n) is not int or n < 0 for n in counts.values())) or counts['toolUsePromptTokenCount'] != 0 or (counts['cachedContentTokenCount'] > counts['promptTokenCount']) or (counts['totalTokenCount'] != counts['promptTokenCount'] + counts['candidatesTokenCount'] + counts['thoughtsTokenCount']): + return + self.evidence = {'protocol': 'gemini-generate-content-' + ('vertex-v1' if vertex else route.path.split('/')[-3]), 'model_version': raw['modelVersion'], 'usage_metadata': {key: usage[key] for key in fields if key in usage}, 'defaulted_fields': [key for key in fields if key not in usage]} + except (TypeError, ValueError, AttributeError): + return + capture = Capture() + return ({**kwargs, 'callbacks': [*(kwargs.get('callbacks') or []), capture]}, capture) + +def _record_judge_usage(response, model: str, *, target: Path | None=None, native_usage: dict | None=None, native_prompt_status: str | None=None, llm_route: str | None=None) -> None: + import fcntl + from datetime import datetime, timezone + data = response.model_dump() if hasattr(response, 'model_dump') else response + usage = data.get('usage') if isinstance(data, dict) else None + granularity = data.get('usage_granularity') if isinstance(data, dict) else None + if not isinstance(usage, dict): + usage = {} + granularity = 'missing_provider_receipt' + prompt, completion = (usage.get('prompt_tokens'), usage.get('completion_tokens')) + native_fresh = usage.get('input_uncached_tokens') + prompt = prompt if type(prompt) is int and prompt >= 0 else None + native_fresh = native_fresh if type(native_fresh) is int and native_fresh >= 0 else None + if type(completion) is not int or completion < 0 or (prompt is None and native_fresh is None): + completion = completion if type(completion) is int and completion >= 0 else 0 + granularity = granularity or 'invalid_provider_receipt' + details = usage.get('prompt_tokens_details') + if details is not None and (not isinstance(details, dict)): + granularity = 'invalid_provider_receipt' + details = details if isinstance(details, dict) else {} + cached = details.get('cached_tokens') + if native_usage is not None: + native = native_usage['usage_metadata'] + native_output = native.get('candidatesTokenCount', 0) + native.get('thoughtsTokenCount', 0) + if prompt == native['promptTokenCount'] and completion == native_output: + cached = native.get('cachedContentTokenCount', 0) + else: + native_usage = None + written = next((value for value in (usage.get('input_cache_write_tokens'), usage.get('cache_creation_input_tokens'), details.get('cache_creation_tokens'), details.get('cache_write_tokens')) if value is not None), None) + invalid = any((value is not None and (type(value) is not int or value < 0) for value in (cached, written))) + cached = cached if type(cached) is int and cached >= 0 else None + written = written if type(written) is int and written >= 0 else None + fresh = native_fresh + if fresh is None and prompt is not None and (cached is not None) and (written is not None): + fresh = prompt - cached - written + if fresh is not None and (fresh < 0 or (prompt is not None and cached is not None and (written is not None) and (fresh + cached + written != prompt))): + invalid, fresh = (True, None) + provider, _, slug = model.partition('/') + event: dict = {'type': 'step_finish', 'part': {'providerID': provider if slug else 'openai', 'modelID': slug or model, 'tokens': {'input': fresh, 'output': completion, 'cache': {'read': cached, 'write': written}}}} + field_status = {'prompt_tokens': _token_field_status(usage, 'prompt_tokens'), 'completion_tokens': _token_field_status(usage, 'completion_tokens'), 'input_uncached_tokens': _token_field_status(usage, 'input_uncached_tokens')} + field_status['native_prompt_token_count'] = native_prompt_status if native_prompt_status in {'missing', 'null', 'invalid', 'valid', 'not_observed'} else 'unsupported' + part: dict = event['part'] + part['usage_field_status'] = field_status + if native_usage is not None: + event['part']['native_usage'] = native_usage + event['part']['token_categories_provenance'] = 'explicit_presence_v1' + if fresh is None and prompt is not None: + event['part']['prompt_tokens_inclusive'] = prompt + if invalid or any((value is None for value in (fresh, cached, written))): + granularity = granularity if granularity not in (None, 'request') else 'invalid_provider_receipt' if invalid else 'incomplete_token_categories' + if granularity: + event['part']['usage_granularity'] = granularity + if provider == 'openrouter': + cost = usage.get('cost') + if cost is None: + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + if isinstance(headers, dict): + cost = headers.get('llm_provider-x-litellm-response-cost') + if isinstance(cost, (int, float)) and (not isinstance(cost, bool)) and math.isfinite(cost) and (cost >= 0): + event['part']['cost'] = cost + data = data if isinstance(data, dict) else {} + if isinstance(data.get('id'), str) and data['id']: + event['part']['provider_request_id'] = data['id'] + for key in ('service_tier', 'cache_ttl'): + if data.get(key): + event['part'][key] = data[key] + route = _llm_route_from_response(response) or _canonical_llm_route(llm_route) + if route is not None: + event['part']['llm_route'] = route + created = data.get('created') + stamp = datetime.now(timezone.utc) + try: + if isinstance(created, str): + parsed = datetime.fromisoformat(created.replace('Z', '+00:00')) + if parsed.tzinfo is not None: + stamp = parsed + elif isinstance(created, (int, float)) and (not isinstance(created, bool)) and math.isfinite(created): + stamp = datetime.fromtimestamp(created, timezone.utc) + except (ValueError, OverflowError, OSError): + pass + pair = json.dumps({'type': 'step_start', 'timestamp': stamp.isoformat()}) + '\n' + pair += json.dumps(event) + '\n' + try: + receipt_path = target or Path(os.environ.get('M1_JUDGE_USAGE_PATH', '/logs/verifier/judge-trajectory.jsonl')) + receipt_path.parent.mkdir(parents=True, exist_ok=True) + with receipt_path.open('a') as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + handle.write(pair) + handle.flush() + os.fsync(handle.fileno()) + except OSError as exc: + if target is not None: + raise JudgeReceiptError(f'judge receipt write failed: {exc}') from exc + print(f'judge accounting: write failed ({type(exc).__name__})', file=sys.stderr) + +def openrouter_judge_pins() -> dict[str, dict]: + raw = os.environ.get('M1_OPENROUTER_JUDGE_PROVIDER_PINS', '').strip() + if not raw: + return {} + try: + pins = json.loads(raw) + except json.JSONDecodeError: + print('judge provider pins: invalid JSON in M1_OPENROUTER_JUDGE_PROVIDER_PINS', file=sys.stderr) + return {} + return {model: pin for model, pin in pins.items() if isinstance(pin, dict) and pin.get('order')} if isinstance(pins, dict) else {} + +def apply_judge_provider_pin(kwargs: dict, pins: dict[str, dict]) -> dict: + model = kwargs.get('model') + pin = pins.get(model) if isinstance(model, str) else None + if pin is None: + return kwargs + extra_body = dict(kwargs.get('extra_body') or {}) + provider = dict(extra_body.get('provider') or {}) + provider['order'] = list(pin['order']) + if pin.get('allow_fallbacks') is False: + provider['allow_fallbacks'] = False + if pin.get('zdr'): + provider['zdr'] = True + extra_body['provider'] = provider + return {**kwargs, 'extra_body': extra_body} +_TRANSIENT_ERROR_NAMES = ('RateLimitError', 'ServiceUnavailableError', 'InternalServerError', 'BadGatewayError', 'APIConnectionError') +_RETRYABLE_STATUS_CODES = frozenset({408, 409, 425, 429, 500, 502, 503, 504}) +_AUTH_ERROR_NAMES = ('AuthenticationError', 'PermissionDeniedError') +_AUTH_STATUS_CODES = frozenset({401, 403}) +_AUTH_RETRIES = 4 +_DEFAULT_TRANSIENT_RETRIES = 6 +_MAX_TRANSIENT_RETRIES = 20 +_MAX_RETRY_DELAY_SECONDS = 60.0 +_DEFAULT_EMPTY_RESPONSE_RETRIES = 3 +_DEFAULT_RETRY_BUDGET_SECONDS = 900.0 +_MAX_RETRY_BUDGET_SECONDS = 86400.0 + +def transient_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_TRANSIENT_RETRIES', '').strip() + if not raw: + return _DEFAULT_TRANSIENT_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_TRANSIENT_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_TRANSIENT_RETRIES + +def empty_response_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_EMPTY_RESPONSE_RETRIES', '').strip() + if not raw: + return _DEFAULT_EMPTY_RESPONSE_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_EMPTY_RESPONSE_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_EMPTY_RESPONSE_RETRIES + +def retry_budget_seconds() -> float: + raw = os.environ.get('M1_JUDGE_RETRY_BUDGET_SECONDS', '').strip() + if not raw: + return _DEFAULT_RETRY_BUDGET_SECONDS + try: + value = float(raw) + except ValueError: + value = math.nan + if not math.isfinite(value) or value < 0: + print('judge retries: invalid M1_JUDGE_RETRY_BUDGET_SECONDS, using the default', file=sys.stderr) + return _DEFAULT_RETRY_BUDGET_SECONDS + return min(value, _MAX_RETRY_BUDGET_SECONDS) + +def _within_budget(deadline: float, delay: float, model) -> bool: + remaining = deadline - time.monotonic() + if delay <= remaining: + return True + print(f'judge call retry budget spent: {model} would wait {delay:.1f}s with {max(remaining, 0.0):.1f}s left of M1_JUDGE_RETRY_BUDGET_SECONDS, failing now', file=sys.stderr) + return False + +def is_empty_verdict(response) -> bool: + data = response.model_dump() if hasattr(response, 'model_dump') else response + if not isinstance(data, dict): + return False + choices = data.get('choices') + if not isinstance(choices, list) or not choices: + return True + first = choices[0] + message = first.get('message') if isinstance(first, dict) else None + if not isinstance(message, dict): + return True + if message.get('tool_calls') or message.get('function_call'): + return False + content = message.get('content') + if isinstance(content, list): + content = ''.join((part.get('text') or '' for part in content if isinstance(part, dict))) + return not (isinstance(content, str) and content.strip()) + +def _matches(exc: BaseException, litellm, names: tuple[str, ...], statuses: frozenset[int]) -> bool: + classes = tuple((cls for cls in (getattr(litellm, name, None) for name in names) if isinstance(cls, type))) + if classes and isinstance(exc, classes): + return True + status = getattr(exc, 'status_code', None) + return type(status) is int and status in statuses + +def is_transient_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _TRANSIENT_ERROR_NAMES, _RETRYABLE_STATUS_CODES) + +def is_auth_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _AUTH_ERROR_NAMES, _AUTH_STATUS_CODES) + +def should_retry(exc: BaseException, litellm, attempt: int, limit: int) -> bool: + if attempt < limit and is_transient_error(exc, litellm): + return True + return attempt < min(limit, _AUTH_RETRIES) and is_auth_error(exc, litellm) + +def _retry_after_seconds(exc: BaseException) -> float | None: + headers = getattr(exc, 'headers', None) + if headers is None: + headers = getattr(getattr(exc, 'response', None), 'headers', None) + if headers is None: + return None + try: + raw = headers.get('retry-after') + if raw is None: + raw = headers.get('Retry-After') + value = float(raw) + except (AttributeError, TypeError, ValueError): + return None + return value if math.isfinite(value) and value >= 0 else None + +def retry_delay(exc: BaseException | None, attempt: int) -> float: + base = min(_MAX_RETRY_DELAY_SECONDS, 2.0 ** (attempt + 1)) + delay = base * (0.5 + random.random()) + retry_after = _retry_after_seconds(exc) if exc is not None else None + if retry_after is not None: + delay = max(delay, min(_MAX_RETRY_DELAY_SECONDS, retry_after)) + return delay + +def _note_retry(model, exc: BaseException, attempt: int, limit: int, delay: float) -> None: + status = getattr(exc, 'status_code', None) + print(f"judge call retry {attempt}/{limit}: {model} {type(exc).__name__} status={(status if type(status) is int else 'n/a')}, waiting {delay:.1f}s", file=sys.stderr) + +def _note_empty(model, response, attempt: int, limit: int, delay: float) -> None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + reason = None + if isinstance(data, dict) and isinstance(data.get('choices'), list) and data['choices']: + first = data['choices'][0] + reason = first.get('finish_reason') if isinstance(first, dict) else None + print(f'judge call retry {attempt}/{limit}: {model} empty verdict (finish_reason={reason}), waiting {delay:.1f}s', file=sys.stderr) + +def install(litellm, *, synchronous: bool=False) -> None: + pins = openrouter_judge_pins() + limit = transient_retry_limit() + empty_limit = empty_response_retry_limit() + deadline = time.monotonic() + retry_budget_seconds() + if synchronous: + original = litellm.completion + + def accounted(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = original(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + time.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + time.sleep(delay) + continue + return response + litellm.completion = accounted + return + original_async = litellm.acompletion + + async def accounted_async(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = await original_async(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + await asyncio.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + await asyncio.sleep(delay) + continue + return response + litellm.acompletion = accounted_async + +def record_agent_usage(attempt, *, model: str, provider: str) -> None: + records: dict[str, tuple[str, dict]] = {} + current_model = model + for filename in getattr(attempt, 'logs', []): + try: + with Path(filename).open() as stream: + for line in stream: + try: + event = json.loads(line) + except (ValueError, TypeError): + continue + if not isinstance(event, dict): + continue + message = event.get('message') or {} + if event.get('type') == 'assistant' and isinstance(message, dict) and isinstance(message.get('usage'), dict): + raw = message['usage'] + cached, written = (raw.get('cache_read_input_tokens'), raw.get('cache_creation_input_tokens')) + if all((type(value) is int and value >= 0 for value in (raw.get('input_tokens'), raw.get('output_tokens')))) and all((value is None or (type(value) is int and value >= 0) for value in (cached, written))): + receipt: dict = {'usage': {'input_uncached_tokens': raw['input_tokens'], 'prompt_tokens': raw['input_tokens'] + cached + written if cached is not None and written is not None else None, 'completion_tokens': raw['output_tokens'], 'prompt_tokens_details': {'cached_tokens': cached, 'cache_creation_tokens': written}}} + receipt['created'] = event.get('timestamp') + creation = raw.get('cache_creation') or {} + hour = creation.get('ephemeral_1h_input_tokens', 0) if isinstance(creation, dict) else 0 + if type(hour) is int and hour > 0: + if hour == written: + receipt['cache_ttl'] = '1h' + else: + receipt['usage_granularity'] = 'mixed_cache_ttl' + records[message.get('id') or json.dumps(raw, sort_keys=True)] = (message.get('model') or current_model, receipt) + payload = event.get('payload') or {} + if not isinstance(payload, dict): + continue + if event.get('type') == 'turn_context' and payload.get('model'): + current_model = payload['model'] + if event.get('type') == 'event_msg' and payload.get('type') == 'token_count': + info = payload.get('info') or {} + raw, total = (info.get('last_token_usage'), info.get('total_token_usage')) + if isinstance(raw, dict) and isinstance(total, dict) and all((type(raw.get(key)) is int and raw.get(key) >= 0 for key in ('input_tokens', 'output_tokens'))): + receipt = {'usage': {'prompt_tokens': raw.get('input_tokens'), 'input_uncached_tokens': raw.get('input_uncached_tokens'), 'input_cache_write_tokens': raw.get('input_cache_write_tokens'), 'completion_tokens': raw.get('output_tokens'), 'prompt_tokens_details': {'cached_tokens': raw.get('cached_input_tokens')}}} + receipt['created'] = event.get('timestamp') + records[json.dumps(total, sort_keys=True)] = (current_model, receipt) + except OSError: + continue + captured_input = captured_output = 0 + input_complete = True + for requested, receipt in records.values(): + requested = requested if '/' in requested else f'{provider}/{requested}' + _record_judge_usage(receipt, requested) + receipt_input = receipt['usage'].get('prompt_tokens') + if receipt_input is None: + input_complete = False + else: + captured_input += receipt_input + captured_output += receipt['usage'].get('completion_tokens') or 0 + total = getattr(attempt, 'usage', {}) or {} + if not records or (input_complete and total.get('input_tokens') != captured_input) or total.get('output_tokens') != captured_output: + _record_judge_usage({'usage': {'prompt_tokens': 0, 'completion_tokens': 0}, 'usage_granularity': 'incomplete_agent_receipts'}, model if '/' in model else f'{provider}/{model}') + +def install_rewardkit_agents() -> None: + import rewardkit.judges as judges + original = judges.get_agent + + def get_accounted_agent(judge, cwd=None): + backend = original(judge, cwd) + run = backend.run + + async def accounted_run(*args, **kwargs): + attempt = await run(*args, **kwargs) + record_agent_usage(attempt, model=judge.model or 'unknown', provider='anthropic' if judge.agent == 'claude-code' else 'openai') + return attempt + setattr(backend, 'run', accounted_run) + return backend + setattr(judges, 'get_agent', get_accounted_agent) +if __name__ == '__main__': + import litellm + if len(sys.argv) > 2 and sys.argv[1] == '--script': + import runpy + install(litellm, synchronous=True) + sys.argv = sys.argv[2:] + runpy.run_path(sys.argv[0], run_name='__main__') + else: + install(litellm) + install_rewardkit_agents() + if Path(__file__).with_name('m1_judge_panel.json').is_file(): + from m1_rewardkit_panel import install_panel + install_panel(Path(__file__).with_name('m1_judge_panel.json')) + if Path(__file__).with_name('m1_judge_jev.json').is_file(): + from m1_rewardkit_jev import install_jev + install_jev(Path(__file__).with_name('m1_judge_jev.json')) + from rewardkit.__main__ import main + main() diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/m1_rewardkit_panel.py b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/m1_rewardkit_panel.py new file mode 100644 index 0000000000000000000000000000000000000000..164cc2ae521cdd368c2e1749d7ed8fe09f4545eb --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/m1_rewardkit_panel.py @@ -0,0 +1,169 @@ +from __future__ import annotations +import asyncio +from contextvars import ContextVar +import json +import math +import os +import sys +from pathlib import Path +from typing import Any +import uuid +_request_audit: ContextVar[tuple[Path, list[str]] | None] = ContextVar('panel_request_audit', default=None) + +class PanelIncompleteError(RuntimeError): + pass + +def _audit_warning(exc: Exception, warnings: list[str]) -> None: + message = f'judge panel audit: diagnostic capture failed ({type(exc).__name__})' + if message not in warnings: + warnings.append(message) + print(message, file=sys.stderr) + +def _write_audit(path: Path, record: dict[str, Any], warnings: list[str], *, append: bool=False) -> None: + try: + text = json.dumps(record, allow_nan=False, default=str) + '\n' + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('a' if append else 'w') as stream: + stream.write(text) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + +def _binary(raw: Any) -> int: + if isinstance(raw, bool): + return int(raw) + if isinstance(raw, int | float) and math.isfinite(raw) and (raw in (0, 1)): + return int(raw) + if isinstance(raw, str): + value = raw.strip().lower() + if value in {'yes', 'true', '1'}: + return 1 + if value in {'no', 'false', '0'}: + return 0 + raise PanelIncompleteError('m1_judge_panel_incomplete: invalid binary vote') + +def validate_votes(scores: list[Any], criteria: list[Any]) -> None: + names = [criterion.name for criterion in criteria] + if len(set(names)) != len(names) or [score.name for score in scores] != names: + raise PanelIncompleteError('m1_judge_panel_incomplete: criterion membership mismatch') + for score, criterion in zip(scores, criteria, strict=True): + if score.error: + raise PanelIncompleteError('m1_judge_panel_incomplete: judge returned an error') + raw = _binary(score.raw) + expected = 1 - raw if criterion.negate else raw + if not math.isfinite(score.value) or score.value != expected: + raise PanelIncompleteError('m1_judge_panel_incomplete: inconsistent binary score') + +async def run_panel(judge: Any, criteria: list[Any], weights: list[float] | None, system_prompt: str | None, *, config: dict[str, Any], run_llm: Any, score_type: Any, audit_dir: Path) -> tuple[list[Any], str, list[str]]: + from rewardkit.models import Binary + if not criteria or any((not isinstance(criterion.output_format, Binary) for criterion in criteria)): + raise ValueError('panel majority voting requires nonempty binary criteria') + group_dir = audit_dir / uuid.uuid4().hex + warnings_out: list[str] = [] + + async def member_call(index: int, member: dict[str, Any]): + member_judge = judge.model_copy(update=member) + evidence: dict[str, Any] = {'member': index + 1, 'judge': member, 'criteria': [criterion.name for criterion in criteria], 'status': 'started'} + path = group_dir / f'judge-{index + 1}.json' + _write_audit(path, evidence, warnings_out) + token = _request_audit.set((group_dir / f'judge-{index + 1}-requests.jsonl', warnings_out)) + try: + scores, output, warnings = await run_llm(member_judge, criteria, weights, system_prompt) + evidence.update(output=output, warnings=warnings) + validate_votes(scores, criteria) + evidence['scores'] = [score.to_dict() for score in scores] + evidence['status'] = 'completed' + return (scores, output, warnings) + except BaseException as exc: + evidence.update(status='failed', error_class=type(exc).__name__) + if isinstance(exc, PanelIncompleteError): + evidence['error'] = str(exc) + raise + finally: + _request_audit.reset(token) + _write_audit(path, evidence, warnings_out) + outcomes = await asyncio.gather(*(member_call(index, member) for index, member in enumerate(config['members'])), return_exceptions=True) + failed = [index + 1 for index, result in enumerate(outcomes) if isinstance(result, BaseException)] + if failed: + _write_audit(group_dir / 'panel.json', {'status': 'incomplete', 'failed_members': failed}, warnings_out) + raise PanelIncompleteError(f'm1_judge_panel_incomplete: failed members {failed}; see panel audit artifacts') + completed = [outcome for outcome in outcomes if not isinstance(outcome, BaseException)] + combined = [] + for index, criterion in enumerate(criteria): + votes = [{'judge': config['members'][member_index], **outcome[0][index].to_dict()} for member_index, outcome in enumerate(completed)] + passes = sum((vote['value'] == 1 for vote in votes)) + value = int(passes >= 2) + combined.append(score_type(name=criterion.name, value=value, raw=bool(1 - value if criterion.negate else value), weight=weights[index] if weights is not None else 1.0, reasoning=f'{passes}/3 judges passed; strict majority requires 2/3.', description=criterion.description, id=criterion.id, negate=criterion.negate, optional=criterion.optional, votes=votes)) + for outcome in completed: + warnings_out.extend(outcome[2]) + audit = {'status': 'completed', 'mode': 'panel', 'aggregation': 'majority', 'required_votes': 2, 'members': config['members'], 'criteria': [score.to_dict() for score in combined]} + output = json.dumps(audit, indent=2, allow_nan=False) + _write_audit(group_dir / 'panel.json', audit, warnings_out) + return (combined, output, warnings_out) + +def install_panel(config_path: Path, *, audit_dir: Path=Path('/logs/verifier/judge-panel')) -> None: + import rewardkit.judges as judges + import rewardkit.reward as reward + from rewardkit.models import LLMJudge, Score + import litellm + config = json.loads(config_path.read_text()) + members = config.get('members') + concurrency = config.get('max_concurrent_llm') + if config.get('mode') != 'panel' or not isinstance(members, list) or len(members) != 3 or (len({member['model'] for member in members}) != 3) or (type(concurrency) is not int) or (not 1 <= concurrency <= 64): + raise ValueError('invalid materialized panel configuration') + if os.environ.get('REWARDKIT_JUDGE') or os.environ.get('REWARDKIT_MODEL'): + raise ValueError('RewardKit environment overrides cannot replace a frozen panel') + + class PanelScore(Score): + votes: list[dict[str, Any]] + + def to_dict(self): + return {**super().to_dict(), 'votes': self.votes} + original_llm = judges.arun_llm + original_call = judges._arun_llm_call + original_details = reward.Reward.to_detail_dict + original_completion = litellm.acompletion + active_loop = None + semaphore = None + + async def captured_completion(*args, **kwargs): + context = _request_audit.get() + record = {'requested_model': kwargs.get('model')} + response = None + try: + response = await original_completion(*args, **kwargs) + return response + except BaseException as exc: + record['error_class'] = type(exc).__name__ + raise + finally: + if context is not None: + path, warnings = context + try: + if response is not None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + record.update(response_model=data.get('model'), choices=data.get('choices')) + _write_audit(path, record, warnings, append=True) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + + async def bounded_call(*args, **kwargs): + nonlocal active_loop, semaphore + loop = asyncio.get_running_loop() + if active_loop is not loop: + active_loop, semaphore = (loop, asyncio.Semaphore(concurrency)) + assert semaphore is not None + async with semaphore: + return await original_call(*args, **kwargs) + + async def panel_call(judge, criteria, weights=None, system_prompt=None): + return await run_panel(judge, criteria, weights, system_prompt, config=config, run_llm=original_llm, score_type=PanelScore, audit_dir=audit_dir) + + def panel_details(self, score): + detail = original_details(self, score) + if isinstance(self.judge, LLMJudge): + detail.update(kind='llm_panel', judge=config, aggregation='majority', required_votes=2) + return detail + setattr(reward, 'arun_llm', panel_call) + setattr(judges, '_arun_llm_call', bounded_call) + setattr(litellm, 'acompletion', captured_completion) + reward.Reward.to_detail_dict = panel_details diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/normalize_reward.py b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/normalize_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..91817ef00ea9152ca57f0030d8e879eb850ddff0 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/normalize_reward.py @@ -0,0 +1,71 @@ +from __future__ import annotations +import argparse +import json +from pathlib import Path +from typing import Any + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument('--raw-details', required=True) + parser.add_argument('--rubric', required=True) + parser.add_argument('--reward-out', required=True) + parser.add_argument('--details-out', required=True) + args = parser.parse_args() + raw_details = _load_json(Path(args.raw_details)) + rubric = _load_json(Path(args.rubric)) + criteria = rubric['criteria'] + raw_by_name = _raw_criteria_by_name(raw_details) + positive_total = sum((float(item['score']) for item in criteria if float(item['score']) > 0)) + if positive_total <= 0: + raise ValueError('rubric must contain at least one positive score') + earned = 0.0 + normalized_criteria: list[dict[str, Any]] = [] + for item in criteria: + signed_score = float(item['score']) + raw = raw_by_name.get(item['name'], {}) + value = _coerce_score(raw.get('value', 0.0)) + contribution = value * signed_score + earned += contribution + normalized_criteria.append({'name': item['name'], 'value': value, 'raw': raw.get('raw'), 'weight': signed_score, 'signed_score': signed_score, 'polarity': item['polarity'], 'contribution': contribution, 'description': item['description'], 'source': item.get('source', ''), 'justification': item.get('justification', ''), 'metadata': item.get('metadata', {}), 'reasoning': raw.get('reasoning'), 'judge_reasoning': raw.get('reasoning'), 'judge_error': raw.get('error'), **({'votes': raw['votes']} if 'votes' in raw else {})}) + unclamped = earned / positive_total + reward = max(0.0, min(1.0, unclamped)) + reward_out = {'correctness': reward} + details_out = {'correctness': {'score': reward, 'kind': 'signed_score', 'criteria': normalized_criteria, 'aggregation': {'method': 'signed_score_ratio_clamped', 'earned': earned, 'positive_total': positive_total, 'unclamped': unclamped, 'clamped': reward}, 'raw_rewardkit': raw_details}} + _write_json(Path(args.reward_out), reward_out) + _write_json(Path(args.details_out), details_out) + +def _load_json(path: Path) -> Any: + return json.loads(path.read_text()) + +def _write_json(path: Path, data: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data, indent=2) + '\n') + +def _raw_criteria_by_name(details: dict[str, Any]) -> dict[str, dict[str, Any]]: + out: dict[str, dict[str, Any]] = {} + for reward in details.values(): + for item in _iter_raw_criteria(reward): + name = item.get('name') + if isinstance(name, str): + out[name] = item + return out + +def _iter_raw_criteria(value: Any): + if isinstance(value, list): + for item in value: + yield from _iter_raw_criteria(item) + return + if not isinstance(value, dict): + return + for item in value.get('criteria') or []: + if isinstance(item, dict): + yield item + +def _coerce_score(value: Any) -> float: + if isinstance(value, bool): + return 1.0 if value else 0.0 + if isinstance(value, int | float): + return max(0.0, min(1.0, float(value))) + return 0.0 +if __name__ == '__main__': + main() diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/agent_prompt.md b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/agent_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..ca489c065bafd5d10e764f033c9dfd1195933db3 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/agent_prompt.md @@ -0,0 +1,10 @@ +You are grading the submitted legal analysis against the criteria below. + +Read `/logs/artifacts/answer.md`, the answer captured by the verifier, before +assigning any scores. Evaluate that file as the submission. Other files in +`/app` may supply context, but must not replace the submitted answer. Do not +modify the submission. If it is missing or empty, state that in your reasoning +and apply the criteria to that missing or empty submission. Preserve each +criterion's stated positive or penalty polarity. + +{criteria} diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_1.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_1.toml new file mode 100644 index 0000000000000000000000000000000000000000..dd1bc33fc3bb726dc33720ea984dadbbef0416f8 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_1.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_1" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in Assignment #1that the Defendants motion was supported by two affidavits which was absent in Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995)." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_10.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_10.toml new file mode 100644 index 0000000000000000000000000000000000000000..8b5c2a875679c46b61f6fa93d17210aa8bedb405 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_10.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_10" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in Assignment #1 that Plaintiff, Sara Davis should file an affidavit establishing her residence outside of DuPage County." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_11.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_11.toml new file mode 100644 index 0000000000000000000000000000000000000000..b3ef8335fb2596aca9d6fd10e2c246d1837f3268 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_11.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_11" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in Assignment #1 that Plaintiff, Sara Davis should file an affidavit that it would be inconvenient to proceed with this litigation in DuPage County." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_12.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_12.toml new file mode 100644 index 0000000000000000000000000000000000000000..6e5819f53bd3eab91541f000e90aacfef1c362c4 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_12.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_12" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions in Assignment #1 that 5 of the Cook County Hospital Doctors who provided care to Baby Davis are located within Cook County." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_13.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_13.toml new file mode 100644 index 0000000000000000000000000000000000000000..a00d062abedd8f8d77f70d6c964a15c395a85d29 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_13.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_13" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in Assignment #1 that Plaintiff should obtain affidavits from the 5 Cook County Hospital Doctors who provided care to Baby Davis that it would be inconvenient for them to testify in DuPage County." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_15.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_15.toml new file mode 100644 index 0000000000000000000000000000000000000000..ede36bada3c831f9cf0b875ecd061824725aed13 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_15.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_15" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies in Assignment #1 that the medical records from Cook County Hospital are important for the analysis of the Plaintiff’s survival action." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_16.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_16.toml new file mode 100644 index 0000000000000000000000000000000000000000..6aea27c37c652e5bed370e4c3b0a58f4f5274ae4 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_16.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_16" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in Assignment #1 that the medical records from Cook County Hospital are relevant for the analysis of the Plaintiff’s wrongful death claim." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_17.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_17.toml new file mode 100644 index 0000000000000000000000000000000000000000..53005414dd7f9070c30802498c80c24bf65d81f2 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_17.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_17" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions in Assignment #1 that Defendants have provided no evidentiary basis regarding the burden of the compulsory process for attendance of witnesses." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_18.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_18.toml new file mode 100644 index 0000000000000000000000000000000000000000..d1ee52ef6cf61830eefcd31e98a6f2b1cd01346f --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_18.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_18" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions in Assignment #1 that we live in a smaller world, we are connected by interstate highways, bustling airways, today, convenience - the touchstone of the forum non conveniens doctrine has a different meaning, under Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006)." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_19.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_19.toml new file mode 100644 index 0000000000000000000000000000000000000000..f6b37038882e3f0ea7a7a73d9d783019ae3a2be4 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_19.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_19" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies in Assignment #1 that the Defendants have distinguished First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002) where potential witnesses resided in multiple counties." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_2.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_2.toml new file mode 100644 index 0000000000000000000000000000000000000000..5dea72f0f9a48785a57b7127e4e708786746921f --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_2.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_2" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies in Assignment #1 an affidavit by John Smith, M.D. does not indicate that Cook County would be an inconvenient forum for him to litigate this case as required under Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006)." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_20.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_20.toml new file mode 100644 index 0000000000000000000000000000000000000000..93a0b0345d261ee3f9ef6ef7dae804e0f57f0ce6 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_20.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_20" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies in Assignment #1 that the Defendants have distinguished Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006) where potential witnesses resided in multiple counties" +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_21.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_21.toml new file mode 100644 index 0000000000000000000000000000000000000000..8832d5aca68ba23856dd1761292cd49209681e5b --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_21.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_21" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in Assignment #1 that Cook County has an interest in this litigation because the decedent died in Cook County, under Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995)." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_22.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_22.toml new file mode 100644 index 0000000000000000000000000000000000000000..2dbad9a0a4dc625c1c6c473ae06b4e847f1aee3a --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_22.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_22" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: Mentions in Assignment #1 that Cook County lacks interest in adjudicating a controversy over care rendered by its DuPage based providers." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_23.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_23.toml new file mode 100644 index 0000000000000000000000000000000000000000..b008550b8dbb04676d5fd49752d5b8710e554dff --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_23.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_23" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies in Assignment #1 that Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) treated the location of death alone as sufficient to give Cook County a genuine interest in the litigation." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_24.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_24.toml new file mode 100644 index 0000000000000000000000000000000000000000..7213142a0fde9d4b8c42fd25981ca540970eee81 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_24.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_24" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in Assignment #1 that court congestion is a relatively insignificant factor, especially where the record does not show the other forum would resolve the case more quickly, under First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002)." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_25.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_25.toml new file mode 100644 index 0000000000000000000000000000000000000000..d5ba8fda2d12a462cc0f02307de04488433145ba --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_25.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_25" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: Mentions in Assignment #1 that Cook County’s overall clearance rate is 60.5%." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_26.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_26.toml new file mode 100644 index 0000000000000000000000000000000000000000..341882a3da554356884ef50d623c07688acf2440 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_26.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_26" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies in Assignment #1 that in the overall Civil Category, Cook County had a clearance rate of 97.9%." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_27.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_27.toml new file mode 100644 index 0000000000000000000000000000000000000000..d600ba9bc2dcf501ba8e1e63c003826d5d555bb4 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_27.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_27" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in Assignment #1 that in the overall Civil Category, the 18th Judicial Circuit had a clearance rate of 96.3%." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_28.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_28.toml new file mode 100644 index 0000000000000000000000000000000000000000..ced8c4d8bf1e0febbb5a9189ae0e5d37e16484d3 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_28.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_28" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in Assignment #1 that the Defendants cannot supply information regarding the time lapse for civil cases in excess of $50,000.00 because Cook County did not report information in 2023." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_29.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_29.toml new file mode 100644 index 0000000000000000000000000000000000000000..c72f361ad377ec670beabde4436fe411b1d564df --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_29.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_29" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in Assignment #1 that the Defendants have provided no evidence to show that DuPage County will resolve the case more quickly than Cook County." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_3.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_3.toml new file mode 100644 index 0000000000000000000000000000000000000000..c9ef4f2657228dda362c2fc734842248cadab63f --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_3.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_3" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies in Assignment #1 an affidavit by Safe Hospital representative does not indicate that Cook County would be an inconvenient forum for them to litigate this case as required under Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006)." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_30.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_30.toml new file mode 100644 index 0000000000000000000000000000000000000000..df5bd5cba4df19c2bcaab045b4f448e3f7992555 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_30.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_30" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in Assignment #1 that the burden is on the movant to show that the balance of public interest factors with all other factors, strongly favors the proposed forum under Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006)." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_4.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_4.toml new file mode 100644 index 0000000000000000000000000000000000000000..7d00e5abbda220349cb467719d23d12e3bcec774 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_4.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_4" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in Assignment #1 that the burden is on the movant to show that the balance of private interest factors with all other factors, strongly favors the proposed forum, under Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006)." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_5.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_5.toml new file mode 100644 index 0000000000000000000000000000000000000000..fefdbe2581445eb5eaaa14831939ff231ce0e0dc --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_5.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_5" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions in Assignment #1 that the plaintiff’s interest in choosing the forum receives less deference when the plaintiff’s residence is located outside the chosen forum, under Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006)." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_6.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_6.toml new file mode 100644 index 0000000000000000000000000000000000000000..048b53cdc08a5f251d9f30e1404b2372fe77928a --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_6.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_6" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies in Assignment #1 that in Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006) the reviewing court affirmed the denial of transfer even though the plaintiff’s residence was outside the chosen forum." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_7.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_7.toml new file mode 100644 index 0000000000000000000000000000000000000000..44c238661b9c090ec539c6b57e3f39590eca24dd --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_7.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_7" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies in Assignment #1 that in Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 the reviewing court affirmed the denial of transfer even though the plaintiff failed to establish residency in the chosen forum." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_8.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_8.toml new file mode 100644 index 0000000000000000000000000000000000000000..74b02f83e85c6afa27aaf05604acc578b092bbd7 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_8.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_8" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies in Assignment #1 that in First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002) the reviewing court reversed a grant of transfer even though the plaintiff’s residence was outside the chosen forum." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_9.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_9.toml new file mode 100644 index 0000000000000000000000000000000000000000..bfb4cbc4917115f727044103409368ca98341696 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/raw_correctness/criterion_9.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_9" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions in Assignment #1 that Plaintiff, Sara Davis’ residence is unknown by the Defendant in its analysis for the motion to transfer." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/test.sh b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..66a509a7bcdbe412851f3a012a5ba7b16cf0925b --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/tests/test.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +set -euo pipefail + +mkdir -p /logs/artifacts /logs/verifier/raw + +python3 - <<'PYEOF' +import json +import shutil +from pathlib import Path + + +def has_text(path: Path) -> bool: + return path.exists() and path.is_file() and bool(path.read_text(errors="replace").strip()) + + +def fallback_paths(answer_path: Path) -> list[Path]: + paths = [] + try: + relative = answer_path.relative_to("/app") + paths.append(Path("/app/app") / relative) + except ValueError: + pass + return [path for path in paths if path != answer_path] + + +config = json.loads(Path("/tests/fixtures/config.json").read_text()) +answer_path = Path(config["answer_path"]) +artifact_answer = Path("/logs/artifacts/answer.md") +artifact_answer.parent.mkdir(parents=True, exist_ok=True) +if has_text(answer_path): + shutil.copyfile(answer_path, artifact_answer) +else: + for candidate in fallback_paths(answer_path): + if has_text(candidate): + shutil.copyfile(candidate, artifact_answer) + break + else: + artifact_answer.write_text("") + +# Harbor collects /logs/artifacts when the agent step ends, which is before this +# script runs, so the copy above never reaches the uploaded artifacts. /logs/verifier +# is uploaded after the verifier phase, so persist the graded answer there too. +verifier_answer = Path("/logs/verifier/answer.md") +verifier_answer.parent.mkdir(parents=True, exist_ok=True) +shutil.copyfile(artifact_answer, verifier_answer) +PYEOF + +uv run --no-project --with 'harbor-rewardkit[all]==0.2.0' python /tests/m1_rewardkit_accounting.py /tests/raw_correctness \ + --workspace /app \ + --output /logs/verifier/raw/reward.json \ + --max-concurrent-llm "${MAX_CONCURRENT_LLM:-4}" \ + --max-concurrent-agent "${M1_MAX_CONCURRENT_AGENT:-1}" + +python /tests/normalize_reward.py \ + --raw-details /logs/verifier/raw/reward-details.json \ + --rubric /tests/fixtures/rubric.json \ + --reward-out /logs/verifier/reward.json \ + --details-out /logs/verifier/reward-details.json diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/workdir/attachments/2023 Annual Report Statistical Summary.pdf b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/workdir/attachments/2023 Annual Report Statistical Summary.pdf new file mode 100644 index 0000000000000000000000000000000000000000..fa4e9d236dd952e3dddc6f532e23a961682b4c6e --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/workdir/attachments/2023 Annual Report Statistical Summary.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8bf34637f28292c0009d408c050124904a8b01111e5020c21ed707d781fd0496 +size 12962846 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/workdir/attachments/Bradbury v. St. Mary's Hospital.pdf b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/workdir/attachments/Bradbury v. St. Mary's Hospital.pdf new file mode 100644 index 0000000000000000000000000000000000000000..2e674eeee065ae4fda7c1470cc78f141eb8bcfe8 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/workdir/attachments/Bradbury v. St. Mary's Hospital.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b5dd36efa5bd84c7fbe31bdbb478817c22500d48e64b24257915e17f6bb5f2a0 +size 572611 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/workdir/attachments/Davis Complaint.docx b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/workdir/attachments/Davis Complaint.docx new file mode 100644 index 0000000000000000000000000000000000000000..422bb8fea94f9a850aa9ee2be513ae586311d2dc Binary files /dev/null and b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/workdir/attachments/Davis Complaint.docx differ diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/workdir/attachments/Defendants Motion to Transfer.pdf b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/workdir/attachments/Defendants Motion to Transfer.pdf new file mode 100644 index 0000000000000000000000000000000000000000..626d4259e34adc22ed9a051cfe6966bdc87fb99f --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/workdir/attachments/Defendants Motion to Transfer.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:54da66d335b9c7a920d8a49fdd49a565244563734b04b01927582170b5f2aadc +size 832692 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/workdir/attachments/First Am Bank v. Guerine.pdf b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/workdir/attachments/First Am Bank v. Guerine.pdf new file mode 100644 index 0000000000000000000000000000000000000000..c0bd2f36bb879d24de686696dc9140cc60c5fbbb --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/workdir/attachments/First Am Bank v. Guerine.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f8a188b924402eeed7075cbb2d4a2a55bc16b75abdf586206e8b470920f3979a +size 498833 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/workdir/attachments/Langenhorst v. Norfolk Southern.pdf b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/workdir/attachments/Langenhorst v. Norfolk Southern.pdf new file mode 100644 index 0000000000000000000000000000000000000000..067db080672db11c40bb312194a28dc4bf2eb190 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-1/workdir/attachments/Langenhorst v. Norfolk Southern.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:371eb4caa533accf4e6ee180efae95d0e65a563add28df93bcb98e27ae55c5b9 +size 573433 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/instruction.md b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..79cd7ffba629564c92f8118163c8f839b6b43dc3 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/instruction.md @@ -0,0 +1,68 @@ +# Plaintiff's Response - Forum Non Conveniens — Assignment 2 + +You are a senior legal analyst operating autonomously. You are completing a multi-step legal reasoning task. Follow the role, factual record, instructions, and deliverable requirements provided in the Task and each Assignment. + +Each Assignment may require a different legal deliverable. Follow the requirements specific to that Assignment. + +## Word limits for court briefs + +- A brief in support of or in response to a motion may not exceed **8,750 words**. +- A reply brief may not exceed **3,500 words**. +- For a motion for reconsideration, a brief in support of or in response to the motion may not exceed **3,500 words**, and a reply brief may not exceed **1,750 words**. +- If an Assignment specifies a stricter word limit, follow the stricter limit. + +These word limits do not apply to legal memoranda or other non-court-filing deliverables unless the Assignment expressly provides otherwise. + +Complete the task end-to-end without asking for confirmation, permission, or clarification. + +Use the uploaded matter documents in `/app/attachments/` as your primary case file. You also have internet access via OpenCode's `websearch` tool; use it to research any statutes, regulations, cases, administrative guidance, or secondary authorities that are not supplied as attachments. Cite any authority you rely on in the format requested by the prompt. + +For document inspection: +- PDF: `pdftotext /app/attachments/.pdf -` +- DOCX: `pandoc /app/attachments/.docx -t markdown` +- XLSX/CSV: use Python with `openpyxl` or `pandas` +- If extraction is unreliable, inspect the raw file with Python libraries or convert/render the relevant pages. + +Write the final complete legal deliverable for this assignment to `/app/response2.md`. The verifier reads only that file. + +This is a follow-on assignment. The documents from the previous assignment(s) remain available in `/app/attachments/`, and your prior deliverable `/app/response1.md` is also on disk. Build on that analysis as the prompt directs. + +## Attachments + +- `/app/attachments/2023 Annual Report Statistical Summary.pdf` +- `/app/attachments/Bradbury v. St. Mary's Hospital.pdf` +- `/app/attachments/Davis Complaint.docx` +- `/app/attachments/Defendants Motion to Transfer.pdf` +- `/app/attachments/First Am Bank v. Guerine.pdf` +- `/app/attachments/Langenhorst v. Norfolk Southern.pdf` + + +## Prompt + +To: Quinn Vivero +From: James Rogers +Re: Davis v. Smith, Forum Non Conveniens – Response Brief +Date: 7/20/2026 + +Mr. Vivero, + +Thank you for the information you provided to me following your review of the Defendant’s motion to transfer pursuant to forum non conveniens. As I reviewed the information, I think that the best argument that we have is that the burden is on the defendants to show that relevant private and public interest factors “strongly favor� the defendant's choice of forum to warrant disturbing plaintiff’s choice. Given the notes you made, while the Defendants do have some arguments, I do not believe they’ve satisfied their burden. + +For Assignment #2, please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens. Please include all affidavits and information you referenced from Assignment #1. + +The names of the physicians from Cook County we have spoken to are: + +• Liam Vance +• Savannah Brooks +• Caleb Montgomery +• Maya Linwood +• Garrett Hayes + +Be sure to limit your review to the documents provided in Assignment #1. Do not rely on, reference, or infer any legal authority, factual information, or data beyond what is contained in these uploaded files. If a document is not uploaded, it does not exist for purposes of this analysis. All citations must reference the document by its exact name as listed below, followed by the page and paragraph number. Do not cite to external websites, databases, or any source outside the uploaded materials. + +Defendants Motion to Transfer.pdf +Davis Complaint.docx +Bradbury v. St. Mary’s Hospital.pdf +First Am Bank v. Guerine.pdf +Langenhorst v. Norfolk Southern.pdf +2023 Annual Report Statistical Summary.pdf diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/solution/solve.sh b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7710414a6da6d0ad740717c8c85a9af850d5da33 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/solution/solve.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# No oracle solution ships with LegalReasonBench. The verifier grades the +# agent's own legal deliverable for this assignment against the rubric. +echo "no oracle solution" diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/fixtures/config.json b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/fixtures/config.json new file mode 100644 index 0000000000000000000000000000000000000000..71bb010624b34f82246753b2ee1fb8eccd380fb0 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/fixtures/config.json @@ -0,0 +1,318 @@ +{ + "task_id": "lrb-forum-non-conveniens-response", + "title": "Plaintiff's Response - Forum Non Conveniens", + "domain": "", + "matter": "", + "judge": { + "max_concurrent_llm": 12, + "mode": "panel", + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ], + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + "step_index": 2, + "step_name": "assignment-2", + "step_title": "", + "prompt": "To: Quinn Vivero\nFrom: James Rogers\nRe: Davis v. Smith, Forum Non Conveniens \u2013 Response Brief\nDate: 7/20/2026\n\nMr. Vivero,\n\nThank you for the information you provided to me following your review of the Defendant\u2019s motion to transfer pursuant to forum non conveniens. As I reviewed the information, I think that the best argument that we have is that the burden is on the defendants to show that relevant private and public interest factors \u201cstrongly favor\u201d the defendant's choice of forum to warrant disturbing plaintiff\u2019s choice. Given the notes you made, while the Defendants do have some arguments, I do not believe they\u2019ve satisfied their burden. \n\nFor Assignment #2, please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens. Please include all affidavits and information you referenced from Assignment #1. \n\nThe names of the physicians from Cook County we have spoken to are: \n\n\u2022 Liam Vance\n\u2022 Savannah Brooks\n\u2022 Caleb Montgomery\n\u2022 Maya Linwood\n\u2022 Garrett Hayes\n\nBe sure to limit your review to the documents provided in Assignment #1. Do not rely on, reference, or infer any legal authority, factual information, or data beyond what is contained in these uploaded files. If a document is not uploaded, it does not exist for purposes of this analysis. All citations must reference the document by its exact name as listed below, followed by the page and paragraph number. Do not cite to external websites, databases, or any source outside the uploaded materials.\n\nDefendants Motion to Transfer.pdf\nDavis Complaint.docx\nBradbury v. St. Mary\u2019s Hospital.pdf\nFirst Am Bank v. Guerine.pdf\nLangenhorst v. Norfolk Southern.pdf\n2023 Annual Report Statistical Summary.pdf", + "attachments": [ + { + "filename": "2023 Annual Report Statistical Summary.pdf", + "description": "", + "metadata": {}, + "path": "/app/attachments/2023 Annual Report Statistical Summary.pdf" + }, + { + "filename": "Bradbury v. St. Mary's Hospital.pdf", + "description": "", + "metadata": {}, + "path": "/app/attachments/Bradbury v. St. Mary's Hospital.pdf" + }, + { + "filename": "Davis Complaint.docx", + "description": "", + "metadata": {}, + "path": "/app/attachments/Davis Complaint.docx" + }, + { + "filename": "Defendants Motion to Transfer.pdf", + "description": "", + "metadata": {}, + "path": "/app/attachments/Defendants Motion to Transfer.pdf" + }, + { + "filename": "First Am Bank v. Guerine.pdf", + "description": "", + "metadata": {}, + "path": "/app/attachments/First Am Bank v. Guerine.pdf" + }, + { + "filename": "Langenhorst v. Norfolk Southern.pdf", + "description": "", + "metadata": {}, + "path": "/app/attachments/Langenhorst v. Norfolk Southern.pdf" + } + ], + "rubric": [ + { + "name": "criterion_1", + "description": "States in Assignment #2 that the response is supported by the affidavit of Liam Vance, a physician who provided care to Baby Davis at Cook County Hospital.", + "source": "Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) (Bradbury v. St. Mary\u2019s Hospital.pdf at p.3).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_2", + "description": "States in Assignment #2 that the response is supported by the affidavit of Savannah Brooks, a physician who provided care to Baby Davis at Cook County Hospital.", + "source": "Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) (Bradbury v. St. Mary\u2019s Hospital.pdf at p.3).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_3", + "description": "States in Assignment #2 that the response is supported by the affidavit of Caleb Montgomery, a physician who provided care to Baby Davis at Cook County Hospital.", + "source": "Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) (Bradbury v. St. Mary\u2019s Hospital.pdf at p.3).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_4", + "description": "States in Assignment #2 that the response is supported by the affidavit of Maya Linwood, a physician who provided care to Baby Davis at Cook County Hospital.", + "source": "Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) (Bradbury v. St. Mary\u2019s Hospital.pdf at p.3).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_5", + "description": "States in Assignment #2 that the response is supported by the affidavit of Garrett Hayes, a physician who provided care to Baby Davis at Cook County Hospital.", + "source": "Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) (Bradbury v. St. Mary\u2019s Hospital.pdf at p.3).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_6", + "description": "Identifies in Assignment #2 that the affidavit by Liam Vance indicates that DuPage County would be an inconvenient forum for him to litigate this case as required under Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006).", + "source": "Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.10).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_7", + "description": "Identifies in Assignment #2 that the affidavit by Savannah Brooks indicates that DuPage County would be an inconvenient forum for her to litigate this case as required under Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006).", + "source": "Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.10).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_8", + "description": "Identifies in Assignment #2 that the affidavit by Caleb Montgomery indicates that DuPage County would be an inconvenient forum for him to litigate this case as required under Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006).", + "source": "Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.10).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_9", + "description": "Identifies in Assignment #2 that the affidavit by Maya Linwood indicates that DuPage County would be an inconvenient forum for her to litigate this case as required under Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006).", + "source": "Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.10).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_10", + "description": "Identifies in Assignment #2 that the affidavit by Garrett Hayes indicates that DuPage County would be an inconvenient forum for him to litigate this case as required under Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006).", + "source": "Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.10).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_11", + "description": "States in Assignment #2 that the response is supported by the affidavit of the plaintiff, Sara Davis.", + "source": "Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) (Bradbury v. St. Mary\u2019s Hospital.pdf at p.3).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_12", + "description": "Identifies in Assignment #2 that the affidavit by the Plaintiff, Sara Davis, indicates that DuPage County would be an inconvenient forum for her to litigate this case as required under Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006).", + "source": "Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.10).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_13", + "description": "Mentions in Assignment #2 that the forum non conveniens doctrine gives courts discretionary power that should be exercised only in exceptional circumstances when the interests of justice require a trial in a more convenient forum under Langenhorst v. Norfolk S. Ry. Co., 219 Ill.2d 430 (2006).", + "source": "Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.6).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_14", + "description": "Mentions in Assignment #2 that the test is whether the relevant factors, viewed in their totality, strongly favor transfer to the forum suggested by defendant under First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002).", + "source": "First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002) (First Am Bank v. Guerine.pdf at p.7).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_15", + "description": "States in Assignment #2 that the Defendants have failed to meet their burden of proving that balance of factors must strongly favor transfer of the case before the plaintiff can be deprived of her chosen forum.", + "source": "First Nat. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002) (First Am Bank v. Guerine.pdf at p.8).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_16", + "description": "Identifies in Assignment #2 that the plaintiff has a substantial interest in choosing the forum where his rights will be vindicated under First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002).", + "source": "First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002) (First Am Bank v. Guerine.pdf at p.3).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_17", + "description": "States in Assignment #2 that the issue of court congestion is a relatively insignificant factor, especially where the record does not show the other forum would resolve the case more quickly, under Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006).", + "source": "Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.10).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_18", + "description": "States in Assignment #2 that the 2023 Illinois Annual Report Statistics report a 60.5% clearance rate in Cook County, Illinois.", + "source": "2023 Annual Report Statistical Summary.pdf at p.21", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": -30.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_19", + "description": "States in Assignment #2 that the 2023 Illinois Annual Report Statistics report a 96.3% clearance rate in DuPage County Civil cases.", + "source": "2023 Annual Report Statistical Summary.pdf at p.21", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 1.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_20", + "description": "States in Assignment #2 that the 2023 Illinois Annual Report Statistics report a 97.9% clearance rate in Cook County Civil cases.", + "source": "2023 Annual Report Statistical Summary.pdf at p.21", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 1.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_21", + "description": "States in Assignment #2 that the medical treatment rendered to Baby Davis from Cook County physicians are relevant for the analysis of the Plaintiff\u2019s wrongful death claim.", + "source": "Davis Complaint.docx, Count II.", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_22", + "description": "States in Assignment #2 that the medical treatment rendered to Baby Davis from Cook County physicians are relevant for the testimony necessary to offer evidence on the damages sustained by Baby Davis under the Plaintiff\u2019s survival claims.", + "source": "Davis Complaint.docx, Count I.", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_23", + "description": "States in Assignment #2 that Plaintiff has met its burden of establishing Cook County as the appropriate forum.", + "source": "Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.7).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": -30.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_24", + "description": "Mentions in Assignment #2 that Plaintiff receives no deference to Cook County as it is a forum in which she does not reside.", + "source": "First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002) (First Am Bank v. Guerine.pdf at p.3).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": -30.0, + "polarity": "negative", + "raw_weight": 1.0 + } + ], + "answer_path": "/app/response2.md", + "answer_relative_path": "response2.md", + "is_followon": true, + "prev_answer_path": "/app/response1.md" +} diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/fixtures/rubric.json b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/fixtures/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..8914c3015a341dc062556d280e40a78cb8b028e2 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/fixtures/rubric.json @@ -0,0 +1,244 @@ +{ + "criteria": [ + { + "name": "criterion_1", + "description": "States in Assignment #2 that the response is supported by the affidavit of Liam Vance, a physician who provided care to Baby Davis at Cook County Hospital.", + "source": "Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) (Bradbury v. St. Mary\u2019s Hospital.pdf at p.3).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_2", + "description": "States in Assignment #2 that the response is supported by the affidavit of Savannah Brooks, a physician who provided care to Baby Davis at Cook County Hospital.", + "source": "Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) (Bradbury v. St. Mary\u2019s Hospital.pdf at p.3).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_3", + "description": "States in Assignment #2 that the response is supported by the affidavit of Caleb Montgomery, a physician who provided care to Baby Davis at Cook County Hospital.", + "source": "Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) (Bradbury v. St. Mary\u2019s Hospital.pdf at p.3).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_4", + "description": "States in Assignment #2 that the response is supported by the affidavit of Maya Linwood, a physician who provided care to Baby Davis at Cook County Hospital.", + "source": "Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) (Bradbury v. St. Mary\u2019s Hospital.pdf at p.3).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_5", + "description": "States in Assignment #2 that the response is supported by the affidavit of Garrett Hayes, a physician who provided care to Baby Davis at Cook County Hospital.", + "source": "Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) (Bradbury v. St. Mary\u2019s Hospital.pdf at p.3).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_6", + "description": "Identifies in Assignment #2 that the affidavit by Liam Vance indicates that DuPage County would be an inconvenient forum for him to litigate this case as required under Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006).", + "source": "Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.10).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_7", + "description": "Identifies in Assignment #2 that the affidavit by Savannah Brooks indicates that DuPage County would be an inconvenient forum for her to litigate this case as required under Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006).", + "source": "Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.10).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_8", + "description": "Identifies in Assignment #2 that the affidavit by Caleb Montgomery indicates that DuPage County would be an inconvenient forum for him to litigate this case as required under Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006).", + "source": "Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.10).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_9", + "description": "Identifies in Assignment #2 that the affidavit by Maya Linwood indicates that DuPage County would be an inconvenient forum for her to litigate this case as required under Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006).", + "source": "Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.10).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_10", + "description": "Identifies in Assignment #2 that the affidavit by Garrett Hayes indicates that DuPage County would be an inconvenient forum for him to litigate this case as required under Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006).", + "source": "Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.10).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_11", + "description": "States in Assignment #2 that the response is supported by the affidavit of the plaintiff, Sara Davis.", + "source": "Bradbury v. St. Mary's Hospital of Kankakee, 273 Ill. App. 3d 555 (Ill. App. 1 Dist. 1995) (Bradbury v. St. Mary\u2019s Hospital.pdf at p.3).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_12", + "description": "Identifies in Assignment #2 that the affidavit by the Plaintiff, Sara Davis, indicates that DuPage County would be an inconvenient forum for her to litigate this case as required under Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006).", + "source": "Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.10).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_13", + "description": "Mentions in Assignment #2 that the forum non conveniens doctrine gives courts discretionary power that should be exercised only in exceptional circumstances when the interests of justice require a trial in a more convenient forum under Langenhorst v. Norfolk S. Ry. Co., 219 Ill.2d 430 (2006).", + "source": "Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.6).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_14", + "description": "Mentions in Assignment #2 that the test is whether the relevant factors, viewed in their totality, strongly favor transfer to the forum suggested by defendant under First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002).", + "source": "First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002) (First Am Bank v. Guerine.pdf at p.7).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_15", + "description": "States in Assignment #2 that the Defendants have failed to meet their burden of proving that balance of factors must strongly favor transfer of the case before the plaintiff can be deprived of her chosen forum.", + "source": "First Nat. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002) (First Am Bank v. Guerine.pdf at p.8).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_16", + "description": "Identifies in Assignment #2 that the plaintiff has a substantial interest in choosing the forum where his rights will be vindicated under First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002).", + "source": "First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002) (First Am Bank v. Guerine.pdf at p.3).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_17", + "description": "States in Assignment #2 that the issue of court congestion is a relatively insignificant factor, especially where the record does not show the other forum would resolve the case more quickly, under Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006).", + "source": "Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.10).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_18", + "description": "States in Assignment #2 that the 2023 Illinois Annual Report Statistics report a 60.5% clearance rate in Cook County, Illinois.", + "source": "2023 Annual Report Statistical Summary.pdf at p.21", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": -30.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_19", + "description": "States in Assignment #2 that the 2023 Illinois Annual Report Statistics report a 96.3% clearance rate in DuPage County Civil cases.", + "source": "2023 Annual Report Statistical Summary.pdf at p.21", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 1.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_20", + "description": "States in Assignment #2 that the 2023 Illinois Annual Report Statistics report a 97.9% clearance rate in Cook County Civil cases.", + "source": "2023 Annual Report Statistical Summary.pdf at p.21", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 1.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_21", + "description": "States in Assignment #2 that the medical treatment rendered to Baby Davis from Cook County physicians are relevant for the analysis of the Plaintiff\u2019s wrongful death claim.", + "source": "Davis Complaint.docx, Count II.", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_22", + "description": "States in Assignment #2 that the medical treatment rendered to Baby Davis from Cook County physicians are relevant for the testimony necessary to offer evidence on the damages sustained by Baby Davis under the Plaintiff\u2019s survival claims.", + "source": "Davis Complaint.docx, Count I.", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_23", + "description": "States in Assignment #2 that Plaintiff has met its burden of establishing Cook County as the appropriate forum.", + "source": "Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006), (Langenhorst v. Norfolk Southern.pdf at p.7).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": -30.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_24", + "description": "Mentions in Assignment #2 that Plaintiff receives no deference to Cook County as it is a forum in which she does not reside.", + "source": "First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002) (First Am Bank v. Guerine.pdf at p.3).", + "justification": "This rubric item is requested directly in the following portion of the prompt \"Assignment #2\"; \"Please draft a response to the Defendants motion to transfer pursuant to the doctrine of forum non conveniens.\"", + "metadata": {}, + "score": -30.0, + "polarity": "negative", + "raw_weight": 1.0 + } + ] +} diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/m1_judge_panel.json b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/m1_judge_panel.json new file mode 100644 index 0000000000000000000000000000000000000000..a8041f6781a899f9083fe4a1a95f51bc78d35601 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/m1_judge_panel.json @@ -0,0 +1,21 @@ +{ + "mode": "panel", + "max_concurrent_llm": 12, + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ] +} diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/m1_rewardkit_accounting.py b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/m1_rewardkit_accounting.py new file mode 100644 index 0000000000000000000000000000000000000000..406dc5e7c675b222d94514e71bf5fad6ae141d8f --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/m1_rewardkit_accounting.py @@ -0,0 +1,490 @@ +import asyncio +import json +import math +import os +from pathlib import Path +import random +import sys +import time + +class JudgeReceiptError(OSError): + pass +_LLM_ROUTES = frozenset({'vertex', 'anthropic fallback', 'aistudio', 'direct'}) +_LLM_ROUTE_HEADERS = ('x-m1-llm-route', 'llm_provider-x-m1-llm-route') + +def _canonical_llm_route(value): + return value if isinstance(value, str) and value in _LLM_ROUTES else None + +def _llm_route_from_headers(headers): + if not isinstance(headers, dict): + return None + folded = {str(key).lower(): value for key, value in headers.items()} + for name in _LLM_ROUTE_HEADERS: + route = _canonical_llm_route(folded.get(name)) + if route is not None: + return route + return None + +def _llm_route_from_response(response): + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + route = _llm_route_from_headers(headers) + if route is not None: + return route + return _llm_route_from_headers(getattr(response, 'headers', None)) + +def _token_field_status(values, key): + if not isinstance(values, dict) or key not in values: + return 'missing' + value = values[key] + if value is None: + return 'null' + return 'valid' if type(value) is int and value >= 0 else 'invalid' + +def _gemini_capture(kwargs, model): + if not model.startswith('gemini/') or kwargs.get('stream') or kwargs.get('tools') or kwargs.get('functions'): + return (kwargs, None) + from litellm.integrations.custom_logger import CustomLogger + from urllib.parse import urlsplit + + class Capture(CustomLogger): + evidence = None + prompt_status = 'not_observed' + llm_route = None + + def log_post_api_call(self, kwargs, response_obj, start_time, end_time): + self.evidence = None + self.prompt_status = 'not_observed' + try: + params = kwargs.get('litellm_params') or {} + route = urlsplit(params.get('api_base') or '') + bare = model.removeprefix('gemini/') + gemini = params.get('custom_llm_provider') == 'gemini' + ai_studio = gemini and route.hostname == 'generativelanguage.googleapis.com' and (route.path in {'/' + version + '/models/' + bare + ':generateContent' for version in ('v1alpha', 'v1beta')}) + broker = urlsplit(os.environ.get('GEMINI_API_BASE') or '') + brokered = gemini and bool(broker.netloc) and (route.netloc == broker.netloc) and (broker.path.rstrip('/').rsplit('/', 1)[-1] in ('v1alpha', 'v1beta')) and (route.path == broker.path.rstrip('/') + '/models/' + bare + ':generateContent') + vertex = params.get('custom_llm_provider') == 'vertex_ai' and route.hostname == 'aiplatform.googleapis.com' and route.path.startswith('/v1/projects/') and route.path.endswith('/locations/global/publishers/google/models/' + bare + ':generateContent') + if route.scheme != 'https' or not (ai_studio or brokered or vertex) or kwargs.get('stream'): + return + self.llm_route = 'vertex' if vertex else 'aistudio' if ai_studio else None + raw = kwargs.get('original_response') + raw = json.loads(raw) if isinstance(raw, str) else raw + if not isinstance(raw, dict): + return + candidates = raw.get('candidates') + if not isinstance(candidates, list) or not candidates or any((not isinstance(c, dict) or not c.get('finishReason') for c in candidates)) or (not isinstance(raw.get('modelVersion'), str)) or (not raw['modelVersion']): + return + usage = raw.get('usageMetadata') + self.prompt_status = _token_field_status(usage, 'promptTokenCount') + if not isinstance(usage, dict): + return + fields = ('promptTokenCount', 'candidatesTokenCount', 'thoughtsTokenCount', 'cachedContentTokenCount', 'totalTokenCount', 'toolUsePromptTokenCount') + counts = {key: usage.get(key, 0) for key in fields} + if not {'promptTokenCount', 'totalTokenCount'} <= usage.keys() or any((type(n) is not int or n < 0 for n in counts.values())) or counts['toolUsePromptTokenCount'] != 0 or (counts['cachedContentTokenCount'] > counts['promptTokenCount']) or (counts['totalTokenCount'] != counts['promptTokenCount'] + counts['candidatesTokenCount'] + counts['thoughtsTokenCount']): + return + self.evidence = {'protocol': 'gemini-generate-content-' + ('vertex-v1' if vertex else route.path.split('/')[-3]), 'model_version': raw['modelVersion'], 'usage_metadata': {key: usage[key] for key in fields if key in usage}, 'defaulted_fields': [key for key in fields if key not in usage]} + except (TypeError, ValueError, AttributeError): + return + capture = Capture() + return ({**kwargs, 'callbacks': [*(kwargs.get('callbacks') or []), capture]}, capture) + +def _record_judge_usage(response, model: str, *, target: Path | None=None, native_usage: dict | None=None, native_prompt_status: str | None=None, llm_route: str | None=None) -> None: + import fcntl + from datetime import datetime, timezone + data = response.model_dump() if hasattr(response, 'model_dump') else response + usage = data.get('usage') if isinstance(data, dict) else None + granularity = data.get('usage_granularity') if isinstance(data, dict) else None + if not isinstance(usage, dict): + usage = {} + granularity = 'missing_provider_receipt' + prompt, completion = (usage.get('prompt_tokens'), usage.get('completion_tokens')) + native_fresh = usage.get('input_uncached_tokens') + prompt = prompt if type(prompt) is int and prompt >= 0 else None + native_fresh = native_fresh if type(native_fresh) is int and native_fresh >= 0 else None + if type(completion) is not int or completion < 0 or (prompt is None and native_fresh is None): + completion = completion if type(completion) is int and completion >= 0 else 0 + granularity = granularity or 'invalid_provider_receipt' + details = usage.get('prompt_tokens_details') + if details is not None and (not isinstance(details, dict)): + granularity = 'invalid_provider_receipt' + details = details if isinstance(details, dict) else {} + cached = details.get('cached_tokens') + if native_usage is not None: + native = native_usage['usage_metadata'] + native_output = native.get('candidatesTokenCount', 0) + native.get('thoughtsTokenCount', 0) + if prompt == native['promptTokenCount'] and completion == native_output: + cached = native.get('cachedContentTokenCount', 0) + else: + native_usage = None + written = next((value for value in (usage.get('input_cache_write_tokens'), usage.get('cache_creation_input_tokens'), details.get('cache_creation_tokens'), details.get('cache_write_tokens')) if value is not None), None) + invalid = any((value is not None and (type(value) is not int or value < 0) for value in (cached, written))) + cached = cached if type(cached) is int and cached >= 0 else None + written = written if type(written) is int and written >= 0 else None + fresh = native_fresh + if fresh is None and prompt is not None and (cached is not None) and (written is not None): + fresh = prompt - cached - written + if fresh is not None and (fresh < 0 or (prompt is not None and cached is not None and (written is not None) and (fresh + cached + written != prompt))): + invalid, fresh = (True, None) + provider, _, slug = model.partition('/') + event: dict = {'type': 'step_finish', 'part': {'providerID': provider if slug else 'openai', 'modelID': slug or model, 'tokens': {'input': fresh, 'output': completion, 'cache': {'read': cached, 'write': written}}}} + field_status = {'prompt_tokens': _token_field_status(usage, 'prompt_tokens'), 'completion_tokens': _token_field_status(usage, 'completion_tokens'), 'input_uncached_tokens': _token_field_status(usage, 'input_uncached_tokens')} + field_status['native_prompt_token_count'] = native_prompt_status if native_prompt_status in {'missing', 'null', 'invalid', 'valid', 'not_observed'} else 'unsupported' + part: dict = event['part'] + part['usage_field_status'] = field_status + if native_usage is not None: + event['part']['native_usage'] = native_usage + event['part']['token_categories_provenance'] = 'explicit_presence_v1' + if fresh is None and prompt is not None: + event['part']['prompt_tokens_inclusive'] = prompt + if invalid or any((value is None for value in (fresh, cached, written))): + granularity = granularity if granularity not in (None, 'request') else 'invalid_provider_receipt' if invalid else 'incomplete_token_categories' + if granularity: + event['part']['usage_granularity'] = granularity + if provider == 'openrouter': + cost = usage.get('cost') + if cost is None: + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + if isinstance(headers, dict): + cost = headers.get('llm_provider-x-litellm-response-cost') + if isinstance(cost, (int, float)) and (not isinstance(cost, bool)) and math.isfinite(cost) and (cost >= 0): + event['part']['cost'] = cost + data = data if isinstance(data, dict) else {} + if isinstance(data.get('id'), str) and data['id']: + event['part']['provider_request_id'] = data['id'] + for key in ('service_tier', 'cache_ttl'): + if data.get(key): + event['part'][key] = data[key] + route = _llm_route_from_response(response) or _canonical_llm_route(llm_route) + if route is not None: + event['part']['llm_route'] = route + created = data.get('created') + stamp = datetime.now(timezone.utc) + try: + if isinstance(created, str): + parsed = datetime.fromisoformat(created.replace('Z', '+00:00')) + if parsed.tzinfo is not None: + stamp = parsed + elif isinstance(created, (int, float)) and (not isinstance(created, bool)) and math.isfinite(created): + stamp = datetime.fromtimestamp(created, timezone.utc) + except (ValueError, OverflowError, OSError): + pass + pair = json.dumps({'type': 'step_start', 'timestamp': stamp.isoformat()}) + '\n' + pair += json.dumps(event) + '\n' + try: + receipt_path = target or Path(os.environ.get('M1_JUDGE_USAGE_PATH', '/logs/verifier/judge-trajectory.jsonl')) + receipt_path.parent.mkdir(parents=True, exist_ok=True) + with receipt_path.open('a') as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + handle.write(pair) + handle.flush() + os.fsync(handle.fileno()) + except OSError as exc: + if target is not None: + raise JudgeReceiptError(f'judge receipt write failed: {exc}') from exc + print(f'judge accounting: write failed ({type(exc).__name__})', file=sys.stderr) + +def openrouter_judge_pins() -> dict[str, dict]: + raw = os.environ.get('M1_OPENROUTER_JUDGE_PROVIDER_PINS', '').strip() + if not raw: + return {} + try: + pins = json.loads(raw) + except json.JSONDecodeError: + print('judge provider pins: invalid JSON in M1_OPENROUTER_JUDGE_PROVIDER_PINS', file=sys.stderr) + return {} + return {model: pin for model, pin in pins.items() if isinstance(pin, dict) and pin.get('order')} if isinstance(pins, dict) else {} + +def apply_judge_provider_pin(kwargs: dict, pins: dict[str, dict]) -> dict: + model = kwargs.get('model') + pin = pins.get(model) if isinstance(model, str) else None + if pin is None: + return kwargs + extra_body = dict(kwargs.get('extra_body') or {}) + provider = dict(extra_body.get('provider') or {}) + provider['order'] = list(pin['order']) + if pin.get('allow_fallbacks') is False: + provider['allow_fallbacks'] = False + if pin.get('zdr'): + provider['zdr'] = True + extra_body['provider'] = provider + return {**kwargs, 'extra_body': extra_body} +_TRANSIENT_ERROR_NAMES = ('RateLimitError', 'ServiceUnavailableError', 'InternalServerError', 'BadGatewayError', 'APIConnectionError') +_RETRYABLE_STATUS_CODES = frozenset({408, 409, 425, 429, 500, 502, 503, 504}) +_AUTH_ERROR_NAMES = ('AuthenticationError', 'PermissionDeniedError') +_AUTH_STATUS_CODES = frozenset({401, 403}) +_AUTH_RETRIES = 4 +_DEFAULT_TRANSIENT_RETRIES = 6 +_MAX_TRANSIENT_RETRIES = 20 +_MAX_RETRY_DELAY_SECONDS = 60.0 +_DEFAULT_EMPTY_RESPONSE_RETRIES = 3 +_DEFAULT_RETRY_BUDGET_SECONDS = 900.0 +_MAX_RETRY_BUDGET_SECONDS = 86400.0 + +def transient_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_TRANSIENT_RETRIES', '').strip() + if not raw: + return _DEFAULT_TRANSIENT_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_TRANSIENT_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_TRANSIENT_RETRIES + +def empty_response_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_EMPTY_RESPONSE_RETRIES', '').strip() + if not raw: + return _DEFAULT_EMPTY_RESPONSE_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_EMPTY_RESPONSE_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_EMPTY_RESPONSE_RETRIES + +def retry_budget_seconds() -> float: + raw = os.environ.get('M1_JUDGE_RETRY_BUDGET_SECONDS', '').strip() + if not raw: + return _DEFAULT_RETRY_BUDGET_SECONDS + try: + value = float(raw) + except ValueError: + value = math.nan + if not math.isfinite(value) or value < 0: + print('judge retries: invalid M1_JUDGE_RETRY_BUDGET_SECONDS, using the default', file=sys.stderr) + return _DEFAULT_RETRY_BUDGET_SECONDS + return min(value, _MAX_RETRY_BUDGET_SECONDS) + +def _within_budget(deadline: float, delay: float, model) -> bool: + remaining = deadline - time.monotonic() + if delay <= remaining: + return True + print(f'judge call retry budget spent: {model} would wait {delay:.1f}s with {max(remaining, 0.0):.1f}s left of M1_JUDGE_RETRY_BUDGET_SECONDS, failing now', file=sys.stderr) + return False + +def is_empty_verdict(response) -> bool: + data = response.model_dump() if hasattr(response, 'model_dump') else response + if not isinstance(data, dict): + return False + choices = data.get('choices') + if not isinstance(choices, list) or not choices: + return True + first = choices[0] + message = first.get('message') if isinstance(first, dict) else None + if not isinstance(message, dict): + return True + if message.get('tool_calls') or message.get('function_call'): + return False + content = message.get('content') + if isinstance(content, list): + content = ''.join((part.get('text') or '' for part in content if isinstance(part, dict))) + return not (isinstance(content, str) and content.strip()) + +def _matches(exc: BaseException, litellm, names: tuple[str, ...], statuses: frozenset[int]) -> bool: + classes = tuple((cls for cls in (getattr(litellm, name, None) for name in names) if isinstance(cls, type))) + if classes and isinstance(exc, classes): + return True + status = getattr(exc, 'status_code', None) + return type(status) is int and status in statuses + +def is_transient_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _TRANSIENT_ERROR_NAMES, _RETRYABLE_STATUS_CODES) + +def is_auth_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _AUTH_ERROR_NAMES, _AUTH_STATUS_CODES) + +def should_retry(exc: BaseException, litellm, attempt: int, limit: int) -> bool: + if attempt < limit and is_transient_error(exc, litellm): + return True + return attempt < min(limit, _AUTH_RETRIES) and is_auth_error(exc, litellm) + +def _retry_after_seconds(exc: BaseException) -> float | None: + headers = getattr(exc, 'headers', None) + if headers is None: + headers = getattr(getattr(exc, 'response', None), 'headers', None) + if headers is None: + return None + try: + raw = headers.get('retry-after') + if raw is None: + raw = headers.get('Retry-After') + value = float(raw) + except (AttributeError, TypeError, ValueError): + return None + return value if math.isfinite(value) and value >= 0 else None + +def retry_delay(exc: BaseException | None, attempt: int) -> float: + base = min(_MAX_RETRY_DELAY_SECONDS, 2.0 ** (attempt + 1)) + delay = base * (0.5 + random.random()) + retry_after = _retry_after_seconds(exc) if exc is not None else None + if retry_after is not None: + delay = max(delay, min(_MAX_RETRY_DELAY_SECONDS, retry_after)) + return delay + +def _note_retry(model, exc: BaseException, attempt: int, limit: int, delay: float) -> None: + status = getattr(exc, 'status_code', None) + print(f"judge call retry {attempt}/{limit}: {model} {type(exc).__name__} status={(status if type(status) is int else 'n/a')}, waiting {delay:.1f}s", file=sys.stderr) + +def _note_empty(model, response, attempt: int, limit: int, delay: float) -> None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + reason = None + if isinstance(data, dict) and isinstance(data.get('choices'), list) and data['choices']: + first = data['choices'][0] + reason = first.get('finish_reason') if isinstance(first, dict) else None + print(f'judge call retry {attempt}/{limit}: {model} empty verdict (finish_reason={reason}), waiting {delay:.1f}s', file=sys.stderr) + +def install(litellm, *, synchronous: bool=False) -> None: + pins = openrouter_judge_pins() + limit = transient_retry_limit() + empty_limit = empty_response_retry_limit() + deadline = time.monotonic() + retry_budget_seconds() + if synchronous: + original = litellm.completion + + def accounted(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = original(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + time.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + time.sleep(delay) + continue + return response + litellm.completion = accounted + return + original_async = litellm.acompletion + + async def accounted_async(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = await original_async(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + await asyncio.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + await asyncio.sleep(delay) + continue + return response + litellm.acompletion = accounted_async + +def record_agent_usage(attempt, *, model: str, provider: str) -> None: + records: dict[str, tuple[str, dict]] = {} + current_model = model + for filename in getattr(attempt, 'logs', []): + try: + with Path(filename).open() as stream: + for line in stream: + try: + event = json.loads(line) + except (ValueError, TypeError): + continue + if not isinstance(event, dict): + continue + message = event.get('message') or {} + if event.get('type') == 'assistant' and isinstance(message, dict) and isinstance(message.get('usage'), dict): + raw = message['usage'] + cached, written = (raw.get('cache_read_input_tokens'), raw.get('cache_creation_input_tokens')) + if all((type(value) is int and value >= 0 for value in (raw.get('input_tokens'), raw.get('output_tokens')))) and all((value is None or (type(value) is int and value >= 0) for value in (cached, written))): + receipt: dict = {'usage': {'input_uncached_tokens': raw['input_tokens'], 'prompt_tokens': raw['input_tokens'] + cached + written if cached is not None and written is not None else None, 'completion_tokens': raw['output_tokens'], 'prompt_tokens_details': {'cached_tokens': cached, 'cache_creation_tokens': written}}} + receipt['created'] = event.get('timestamp') + creation = raw.get('cache_creation') or {} + hour = creation.get('ephemeral_1h_input_tokens', 0) if isinstance(creation, dict) else 0 + if type(hour) is int and hour > 0: + if hour == written: + receipt['cache_ttl'] = '1h' + else: + receipt['usage_granularity'] = 'mixed_cache_ttl' + records[message.get('id') or json.dumps(raw, sort_keys=True)] = (message.get('model') or current_model, receipt) + payload = event.get('payload') or {} + if not isinstance(payload, dict): + continue + if event.get('type') == 'turn_context' and payload.get('model'): + current_model = payload['model'] + if event.get('type') == 'event_msg' and payload.get('type') == 'token_count': + info = payload.get('info') or {} + raw, total = (info.get('last_token_usage'), info.get('total_token_usage')) + if isinstance(raw, dict) and isinstance(total, dict) and all((type(raw.get(key)) is int and raw.get(key) >= 0 for key in ('input_tokens', 'output_tokens'))): + receipt = {'usage': {'prompt_tokens': raw.get('input_tokens'), 'input_uncached_tokens': raw.get('input_uncached_tokens'), 'input_cache_write_tokens': raw.get('input_cache_write_tokens'), 'completion_tokens': raw.get('output_tokens'), 'prompt_tokens_details': {'cached_tokens': raw.get('cached_input_tokens')}}} + receipt['created'] = event.get('timestamp') + records[json.dumps(total, sort_keys=True)] = (current_model, receipt) + except OSError: + continue + captured_input = captured_output = 0 + input_complete = True + for requested, receipt in records.values(): + requested = requested if '/' in requested else f'{provider}/{requested}' + _record_judge_usage(receipt, requested) + receipt_input = receipt['usage'].get('prompt_tokens') + if receipt_input is None: + input_complete = False + else: + captured_input += receipt_input + captured_output += receipt['usage'].get('completion_tokens') or 0 + total = getattr(attempt, 'usage', {}) or {} + if not records or (input_complete and total.get('input_tokens') != captured_input) or total.get('output_tokens') != captured_output: + _record_judge_usage({'usage': {'prompt_tokens': 0, 'completion_tokens': 0}, 'usage_granularity': 'incomplete_agent_receipts'}, model if '/' in model else f'{provider}/{model}') + +def install_rewardkit_agents() -> None: + import rewardkit.judges as judges + original = judges.get_agent + + def get_accounted_agent(judge, cwd=None): + backend = original(judge, cwd) + run = backend.run + + async def accounted_run(*args, **kwargs): + attempt = await run(*args, **kwargs) + record_agent_usage(attempt, model=judge.model or 'unknown', provider='anthropic' if judge.agent == 'claude-code' else 'openai') + return attempt + setattr(backend, 'run', accounted_run) + return backend + setattr(judges, 'get_agent', get_accounted_agent) +if __name__ == '__main__': + import litellm + if len(sys.argv) > 2 and sys.argv[1] == '--script': + import runpy + install(litellm, synchronous=True) + sys.argv = sys.argv[2:] + runpy.run_path(sys.argv[0], run_name='__main__') + else: + install(litellm) + install_rewardkit_agents() + if Path(__file__).with_name('m1_judge_panel.json').is_file(): + from m1_rewardkit_panel import install_panel + install_panel(Path(__file__).with_name('m1_judge_panel.json')) + if Path(__file__).with_name('m1_judge_jev.json').is_file(): + from m1_rewardkit_jev import install_jev + install_jev(Path(__file__).with_name('m1_judge_jev.json')) + from rewardkit.__main__ import main + main() diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/m1_rewardkit_panel.py b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/m1_rewardkit_panel.py new file mode 100644 index 0000000000000000000000000000000000000000..164cc2ae521cdd368c2e1749d7ed8fe09f4545eb --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/m1_rewardkit_panel.py @@ -0,0 +1,169 @@ +from __future__ import annotations +import asyncio +from contextvars import ContextVar +import json +import math +import os +import sys +from pathlib import Path +from typing import Any +import uuid +_request_audit: ContextVar[tuple[Path, list[str]] | None] = ContextVar('panel_request_audit', default=None) + +class PanelIncompleteError(RuntimeError): + pass + +def _audit_warning(exc: Exception, warnings: list[str]) -> None: + message = f'judge panel audit: diagnostic capture failed ({type(exc).__name__})' + if message not in warnings: + warnings.append(message) + print(message, file=sys.stderr) + +def _write_audit(path: Path, record: dict[str, Any], warnings: list[str], *, append: bool=False) -> None: + try: + text = json.dumps(record, allow_nan=False, default=str) + '\n' + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('a' if append else 'w') as stream: + stream.write(text) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + +def _binary(raw: Any) -> int: + if isinstance(raw, bool): + return int(raw) + if isinstance(raw, int | float) and math.isfinite(raw) and (raw in (0, 1)): + return int(raw) + if isinstance(raw, str): + value = raw.strip().lower() + if value in {'yes', 'true', '1'}: + return 1 + if value in {'no', 'false', '0'}: + return 0 + raise PanelIncompleteError('m1_judge_panel_incomplete: invalid binary vote') + +def validate_votes(scores: list[Any], criteria: list[Any]) -> None: + names = [criterion.name for criterion in criteria] + if len(set(names)) != len(names) or [score.name for score in scores] != names: + raise PanelIncompleteError('m1_judge_panel_incomplete: criterion membership mismatch') + for score, criterion in zip(scores, criteria, strict=True): + if score.error: + raise PanelIncompleteError('m1_judge_panel_incomplete: judge returned an error') + raw = _binary(score.raw) + expected = 1 - raw if criterion.negate else raw + if not math.isfinite(score.value) or score.value != expected: + raise PanelIncompleteError('m1_judge_panel_incomplete: inconsistent binary score') + +async def run_panel(judge: Any, criteria: list[Any], weights: list[float] | None, system_prompt: str | None, *, config: dict[str, Any], run_llm: Any, score_type: Any, audit_dir: Path) -> tuple[list[Any], str, list[str]]: + from rewardkit.models import Binary + if not criteria or any((not isinstance(criterion.output_format, Binary) for criterion in criteria)): + raise ValueError('panel majority voting requires nonempty binary criteria') + group_dir = audit_dir / uuid.uuid4().hex + warnings_out: list[str] = [] + + async def member_call(index: int, member: dict[str, Any]): + member_judge = judge.model_copy(update=member) + evidence: dict[str, Any] = {'member': index + 1, 'judge': member, 'criteria': [criterion.name for criterion in criteria], 'status': 'started'} + path = group_dir / f'judge-{index + 1}.json' + _write_audit(path, evidence, warnings_out) + token = _request_audit.set((group_dir / f'judge-{index + 1}-requests.jsonl', warnings_out)) + try: + scores, output, warnings = await run_llm(member_judge, criteria, weights, system_prompt) + evidence.update(output=output, warnings=warnings) + validate_votes(scores, criteria) + evidence['scores'] = [score.to_dict() for score in scores] + evidence['status'] = 'completed' + return (scores, output, warnings) + except BaseException as exc: + evidence.update(status='failed', error_class=type(exc).__name__) + if isinstance(exc, PanelIncompleteError): + evidence['error'] = str(exc) + raise + finally: + _request_audit.reset(token) + _write_audit(path, evidence, warnings_out) + outcomes = await asyncio.gather(*(member_call(index, member) for index, member in enumerate(config['members'])), return_exceptions=True) + failed = [index + 1 for index, result in enumerate(outcomes) if isinstance(result, BaseException)] + if failed: + _write_audit(group_dir / 'panel.json', {'status': 'incomplete', 'failed_members': failed}, warnings_out) + raise PanelIncompleteError(f'm1_judge_panel_incomplete: failed members {failed}; see panel audit artifacts') + completed = [outcome for outcome in outcomes if not isinstance(outcome, BaseException)] + combined = [] + for index, criterion in enumerate(criteria): + votes = [{'judge': config['members'][member_index], **outcome[0][index].to_dict()} for member_index, outcome in enumerate(completed)] + passes = sum((vote['value'] == 1 for vote in votes)) + value = int(passes >= 2) + combined.append(score_type(name=criterion.name, value=value, raw=bool(1 - value if criterion.negate else value), weight=weights[index] if weights is not None else 1.0, reasoning=f'{passes}/3 judges passed; strict majority requires 2/3.', description=criterion.description, id=criterion.id, negate=criterion.negate, optional=criterion.optional, votes=votes)) + for outcome in completed: + warnings_out.extend(outcome[2]) + audit = {'status': 'completed', 'mode': 'panel', 'aggregation': 'majority', 'required_votes': 2, 'members': config['members'], 'criteria': [score.to_dict() for score in combined]} + output = json.dumps(audit, indent=2, allow_nan=False) + _write_audit(group_dir / 'panel.json', audit, warnings_out) + return (combined, output, warnings_out) + +def install_panel(config_path: Path, *, audit_dir: Path=Path('/logs/verifier/judge-panel')) -> None: + import rewardkit.judges as judges + import rewardkit.reward as reward + from rewardkit.models import LLMJudge, Score + import litellm + config = json.loads(config_path.read_text()) + members = config.get('members') + concurrency = config.get('max_concurrent_llm') + if config.get('mode') != 'panel' or not isinstance(members, list) or len(members) != 3 or (len({member['model'] for member in members}) != 3) or (type(concurrency) is not int) or (not 1 <= concurrency <= 64): + raise ValueError('invalid materialized panel configuration') + if os.environ.get('REWARDKIT_JUDGE') or os.environ.get('REWARDKIT_MODEL'): + raise ValueError('RewardKit environment overrides cannot replace a frozen panel') + + class PanelScore(Score): + votes: list[dict[str, Any]] + + def to_dict(self): + return {**super().to_dict(), 'votes': self.votes} + original_llm = judges.arun_llm + original_call = judges._arun_llm_call + original_details = reward.Reward.to_detail_dict + original_completion = litellm.acompletion + active_loop = None + semaphore = None + + async def captured_completion(*args, **kwargs): + context = _request_audit.get() + record = {'requested_model': kwargs.get('model')} + response = None + try: + response = await original_completion(*args, **kwargs) + return response + except BaseException as exc: + record['error_class'] = type(exc).__name__ + raise + finally: + if context is not None: + path, warnings = context + try: + if response is not None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + record.update(response_model=data.get('model'), choices=data.get('choices')) + _write_audit(path, record, warnings, append=True) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + + async def bounded_call(*args, **kwargs): + nonlocal active_loop, semaphore + loop = asyncio.get_running_loop() + if active_loop is not loop: + active_loop, semaphore = (loop, asyncio.Semaphore(concurrency)) + assert semaphore is not None + async with semaphore: + return await original_call(*args, **kwargs) + + async def panel_call(judge, criteria, weights=None, system_prompt=None): + return await run_panel(judge, criteria, weights, system_prompt, config=config, run_llm=original_llm, score_type=PanelScore, audit_dir=audit_dir) + + def panel_details(self, score): + detail = original_details(self, score) + if isinstance(self.judge, LLMJudge): + detail.update(kind='llm_panel', judge=config, aggregation='majority', required_votes=2) + return detail + setattr(reward, 'arun_llm', panel_call) + setattr(judges, '_arun_llm_call', bounded_call) + setattr(litellm, 'acompletion', captured_completion) + reward.Reward.to_detail_dict = panel_details diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/normalize_reward.py b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/normalize_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..91817ef00ea9152ca57f0030d8e879eb850ddff0 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/normalize_reward.py @@ -0,0 +1,71 @@ +from __future__ import annotations +import argparse +import json +from pathlib import Path +from typing import Any + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument('--raw-details', required=True) + parser.add_argument('--rubric', required=True) + parser.add_argument('--reward-out', required=True) + parser.add_argument('--details-out', required=True) + args = parser.parse_args() + raw_details = _load_json(Path(args.raw_details)) + rubric = _load_json(Path(args.rubric)) + criteria = rubric['criteria'] + raw_by_name = _raw_criteria_by_name(raw_details) + positive_total = sum((float(item['score']) for item in criteria if float(item['score']) > 0)) + if positive_total <= 0: + raise ValueError('rubric must contain at least one positive score') + earned = 0.0 + normalized_criteria: list[dict[str, Any]] = [] + for item in criteria: + signed_score = float(item['score']) + raw = raw_by_name.get(item['name'], {}) + value = _coerce_score(raw.get('value', 0.0)) + contribution = value * signed_score + earned += contribution + normalized_criteria.append({'name': item['name'], 'value': value, 'raw': raw.get('raw'), 'weight': signed_score, 'signed_score': signed_score, 'polarity': item['polarity'], 'contribution': contribution, 'description': item['description'], 'source': item.get('source', ''), 'justification': item.get('justification', ''), 'metadata': item.get('metadata', {}), 'reasoning': raw.get('reasoning'), 'judge_reasoning': raw.get('reasoning'), 'judge_error': raw.get('error'), **({'votes': raw['votes']} if 'votes' in raw else {})}) + unclamped = earned / positive_total + reward = max(0.0, min(1.0, unclamped)) + reward_out = {'correctness': reward} + details_out = {'correctness': {'score': reward, 'kind': 'signed_score', 'criteria': normalized_criteria, 'aggregation': {'method': 'signed_score_ratio_clamped', 'earned': earned, 'positive_total': positive_total, 'unclamped': unclamped, 'clamped': reward}, 'raw_rewardkit': raw_details}} + _write_json(Path(args.reward_out), reward_out) + _write_json(Path(args.details_out), details_out) + +def _load_json(path: Path) -> Any: + return json.loads(path.read_text()) + +def _write_json(path: Path, data: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data, indent=2) + '\n') + +def _raw_criteria_by_name(details: dict[str, Any]) -> dict[str, dict[str, Any]]: + out: dict[str, dict[str, Any]] = {} + for reward in details.values(): + for item in _iter_raw_criteria(reward): + name = item.get('name') + if isinstance(name, str): + out[name] = item + return out + +def _iter_raw_criteria(value: Any): + if isinstance(value, list): + for item in value: + yield from _iter_raw_criteria(item) + return + if not isinstance(value, dict): + return + for item in value.get('criteria') or []: + if isinstance(item, dict): + yield item + +def _coerce_score(value: Any) -> float: + if isinstance(value, bool): + return 1.0 if value else 0.0 + if isinstance(value, int | float): + return max(0.0, min(1.0, float(value))) + return 0.0 +if __name__ == '__main__': + main() diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/agent_prompt.md b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/agent_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..ca489c065bafd5d10e764f033c9dfd1195933db3 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/agent_prompt.md @@ -0,0 +1,10 @@ +You are grading the submitted legal analysis against the criteria below. + +Read `/logs/artifacts/answer.md`, the answer captured by the verifier, before +assigning any scores. Evaluate that file as the submission. Other files in +`/app` may supply context, but must not replace the submitted answer. Do not +modify the submission. If it is missing or empty, state that in your reasoning +and apply the criteria to that missing or empty submission. Preserve each +criterion's stated positive or penalty polarity. + +{criteria} diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_1.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_1.toml new file mode 100644 index 0000000000000000000000000000000000000000..812e285d8b91837c51478c0c199f788e7a48a41e --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_1.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_1" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in Assignment #2 that the response is supported by the affidavit of Liam Vance, a physician who provided care to Baby Davis at Cook County Hospital." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_10.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_10.toml new file mode 100644 index 0000000000000000000000000000000000000000..2e40d35bcb6dbdd4c8e9dfcb1c8b75eb9122c491 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_10.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_10" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies in Assignment #2 that the affidavit by Garrett Hayes indicates that DuPage County would be an inconvenient forum for him to litigate this case as required under Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006)." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_11.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_11.toml new file mode 100644 index 0000000000000000000000000000000000000000..b7ad2731449720e8dbdb211c0e79780249a4c3f2 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_11.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_11" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in Assignment #2 that the response is supported by the affidavit of the plaintiff, Sara Davis." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_12.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_12.toml new file mode 100644 index 0000000000000000000000000000000000000000..d1fb736cd328d484f77ec6b3631c1af2dd0ac21c --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_12.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_12" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies in Assignment #2 that the affidavit by the Plaintiff, Sara Davis, indicates that DuPage County would be an inconvenient forum for her to litigate this case as required under Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006)." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_13.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_13.toml new file mode 100644 index 0000000000000000000000000000000000000000..5c549e1ff75f539286c0e264d0a7d048c39fab0c --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_13.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_13" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions in Assignment #2 that the forum non conveniens doctrine gives courts discretionary power that should be exercised only in exceptional circumstances when the interests of justice require a trial in a more convenient forum under Langenhorst v. Norfolk S. Ry. Co., 219 Ill.2d 430 (2006)." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_14.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_14.toml new file mode 100644 index 0000000000000000000000000000000000000000..41aed371349d7762ee9e66ad3fcc77fd8ac8fade --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_14.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_14" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions in Assignment #2 that the test is whether the relevant factors, viewed in their totality, strongly favor transfer to the forum suggested by defendant under First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002)." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_15.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_15.toml new file mode 100644 index 0000000000000000000000000000000000000000..1901cf7900105373a03bbb1dd644c709368bc8ee --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_15.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_15" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in Assignment #2 that the Defendants have failed to meet their burden of proving that balance of factors must strongly favor transfer of the case before the plaintiff can be deprived of her chosen forum." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_16.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_16.toml new file mode 100644 index 0000000000000000000000000000000000000000..02b4817686e0d1057192c06f01668a40f6668036 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_16.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_16" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies in Assignment #2 that the plaintiff has a substantial interest in choosing the forum where his rights will be vindicated under First Am. Bank v. Guerine, 198 Ill.2d 511 (Ill. 2002)." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_17.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_17.toml new file mode 100644 index 0000000000000000000000000000000000000000..b049a77afef58c40187a3bfb2788a2ec4c3401b0 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_17.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_17" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in Assignment #2 that the issue of court congestion is a relatively insignificant factor, especially where the record does not show the other forum would resolve the case more quickly, under Langenhorst v. Norfolk S. Ry. Co., 219 Ill. 2d 430 (Ill. 2006)." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_18.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_18.toml new file mode 100644 index 0000000000000000000000000000000000000000..9588703a50ab013deff1892f480bd93701f226f6 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_18.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_18" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: States in Assignment #2 that the 2023 Illinois Annual Report Statistics report a 60.5% clearance rate in Cook County, Illinois." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_19.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_19.toml new file mode 100644 index 0000000000000000000000000000000000000000..b1851d7e881cef60bb9f42eb29c74e4d8367e7e1 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_19.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_19" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in Assignment #2 that the 2023 Illinois Annual Report Statistics report a 96.3% clearance rate in DuPage County Civil cases." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_2.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_2.toml new file mode 100644 index 0000000000000000000000000000000000000000..9864c6095aa9ad11bf330687834e711d91030e74 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_2.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_2" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in Assignment #2 that the response is supported by the affidavit of Savannah Brooks, a physician who provided care to Baby Davis at Cook County Hospital." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_20.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_20.toml new file mode 100644 index 0000000000000000000000000000000000000000..d63854e59802c21a7cb61bf36294f934c229c91b --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_20.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_20" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in Assignment #2 that the 2023 Illinois Annual Report Statistics report a 97.9% clearance rate in Cook County Civil cases." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_21.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_21.toml new file mode 100644 index 0000000000000000000000000000000000000000..919ad19ad9acdf787ba17225ed1a4396e913566f --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_21.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_21" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in Assignment #2 that the medical treatment rendered to Baby Davis from Cook County physicians are relevant for the analysis of the Plaintiff’s wrongful death claim." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_22.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_22.toml new file mode 100644 index 0000000000000000000000000000000000000000..a13ff7d537c2ce69c6b89af949da20cdac6d4e5b --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_22.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_22" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in Assignment #2 that the medical treatment rendered to Baby Davis from Cook County physicians are relevant for the testimony necessary to offer evidence on the damages sustained by Baby Davis under the Plaintiff’s survival claims." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_23.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_23.toml new file mode 100644 index 0000000000000000000000000000000000000000..08ffb9da6b4e88ebd0842e1bb1b87d8882486d0e --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_23.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_23" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: States in Assignment #2 that Plaintiff has met its burden of establishing Cook County as the appropriate forum." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_24.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_24.toml new file mode 100644 index 0000000000000000000000000000000000000000..e117328ef5392060756662c8c1c8d8282ce0a59a --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_24.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_24" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: Mentions in Assignment #2 that Plaintiff receives no deference to Cook County as it is a forum in which she does not reside." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_3.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_3.toml new file mode 100644 index 0000000000000000000000000000000000000000..aad072ad9d61ef0f551661f4c1ccf64dfb429066 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_3.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_3" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in Assignment #2 that the response is supported by the affidavit of Caleb Montgomery, a physician who provided care to Baby Davis at Cook County Hospital." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_4.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_4.toml new file mode 100644 index 0000000000000000000000000000000000000000..3519373d8a5e1a57f50e079dca59b1cabf6ef2b8 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_4.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_4" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in Assignment #2 that the response is supported by the affidavit of Maya Linwood, a physician who provided care to Baby Davis at Cook County Hospital." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_5.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_5.toml new file mode 100644 index 0000000000000000000000000000000000000000..268493c86287b9f9944e6f9b8fe97588d94bd7d2 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_5.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_5" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States in Assignment #2 that the response is supported by the affidavit of Garrett Hayes, a physician who provided care to Baby Davis at Cook County Hospital." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_6.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_6.toml new file mode 100644 index 0000000000000000000000000000000000000000..deef1062a1baf31831b401ae0f342a7c67549614 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_6.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_6" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies in Assignment #2 that the affidavit by Liam Vance indicates that DuPage County would be an inconvenient forum for him to litigate this case as required under Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006)." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_7.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_7.toml new file mode 100644 index 0000000000000000000000000000000000000000..90e71f72e9dd7ba34625531a395987e3fa699974 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_7.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_7" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies in Assignment #2 that the affidavit by Savannah Brooks indicates that DuPage County would be an inconvenient forum for her to litigate this case as required under Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006)." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_8.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_8.toml new file mode 100644 index 0000000000000000000000000000000000000000..5aa7bb33998bf032d297f3d3876922ee290a9ea6 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_8.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_8" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies in Assignment #2 that the affidavit by Caleb Montgomery indicates that DuPage County would be an inconvenient forum for him to litigate this case as required under Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006)." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_9.toml b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_9.toml new file mode 100644 index 0000000000000000000000000000000000000000..cb96121cc6eb9e1e4b9e066812c35e113cdb5089 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/raw_correctness/criterion_9.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_9" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies in Assignment #2 that the affidavit by Maya Linwood indicates that DuPage County would be an inconvenient forum for her to litigate this case as required under Langenhorst v. Norfolk S. Ry. Co. 219 Ill. 2d 430 (Ill. 2006)." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/test.sh b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..66a509a7bcdbe412851f3a012a5ba7b16cf0925b --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/tests/test.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +set -euo pipefail + +mkdir -p /logs/artifacts /logs/verifier/raw + +python3 - <<'PYEOF' +import json +import shutil +from pathlib import Path + + +def has_text(path: Path) -> bool: + return path.exists() and path.is_file() and bool(path.read_text(errors="replace").strip()) + + +def fallback_paths(answer_path: Path) -> list[Path]: + paths = [] + try: + relative = answer_path.relative_to("/app") + paths.append(Path("/app/app") / relative) + except ValueError: + pass + return [path for path in paths if path != answer_path] + + +config = json.loads(Path("/tests/fixtures/config.json").read_text()) +answer_path = Path(config["answer_path"]) +artifact_answer = Path("/logs/artifacts/answer.md") +artifact_answer.parent.mkdir(parents=True, exist_ok=True) +if has_text(answer_path): + shutil.copyfile(answer_path, artifact_answer) +else: + for candidate in fallback_paths(answer_path): + if has_text(candidate): + shutil.copyfile(candidate, artifact_answer) + break + else: + artifact_answer.write_text("") + +# Harbor collects /logs/artifacts when the agent step ends, which is before this +# script runs, so the copy above never reaches the uploaded artifacts. /logs/verifier +# is uploaded after the verifier phase, so persist the graded answer there too. +verifier_answer = Path("/logs/verifier/answer.md") +verifier_answer.parent.mkdir(parents=True, exist_ok=True) +shutil.copyfile(artifact_answer, verifier_answer) +PYEOF + +uv run --no-project --with 'harbor-rewardkit[all]==0.2.0' python /tests/m1_rewardkit_accounting.py /tests/raw_correctness \ + --workspace /app \ + --output /logs/verifier/raw/reward.json \ + --max-concurrent-llm "${MAX_CONCURRENT_LLM:-4}" \ + --max-concurrent-agent "${M1_MAX_CONCURRENT_AGENT:-1}" + +python /tests/normalize_reward.py \ + --raw-details /logs/verifier/raw/reward-details.json \ + --rubric /tests/fixtures/rubric.json \ + --reward-out /logs/verifier/reward.json \ + --details-out /logs/verifier/reward-details.json diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/workdir/attachments/2023 Annual Report Statistical Summary.pdf b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/workdir/attachments/2023 Annual Report Statistical Summary.pdf new file mode 100644 index 0000000000000000000000000000000000000000..fa4e9d236dd952e3dddc6f532e23a961682b4c6e --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/workdir/attachments/2023 Annual Report Statistical Summary.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8bf34637f28292c0009d408c050124904a8b01111e5020c21ed707d781fd0496 +size 12962846 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/workdir/attachments/Bradbury v. St. Mary's Hospital.pdf b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/workdir/attachments/Bradbury v. St. Mary's Hospital.pdf new file mode 100644 index 0000000000000000000000000000000000000000..2e674eeee065ae4fda7c1470cc78f141eb8bcfe8 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/workdir/attachments/Bradbury v. St. Mary's Hospital.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b5dd36efa5bd84c7fbe31bdbb478817c22500d48e64b24257915e17f6bb5f2a0 +size 572611 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/workdir/attachments/Davis Complaint.docx b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/workdir/attachments/Davis Complaint.docx new file mode 100644 index 0000000000000000000000000000000000000000..422bb8fea94f9a850aa9ee2be513ae586311d2dc Binary files /dev/null and b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/workdir/attachments/Davis Complaint.docx differ diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/workdir/attachments/Defendants Motion to Transfer.pdf b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/workdir/attachments/Defendants Motion to Transfer.pdf new file mode 100644 index 0000000000000000000000000000000000000000..626d4259e34adc22ed9a051cfe6966bdc87fb99f --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/workdir/attachments/Defendants Motion to Transfer.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:54da66d335b9c7a920d8a49fdd49a565244563734b04b01927582170b5f2aadc +size 832692 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/workdir/attachments/First Am Bank v. Guerine.pdf b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/workdir/attachments/First Am Bank v. Guerine.pdf new file mode 100644 index 0000000000000000000000000000000000000000..c0bd2f36bb879d24de686696dc9140cc60c5fbbb --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/workdir/attachments/First Am Bank v. Guerine.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f8a188b924402eeed7075cbb2d4a2a55bc16b75abdf586206e8b470920f3979a +size 498833 diff --git a/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/workdir/attachments/Langenhorst v. Norfolk Southern.pdf b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/workdir/attachments/Langenhorst v. Norfolk Southern.pdf new file mode 100644 index 0000000000000000000000000000000000000000..067db080672db11c40bb312194a28dc4bf2eb190 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/steps/assignment-2/workdir/attachments/Langenhorst v. Norfolk Southern.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:371eb4caa533accf4e6ee180efae95d0e65a563add28df93bcb98e27ae55c5b9 +size 573433 diff --git a/tasks/lrb-forum-non-conveniens-response/task.toml b/tasks/lrb-forum-non-conveniens-response/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a275dba99c23d2120a93fd31b0f84279b7e0aee8 --- /dev/null +++ b/tasks/lrb-forum-non-conveniens-response/task.toml @@ -0,0 +1,76 @@ +schema_version = "1.1" +multi_step_reward_strategy = "mean" + +[task] +name = "micro1/lrb-forum-non-conveniens-response" + +[metadata] +benchmark = "LegalReasonBench" +title = "Plaintiff's Response - Forum Non Conveniens" +practice_area = "Litigation and dispute resolution" +research_universe = "closed-universe" +task_version = "20" +overall_reward = "points-weighted across assignments: sum of earned signed points over sum of positive points, clamped to [0, 1]. Harbor multi_step_reward_strategy=mean is diagnostic only. See scripts/score_matter.py." + +[agent] +timeout_sec = 10800.0 + +[environment] +build_timeout_sec = 900.0 +cpus = 2 +memory_mb = 4096 +storage_mb = 8192 +workdir = "/app" +allow_internet = true + +[environment.env] +OPENCODE_ENABLE_EXA = "${OPENCODE_ENABLE_EXA:-1}" + +[[steps]] +name = "assignment-1" +artifacts = ["/app/response1.md"] + +[steps.agent] +timeout_sec = 10800.0 + +[steps.verifier] +timeout_sec = 1800.0 + +[steps.verifier.env] +OPENAI_API_KEY = "${OPENAI_API_KEY:-}" +ANTHROPIC_API_KEY = "${ANTHROPIC_API_KEY:-}" +GOOGLE_API_KEY = "${GOOGLE_API_KEY:-}" +GEMINI_API_KEY = "${GEMINI_API_KEY:-}" +JUDGE_MODEL = "openai/gpt-5.6-terra" +JUDGE_REASONING_EFFORT = "medium" +JUDGE_TIMEOUT = "1500" +MAX_CONCURRENT_LLM = "12" +M1_MAX_CONCURRENT_AGENT = "1" +M1_JUDGE_TRANSIENT_RETRIES = "12" +M1_JUDGE_EMPTY_RESPONSE_RETRIES = "3" +M1_JUDGE_RETRY_BUDGET_SECONDS = "900" + +[[steps]] +name = "assignment-2" +artifacts = ["/app/response2.md"] + +[steps.agent] +timeout_sec = 10800.0 + +[steps.verifier] +timeout_sec = 1800.0 + +[steps.verifier.env] +OPENAI_API_KEY = "${OPENAI_API_KEY:-}" +ANTHROPIC_API_KEY = "${ANTHROPIC_API_KEY:-}" +GOOGLE_API_KEY = "${GOOGLE_API_KEY:-}" +GEMINI_API_KEY = "${GEMINI_API_KEY:-}" +JUDGE_MODEL = "openai/gpt-5.6-terra" +JUDGE_REASONING_EFFORT = "medium" +JUDGE_TIMEOUT = "1500" +MAX_CONCURRENT_LLM = "12" +M1_MAX_CONCURRENT_AGENT = "1" +M1_JUDGE_TRANSIENT_RETRIES = "12" +M1_JUDGE_EMPTY_RESPONSE_RETRIES = "3" +M1_JUDGE_RETRY_BUDGET_SECONDS = "900" + diff --git a/tasks/lrb-interim-cmo-appointment-governance/environment/Dockerfile b/tasks/lrb-interim-cmo-appointment-governance/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c481aae22685617adcf60d0de6e473ce9019975a --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/environment/Dockerfile @@ -0,0 +1,29 @@ +FROM python:3.13-slim-bookworm + +RUN apt-get update && apt-get install -y --no-install-recommends \ + bash \ + ca-certificates \ + curl \ + file \ + git \ + libreoffice-calc \ + libreoffice-impress \ + libreoffice-writer \ + pandoc \ + poppler-utils \ + unzip \ + fonts-dejavu \ + && rm -rf /var/lib/apt/lists/* + +RUN python -m pip install --no-cache-dir \ + uv \ + openpyxl \ + pandas \ + pdfplumber \ + pypdf \ + python-docx \ + python-pptx \ + xlrd + +WORKDIR /app +RUN ln -s . /app/app diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/instruction.md b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c3ac43007818194024633208fa700fa1a12aa767 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/instruction.md @@ -0,0 +1,59 @@ +# Interim CMO Appointment: Governance and Compliance Analysis — Assignment 1 + +You are a senior legal analyst operating autonomously. You are completing a multi-step legal reasoning task. Follow the role, factual record, instructions, and deliverable requirements provided in the Task and each Assignment. + +Each Assignment may require a different legal deliverable. Follow the requirements specific to that Assignment. + +## Word limits for court briefs + +- A brief in support of or in response to a motion may not exceed **8,750 words**. +- A reply brief may not exceed **3,500 words**. +- For a motion for reconsideration, a brief in support of or in response to the motion may not exceed **3,500 words**, and a reply brief may not exceed **1,750 words**. +- If an Assignment specifies a stricter word limit, follow the stricter limit. + +These word limits do not apply to legal memoranda or other non-court-filing deliverables unless the Assignment expressly provides otherwise. + +Complete the task end-to-end without asking for confirmation, permission, or clarification. + +Use the uploaded matter documents in `/app/attachments/` as your primary case file. You also have internet access via OpenCode's `websearch` tool; use it to research any statutes, regulations, cases, administrative guidance, or secondary authorities that are not supplied as attachments. Cite any authority you rely on in the format requested by the prompt. + +For document inspection: +- PDF: `pdftotext /app/attachments/.pdf -` +- DOCX: `pandoc /app/attachments/.docx -t markdown` +- XLSX/CSV: use Python with `openpyxl` or `pandas` +- If extraction is unreliable, inspect the raw file with Python libraries or convert/render the relevant pages. + +Write the final complete legal deliverable for this assignment to `/app/response1.md`. The verifier reads only that file. + +## Attachments + +- `/app/attachments/IHP_Board_Meeting_Calendar_2026.docx` +- `/app/attachments/IHP_Board_Resolution_2026-14.docx` +- `/app/attachments/IHP_CEO_Email_Executive_Staff_Connors_Announcement.docx` +- `/app/attachments/IHP_CMO_Interim_Appointment_Letter_Connors.docx` +- `/app/attachments/IHP_GC_Memo_Appointment_Ratification.docx` +- `/app/attachments/IHP_Regulatory_Reference_Compilation_KKA_2026.docx` +- `/app/attachments/IHP_Bylaws_Excerpt_Article_V_Officers.docx` + + +## Prompt + +You are regulatory compliance counsel for Imperium Health Plan, Inc. ("IHP"), a full-service health care service plan licensed by the California Department of Managed Health Care (DMHC) under the Knox-Keene Health Care Service Plan Act of 1975, headquartered in Sacramento, California. IHP's Chief Medical Officer (CMO) departed the plan effective May 6, 2026. On May 7, 2026, IHP's Chief Executive Officer, Mary T. Lee, appointed Dr. Elena Connors as Interim Chief Medical Officer. The Board of Directors adopted Resolution 2026-14 on May 13, 2026, and the General Counsel has circulated a memorandum concluding that the matter is resolved. The Chief Executive Officer (CEO) has asked you to independently review the governance record and advise the plan. + +The following documents have been uploaded and constitute the complete and exclusive universe of materials for this assignment: + +Interim CMO Appointment Letter — Dr. Connors (IHP_CMO_Interim_Appointment_Letter_Connors.docx) +CEO Announcement Email to Executive Staff (IHP_CEO_Email_Executive_Staff_Connors_Announcement.docx) +Bylaws Excerpt, Article V — Officers (IHP_Bylaws_Excerpt_Article_V_Officers.docx) +Board Resolution 2026-14 (IHP_Board_Resolution_2026-14.docx) +General Counsel Memorandum — Appointment Ratification (IHP_GC_Memo_Appointment_Ratification.docx) +Board of Directors 2026 Regular Meeting Schedule (IHP_Board_Meeting_Calendar_2026.docx) +Regulatory Reference Compilation — Key Personnel and Governance (IHP_Regulatory_Reference_Compilation_KKA_2026.docx) + +Do not rely on, reference, or infer any legal authority, factual information, or data beyond what is contained in these uploaded files. If a document is not uploaded, it does not exist for purposes of this analysis. All citations must reference the uploaded document by its exact name as listed above, followed by the specific page and section. + +Prepare a legal memorandum addressed to the Chief Executive Officer, from Regulatory Compliance Counsel, dated May 15, 2026. The memorandum should be structured as a formal legal memorandum appropriate for a General Counsel audience. All legal analysis must be based solely on the law and guidance as it exists on May 15, 2026. Do not account for any legislative changes, regulatory updates, or DMHC guidance issued after that date. Where a conclusion depends on a date, deadline, or computation, state it and show how you arrived at it. The memorandum must address all of the following: + +1) Prepare a chronology of the corporate and governance actions relating to Dr. Connors' appointment, identifying for each action the actor, the date, and the source of corporate authority for the action as reflected in the files provided. + +2) Assess the validity and current effectiveness of Dr. Connors' appointment as Interim Chief Medical Officer, including the legal effect of Board Resolution 2026-14 on the appointment. diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/solution/solve.sh b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7710414a6da6d0ad740717c8c85a9af850d5da33 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/solution/solve.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# No oracle solution ships with LegalReasonBench. The verifier grades the +# agent's own legal deliverable for this assignment against the rubric. +echo "no oracle solution" diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/fixtures/config.json b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/fixtures/config.json new file mode 100644 index 0000000000000000000000000000000000000000..074be9450fccbe8e67d0987301eabd94a70b8b26 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/fixtures/config.json @@ -0,0 +1,204 @@ +{ + "task_id": "lrb-interim-cmo-appointment-governance", + "title": "Interim CMO Appointment: Governance and Compliance Analysis", + "domain": "", + "matter": "", + "judge": { + "max_concurrent_llm": 12, + "mode": "panel", + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ], + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + "step_index": 1, + "step_name": "assignment-1", + "step_title": "", + "prompt": "You are regulatory compliance counsel for Imperium Health Plan, Inc. (\"IHP\"), a full-service health care service plan licensed by the California Department of Managed Health Care (DMHC) under the Knox-Keene Health Care Service Plan Act of 1975, headquartered in Sacramento, California. IHP's Chief Medical Officer (CMO) departed the plan effective May 6, 2026. On May 7, 2026, IHP's Chief Executive Officer, Mary T. Lee, appointed Dr. Elena Connors as Interim Chief Medical Officer. The Board of Directors adopted Resolution 2026-14 on May 13, 2026, and the General Counsel has circulated a memorandum concluding that the matter is resolved. The Chief Executive Officer (CEO) has asked you to independently review the governance record and advise the plan.\n\nThe following documents have been uploaded and constitute the complete and exclusive universe of materials for this assignment:\n\nInterim CMO Appointment Letter \u2014 Dr. Connors (IHP_CMO_Interim_Appointment_Letter_Connors.docx)\nCEO Announcement Email to Executive Staff (IHP_CEO_Email_Executive_Staff_Connors_Announcement.docx)\nBylaws Excerpt, Article V \u2014 Officers (IHP_Bylaws_Excerpt_Article_V_Officers.docx)\nBoard Resolution 2026-14 (IHP_Board_Resolution_2026-14.docx)\nGeneral Counsel Memorandum \u2014 Appointment Ratification (IHP_GC_Memo_Appointment_Ratification.docx)\nBoard of Directors 2026 Regular Meeting Schedule (IHP_Board_Meeting_Calendar_2026.docx)\nRegulatory Reference Compilation \u2014 Key Personnel and Governance (IHP_Regulatory_Reference_Compilation_KKA_2026.docx)\n\nDo not rely on, reference, or infer any legal authority, factual information, or data beyond what is contained in these uploaded files. If a document is not uploaded, it does not exist for purposes of this analysis. All citations must reference the uploaded document by its exact name as listed above, followed by the specific page and section.\n\nPrepare a legal memorandum addressed to the Chief Executive Officer, from Regulatory Compliance Counsel, dated May 15, 2026. The memorandum should be structured as a formal legal memorandum appropriate for a General Counsel audience. All legal analysis must be based solely on the law and guidance as it exists on May 15, 2026. Do not account for any legislative changes, regulatory updates, or DMHC guidance issued after that date. Where a conclusion depends on a date, deadline, or computation, state it and show how you arrived at it. The memorandum must address all of the following:\n\n1) Prepare a chronology of the corporate and governance actions relating to Dr. Connors' appointment, identifying for each action the actor, the date, and the source of corporate authority for the action as reflected in the files provided.\n\n2) Assess the validity and current effectiveness of Dr. Connors' appointment as Interim Chief Medical Officer, including the legal effect of Board Resolution 2026-14 on the appointment.", + "attachments": [ + { + "filename": "IHP_Board_Meeting_Calendar_2026.docx", + "description": "", + "metadata": {}, + "path": "/app/attachments/IHP_Board_Meeting_Calendar_2026.docx" + }, + { + "filename": "IHP_Board_Resolution_2026-14.docx", + "description": "", + "metadata": {}, + "path": "/app/attachments/IHP_Board_Resolution_2026-14.docx" + }, + { + "filename": "IHP_CEO_Email_Executive_Staff_Connors_Announcement.docx", + "description": "", + "metadata": {}, + "path": "/app/attachments/IHP_CEO_Email_Executive_Staff_Connors_Announcement.docx" + }, + { + "filename": "IHP_CMO_Interim_Appointment_Letter_Connors.docx", + "description": "", + "metadata": {}, + "path": "/app/attachments/IHP_CMO_Interim_Appointment_Letter_Connors.docx" + }, + { + "filename": "IHP_GC_Memo_Appointment_Ratification.docx", + "description": "", + "metadata": {}, + "path": "/app/attachments/IHP_GC_Memo_Appointment_Ratification.docx" + }, + { + "filename": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx", + "description": "", + "metadata": {}, + "path": "/app/attachments/IHP_Regulatory_Reference_Compilation_KKA_2026.docx" + }, + { + "filename": "IHP_Bylaws_Excerpt_Article_V_Officers.docx", + "description": "", + "metadata": {}, + "path": "/app/attachments/IHP_Bylaws_Excerpt_Article_V_Officers.docx" + } + ], + "rubric": [ + { + "name": "criterion_1", + "description": "Identifies that no Board resolution authorizing Dr. Connors' appointment as Interim Chief Medical Officer exists in the governance record prior to May 13, 2026.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 1, Section 5.2 (\"No appointment of a principal officer shall be effective unless and until approved by the Board of Directors in accordance with this Section 5.2\"); IHP_Board_Resolution_2026-14.docx, p. 2, Record of Adoption (\"The foregoing Resolution was duly adopted at the regular meeting of the Board of Directors of Imperium Health Plan, Inc. held on May 13, 2026, at which a quorum was present and acting throughout\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Prepare a chronology of the corporate and governance actions relating to Dr. Connors' appointment, identifying for each action the actor, the date, and the source of corporate authority for the action as reflected in the files provided.\" A complete chronology requires the model to identify the authorization gap, the absence of any Board action before May 13, as the foundational sequencing fact from which the validity defect flows. Section 5.2 establishes the complete set of valid authorization vehicles; the absence of either before May 13 is verifiable by exclusion from the governance record.", + "metadata": { + "irac_section": "Issue" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_2", + "description": "Identifies the CEO Announcement Email dated May 8, 2026 as evidence that Dr. Connors began exercising CMO duties before the Board adopted Resolution 2026-14.", + "source": "IHP_CEO_Email_Executive_Staff_Connors_Announcement.docx, p. 1, body paragraph 1 (\"Dr. Connors assumed the role yesterday and has already begun exercising the duties of the position, including oversight of the utilization management program, quality assurance program, and provider credentialing\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Prepare a chronology of the corporate and governance actions relating to Dr. Connors' appointment, identifying for each action the actor, the date, and the source of corporate authority for the action as reflected in the files provided.\" A complete chronology requires the model to identify the CEO's direction to staff as a discrete governance event, the reliance evidence that Dr. Connors exercised CMO authority during the period before Board ratification.", + "metadata": { + "irac_section": "Issue" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_3", + "description": "States that Section 5.2 of the Bylaws requires Board approval for the appointment of any principal officer.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 1, Section 5.2 (\"The appointment of a principal officer shall require approval by resolution of the Board of Directors adopted at a duly noticed meeting at which a quorum is present, or by unanimous written consent pursuant to Section 5.10 of these Bylaws. No appointment of a principal officer shall be effective unless and until approved by the Board of Directors in accordance with this Section 5.2\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Assess the validity and current effectiveness of Dr. Connors' appointment as Interim Chief Medical Officer, including the legal effect of Board Resolution 2026-14 on the appointment.\" Section 5.2 is the controlling rule on CEO appointment authority. The validity analysis cannot proceed without correctly identifying this provision and its effect.", + "metadata": { + "irac_section": "Rule" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_4", + "description": "States that Section 5.9 of the Bylaws provides that ratification is effective upon adoption of the ratifying resolution.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall be effective upon adoption of the ratifying resolution\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Assess the validity and current effectiveness of Dr. Connors' appointment as Interim Chief Medical Officer, including the legal effect of Board Resolution 2026-14 on the appointment.\" Section 5.9 establishes when ratification takes effect. Combined with Section 5.2's requirement that no appointment is effective until Board approval is obtained, these two provisions together establish that the appointment became effective on May 13, 2026, the date of adoption.", + "metadata": { + "irac_section": "Rule" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_5", + "description": "States that Section 5.10 of the Bylaws permits the Board to act by unanimous written consent in lieu of a meeting.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2-3, Section 5.10 (\"Any action required or permitted to be taken by the Board of Directors at a meeting may be taken without a meeting if all members of the Board individually or collectively consent in writing to that action. Such unanimous written consent shall have the same force and effect as a unanimous vote at a duly held meeting\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"Any instrument you draft must be capable of valid adoption under IHP's governing documents within the time your Step 2 analysis requires.\" Section 5.10 is the only adoption vehicle available before the computed filing deadline. The next regular Board meeting falls on June 10, 2026, after May 18. A model that identifies this mechanism demonstrates the governance literacy required to produce a valid corrective instrument in Step 3.", + "metadata": { + "irac_section": "Rule" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_6", + "description": "Identifies the Chief Medical Officer as a principal officer of IHP under Section 5.1 of the Bylaws.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 1, Section 5.1 (\"The principal officers of the Corporation shall be a Chief Executive Officer, a Chief Financial Officer, a Chief Operating Officer, a Chief Medical Officer, a General Counsel\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"Assess the validity and current effectiveness of Dr. Connors' appointment as Interim Chief Medical Officer, including the legal effect of Board Resolution 2026-14 on the appointment.\" The Section 5.1 classification is the predicate for applying Section 5.2's Board-approval requirement. A model that applies Section 5.2 without grounding it in Section 5.1 has reached the right conclusion through incomplete reasoning.", + "metadata": { + "irac_section": "Application" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_7", + "description": "States that the CEO's May 7 appointment letter lacked the Board authorization required by Section 5.2 of the Bylaws, rendering the appointment defective at issuance.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 1, Section 5.2 (\"No appointment of a principal officer shall be effective unless and until approved by the Board of Directors in accordance with this Section 5.2\"); IHP_CMO_Interim_Appointment_Letter_Connors.docx, p. 1, opening paragraph (\"effective immediately, you are appointed to serve as Interim Chief Medical Officer of Imperium Health Plan, Inc.\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Assess the validity and current effectiveness of Dr. Connors' appointment as Interim Chief Medical Officer, including the legal effect of Board Resolution 2026-14 on the appointment.\" The defective-at-issuance classification is the first contested judgment in the task. It requires the model to apply Section 5.2 to the CEO's unilateral action, a step the GC memo bypasses by assuming the appointment was within the CEO's authority.", + "metadata": { + "irac_section": "Application" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_8", + "description": "States that Resolution 2026-14's designation of May 7, 2026 as the effective date of the ratification is ineffective under Section 5.9 of the Bylaws.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall be effective upon adoption of the ratifying resolution and shall not operate retroactively to cure any deficiency in authorization for the period preceding adoption\"); IHP_Board_Resolution_2026-14.docx, p. 1, NOW THEREFORE clause (\"hereby ratifies and approves the appointment of Elena Connors, M.D., as Interim Chief Medical Officer of the Corporation, effective as of May 7, 2026\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Assess the validity and current effectiveness of Dr. Connors' appointment as Interim Chief Medical Officer, including the legal effect of Board Resolution 2026-14 on the appointment.\" This is the core judgment item in Step 1. The model must apply Section 5.9's anti-retroactivity rule directly to the Resolution's \"effective as of May 7\" language and conclude that the recital is ineffective, the opposite of the GC memo's conclusion.", + "metadata": { + "irac_section": "Application" + }, + "score": 6.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_10", + "description": "States that Dr. Connors' appointment as Interim Chief Medical Officer is valid effective as of May 13, 2026.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall be effective upon adoption of the ratifying resolution and shall not operate retroactively to cure any deficiency in authorization for the period preceding adoption\"); IHP_Board_Resolution_2026-14.docx, p. 2, Record of Adoption (\"The foregoing Resolution was duly adopted at the regular meeting of the Board of Directors of Imperium Health Plan, Inc. held on May 13, 2026, at which a quorum was present and acting throughout\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Assess the validity and current effectiveness of Dr. Connors' appointment as Interim Chief Medical Officer, including the legal effect of Board Resolution 2026-14 on the appointment.\" The May 13th effective date is the correct conclusion and required for all downstream calculations.", + "metadata": { + "irac_section": "Conclusion" + }, + "score": 7.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_11", + "description": "States that Dr. Connors' appointment was valid as of May 7, 2026.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall be effective upon adoption of the ratifying resolution and shall not operate retroactively to cure any deficiency in authorization for the period preceding adoption\"); IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 1, Section 5.2 (\"No appointment of a principal officer shall be effective unless and until approved by the Board of Directors in accordance with this Section 5.2\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"Assess the validity and current effectiveness of Dr. Connors' appointment as Interim Chief Medical Officer, including the legal effect of Board Resolution 2026-14 on the appointment.\" The Bylaws specify when ratification is effective and when an appointment becomes valid. A model that adopts May 7th as the operative date has relied upon a general corporate law doctrine that the specific governing-document text displaces. Accurately reporting the GC memo's or Resolution 2026-14's position while rejecting it does not trigger this item.", + "metadata": { + "irac_section": "Conclusion" + }, + "score": -10.0, + "polarity": "negative", + "raw_weight": 1.0 + } + ], + "answer_path": "/app/response1.md", + "answer_relative_path": "response1.md", + "is_followon": false, + "prev_answer_path": "" +} diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/fixtures/rubric.json b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/fixtures/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..5344e0367592361bee8fb558ecfcc02b9dde19cd --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/fixtures/rubric.json @@ -0,0 +1,124 @@ +{ + "criteria": [ + { + "name": "criterion_1", + "description": "Identifies that no Board resolution authorizing Dr. Connors' appointment as Interim Chief Medical Officer exists in the governance record prior to May 13, 2026.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 1, Section 5.2 (\"No appointment of a principal officer shall be effective unless and until approved by the Board of Directors in accordance with this Section 5.2\"); IHP_Board_Resolution_2026-14.docx, p. 2, Record of Adoption (\"The foregoing Resolution was duly adopted at the regular meeting of the Board of Directors of Imperium Health Plan, Inc. held on May 13, 2026, at which a quorum was present and acting throughout\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Prepare a chronology of the corporate and governance actions relating to Dr. Connors' appointment, identifying for each action the actor, the date, and the source of corporate authority for the action as reflected in the files provided.\" A complete chronology requires the model to identify the authorization gap, the absence of any Board action before May 13, as the foundational sequencing fact from which the validity defect flows. Section 5.2 establishes the complete set of valid authorization vehicles; the absence of either before May 13 is verifiable by exclusion from the governance record.", + "metadata": { + "irac_section": "Issue" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_2", + "description": "Identifies the CEO Announcement Email dated May 8, 2026 as evidence that Dr. Connors began exercising CMO duties before the Board adopted Resolution 2026-14.", + "source": "IHP_CEO_Email_Executive_Staff_Connors_Announcement.docx, p. 1, body paragraph 1 (\"Dr. Connors assumed the role yesterday and has already begun exercising the duties of the position, including oversight of the utilization management program, quality assurance program, and provider credentialing\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Prepare a chronology of the corporate and governance actions relating to Dr. Connors' appointment, identifying for each action the actor, the date, and the source of corporate authority for the action as reflected in the files provided.\" A complete chronology requires the model to identify the CEO's direction to staff as a discrete governance event, the reliance evidence that Dr. Connors exercised CMO authority during the period before Board ratification.", + "metadata": { + "irac_section": "Issue" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_3", + "description": "States that Section 5.2 of the Bylaws requires Board approval for the appointment of any principal officer.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 1, Section 5.2 (\"The appointment of a principal officer shall require approval by resolution of the Board of Directors adopted at a duly noticed meeting at which a quorum is present, or by unanimous written consent pursuant to Section 5.10 of these Bylaws. No appointment of a principal officer shall be effective unless and until approved by the Board of Directors in accordance with this Section 5.2\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Assess the validity and current effectiveness of Dr. Connors' appointment as Interim Chief Medical Officer, including the legal effect of Board Resolution 2026-14 on the appointment.\" Section 5.2 is the controlling rule on CEO appointment authority. The validity analysis cannot proceed without correctly identifying this provision and its effect.", + "metadata": { + "irac_section": "Rule" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_4", + "description": "States that Section 5.9 of the Bylaws provides that ratification is effective upon adoption of the ratifying resolution.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall be effective upon adoption of the ratifying resolution\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Assess the validity and current effectiveness of Dr. Connors' appointment as Interim Chief Medical Officer, including the legal effect of Board Resolution 2026-14 on the appointment.\" Section 5.9 establishes when ratification takes effect. Combined with Section 5.2's requirement that no appointment is effective until Board approval is obtained, these two provisions together establish that the appointment became effective on May 13, 2026, the date of adoption.", + "metadata": { + "irac_section": "Rule" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_5", + "description": "States that Section 5.10 of the Bylaws permits the Board to act by unanimous written consent in lieu of a meeting.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2-3, Section 5.10 (\"Any action required or permitted to be taken by the Board of Directors at a meeting may be taken without a meeting if all members of the Board individually or collectively consent in writing to that action. Such unanimous written consent shall have the same force and effect as a unanimous vote at a duly held meeting\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"Any instrument you draft must be capable of valid adoption under IHP's governing documents within the time your Step 2 analysis requires.\" Section 5.10 is the only adoption vehicle available before the computed filing deadline. The next regular Board meeting falls on June 10, 2026, after May 18. A model that identifies this mechanism demonstrates the governance literacy required to produce a valid corrective instrument in Step 3.", + "metadata": { + "irac_section": "Rule" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_6", + "description": "Identifies the Chief Medical Officer as a principal officer of IHP under Section 5.1 of the Bylaws.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 1, Section 5.1 (\"The principal officers of the Corporation shall be a Chief Executive Officer, a Chief Financial Officer, a Chief Operating Officer, a Chief Medical Officer, a General Counsel\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"Assess the validity and current effectiveness of Dr. Connors' appointment as Interim Chief Medical Officer, including the legal effect of Board Resolution 2026-14 on the appointment.\" The Section 5.1 classification is the predicate for applying Section 5.2's Board-approval requirement. A model that applies Section 5.2 without grounding it in Section 5.1 has reached the right conclusion through incomplete reasoning.", + "metadata": { + "irac_section": "Application" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_7", + "description": "States that the CEO's May 7 appointment letter lacked the Board authorization required by Section 5.2 of the Bylaws, rendering the appointment defective at issuance.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 1, Section 5.2 (\"No appointment of a principal officer shall be effective unless and until approved by the Board of Directors in accordance with this Section 5.2\"); IHP_CMO_Interim_Appointment_Letter_Connors.docx, p. 1, opening paragraph (\"effective immediately, you are appointed to serve as Interim Chief Medical Officer of Imperium Health Plan, Inc.\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Assess the validity and current effectiveness of Dr. Connors' appointment as Interim Chief Medical Officer, including the legal effect of Board Resolution 2026-14 on the appointment.\" The defective-at-issuance classification is the first contested judgment in the task. It requires the model to apply Section 5.2 to the CEO's unilateral action, a step the GC memo bypasses by assuming the appointment was within the CEO's authority.", + "metadata": { + "irac_section": "Application" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_8", + "description": "States that Resolution 2026-14's designation of May 7, 2026 as the effective date of the ratification is ineffective under Section 5.9 of the Bylaws.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall be effective upon adoption of the ratifying resolution and shall not operate retroactively to cure any deficiency in authorization for the period preceding adoption\"); IHP_Board_Resolution_2026-14.docx, p. 1, NOW THEREFORE clause (\"hereby ratifies and approves the appointment of Elena Connors, M.D., as Interim Chief Medical Officer of the Corporation, effective as of May 7, 2026\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Assess the validity and current effectiveness of Dr. Connors' appointment as Interim Chief Medical Officer, including the legal effect of Board Resolution 2026-14 on the appointment.\" This is the core judgment item in Step 1. The model must apply Section 5.9's anti-retroactivity rule directly to the Resolution's \"effective as of May 7\" language and conclude that the recital is ineffective, the opposite of the GC memo's conclusion.", + "metadata": { + "irac_section": "Application" + }, + "score": 6.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_10", + "description": "States that Dr. Connors' appointment as Interim Chief Medical Officer is valid effective as of May 13, 2026.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall be effective upon adoption of the ratifying resolution and shall not operate retroactively to cure any deficiency in authorization for the period preceding adoption\"); IHP_Board_Resolution_2026-14.docx, p. 2, Record of Adoption (\"The foregoing Resolution was duly adopted at the regular meeting of the Board of Directors of Imperium Health Plan, Inc. held on May 13, 2026, at which a quorum was present and acting throughout\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Assess the validity and current effectiveness of Dr. Connors' appointment as Interim Chief Medical Officer, including the legal effect of Board Resolution 2026-14 on the appointment.\" The May 13th effective date is the correct conclusion and required for all downstream calculations.", + "metadata": { + "irac_section": "Conclusion" + }, + "score": 7.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_11", + "description": "States that Dr. Connors' appointment was valid as of May 7, 2026.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall be effective upon adoption of the ratifying resolution and shall not operate retroactively to cure any deficiency in authorization for the period preceding adoption\"); IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 1, Section 5.2 (\"No appointment of a principal officer shall be effective unless and until approved by the Board of Directors in accordance with this Section 5.2\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"Assess the validity and current effectiveness of Dr. Connors' appointment as Interim Chief Medical Officer, including the legal effect of Board Resolution 2026-14 on the appointment.\" The Bylaws specify when ratification is effective and when an appointment becomes valid. A model that adopts May 7th as the operative date has relied upon a general corporate law doctrine that the specific governing-document text displaces. Accurately reporting the GC memo's or Resolution 2026-14's position while rejecting it does not trigger this item.", + "metadata": { + "irac_section": "Conclusion" + }, + "score": -10.0, + "polarity": "negative", + "raw_weight": 1.0 + } + ] +} diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/m1_judge_panel.json b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/m1_judge_panel.json new file mode 100644 index 0000000000000000000000000000000000000000..a8041f6781a899f9083fe4a1a95f51bc78d35601 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/m1_judge_panel.json @@ -0,0 +1,21 @@ +{ + "mode": "panel", + "max_concurrent_llm": 12, + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ] +} diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/m1_rewardkit_accounting.py b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/m1_rewardkit_accounting.py new file mode 100644 index 0000000000000000000000000000000000000000..406dc5e7c675b222d94514e71bf5fad6ae141d8f --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/m1_rewardkit_accounting.py @@ -0,0 +1,490 @@ +import asyncio +import json +import math +import os +from pathlib import Path +import random +import sys +import time + +class JudgeReceiptError(OSError): + pass +_LLM_ROUTES = frozenset({'vertex', 'anthropic fallback', 'aistudio', 'direct'}) +_LLM_ROUTE_HEADERS = ('x-m1-llm-route', 'llm_provider-x-m1-llm-route') + +def _canonical_llm_route(value): + return value if isinstance(value, str) and value in _LLM_ROUTES else None + +def _llm_route_from_headers(headers): + if not isinstance(headers, dict): + return None + folded = {str(key).lower(): value for key, value in headers.items()} + for name in _LLM_ROUTE_HEADERS: + route = _canonical_llm_route(folded.get(name)) + if route is not None: + return route + return None + +def _llm_route_from_response(response): + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + route = _llm_route_from_headers(headers) + if route is not None: + return route + return _llm_route_from_headers(getattr(response, 'headers', None)) + +def _token_field_status(values, key): + if not isinstance(values, dict) or key not in values: + return 'missing' + value = values[key] + if value is None: + return 'null' + return 'valid' if type(value) is int and value >= 0 else 'invalid' + +def _gemini_capture(kwargs, model): + if not model.startswith('gemini/') or kwargs.get('stream') or kwargs.get('tools') or kwargs.get('functions'): + return (kwargs, None) + from litellm.integrations.custom_logger import CustomLogger + from urllib.parse import urlsplit + + class Capture(CustomLogger): + evidence = None + prompt_status = 'not_observed' + llm_route = None + + def log_post_api_call(self, kwargs, response_obj, start_time, end_time): + self.evidence = None + self.prompt_status = 'not_observed' + try: + params = kwargs.get('litellm_params') or {} + route = urlsplit(params.get('api_base') or '') + bare = model.removeprefix('gemini/') + gemini = params.get('custom_llm_provider') == 'gemini' + ai_studio = gemini and route.hostname == 'generativelanguage.googleapis.com' and (route.path in {'/' + version + '/models/' + bare + ':generateContent' for version in ('v1alpha', 'v1beta')}) + broker = urlsplit(os.environ.get('GEMINI_API_BASE') or '') + brokered = gemini and bool(broker.netloc) and (route.netloc == broker.netloc) and (broker.path.rstrip('/').rsplit('/', 1)[-1] in ('v1alpha', 'v1beta')) and (route.path == broker.path.rstrip('/') + '/models/' + bare + ':generateContent') + vertex = params.get('custom_llm_provider') == 'vertex_ai' and route.hostname == 'aiplatform.googleapis.com' and route.path.startswith('/v1/projects/') and route.path.endswith('/locations/global/publishers/google/models/' + bare + ':generateContent') + if route.scheme != 'https' or not (ai_studio or brokered or vertex) or kwargs.get('stream'): + return + self.llm_route = 'vertex' if vertex else 'aistudio' if ai_studio else None + raw = kwargs.get('original_response') + raw = json.loads(raw) if isinstance(raw, str) else raw + if not isinstance(raw, dict): + return + candidates = raw.get('candidates') + if not isinstance(candidates, list) or not candidates or any((not isinstance(c, dict) or not c.get('finishReason') for c in candidates)) or (not isinstance(raw.get('modelVersion'), str)) or (not raw['modelVersion']): + return + usage = raw.get('usageMetadata') + self.prompt_status = _token_field_status(usage, 'promptTokenCount') + if not isinstance(usage, dict): + return + fields = ('promptTokenCount', 'candidatesTokenCount', 'thoughtsTokenCount', 'cachedContentTokenCount', 'totalTokenCount', 'toolUsePromptTokenCount') + counts = {key: usage.get(key, 0) for key in fields} + if not {'promptTokenCount', 'totalTokenCount'} <= usage.keys() or any((type(n) is not int or n < 0 for n in counts.values())) or counts['toolUsePromptTokenCount'] != 0 or (counts['cachedContentTokenCount'] > counts['promptTokenCount']) or (counts['totalTokenCount'] != counts['promptTokenCount'] + counts['candidatesTokenCount'] + counts['thoughtsTokenCount']): + return + self.evidence = {'protocol': 'gemini-generate-content-' + ('vertex-v1' if vertex else route.path.split('/')[-3]), 'model_version': raw['modelVersion'], 'usage_metadata': {key: usage[key] for key in fields if key in usage}, 'defaulted_fields': [key for key in fields if key not in usage]} + except (TypeError, ValueError, AttributeError): + return + capture = Capture() + return ({**kwargs, 'callbacks': [*(kwargs.get('callbacks') or []), capture]}, capture) + +def _record_judge_usage(response, model: str, *, target: Path | None=None, native_usage: dict | None=None, native_prompt_status: str | None=None, llm_route: str | None=None) -> None: + import fcntl + from datetime import datetime, timezone + data = response.model_dump() if hasattr(response, 'model_dump') else response + usage = data.get('usage') if isinstance(data, dict) else None + granularity = data.get('usage_granularity') if isinstance(data, dict) else None + if not isinstance(usage, dict): + usage = {} + granularity = 'missing_provider_receipt' + prompt, completion = (usage.get('prompt_tokens'), usage.get('completion_tokens')) + native_fresh = usage.get('input_uncached_tokens') + prompt = prompt if type(prompt) is int and prompt >= 0 else None + native_fresh = native_fresh if type(native_fresh) is int and native_fresh >= 0 else None + if type(completion) is not int or completion < 0 or (prompt is None and native_fresh is None): + completion = completion if type(completion) is int and completion >= 0 else 0 + granularity = granularity or 'invalid_provider_receipt' + details = usage.get('prompt_tokens_details') + if details is not None and (not isinstance(details, dict)): + granularity = 'invalid_provider_receipt' + details = details if isinstance(details, dict) else {} + cached = details.get('cached_tokens') + if native_usage is not None: + native = native_usage['usage_metadata'] + native_output = native.get('candidatesTokenCount', 0) + native.get('thoughtsTokenCount', 0) + if prompt == native['promptTokenCount'] and completion == native_output: + cached = native.get('cachedContentTokenCount', 0) + else: + native_usage = None + written = next((value for value in (usage.get('input_cache_write_tokens'), usage.get('cache_creation_input_tokens'), details.get('cache_creation_tokens'), details.get('cache_write_tokens')) if value is not None), None) + invalid = any((value is not None and (type(value) is not int or value < 0) for value in (cached, written))) + cached = cached if type(cached) is int and cached >= 0 else None + written = written if type(written) is int and written >= 0 else None + fresh = native_fresh + if fresh is None and prompt is not None and (cached is not None) and (written is not None): + fresh = prompt - cached - written + if fresh is not None and (fresh < 0 or (prompt is not None and cached is not None and (written is not None) and (fresh + cached + written != prompt))): + invalid, fresh = (True, None) + provider, _, slug = model.partition('/') + event: dict = {'type': 'step_finish', 'part': {'providerID': provider if slug else 'openai', 'modelID': slug or model, 'tokens': {'input': fresh, 'output': completion, 'cache': {'read': cached, 'write': written}}}} + field_status = {'prompt_tokens': _token_field_status(usage, 'prompt_tokens'), 'completion_tokens': _token_field_status(usage, 'completion_tokens'), 'input_uncached_tokens': _token_field_status(usage, 'input_uncached_tokens')} + field_status['native_prompt_token_count'] = native_prompt_status if native_prompt_status in {'missing', 'null', 'invalid', 'valid', 'not_observed'} else 'unsupported' + part: dict = event['part'] + part['usage_field_status'] = field_status + if native_usage is not None: + event['part']['native_usage'] = native_usage + event['part']['token_categories_provenance'] = 'explicit_presence_v1' + if fresh is None and prompt is not None: + event['part']['prompt_tokens_inclusive'] = prompt + if invalid or any((value is None for value in (fresh, cached, written))): + granularity = granularity if granularity not in (None, 'request') else 'invalid_provider_receipt' if invalid else 'incomplete_token_categories' + if granularity: + event['part']['usage_granularity'] = granularity + if provider == 'openrouter': + cost = usage.get('cost') + if cost is None: + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + if isinstance(headers, dict): + cost = headers.get('llm_provider-x-litellm-response-cost') + if isinstance(cost, (int, float)) and (not isinstance(cost, bool)) and math.isfinite(cost) and (cost >= 0): + event['part']['cost'] = cost + data = data if isinstance(data, dict) else {} + if isinstance(data.get('id'), str) and data['id']: + event['part']['provider_request_id'] = data['id'] + for key in ('service_tier', 'cache_ttl'): + if data.get(key): + event['part'][key] = data[key] + route = _llm_route_from_response(response) or _canonical_llm_route(llm_route) + if route is not None: + event['part']['llm_route'] = route + created = data.get('created') + stamp = datetime.now(timezone.utc) + try: + if isinstance(created, str): + parsed = datetime.fromisoformat(created.replace('Z', '+00:00')) + if parsed.tzinfo is not None: + stamp = parsed + elif isinstance(created, (int, float)) and (not isinstance(created, bool)) and math.isfinite(created): + stamp = datetime.fromtimestamp(created, timezone.utc) + except (ValueError, OverflowError, OSError): + pass + pair = json.dumps({'type': 'step_start', 'timestamp': stamp.isoformat()}) + '\n' + pair += json.dumps(event) + '\n' + try: + receipt_path = target or Path(os.environ.get('M1_JUDGE_USAGE_PATH', '/logs/verifier/judge-trajectory.jsonl')) + receipt_path.parent.mkdir(parents=True, exist_ok=True) + with receipt_path.open('a') as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + handle.write(pair) + handle.flush() + os.fsync(handle.fileno()) + except OSError as exc: + if target is not None: + raise JudgeReceiptError(f'judge receipt write failed: {exc}') from exc + print(f'judge accounting: write failed ({type(exc).__name__})', file=sys.stderr) + +def openrouter_judge_pins() -> dict[str, dict]: + raw = os.environ.get('M1_OPENROUTER_JUDGE_PROVIDER_PINS', '').strip() + if not raw: + return {} + try: + pins = json.loads(raw) + except json.JSONDecodeError: + print('judge provider pins: invalid JSON in M1_OPENROUTER_JUDGE_PROVIDER_PINS', file=sys.stderr) + return {} + return {model: pin for model, pin in pins.items() if isinstance(pin, dict) and pin.get('order')} if isinstance(pins, dict) else {} + +def apply_judge_provider_pin(kwargs: dict, pins: dict[str, dict]) -> dict: + model = kwargs.get('model') + pin = pins.get(model) if isinstance(model, str) else None + if pin is None: + return kwargs + extra_body = dict(kwargs.get('extra_body') or {}) + provider = dict(extra_body.get('provider') or {}) + provider['order'] = list(pin['order']) + if pin.get('allow_fallbacks') is False: + provider['allow_fallbacks'] = False + if pin.get('zdr'): + provider['zdr'] = True + extra_body['provider'] = provider + return {**kwargs, 'extra_body': extra_body} +_TRANSIENT_ERROR_NAMES = ('RateLimitError', 'ServiceUnavailableError', 'InternalServerError', 'BadGatewayError', 'APIConnectionError') +_RETRYABLE_STATUS_CODES = frozenset({408, 409, 425, 429, 500, 502, 503, 504}) +_AUTH_ERROR_NAMES = ('AuthenticationError', 'PermissionDeniedError') +_AUTH_STATUS_CODES = frozenset({401, 403}) +_AUTH_RETRIES = 4 +_DEFAULT_TRANSIENT_RETRIES = 6 +_MAX_TRANSIENT_RETRIES = 20 +_MAX_RETRY_DELAY_SECONDS = 60.0 +_DEFAULT_EMPTY_RESPONSE_RETRIES = 3 +_DEFAULT_RETRY_BUDGET_SECONDS = 900.0 +_MAX_RETRY_BUDGET_SECONDS = 86400.0 + +def transient_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_TRANSIENT_RETRIES', '').strip() + if not raw: + return _DEFAULT_TRANSIENT_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_TRANSIENT_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_TRANSIENT_RETRIES + +def empty_response_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_EMPTY_RESPONSE_RETRIES', '').strip() + if not raw: + return _DEFAULT_EMPTY_RESPONSE_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_EMPTY_RESPONSE_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_EMPTY_RESPONSE_RETRIES + +def retry_budget_seconds() -> float: + raw = os.environ.get('M1_JUDGE_RETRY_BUDGET_SECONDS', '').strip() + if not raw: + return _DEFAULT_RETRY_BUDGET_SECONDS + try: + value = float(raw) + except ValueError: + value = math.nan + if not math.isfinite(value) or value < 0: + print('judge retries: invalid M1_JUDGE_RETRY_BUDGET_SECONDS, using the default', file=sys.stderr) + return _DEFAULT_RETRY_BUDGET_SECONDS + return min(value, _MAX_RETRY_BUDGET_SECONDS) + +def _within_budget(deadline: float, delay: float, model) -> bool: + remaining = deadline - time.monotonic() + if delay <= remaining: + return True + print(f'judge call retry budget spent: {model} would wait {delay:.1f}s with {max(remaining, 0.0):.1f}s left of M1_JUDGE_RETRY_BUDGET_SECONDS, failing now', file=sys.stderr) + return False + +def is_empty_verdict(response) -> bool: + data = response.model_dump() if hasattr(response, 'model_dump') else response + if not isinstance(data, dict): + return False + choices = data.get('choices') + if not isinstance(choices, list) or not choices: + return True + first = choices[0] + message = first.get('message') if isinstance(first, dict) else None + if not isinstance(message, dict): + return True + if message.get('tool_calls') or message.get('function_call'): + return False + content = message.get('content') + if isinstance(content, list): + content = ''.join((part.get('text') or '' for part in content if isinstance(part, dict))) + return not (isinstance(content, str) and content.strip()) + +def _matches(exc: BaseException, litellm, names: tuple[str, ...], statuses: frozenset[int]) -> bool: + classes = tuple((cls for cls in (getattr(litellm, name, None) for name in names) if isinstance(cls, type))) + if classes and isinstance(exc, classes): + return True + status = getattr(exc, 'status_code', None) + return type(status) is int and status in statuses + +def is_transient_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _TRANSIENT_ERROR_NAMES, _RETRYABLE_STATUS_CODES) + +def is_auth_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _AUTH_ERROR_NAMES, _AUTH_STATUS_CODES) + +def should_retry(exc: BaseException, litellm, attempt: int, limit: int) -> bool: + if attempt < limit and is_transient_error(exc, litellm): + return True + return attempt < min(limit, _AUTH_RETRIES) and is_auth_error(exc, litellm) + +def _retry_after_seconds(exc: BaseException) -> float | None: + headers = getattr(exc, 'headers', None) + if headers is None: + headers = getattr(getattr(exc, 'response', None), 'headers', None) + if headers is None: + return None + try: + raw = headers.get('retry-after') + if raw is None: + raw = headers.get('Retry-After') + value = float(raw) + except (AttributeError, TypeError, ValueError): + return None + return value if math.isfinite(value) and value >= 0 else None + +def retry_delay(exc: BaseException | None, attempt: int) -> float: + base = min(_MAX_RETRY_DELAY_SECONDS, 2.0 ** (attempt + 1)) + delay = base * (0.5 + random.random()) + retry_after = _retry_after_seconds(exc) if exc is not None else None + if retry_after is not None: + delay = max(delay, min(_MAX_RETRY_DELAY_SECONDS, retry_after)) + return delay + +def _note_retry(model, exc: BaseException, attempt: int, limit: int, delay: float) -> None: + status = getattr(exc, 'status_code', None) + print(f"judge call retry {attempt}/{limit}: {model} {type(exc).__name__} status={(status if type(status) is int else 'n/a')}, waiting {delay:.1f}s", file=sys.stderr) + +def _note_empty(model, response, attempt: int, limit: int, delay: float) -> None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + reason = None + if isinstance(data, dict) and isinstance(data.get('choices'), list) and data['choices']: + first = data['choices'][0] + reason = first.get('finish_reason') if isinstance(first, dict) else None + print(f'judge call retry {attempt}/{limit}: {model} empty verdict (finish_reason={reason}), waiting {delay:.1f}s', file=sys.stderr) + +def install(litellm, *, synchronous: bool=False) -> None: + pins = openrouter_judge_pins() + limit = transient_retry_limit() + empty_limit = empty_response_retry_limit() + deadline = time.monotonic() + retry_budget_seconds() + if synchronous: + original = litellm.completion + + def accounted(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = original(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + time.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + time.sleep(delay) + continue + return response + litellm.completion = accounted + return + original_async = litellm.acompletion + + async def accounted_async(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = await original_async(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + await asyncio.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + await asyncio.sleep(delay) + continue + return response + litellm.acompletion = accounted_async + +def record_agent_usage(attempt, *, model: str, provider: str) -> None: + records: dict[str, tuple[str, dict]] = {} + current_model = model + for filename in getattr(attempt, 'logs', []): + try: + with Path(filename).open() as stream: + for line in stream: + try: + event = json.loads(line) + except (ValueError, TypeError): + continue + if not isinstance(event, dict): + continue + message = event.get('message') or {} + if event.get('type') == 'assistant' and isinstance(message, dict) and isinstance(message.get('usage'), dict): + raw = message['usage'] + cached, written = (raw.get('cache_read_input_tokens'), raw.get('cache_creation_input_tokens')) + if all((type(value) is int and value >= 0 for value in (raw.get('input_tokens'), raw.get('output_tokens')))) and all((value is None or (type(value) is int and value >= 0) for value in (cached, written))): + receipt: dict = {'usage': {'input_uncached_tokens': raw['input_tokens'], 'prompt_tokens': raw['input_tokens'] + cached + written if cached is not None and written is not None else None, 'completion_tokens': raw['output_tokens'], 'prompt_tokens_details': {'cached_tokens': cached, 'cache_creation_tokens': written}}} + receipt['created'] = event.get('timestamp') + creation = raw.get('cache_creation') or {} + hour = creation.get('ephemeral_1h_input_tokens', 0) if isinstance(creation, dict) else 0 + if type(hour) is int and hour > 0: + if hour == written: + receipt['cache_ttl'] = '1h' + else: + receipt['usage_granularity'] = 'mixed_cache_ttl' + records[message.get('id') or json.dumps(raw, sort_keys=True)] = (message.get('model') or current_model, receipt) + payload = event.get('payload') or {} + if not isinstance(payload, dict): + continue + if event.get('type') == 'turn_context' and payload.get('model'): + current_model = payload['model'] + if event.get('type') == 'event_msg' and payload.get('type') == 'token_count': + info = payload.get('info') or {} + raw, total = (info.get('last_token_usage'), info.get('total_token_usage')) + if isinstance(raw, dict) and isinstance(total, dict) and all((type(raw.get(key)) is int and raw.get(key) >= 0 for key in ('input_tokens', 'output_tokens'))): + receipt = {'usage': {'prompt_tokens': raw.get('input_tokens'), 'input_uncached_tokens': raw.get('input_uncached_tokens'), 'input_cache_write_tokens': raw.get('input_cache_write_tokens'), 'completion_tokens': raw.get('output_tokens'), 'prompt_tokens_details': {'cached_tokens': raw.get('cached_input_tokens')}}} + receipt['created'] = event.get('timestamp') + records[json.dumps(total, sort_keys=True)] = (current_model, receipt) + except OSError: + continue + captured_input = captured_output = 0 + input_complete = True + for requested, receipt in records.values(): + requested = requested if '/' in requested else f'{provider}/{requested}' + _record_judge_usage(receipt, requested) + receipt_input = receipt['usage'].get('prompt_tokens') + if receipt_input is None: + input_complete = False + else: + captured_input += receipt_input + captured_output += receipt['usage'].get('completion_tokens') or 0 + total = getattr(attempt, 'usage', {}) or {} + if not records or (input_complete and total.get('input_tokens') != captured_input) or total.get('output_tokens') != captured_output: + _record_judge_usage({'usage': {'prompt_tokens': 0, 'completion_tokens': 0}, 'usage_granularity': 'incomplete_agent_receipts'}, model if '/' in model else f'{provider}/{model}') + +def install_rewardkit_agents() -> None: + import rewardkit.judges as judges + original = judges.get_agent + + def get_accounted_agent(judge, cwd=None): + backend = original(judge, cwd) + run = backend.run + + async def accounted_run(*args, **kwargs): + attempt = await run(*args, **kwargs) + record_agent_usage(attempt, model=judge.model or 'unknown', provider='anthropic' if judge.agent == 'claude-code' else 'openai') + return attempt + setattr(backend, 'run', accounted_run) + return backend + setattr(judges, 'get_agent', get_accounted_agent) +if __name__ == '__main__': + import litellm + if len(sys.argv) > 2 and sys.argv[1] == '--script': + import runpy + install(litellm, synchronous=True) + sys.argv = sys.argv[2:] + runpy.run_path(sys.argv[0], run_name='__main__') + else: + install(litellm) + install_rewardkit_agents() + if Path(__file__).with_name('m1_judge_panel.json').is_file(): + from m1_rewardkit_panel import install_panel + install_panel(Path(__file__).with_name('m1_judge_panel.json')) + if Path(__file__).with_name('m1_judge_jev.json').is_file(): + from m1_rewardkit_jev import install_jev + install_jev(Path(__file__).with_name('m1_judge_jev.json')) + from rewardkit.__main__ import main + main() diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/m1_rewardkit_panel.py b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/m1_rewardkit_panel.py new file mode 100644 index 0000000000000000000000000000000000000000..164cc2ae521cdd368c2e1749d7ed8fe09f4545eb --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/m1_rewardkit_panel.py @@ -0,0 +1,169 @@ +from __future__ import annotations +import asyncio +from contextvars import ContextVar +import json +import math +import os +import sys +from pathlib import Path +from typing import Any +import uuid +_request_audit: ContextVar[tuple[Path, list[str]] | None] = ContextVar('panel_request_audit', default=None) + +class PanelIncompleteError(RuntimeError): + pass + +def _audit_warning(exc: Exception, warnings: list[str]) -> None: + message = f'judge panel audit: diagnostic capture failed ({type(exc).__name__})' + if message not in warnings: + warnings.append(message) + print(message, file=sys.stderr) + +def _write_audit(path: Path, record: dict[str, Any], warnings: list[str], *, append: bool=False) -> None: + try: + text = json.dumps(record, allow_nan=False, default=str) + '\n' + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('a' if append else 'w') as stream: + stream.write(text) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + +def _binary(raw: Any) -> int: + if isinstance(raw, bool): + return int(raw) + if isinstance(raw, int | float) and math.isfinite(raw) and (raw in (0, 1)): + return int(raw) + if isinstance(raw, str): + value = raw.strip().lower() + if value in {'yes', 'true', '1'}: + return 1 + if value in {'no', 'false', '0'}: + return 0 + raise PanelIncompleteError('m1_judge_panel_incomplete: invalid binary vote') + +def validate_votes(scores: list[Any], criteria: list[Any]) -> None: + names = [criterion.name for criterion in criteria] + if len(set(names)) != len(names) or [score.name for score in scores] != names: + raise PanelIncompleteError('m1_judge_panel_incomplete: criterion membership mismatch') + for score, criterion in zip(scores, criteria, strict=True): + if score.error: + raise PanelIncompleteError('m1_judge_panel_incomplete: judge returned an error') + raw = _binary(score.raw) + expected = 1 - raw if criterion.negate else raw + if not math.isfinite(score.value) or score.value != expected: + raise PanelIncompleteError('m1_judge_panel_incomplete: inconsistent binary score') + +async def run_panel(judge: Any, criteria: list[Any], weights: list[float] | None, system_prompt: str | None, *, config: dict[str, Any], run_llm: Any, score_type: Any, audit_dir: Path) -> tuple[list[Any], str, list[str]]: + from rewardkit.models import Binary + if not criteria or any((not isinstance(criterion.output_format, Binary) for criterion in criteria)): + raise ValueError('panel majority voting requires nonempty binary criteria') + group_dir = audit_dir / uuid.uuid4().hex + warnings_out: list[str] = [] + + async def member_call(index: int, member: dict[str, Any]): + member_judge = judge.model_copy(update=member) + evidence: dict[str, Any] = {'member': index + 1, 'judge': member, 'criteria': [criterion.name for criterion in criteria], 'status': 'started'} + path = group_dir / f'judge-{index + 1}.json' + _write_audit(path, evidence, warnings_out) + token = _request_audit.set((group_dir / f'judge-{index + 1}-requests.jsonl', warnings_out)) + try: + scores, output, warnings = await run_llm(member_judge, criteria, weights, system_prompt) + evidence.update(output=output, warnings=warnings) + validate_votes(scores, criteria) + evidence['scores'] = [score.to_dict() for score in scores] + evidence['status'] = 'completed' + return (scores, output, warnings) + except BaseException as exc: + evidence.update(status='failed', error_class=type(exc).__name__) + if isinstance(exc, PanelIncompleteError): + evidence['error'] = str(exc) + raise + finally: + _request_audit.reset(token) + _write_audit(path, evidence, warnings_out) + outcomes = await asyncio.gather(*(member_call(index, member) for index, member in enumerate(config['members'])), return_exceptions=True) + failed = [index + 1 for index, result in enumerate(outcomes) if isinstance(result, BaseException)] + if failed: + _write_audit(group_dir / 'panel.json', {'status': 'incomplete', 'failed_members': failed}, warnings_out) + raise PanelIncompleteError(f'm1_judge_panel_incomplete: failed members {failed}; see panel audit artifacts') + completed = [outcome for outcome in outcomes if not isinstance(outcome, BaseException)] + combined = [] + for index, criterion in enumerate(criteria): + votes = [{'judge': config['members'][member_index], **outcome[0][index].to_dict()} for member_index, outcome in enumerate(completed)] + passes = sum((vote['value'] == 1 for vote in votes)) + value = int(passes >= 2) + combined.append(score_type(name=criterion.name, value=value, raw=bool(1 - value if criterion.negate else value), weight=weights[index] if weights is not None else 1.0, reasoning=f'{passes}/3 judges passed; strict majority requires 2/3.', description=criterion.description, id=criterion.id, negate=criterion.negate, optional=criterion.optional, votes=votes)) + for outcome in completed: + warnings_out.extend(outcome[2]) + audit = {'status': 'completed', 'mode': 'panel', 'aggregation': 'majority', 'required_votes': 2, 'members': config['members'], 'criteria': [score.to_dict() for score in combined]} + output = json.dumps(audit, indent=2, allow_nan=False) + _write_audit(group_dir / 'panel.json', audit, warnings_out) + return (combined, output, warnings_out) + +def install_panel(config_path: Path, *, audit_dir: Path=Path('/logs/verifier/judge-panel')) -> None: + import rewardkit.judges as judges + import rewardkit.reward as reward + from rewardkit.models import LLMJudge, Score + import litellm + config = json.loads(config_path.read_text()) + members = config.get('members') + concurrency = config.get('max_concurrent_llm') + if config.get('mode') != 'panel' or not isinstance(members, list) or len(members) != 3 or (len({member['model'] for member in members}) != 3) or (type(concurrency) is not int) or (not 1 <= concurrency <= 64): + raise ValueError('invalid materialized panel configuration') + if os.environ.get('REWARDKIT_JUDGE') or os.environ.get('REWARDKIT_MODEL'): + raise ValueError('RewardKit environment overrides cannot replace a frozen panel') + + class PanelScore(Score): + votes: list[dict[str, Any]] + + def to_dict(self): + return {**super().to_dict(), 'votes': self.votes} + original_llm = judges.arun_llm + original_call = judges._arun_llm_call + original_details = reward.Reward.to_detail_dict + original_completion = litellm.acompletion + active_loop = None + semaphore = None + + async def captured_completion(*args, **kwargs): + context = _request_audit.get() + record = {'requested_model': kwargs.get('model')} + response = None + try: + response = await original_completion(*args, **kwargs) + return response + except BaseException as exc: + record['error_class'] = type(exc).__name__ + raise + finally: + if context is not None: + path, warnings = context + try: + if response is not None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + record.update(response_model=data.get('model'), choices=data.get('choices')) + _write_audit(path, record, warnings, append=True) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + + async def bounded_call(*args, **kwargs): + nonlocal active_loop, semaphore + loop = asyncio.get_running_loop() + if active_loop is not loop: + active_loop, semaphore = (loop, asyncio.Semaphore(concurrency)) + assert semaphore is not None + async with semaphore: + return await original_call(*args, **kwargs) + + async def panel_call(judge, criteria, weights=None, system_prompt=None): + return await run_panel(judge, criteria, weights, system_prompt, config=config, run_llm=original_llm, score_type=PanelScore, audit_dir=audit_dir) + + def panel_details(self, score): + detail = original_details(self, score) + if isinstance(self.judge, LLMJudge): + detail.update(kind='llm_panel', judge=config, aggregation='majority', required_votes=2) + return detail + setattr(reward, 'arun_llm', panel_call) + setattr(judges, '_arun_llm_call', bounded_call) + setattr(litellm, 'acompletion', captured_completion) + reward.Reward.to_detail_dict = panel_details diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/normalize_reward.py b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/normalize_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..91817ef00ea9152ca57f0030d8e879eb850ddff0 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/normalize_reward.py @@ -0,0 +1,71 @@ +from __future__ import annotations +import argparse +import json +from pathlib import Path +from typing import Any + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument('--raw-details', required=True) + parser.add_argument('--rubric', required=True) + parser.add_argument('--reward-out', required=True) + parser.add_argument('--details-out', required=True) + args = parser.parse_args() + raw_details = _load_json(Path(args.raw_details)) + rubric = _load_json(Path(args.rubric)) + criteria = rubric['criteria'] + raw_by_name = _raw_criteria_by_name(raw_details) + positive_total = sum((float(item['score']) for item in criteria if float(item['score']) > 0)) + if positive_total <= 0: + raise ValueError('rubric must contain at least one positive score') + earned = 0.0 + normalized_criteria: list[dict[str, Any]] = [] + for item in criteria: + signed_score = float(item['score']) + raw = raw_by_name.get(item['name'], {}) + value = _coerce_score(raw.get('value', 0.0)) + contribution = value * signed_score + earned += contribution + normalized_criteria.append({'name': item['name'], 'value': value, 'raw': raw.get('raw'), 'weight': signed_score, 'signed_score': signed_score, 'polarity': item['polarity'], 'contribution': contribution, 'description': item['description'], 'source': item.get('source', ''), 'justification': item.get('justification', ''), 'metadata': item.get('metadata', {}), 'reasoning': raw.get('reasoning'), 'judge_reasoning': raw.get('reasoning'), 'judge_error': raw.get('error'), **({'votes': raw['votes']} if 'votes' in raw else {})}) + unclamped = earned / positive_total + reward = max(0.0, min(1.0, unclamped)) + reward_out = {'correctness': reward} + details_out = {'correctness': {'score': reward, 'kind': 'signed_score', 'criteria': normalized_criteria, 'aggregation': {'method': 'signed_score_ratio_clamped', 'earned': earned, 'positive_total': positive_total, 'unclamped': unclamped, 'clamped': reward}, 'raw_rewardkit': raw_details}} + _write_json(Path(args.reward_out), reward_out) + _write_json(Path(args.details_out), details_out) + +def _load_json(path: Path) -> Any: + return json.loads(path.read_text()) + +def _write_json(path: Path, data: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data, indent=2) + '\n') + +def _raw_criteria_by_name(details: dict[str, Any]) -> dict[str, dict[str, Any]]: + out: dict[str, dict[str, Any]] = {} + for reward in details.values(): + for item in _iter_raw_criteria(reward): + name = item.get('name') + if isinstance(name, str): + out[name] = item + return out + +def _iter_raw_criteria(value: Any): + if isinstance(value, list): + for item in value: + yield from _iter_raw_criteria(item) + return + if not isinstance(value, dict): + return + for item in value.get('criteria') or []: + if isinstance(item, dict): + yield item + +def _coerce_score(value: Any) -> float: + if isinstance(value, bool): + return 1.0 if value else 0.0 + if isinstance(value, int | float): + return max(0.0, min(1.0, float(value))) + return 0.0 +if __name__ == '__main__': + main() diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/agent_prompt.md b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/agent_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..ca489c065bafd5d10e764f033c9dfd1195933db3 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/agent_prompt.md @@ -0,0 +1,10 @@ +You are grading the submitted legal analysis against the criteria below. + +Read `/logs/artifacts/answer.md`, the answer captured by the verifier, before +assigning any scores. Evaluate that file as the submission. Other files in +`/app` may supply context, but must not replace the submitted answer. Do not +modify the submission. If it is missing or empty, state that in your reasoning +and apply the criteria to that missing or empty submission. Preserve each +criterion's stated positive or penalty polarity. + +{criteria} diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_1.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_1.toml new file mode 100644 index 0000000000000000000000000000000000000000..e2cc0ad9e09690a45bb7c17e50d1cb47aea881ab --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_1.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_1" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that no Board resolution authorizing Dr. Connors' appointment as Interim Chief Medical Officer exists in the governance record prior to May 13, 2026." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_10.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_10.toml new file mode 100644 index 0000000000000000000000000000000000000000..9af7994ea1607e4f4cac85ea35052873c5bdcb34 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_10.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_10" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that Dr. Connors' appointment as Interim Chief Medical Officer is valid effective as of May 13, 2026." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_11.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_11.toml new file mode 100644 index 0000000000000000000000000000000000000000..a711637e001db0edada71b35a830c5333d074254 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_11.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_11" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: States that Dr. Connors' appointment was valid as of May 7, 2026." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_2.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_2.toml new file mode 100644 index 0000000000000000000000000000000000000000..0168deb09e927a2380f0633b86941bd28362b666 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_2.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_2" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies the CEO Announcement Email dated May 8, 2026 as evidence that Dr. Connors began exercising CMO duties before the Board adopted Resolution 2026-14." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_3.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_3.toml new file mode 100644 index 0000000000000000000000000000000000000000..b8d740a06d8acd24a79dddddf6cdcea6b45f432c --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_3.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_3" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that Section 5.2 of the Bylaws requires Board approval for the appointment of any principal officer." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_4.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_4.toml new file mode 100644 index 0000000000000000000000000000000000000000..64bead44f3b2a60435dc13da78a3acf57952028d --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_4.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_4" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that Section 5.9 of the Bylaws provides that ratification is effective upon adoption of the ratifying resolution." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_5.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_5.toml new file mode 100644 index 0000000000000000000000000000000000000000..13bfa78398b77d306ec318b4960ee4da9a790580 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_5.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_5" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that Section 5.10 of the Bylaws permits the Board to act by unanimous written consent in lieu of a meeting." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_6.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_6.toml new file mode 100644 index 0000000000000000000000000000000000000000..8a021569da545557573b7e3d27deb061d6ca84d7 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_6.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_6" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies the Chief Medical Officer as a principal officer of IHP under Section 5.1 of the Bylaws." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_7.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_7.toml new file mode 100644 index 0000000000000000000000000000000000000000..2f20b86b7e4167641f4ec82fde95b7afb3bc2341 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_7.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_7" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that the CEO's May 7 appointment letter lacked the Board authorization required by Section 5.2 of the Bylaws, rendering the appointment defective at issuance." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_8.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_8.toml new file mode 100644 index 0000000000000000000000000000000000000000..03c20e170acdad3518eb031baa64c2b318bba316 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/raw_correctness/criterion_8.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_8" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that Resolution 2026-14's designation of May 7, 2026 as the effective date of the ratification is ineffective under Section 5.9 of the Bylaws." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/test.sh b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..66a509a7bcdbe412851f3a012a5ba7b16cf0925b --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/tests/test.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +set -euo pipefail + +mkdir -p /logs/artifacts /logs/verifier/raw + +python3 - <<'PYEOF' +import json +import shutil +from pathlib import Path + + +def has_text(path: Path) -> bool: + return path.exists() and path.is_file() and bool(path.read_text(errors="replace").strip()) + + +def fallback_paths(answer_path: Path) -> list[Path]: + paths = [] + try: + relative = answer_path.relative_to("/app") + paths.append(Path("/app/app") / relative) + except ValueError: + pass + return [path for path in paths if path != answer_path] + + +config = json.loads(Path("/tests/fixtures/config.json").read_text()) +answer_path = Path(config["answer_path"]) +artifact_answer = Path("/logs/artifacts/answer.md") +artifact_answer.parent.mkdir(parents=True, exist_ok=True) +if has_text(answer_path): + shutil.copyfile(answer_path, artifact_answer) +else: + for candidate in fallback_paths(answer_path): + if has_text(candidate): + shutil.copyfile(candidate, artifact_answer) + break + else: + artifact_answer.write_text("") + +# Harbor collects /logs/artifacts when the agent step ends, which is before this +# script runs, so the copy above never reaches the uploaded artifacts. /logs/verifier +# is uploaded after the verifier phase, so persist the graded answer there too. +verifier_answer = Path("/logs/verifier/answer.md") +verifier_answer.parent.mkdir(parents=True, exist_ok=True) +shutil.copyfile(artifact_answer, verifier_answer) +PYEOF + +uv run --no-project --with 'harbor-rewardkit[all]==0.2.0' python /tests/m1_rewardkit_accounting.py /tests/raw_correctness \ + --workspace /app \ + --output /logs/verifier/raw/reward.json \ + --max-concurrent-llm "${MAX_CONCURRENT_LLM:-4}" \ + --max-concurrent-agent "${M1_MAX_CONCURRENT_AGENT:-1}" + +python /tests/normalize_reward.py \ + --raw-details /logs/verifier/raw/reward-details.json \ + --rubric /tests/fixtures/rubric.json \ + --reward-out /logs/verifier/reward.json \ + --details-out /logs/verifier/reward-details.json diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/workdir/attachments/IHP_Board_Meeting_Calendar_2026.docx b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/workdir/attachments/IHP_Board_Meeting_Calendar_2026.docx new file mode 100644 index 0000000000000000000000000000000000000000..8061e1407d7ae28bae788564c3f76c198aa3e0e4 Binary files /dev/null and b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/workdir/attachments/IHP_Board_Meeting_Calendar_2026.docx differ diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/workdir/attachments/IHP_Board_Resolution_2026-14.docx b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/workdir/attachments/IHP_Board_Resolution_2026-14.docx new file mode 100644 index 0000000000000000000000000000000000000000..016feda4b87fbd10dde93ae76dd2a32365803050 Binary files /dev/null and b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/workdir/attachments/IHP_Board_Resolution_2026-14.docx differ diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/workdir/attachments/IHP_Bylaws_Excerpt_Article_V_Officers.docx b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/workdir/attachments/IHP_Bylaws_Excerpt_Article_V_Officers.docx new file mode 100644 index 0000000000000000000000000000000000000000..597f0b05698c7c71206d660fbb6d82ab8e3469bd Binary files /dev/null and b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/workdir/attachments/IHP_Bylaws_Excerpt_Article_V_Officers.docx differ diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/workdir/attachments/IHP_CEO_Email_Executive_Staff_Connors_Announcement.docx b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/workdir/attachments/IHP_CEO_Email_Executive_Staff_Connors_Announcement.docx new file mode 100644 index 0000000000000000000000000000000000000000..9261fc3409835de36b4e0ef8263b815ac0741a05 Binary files /dev/null and b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/workdir/attachments/IHP_CEO_Email_Executive_Staff_Connors_Announcement.docx differ diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/workdir/attachments/IHP_CMO_Interim_Appointment_Letter_Connors.docx b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/workdir/attachments/IHP_CMO_Interim_Appointment_Letter_Connors.docx new file mode 100644 index 0000000000000000000000000000000000000000..9c510362db9daf5a84d6dc508ce11c3ed595abb5 Binary files /dev/null and b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/workdir/attachments/IHP_CMO_Interim_Appointment_Letter_Connors.docx differ diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/workdir/attachments/IHP_GC_Memo_Appointment_Ratification.docx b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/workdir/attachments/IHP_GC_Memo_Appointment_Ratification.docx new file mode 100644 index 0000000000000000000000000000000000000000..79f4b6adcfc5085442a5f5277e4b41e29b0c6630 Binary files /dev/null and b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/workdir/attachments/IHP_GC_Memo_Appointment_Ratification.docx differ diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/workdir/attachments/IHP_Regulatory_Reference_Compilation_KKA_2026.docx b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/workdir/attachments/IHP_Regulatory_Reference_Compilation_KKA_2026.docx new file mode 100644 index 0000000000000000000000000000000000000000..b94b1866e72d6270c7c8a22e4df6b28fcdcd7476 Binary files /dev/null and b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-1/workdir/attachments/IHP_Regulatory_Reference_Compilation_KKA_2026.docx differ diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/instruction.md b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e3b5e8713dda05563ad4ccbc75a4e64f2f075157 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/instruction.md @@ -0,0 +1,44 @@ +# Interim CMO Appointment: Governance and Compliance Analysis — Assignment 2 + +You are a senior legal analyst operating autonomously. You are completing a multi-step legal reasoning task. Follow the role, factual record, instructions, and deliverable requirements provided in the Task and each Assignment. + +Each Assignment may require a different legal deliverable. Follow the requirements specific to that Assignment. + +## Word limits for court briefs + +- A brief in support of or in response to a motion may not exceed **8,750 words**. +- A reply brief may not exceed **3,500 words**. +- For a motion for reconsideration, a brief in support of or in response to the motion may not exceed **3,500 words**, and a reply brief may not exceed **1,750 words**. +- If an Assignment specifies a stricter word limit, follow the stricter limit. + +These word limits do not apply to legal memoranda or other non-court-filing deliverables unless the Assignment expressly provides otherwise. + +Complete the task end-to-end without asking for confirmation, permission, or clarification. + +Use the uploaded matter documents in `/app/attachments/` as your primary case file. You also have internet access via OpenCode's `websearch` tool; use it to research any statutes, regulations, cases, administrative guidance, or secondary authorities that are not supplied as attachments. Cite any authority you rely on in the format requested by the prompt. + +For document inspection: +- PDF: `pdftotext /app/attachments/.pdf -` +- DOCX: `pandoc /app/attachments/.docx -t markdown` +- XLSX/CSV: use Python with `openpyxl` or `pandas` +- If extraction is unreliable, inspect the raw file with Python libraries or convert/render the relevant pages. + +Write the final complete legal deliverable for this assignment to `/app/response2.md`. The verifier reads only that file. + +This is a follow-on assignment. The documents from the previous assignment(s) remain available in `/app/attachments/`, and your prior deliverable `/app/response1.md` is also on disk. Build on that analysis as the prompt directs. + +## Attachments + +_No new documents for this assignment. The documents from the previous assignment(s) remain available in `/app/attachments/`._ + +## Prompt + +Following the same instructions and your analysis from Step 1, incorporate the following into the memorandum: + +1) Identify each notification or filing obligation to the Department of Managed Health Care arising from the events described in the files, with citation to the controlling authority reproduced in the files. + +2) For each obligation identified, determine IHP's compliance status as of May 15, 2026, including any applicable deadline and its corresponding calculation. + +3) Provide a recommended course of action addressing each obligation identified, including timing and submission mechanics. + +The same uploaded documents from Step 1 constitute the complete and exclusive universe of materials for this assignment. All legal analysis must be based solely on the law and guidance as it exists on May 15, 2026. Do not account for any legislative changes, regulatory updates, or Department of Managed Health Care (DMHC) guidance issued after that date. Support your analysis with citations to the uploaded documents. diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/solution/solve.sh b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7710414a6da6d0ad740717c8c85a9af850d5da33 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/solution/solve.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# No oracle solution ships with LegalReasonBench. The verifier grades the +# agent's own legal deliverable for this assignment against the rubric. +echo "no oracle solution" diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/fixtures/config.json b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/fixtures/config.json new file mode 100644 index 0000000000000000000000000000000000000000..c869dfd775955fcc3ab74a84611789294ab927f9 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/fixtures/config.json @@ -0,0 +1,221 @@ +{ + "task_id": "lrb-interim-cmo-appointment-governance", + "title": "Interim CMO Appointment: Governance and Compliance Analysis", + "domain": "", + "matter": "", + "judge": { + "max_concurrent_llm": 12, + "mode": "panel", + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ], + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + "step_index": 2, + "step_name": "assignment-2", + "step_title": "", + "prompt": "Following the same instructions and your analysis from Step 1, incorporate the following into the memorandum:\n\n1) Identify each notification or filing obligation to the Department of Managed Health Care arising from the events described in the files, with citation to the controlling authority reproduced in the files.\n\n2) For each obligation identified, determine IHP's compliance status as of May 15, 2026, including any applicable deadline and its corresponding calculation.\n\n3) Provide a recommended course of action addressing each obligation identified, including timing and submission mechanics.\n\nThe same uploaded documents from Step 1 constitute the complete and exclusive universe of materials for this assignment. All legal analysis must be based solely on the law and guidance as it exists on May 15, 2026. Do not account for any legislative changes, regulatory updates, or Department of Managed Health Care (DMHC) guidance issued after that date. Support your analysis with citations to the uploaded documents.", + "attachments": [], + "rubric": [ + { + "name": "criterion_1", + "description": "Identifies that the notice requirement under Cal. Health & Safety Code \u00a7 1352(c) (2026) mandating disclosure \"of a change in the officers\" is triggered by Dr. Connors' appointment to a principal officer position at IHP.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 3, Cal. Health & Safety Code \u00a7 1352(c) (2026) (\"A plan shall, within five days, give written notice to the director in the form as by rule may be prescribed, of a change in the officers, directors, partners, controlling shareholders, principal creditors, or persons occupying similar positions or performing similar functions, of the plan\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Identify each notification or filing obligation to the Department of Managed Health Care arising from the events described in the files, with citation to the controlling authority reproduced in the files.\" Identifying the obligation requires the model to recognize that the addition of Dr. Connors to a principal officer position constitutes a change in officers triggering the written notice requirement under the controlling statute.", + "metadata": { + "irac_section": "Issue" + }, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_2", + "description": "States that Cal. Health & Safety Code \u00a7 1352(c) (2026) requires a plan to give written notice to the director within five days of a change in the officers of the plan.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 3, Cal. Health & Safety Code \u00a7 1352(c) (2026) (\"A plan shall, within five days, give written notice to the director in the form as by rule may be prescribed, of a change in the officers, directors, partners, controlling shareholders, principal creditors, or persons occupying similar positions or performing similar functions, of the plan\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Identify each notification or filing obligation to the Department of Managed Health Care arising from the events described in the files, with citation to the controlling authority reproduced in the files.\" Cal. Health & Safety Code \u00a7 1352(c) (2026) is the controlling statutory provision establishing the five-day notice standard. Correct identification of this provision and its day-count is required before any deadline computation can proceed.", + "metadata": { + "irac_section": "Rule" + }, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_3", + "description": "Identifies the departure of IHP's prior Chief Medical Officer effective May 6, 2026 as a change in the officers giving rise to a separate notice obligation under Cal. Health & Safety Code \u00a7 1352(c) (2026).", + "source": "IHP_GC_Memo_Appointment_Ratification.docx, p. 1, Analysis Section I (\"IHP's Chief Medical Officer departed the plan effective May 6, 2026\"); IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 3, Cal. Health & Safety Code \u00a7 1352(c) (2026) (\"A plan shall, within five days, give written notice to the director in the form as by rule may be prescribed, of a change in the officers\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Identify each notification or filing obligation to the Department of Managed Health Care arising from the events described in the files, with citation to the controlling authority reproduced in the files.\" The prior CMO's departure is a distinct change in officers from Dr. Connors' appointment. Each change carries its own independent five-day notice obligation with its own trigger date and deadline. A model that identifies only the Connors appointment obligation has missed a separate filing requirement arising from the same record.", + "metadata": { + "irac_section": "Issue" + }, + "score": 8.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_4", + "description": "States that the deadline for the Cal. Health & Safety Code \u00a7 1352(c) (2026) notice arising from the prior Chief Medical Officer's departure was May 11, 2026, computed as five days from May 6, 2026.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 3, Cal. Health & Safety Code \u00a7 1352(c) (2026) (\"A plan shall, within five days, give written notice to the director in the form as by rule may be prescribed, of a change in the officers\"); IHP_GC_Memo_Appointment_Ratification.docx, p. 1, Analysis Section I (\"IHP's Chief Medical Officer departed the plan effective May 6, 2026\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"For each obligation identified, determine IHP's compliance status as of May 15, 2026, including any applicable deadline and its computation.\" The five-day window from May 6 closes on May 11, 2026. As of May 15, that deadline has already passed. The model must calculate this deadline separately from the Connors appointment deadline and assess compliance status independently for each obligation.", + "metadata": { + "irac_section": "Application" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_5", + "description": "States that the uploaded files contain no indication that a notice was filed under Cal. Health & Safety Code \u00a7 1352(c) (2026) regarding the departure of the previous Chief Medical Officer.", + "source": "IHP_GC_Memo_Appointment_Ratification.docx, p. 3, Completeness of the Governance Record section (\"The governance record with respect to the Connors Interim CMO appointment is complete. The record consists of three documents\"); IHP_Board_Resolution_2026-14.docx, p. 1, WHEREAS clauses (reciting the appointment of Dr. Connors; no reference to a prior CMO departure filing).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"For each obligation identified, determine IHP's compliance status as of May 15, 2026, including any applicable deadline and its computation.\" The GC memo's governance record description enumerates three documents and makes no reference to a departure notice filing. The absence of any such filing in the record is verifiable by exclusion from the documents enumerated. A model that does not identify this gap has accepted the GC memo's completeness conclusion without testing it against the departure obligation.", + "metadata": { + "irac_section": "Application" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_6", + "description": "Mentions the need for an immediate Cal. Health & Safety Code \u00a7 1352(c) (2026) filing for the prior Chief Medical Officer's departure if no notice has been filed.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 3, Cal. Health & Safety Code \u00a7 1352(c) (2026) (\"A plan shall, within five days, give written notice to the director in the form as by rule may be prescribed, of a change in the officers\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Provide a recommended course of action addressing each obligation identified, including timing and submission mechanics.\" The departure obligation deadline of May 11, 2026 has already passed as of May 15th. A complete course of action requires the model to address this overdue obligation separately from the Connors appointment obligation and recommend immediate filing.", + "metadata": { + "irac_section": "Rule" + }, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_7", + "description": "States that the operative trigger date for the Cal. Health & Safety Code \u00a7 1352(c) (2026) notice arising from Dr. Connors' appointment is May 13, 2026, the date the change was validly effected.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall be effective upon adoption of the ratifying resolution\"); IHP_Board_Resolution_2026-14.docx, p. 2, Record of Adoption (\"The foregoing Resolution was duly adopted at the regular meeting of the Board of Directors of Imperium Health Plan, Inc. held on May 13, 2026, at which a quorum was present and acting throughout\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"For each obligation identified, determine IHP's compliance status as of May 15, 2026, including any applicable deadline and its computation.\" The trigger date is the date the change was validly effected. Because Section 5.9 provides that ratification is effective upon adoption, the change occurred on May 13, 2026. A model that selects May 7th as the trigger carries a wrong premise into the deadline calculation.", + "metadata": { + "irac_section": "Application" + }, + "score": 30.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_8", + "description": "States that May 18, 2026, computed as five days from May 13, 2026, is the sole operative filing deadline for the Cal. Health & Safety Code \u00a7 1352(c) (2026) notice arising from Dr. Connors' appointment.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 3, Cal. Health & Safety Code \u00a7 1352(c) (2026) (\"A plan shall, within five days, give written notice to the director in the form as by rule may be prescribed, of a change in the officers\"); IHP_Board_Resolution_2026-14.docx, p. 2, Record of Adoption (\"The foregoing Resolution was duly adopted at the regular meeting of the Board of Directors of Imperium Health Plan, Inc. held on May 13, 2026, at which a quorum was present and acting throughout\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"For each obligation identified, determine IHP's compliance status as of May 15, 2026, including any applicable deadline and its computation.\" May 18, 2026 is the correct deadline under a May 13th trigger. Credit requires the memorandum to adopt May 18th as the controlling deadline for this obligation. Presenting May 18th as one alternative alongside an adopted earlier deadline does not earn credit.", + "metadata": { + "irac_section": "Application" + }, + "score": 25.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_9", + "description": "States that as of May 15, 2026, the Cal. Health & Safety Code \u00a7 1352(c) (2026) obligation arising from Dr. Connors' appointment is not yet overdue.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 3, Cal. Health & Safety Code \u00a7 1352(c) (2026) (\"A plan shall, within five days, give written notice to the director in the form as by rule may be prescribed, of a change in the officers\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"For each obligation identified, determine IHP's compliance status as of May 15, 2026, including any applicable deadline and its computation.\" The anchor date is May 15, 2026. The deadline is May 18, 2026. IHP has three days remaining to file. A model that correctly identifies the May 13th trigger and the May 18th deadline reaches this compliance status conclusion.", + "metadata": { + "irac_section": "Application" + }, + "score": 15.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_10", + "description": "States that Cal. Code Regs. tit. 28, \u00a7 1300.52.2(a) (2026) requires an amendment filing for the addition of a principal officer.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 4, Cal. Code Regs. tit. 28, \u00a7 1300.52.2(a) (2026) (\"There is an addition or deletion of a director, trustee, principal officer, general partner, general manager or principal management persons, or persons occupying similar positions or performing similar functions, or a substantial and material change in the duties of any such person\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Provide a recommended course of action addressing each obligation identified, including timing and submission mechanics.\" Cal. Code Regs. tit. 28, \u00a7 1300.52.2(a) (2026) is the regulatory provision specifying that a principal officer addition requires an amendment filing. A complete course of action requires identifying the correct filing vehicle, not merely the statutory notice obligation.", + "metadata": { + "irac_section": "Rule" + }, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_11", + "description": "States that Cal. Code Regs. tit. 28, \u00a7 1300.52.4(b)(ii) (2026) provides that an amendment filed for a change described in Cal. Health & Safety Code \u00a7 1352(c) (2026) is effective on the date implemented.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 6, Cal. Code Regs. tit. 28, \u00a7 1300.52.4(b)(ii) (2026) (\"In the event of any change described in Section 1352(c) of the Act, the plan shall file an amendment in accordance with the requirements of Section 1300.52.2. A change that is the subject of an amendment required to be filed pursuant to this subsection (b)(ii) shall be effective on the date implemented\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Provide a recommended course of action addressing each obligation identified, including timing and submission mechanics.\" Cal. Code Regs. tit. 28, \u00a7 1300.52.4(b)(ii) (2026) confirms that the amendment filing for a section 1352(c) change is effective on the date implemented, not the date filed. This mechanic is relevant to the submission posture and the recommended course of action.", + "metadata": { + "irac_section": "Rule" + }, + "score": 6.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_12", + "description": "States that IHP should file the Cal. Health & Safety Code \u00a7 1352(c) (2026) amendment for Dr. Connors' appointment before May 18, 2026.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 3, Cal. Health & Safety Code \u00a7 1352(c) (2026) (\"A plan shall, within five days, give written notice to the director in the form as by rule may be prescribed, of a change in the officers\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Provide a recommended course of action addressing each obligation identified, including timing and submission mechanics.\" The five-day window closes on May 18, 2026. Filing before that date preserves IHP's timely compliance posture for the Connors appointment obligation. A recommended course of action that does not specify the deadline date is incomplete.", + "metadata": { + "irac_section": "Conclusion" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_13", + "description": "States that IHP's Cal. Health & Safety Code \u00a7 1352(c) (2026) filing obligation arising from Dr. Connors' appointment lapsed before May 15, 2026.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 3, Cal. Health & Safety Code \u00a7 1352(c) (2026) (\"A plan shall, within five days, give written notice to the director in the form as by rule may be prescribed, of a change in the officers\"); IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall be effective upon adoption of the ratifying resolution\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"For each obligation identified, determine IHP's compliance status as of May 15, 2026, including any applicable deadline and its computation.\" The Connors appointment obligation does not lapse before May 15, 2026 under a correct trigger analysis. A model that concludes otherwise has applied the wrong trigger date. A lapse conclusion for the departure obligation does not trigger this item.", + "metadata": { + "irac_section": "Application" + }, + "score": -30.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_14", + "description": "Mentions that the Cal. Health & Safety Code \u00a7 1352(c) (2026) filing for Dr. Connors' appointment is timely based on a May 7, 2026 trigger date.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 3, Cal. Health & Safety Code \u00a7 1352(c) (2026) (\"A plan shall, within five days, give written notice to the director in the form as by rule may be prescribed, of a change in the officers\"); IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall be effective upon adoption of the ratifying resolution\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"For each obligation identified, determine IHP's compliance status as of May 15, 2026, including any applicable deadline and its computation.\" Under a May 7th trigger, the five-day window closed on May 12, 2026. A model that accepts May 7th as the trigger but concludes the filing is still timely as of May 15th has produced an internally inconsistent analysis. Timeliness and a May 7th trigger cannot coexist.", + "metadata": { + "irac_section": "Application" + }, + "score": -15.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_15", + "description": "Mentions filing the Cal. Health & Safety Code \u00a7 1352(c) (2026) notice for Dr. Connors' appointment by a date computed from May 7, 2026 as a precautionary measure.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 3, Cal. Health & Safety Code \u00a7 1352(c) (2026) (\"A plan shall, within five days, give written notice to the director in the form as by rule may be prescribed, of a change in the officers\"); IHP_Board_Resolution_2026-14.docx, p. 2, Record of Adoption (\"The foregoing Resolution was duly adopted at the regular meeting of the Board of Directors of Imperium Health Plan, Inc. held on May 13, 2026, at which a quorum was present and acting throughout\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"For each obligation identified, determine IHP's compliance status as of May 15, 2026, including any applicable deadline and its computation.\" A model that identifies May 13 as the trigger date but recommends filing by a date computed from May 7th as a precautionary measure has adopted a dual-track hedge that is internally inconsistent. The May 13th trigger produces a May 18th deadline. Recommending an earlier date derived from a rejected trigger framework undermines the analysis the model has already committed to.", + "metadata": { + "irac_section": "Application" + }, + "score": -10.0, + "polarity": "negative", + "raw_weight": 1.0 + } + ], + "answer_path": "/app/response2.md", + "answer_relative_path": "response2.md", + "is_followon": true, + "prev_answer_path": "/app/response1.md" +} diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/fixtures/rubric.json b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/fixtures/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..7f999311e3bf1b99163b1da505662cc11f77419e --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/fixtures/rubric.json @@ -0,0 +1,184 @@ +{ + "criteria": [ + { + "name": "criterion_1", + "description": "Identifies that the notice requirement under Cal. Health & Safety Code \u00a7 1352(c) (2026) mandating disclosure \"of a change in the officers\" is triggered by Dr. Connors' appointment to a principal officer position at IHP.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 3, Cal. Health & Safety Code \u00a7 1352(c) (2026) (\"A plan shall, within five days, give written notice to the director in the form as by rule may be prescribed, of a change in the officers, directors, partners, controlling shareholders, principal creditors, or persons occupying similar positions or performing similar functions, of the plan\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Identify each notification or filing obligation to the Department of Managed Health Care arising from the events described in the files, with citation to the controlling authority reproduced in the files.\" Identifying the obligation requires the model to recognize that the addition of Dr. Connors to a principal officer position constitutes a change in officers triggering the written notice requirement under the controlling statute.", + "metadata": { + "irac_section": "Issue" + }, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_2", + "description": "States that Cal. Health & Safety Code \u00a7 1352(c) (2026) requires a plan to give written notice to the director within five days of a change in the officers of the plan.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 3, Cal. Health & Safety Code \u00a7 1352(c) (2026) (\"A plan shall, within five days, give written notice to the director in the form as by rule may be prescribed, of a change in the officers, directors, partners, controlling shareholders, principal creditors, or persons occupying similar positions or performing similar functions, of the plan\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Identify each notification or filing obligation to the Department of Managed Health Care arising from the events described in the files, with citation to the controlling authority reproduced in the files.\" Cal. Health & Safety Code \u00a7 1352(c) (2026) is the controlling statutory provision establishing the five-day notice standard. Correct identification of this provision and its day-count is required before any deadline computation can proceed.", + "metadata": { + "irac_section": "Rule" + }, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_3", + "description": "Identifies the departure of IHP's prior Chief Medical Officer effective May 6, 2026 as a change in the officers giving rise to a separate notice obligation under Cal. Health & Safety Code \u00a7 1352(c) (2026).", + "source": "IHP_GC_Memo_Appointment_Ratification.docx, p. 1, Analysis Section I (\"IHP's Chief Medical Officer departed the plan effective May 6, 2026\"); IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 3, Cal. Health & Safety Code \u00a7 1352(c) (2026) (\"A plan shall, within five days, give written notice to the director in the form as by rule may be prescribed, of a change in the officers\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Identify each notification or filing obligation to the Department of Managed Health Care arising from the events described in the files, with citation to the controlling authority reproduced in the files.\" The prior CMO's departure is a distinct change in officers from Dr. Connors' appointment. Each change carries its own independent five-day notice obligation with its own trigger date and deadline. A model that identifies only the Connors appointment obligation has missed a separate filing requirement arising from the same record.", + "metadata": { + "irac_section": "Issue" + }, + "score": 8.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_4", + "description": "States that the deadline for the Cal. Health & Safety Code \u00a7 1352(c) (2026) notice arising from the prior Chief Medical Officer's departure was May 11, 2026, computed as five days from May 6, 2026.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 3, Cal. Health & Safety Code \u00a7 1352(c) (2026) (\"A plan shall, within five days, give written notice to the director in the form as by rule may be prescribed, of a change in the officers\"); IHP_GC_Memo_Appointment_Ratification.docx, p. 1, Analysis Section I (\"IHP's Chief Medical Officer departed the plan effective May 6, 2026\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"For each obligation identified, determine IHP's compliance status as of May 15, 2026, including any applicable deadline and its computation.\" The five-day window from May 6 closes on May 11, 2026. As of May 15, that deadline has already passed. The model must calculate this deadline separately from the Connors appointment deadline and assess compliance status independently for each obligation.", + "metadata": { + "irac_section": "Application" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_5", + "description": "States that the uploaded files contain no indication that a notice was filed under Cal. Health & Safety Code \u00a7 1352(c) (2026) regarding the departure of the previous Chief Medical Officer.", + "source": "IHP_GC_Memo_Appointment_Ratification.docx, p. 3, Completeness of the Governance Record section (\"The governance record with respect to the Connors Interim CMO appointment is complete. The record consists of three documents\"); IHP_Board_Resolution_2026-14.docx, p. 1, WHEREAS clauses (reciting the appointment of Dr. Connors; no reference to a prior CMO departure filing).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"For each obligation identified, determine IHP's compliance status as of May 15, 2026, including any applicable deadline and its computation.\" The GC memo's governance record description enumerates three documents and makes no reference to a departure notice filing. The absence of any such filing in the record is verifiable by exclusion from the documents enumerated. A model that does not identify this gap has accepted the GC memo's completeness conclusion without testing it against the departure obligation.", + "metadata": { + "irac_section": "Application" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_6", + "description": "Mentions the need for an immediate Cal. Health & Safety Code \u00a7 1352(c) (2026) filing for the prior Chief Medical Officer's departure if no notice has been filed.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 3, Cal. Health & Safety Code \u00a7 1352(c) (2026) (\"A plan shall, within five days, give written notice to the director in the form as by rule may be prescribed, of a change in the officers\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Provide a recommended course of action addressing each obligation identified, including timing and submission mechanics.\" The departure obligation deadline of May 11, 2026 has already passed as of May 15th. A complete course of action requires the model to address this overdue obligation separately from the Connors appointment obligation and recommend immediate filing.", + "metadata": { + "irac_section": "Rule" + }, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_7", + "description": "States that the operative trigger date for the Cal. Health & Safety Code \u00a7 1352(c) (2026) notice arising from Dr. Connors' appointment is May 13, 2026, the date the change was validly effected.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall be effective upon adoption of the ratifying resolution\"); IHP_Board_Resolution_2026-14.docx, p. 2, Record of Adoption (\"The foregoing Resolution was duly adopted at the regular meeting of the Board of Directors of Imperium Health Plan, Inc. held on May 13, 2026, at which a quorum was present and acting throughout\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"For each obligation identified, determine IHP's compliance status as of May 15, 2026, including any applicable deadline and its computation.\" The trigger date is the date the change was validly effected. Because Section 5.9 provides that ratification is effective upon adoption, the change occurred on May 13, 2026. A model that selects May 7th as the trigger carries a wrong premise into the deadline calculation.", + "metadata": { + "irac_section": "Application" + }, + "score": 30.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_8", + "description": "States that May 18, 2026, computed as five days from May 13, 2026, is the sole operative filing deadline for the Cal. Health & Safety Code \u00a7 1352(c) (2026) notice arising from Dr. Connors' appointment.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 3, Cal. Health & Safety Code \u00a7 1352(c) (2026) (\"A plan shall, within five days, give written notice to the director in the form as by rule may be prescribed, of a change in the officers\"); IHP_Board_Resolution_2026-14.docx, p. 2, Record of Adoption (\"The foregoing Resolution was duly adopted at the regular meeting of the Board of Directors of Imperium Health Plan, Inc. held on May 13, 2026, at which a quorum was present and acting throughout\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"For each obligation identified, determine IHP's compliance status as of May 15, 2026, including any applicable deadline and its computation.\" May 18, 2026 is the correct deadline under a May 13th trigger. Credit requires the memorandum to adopt May 18th as the controlling deadline for this obligation. Presenting May 18th as one alternative alongside an adopted earlier deadline does not earn credit.", + "metadata": { + "irac_section": "Application" + }, + "score": 25.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_9", + "description": "States that as of May 15, 2026, the Cal. Health & Safety Code \u00a7 1352(c) (2026) obligation arising from Dr. Connors' appointment is not yet overdue.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 3, Cal. Health & Safety Code \u00a7 1352(c) (2026) (\"A plan shall, within five days, give written notice to the director in the form as by rule may be prescribed, of a change in the officers\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"For each obligation identified, determine IHP's compliance status as of May 15, 2026, including any applicable deadline and its computation.\" The anchor date is May 15, 2026. The deadline is May 18, 2026. IHP has three days remaining to file. A model that correctly identifies the May 13th trigger and the May 18th deadline reaches this compliance status conclusion.", + "metadata": { + "irac_section": "Application" + }, + "score": 15.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_10", + "description": "States that Cal. Code Regs. tit. 28, \u00a7 1300.52.2(a) (2026) requires an amendment filing for the addition of a principal officer.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 4, Cal. Code Regs. tit. 28, \u00a7 1300.52.2(a) (2026) (\"There is an addition or deletion of a director, trustee, principal officer, general partner, general manager or principal management persons, or persons occupying similar positions or performing similar functions, or a substantial and material change in the duties of any such person\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Provide a recommended course of action addressing each obligation identified, including timing and submission mechanics.\" Cal. Code Regs. tit. 28, \u00a7 1300.52.2(a) (2026) is the regulatory provision specifying that a principal officer addition requires an amendment filing. A complete course of action requires identifying the correct filing vehicle, not merely the statutory notice obligation.", + "metadata": { + "irac_section": "Rule" + }, + "score": 3.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_11", + "description": "States that Cal. Code Regs. tit. 28, \u00a7 1300.52.4(b)(ii) (2026) provides that an amendment filed for a change described in Cal. Health & Safety Code \u00a7 1352(c) (2026) is effective on the date implemented.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 6, Cal. Code Regs. tit. 28, \u00a7 1300.52.4(b)(ii) (2026) (\"In the event of any change described in Section 1352(c) of the Act, the plan shall file an amendment in accordance with the requirements of Section 1300.52.2. A change that is the subject of an amendment required to be filed pursuant to this subsection (b)(ii) shall be effective on the date implemented\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Provide a recommended course of action addressing each obligation identified, including timing and submission mechanics.\" Cal. Code Regs. tit. 28, \u00a7 1300.52.4(b)(ii) (2026) confirms that the amendment filing for a section 1352(c) change is effective on the date implemented, not the date filed. This mechanic is relevant to the submission posture and the recommended course of action.", + "metadata": { + "irac_section": "Rule" + }, + "score": 6.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_12", + "description": "States that IHP should file the Cal. Health & Safety Code \u00a7 1352(c) (2026) amendment for Dr. Connors' appointment before May 18, 2026.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 3, Cal. Health & Safety Code \u00a7 1352(c) (2026) (\"A plan shall, within five days, give written notice to the director in the form as by rule may be prescribed, of a change in the officers\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Provide a recommended course of action addressing each obligation identified, including timing and submission mechanics.\" The five-day window closes on May 18, 2026. Filing before that date preserves IHP's timely compliance posture for the Connors appointment obligation. A recommended course of action that does not specify the deadline date is incomplete.", + "metadata": { + "irac_section": "Conclusion" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_13", + "description": "States that IHP's Cal. Health & Safety Code \u00a7 1352(c) (2026) filing obligation arising from Dr. Connors' appointment lapsed before May 15, 2026.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 3, Cal. Health & Safety Code \u00a7 1352(c) (2026) (\"A plan shall, within five days, give written notice to the director in the form as by rule may be prescribed, of a change in the officers\"); IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall be effective upon adoption of the ratifying resolution\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"For each obligation identified, determine IHP's compliance status as of May 15, 2026, including any applicable deadline and its computation.\" The Connors appointment obligation does not lapse before May 15, 2026 under a correct trigger analysis. A model that concludes otherwise has applied the wrong trigger date. A lapse conclusion for the departure obligation does not trigger this item.", + "metadata": { + "irac_section": "Application" + }, + "score": -30.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_14", + "description": "Mentions that the Cal. Health & Safety Code \u00a7 1352(c) (2026) filing for Dr. Connors' appointment is timely based on a May 7, 2026 trigger date.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 3, Cal. Health & Safety Code \u00a7 1352(c) (2026) (\"A plan shall, within five days, give written notice to the director in the form as by rule may be prescribed, of a change in the officers\"); IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall be effective upon adoption of the ratifying resolution\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"For each obligation identified, determine IHP's compliance status as of May 15, 2026, including any applicable deadline and its computation.\" Under a May 7th trigger, the five-day window closed on May 12, 2026. A model that accepts May 7th as the trigger but concludes the filing is still timely as of May 15th has produced an internally inconsistent analysis. Timeliness and a May 7th trigger cannot coexist.", + "metadata": { + "irac_section": "Application" + }, + "score": -15.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_15", + "description": "Mentions filing the Cal. Health & Safety Code \u00a7 1352(c) (2026) notice for Dr. Connors' appointment by a date computed from May 7, 2026 as a precautionary measure.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 3, Cal. Health & Safety Code \u00a7 1352(c) (2026) (\"A plan shall, within five days, give written notice to the director in the form as by rule may be prescribed, of a change in the officers\"); IHP_Board_Resolution_2026-14.docx, p. 2, Record of Adoption (\"The foregoing Resolution was duly adopted at the regular meeting of the Board of Directors of Imperium Health Plan, Inc. held on May 13, 2026, at which a quorum was present and acting throughout\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"For each obligation identified, determine IHP's compliance status as of May 15, 2026, including any applicable deadline and its computation.\" A model that identifies May 13 as the trigger date but recommends filing by a date computed from May 7th as a precautionary measure has adopted a dual-track hedge that is internally inconsistent. The May 13th trigger produces a May 18th deadline. Recommending an earlier date derived from a rejected trigger framework undermines the analysis the model has already committed to.", + "metadata": { + "irac_section": "Application" + }, + "score": -10.0, + "polarity": "negative", + "raw_weight": 1.0 + } + ] +} diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/m1_judge_panel.json b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/m1_judge_panel.json new file mode 100644 index 0000000000000000000000000000000000000000..a8041f6781a899f9083fe4a1a95f51bc78d35601 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/m1_judge_panel.json @@ -0,0 +1,21 @@ +{ + "mode": "panel", + "max_concurrent_llm": 12, + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ] +} diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/m1_rewardkit_accounting.py b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/m1_rewardkit_accounting.py new file mode 100644 index 0000000000000000000000000000000000000000..406dc5e7c675b222d94514e71bf5fad6ae141d8f --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/m1_rewardkit_accounting.py @@ -0,0 +1,490 @@ +import asyncio +import json +import math +import os +from pathlib import Path +import random +import sys +import time + +class JudgeReceiptError(OSError): + pass +_LLM_ROUTES = frozenset({'vertex', 'anthropic fallback', 'aistudio', 'direct'}) +_LLM_ROUTE_HEADERS = ('x-m1-llm-route', 'llm_provider-x-m1-llm-route') + +def _canonical_llm_route(value): + return value if isinstance(value, str) and value in _LLM_ROUTES else None + +def _llm_route_from_headers(headers): + if not isinstance(headers, dict): + return None + folded = {str(key).lower(): value for key, value in headers.items()} + for name in _LLM_ROUTE_HEADERS: + route = _canonical_llm_route(folded.get(name)) + if route is not None: + return route + return None + +def _llm_route_from_response(response): + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + route = _llm_route_from_headers(headers) + if route is not None: + return route + return _llm_route_from_headers(getattr(response, 'headers', None)) + +def _token_field_status(values, key): + if not isinstance(values, dict) or key not in values: + return 'missing' + value = values[key] + if value is None: + return 'null' + return 'valid' if type(value) is int and value >= 0 else 'invalid' + +def _gemini_capture(kwargs, model): + if not model.startswith('gemini/') or kwargs.get('stream') or kwargs.get('tools') or kwargs.get('functions'): + return (kwargs, None) + from litellm.integrations.custom_logger import CustomLogger + from urllib.parse import urlsplit + + class Capture(CustomLogger): + evidence = None + prompt_status = 'not_observed' + llm_route = None + + def log_post_api_call(self, kwargs, response_obj, start_time, end_time): + self.evidence = None + self.prompt_status = 'not_observed' + try: + params = kwargs.get('litellm_params') or {} + route = urlsplit(params.get('api_base') or '') + bare = model.removeprefix('gemini/') + gemini = params.get('custom_llm_provider') == 'gemini' + ai_studio = gemini and route.hostname == 'generativelanguage.googleapis.com' and (route.path in {'/' + version + '/models/' + bare + ':generateContent' for version in ('v1alpha', 'v1beta')}) + broker = urlsplit(os.environ.get('GEMINI_API_BASE') or '') + brokered = gemini and bool(broker.netloc) and (route.netloc == broker.netloc) and (broker.path.rstrip('/').rsplit('/', 1)[-1] in ('v1alpha', 'v1beta')) and (route.path == broker.path.rstrip('/') + '/models/' + bare + ':generateContent') + vertex = params.get('custom_llm_provider') == 'vertex_ai' and route.hostname == 'aiplatform.googleapis.com' and route.path.startswith('/v1/projects/') and route.path.endswith('/locations/global/publishers/google/models/' + bare + ':generateContent') + if route.scheme != 'https' or not (ai_studio or brokered or vertex) or kwargs.get('stream'): + return + self.llm_route = 'vertex' if vertex else 'aistudio' if ai_studio else None + raw = kwargs.get('original_response') + raw = json.loads(raw) if isinstance(raw, str) else raw + if not isinstance(raw, dict): + return + candidates = raw.get('candidates') + if not isinstance(candidates, list) or not candidates or any((not isinstance(c, dict) or not c.get('finishReason') for c in candidates)) or (not isinstance(raw.get('modelVersion'), str)) or (not raw['modelVersion']): + return + usage = raw.get('usageMetadata') + self.prompt_status = _token_field_status(usage, 'promptTokenCount') + if not isinstance(usage, dict): + return + fields = ('promptTokenCount', 'candidatesTokenCount', 'thoughtsTokenCount', 'cachedContentTokenCount', 'totalTokenCount', 'toolUsePromptTokenCount') + counts = {key: usage.get(key, 0) for key in fields} + if not {'promptTokenCount', 'totalTokenCount'} <= usage.keys() or any((type(n) is not int or n < 0 for n in counts.values())) or counts['toolUsePromptTokenCount'] != 0 or (counts['cachedContentTokenCount'] > counts['promptTokenCount']) or (counts['totalTokenCount'] != counts['promptTokenCount'] + counts['candidatesTokenCount'] + counts['thoughtsTokenCount']): + return + self.evidence = {'protocol': 'gemini-generate-content-' + ('vertex-v1' if vertex else route.path.split('/')[-3]), 'model_version': raw['modelVersion'], 'usage_metadata': {key: usage[key] for key in fields if key in usage}, 'defaulted_fields': [key for key in fields if key not in usage]} + except (TypeError, ValueError, AttributeError): + return + capture = Capture() + return ({**kwargs, 'callbacks': [*(kwargs.get('callbacks') or []), capture]}, capture) + +def _record_judge_usage(response, model: str, *, target: Path | None=None, native_usage: dict | None=None, native_prompt_status: str | None=None, llm_route: str | None=None) -> None: + import fcntl + from datetime import datetime, timezone + data = response.model_dump() if hasattr(response, 'model_dump') else response + usage = data.get('usage') if isinstance(data, dict) else None + granularity = data.get('usage_granularity') if isinstance(data, dict) else None + if not isinstance(usage, dict): + usage = {} + granularity = 'missing_provider_receipt' + prompt, completion = (usage.get('prompt_tokens'), usage.get('completion_tokens')) + native_fresh = usage.get('input_uncached_tokens') + prompt = prompt if type(prompt) is int and prompt >= 0 else None + native_fresh = native_fresh if type(native_fresh) is int and native_fresh >= 0 else None + if type(completion) is not int or completion < 0 or (prompt is None and native_fresh is None): + completion = completion if type(completion) is int and completion >= 0 else 0 + granularity = granularity or 'invalid_provider_receipt' + details = usage.get('prompt_tokens_details') + if details is not None and (not isinstance(details, dict)): + granularity = 'invalid_provider_receipt' + details = details if isinstance(details, dict) else {} + cached = details.get('cached_tokens') + if native_usage is not None: + native = native_usage['usage_metadata'] + native_output = native.get('candidatesTokenCount', 0) + native.get('thoughtsTokenCount', 0) + if prompt == native['promptTokenCount'] and completion == native_output: + cached = native.get('cachedContentTokenCount', 0) + else: + native_usage = None + written = next((value for value in (usage.get('input_cache_write_tokens'), usage.get('cache_creation_input_tokens'), details.get('cache_creation_tokens'), details.get('cache_write_tokens')) if value is not None), None) + invalid = any((value is not None and (type(value) is not int or value < 0) for value in (cached, written))) + cached = cached if type(cached) is int and cached >= 0 else None + written = written if type(written) is int and written >= 0 else None + fresh = native_fresh + if fresh is None and prompt is not None and (cached is not None) and (written is not None): + fresh = prompt - cached - written + if fresh is not None and (fresh < 0 or (prompt is not None and cached is not None and (written is not None) and (fresh + cached + written != prompt))): + invalid, fresh = (True, None) + provider, _, slug = model.partition('/') + event: dict = {'type': 'step_finish', 'part': {'providerID': provider if slug else 'openai', 'modelID': slug or model, 'tokens': {'input': fresh, 'output': completion, 'cache': {'read': cached, 'write': written}}}} + field_status = {'prompt_tokens': _token_field_status(usage, 'prompt_tokens'), 'completion_tokens': _token_field_status(usage, 'completion_tokens'), 'input_uncached_tokens': _token_field_status(usage, 'input_uncached_tokens')} + field_status['native_prompt_token_count'] = native_prompt_status if native_prompt_status in {'missing', 'null', 'invalid', 'valid', 'not_observed'} else 'unsupported' + part: dict = event['part'] + part['usage_field_status'] = field_status + if native_usage is not None: + event['part']['native_usage'] = native_usage + event['part']['token_categories_provenance'] = 'explicit_presence_v1' + if fresh is None and prompt is not None: + event['part']['prompt_tokens_inclusive'] = prompt + if invalid or any((value is None for value in (fresh, cached, written))): + granularity = granularity if granularity not in (None, 'request') else 'invalid_provider_receipt' if invalid else 'incomplete_token_categories' + if granularity: + event['part']['usage_granularity'] = granularity + if provider == 'openrouter': + cost = usage.get('cost') + if cost is None: + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + if isinstance(headers, dict): + cost = headers.get('llm_provider-x-litellm-response-cost') + if isinstance(cost, (int, float)) and (not isinstance(cost, bool)) and math.isfinite(cost) and (cost >= 0): + event['part']['cost'] = cost + data = data if isinstance(data, dict) else {} + if isinstance(data.get('id'), str) and data['id']: + event['part']['provider_request_id'] = data['id'] + for key in ('service_tier', 'cache_ttl'): + if data.get(key): + event['part'][key] = data[key] + route = _llm_route_from_response(response) or _canonical_llm_route(llm_route) + if route is not None: + event['part']['llm_route'] = route + created = data.get('created') + stamp = datetime.now(timezone.utc) + try: + if isinstance(created, str): + parsed = datetime.fromisoformat(created.replace('Z', '+00:00')) + if parsed.tzinfo is not None: + stamp = parsed + elif isinstance(created, (int, float)) and (not isinstance(created, bool)) and math.isfinite(created): + stamp = datetime.fromtimestamp(created, timezone.utc) + except (ValueError, OverflowError, OSError): + pass + pair = json.dumps({'type': 'step_start', 'timestamp': stamp.isoformat()}) + '\n' + pair += json.dumps(event) + '\n' + try: + receipt_path = target or Path(os.environ.get('M1_JUDGE_USAGE_PATH', '/logs/verifier/judge-trajectory.jsonl')) + receipt_path.parent.mkdir(parents=True, exist_ok=True) + with receipt_path.open('a') as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + handle.write(pair) + handle.flush() + os.fsync(handle.fileno()) + except OSError as exc: + if target is not None: + raise JudgeReceiptError(f'judge receipt write failed: {exc}') from exc + print(f'judge accounting: write failed ({type(exc).__name__})', file=sys.stderr) + +def openrouter_judge_pins() -> dict[str, dict]: + raw = os.environ.get('M1_OPENROUTER_JUDGE_PROVIDER_PINS', '').strip() + if not raw: + return {} + try: + pins = json.loads(raw) + except json.JSONDecodeError: + print('judge provider pins: invalid JSON in M1_OPENROUTER_JUDGE_PROVIDER_PINS', file=sys.stderr) + return {} + return {model: pin for model, pin in pins.items() if isinstance(pin, dict) and pin.get('order')} if isinstance(pins, dict) else {} + +def apply_judge_provider_pin(kwargs: dict, pins: dict[str, dict]) -> dict: + model = kwargs.get('model') + pin = pins.get(model) if isinstance(model, str) else None + if pin is None: + return kwargs + extra_body = dict(kwargs.get('extra_body') or {}) + provider = dict(extra_body.get('provider') or {}) + provider['order'] = list(pin['order']) + if pin.get('allow_fallbacks') is False: + provider['allow_fallbacks'] = False + if pin.get('zdr'): + provider['zdr'] = True + extra_body['provider'] = provider + return {**kwargs, 'extra_body': extra_body} +_TRANSIENT_ERROR_NAMES = ('RateLimitError', 'ServiceUnavailableError', 'InternalServerError', 'BadGatewayError', 'APIConnectionError') +_RETRYABLE_STATUS_CODES = frozenset({408, 409, 425, 429, 500, 502, 503, 504}) +_AUTH_ERROR_NAMES = ('AuthenticationError', 'PermissionDeniedError') +_AUTH_STATUS_CODES = frozenset({401, 403}) +_AUTH_RETRIES = 4 +_DEFAULT_TRANSIENT_RETRIES = 6 +_MAX_TRANSIENT_RETRIES = 20 +_MAX_RETRY_DELAY_SECONDS = 60.0 +_DEFAULT_EMPTY_RESPONSE_RETRIES = 3 +_DEFAULT_RETRY_BUDGET_SECONDS = 900.0 +_MAX_RETRY_BUDGET_SECONDS = 86400.0 + +def transient_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_TRANSIENT_RETRIES', '').strip() + if not raw: + return _DEFAULT_TRANSIENT_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_TRANSIENT_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_TRANSIENT_RETRIES + +def empty_response_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_EMPTY_RESPONSE_RETRIES', '').strip() + if not raw: + return _DEFAULT_EMPTY_RESPONSE_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_EMPTY_RESPONSE_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_EMPTY_RESPONSE_RETRIES + +def retry_budget_seconds() -> float: + raw = os.environ.get('M1_JUDGE_RETRY_BUDGET_SECONDS', '').strip() + if not raw: + return _DEFAULT_RETRY_BUDGET_SECONDS + try: + value = float(raw) + except ValueError: + value = math.nan + if not math.isfinite(value) or value < 0: + print('judge retries: invalid M1_JUDGE_RETRY_BUDGET_SECONDS, using the default', file=sys.stderr) + return _DEFAULT_RETRY_BUDGET_SECONDS + return min(value, _MAX_RETRY_BUDGET_SECONDS) + +def _within_budget(deadline: float, delay: float, model) -> bool: + remaining = deadline - time.monotonic() + if delay <= remaining: + return True + print(f'judge call retry budget spent: {model} would wait {delay:.1f}s with {max(remaining, 0.0):.1f}s left of M1_JUDGE_RETRY_BUDGET_SECONDS, failing now', file=sys.stderr) + return False + +def is_empty_verdict(response) -> bool: + data = response.model_dump() if hasattr(response, 'model_dump') else response + if not isinstance(data, dict): + return False + choices = data.get('choices') + if not isinstance(choices, list) or not choices: + return True + first = choices[0] + message = first.get('message') if isinstance(first, dict) else None + if not isinstance(message, dict): + return True + if message.get('tool_calls') or message.get('function_call'): + return False + content = message.get('content') + if isinstance(content, list): + content = ''.join((part.get('text') or '' for part in content if isinstance(part, dict))) + return not (isinstance(content, str) and content.strip()) + +def _matches(exc: BaseException, litellm, names: tuple[str, ...], statuses: frozenset[int]) -> bool: + classes = tuple((cls for cls in (getattr(litellm, name, None) for name in names) if isinstance(cls, type))) + if classes and isinstance(exc, classes): + return True + status = getattr(exc, 'status_code', None) + return type(status) is int and status in statuses + +def is_transient_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _TRANSIENT_ERROR_NAMES, _RETRYABLE_STATUS_CODES) + +def is_auth_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _AUTH_ERROR_NAMES, _AUTH_STATUS_CODES) + +def should_retry(exc: BaseException, litellm, attempt: int, limit: int) -> bool: + if attempt < limit and is_transient_error(exc, litellm): + return True + return attempt < min(limit, _AUTH_RETRIES) and is_auth_error(exc, litellm) + +def _retry_after_seconds(exc: BaseException) -> float | None: + headers = getattr(exc, 'headers', None) + if headers is None: + headers = getattr(getattr(exc, 'response', None), 'headers', None) + if headers is None: + return None + try: + raw = headers.get('retry-after') + if raw is None: + raw = headers.get('Retry-After') + value = float(raw) + except (AttributeError, TypeError, ValueError): + return None + return value if math.isfinite(value) and value >= 0 else None + +def retry_delay(exc: BaseException | None, attempt: int) -> float: + base = min(_MAX_RETRY_DELAY_SECONDS, 2.0 ** (attempt + 1)) + delay = base * (0.5 + random.random()) + retry_after = _retry_after_seconds(exc) if exc is not None else None + if retry_after is not None: + delay = max(delay, min(_MAX_RETRY_DELAY_SECONDS, retry_after)) + return delay + +def _note_retry(model, exc: BaseException, attempt: int, limit: int, delay: float) -> None: + status = getattr(exc, 'status_code', None) + print(f"judge call retry {attempt}/{limit}: {model} {type(exc).__name__} status={(status if type(status) is int else 'n/a')}, waiting {delay:.1f}s", file=sys.stderr) + +def _note_empty(model, response, attempt: int, limit: int, delay: float) -> None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + reason = None + if isinstance(data, dict) and isinstance(data.get('choices'), list) and data['choices']: + first = data['choices'][0] + reason = first.get('finish_reason') if isinstance(first, dict) else None + print(f'judge call retry {attempt}/{limit}: {model} empty verdict (finish_reason={reason}), waiting {delay:.1f}s', file=sys.stderr) + +def install(litellm, *, synchronous: bool=False) -> None: + pins = openrouter_judge_pins() + limit = transient_retry_limit() + empty_limit = empty_response_retry_limit() + deadline = time.monotonic() + retry_budget_seconds() + if synchronous: + original = litellm.completion + + def accounted(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = original(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + time.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + time.sleep(delay) + continue + return response + litellm.completion = accounted + return + original_async = litellm.acompletion + + async def accounted_async(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = await original_async(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + await asyncio.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + await asyncio.sleep(delay) + continue + return response + litellm.acompletion = accounted_async + +def record_agent_usage(attempt, *, model: str, provider: str) -> None: + records: dict[str, tuple[str, dict]] = {} + current_model = model + for filename in getattr(attempt, 'logs', []): + try: + with Path(filename).open() as stream: + for line in stream: + try: + event = json.loads(line) + except (ValueError, TypeError): + continue + if not isinstance(event, dict): + continue + message = event.get('message') or {} + if event.get('type') == 'assistant' and isinstance(message, dict) and isinstance(message.get('usage'), dict): + raw = message['usage'] + cached, written = (raw.get('cache_read_input_tokens'), raw.get('cache_creation_input_tokens')) + if all((type(value) is int and value >= 0 for value in (raw.get('input_tokens'), raw.get('output_tokens')))) and all((value is None or (type(value) is int and value >= 0) for value in (cached, written))): + receipt: dict = {'usage': {'input_uncached_tokens': raw['input_tokens'], 'prompt_tokens': raw['input_tokens'] + cached + written if cached is not None and written is not None else None, 'completion_tokens': raw['output_tokens'], 'prompt_tokens_details': {'cached_tokens': cached, 'cache_creation_tokens': written}}} + receipt['created'] = event.get('timestamp') + creation = raw.get('cache_creation') or {} + hour = creation.get('ephemeral_1h_input_tokens', 0) if isinstance(creation, dict) else 0 + if type(hour) is int and hour > 0: + if hour == written: + receipt['cache_ttl'] = '1h' + else: + receipt['usage_granularity'] = 'mixed_cache_ttl' + records[message.get('id') or json.dumps(raw, sort_keys=True)] = (message.get('model') or current_model, receipt) + payload = event.get('payload') or {} + if not isinstance(payload, dict): + continue + if event.get('type') == 'turn_context' and payload.get('model'): + current_model = payload['model'] + if event.get('type') == 'event_msg' and payload.get('type') == 'token_count': + info = payload.get('info') or {} + raw, total = (info.get('last_token_usage'), info.get('total_token_usage')) + if isinstance(raw, dict) and isinstance(total, dict) and all((type(raw.get(key)) is int and raw.get(key) >= 0 for key in ('input_tokens', 'output_tokens'))): + receipt = {'usage': {'prompt_tokens': raw.get('input_tokens'), 'input_uncached_tokens': raw.get('input_uncached_tokens'), 'input_cache_write_tokens': raw.get('input_cache_write_tokens'), 'completion_tokens': raw.get('output_tokens'), 'prompt_tokens_details': {'cached_tokens': raw.get('cached_input_tokens')}}} + receipt['created'] = event.get('timestamp') + records[json.dumps(total, sort_keys=True)] = (current_model, receipt) + except OSError: + continue + captured_input = captured_output = 0 + input_complete = True + for requested, receipt in records.values(): + requested = requested if '/' in requested else f'{provider}/{requested}' + _record_judge_usage(receipt, requested) + receipt_input = receipt['usage'].get('prompt_tokens') + if receipt_input is None: + input_complete = False + else: + captured_input += receipt_input + captured_output += receipt['usage'].get('completion_tokens') or 0 + total = getattr(attempt, 'usage', {}) or {} + if not records or (input_complete and total.get('input_tokens') != captured_input) or total.get('output_tokens') != captured_output: + _record_judge_usage({'usage': {'prompt_tokens': 0, 'completion_tokens': 0}, 'usage_granularity': 'incomplete_agent_receipts'}, model if '/' in model else f'{provider}/{model}') + +def install_rewardkit_agents() -> None: + import rewardkit.judges as judges + original = judges.get_agent + + def get_accounted_agent(judge, cwd=None): + backend = original(judge, cwd) + run = backend.run + + async def accounted_run(*args, **kwargs): + attempt = await run(*args, **kwargs) + record_agent_usage(attempt, model=judge.model or 'unknown', provider='anthropic' if judge.agent == 'claude-code' else 'openai') + return attempt + setattr(backend, 'run', accounted_run) + return backend + setattr(judges, 'get_agent', get_accounted_agent) +if __name__ == '__main__': + import litellm + if len(sys.argv) > 2 and sys.argv[1] == '--script': + import runpy + install(litellm, synchronous=True) + sys.argv = sys.argv[2:] + runpy.run_path(sys.argv[0], run_name='__main__') + else: + install(litellm) + install_rewardkit_agents() + if Path(__file__).with_name('m1_judge_panel.json').is_file(): + from m1_rewardkit_panel import install_panel + install_panel(Path(__file__).with_name('m1_judge_panel.json')) + if Path(__file__).with_name('m1_judge_jev.json').is_file(): + from m1_rewardkit_jev import install_jev + install_jev(Path(__file__).with_name('m1_judge_jev.json')) + from rewardkit.__main__ import main + main() diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/m1_rewardkit_panel.py b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/m1_rewardkit_panel.py new file mode 100644 index 0000000000000000000000000000000000000000..164cc2ae521cdd368c2e1749d7ed8fe09f4545eb --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/m1_rewardkit_panel.py @@ -0,0 +1,169 @@ +from __future__ import annotations +import asyncio +from contextvars import ContextVar +import json +import math +import os +import sys +from pathlib import Path +from typing import Any +import uuid +_request_audit: ContextVar[tuple[Path, list[str]] | None] = ContextVar('panel_request_audit', default=None) + +class PanelIncompleteError(RuntimeError): + pass + +def _audit_warning(exc: Exception, warnings: list[str]) -> None: + message = f'judge panel audit: diagnostic capture failed ({type(exc).__name__})' + if message not in warnings: + warnings.append(message) + print(message, file=sys.stderr) + +def _write_audit(path: Path, record: dict[str, Any], warnings: list[str], *, append: bool=False) -> None: + try: + text = json.dumps(record, allow_nan=False, default=str) + '\n' + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('a' if append else 'w') as stream: + stream.write(text) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + +def _binary(raw: Any) -> int: + if isinstance(raw, bool): + return int(raw) + if isinstance(raw, int | float) and math.isfinite(raw) and (raw in (0, 1)): + return int(raw) + if isinstance(raw, str): + value = raw.strip().lower() + if value in {'yes', 'true', '1'}: + return 1 + if value in {'no', 'false', '0'}: + return 0 + raise PanelIncompleteError('m1_judge_panel_incomplete: invalid binary vote') + +def validate_votes(scores: list[Any], criteria: list[Any]) -> None: + names = [criterion.name for criterion in criteria] + if len(set(names)) != len(names) or [score.name for score in scores] != names: + raise PanelIncompleteError('m1_judge_panel_incomplete: criterion membership mismatch') + for score, criterion in zip(scores, criteria, strict=True): + if score.error: + raise PanelIncompleteError('m1_judge_panel_incomplete: judge returned an error') + raw = _binary(score.raw) + expected = 1 - raw if criterion.negate else raw + if not math.isfinite(score.value) or score.value != expected: + raise PanelIncompleteError('m1_judge_panel_incomplete: inconsistent binary score') + +async def run_panel(judge: Any, criteria: list[Any], weights: list[float] | None, system_prompt: str | None, *, config: dict[str, Any], run_llm: Any, score_type: Any, audit_dir: Path) -> tuple[list[Any], str, list[str]]: + from rewardkit.models import Binary + if not criteria or any((not isinstance(criterion.output_format, Binary) for criterion in criteria)): + raise ValueError('panel majority voting requires nonempty binary criteria') + group_dir = audit_dir / uuid.uuid4().hex + warnings_out: list[str] = [] + + async def member_call(index: int, member: dict[str, Any]): + member_judge = judge.model_copy(update=member) + evidence: dict[str, Any] = {'member': index + 1, 'judge': member, 'criteria': [criterion.name for criterion in criteria], 'status': 'started'} + path = group_dir / f'judge-{index + 1}.json' + _write_audit(path, evidence, warnings_out) + token = _request_audit.set((group_dir / f'judge-{index + 1}-requests.jsonl', warnings_out)) + try: + scores, output, warnings = await run_llm(member_judge, criteria, weights, system_prompt) + evidence.update(output=output, warnings=warnings) + validate_votes(scores, criteria) + evidence['scores'] = [score.to_dict() for score in scores] + evidence['status'] = 'completed' + return (scores, output, warnings) + except BaseException as exc: + evidence.update(status='failed', error_class=type(exc).__name__) + if isinstance(exc, PanelIncompleteError): + evidence['error'] = str(exc) + raise + finally: + _request_audit.reset(token) + _write_audit(path, evidence, warnings_out) + outcomes = await asyncio.gather(*(member_call(index, member) for index, member in enumerate(config['members'])), return_exceptions=True) + failed = [index + 1 for index, result in enumerate(outcomes) if isinstance(result, BaseException)] + if failed: + _write_audit(group_dir / 'panel.json', {'status': 'incomplete', 'failed_members': failed}, warnings_out) + raise PanelIncompleteError(f'm1_judge_panel_incomplete: failed members {failed}; see panel audit artifacts') + completed = [outcome for outcome in outcomes if not isinstance(outcome, BaseException)] + combined = [] + for index, criterion in enumerate(criteria): + votes = [{'judge': config['members'][member_index], **outcome[0][index].to_dict()} for member_index, outcome in enumerate(completed)] + passes = sum((vote['value'] == 1 for vote in votes)) + value = int(passes >= 2) + combined.append(score_type(name=criterion.name, value=value, raw=bool(1 - value if criterion.negate else value), weight=weights[index] if weights is not None else 1.0, reasoning=f'{passes}/3 judges passed; strict majority requires 2/3.', description=criterion.description, id=criterion.id, negate=criterion.negate, optional=criterion.optional, votes=votes)) + for outcome in completed: + warnings_out.extend(outcome[2]) + audit = {'status': 'completed', 'mode': 'panel', 'aggregation': 'majority', 'required_votes': 2, 'members': config['members'], 'criteria': [score.to_dict() for score in combined]} + output = json.dumps(audit, indent=2, allow_nan=False) + _write_audit(group_dir / 'panel.json', audit, warnings_out) + return (combined, output, warnings_out) + +def install_panel(config_path: Path, *, audit_dir: Path=Path('/logs/verifier/judge-panel')) -> None: + import rewardkit.judges as judges + import rewardkit.reward as reward + from rewardkit.models import LLMJudge, Score + import litellm + config = json.loads(config_path.read_text()) + members = config.get('members') + concurrency = config.get('max_concurrent_llm') + if config.get('mode') != 'panel' or not isinstance(members, list) or len(members) != 3 or (len({member['model'] for member in members}) != 3) or (type(concurrency) is not int) or (not 1 <= concurrency <= 64): + raise ValueError('invalid materialized panel configuration') + if os.environ.get('REWARDKIT_JUDGE') or os.environ.get('REWARDKIT_MODEL'): + raise ValueError('RewardKit environment overrides cannot replace a frozen panel') + + class PanelScore(Score): + votes: list[dict[str, Any]] + + def to_dict(self): + return {**super().to_dict(), 'votes': self.votes} + original_llm = judges.arun_llm + original_call = judges._arun_llm_call + original_details = reward.Reward.to_detail_dict + original_completion = litellm.acompletion + active_loop = None + semaphore = None + + async def captured_completion(*args, **kwargs): + context = _request_audit.get() + record = {'requested_model': kwargs.get('model')} + response = None + try: + response = await original_completion(*args, **kwargs) + return response + except BaseException as exc: + record['error_class'] = type(exc).__name__ + raise + finally: + if context is not None: + path, warnings = context + try: + if response is not None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + record.update(response_model=data.get('model'), choices=data.get('choices')) + _write_audit(path, record, warnings, append=True) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + + async def bounded_call(*args, **kwargs): + nonlocal active_loop, semaphore + loop = asyncio.get_running_loop() + if active_loop is not loop: + active_loop, semaphore = (loop, asyncio.Semaphore(concurrency)) + assert semaphore is not None + async with semaphore: + return await original_call(*args, **kwargs) + + async def panel_call(judge, criteria, weights=None, system_prompt=None): + return await run_panel(judge, criteria, weights, system_prompt, config=config, run_llm=original_llm, score_type=PanelScore, audit_dir=audit_dir) + + def panel_details(self, score): + detail = original_details(self, score) + if isinstance(self.judge, LLMJudge): + detail.update(kind='llm_panel', judge=config, aggregation='majority', required_votes=2) + return detail + setattr(reward, 'arun_llm', panel_call) + setattr(judges, '_arun_llm_call', bounded_call) + setattr(litellm, 'acompletion', captured_completion) + reward.Reward.to_detail_dict = panel_details diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/normalize_reward.py b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/normalize_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..91817ef00ea9152ca57f0030d8e879eb850ddff0 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/normalize_reward.py @@ -0,0 +1,71 @@ +from __future__ import annotations +import argparse +import json +from pathlib import Path +from typing import Any + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument('--raw-details', required=True) + parser.add_argument('--rubric', required=True) + parser.add_argument('--reward-out', required=True) + parser.add_argument('--details-out', required=True) + args = parser.parse_args() + raw_details = _load_json(Path(args.raw_details)) + rubric = _load_json(Path(args.rubric)) + criteria = rubric['criteria'] + raw_by_name = _raw_criteria_by_name(raw_details) + positive_total = sum((float(item['score']) for item in criteria if float(item['score']) > 0)) + if positive_total <= 0: + raise ValueError('rubric must contain at least one positive score') + earned = 0.0 + normalized_criteria: list[dict[str, Any]] = [] + for item in criteria: + signed_score = float(item['score']) + raw = raw_by_name.get(item['name'], {}) + value = _coerce_score(raw.get('value', 0.0)) + contribution = value * signed_score + earned += contribution + normalized_criteria.append({'name': item['name'], 'value': value, 'raw': raw.get('raw'), 'weight': signed_score, 'signed_score': signed_score, 'polarity': item['polarity'], 'contribution': contribution, 'description': item['description'], 'source': item.get('source', ''), 'justification': item.get('justification', ''), 'metadata': item.get('metadata', {}), 'reasoning': raw.get('reasoning'), 'judge_reasoning': raw.get('reasoning'), 'judge_error': raw.get('error'), **({'votes': raw['votes']} if 'votes' in raw else {})}) + unclamped = earned / positive_total + reward = max(0.0, min(1.0, unclamped)) + reward_out = {'correctness': reward} + details_out = {'correctness': {'score': reward, 'kind': 'signed_score', 'criteria': normalized_criteria, 'aggregation': {'method': 'signed_score_ratio_clamped', 'earned': earned, 'positive_total': positive_total, 'unclamped': unclamped, 'clamped': reward}, 'raw_rewardkit': raw_details}} + _write_json(Path(args.reward_out), reward_out) + _write_json(Path(args.details_out), details_out) + +def _load_json(path: Path) -> Any: + return json.loads(path.read_text()) + +def _write_json(path: Path, data: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data, indent=2) + '\n') + +def _raw_criteria_by_name(details: dict[str, Any]) -> dict[str, dict[str, Any]]: + out: dict[str, dict[str, Any]] = {} + for reward in details.values(): + for item in _iter_raw_criteria(reward): + name = item.get('name') + if isinstance(name, str): + out[name] = item + return out + +def _iter_raw_criteria(value: Any): + if isinstance(value, list): + for item in value: + yield from _iter_raw_criteria(item) + return + if not isinstance(value, dict): + return + for item in value.get('criteria') or []: + if isinstance(item, dict): + yield item + +def _coerce_score(value: Any) -> float: + if isinstance(value, bool): + return 1.0 if value else 0.0 + if isinstance(value, int | float): + return max(0.0, min(1.0, float(value))) + return 0.0 +if __name__ == '__main__': + main() diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/agent_prompt.md b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/agent_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..ca489c065bafd5d10e764f033c9dfd1195933db3 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/agent_prompt.md @@ -0,0 +1,10 @@ +You are grading the submitted legal analysis against the criteria below. + +Read `/logs/artifacts/answer.md`, the answer captured by the verifier, before +assigning any scores. Evaluate that file as the submission. Other files in +`/app` may supply context, but must not replace the submitted answer. Do not +modify the submission. If it is missing or empty, state that in your reasoning +and apply the criteria to that missing or empty submission. Preserve each +criterion's stated positive or penalty polarity. + +{criteria} diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_1.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_1.toml new file mode 100644 index 0000000000000000000000000000000000000000..5d55d0ff535dd8039e460e6f9cc61ee006b40a0b --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_1.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_1" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that the notice requirement under Cal. Health & Safety Code § 1352(c) (2026) mandating disclosure \"of a change in the officers\" is triggered by Dr. Connors' appointment to a principal officer position at IHP." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_10.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_10.toml new file mode 100644 index 0000000000000000000000000000000000000000..a1095928071a5449d3dd96e1ee0944402ccbf90c --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_10.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_10" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that Cal. Code Regs. tit. 28, § 1300.52.2(a) (2026) requires an amendment filing for the addition of a principal officer." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_11.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_11.toml new file mode 100644 index 0000000000000000000000000000000000000000..76f2664c3d17578faa17f81db432d4e5d63ee34b --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_11.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_11" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that Cal. Code Regs. tit. 28, § 1300.52.4(b)(ii) (2026) provides that an amendment filed for a change described in Cal. Health & Safety Code § 1352(c) (2026) is effective on the date implemented." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_12.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_12.toml new file mode 100644 index 0000000000000000000000000000000000000000..6225646468d98755de8914a64a78d0bc9727cd7a --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_12.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_12" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that IHP should file the Cal. Health & Safety Code § 1352(c) (2026) amendment for Dr. Connors' appointment before May 18, 2026." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_13.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_13.toml new file mode 100644 index 0000000000000000000000000000000000000000..4a75155833e11eb7007b070e251d9567e8a64aab --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_13.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_13" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: States that IHP's Cal. Health & Safety Code § 1352(c) (2026) filing obligation arising from Dr. Connors' appointment lapsed before May 15, 2026." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_14.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_14.toml new file mode 100644 index 0000000000000000000000000000000000000000..2b54333cd7322d74cbcfbab2a026d90dc7e006ed --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_14.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_14" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: Mentions that the Cal. Health & Safety Code § 1352(c) (2026) filing for Dr. Connors' appointment is timely based on a May 7, 2026 trigger date." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_15.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_15.toml new file mode 100644 index 0000000000000000000000000000000000000000..bed20138e669045e4092d1b9138b403ecba6776e --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_15.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_15" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: Mentions filing the Cal. Health & Safety Code § 1352(c) (2026) notice for Dr. Connors' appointment by a date computed from May 7, 2026 as a precautionary measure." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_2.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_2.toml new file mode 100644 index 0000000000000000000000000000000000000000..c66124e5ad28a64c6e80543bbb1bec9d2541293c --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_2.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_2" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that Cal. Health & Safety Code § 1352(c) (2026) requires a plan to give written notice to the director within five days of a change in the officers of the plan." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_3.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_3.toml new file mode 100644 index 0000000000000000000000000000000000000000..ae03b38479a0799e5fced4b8c8f0680bb05b030c --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_3.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_3" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies the departure of IHP's prior Chief Medical Officer effective May 6, 2026 as a change in the officers giving rise to a separate notice obligation under Cal. Health & Safety Code § 1352(c) (2026)." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_4.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_4.toml new file mode 100644 index 0000000000000000000000000000000000000000..866ff8b1c3947dd8ce944abebab3ae800395164e --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_4.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_4" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that the deadline for the Cal. Health & Safety Code § 1352(c) (2026) notice arising from the prior Chief Medical Officer's departure was May 11, 2026, computed as five days from May 6, 2026." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_5.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_5.toml new file mode 100644 index 0000000000000000000000000000000000000000..add38ca72b96de3933adfb6be08e5606685cad52 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_5.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_5" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that the uploaded files contain no indication that a notice was filed under Cal. Health & Safety Code § 1352(c) (2026) regarding the departure of the previous Chief Medical Officer." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_6.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_6.toml new file mode 100644 index 0000000000000000000000000000000000000000..7ed130baf5f01fb7a71fb56612bb28dd39b4ba8b --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_6.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_6" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions the need for an immediate Cal. Health & Safety Code § 1352(c) (2026) filing for the prior Chief Medical Officer's departure if no notice has been filed." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_7.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_7.toml new file mode 100644 index 0000000000000000000000000000000000000000..ab6a88ad80e20036a9506750b64dbd072e10b7cf --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_7.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_7" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that the operative trigger date for the Cal. Health & Safety Code § 1352(c) (2026) notice arising from Dr. Connors' appointment is May 13, 2026, the date the change was validly effected." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_8.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_8.toml new file mode 100644 index 0000000000000000000000000000000000000000..d7973c4ac216d6e3d84be95306d2e96002158af4 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_8.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_8" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that May 18, 2026, computed as five days from May 13, 2026, is the sole operative filing deadline for the Cal. Health & Safety Code § 1352(c) (2026) notice arising from Dr. Connors' appointment." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_9.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_9.toml new file mode 100644 index 0000000000000000000000000000000000000000..2d73676cd702298d08be24a5b9f89dcf4e4fb124 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/raw_correctness/criterion_9.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_9" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that as of May 15, 2026, the Cal. Health & Safety Code § 1352(c) (2026) obligation arising from Dr. Connors' appointment is not yet overdue." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/test.sh b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..66a509a7bcdbe412851f3a012a5ba7b16cf0925b --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-2/tests/test.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +set -euo pipefail + +mkdir -p /logs/artifacts /logs/verifier/raw + +python3 - <<'PYEOF' +import json +import shutil +from pathlib import Path + + +def has_text(path: Path) -> bool: + return path.exists() and path.is_file() and bool(path.read_text(errors="replace").strip()) + + +def fallback_paths(answer_path: Path) -> list[Path]: + paths = [] + try: + relative = answer_path.relative_to("/app") + paths.append(Path("/app/app") / relative) + except ValueError: + pass + return [path for path in paths if path != answer_path] + + +config = json.loads(Path("/tests/fixtures/config.json").read_text()) +answer_path = Path(config["answer_path"]) +artifact_answer = Path("/logs/artifacts/answer.md") +artifact_answer.parent.mkdir(parents=True, exist_ok=True) +if has_text(answer_path): + shutil.copyfile(answer_path, artifact_answer) +else: + for candidate in fallback_paths(answer_path): + if has_text(candidate): + shutil.copyfile(candidate, artifact_answer) + break + else: + artifact_answer.write_text("") + +# Harbor collects /logs/artifacts when the agent step ends, which is before this +# script runs, so the copy above never reaches the uploaded artifacts. /logs/verifier +# is uploaded after the verifier phase, so persist the graded answer there too. +verifier_answer = Path("/logs/verifier/answer.md") +verifier_answer.parent.mkdir(parents=True, exist_ok=True) +shutil.copyfile(artifact_answer, verifier_answer) +PYEOF + +uv run --no-project --with 'harbor-rewardkit[all]==0.2.0' python /tests/m1_rewardkit_accounting.py /tests/raw_correctness \ + --workspace /app \ + --output /logs/verifier/raw/reward.json \ + --max-concurrent-llm "${MAX_CONCURRENT_LLM:-4}" \ + --max-concurrent-agent "${M1_MAX_CONCURRENT_AGENT:-1}" + +python /tests/normalize_reward.py \ + --raw-details /logs/verifier/raw/reward-details.json \ + --rubric /tests/fixtures/rubric.json \ + --reward-out /logs/verifier/reward.json \ + --details-out /logs/verifier/reward-details.json diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/instruction.md b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..066c61fb46f75534ba2c9dbd330c63ef55762c1c --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/instruction.md @@ -0,0 +1,40 @@ +# Interim CMO Appointment: Governance and Compliance Analysis — Assignment 3 + +You are a senior legal analyst operating autonomously. You are completing a multi-step legal reasoning task. Follow the role, factual record, instructions, and deliverable requirements provided in the Task and each Assignment. + +Each Assignment may require a different legal deliverable. Follow the requirements specific to that Assignment. + +## Word limits for court briefs + +- A brief in support of or in response to a motion may not exceed **8,750 words**. +- A reply brief may not exceed **3,500 words**. +- For a motion for reconsideration, a brief in support of or in response to the motion may not exceed **3,500 words**, and a reply brief may not exceed **1,750 words**. +- If an Assignment specifies a stricter word limit, follow the stricter limit. + +These word limits do not apply to legal memoranda or other non-court-filing deliverables unless the Assignment expressly provides otherwise. + +Complete the task end-to-end without asking for confirmation, permission, or clarification. + +Use the uploaded matter documents in `/app/attachments/` as your primary case file. You also have internet access via OpenCode's `websearch` tool; use it to research any statutes, regulations, cases, administrative guidance, or secondary authorities that are not supplied as attachments. Cite any authority you rely on in the format requested by the prompt. + +For document inspection: +- PDF: `pdftotext /app/attachments/.pdf -` +- DOCX: `pandoc /app/attachments/.docx -t markdown` +- XLSX/CSV: use Python with `openpyxl` or `pandas` +- If extraction is unreliable, inspect the raw file with Python libraries or convert/render the relevant pages. + +Write the final complete legal deliverable for this assignment to `/app/response3.md`. The verifier reads only that file. + +This is a follow-on assignment. The documents from the previous assignment(s) remain available in `/app/attachments/`, and your prior deliverable `/app/response2.md` is also on disk. Build on that analysis as the prompt directs. + +## Attachments + +_No new documents for this assignment. The documents from the previous assignment(s) remain available in `/app/attachments/`._ + +## Prompt + +Following the same instructions and your analysis from Steps 1 and 2, incorporate the following into the memorandum: + +The Chief Executive Officer has reviewed your analysis and asks you to prepare the corrective governance documents for the Board. Identify the corporate instruments necessary to place Dr. Connors' appointment on a sound footing and correct any defects you have identified in IHP's governance record, specifying for each the form of instrument, the adoption mechanism, the operative provisions, and the effective date. + +The same uploaded documents from Step 1 constitute the complete and exclusive universe of materials for this assignment. All legal analysis must be based solely on the law and guidance as it exists on May 15, 2026. Do not account for any legislative changes, regulatory updates, or Department of Managed Health Care (DMHC) guidance issued after that date. All citations in the memorandum analysis must reference the uploaded document by its exact name as listed in Step 1, followed by the specific page and section. diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/solution/solve.sh b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7710414a6da6d0ad740717c8c85a9af850d5da33 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/solution/solve.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# No oracle solution ships with LegalReasonBench. The verifier grades the +# agent's own legal deliverable for this assignment against the rubric. +echo "no oracle solution" diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/fixtures/config.json b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/fixtures/config.json new file mode 100644 index 0000000000000000000000000000000000000000..5631435242eb4fe9ede77c95936a184acdc286ce --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/fixtures/config.json @@ -0,0 +1,173 @@ +{ + "task_id": "lrb-interim-cmo-appointment-governance", + "title": "Interim CMO Appointment: Governance and Compliance Analysis", + "domain": "", + "matter": "", + "judge": { + "max_concurrent_llm": 12, + "mode": "panel", + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ], + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + "step_index": 3, + "step_name": "assignment-3", + "step_title": "", + "prompt": "Following the same instructions and your analysis from Steps 1 and 2, incorporate the following into the memorandum:\n\nThe Chief Executive Officer has reviewed your analysis and asks you to prepare the corrective governance documents for the Board. Identify the corporate instruments necessary to place Dr. Connors' appointment on a sound footing and correct any defects you have identified in IHP's governance record, specifying for each the form of instrument, the adoption mechanism, the operative provisions, and the effective date. \n\nThe same uploaded documents from Step 1 constitute the complete and exclusive universe of materials for this assignment. All legal analysis must be based solely on the law and guidance as it exists on May 15, 2026. Do not account for any legislative changes, regulatory updates, or Department of Managed Health Care (DMHC) guidance issued after that date. All citations in the memorandum analysis must reference the uploaded document by its exact name as listed in Step 1, followed by the specific page and section.", + "attachments": [], + "rubric": [ + { + "name": "criterion_1", + "description": "States that the corrective instrument ratifies Dr. Connors' appointment prospectively.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall be effective upon adoption of the ratifying resolution\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Draft the corporate instrument or instruments necessary to place Dr. Connors' appointment on a sound footing and correct any defects you have identified in IHP's governance record, in final form ready for adoption.\" A corrective instrument that ratifies prospectively, effective upon adoption, is the only instrument capable of placing the appointment on a sound footing under Section 5.9. An instrument that proposes to ratify retroactively repeats the original defect.", + "metadata": { + "irac_section": "Conclusion" + }, + "score": 8.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_2", + "description": "States that the corrective instrument supersedes the \"effective as of May 7, 2026\" language in Resolution 2026-14.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall be effective upon adoption of the ratifying resolution and shall not operate retroactively to cure any deficiency in authorization for the period preceding adoption\"); IHP_Board_Resolution_2026-14.docx, p. 1, NOW THEREFORE clause (\"hereby ratifies and approves the appointment of Elena Connors, M.D., as Interim Chief Medical Officer of the Corporation, effective as of May 7, 2026\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Draft the corporate instrument or instruments necessary to place Dr. Connors' appointment on a sound footing and correct any defects you have identified in IHP's governance record, in final form ready for adoption.\" Resolution 2026-14's retroactivity recital is the specific defect identified in Step 1. A corrective instrument that does not address that recital leaves the defect in the governance record.", + "metadata": { + "irac_section": "Application" + }, + "score": 12.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_3", + "description": "States that the corrective instrument accurately characterizes the period from May 7 to May 13, 2026 as a period during which the appointment lacked valid Board authorization.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall be effective upon adoption of the ratifying resolution and shall not operate retroactively to cure any deficiency in authorization for the period preceding adoption\"); IHP_CMO_Interim_Appointment_Letter_Connors.docx, p. 1, opening paragraph (\"effective immediately, you are appointed to serve as Interim Chief Medical Officer of Imperium Health Plan, Inc.\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Draft the corporate instrument or instruments necessary to place Dr. Connors' appointment on a sound footing and correct any defects you have identified in IHP's governance record, in final form ready for adoption.\" An accurate characterization of the May 7th to May 13th period is required for the governance record to be complete and defensible. An instrument whose recitals treat that period as authorized is internally inconsistent with a prospective ratification posture.", + "metadata": { + "irac_section": "Application" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_4", + "description": "States that the corrective instrument is structured for adoption by unanimous written consent.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.10 (\"Any action required or permitted to be taken by the Board of Directors at a meeting may be taken without a meeting if all members of the Board individually or collectively consent in writing to that action\"); IHP_Board_Meeting_Calendar_2026.docx, p. 1, 2026 Regular Meeting Schedule (next regular meeting listed as June 10, 2026).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Any instrument you draft must be capable of valid adoption under IHP's governing documents within the time your Step 2 analysis requires.\" The filing deadline is May 18, 2026. The next regular Board meeting is June 10, 2026, which falls after that deadline. Unanimous written consent under Section 5.10 is the only adoption vehicle available within the required timeframe.", + "metadata": { + "irac_section": "Application" + }, + "score": 8.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_5", + "description": "States that the drafted instrument directs the Cal. Health & Safety Code \u00a7 1352(c) (2026) filing for Dr. Connors' appointment by May 18, 2026.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 3, Cal. Health & Safety Code \u00a7 1352(c) (2026) (\"A plan shall, within five days, give written notice to the director in the form as by rule may be prescribed, of a change in the officers\"); IHP_Board_Resolution_2026-14.docx, p. 2, Record of Adoption (\"The foregoing Resolution was duly adopted at the regular meeting of the Board of Directors of Imperium Health Plan, Inc. held on May 13, 2026, at which a quorum was present and acting throughout\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"Draft the corporate instrument or instruments necessary to place Dr. Connors' appointment on a sound footing and correct any defects you have identified in IHP's governance record, in final form ready for adoption.\" A corrective instrument that does not direct the filing obligation is incomplete. The instrument must connect the governance correction to the regulatory action required within the same timeframe, keyed to the May 13th trigger and May 18th deadline established in Step 2.", + "metadata": { + "irac_section": "Application" + }, + "score": 15.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_6", + "description": "Identifies that the drafted instrument includes a recitals block setting out the factual governance background.", + "source": "IHP_Board_Resolution_2026-14.docx, p. 1, WHEREAS clauses (\"WHEREAS, by letter dated May 7, 2026, Mary T. Lee, Chief Executive Officer of Imperium Health Plan, Inc., appointed Elena Connors, M.D., to serve as Interim Chief Medical Officer of the Corporation, effective immediately\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"Use the drafting conventions of formal corporate instruments.\" A recitals block is a standard structural element of a formal corporate resolution. It establishes the factual basis for the operative clauses and is required for the instrument to satisfy formal corporate drafting conventions.", + "metadata": { + "irac_section": "Issue" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_7", + "description": "Identifies that the drafted instrument includes an adoption block reflecting the mechanism of adoption.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.10 (\"Any action required or permitted to be taken by the Board of Directors at a meeting may be taken without a meeting if all members of the Board individually or collectively consent in writing to that action. Such unanimous written consent shall have the same force and effect as a unanimous vote at a duly held meeting\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"Use the drafting conventions of formal corporate instruments.\" An adoption or consent block is required to reflect the mechanism by which the instrument is validly adopted. For an instrument adopted by unanimous written consent, the consent block must reflect the Section 5.10 procedure.", + "metadata": { + "irac_section": "Issue" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_8", + "description": "Identifies that the drafted instrument includes an officer authorization clause directing officers to take actions necessary to implement it.", + "source": "IHP_Board_Resolution_2026-14.docx, p. 1, RESOLVED FURTHER clause (\"the officers of the Corporation are hereby authorized and directed to take all actions and execute all instruments and documents as may be necessary or appropriate to implement and carry out the intent and purposes of this Resolution\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"Use the drafting conventions of formal corporate instruments.\" An officer authorization clause is a standard operative element of a formal corporate resolution. Its presence authorizes the plan's officers to take the steps required to implement the Board's action, including submission of the regulatory filing.", + "metadata": { + "irac_section": "Issue" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_9", + "description": "States that the corrective instrument is capable of valid adoption under the Bylaws.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall require adoption of a resolution by the Board of Directors in accordance with the procedures applicable to the authorization of the act being ratified\"); IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.10 (\"Any action required or permitted to be taken by the Board of Directors at a meeting may be taken without a meeting if all members of the Board individually or collectively consent in writing to that action\"); IHP_Board_Meeting_Calendar_2026.docx, p. 1, 2026 Regular Meeting Schedule (next regular meeting listed as June 10, 2026).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Any instrument you draft must be capable of valid adoption under IHP's governing documents within the time your Step 2 analysis requires.\" Section 5.9 requires ratification to follow the procedures applicable to the authorization of the act being ratified. Section 5.10 provides the written consent procedure that satisfies that requirement within the May 18th deadline.", + "metadata": { + "irac_section": "Rule" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_10", + "description": "Mentions language in the drafted instrument designating May 7, 2026 as the effective date of Dr. Connors' appointment as Interim Chief Medical Officer.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall be effective upon adoption of the ratifying resolution\"); IHP_Board_Resolution_2026-14.docx, p. 1, NOW THEREFORE clause (\"hereby ratifies and approves the appointment of Elena Connors, M.D., as Interim Chief Medical Officer of the Corporation, effective as of May 7, 2026\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"Draft the corporate instrument or instruments necessary to place Dr. Connors' appointment on a sound footing and correct any defects you have identified in IHP's governance record, in final form ready for adoption.\" Section 5.9 provides that ratification is effective upon adoption. An instrument that includes a retroactive effective date repeats the defect identified in Resolution 2026-14 and does not place the appointment on a sound footing.", + "metadata": { + "irac_section": "Conclusion" + }, + "score": -20.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_11", + "description": "Mentions that the Cal. Health & Safety Code \u00a7 1352(c) (2026) personnel notice requires resubmission of organizational exhibits.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 4, Cal. Code Regs. tit. 28, \u00a7 1300.52.2(a) (2026) (\"There is an addition or deletion of a director, trustee, principal officer, general partner, general manager or principal management persons, or persons occupying similar positions or performing similar functions, or a substantial and material change in the duties of any such person\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"Provide a recommended course of action addressing each obligation identified, including timing and submission mechanics.\" Cal. Code Regs. tit. 28, \u00a7 1300.52.2(a) (2026) governs personnel change filings. A routine officer-level personnel change does not affect the organizational structure of the plan. Organizational exhibits are not required to be resubmitted as part of a routine personnel notice. A model that recommends resubmission has conflated a personnel change with an organizational structure change.", + "metadata": { + "irac_section": "Application" + }, + "score": -10.0, + "polarity": "negative", + "raw_weight": 1.0 + } + ], + "answer_path": "/app/response3.md", + "answer_relative_path": "response3.md", + "is_followon": true, + "prev_answer_path": "/app/response2.md" +} diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/fixtures/rubric.json b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/fixtures/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..2d1b96e5d4d6c540b395210889b34d2930904cf3 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/fixtures/rubric.json @@ -0,0 +1,136 @@ +{ + "criteria": [ + { + "name": "criterion_1", + "description": "States that the corrective instrument ratifies Dr. Connors' appointment prospectively.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall be effective upon adoption of the ratifying resolution\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Draft the corporate instrument or instruments necessary to place Dr. Connors' appointment on a sound footing and correct any defects you have identified in IHP's governance record, in final form ready for adoption.\" A corrective instrument that ratifies prospectively, effective upon adoption, is the only instrument capable of placing the appointment on a sound footing under Section 5.9. An instrument that proposes to ratify retroactively repeats the original defect.", + "metadata": { + "irac_section": "Conclusion" + }, + "score": 8.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_2", + "description": "States that the corrective instrument supersedes the \"effective as of May 7, 2026\" language in Resolution 2026-14.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall be effective upon adoption of the ratifying resolution and shall not operate retroactively to cure any deficiency in authorization for the period preceding adoption\"); IHP_Board_Resolution_2026-14.docx, p. 1, NOW THEREFORE clause (\"hereby ratifies and approves the appointment of Elena Connors, M.D., as Interim Chief Medical Officer of the Corporation, effective as of May 7, 2026\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Draft the corporate instrument or instruments necessary to place Dr. Connors' appointment on a sound footing and correct any defects you have identified in IHP's governance record, in final form ready for adoption.\" Resolution 2026-14's retroactivity recital is the specific defect identified in Step 1. A corrective instrument that does not address that recital leaves the defect in the governance record.", + "metadata": { + "irac_section": "Application" + }, + "score": 12.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_3", + "description": "States that the corrective instrument accurately characterizes the period from May 7 to May 13, 2026 as a period during which the appointment lacked valid Board authorization.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall be effective upon adoption of the ratifying resolution and shall not operate retroactively to cure any deficiency in authorization for the period preceding adoption\"); IHP_CMO_Interim_Appointment_Letter_Connors.docx, p. 1, opening paragraph (\"effective immediately, you are appointed to serve as Interim Chief Medical Officer of Imperium Health Plan, Inc.\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Draft the corporate instrument or instruments necessary to place Dr. Connors' appointment on a sound footing and correct any defects you have identified in IHP's governance record, in final form ready for adoption.\" An accurate characterization of the May 7th to May 13th period is required for the governance record to be complete and defensible. An instrument whose recitals treat that period as authorized is internally inconsistent with a prospective ratification posture.", + "metadata": { + "irac_section": "Application" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_4", + "description": "States that the corrective instrument is structured for adoption by unanimous written consent.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.10 (\"Any action required or permitted to be taken by the Board of Directors at a meeting may be taken without a meeting if all members of the Board individually or collectively consent in writing to that action\"); IHP_Board_Meeting_Calendar_2026.docx, p. 1, 2026 Regular Meeting Schedule (next regular meeting listed as June 10, 2026).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Any instrument you draft must be capable of valid adoption under IHP's governing documents within the time your Step 2 analysis requires.\" The filing deadline is May 18, 2026. The next regular Board meeting is June 10, 2026, which falls after that deadline. Unanimous written consent under Section 5.10 is the only adoption vehicle available within the required timeframe.", + "metadata": { + "irac_section": "Application" + }, + "score": 8.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_5", + "description": "States that the drafted instrument directs the Cal. Health & Safety Code \u00a7 1352(c) (2026) filing for Dr. Connors' appointment by May 18, 2026.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 3, Cal. Health & Safety Code \u00a7 1352(c) (2026) (\"A plan shall, within five days, give written notice to the director in the form as by rule may be prescribed, of a change in the officers\"); IHP_Board_Resolution_2026-14.docx, p. 2, Record of Adoption (\"The foregoing Resolution was duly adopted at the regular meeting of the Board of Directors of Imperium Health Plan, Inc. held on May 13, 2026, at which a quorum was present and acting throughout\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"Draft the corporate instrument or instruments necessary to place Dr. Connors' appointment on a sound footing and correct any defects you have identified in IHP's governance record, in final form ready for adoption.\" A corrective instrument that does not direct the filing obligation is incomplete. The instrument must connect the governance correction to the regulatory action required within the same timeframe, keyed to the May 13th trigger and May 18th deadline established in Step 2.", + "metadata": { + "irac_section": "Application" + }, + "score": 15.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_6", + "description": "Identifies that the drafted instrument includes a recitals block setting out the factual governance background.", + "source": "IHP_Board_Resolution_2026-14.docx, p. 1, WHEREAS clauses (\"WHEREAS, by letter dated May 7, 2026, Mary T. Lee, Chief Executive Officer of Imperium Health Plan, Inc., appointed Elena Connors, M.D., to serve as Interim Chief Medical Officer of the Corporation, effective immediately\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"Use the drafting conventions of formal corporate instruments.\" A recitals block is a standard structural element of a formal corporate resolution. It establishes the factual basis for the operative clauses and is required for the instrument to satisfy formal corporate drafting conventions.", + "metadata": { + "irac_section": "Issue" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_7", + "description": "Identifies that the drafted instrument includes an adoption block reflecting the mechanism of adoption.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.10 (\"Any action required or permitted to be taken by the Board of Directors at a meeting may be taken without a meeting if all members of the Board individually or collectively consent in writing to that action. Such unanimous written consent shall have the same force and effect as a unanimous vote at a duly held meeting\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"Use the drafting conventions of formal corporate instruments.\" An adoption or consent block is required to reflect the mechanism by which the instrument is validly adopted. For an instrument adopted by unanimous written consent, the consent block must reflect the Section 5.10 procedure.", + "metadata": { + "irac_section": "Issue" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_8", + "description": "Identifies that the drafted instrument includes an officer authorization clause directing officers to take actions necessary to implement it.", + "source": "IHP_Board_Resolution_2026-14.docx, p. 1, RESOLVED FURTHER clause (\"the officers of the Corporation are hereby authorized and directed to take all actions and execute all instruments and documents as may be necessary or appropriate to implement and carry out the intent and purposes of this Resolution\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"Use the drafting conventions of formal corporate instruments.\" An officer authorization clause is a standard operative element of a formal corporate resolution. Its presence authorizes the plan's officers to take the steps required to implement the Board's action, including submission of the regulatory filing.", + "metadata": { + "irac_section": "Issue" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_9", + "description": "States that the corrective instrument is capable of valid adoption under the Bylaws.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall require adoption of a resolution by the Board of Directors in accordance with the procedures applicable to the authorization of the act being ratified\"); IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.10 (\"Any action required or permitted to be taken by the Board of Directors at a meeting may be taken without a meeting if all members of the Board individually or collectively consent in writing to that action\"); IHP_Board_Meeting_Calendar_2026.docx, p. 1, 2026 Regular Meeting Schedule (next regular meeting listed as June 10, 2026).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Any instrument you draft must be capable of valid adoption under IHP's governing documents within the time your Step 2 analysis requires.\" Section 5.9 requires ratification to follow the procedures applicable to the authorization of the act being ratified. Section 5.10 provides the written consent procedure that satisfies that requirement within the May 18th deadline.", + "metadata": { + "irac_section": "Rule" + }, + "score": 2.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_10", + "description": "Mentions language in the drafted instrument designating May 7, 2026 as the effective date of Dr. Connors' appointment as Interim Chief Medical Officer.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall be effective upon adoption of the ratifying resolution\"); IHP_Board_Resolution_2026-14.docx, p. 1, NOW THEREFORE clause (\"hereby ratifies and approves the appointment of Elena Connors, M.D., as Interim Chief Medical Officer of the Corporation, effective as of May 7, 2026\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"Draft the corporate instrument or instruments necessary to place Dr. Connors' appointment on a sound footing and correct any defects you have identified in IHP's governance record, in final form ready for adoption.\" Section 5.9 provides that ratification is effective upon adoption. An instrument that includes a retroactive effective date repeats the defect identified in Resolution 2026-14 and does not place the appointment on a sound footing.", + "metadata": { + "irac_section": "Conclusion" + }, + "score": -20.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_11", + "description": "Mentions that the Cal. Health & Safety Code \u00a7 1352(c) (2026) personnel notice requires resubmission of organizational exhibits.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 4, Cal. Code Regs. tit. 28, \u00a7 1300.52.2(a) (2026) (\"There is an addition or deletion of a director, trustee, principal officer, general partner, general manager or principal management persons, or persons occupying similar positions or performing similar functions, or a substantial and material change in the duties of any such person\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"Provide a recommended course of action addressing each obligation identified, including timing and submission mechanics.\" Cal. Code Regs. tit. 28, \u00a7 1300.52.2(a) (2026) governs personnel change filings. A routine officer-level personnel change does not affect the organizational structure of the plan. Organizational exhibits are not required to be resubmitted as part of a routine personnel notice. A model that recommends resubmission has conflated a personnel change with an organizational structure change.", + "metadata": { + "irac_section": "Application" + }, + "score": -10.0, + "polarity": "negative", + "raw_weight": 1.0 + } + ] +} diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/m1_judge_panel.json b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/m1_judge_panel.json new file mode 100644 index 0000000000000000000000000000000000000000..a8041f6781a899f9083fe4a1a95f51bc78d35601 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/m1_judge_panel.json @@ -0,0 +1,21 @@ +{ + "mode": "panel", + "max_concurrent_llm": 12, + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ] +} diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/m1_rewardkit_accounting.py b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/m1_rewardkit_accounting.py new file mode 100644 index 0000000000000000000000000000000000000000..406dc5e7c675b222d94514e71bf5fad6ae141d8f --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/m1_rewardkit_accounting.py @@ -0,0 +1,490 @@ +import asyncio +import json +import math +import os +from pathlib import Path +import random +import sys +import time + +class JudgeReceiptError(OSError): + pass +_LLM_ROUTES = frozenset({'vertex', 'anthropic fallback', 'aistudio', 'direct'}) +_LLM_ROUTE_HEADERS = ('x-m1-llm-route', 'llm_provider-x-m1-llm-route') + +def _canonical_llm_route(value): + return value if isinstance(value, str) and value in _LLM_ROUTES else None + +def _llm_route_from_headers(headers): + if not isinstance(headers, dict): + return None + folded = {str(key).lower(): value for key, value in headers.items()} + for name in _LLM_ROUTE_HEADERS: + route = _canonical_llm_route(folded.get(name)) + if route is not None: + return route + return None + +def _llm_route_from_response(response): + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + route = _llm_route_from_headers(headers) + if route is not None: + return route + return _llm_route_from_headers(getattr(response, 'headers', None)) + +def _token_field_status(values, key): + if not isinstance(values, dict) or key not in values: + return 'missing' + value = values[key] + if value is None: + return 'null' + return 'valid' if type(value) is int and value >= 0 else 'invalid' + +def _gemini_capture(kwargs, model): + if not model.startswith('gemini/') or kwargs.get('stream') or kwargs.get('tools') or kwargs.get('functions'): + return (kwargs, None) + from litellm.integrations.custom_logger import CustomLogger + from urllib.parse import urlsplit + + class Capture(CustomLogger): + evidence = None + prompt_status = 'not_observed' + llm_route = None + + def log_post_api_call(self, kwargs, response_obj, start_time, end_time): + self.evidence = None + self.prompt_status = 'not_observed' + try: + params = kwargs.get('litellm_params') or {} + route = urlsplit(params.get('api_base') or '') + bare = model.removeprefix('gemini/') + gemini = params.get('custom_llm_provider') == 'gemini' + ai_studio = gemini and route.hostname == 'generativelanguage.googleapis.com' and (route.path in {'/' + version + '/models/' + bare + ':generateContent' for version in ('v1alpha', 'v1beta')}) + broker = urlsplit(os.environ.get('GEMINI_API_BASE') or '') + brokered = gemini and bool(broker.netloc) and (route.netloc == broker.netloc) and (broker.path.rstrip('/').rsplit('/', 1)[-1] in ('v1alpha', 'v1beta')) and (route.path == broker.path.rstrip('/') + '/models/' + bare + ':generateContent') + vertex = params.get('custom_llm_provider') == 'vertex_ai' and route.hostname == 'aiplatform.googleapis.com' and route.path.startswith('/v1/projects/') and route.path.endswith('/locations/global/publishers/google/models/' + bare + ':generateContent') + if route.scheme != 'https' or not (ai_studio or brokered or vertex) or kwargs.get('stream'): + return + self.llm_route = 'vertex' if vertex else 'aistudio' if ai_studio else None + raw = kwargs.get('original_response') + raw = json.loads(raw) if isinstance(raw, str) else raw + if not isinstance(raw, dict): + return + candidates = raw.get('candidates') + if not isinstance(candidates, list) or not candidates or any((not isinstance(c, dict) or not c.get('finishReason') for c in candidates)) or (not isinstance(raw.get('modelVersion'), str)) or (not raw['modelVersion']): + return + usage = raw.get('usageMetadata') + self.prompt_status = _token_field_status(usage, 'promptTokenCount') + if not isinstance(usage, dict): + return + fields = ('promptTokenCount', 'candidatesTokenCount', 'thoughtsTokenCount', 'cachedContentTokenCount', 'totalTokenCount', 'toolUsePromptTokenCount') + counts = {key: usage.get(key, 0) for key in fields} + if not {'promptTokenCount', 'totalTokenCount'} <= usage.keys() or any((type(n) is not int or n < 0 for n in counts.values())) or counts['toolUsePromptTokenCount'] != 0 or (counts['cachedContentTokenCount'] > counts['promptTokenCount']) or (counts['totalTokenCount'] != counts['promptTokenCount'] + counts['candidatesTokenCount'] + counts['thoughtsTokenCount']): + return + self.evidence = {'protocol': 'gemini-generate-content-' + ('vertex-v1' if vertex else route.path.split('/')[-3]), 'model_version': raw['modelVersion'], 'usage_metadata': {key: usage[key] for key in fields if key in usage}, 'defaulted_fields': [key for key in fields if key not in usage]} + except (TypeError, ValueError, AttributeError): + return + capture = Capture() + return ({**kwargs, 'callbacks': [*(kwargs.get('callbacks') or []), capture]}, capture) + +def _record_judge_usage(response, model: str, *, target: Path | None=None, native_usage: dict | None=None, native_prompt_status: str | None=None, llm_route: str | None=None) -> None: + import fcntl + from datetime import datetime, timezone + data = response.model_dump() if hasattr(response, 'model_dump') else response + usage = data.get('usage') if isinstance(data, dict) else None + granularity = data.get('usage_granularity') if isinstance(data, dict) else None + if not isinstance(usage, dict): + usage = {} + granularity = 'missing_provider_receipt' + prompt, completion = (usage.get('prompt_tokens'), usage.get('completion_tokens')) + native_fresh = usage.get('input_uncached_tokens') + prompt = prompt if type(prompt) is int and prompt >= 0 else None + native_fresh = native_fresh if type(native_fresh) is int and native_fresh >= 0 else None + if type(completion) is not int or completion < 0 or (prompt is None and native_fresh is None): + completion = completion if type(completion) is int and completion >= 0 else 0 + granularity = granularity or 'invalid_provider_receipt' + details = usage.get('prompt_tokens_details') + if details is not None and (not isinstance(details, dict)): + granularity = 'invalid_provider_receipt' + details = details if isinstance(details, dict) else {} + cached = details.get('cached_tokens') + if native_usage is not None: + native = native_usage['usage_metadata'] + native_output = native.get('candidatesTokenCount', 0) + native.get('thoughtsTokenCount', 0) + if prompt == native['promptTokenCount'] and completion == native_output: + cached = native.get('cachedContentTokenCount', 0) + else: + native_usage = None + written = next((value for value in (usage.get('input_cache_write_tokens'), usage.get('cache_creation_input_tokens'), details.get('cache_creation_tokens'), details.get('cache_write_tokens')) if value is not None), None) + invalid = any((value is not None and (type(value) is not int or value < 0) for value in (cached, written))) + cached = cached if type(cached) is int and cached >= 0 else None + written = written if type(written) is int and written >= 0 else None + fresh = native_fresh + if fresh is None and prompt is not None and (cached is not None) and (written is not None): + fresh = prompt - cached - written + if fresh is not None and (fresh < 0 or (prompt is not None and cached is not None and (written is not None) and (fresh + cached + written != prompt))): + invalid, fresh = (True, None) + provider, _, slug = model.partition('/') + event: dict = {'type': 'step_finish', 'part': {'providerID': provider if slug else 'openai', 'modelID': slug or model, 'tokens': {'input': fresh, 'output': completion, 'cache': {'read': cached, 'write': written}}}} + field_status = {'prompt_tokens': _token_field_status(usage, 'prompt_tokens'), 'completion_tokens': _token_field_status(usage, 'completion_tokens'), 'input_uncached_tokens': _token_field_status(usage, 'input_uncached_tokens')} + field_status['native_prompt_token_count'] = native_prompt_status if native_prompt_status in {'missing', 'null', 'invalid', 'valid', 'not_observed'} else 'unsupported' + part: dict = event['part'] + part['usage_field_status'] = field_status + if native_usage is not None: + event['part']['native_usage'] = native_usage + event['part']['token_categories_provenance'] = 'explicit_presence_v1' + if fresh is None and prompt is not None: + event['part']['prompt_tokens_inclusive'] = prompt + if invalid or any((value is None for value in (fresh, cached, written))): + granularity = granularity if granularity not in (None, 'request') else 'invalid_provider_receipt' if invalid else 'incomplete_token_categories' + if granularity: + event['part']['usage_granularity'] = granularity + if provider == 'openrouter': + cost = usage.get('cost') + if cost is None: + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + if isinstance(headers, dict): + cost = headers.get('llm_provider-x-litellm-response-cost') + if isinstance(cost, (int, float)) and (not isinstance(cost, bool)) and math.isfinite(cost) and (cost >= 0): + event['part']['cost'] = cost + data = data if isinstance(data, dict) else {} + if isinstance(data.get('id'), str) and data['id']: + event['part']['provider_request_id'] = data['id'] + for key in ('service_tier', 'cache_ttl'): + if data.get(key): + event['part'][key] = data[key] + route = _llm_route_from_response(response) or _canonical_llm_route(llm_route) + if route is not None: + event['part']['llm_route'] = route + created = data.get('created') + stamp = datetime.now(timezone.utc) + try: + if isinstance(created, str): + parsed = datetime.fromisoformat(created.replace('Z', '+00:00')) + if parsed.tzinfo is not None: + stamp = parsed + elif isinstance(created, (int, float)) and (not isinstance(created, bool)) and math.isfinite(created): + stamp = datetime.fromtimestamp(created, timezone.utc) + except (ValueError, OverflowError, OSError): + pass + pair = json.dumps({'type': 'step_start', 'timestamp': stamp.isoformat()}) + '\n' + pair += json.dumps(event) + '\n' + try: + receipt_path = target or Path(os.environ.get('M1_JUDGE_USAGE_PATH', '/logs/verifier/judge-trajectory.jsonl')) + receipt_path.parent.mkdir(parents=True, exist_ok=True) + with receipt_path.open('a') as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + handle.write(pair) + handle.flush() + os.fsync(handle.fileno()) + except OSError as exc: + if target is not None: + raise JudgeReceiptError(f'judge receipt write failed: {exc}') from exc + print(f'judge accounting: write failed ({type(exc).__name__})', file=sys.stderr) + +def openrouter_judge_pins() -> dict[str, dict]: + raw = os.environ.get('M1_OPENROUTER_JUDGE_PROVIDER_PINS', '').strip() + if not raw: + return {} + try: + pins = json.loads(raw) + except json.JSONDecodeError: + print('judge provider pins: invalid JSON in M1_OPENROUTER_JUDGE_PROVIDER_PINS', file=sys.stderr) + return {} + return {model: pin for model, pin in pins.items() if isinstance(pin, dict) and pin.get('order')} if isinstance(pins, dict) else {} + +def apply_judge_provider_pin(kwargs: dict, pins: dict[str, dict]) -> dict: + model = kwargs.get('model') + pin = pins.get(model) if isinstance(model, str) else None + if pin is None: + return kwargs + extra_body = dict(kwargs.get('extra_body') or {}) + provider = dict(extra_body.get('provider') or {}) + provider['order'] = list(pin['order']) + if pin.get('allow_fallbacks') is False: + provider['allow_fallbacks'] = False + if pin.get('zdr'): + provider['zdr'] = True + extra_body['provider'] = provider + return {**kwargs, 'extra_body': extra_body} +_TRANSIENT_ERROR_NAMES = ('RateLimitError', 'ServiceUnavailableError', 'InternalServerError', 'BadGatewayError', 'APIConnectionError') +_RETRYABLE_STATUS_CODES = frozenset({408, 409, 425, 429, 500, 502, 503, 504}) +_AUTH_ERROR_NAMES = ('AuthenticationError', 'PermissionDeniedError') +_AUTH_STATUS_CODES = frozenset({401, 403}) +_AUTH_RETRIES = 4 +_DEFAULT_TRANSIENT_RETRIES = 6 +_MAX_TRANSIENT_RETRIES = 20 +_MAX_RETRY_DELAY_SECONDS = 60.0 +_DEFAULT_EMPTY_RESPONSE_RETRIES = 3 +_DEFAULT_RETRY_BUDGET_SECONDS = 900.0 +_MAX_RETRY_BUDGET_SECONDS = 86400.0 + +def transient_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_TRANSIENT_RETRIES', '').strip() + if not raw: + return _DEFAULT_TRANSIENT_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_TRANSIENT_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_TRANSIENT_RETRIES + +def empty_response_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_EMPTY_RESPONSE_RETRIES', '').strip() + if not raw: + return _DEFAULT_EMPTY_RESPONSE_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_EMPTY_RESPONSE_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_EMPTY_RESPONSE_RETRIES + +def retry_budget_seconds() -> float: + raw = os.environ.get('M1_JUDGE_RETRY_BUDGET_SECONDS', '').strip() + if not raw: + return _DEFAULT_RETRY_BUDGET_SECONDS + try: + value = float(raw) + except ValueError: + value = math.nan + if not math.isfinite(value) or value < 0: + print('judge retries: invalid M1_JUDGE_RETRY_BUDGET_SECONDS, using the default', file=sys.stderr) + return _DEFAULT_RETRY_BUDGET_SECONDS + return min(value, _MAX_RETRY_BUDGET_SECONDS) + +def _within_budget(deadline: float, delay: float, model) -> bool: + remaining = deadline - time.monotonic() + if delay <= remaining: + return True + print(f'judge call retry budget spent: {model} would wait {delay:.1f}s with {max(remaining, 0.0):.1f}s left of M1_JUDGE_RETRY_BUDGET_SECONDS, failing now', file=sys.stderr) + return False + +def is_empty_verdict(response) -> bool: + data = response.model_dump() if hasattr(response, 'model_dump') else response + if not isinstance(data, dict): + return False + choices = data.get('choices') + if not isinstance(choices, list) or not choices: + return True + first = choices[0] + message = first.get('message') if isinstance(first, dict) else None + if not isinstance(message, dict): + return True + if message.get('tool_calls') or message.get('function_call'): + return False + content = message.get('content') + if isinstance(content, list): + content = ''.join((part.get('text') or '' for part in content if isinstance(part, dict))) + return not (isinstance(content, str) and content.strip()) + +def _matches(exc: BaseException, litellm, names: tuple[str, ...], statuses: frozenset[int]) -> bool: + classes = tuple((cls for cls in (getattr(litellm, name, None) for name in names) if isinstance(cls, type))) + if classes and isinstance(exc, classes): + return True + status = getattr(exc, 'status_code', None) + return type(status) is int and status in statuses + +def is_transient_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _TRANSIENT_ERROR_NAMES, _RETRYABLE_STATUS_CODES) + +def is_auth_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _AUTH_ERROR_NAMES, _AUTH_STATUS_CODES) + +def should_retry(exc: BaseException, litellm, attempt: int, limit: int) -> bool: + if attempt < limit and is_transient_error(exc, litellm): + return True + return attempt < min(limit, _AUTH_RETRIES) and is_auth_error(exc, litellm) + +def _retry_after_seconds(exc: BaseException) -> float | None: + headers = getattr(exc, 'headers', None) + if headers is None: + headers = getattr(getattr(exc, 'response', None), 'headers', None) + if headers is None: + return None + try: + raw = headers.get('retry-after') + if raw is None: + raw = headers.get('Retry-After') + value = float(raw) + except (AttributeError, TypeError, ValueError): + return None + return value if math.isfinite(value) and value >= 0 else None + +def retry_delay(exc: BaseException | None, attempt: int) -> float: + base = min(_MAX_RETRY_DELAY_SECONDS, 2.0 ** (attempt + 1)) + delay = base * (0.5 + random.random()) + retry_after = _retry_after_seconds(exc) if exc is not None else None + if retry_after is not None: + delay = max(delay, min(_MAX_RETRY_DELAY_SECONDS, retry_after)) + return delay + +def _note_retry(model, exc: BaseException, attempt: int, limit: int, delay: float) -> None: + status = getattr(exc, 'status_code', None) + print(f"judge call retry {attempt}/{limit}: {model} {type(exc).__name__} status={(status if type(status) is int else 'n/a')}, waiting {delay:.1f}s", file=sys.stderr) + +def _note_empty(model, response, attempt: int, limit: int, delay: float) -> None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + reason = None + if isinstance(data, dict) and isinstance(data.get('choices'), list) and data['choices']: + first = data['choices'][0] + reason = first.get('finish_reason') if isinstance(first, dict) else None + print(f'judge call retry {attempt}/{limit}: {model} empty verdict (finish_reason={reason}), waiting {delay:.1f}s', file=sys.stderr) + +def install(litellm, *, synchronous: bool=False) -> None: + pins = openrouter_judge_pins() + limit = transient_retry_limit() + empty_limit = empty_response_retry_limit() + deadline = time.monotonic() + retry_budget_seconds() + if synchronous: + original = litellm.completion + + def accounted(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = original(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + time.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + time.sleep(delay) + continue + return response + litellm.completion = accounted + return + original_async = litellm.acompletion + + async def accounted_async(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = await original_async(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + await asyncio.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + await asyncio.sleep(delay) + continue + return response + litellm.acompletion = accounted_async + +def record_agent_usage(attempt, *, model: str, provider: str) -> None: + records: dict[str, tuple[str, dict]] = {} + current_model = model + for filename in getattr(attempt, 'logs', []): + try: + with Path(filename).open() as stream: + for line in stream: + try: + event = json.loads(line) + except (ValueError, TypeError): + continue + if not isinstance(event, dict): + continue + message = event.get('message') or {} + if event.get('type') == 'assistant' and isinstance(message, dict) and isinstance(message.get('usage'), dict): + raw = message['usage'] + cached, written = (raw.get('cache_read_input_tokens'), raw.get('cache_creation_input_tokens')) + if all((type(value) is int and value >= 0 for value in (raw.get('input_tokens'), raw.get('output_tokens')))) and all((value is None or (type(value) is int and value >= 0) for value in (cached, written))): + receipt: dict = {'usage': {'input_uncached_tokens': raw['input_tokens'], 'prompt_tokens': raw['input_tokens'] + cached + written if cached is not None and written is not None else None, 'completion_tokens': raw['output_tokens'], 'prompt_tokens_details': {'cached_tokens': cached, 'cache_creation_tokens': written}}} + receipt['created'] = event.get('timestamp') + creation = raw.get('cache_creation') or {} + hour = creation.get('ephemeral_1h_input_tokens', 0) if isinstance(creation, dict) else 0 + if type(hour) is int and hour > 0: + if hour == written: + receipt['cache_ttl'] = '1h' + else: + receipt['usage_granularity'] = 'mixed_cache_ttl' + records[message.get('id') or json.dumps(raw, sort_keys=True)] = (message.get('model') or current_model, receipt) + payload = event.get('payload') or {} + if not isinstance(payload, dict): + continue + if event.get('type') == 'turn_context' and payload.get('model'): + current_model = payload['model'] + if event.get('type') == 'event_msg' and payload.get('type') == 'token_count': + info = payload.get('info') or {} + raw, total = (info.get('last_token_usage'), info.get('total_token_usage')) + if isinstance(raw, dict) and isinstance(total, dict) and all((type(raw.get(key)) is int and raw.get(key) >= 0 for key in ('input_tokens', 'output_tokens'))): + receipt = {'usage': {'prompt_tokens': raw.get('input_tokens'), 'input_uncached_tokens': raw.get('input_uncached_tokens'), 'input_cache_write_tokens': raw.get('input_cache_write_tokens'), 'completion_tokens': raw.get('output_tokens'), 'prompt_tokens_details': {'cached_tokens': raw.get('cached_input_tokens')}}} + receipt['created'] = event.get('timestamp') + records[json.dumps(total, sort_keys=True)] = (current_model, receipt) + except OSError: + continue + captured_input = captured_output = 0 + input_complete = True + for requested, receipt in records.values(): + requested = requested if '/' in requested else f'{provider}/{requested}' + _record_judge_usage(receipt, requested) + receipt_input = receipt['usage'].get('prompt_tokens') + if receipt_input is None: + input_complete = False + else: + captured_input += receipt_input + captured_output += receipt['usage'].get('completion_tokens') or 0 + total = getattr(attempt, 'usage', {}) or {} + if not records or (input_complete and total.get('input_tokens') != captured_input) or total.get('output_tokens') != captured_output: + _record_judge_usage({'usage': {'prompt_tokens': 0, 'completion_tokens': 0}, 'usage_granularity': 'incomplete_agent_receipts'}, model if '/' in model else f'{provider}/{model}') + +def install_rewardkit_agents() -> None: + import rewardkit.judges as judges + original = judges.get_agent + + def get_accounted_agent(judge, cwd=None): + backend = original(judge, cwd) + run = backend.run + + async def accounted_run(*args, **kwargs): + attempt = await run(*args, **kwargs) + record_agent_usage(attempt, model=judge.model or 'unknown', provider='anthropic' if judge.agent == 'claude-code' else 'openai') + return attempt + setattr(backend, 'run', accounted_run) + return backend + setattr(judges, 'get_agent', get_accounted_agent) +if __name__ == '__main__': + import litellm + if len(sys.argv) > 2 and sys.argv[1] == '--script': + import runpy + install(litellm, synchronous=True) + sys.argv = sys.argv[2:] + runpy.run_path(sys.argv[0], run_name='__main__') + else: + install(litellm) + install_rewardkit_agents() + if Path(__file__).with_name('m1_judge_panel.json').is_file(): + from m1_rewardkit_panel import install_panel + install_panel(Path(__file__).with_name('m1_judge_panel.json')) + if Path(__file__).with_name('m1_judge_jev.json').is_file(): + from m1_rewardkit_jev import install_jev + install_jev(Path(__file__).with_name('m1_judge_jev.json')) + from rewardkit.__main__ import main + main() diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/m1_rewardkit_panel.py b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/m1_rewardkit_panel.py new file mode 100644 index 0000000000000000000000000000000000000000..164cc2ae521cdd368c2e1749d7ed8fe09f4545eb --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/m1_rewardkit_panel.py @@ -0,0 +1,169 @@ +from __future__ import annotations +import asyncio +from contextvars import ContextVar +import json +import math +import os +import sys +from pathlib import Path +from typing import Any +import uuid +_request_audit: ContextVar[tuple[Path, list[str]] | None] = ContextVar('panel_request_audit', default=None) + +class PanelIncompleteError(RuntimeError): + pass + +def _audit_warning(exc: Exception, warnings: list[str]) -> None: + message = f'judge panel audit: diagnostic capture failed ({type(exc).__name__})' + if message not in warnings: + warnings.append(message) + print(message, file=sys.stderr) + +def _write_audit(path: Path, record: dict[str, Any], warnings: list[str], *, append: bool=False) -> None: + try: + text = json.dumps(record, allow_nan=False, default=str) + '\n' + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('a' if append else 'w') as stream: + stream.write(text) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + +def _binary(raw: Any) -> int: + if isinstance(raw, bool): + return int(raw) + if isinstance(raw, int | float) and math.isfinite(raw) and (raw in (0, 1)): + return int(raw) + if isinstance(raw, str): + value = raw.strip().lower() + if value in {'yes', 'true', '1'}: + return 1 + if value in {'no', 'false', '0'}: + return 0 + raise PanelIncompleteError('m1_judge_panel_incomplete: invalid binary vote') + +def validate_votes(scores: list[Any], criteria: list[Any]) -> None: + names = [criterion.name for criterion in criteria] + if len(set(names)) != len(names) or [score.name for score in scores] != names: + raise PanelIncompleteError('m1_judge_panel_incomplete: criterion membership mismatch') + for score, criterion in zip(scores, criteria, strict=True): + if score.error: + raise PanelIncompleteError('m1_judge_panel_incomplete: judge returned an error') + raw = _binary(score.raw) + expected = 1 - raw if criterion.negate else raw + if not math.isfinite(score.value) or score.value != expected: + raise PanelIncompleteError('m1_judge_panel_incomplete: inconsistent binary score') + +async def run_panel(judge: Any, criteria: list[Any], weights: list[float] | None, system_prompt: str | None, *, config: dict[str, Any], run_llm: Any, score_type: Any, audit_dir: Path) -> tuple[list[Any], str, list[str]]: + from rewardkit.models import Binary + if not criteria or any((not isinstance(criterion.output_format, Binary) for criterion in criteria)): + raise ValueError('panel majority voting requires nonempty binary criteria') + group_dir = audit_dir / uuid.uuid4().hex + warnings_out: list[str] = [] + + async def member_call(index: int, member: dict[str, Any]): + member_judge = judge.model_copy(update=member) + evidence: dict[str, Any] = {'member': index + 1, 'judge': member, 'criteria': [criterion.name for criterion in criteria], 'status': 'started'} + path = group_dir / f'judge-{index + 1}.json' + _write_audit(path, evidence, warnings_out) + token = _request_audit.set((group_dir / f'judge-{index + 1}-requests.jsonl', warnings_out)) + try: + scores, output, warnings = await run_llm(member_judge, criteria, weights, system_prompt) + evidence.update(output=output, warnings=warnings) + validate_votes(scores, criteria) + evidence['scores'] = [score.to_dict() for score in scores] + evidence['status'] = 'completed' + return (scores, output, warnings) + except BaseException as exc: + evidence.update(status='failed', error_class=type(exc).__name__) + if isinstance(exc, PanelIncompleteError): + evidence['error'] = str(exc) + raise + finally: + _request_audit.reset(token) + _write_audit(path, evidence, warnings_out) + outcomes = await asyncio.gather(*(member_call(index, member) for index, member in enumerate(config['members'])), return_exceptions=True) + failed = [index + 1 for index, result in enumerate(outcomes) if isinstance(result, BaseException)] + if failed: + _write_audit(group_dir / 'panel.json', {'status': 'incomplete', 'failed_members': failed}, warnings_out) + raise PanelIncompleteError(f'm1_judge_panel_incomplete: failed members {failed}; see panel audit artifacts') + completed = [outcome for outcome in outcomes if not isinstance(outcome, BaseException)] + combined = [] + for index, criterion in enumerate(criteria): + votes = [{'judge': config['members'][member_index], **outcome[0][index].to_dict()} for member_index, outcome in enumerate(completed)] + passes = sum((vote['value'] == 1 for vote in votes)) + value = int(passes >= 2) + combined.append(score_type(name=criterion.name, value=value, raw=bool(1 - value if criterion.negate else value), weight=weights[index] if weights is not None else 1.0, reasoning=f'{passes}/3 judges passed; strict majority requires 2/3.', description=criterion.description, id=criterion.id, negate=criterion.negate, optional=criterion.optional, votes=votes)) + for outcome in completed: + warnings_out.extend(outcome[2]) + audit = {'status': 'completed', 'mode': 'panel', 'aggregation': 'majority', 'required_votes': 2, 'members': config['members'], 'criteria': [score.to_dict() for score in combined]} + output = json.dumps(audit, indent=2, allow_nan=False) + _write_audit(group_dir / 'panel.json', audit, warnings_out) + return (combined, output, warnings_out) + +def install_panel(config_path: Path, *, audit_dir: Path=Path('/logs/verifier/judge-panel')) -> None: + import rewardkit.judges as judges + import rewardkit.reward as reward + from rewardkit.models import LLMJudge, Score + import litellm + config = json.loads(config_path.read_text()) + members = config.get('members') + concurrency = config.get('max_concurrent_llm') + if config.get('mode') != 'panel' or not isinstance(members, list) or len(members) != 3 or (len({member['model'] for member in members}) != 3) or (type(concurrency) is not int) or (not 1 <= concurrency <= 64): + raise ValueError('invalid materialized panel configuration') + if os.environ.get('REWARDKIT_JUDGE') or os.environ.get('REWARDKIT_MODEL'): + raise ValueError('RewardKit environment overrides cannot replace a frozen panel') + + class PanelScore(Score): + votes: list[dict[str, Any]] + + def to_dict(self): + return {**super().to_dict(), 'votes': self.votes} + original_llm = judges.arun_llm + original_call = judges._arun_llm_call + original_details = reward.Reward.to_detail_dict + original_completion = litellm.acompletion + active_loop = None + semaphore = None + + async def captured_completion(*args, **kwargs): + context = _request_audit.get() + record = {'requested_model': kwargs.get('model')} + response = None + try: + response = await original_completion(*args, **kwargs) + return response + except BaseException as exc: + record['error_class'] = type(exc).__name__ + raise + finally: + if context is not None: + path, warnings = context + try: + if response is not None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + record.update(response_model=data.get('model'), choices=data.get('choices')) + _write_audit(path, record, warnings, append=True) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + + async def bounded_call(*args, **kwargs): + nonlocal active_loop, semaphore + loop = asyncio.get_running_loop() + if active_loop is not loop: + active_loop, semaphore = (loop, asyncio.Semaphore(concurrency)) + assert semaphore is not None + async with semaphore: + return await original_call(*args, **kwargs) + + async def panel_call(judge, criteria, weights=None, system_prompt=None): + return await run_panel(judge, criteria, weights, system_prompt, config=config, run_llm=original_llm, score_type=PanelScore, audit_dir=audit_dir) + + def panel_details(self, score): + detail = original_details(self, score) + if isinstance(self.judge, LLMJudge): + detail.update(kind='llm_panel', judge=config, aggregation='majority', required_votes=2) + return detail + setattr(reward, 'arun_llm', panel_call) + setattr(judges, '_arun_llm_call', bounded_call) + setattr(litellm, 'acompletion', captured_completion) + reward.Reward.to_detail_dict = panel_details diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/normalize_reward.py b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/normalize_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..91817ef00ea9152ca57f0030d8e879eb850ddff0 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/normalize_reward.py @@ -0,0 +1,71 @@ +from __future__ import annotations +import argparse +import json +from pathlib import Path +from typing import Any + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument('--raw-details', required=True) + parser.add_argument('--rubric', required=True) + parser.add_argument('--reward-out', required=True) + parser.add_argument('--details-out', required=True) + args = parser.parse_args() + raw_details = _load_json(Path(args.raw_details)) + rubric = _load_json(Path(args.rubric)) + criteria = rubric['criteria'] + raw_by_name = _raw_criteria_by_name(raw_details) + positive_total = sum((float(item['score']) for item in criteria if float(item['score']) > 0)) + if positive_total <= 0: + raise ValueError('rubric must contain at least one positive score') + earned = 0.0 + normalized_criteria: list[dict[str, Any]] = [] + for item in criteria: + signed_score = float(item['score']) + raw = raw_by_name.get(item['name'], {}) + value = _coerce_score(raw.get('value', 0.0)) + contribution = value * signed_score + earned += contribution + normalized_criteria.append({'name': item['name'], 'value': value, 'raw': raw.get('raw'), 'weight': signed_score, 'signed_score': signed_score, 'polarity': item['polarity'], 'contribution': contribution, 'description': item['description'], 'source': item.get('source', ''), 'justification': item.get('justification', ''), 'metadata': item.get('metadata', {}), 'reasoning': raw.get('reasoning'), 'judge_reasoning': raw.get('reasoning'), 'judge_error': raw.get('error'), **({'votes': raw['votes']} if 'votes' in raw else {})}) + unclamped = earned / positive_total + reward = max(0.0, min(1.0, unclamped)) + reward_out = {'correctness': reward} + details_out = {'correctness': {'score': reward, 'kind': 'signed_score', 'criteria': normalized_criteria, 'aggregation': {'method': 'signed_score_ratio_clamped', 'earned': earned, 'positive_total': positive_total, 'unclamped': unclamped, 'clamped': reward}, 'raw_rewardkit': raw_details}} + _write_json(Path(args.reward_out), reward_out) + _write_json(Path(args.details_out), details_out) + +def _load_json(path: Path) -> Any: + return json.loads(path.read_text()) + +def _write_json(path: Path, data: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data, indent=2) + '\n') + +def _raw_criteria_by_name(details: dict[str, Any]) -> dict[str, dict[str, Any]]: + out: dict[str, dict[str, Any]] = {} + for reward in details.values(): + for item in _iter_raw_criteria(reward): + name = item.get('name') + if isinstance(name, str): + out[name] = item + return out + +def _iter_raw_criteria(value: Any): + if isinstance(value, list): + for item in value: + yield from _iter_raw_criteria(item) + return + if not isinstance(value, dict): + return + for item in value.get('criteria') or []: + if isinstance(item, dict): + yield item + +def _coerce_score(value: Any) -> float: + if isinstance(value, bool): + return 1.0 if value else 0.0 + if isinstance(value, int | float): + return max(0.0, min(1.0, float(value))) + return 0.0 +if __name__ == '__main__': + main() diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/agent_prompt.md b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/agent_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..ca489c065bafd5d10e764f033c9dfd1195933db3 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/agent_prompt.md @@ -0,0 +1,10 @@ +You are grading the submitted legal analysis against the criteria below. + +Read `/logs/artifacts/answer.md`, the answer captured by the verifier, before +assigning any scores. Evaluate that file as the submission. Other files in +`/app` may supply context, but must not replace the submitted answer. Do not +modify the submission. If it is missing or empty, state that in your reasoning +and apply the criteria to that missing or empty submission. Preserve each +criterion's stated positive or penalty polarity. + +{criteria} diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_1.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_1.toml new file mode 100644 index 0000000000000000000000000000000000000000..d8378348316b2dcc009d8652325d6ddff8b0bdf0 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_1.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_1" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that the corrective instrument ratifies Dr. Connors' appointment prospectively." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_10.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_10.toml new file mode 100644 index 0000000000000000000000000000000000000000..66d97df56c47f0302df96c6692015528868ab915 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_10.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_10" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: Mentions language in the drafted instrument designating May 7, 2026 as the effective date of Dr. Connors' appointment as Interim Chief Medical Officer." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_11.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_11.toml new file mode 100644 index 0000000000000000000000000000000000000000..80da43afc16e6a9571623c685113e0b3f8052144 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_11.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_11" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: Mentions that the Cal. Health & Safety Code § 1352(c) (2026) personnel notice requires resubmission of organizational exhibits." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_2.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_2.toml new file mode 100644 index 0000000000000000000000000000000000000000..958a3153efe9ac37214689b47015a45c076fefd8 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_2.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_2" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that the corrective instrument supersedes the \"effective as of May 7, 2026\" language in Resolution 2026-14." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_3.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_3.toml new file mode 100644 index 0000000000000000000000000000000000000000..120e498bec43dbfcb11ed4d74ec9b21e22c41466 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_3.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_3" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that the corrective instrument accurately characterizes the period from May 7 to May 13, 2026 as a period during which the appointment lacked valid Board authorization." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_4.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_4.toml new file mode 100644 index 0000000000000000000000000000000000000000..9906bde63b46ee5af29da8c62c6a51c0dc9a4308 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_4.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_4" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that the corrective instrument is structured for adoption by unanimous written consent." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_5.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_5.toml new file mode 100644 index 0000000000000000000000000000000000000000..9474abaafc20c72fa0bf9b6dee8a1cc5886adc66 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_5.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_5" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that the drafted instrument directs the Cal. Health & Safety Code § 1352(c) (2026) filing for Dr. Connors' appointment by May 18, 2026." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_6.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_6.toml new file mode 100644 index 0000000000000000000000000000000000000000..7dcfdc3ce5a198f6ad86a75c524157cb6c8c2eab --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_6.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_6" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that the drafted instrument includes a recitals block setting out the factual governance background." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_7.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_7.toml new file mode 100644 index 0000000000000000000000000000000000000000..79e12553195f707cd5d50ae37a4c19161a81ac23 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_7.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_7" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that the drafted instrument includes an adoption block reflecting the mechanism of adoption." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_8.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_8.toml new file mode 100644 index 0000000000000000000000000000000000000000..18b6af6d1d645898da7c95ba50e42b36f841b1f0 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_8.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_8" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that the drafted instrument includes an officer authorization clause directing officers to take actions necessary to implement it." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_9.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_9.toml new file mode 100644 index 0000000000000000000000000000000000000000..4ac69a57cf88905f47d6cc587988109617d1769c --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/raw_correctness/criterion_9.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_9" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that the corrective instrument is capable of valid adoption under the Bylaws." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/test.sh b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..66a509a7bcdbe412851f3a012a5ba7b16cf0925b --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-3/tests/test.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +set -euo pipefail + +mkdir -p /logs/artifacts /logs/verifier/raw + +python3 - <<'PYEOF' +import json +import shutil +from pathlib import Path + + +def has_text(path: Path) -> bool: + return path.exists() and path.is_file() and bool(path.read_text(errors="replace").strip()) + + +def fallback_paths(answer_path: Path) -> list[Path]: + paths = [] + try: + relative = answer_path.relative_to("/app") + paths.append(Path("/app/app") / relative) + except ValueError: + pass + return [path for path in paths if path != answer_path] + + +config = json.loads(Path("/tests/fixtures/config.json").read_text()) +answer_path = Path(config["answer_path"]) +artifact_answer = Path("/logs/artifacts/answer.md") +artifact_answer.parent.mkdir(parents=True, exist_ok=True) +if has_text(answer_path): + shutil.copyfile(answer_path, artifact_answer) +else: + for candidate in fallback_paths(answer_path): + if has_text(candidate): + shutil.copyfile(candidate, artifact_answer) + break + else: + artifact_answer.write_text("") + +# Harbor collects /logs/artifacts when the agent step ends, which is before this +# script runs, so the copy above never reaches the uploaded artifacts. /logs/verifier +# is uploaded after the verifier phase, so persist the graded answer there too. +verifier_answer = Path("/logs/verifier/answer.md") +verifier_answer.parent.mkdir(parents=True, exist_ok=True) +shutil.copyfile(artifact_answer, verifier_answer) +PYEOF + +uv run --no-project --with 'harbor-rewardkit[all]==0.2.0' python /tests/m1_rewardkit_accounting.py /tests/raw_correctness \ + --workspace /app \ + --output /logs/verifier/raw/reward.json \ + --max-concurrent-llm "${MAX_CONCURRENT_LLM:-4}" \ + --max-concurrent-agent "${M1_MAX_CONCURRENT_AGENT:-1}" + +python /tests/normalize_reward.py \ + --raw-details /logs/verifier/raw/reward-details.json \ + --rubric /tests/fixtures/rubric.json \ + --reward-out /logs/verifier/reward.json \ + --details-out /logs/verifier/reward-details.json diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/instruction.md b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a3602609f33cb87b0f74269fa54e8d7e5a5c975e --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/instruction.md @@ -0,0 +1,40 @@ +# Interim CMO Appointment: Governance and Compliance Analysis — Assignment 4 + +You are a senior legal analyst operating autonomously. You are completing a multi-step legal reasoning task. Follow the role, factual record, instructions, and deliverable requirements provided in the Task and each Assignment. + +Each Assignment may require a different legal deliverable. Follow the requirements specific to that Assignment. + +## Word limits for court briefs + +- A brief in support of or in response to a motion may not exceed **8,750 words**. +- A reply brief may not exceed **3,500 words**. +- For a motion for reconsideration, a brief in support of or in response to the motion may not exceed **3,500 words**, and a reply brief may not exceed **1,750 words**. +- If an Assignment specifies a stricter word limit, follow the stricter limit. + +These word limits do not apply to legal memoranda or other non-court-filing deliverables unless the Assignment expressly provides otherwise. + +Complete the task end-to-end without asking for confirmation, permission, or clarification. + +Use the uploaded matter documents in `/app/attachments/` as your primary case file. You also have internet access via OpenCode's `websearch` tool; use it to research any statutes, regulations, cases, administrative guidance, or secondary authorities that are not supplied as attachments. Cite any authority you rely on in the format requested by the prompt. + +For document inspection: +- PDF: `pdftotext /app/attachments/.pdf -` +- DOCX: `pandoc /app/attachments/.docx -t markdown` +- XLSX/CSV: use Python with `openpyxl` or `pandas` +- If extraction is unreliable, inspect the raw file with Python libraries or convert/render the relevant pages. + +Write the final complete legal deliverable for this assignment to `/app/response4.md`. The verifier reads only that file. + +This is a follow-on assignment. The documents from the previous assignment(s) remain available in `/app/attachments/`, and your prior deliverable `/app/response3.md` is also on disk. Build on that analysis as the prompt directs. + +## Attachments + +_No new documents for this assignment. The documents from the previous assignment(s) remain available in `/app/attachments/`._ + +## Prompt + +Following the same instructions and your analysis from Steps 1, 2, and 3, incorporate the following into the memorandum: + +Assess the regulatory exposure, if any, arising from actions taken by or under the authority of Dr. Connors between May 7, 2026 and the date her appointment became effective under your Step 1 analysis, including any exposure relating to IHP's utilization management obligations, and provide your recommended remediation. + +The same uploaded documents from Step 1 constitute the complete and exclusive universe of materials for this assignment. All legal analysis must be based solely on the law and guidance as it exists on May 15, 2026. Do not account for any legislative changes, regulatory updates, or Department of Managed Health Care (DMHC) guidance issued after that date. All citations must reference the uploaded document by its exact name as listed in Step 1, followed by the specific page and section. diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/solution/solve.sh b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7710414a6da6d0ad740717c8c85a9af850d5da33 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/solution/solve.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# No oracle solution ships with LegalReasonBench. The verifier grades the +# agent's own legal deliverable for this assignment against the rubric. +echo "no oracle solution" diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/fixtures/config.json b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/fixtures/config.json new file mode 100644 index 0000000000000000000000000000000000000000..d3341211faacd2f88519cf8ee92881e32e71fc33 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/fixtures/config.json @@ -0,0 +1,113 @@ +{ + "task_id": "lrb-interim-cmo-appointment-governance", + "title": "Interim CMO Appointment: Governance and Compliance Analysis", + "domain": "", + "matter": "", + "judge": { + "max_concurrent_llm": 12, + "mode": "panel", + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ], + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + "step_index": 4, + "step_name": "assignment-4", + "step_title": "", + "prompt": "Following the same instructions and your analysis from Steps 1, 2, and 3, incorporate the following into the memorandum:\n\nAssess the regulatory exposure, if any, arising from actions taken by or under the authority of Dr. Connors between May 7, 2026 and the date her appointment became effective under your Step 1 analysis, including any exposure relating to IHP's utilization management obligations, and provide your recommended remediation.\n\nThe same uploaded documents from Step 1 constitute the complete and exclusive universe of materials for this assignment. All legal analysis must be based solely on the law and guidance as it exists on May 15, 2026. Do not account for any legislative changes, regulatory updates, or Department of Managed Health Care (DMHC) guidance issued after that date. All citations must reference the uploaded document by its exact name as listed in Step 1, followed by the specific page and section.", + "attachments": [], + "rubric": [ + { + "name": "criterion_1", + "description": "States that IHP lacked a validly designated medical director under Cal. Health & Safety Code \u00a7 1367.01(c) (2026) during the period from May 7 to May 13, 2026.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 3, Section 5.12 (\"The Chief Medical Officer shall be a physician holding an unrestricted license to practice medicine in the State of California and shall serve as the Corporation's designated medical director pursuant to Health and Safety Code Section 1367.01\"); IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 8, Cal. Health & Safety Code \u00a7 1367.01(c) (2026) (\"A health care service plan subject to this section, except a plan that meets the requirements of Section 1351.2, shall employ or designate a medical director who holds an unrestricted license to practice medicine in this state\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Assess the regulatory exposure, if any, arising from actions taken by or under the authority of Dr. Connors between May 7, 2026 and the date her appointment became effective under your Step 1 analysis, including any exposure relating to IHP's utilization management obligations.\" Designation as medical director routes through the CMO office under Section 5.12. Because the CMO appointment was ineffective until May 13th, IHP lacked a validly designated medical director under Cal. Health & Safety Code \u00a7 1367.01(c) (2026) during the May 7th to May 13th period.", + "metadata": { + "irac_section": "Application" + }, + "score": 30.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_2", + "description": "States that the requirements of Cal. Health & Safety Code \u00a7 1367.01(e) (2026) turn on the licensure of the reviewing physician.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 9, Cal. Health & Safety Code \u00a7 1367.01(e) (2026) (\"No individual, other than a licensed physician or a licensed health care professional who is competent to evaluate the specific clinical issues involved in the health care services requested by the provider, may deny or modify requests for authorization of health care services for an enrollee for reasons of medical necessity\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Assess the regulatory exposure, if any, arising from actions taken by or under the authority of Dr. Connors between May 7, 2026 and the date her appointment became effective under your Step 1 analysis, including any exposure relating to IHP's utilization management obligations.\" Cal. Health & Safety Code \u00a7 1367.01(e) (2026) conditions the validity of individual utilization management determinations on the licensure of the reviewing clinician, not on the corporate validity of the officer appointment. Dr. Connors held an unrestricted California medical license throughout the period. Individual determinations she made are not invalidated by the designation gap.", + "metadata": { + "irac_section": "Application" + }, + "score": 20.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_3", + "description": "States that the lack of a validly designated medical director was cured prospectively by the Board action of May 13, 2026.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall be effective upon adoption of the ratifying resolution\"); IHP_Board_Resolution_2026-14.docx, p. 2, Record of Adoption (\"The foregoing Resolution was duly adopted at the regular meeting of the Board of Directors of Imperium Health Plan, Inc. held on May 13, 2026, at which a quorum was present and acting throughout\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Assess the regulatory exposure, if any, arising from actions taken by or under the authority of Dr. Connors between May 7, 2026 and the date her appointment became effective under your Step 1 analysis, and provide your recommended remediation.\" Section 5.9 provides that ratification is effective upon adoption. The Board's adoption of Resolution 2026-14 on May 13, 2026 cured the designation defect prospectively from that date. Remediation for the May 7 to May 13 exposure period is addressed separately.", + "metadata": { + "irac_section": "Conclusion" + }, + "score": 15.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_4", + "description": "States that the omnibus ratification clause in Resolution 2026-14 does not retroactively cure actions taken during the period from May 7 to May 13, 2026 under the Bylaws.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall be effective upon adoption of the ratifying resolution\"); IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 1, Section 5.2 (\"No appointment of a principal officer shall be effective unless and until approved by the Board of Directors in accordance with this Section 5.2\"); IHP_Board_Resolution_2026-14.docx, p. 1, RESOLVED FURTHER clause (\"all actions heretofore taken by the officers and agents of the Corporation in connection with the matters contemplated by this Resolution are hereby ratified, confirmed, and approved in all respects\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Assess the regulatory exposure, if any, arising from actions taken by or under the authority of Dr. Connors between May 7, 2026 and the date her appointment became effective under your Step 1 analysis.\" The omnibus clause in Resolution 2026-14 purports to ratify all prior actions. Under the Bylaws, ratification is effective upon adoption and does not operate to cure deficiencies in the period preceding adoption. The omnibus clause does not eliminate the May 7th to May 13th exposure period.", + "metadata": { + "irac_section": "Application" + }, + "score": 8.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_5", + "description": "Mentions that utilization management determinations made during the period from May 7 to May 13, 2026 are invalid.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 9, Cal. Health & Safety Code \u00a7 1367.01(e) (2026) (\"No individual, other than a licensed physician or a licensed health care professional who is competent to evaluate the specific clinical issues involved in the health care services requested by the provider, may deny or modify requests for authorization of health care services for an enrollee for reasons of medical necessity\"); IHP_CMO_Interim_Appointment_Letter_Connors.docx, p. 1, opening paragraph (\"effective immediately, you are appointed to serve as Interim Chief Medical Officer of Imperium Health Plan, Inc.\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"Assess the regulatory exposure, if any, arising from actions taken by or under the authority of Dr. Connors between May 7, 2026 and the date her appointment became effective under your Step 1 analysis, including any exposure relating to IHP's utilization management obligations, and provide your recommended remediation.\" Cal. Health & Safety Code \u00a7 1367.01(e) (2026) conditions the validity of individual utilization management determinations on the licensure of the reviewing clinician. Dr. Connors held an unrestricted California medical license throughout the period. A model that recommends mass re-review has conflated the corporate designation defect with the individual licensure requirement that governs the validity of specific determinations.", + "metadata": { + "irac_section": "Conclusion" + }, + "score": -15.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_6", + "description": "Mentions that utilization management determinations made during the period from May 7 to May 13, 2026 require re-review.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 9, Cal. Health & Safety Code \u00a7 1367.01(e) (2026) (\"No individual, other than a licensed physician or a licensed health care professional who is competent to evaluate the specific clinical issues involved in the health care services requested by the provider, may deny or modify requests for authorization of health care services for an enrollee for reasons of medical necessity\"); IHP_CMO_Interim_Appointment_Letter_Connors.docx, p. 1, opening paragraph (\"effective immediately, you are appointed to serve as Interim Chief Medical Officer of Imperium Health Plan, Inc.\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"Assess the regulatory exposure, if any, arising from actions taken by or under the authority of Dr. Connors between May 7, 2026 and the date her appointment became effective under your Step 1 analysis, including any exposure relating to IHP's utilization management obligations, and provide your recommended remediation.\" Cal. Health & Safety Code \u00a7 1367.01(e) (2026) conditions the validity of individual utilization management determinations on the licensure of the reviewing clinician. Dr. Connors held an unrestricted California medical license throughout the period. A model that recommends mass re-review has conflated the corporate designation defect with the individual licensure requirement that governs the validity of specific determinations.", + "metadata": { + "irac_section": "Conclusion" + }, + "score": -10.0, + "polarity": "negative", + "raw_weight": 1.0 + } + ], + "answer_path": "/app/response4.md", + "answer_relative_path": "response4.md", + "is_followon": true, + "prev_answer_path": "/app/response3.md" +} diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/fixtures/rubric.json b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/fixtures/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..689da893f1751ce4190bc552d4274e167c0b7cb7 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/fixtures/rubric.json @@ -0,0 +1,76 @@ +{ + "criteria": [ + { + "name": "criterion_1", + "description": "States that IHP lacked a validly designated medical director under Cal. Health & Safety Code \u00a7 1367.01(c) (2026) during the period from May 7 to May 13, 2026.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 3, Section 5.12 (\"The Chief Medical Officer shall be a physician holding an unrestricted license to practice medicine in the State of California and shall serve as the Corporation's designated medical director pursuant to Health and Safety Code Section 1367.01\"); IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 8, Cal. Health & Safety Code \u00a7 1367.01(c) (2026) (\"A health care service plan subject to this section, except a plan that meets the requirements of Section 1351.2, shall employ or designate a medical director who holds an unrestricted license to practice medicine in this state\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Assess the regulatory exposure, if any, arising from actions taken by or under the authority of Dr. Connors between May 7, 2026 and the date her appointment became effective under your Step 1 analysis, including any exposure relating to IHP's utilization management obligations.\" Designation as medical director routes through the CMO office under Section 5.12. Because the CMO appointment was ineffective until May 13th, IHP lacked a validly designated medical director under Cal. Health & Safety Code \u00a7 1367.01(c) (2026) during the May 7th to May 13th period.", + "metadata": { + "irac_section": "Application" + }, + "score": 30.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_2", + "description": "States that the requirements of Cal. Health & Safety Code \u00a7 1367.01(e) (2026) turn on the licensure of the reviewing physician.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 9, Cal. Health & Safety Code \u00a7 1367.01(e) (2026) (\"No individual, other than a licensed physician or a licensed health care professional who is competent to evaluate the specific clinical issues involved in the health care services requested by the provider, may deny or modify requests for authorization of health care services for an enrollee for reasons of medical necessity\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Assess the regulatory exposure, if any, arising from actions taken by or under the authority of Dr. Connors between May 7, 2026 and the date her appointment became effective under your Step 1 analysis, including any exposure relating to IHP's utilization management obligations.\" Cal. Health & Safety Code \u00a7 1367.01(e) (2026) conditions the validity of individual utilization management determinations on the licensure of the reviewing clinician, not on the corporate validity of the officer appointment. Dr. Connors held an unrestricted California medical license throughout the period. Individual determinations she made are not invalidated by the designation gap.", + "metadata": { + "irac_section": "Application" + }, + "score": 20.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_3", + "description": "States that the lack of a validly designated medical director was cured prospectively by the Board action of May 13, 2026.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall be effective upon adoption of the ratifying resolution\"); IHP_Board_Resolution_2026-14.docx, p. 2, Record of Adoption (\"The foregoing Resolution was duly adopted at the regular meeting of the Board of Directors of Imperium Health Plan, Inc. held on May 13, 2026, at which a quorum was present and acting throughout\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Assess the regulatory exposure, if any, arising from actions taken by or under the authority of Dr. Connors between May 7, 2026 and the date her appointment became effective under your Step 1 analysis, and provide your recommended remediation.\" Section 5.9 provides that ratification is effective upon adoption. The Board's adoption of Resolution 2026-14 on May 13, 2026 cured the designation defect prospectively from that date. Remediation for the May 7 to May 13 exposure period is addressed separately.", + "metadata": { + "irac_section": "Conclusion" + }, + "score": 15.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_4", + "description": "States that the omnibus ratification clause in Resolution 2026-14 does not retroactively cure actions taken during the period from May 7 to May 13, 2026 under the Bylaws.", + "source": "IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 2, Section 5.9 (\"Ratification shall be effective upon adoption of the ratifying resolution\"); IHP_Bylaws_Excerpt_Article_V_Officers.docx, p. 1, Section 5.2 (\"No appointment of a principal officer shall be effective unless and until approved by the Board of Directors in accordance with this Section 5.2\"); IHP_Board_Resolution_2026-14.docx, p. 1, RESOLVED FURTHER clause (\"all actions heretofore taken by the officers and agents of the Corporation in connection with the matters contemplated by this Resolution are hereby ratified, confirmed, and approved in all respects\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Assess the regulatory exposure, if any, arising from actions taken by or under the authority of Dr. Connors between May 7, 2026 and the date her appointment became effective under your Step 1 analysis.\" The omnibus clause in Resolution 2026-14 purports to ratify all prior actions. Under the Bylaws, ratification is effective upon adoption and does not operate to cure deficiencies in the period preceding adoption. The omnibus clause does not eliminate the May 7th to May 13th exposure period.", + "metadata": { + "irac_section": "Application" + }, + "score": 8.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_5", + "description": "Mentions that utilization management determinations made during the period from May 7 to May 13, 2026 are invalid.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 9, Cal. Health & Safety Code \u00a7 1367.01(e) (2026) (\"No individual, other than a licensed physician or a licensed health care professional who is competent to evaluate the specific clinical issues involved in the health care services requested by the provider, may deny or modify requests for authorization of health care services for an enrollee for reasons of medical necessity\"); IHP_CMO_Interim_Appointment_Letter_Connors.docx, p. 1, opening paragraph (\"effective immediately, you are appointed to serve as Interim Chief Medical Officer of Imperium Health Plan, Inc.\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"Assess the regulatory exposure, if any, arising from actions taken by or under the authority of Dr. Connors between May 7, 2026 and the date her appointment became effective under your Step 1 analysis, including any exposure relating to IHP's utilization management obligations, and provide your recommended remediation.\" Cal. Health & Safety Code \u00a7 1367.01(e) (2026) conditions the validity of individual utilization management determinations on the licensure of the reviewing clinician. Dr. Connors held an unrestricted California medical license throughout the period. A model that recommends mass re-review has conflated the corporate designation defect with the individual licensure requirement that governs the validity of specific determinations.", + "metadata": { + "irac_section": "Conclusion" + }, + "score": -15.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_6", + "description": "Mentions that utilization management determinations made during the period from May 7 to May 13, 2026 require re-review.", + "source": "IHP_Regulatory_Reference_Compilation_KKA_2026.docx, p. 9, Cal. Health & Safety Code \u00a7 1367.01(e) (2026) (\"No individual, other than a licensed physician or a licensed health care professional who is competent to evaluate the specific clinical issues involved in the health care services requested by the provider, may deny or modify requests for authorization of health care services for an enrollee for reasons of medical necessity\"); IHP_CMO_Interim_Appointment_Letter_Connors.docx, p. 1, opening paragraph (\"effective immediately, you are appointed to serve as Interim Chief Medical Officer of Imperium Health Plan, Inc.\").", + "justification": "This rubric item is implied, though not directly requested, in the following portion of the prompt: \"Assess the regulatory exposure, if any, arising from actions taken by or under the authority of Dr. Connors between May 7, 2026 and the date her appointment became effective under your Step 1 analysis, including any exposure relating to IHP's utilization management obligations, and provide your recommended remediation.\" Cal. Health & Safety Code \u00a7 1367.01(e) (2026) conditions the validity of individual utilization management determinations on the licensure of the reviewing clinician. Dr. Connors held an unrestricted California medical license throughout the period. A model that recommends mass re-review has conflated the corporate designation defect with the individual licensure requirement that governs the validity of specific determinations.", + "metadata": { + "irac_section": "Conclusion" + }, + "score": -10.0, + "polarity": "negative", + "raw_weight": 1.0 + } + ] +} diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/m1_judge_panel.json b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/m1_judge_panel.json new file mode 100644 index 0000000000000000000000000000000000000000..a8041f6781a899f9083fe4a1a95f51bc78d35601 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/m1_judge_panel.json @@ -0,0 +1,21 @@ +{ + "mode": "panel", + "max_concurrent_llm": 12, + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ] +} diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/m1_rewardkit_accounting.py b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/m1_rewardkit_accounting.py new file mode 100644 index 0000000000000000000000000000000000000000..406dc5e7c675b222d94514e71bf5fad6ae141d8f --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/m1_rewardkit_accounting.py @@ -0,0 +1,490 @@ +import asyncio +import json +import math +import os +from pathlib import Path +import random +import sys +import time + +class JudgeReceiptError(OSError): + pass +_LLM_ROUTES = frozenset({'vertex', 'anthropic fallback', 'aistudio', 'direct'}) +_LLM_ROUTE_HEADERS = ('x-m1-llm-route', 'llm_provider-x-m1-llm-route') + +def _canonical_llm_route(value): + return value if isinstance(value, str) and value in _LLM_ROUTES else None + +def _llm_route_from_headers(headers): + if not isinstance(headers, dict): + return None + folded = {str(key).lower(): value for key, value in headers.items()} + for name in _LLM_ROUTE_HEADERS: + route = _canonical_llm_route(folded.get(name)) + if route is not None: + return route + return None + +def _llm_route_from_response(response): + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + route = _llm_route_from_headers(headers) + if route is not None: + return route + return _llm_route_from_headers(getattr(response, 'headers', None)) + +def _token_field_status(values, key): + if not isinstance(values, dict) or key not in values: + return 'missing' + value = values[key] + if value is None: + return 'null' + return 'valid' if type(value) is int and value >= 0 else 'invalid' + +def _gemini_capture(kwargs, model): + if not model.startswith('gemini/') or kwargs.get('stream') or kwargs.get('tools') or kwargs.get('functions'): + return (kwargs, None) + from litellm.integrations.custom_logger import CustomLogger + from urllib.parse import urlsplit + + class Capture(CustomLogger): + evidence = None + prompt_status = 'not_observed' + llm_route = None + + def log_post_api_call(self, kwargs, response_obj, start_time, end_time): + self.evidence = None + self.prompt_status = 'not_observed' + try: + params = kwargs.get('litellm_params') or {} + route = urlsplit(params.get('api_base') or '') + bare = model.removeprefix('gemini/') + gemini = params.get('custom_llm_provider') == 'gemini' + ai_studio = gemini and route.hostname == 'generativelanguage.googleapis.com' and (route.path in {'/' + version + '/models/' + bare + ':generateContent' for version in ('v1alpha', 'v1beta')}) + broker = urlsplit(os.environ.get('GEMINI_API_BASE') or '') + brokered = gemini and bool(broker.netloc) and (route.netloc == broker.netloc) and (broker.path.rstrip('/').rsplit('/', 1)[-1] in ('v1alpha', 'v1beta')) and (route.path == broker.path.rstrip('/') + '/models/' + bare + ':generateContent') + vertex = params.get('custom_llm_provider') == 'vertex_ai' and route.hostname == 'aiplatform.googleapis.com' and route.path.startswith('/v1/projects/') and route.path.endswith('/locations/global/publishers/google/models/' + bare + ':generateContent') + if route.scheme != 'https' or not (ai_studio or brokered or vertex) or kwargs.get('stream'): + return + self.llm_route = 'vertex' if vertex else 'aistudio' if ai_studio else None + raw = kwargs.get('original_response') + raw = json.loads(raw) if isinstance(raw, str) else raw + if not isinstance(raw, dict): + return + candidates = raw.get('candidates') + if not isinstance(candidates, list) or not candidates or any((not isinstance(c, dict) or not c.get('finishReason') for c in candidates)) or (not isinstance(raw.get('modelVersion'), str)) or (not raw['modelVersion']): + return + usage = raw.get('usageMetadata') + self.prompt_status = _token_field_status(usage, 'promptTokenCount') + if not isinstance(usage, dict): + return + fields = ('promptTokenCount', 'candidatesTokenCount', 'thoughtsTokenCount', 'cachedContentTokenCount', 'totalTokenCount', 'toolUsePromptTokenCount') + counts = {key: usage.get(key, 0) for key in fields} + if not {'promptTokenCount', 'totalTokenCount'} <= usage.keys() or any((type(n) is not int or n < 0 for n in counts.values())) or counts['toolUsePromptTokenCount'] != 0 or (counts['cachedContentTokenCount'] > counts['promptTokenCount']) or (counts['totalTokenCount'] != counts['promptTokenCount'] + counts['candidatesTokenCount'] + counts['thoughtsTokenCount']): + return + self.evidence = {'protocol': 'gemini-generate-content-' + ('vertex-v1' if vertex else route.path.split('/')[-3]), 'model_version': raw['modelVersion'], 'usage_metadata': {key: usage[key] for key in fields if key in usage}, 'defaulted_fields': [key for key in fields if key not in usage]} + except (TypeError, ValueError, AttributeError): + return + capture = Capture() + return ({**kwargs, 'callbacks': [*(kwargs.get('callbacks') or []), capture]}, capture) + +def _record_judge_usage(response, model: str, *, target: Path | None=None, native_usage: dict | None=None, native_prompt_status: str | None=None, llm_route: str | None=None) -> None: + import fcntl + from datetime import datetime, timezone + data = response.model_dump() if hasattr(response, 'model_dump') else response + usage = data.get('usage') if isinstance(data, dict) else None + granularity = data.get('usage_granularity') if isinstance(data, dict) else None + if not isinstance(usage, dict): + usage = {} + granularity = 'missing_provider_receipt' + prompt, completion = (usage.get('prompt_tokens'), usage.get('completion_tokens')) + native_fresh = usage.get('input_uncached_tokens') + prompt = prompt if type(prompt) is int and prompt >= 0 else None + native_fresh = native_fresh if type(native_fresh) is int and native_fresh >= 0 else None + if type(completion) is not int or completion < 0 or (prompt is None and native_fresh is None): + completion = completion if type(completion) is int and completion >= 0 else 0 + granularity = granularity or 'invalid_provider_receipt' + details = usage.get('prompt_tokens_details') + if details is not None and (not isinstance(details, dict)): + granularity = 'invalid_provider_receipt' + details = details if isinstance(details, dict) else {} + cached = details.get('cached_tokens') + if native_usage is not None: + native = native_usage['usage_metadata'] + native_output = native.get('candidatesTokenCount', 0) + native.get('thoughtsTokenCount', 0) + if prompt == native['promptTokenCount'] and completion == native_output: + cached = native.get('cachedContentTokenCount', 0) + else: + native_usage = None + written = next((value for value in (usage.get('input_cache_write_tokens'), usage.get('cache_creation_input_tokens'), details.get('cache_creation_tokens'), details.get('cache_write_tokens')) if value is not None), None) + invalid = any((value is not None and (type(value) is not int or value < 0) for value in (cached, written))) + cached = cached if type(cached) is int and cached >= 0 else None + written = written if type(written) is int and written >= 0 else None + fresh = native_fresh + if fresh is None and prompt is not None and (cached is not None) and (written is not None): + fresh = prompt - cached - written + if fresh is not None and (fresh < 0 or (prompt is not None and cached is not None and (written is not None) and (fresh + cached + written != prompt))): + invalid, fresh = (True, None) + provider, _, slug = model.partition('/') + event: dict = {'type': 'step_finish', 'part': {'providerID': provider if slug else 'openai', 'modelID': slug or model, 'tokens': {'input': fresh, 'output': completion, 'cache': {'read': cached, 'write': written}}}} + field_status = {'prompt_tokens': _token_field_status(usage, 'prompt_tokens'), 'completion_tokens': _token_field_status(usage, 'completion_tokens'), 'input_uncached_tokens': _token_field_status(usage, 'input_uncached_tokens')} + field_status['native_prompt_token_count'] = native_prompt_status if native_prompt_status in {'missing', 'null', 'invalid', 'valid', 'not_observed'} else 'unsupported' + part: dict = event['part'] + part['usage_field_status'] = field_status + if native_usage is not None: + event['part']['native_usage'] = native_usage + event['part']['token_categories_provenance'] = 'explicit_presence_v1' + if fresh is None and prompt is not None: + event['part']['prompt_tokens_inclusive'] = prompt + if invalid or any((value is None for value in (fresh, cached, written))): + granularity = granularity if granularity not in (None, 'request') else 'invalid_provider_receipt' if invalid else 'incomplete_token_categories' + if granularity: + event['part']['usage_granularity'] = granularity + if provider == 'openrouter': + cost = usage.get('cost') + if cost is None: + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + if isinstance(headers, dict): + cost = headers.get('llm_provider-x-litellm-response-cost') + if isinstance(cost, (int, float)) and (not isinstance(cost, bool)) and math.isfinite(cost) and (cost >= 0): + event['part']['cost'] = cost + data = data if isinstance(data, dict) else {} + if isinstance(data.get('id'), str) and data['id']: + event['part']['provider_request_id'] = data['id'] + for key in ('service_tier', 'cache_ttl'): + if data.get(key): + event['part'][key] = data[key] + route = _llm_route_from_response(response) or _canonical_llm_route(llm_route) + if route is not None: + event['part']['llm_route'] = route + created = data.get('created') + stamp = datetime.now(timezone.utc) + try: + if isinstance(created, str): + parsed = datetime.fromisoformat(created.replace('Z', '+00:00')) + if parsed.tzinfo is not None: + stamp = parsed + elif isinstance(created, (int, float)) and (not isinstance(created, bool)) and math.isfinite(created): + stamp = datetime.fromtimestamp(created, timezone.utc) + except (ValueError, OverflowError, OSError): + pass + pair = json.dumps({'type': 'step_start', 'timestamp': stamp.isoformat()}) + '\n' + pair += json.dumps(event) + '\n' + try: + receipt_path = target or Path(os.environ.get('M1_JUDGE_USAGE_PATH', '/logs/verifier/judge-trajectory.jsonl')) + receipt_path.parent.mkdir(parents=True, exist_ok=True) + with receipt_path.open('a') as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + handle.write(pair) + handle.flush() + os.fsync(handle.fileno()) + except OSError as exc: + if target is not None: + raise JudgeReceiptError(f'judge receipt write failed: {exc}') from exc + print(f'judge accounting: write failed ({type(exc).__name__})', file=sys.stderr) + +def openrouter_judge_pins() -> dict[str, dict]: + raw = os.environ.get('M1_OPENROUTER_JUDGE_PROVIDER_PINS', '').strip() + if not raw: + return {} + try: + pins = json.loads(raw) + except json.JSONDecodeError: + print('judge provider pins: invalid JSON in M1_OPENROUTER_JUDGE_PROVIDER_PINS', file=sys.stderr) + return {} + return {model: pin for model, pin in pins.items() if isinstance(pin, dict) and pin.get('order')} if isinstance(pins, dict) else {} + +def apply_judge_provider_pin(kwargs: dict, pins: dict[str, dict]) -> dict: + model = kwargs.get('model') + pin = pins.get(model) if isinstance(model, str) else None + if pin is None: + return kwargs + extra_body = dict(kwargs.get('extra_body') or {}) + provider = dict(extra_body.get('provider') or {}) + provider['order'] = list(pin['order']) + if pin.get('allow_fallbacks') is False: + provider['allow_fallbacks'] = False + if pin.get('zdr'): + provider['zdr'] = True + extra_body['provider'] = provider + return {**kwargs, 'extra_body': extra_body} +_TRANSIENT_ERROR_NAMES = ('RateLimitError', 'ServiceUnavailableError', 'InternalServerError', 'BadGatewayError', 'APIConnectionError') +_RETRYABLE_STATUS_CODES = frozenset({408, 409, 425, 429, 500, 502, 503, 504}) +_AUTH_ERROR_NAMES = ('AuthenticationError', 'PermissionDeniedError') +_AUTH_STATUS_CODES = frozenset({401, 403}) +_AUTH_RETRIES = 4 +_DEFAULT_TRANSIENT_RETRIES = 6 +_MAX_TRANSIENT_RETRIES = 20 +_MAX_RETRY_DELAY_SECONDS = 60.0 +_DEFAULT_EMPTY_RESPONSE_RETRIES = 3 +_DEFAULT_RETRY_BUDGET_SECONDS = 900.0 +_MAX_RETRY_BUDGET_SECONDS = 86400.0 + +def transient_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_TRANSIENT_RETRIES', '').strip() + if not raw: + return _DEFAULT_TRANSIENT_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_TRANSIENT_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_TRANSIENT_RETRIES + +def empty_response_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_EMPTY_RESPONSE_RETRIES', '').strip() + if not raw: + return _DEFAULT_EMPTY_RESPONSE_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_EMPTY_RESPONSE_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_EMPTY_RESPONSE_RETRIES + +def retry_budget_seconds() -> float: + raw = os.environ.get('M1_JUDGE_RETRY_BUDGET_SECONDS', '').strip() + if not raw: + return _DEFAULT_RETRY_BUDGET_SECONDS + try: + value = float(raw) + except ValueError: + value = math.nan + if not math.isfinite(value) or value < 0: + print('judge retries: invalid M1_JUDGE_RETRY_BUDGET_SECONDS, using the default', file=sys.stderr) + return _DEFAULT_RETRY_BUDGET_SECONDS + return min(value, _MAX_RETRY_BUDGET_SECONDS) + +def _within_budget(deadline: float, delay: float, model) -> bool: + remaining = deadline - time.monotonic() + if delay <= remaining: + return True + print(f'judge call retry budget spent: {model} would wait {delay:.1f}s with {max(remaining, 0.0):.1f}s left of M1_JUDGE_RETRY_BUDGET_SECONDS, failing now', file=sys.stderr) + return False + +def is_empty_verdict(response) -> bool: + data = response.model_dump() if hasattr(response, 'model_dump') else response + if not isinstance(data, dict): + return False + choices = data.get('choices') + if not isinstance(choices, list) or not choices: + return True + first = choices[0] + message = first.get('message') if isinstance(first, dict) else None + if not isinstance(message, dict): + return True + if message.get('tool_calls') or message.get('function_call'): + return False + content = message.get('content') + if isinstance(content, list): + content = ''.join((part.get('text') or '' for part in content if isinstance(part, dict))) + return not (isinstance(content, str) and content.strip()) + +def _matches(exc: BaseException, litellm, names: tuple[str, ...], statuses: frozenset[int]) -> bool: + classes = tuple((cls for cls in (getattr(litellm, name, None) for name in names) if isinstance(cls, type))) + if classes and isinstance(exc, classes): + return True + status = getattr(exc, 'status_code', None) + return type(status) is int and status in statuses + +def is_transient_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _TRANSIENT_ERROR_NAMES, _RETRYABLE_STATUS_CODES) + +def is_auth_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _AUTH_ERROR_NAMES, _AUTH_STATUS_CODES) + +def should_retry(exc: BaseException, litellm, attempt: int, limit: int) -> bool: + if attempt < limit and is_transient_error(exc, litellm): + return True + return attempt < min(limit, _AUTH_RETRIES) and is_auth_error(exc, litellm) + +def _retry_after_seconds(exc: BaseException) -> float | None: + headers = getattr(exc, 'headers', None) + if headers is None: + headers = getattr(getattr(exc, 'response', None), 'headers', None) + if headers is None: + return None + try: + raw = headers.get('retry-after') + if raw is None: + raw = headers.get('Retry-After') + value = float(raw) + except (AttributeError, TypeError, ValueError): + return None + return value if math.isfinite(value) and value >= 0 else None + +def retry_delay(exc: BaseException | None, attempt: int) -> float: + base = min(_MAX_RETRY_DELAY_SECONDS, 2.0 ** (attempt + 1)) + delay = base * (0.5 + random.random()) + retry_after = _retry_after_seconds(exc) if exc is not None else None + if retry_after is not None: + delay = max(delay, min(_MAX_RETRY_DELAY_SECONDS, retry_after)) + return delay + +def _note_retry(model, exc: BaseException, attempt: int, limit: int, delay: float) -> None: + status = getattr(exc, 'status_code', None) + print(f"judge call retry {attempt}/{limit}: {model} {type(exc).__name__} status={(status if type(status) is int else 'n/a')}, waiting {delay:.1f}s", file=sys.stderr) + +def _note_empty(model, response, attempt: int, limit: int, delay: float) -> None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + reason = None + if isinstance(data, dict) and isinstance(data.get('choices'), list) and data['choices']: + first = data['choices'][0] + reason = first.get('finish_reason') if isinstance(first, dict) else None + print(f'judge call retry {attempt}/{limit}: {model} empty verdict (finish_reason={reason}), waiting {delay:.1f}s', file=sys.stderr) + +def install(litellm, *, synchronous: bool=False) -> None: + pins = openrouter_judge_pins() + limit = transient_retry_limit() + empty_limit = empty_response_retry_limit() + deadline = time.monotonic() + retry_budget_seconds() + if synchronous: + original = litellm.completion + + def accounted(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = original(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + time.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + time.sleep(delay) + continue + return response + litellm.completion = accounted + return + original_async = litellm.acompletion + + async def accounted_async(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = await original_async(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + await asyncio.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + await asyncio.sleep(delay) + continue + return response + litellm.acompletion = accounted_async + +def record_agent_usage(attempt, *, model: str, provider: str) -> None: + records: dict[str, tuple[str, dict]] = {} + current_model = model + for filename in getattr(attempt, 'logs', []): + try: + with Path(filename).open() as stream: + for line in stream: + try: + event = json.loads(line) + except (ValueError, TypeError): + continue + if not isinstance(event, dict): + continue + message = event.get('message') or {} + if event.get('type') == 'assistant' and isinstance(message, dict) and isinstance(message.get('usage'), dict): + raw = message['usage'] + cached, written = (raw.get('cache_read_input_tokens'), raw.get('cache_creation_input_tokens')) + if all((type(value) is int and value >= 0 for value in (raw.get('input_tokens'), raw.get('output_tokens')))) and all((value is None or (type(value) is int and value >= 0) for value in (cached, written))): + receipt: dict = {'usage': {'input_uncached_tokens': raw['input_tokens'], 'prompt_tokens': raw['input_tokens'] + cached + written if cached is not None and written is not None else None, 'completion_tokens': raw['output_tokens'], 'prompt_tokens_details': {'cached_tokens': cached, 'cache_creation_tokens': written}}} + receipt['created'] = event.get('timestamp') + creation = raw.get('cache_creation') or {} + hour = creation.get('ephemeral_1h_input_tokens', 0) if isinstance(creation, dict) else 0 + if type(hour) is int and hour > 0: + if hour == written: + receipt['cache_ttl'] = '1h' + else: + receipt['usage_granularity'] = 'mixed_cache_ttl' + records[message.get('id') or json.dumps(raw, sort_keys=True)] = (message.get('model') or current_model, receipt) + payload = event.get('payload') or {} + if not isinstance(payload, dict): + continue + if event.get('type') == 'turn_context' and payload.get('model'): + current_model = payload['model'] + if event.get('type') == 'event_msg' and payload.get('type') == 'token_count': + info = payload.get('info') or {} + raw, total = (info.get('last_token_usage'), info.get('total_token_usage')) + if isinstance(raw, dict) and isinstance(total, dict) and all((type(raw.get(key)) is int and raw.get(key) >= 0 for key in ('input_tokens', 'output_tokens'))): + receipt = {'usage': {'prompt_tokens': raw.get('input_tokens'), 'input_uncached_tokens': raw.get('input_uncached_tokens'), 'input_cache_write_tokens': raw.get('input_cache_write_tokens'), 'completion_tokens': raw.get('output_tokens'), 'prompt_tokens_details': {'cached_tokens': raw.get('cached_input_tokens')}}} + receipt['created'] = event.get('timestamp') + records[json.dumps(total, sort_keys=True)] = (current_model, receipt) + except OSError: + continue + captured_input = captured_output = 0 + input_complete = True + for requested, receipt in records.values(): + requested = requested if '/' in requested else f'{provider}/{requested}' + _record_judge_usage(receipt, requested) + receipt_input = receipt['usage'].get('prompt_tokens') + if receipt_input is None: + input_complete = False + else: + captured_input += receipt_input + captured_output += receipt['usage'].get('completion_tokens') or 0 + total = getattr(attempt, 'usage', {}) or {} + if not records or (input_complete and total.get('input_tokens') != captured_input) or total.get('output_tokens') != captured_output: + _record_judge_usage({'usage': {'prompt_tokens': 0, 'completion_tokens': 0}, 'usage_granularity': 'incomplete_agent_receipts'}, model if '/' in model else f'{provider}/{model}') + +def install_rewardkit_agents() -> None: + import rewardkit.judges as judges + original = judges.get_agent + + def get_accounted_agent(judge, cwd=None): + backend = original(judge, cwd) + run = backend.run + + async def accounted_run(*args, **kwargs): + attempt = await run(*args, **kwargs) + record_agent_usage(attempt, model=judge.model or 'unknown', provider='anthropic' if judge.agent == 'claude-code' else 'openai') + return attempt + setattr(backend, 'run', accounted_run) + return backend + setattr(judges, 'get_agent', get_accounted_agent) +if __name__ == '__main__': + import litellm + if len(sys.argv) > 2 and sys.argv[1] == '--script': + import runpy + install(litellm, synchronous=True) + sys.argv = sys.argv[2:] + runpy.run_path(sys.argv[0], run_name='__main__') + else: + install(litellm) + install_rewardkit_agents() + if Path(__file__).with_name('m1_judge_panel.json').is_file(): + from m1_rewardkit_panel import install_panel + install_panel(Path(__file__).with_name('m1_judge_panel.json')) + if Path(__file__).with_name('m1_judge_jev.json').is_file(): + from m1_rewardkit_jev import install_jev + install_jev(Path(__file__).with_name('m1_judge_jev.json')) + from rewardkit.__main__ import main + main() diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/m1_rewardkit_panel.py b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/m1_rewardkit_panel.py new file mode 100644 index 0000000000000000000000000000000000000000..164cc2ae521cdd368c2e1749d7ed8fe09f4545eb --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/m1_rewardkit_panel.py @@ -0,0 +1,169 @@ +from __future__ import annotations +import asyncio +from contextvars import ContextVar +import json +import math +import os +import sys +from pathlib import Path +from typing import Any +import uuid +_request_audit: ContextVar[tuple[Path, list[str]] | None] = ContextVar('panel_request_audit', default=None) + +class PanelIncompleteError(RuntimeError): + pass + +def _audit_warning(exc: Exception, warnings: list[str]) -> None: + message = f'judge panel audit: diagnostic capture failed ({type(exc).__name__})' + if message not in warnings: + warnings.append(message) + print(message, file=sys.stderr) + +def _write_audit(path: Path, record: dict[str, Any], warnings: list[str], *, append: bool=False) -> None: + try: + text = json.dumps(record, allow_nan=False, default=str) + '\n' + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('a' if append else 'w') as stream: + stream.write(text) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + +def _binary(raw: Any) -> int: + if isinstance(raw, bool): + return int(raw) + if isinstance(raw, int | float) and math.isfinite(raw) and (raw in (0, 1)): + return int(raw) + if isinstance(raw, str): + value = raw.strip().lower() + if value in {'yes', 'true', '1'}: + return 1 + if value in {'no', 'false', '0'}: + return 0 + raise PanelIncompleteError('m1_judge_panel_incomplete: invalid binary vote') + +def validate_votes(scores: list[Any], criteria: list[Any]) -> None: + names = [criterion.name for criterion in criteria] + if len(set(names)) != len(names) or [score.name for score in scores] != names: + raise PanelIncompleteError('m1_judge_panel_incomplete: criterion membership mismatch') + for score, criterion in zip(scores, criteria, strict=True): + if score.error: + raise PanelIncompleteError('m1_judge_panel_incomplete: judge returned an error') + raw = _binary(score.raw) + expected = 1 - raw if criterion.negate else raw + if not math.isfinite(score.value) or score.value != expected: + raise PanelIncompleteError('m1_judge_panel_incomplete: inconsistent binary score') + +async def run_panel(judge: Any, criteria: list[Any], weights: list[float] | None, system_prompt: str | None, *, config: dict[str, Any], run_llm: Any, score_type: Any, audit_dir: Path) -> tuple[list[Any], str, list[str]]: + from rewardkit.models import Binary + if not criteria or any((not isinstance(criterion.output_format, Binary) for criterion in criteria)): + raise ValueError('panel majority voting requires nonempty binary criteria') + group_dir = audit_dir / uuid.uuid4().hex + warnings_out: list[str] = [] + + async def member_call(index: int, member: dict[str, Any]): + member_judge = judge.model_copy(update=member) + evidence: dict[str, Any] = {'member': index + 1, 'judge': member, 'criteria': [criterion.name for criterion in criteria], 'status': 'started'} + path = group_dir / f'judge-{index + 1}.json' + _write_audit(path, evidence, warnings_out) + token = _request_audit.set((group_dir / f'judge-{index + 1}-requests.jsonl', warnings_out)) + try: + scores, output, warnings = await run_llm(member_judge, criteria, weights, system_prompt) + evidence.update(output=output, warnings=warnings) + validate_votes(scores, criteria) + evidence['scores'] = [score.to_dict() for score in scores] + evidence['status'] = 'completed' + return (scores, output, warnings) + except BaseException as exc: + evidence.update(status='failed', error_class=type(exc).__name__) + if isinstance(exc, PanelIncompleteError): + evidence['error'] = str(exc) + raise + finally: + _request_audit.reset(token) + _write_audit(path, evidence, warnings_out) + outcomes = await asyncio.gather(*(member_call(index, member) for index, member in enumerate(config['members'])), return_exceptions=True) + failed = [index + 1 for index, result in enumerate(outcomes) if isinstance(result, BaseException)] + if failed: + _write_audit(group_dir / 'panel.json', {'status': 'incomplete', 'failed_members': failed}, warnings_out) + raise PanelIncompleteError(f'm1_judge_panel_incomplete: failed members {failed}; see panel audit artifacts') + completed = [outcome for outcome in outcomes if not isinstance(outcome, BaseException)] + combined = [] + for index, criterion in enumerate(criteria): + votes = [{'judge': config['members'][member_index], **outcome[0][index].to_dict()} for member_index, outcome in enumerate(completed)] + passes = sum((vote['value'] == 1 for vote in votes)) + value = int(passes >= 2) + combined.append(score_type(name=criterion.name, value=value, raw=bool(1 - value if criterion.negate else value), weight=weights[index] if weights is not None else 1.0, reasoning=f'{passes}/3 judges passed; strict majority requires 2/3.', description=criterion.description, id=criterion.id, negate=criterion.negate, optional=criterion.optional, votes=votes)) + for outcome in completed: + warnings_out.extend(outcome[2]) + audit = {'status': 'completed', 'mode': 'panel', 'aggregation': 'majority', 'required_votes': 2, 'members': config['members'], 'criteria': [score.to_dict() for score in combined]} + output = json.dumps(audit, indent=2, allow_nan=False) + _write_audit(group_dir / 'panel.json', audit, warnings_out) + return (combined, output, warnings_out) + +def install_panel(config_path: Path, *, audit_dir: Path=Path('/logs/verifier/judge-panel')) -> None: + import rewardkit.judges as judges + import rewardkit.reward as reward + from rewardkit.models import LLMJudge, Score + import litellm + config = json.loads(config_path.read_text()) + members = config.get('members') + concurrency = config.get('max_concurrent_llm') + if config.get('mode') != 'panel' or not isinstance(members, list) or len(members) != 3 or (len({member['model'] for member in members}) != 3) or (type(concurrency) is not int) or (not 1 <= concurrency <= 64): + raise ValueError('invalid materialized panel configuration') + if os.environ.get('REWARDKIT_JUDGE') or os.environ.get('REWARDKIT_MODEL'): + raise ValueError('RewardKit environment overrides cannot replace a frozen panel') + + class PanelScore(Score): + votes: list[dict[str, Any]] + + def to_dict(self): + return {**super().to_dict(), 'votes': self.votes} + original_llm = judges.arun_llm + original_call = judges._arun_llm_call + original_details = reward.Reward.to_detail_dict + original_completion = litellm.acompletion + active_loop = None + semaphore = None + + async def captured_completion(*args, **kwargs): + context = _request_audit.get() + record = {'requested_model': kwargs.get('model')} + response = None + try: + response = await original_completion(*args, **kwargs) + return response + except BaseException as exc: + record['error_class'] = type(exc).__name__ + raise + finally: + if context is not None: + path, warnings = context + try: + if response is not None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + record.update(response_model=data.get('model'), choices=data.get('choices')) + _write_audit(path, record, warnings, append=True) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + + async def bounded_call(*args, **kwargs): + nonlocal active_loop, semaphore + loop = asyncio.get_running_loop() + if active_loop is not loop: + active_loop, semaphore = (loop, asyncio.Semaphore(concurrency)) + assert semaphore is not None + async with semaphore: + return await original_call(*args, **kwargs) + + async def panel_call(judge, criteria, weights=None, system_prompt=None): + return await run_panel(judge, criteria, weights, system_prompt, config=config, run_llm=original_llm, score_type=PanelScore, audit_dir=audit_dir) + + def panel_details(self, score): + detail = original_details(self, score) + if isinstance(self.judge, LLMJudge): + detail.update(kind='llm_panel', judge=config, aggregation='majority', required_votes=2) + return detail + setattr(reward, 'arun_llm', panel_call) + setattr(judges, '_arun_llm_call', bounded_call) + setattr(litellm, 'acompletion', captured_completion) + reward.Reward.to_detail_dict = panel_details diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/normalize_reward.py b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/normalize_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..91817ef00ea9152ca57f0030d8e879eb850ddff0 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/normalize_reward.py @@ -0,0 +1,71 @@ +from __future__ import annotations +import argparse +import json +from pathlib import Path +from typing import Any + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument('--raw-details', required=True) + parser.add_argument('--rubric', required=True) + parser.add_argument('--reward-out', required=True) + parser.add_argument('--details-out', required=True) + args = parser.parse_args() + raw_details = _load_json(Path(args.raw_details)) + rubric = _load_json(Path(args.rubric)) + criteria = rubric['criteria'] + raw_by_name = _raw_criteria_by_name(raw_details) + positive_total = sum((float(item['score']) for item in criteria if float(item['score']) > 0)) + if positive_total <= 0: + raise ValueError('rubric must contain at least one positive score') + earned = 0.0 + normalized_criteria: list[dict[str, Any]] = [] + for item in criteria: + signed_score = float(item['score']) + raw = raw_by_name.get(item['name'], {}) + value = _coerce_score(raw.get('value', 0.0)) + contribution = value * signed_score + earned += contribution + normalized_criteria.append({'name': item['name'], 'value': value, 'raw': raw.get('raw'), 'weight': signed_score, 'signed_score': signed_score, 'polarity': item['polarity'], 'contribution': contribution, 'description': item['description'], 'source': item.get('source', ''), 'justification': item.get('justification', ''), 'metadata': item.get('metadata', {}), 'reasoning': raw.get('reasoning'), 'judge_reasoning': raw.get('reasoning'), 'judge_error': raw.get('error'), **({'votes': raw['votes']} if 'votes' in raw else {})}) + unclamped = earned / positive_total + reward = max(0.0, min(1.0, unclamped)) + reward_out = {'correctness': reward} + details_out = {'correctness': {'score': reward, 'kind': 'signed_score', 'criteria': normalized_criteria, 'aggregation': {'method': 'signed_score_ratio_clamped', 'earned': earned, 'positive_total': positive_total, 'unclamped': unclamped, 'clamped': reward}, 'raw_rewardkit': raw_details}} + _write_json(Path(args.reward_out), reward_out) + _write_json(Path(args.details_out), details_out) + +def _load_json(path: Path) -> Any: + return json.loads(path.read_text()) + +def _write_json(path: Path, data: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data, indent=2) + '\n') + +def _raw_criteria_by_name(details: dict[str, Any]) -> dict[str, dict[str, Any]]: + out: dict[str, dict[str, Any]] = {} + for reward in details.values(): + for item in _iter_raw_criteria(reward): + name = item.get('name') + if isinstance(name, str): + out[name] = item + return out + +def _iter_raw_criteria(value: Any): + if isinstance(value, list): + for item in value: + yield from _iter_raw_criteria(item) + return + if not isinstance(value, dict): + return + for item in value.get('criteria') or []: + if isinstance(item, dict): + yield item + +def _coerce_score(value: Any) -> float: + if isinstance(value, bool): + return 1.0 if value else 0.0 + if isinstance(value, int | float): + return max(0.0, min(1.0, float(value))) + return 0.0 +if __name__ == '__main__': + main() diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/raw_correctness/agent_prompt.md b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/raw_correctness/agent_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..ca489c065bafd5d10e764f033c9dfd1195933db3 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/raw_correctness/agent_prompt.md @@ -0,0 +1,10 @@ +You are grading the submitted legal analysis against the criteria below. + +Read `/logs/artifacts/answer.md`, the answer captured by the verifier, before +assigning any scores. Evaluate that file as the submission. Other files in +`/app` may supply context, but must not replace the submitted answer. Do not +modify the submission. If it is missing or empty, state that in your reasoning +and apply the criteria to that missing or empty submission. Preserve each +criterion's stated positive or penalty polarity. + +{criteria} diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/raw_correctness/criterion_1.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/raw_correctness/criterion_1.toml new file mode 100644 index 0000000000000000000000000000000000000000..3fec35c963c1bf1d5f993ee12532da1920e7ed39 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/raw_correctness/criterion_1.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_1" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that IHP lacked a validly designated medical director under Cal. Health & Safety Code § 1367.01(c) (2026) during the period from May 7 to May 13, 2026." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/raw_correctness/criterion_2.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/raw_correctness/criterion_2.toml new file mode 100644 index 0000000000000000000000000000000000000000..dfb359796180b8a7232fe4ad6a185519d5fdf05a --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/raw_correctness/criterion_2.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_2" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that the requirements of Cal. Health & Safety Code § 1367.01(e) (2026) turn on the licensure of the reviewing physician." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/raw_correctness/criterion_3.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/raw_correctness/criterion_3.toml new file mode 100644 index 0000000000000000000000000000000000000000..a90d503d381642b7c36fee8e556e3df8b0919a15 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/raw_correctness/criterion_3.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_3" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that the lack of a validly designated medical director was cured prospectively by the Board action of May 13, 2026." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/raw_correctness/criterion_4.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/raw_correctness/criterion_4.toml new file mode 100644 index 0000000000000000000000000000000000000000..56008bade4c21b06ad7ba40ce657f0cb4fa2a683 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/raw_correctness/criterion_4.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_4" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that the omnibus ratification clause in Resolution 2026-14 does not retroactively cure actions taken during the period from May 7 to May 13, 2026 under the Bylaws." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/raw_correctness/criterion_5.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/raw_correctness/criterion_5.toml new file mode 100644 index 0000000000000000000000000000000000000000..239d735704ac8153dc82165e002c6b5c627894c6 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/raw_correctness/criterion_5.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_5" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: Mentions that utilization management determinations made during the period from May 7 to May 13, 2026 are invalid." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/raw_correctness/criterion_6.toml b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/raw_correctness/criterion_6.toml new file mode 100644 index 0000000000000000000000000000000000000000..38c1f949681fdfc5ada9bf9f7ea6312cb6187cca --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/raw_correctness/criterion_6.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_6" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: Mentions that utilization management determinations made during the period from May 7 to May 13, 2026 require re-review." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/test.sh b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..66a509a7bcdbe412851f3a012a5ba7b16cf0925b --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/steps/assignment-4/tests/test.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +set -euo pipefail + +mkdir -p /logs/artifacts /logs/verifier/raw + +python3 - <<'PYEOF' +import json +import shutil +from pathlib import Path + + +def has_text(path: Path) -> bool: + return path.exists() and path.is_file() and bool(path.read_text(errors="replace").strip()) + + +def fallback_paths(answer_path: Path) -> list[Path]: + paths = [] + try: + relative = answer_path.relative_to("/app") + paths.append(Path("/app/app") / relative) + except ValueError: + pass + return [path for path in paths if path != answer_path] + + +config = json.loads(Path("/tests/fixtures/config.json").read_text()) +answer_path = Path(config["answer_path"]) +artifact_answer = Path("/logs/artifacts/answer.md") +artifact_answer.parent.mkdir(parents=True, exist_ok=True) +if has_text(answer_path): + shutil.copyfile(answer_path, artifact_answer) +else: + for candidate in fallback_paths(answer_path): + if has_text(candidate): + shutil.copyfile(candidate, artifact_answer) + break + else: + artifact_answer.write_text("") + +# Harbor collects /logs/artifacts when the agent step ends, which is before this +# script runs, so the copy above never reaches the uploaded artifacts. /logs/verifier +# is uploaded after the verifier phase, so persist the graded answer there too. +verifier_answer = Path("/logs/verifier/answer.md") +verifier_answer.parent.mkdir(parents=True, exist_ok=True) +shutil.copyfile(artifact_answer, verifier_answer) +PYEOF + +uv run --no-project --with 'harbor-rewardkit[all]==0.2.0' python /tests/m1_rewardkit_accounting.py /tests/raw_correctness \ + --workspace /app \ + --output /logs/verifier/raw/reward.json \ + --max-concurrent-llm "${MAX_CONCURRENT_LLM:-4}" \ + --max-concurrent-agent "${M1_MAX_CONCURRENT_AGENT:-1}" + +python /tests/normalize_reward.py \ + --raw-details /logs/verifier/raw/reward-details.json \ + --rubric /tests/fixtures/rubric.json \ + --reward-out /logs/verifier/reward.json \ + --details-out /logs/verifier/reward-details.json diff --git a/tasks/lrb-interim-cmo-appointment-governance/task.toml b/tasks/lrb-interim-cmo-appointment-governance/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..47dd7ec506cc565404191011b07ca0efd21df7d6 --- /dev/null +++ b/tasks/lrb-interim-cmo-appointment-governance/task.toml @@ -0,0 +1,124 @@ +schema_version = "1.1" +multi_step_reward_strategy = "mean" + +[task] +name = "micro1/lrb-interim-cmo-appointment-governance" + +[metadata] +benchmark = "LegalReasonBench" +title = "Interim CMO Appointment: Governance and Compliance Analysis" +practice_area = "Corporate governance" +research_universe = "closed-universe" +task_version = "32" +overall_reward = "points-weighted across assignments: sum of earned signed points over sum of positive points, clamped to [0, 1]. Harbor multi_step_reward_strategy=mean is diagnostic only. See scripts/score_matter.py." + +[agent] +timeout_sec = 10800.0 + +[environment] +build_timeout_sec = 900.0 +cpus = 2 +memory_mb = 4096 +storage_mb = 8192 +workdir = "/app" +allow_internet = true + +[environment.env] +OPENCODE_ENABLE_EXA = "${OPENCODE_ENABLE_EXA:-1}" + +[[steps]] +name = "assignment-1" +artifacts = ["/app/response1.md"] + +[steps.agent] +timeout_sec = 10800.0 + +[steps.verifier] +timeout_sec = 1800.0 + +[steps.verifier.env] +OPENAI_API_KEY = "${OPENAI_API_KEY:-}" +ANTHROPIC_API_KEY = "${ANTHROPIC_API_KEY:-}" +GOOGLE_API_KEY = "${GOOGLE_API_KEY:-}" +GEMINI_API_KEY = "${GEMINI_API_KEY:-}" +JUDGE_MODEL = "openai/gpt-5.6-terra" +JUDGE_REASONING_EFFORT = "medium" +JUDGE_TIMEOUT = "1500" +MAX_CONCURRENT_LLM = "12" +M1_MAX_CONCURRENT_AGENT = "1" +M1_JUDGE_TRANSIENT_RETRIES = "12" +M1_JUDGE_EMPTY_RESPONSE_RETRIES = "3" +M1_JUDGE_RETRY_BUDGET_SECONDS = "900" + +[[steps]] +name = "assignment-2" +artifacts = ["/app/response2.md"] + +[steps.agent] +timeout_sec = 10800.0 + +[steps.verifier] +timeout_sec = 1800.0 + +[steps.verifier.env] +OPENAI_API_KEY = "${OPENAI_API_KEY:-}" +ANTHROPIC_API_KEY = "${ANTHROPIC_API_KEY:-}" +GOOGLE_API_KEY = "${GOOGLE_API_KEY:-}" +GEMINI_API_KEY = "${GEMINI_API_KEY:-}" +JUDGE_MODEL = "openai/gpt-5.6-terra" +JUDGE_REASONING_EFFORT = "medium" +JUDGE_TIMEOUT = "1500" +MAX_CONCURRENT_LLM = "12" +M1_MAX_CONCURRENT_AGENT = "1" +M1_JUDGE_TRANSIENT_RETRIES = "12" +M1_JUDGE_EMPTY_RESPONSE_RETRIES = "3" +M1_JUDGE_RETRY_BUDGET_SECONDS = "900" + +[[steps]] +name = "assignment-3" +artifacts = ["/app/response3.md"] + +[steps.agent] +timeout_sec = 10800.0 + +[steps.verifier] +timeout_sec = 1800.0 + +[steps.verifier.env] +OPENAI_API_KEY = "${OPENAI_API_KEY:-}" +ANTHROPIC_API_KEY = "${ANTHROPIC_API_KEY:-}" +GOOGLE_API_KEY = "${GOOGLE_API_KEY:-}" +GEMINI_API_KEY = "${GEMINI_API_KEY:-}" +JUDGE_MODEL = "openai/gpt-5.6-terra" +JUDGE_REASONING_EFFORT = "medium" +JUDGE_TIMEOUT = "1500" +MAX_CONCURRENT_LLM = "12" +M1_MAX_CONCURRENT_AGENT = "1" +M1_JUDGE_TRANSIENT_RETRIES = "12" +M1_JUDGE_EMPTY_RESPONSE_RETRIES = "3" +M1_JUDGE_RETRY_BUDGET_SECONDS = "900" + +[[steps]] +name = "assignment-4" +artifacts = ["/app/response4.md"] + +[steps.agent] +timeout_sec = 10800.0 + +[steps.verifier] +timeout_sec = 1800.0 + +[steps.verifier.env] +OPENAI_API_KEY = "${OPENAI_API_KEY:-}" +ANTHROPIC_API_KEY = "${ANTHROPIC_API_KEY:-}" +GOOGLE_API_KEY = "${GOOGLE_API_KEY:-}" +GEMINI_API_KEY = "${GEMINI_API_KEY:-}" +JUDGE_MODEL = "openai/gpt-5.6-terra" +JUDGE_REASONING_EFFORT = "medium" +JUDGE_TIMEOUT = "1500" +MAX_CONCURRENT_LLM = "12" +M1_MAX_CONCURRENT_AGENT = "1" +M1_JUDGE_TRANSIENT_RETRIES = "12" +M1_JUDGE_EMPTY_RESPONSE_RETRIES = "3" +M1_JUDGE_RETRY_BUDGET_SECONDS = "900" + diff --git a/tasks/lrb-vicar-trial-jury-instructions/environment/Dockerfile b/tasks/lrb-vicar-trial-jury-instructions/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c481aae22685617adcf60d0de6e473ce9019975a --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/environment/Dockerfile @@ -0,0 +1,29 @@ +FROM python:3.13-slim-bookworm + +RUN apt-get update && apt-get install -y --no-install-recommends \ + bash \ + ca-certificates \ + curl \ + file \ + git \ + libreoffice-calc \ + libreoffice-impress \ + libreoffice-writer \ + pandoc \ + poppler-utils \ + unzip \ + fonts-dejavu \ + && rm -rf /var/lib/apt/lists/* + +RUN python -m pip install --no-cache-dir \ + uv \ + openpyxl \ + pandas \ + pdfplumber \ + pypdf \ + python-docx \ + python-pptx \ + xlrd + +WORKDIR /app +RUN ln -s . /app/app diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/instruction.md b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..888f19d7f899b4eb31a5446979240594ea92361f --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/instruction.md @@ -0,0 +1,73 @@ +# OTB Gang VICAR Trial Jury Instructions — Appeal brief re: justification instruction + +Matter: OTB Gang VICAR Trial Jury Instructions + +You are a senior legal analyst operating autonomously. You are completing a multi-step legal reasoning task. Follow the role, factual record, instructions, and deliverable requirements provided in the Task and each Assignment. + +Each Assignment may require a different legal deliverable. Follow the requirements specific to that Assignment. + +## Word limits for court briefs + +- A brief in support of or in response to a motion may not exceed **8,750 words**. +- A reply brief may not exceed **3,500 words**. +- For a motion for reconsideration, a brief in support of or in response to the motion may not exceed **3,500 words**, and a reply brief may not exceed **1,750 words**. +- If an Assignment specifies a stricter word limit, follow the stricter limit. + +These word limits do not apply to legal memoranda or other non-court-filing deliverables unless the Assignment expressly provides otherwise. + +Complete the task end-to-end without asking for confirmation, permission, or clarification. + +Use the uploaded matter documents in `/app/attachments/` as your primary case file. You also have internet access via OpenCode's `websearch` tool; use it to research any statutes, regulations, cases, administrative guidance, or secondary authorities that are not supplied as attachments. Cite any authority you rely on in the format requested by the prompt. + +For document inspection: +- PDF: `pdftotext /app/attachments/.pdf -` +- DOCX: `pandoc /app/attachments/.docx -t markdown` +- XLSX/CSV: use Python with `openpyxl` or `pandas` +- If extraction is unreliable, inspect the raw file with Python libraries or convert/render the relevant pages. + +Write the final complete legal deliverable for this assignment to `/app/response1.md`. The verifier reads only that file. + +## Attachments + +- `/app/attachments/Facts.pdf`: Facts +- `/app/attachments/White Horse.pdf`: United States v. White Horse, No. 21-2871, slip op. (8th Cir. June 3, 2022) +- `/app/attachments/702.11.pdf`: Iowa Code § 702.11 (2020) +- `/app/attachments/704.pdf`: Iowa Code ch. 704 (2020) +- `/app/attachments/706.1.pdf`: Iowa Code § 706.1 (2020) +- `/app/attachments/707.11.pdf`: Iowa Code § 707.11 (2020) +- `/app/attachments/708.6.pdf`: Iowa Code § 708.6 (2020) +- `/app/attachments/Ellison.pdf`: State v. Ellison, No. 21-0657, slip op. (Iowa Feb. 3, 2023) +- `/app/attachments/Kehoe.pdf`: United States v. Kehoe, No. 99-2897, slip op. (8th Cir. Nov. 8 2002) +- `/app/attachments/Poe.pdf`: United States v. Poe, No. 05-2914, slip op. (8th Cir. Apr. 6. 2006) +- `/app/attachments/Patton State Plea.pdf`: Patton State Plea + + +## Prompt + +You are an Assistant United States Attorney, practicing law in the Southern District of Iowa. You received the following email from your direct supervisor. + +ASSIGNMENT #1 +From: Molly Short (Molly.Short@usdoj.gov) +To: Alexa Pierre (Alexa.Pierre@usdoj.gov) +Re: OTB appeal argument section +Date: July 15, 2026 + +Good morning, Alexa, + +Thanks for agreeing to help me draft a section of this appellate brief! You are going to be handling the response to Defendant Raekwon's Patton's argument. Patton was an OTB member, who was involved in a gang-related shooting on May 10, 2020. He was charged with, among other things, attempted murder in aid of racketeering under the VICAR statute (18 U.S.C. § 1959). Although there were a ton of issues at the trial and sentencing, Patton only disputes one major issue on appeal. He contends that the court should have given his requested justification instruction. In short, he argued that the evidence showed that Patton was acting in self-defense when he fired at Raysean Nelson's car. The court declined to give the instruction, and we're taking it up on appeal. + +Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law. I've already drafted the facts section of this brief, which I've provided below. You can cite to that document, and I will take care of the citations to the trial transcript or rest of the record. That should save you some time. Below is everything you'll need for this project. Our brief is due July 29, 2026. + +Facts (Facts.pdf) +Iowa Code § 702.11 (2020) (702.11.pdf) +Iowa Code ch. 704 (2020) (704.pdf) +Iowa Code § 706.1 (2020) (706.1.pdf) +Iowa Code § 707.11 (2020) (707.11.pdf) +Iowa Code § 708.6 (2020) (708.6.pdf) +Patton State Plea (Patton State Plea.pdf) +State v. Ellison, No. 21-0657, slip op. (Iowa Feb. 3, 2023) (Ellison.pdf) +United States v. Kehoe, No. 99-2897, slip op. (8th Cir. Nov. 8 2002) (Kehoe.pdf) +United States v. Poe, No. 05-2914, slip op. (8th Cir. Apr. 6. 2006) (Poe.pdf) +United States v. White Horse, No. 21-2871, slip op. (8th Cir. June 3, 2022) (White Horse.pdf) + +Be sure to limit your review for the Assignment to the attached documents. Do not rely on, reference, or infer any legal authority, factual information, or data beyond what is contained in these uploaded files. If a document is not uploaded, it does not exist for purposes of this analysis. All citations must reference the document by its exact name as listed above, followed by the page number, section, or paragraph number if applicable. Do not cite external websites, databases, or any source outside the uploaded materials. diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/solution/solve.sh b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7710414a6da6d0ad740717c8c85a9af850d5da33 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/solution/solve.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# No oracle solution ships with LegalReasonBench. The verifier grades the +# agent's own legal deliverable for this assignment against the rubric. +echo "no oracle solution" diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/fixtures/config.json b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/fixtures/config.json new file mode 100644 index 0000000000000000000000000000000000000000..c59983ad2f6fd71fbacbf7abb8e9d38d85628133 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/fixtures/config.json @@ -0,0 +1,408 @@ +{ + "task_id": "lrb-vicar-trial-jury-instructions", + "title": "OTB Gang VICAR Trial Jury Instructions", + "domain": "", + "matter": "OTB Gang VICAR Trial Jury Instructions", + "judge": { + "max_concurrent_llm": 12, + "mode": "panel", + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ], + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + "step_index": 1, + "step_name": "assignment-1", + "step_title": "Appeal brief re: justification instruction", + "prompt": "You are an Assistant United States Attorney, practicing law in the Southern District of Iowa. You received the following email from your direct supervisor.\n\nASSIGNMENT #1\nFrom: Molly Short (Molly.Short@usdoj.gov)\nTo: Alexa Pierre (Alexa.Pierre@usdoj.gov)\nRe: OTB appeal argument section\nDate: July 15, 2026\n\nGood morning, Alexa,\n\nThanks for agreeing to help me draft a section of this appellate brief! You are going to be handling the response to Defendant Raekwon's Patton's argument. Patton was an OTB member, who was involved in a gang-related shooting on May 10, 2020. He was charged with, among other things, attempted murder in aid of racketeering under the VICAR statute (18 U.S.C. \u00a7 1959). Although there were a ton of issues at the trial and sentencing, Patton only disputes one major issue on appeal. He contends that the court should have given his requested justification instruction. In short, he argued that the evidence showed that Patton was acting in self-defense when he fired at Raysean Nelson's car. The court declined to give the instruction, and we're taking it up on appeal. \n\nPlease draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law. I've already drafted the facts section of this brief, which I've provided below. You can cite to that document, and I will take care of the citations to the trial transcript or rest of the record. That should save you some time. Below is everything you'll need for this project. Our brief is due July 29, 2026.\n\nFacts (Facts.pdf)\nIowa Code \u00a7 702.11 (2020) (702.11.pdf)\nIowa Code ch. 704 (2020) (704.pdf)\nIowa Code \u00a7 706.1 (2020) (706.1.pdf)\nIowa Code \u00a7 707.11 (2020) (707.11.pdf)\nIowa Code \u00a7 708.6 (2020) (708.6.pdf)\nPatton State Plea (Patton State Plea.pdf)\nState v. Ellison, No. 21-0657, slip op. (Iowa Feb. 3, 2023) (Ellison.pdf)\nUnited States v. Kehoe, No. 99-2897, slip op. (8th Cir. Nov. 8 2002) (Kehoe.pdf)\nUnited States v. Poe, No. 05-2914, slip op. (8th Cir. Apr. 6. 2006) (Poe.pdf)\nUnited States v. White Horse, No. 21-2871, slip op. (8th Cir. June 3, 2022) (White Horse.pdf)\n\nBe sure to limit your review for the Assignment to the attached documents. Do not rely on, reference, or infer any legal authority, factual information, or data beyond what is contained in these uploaded files. If a document is not uploaded, it does not exist for purposes of this analysis. All citations must reference the document by its exact name as listed above, followed by the page number, section, or paragraph number if applicable. Do not cite external websites, databases, or any source outside the uploaded materials.", + "attachments": [ + { + "filename": "Facts.pdf", + "description": "Facts", + "metadata": {}, + "path": "/app/attachments/Facts.pdf" + }, + { + "filename": "White Horse.pdf", + "description": "United States v. White Horse, No. 21-2871, slip op. (8th Cir. June 3, 2022)", + "metadata": {}, + "path": "/app/attachments/White Horse.pdf" + }, + { + "filename": "702.11.pdf", + "description": "Iowa Code \u00a7 702.11 (2020)", + "metadata": {}, + "path": "/app/attachments/702.11.pdf" + }, + { + "filename": "704.pdf", + "description": "Iowa Code ch. 704 (2020)", + "metadata": {}, + "path": "/app/attachments/704.pdf" + }, + { + "filename": "706.1.pdf", + "description": "Iowa Code \u00a7 706.1 (2020)", + "metadata": {}, + "path": "/app/attachments/706.1.pdf" + }, + { + "filename": "707.11.pdf", + "description": "Iowa Code \u00a7 707.11 (2020)", + "metadata": {}, + "path": "/app/attachments/707.11.pdf" + }, + { + "filename": "708.6.pdf", + "description": "Iowa Code \u00a7 708.6 (2020)", + "metadata": {}, + "path": "/app/attachments/708.6.pdf" + }, + { + "filename": "Ellison.pdf", + "description": "State v. Ellison, No. 21-0657, slip op. (Iowa Feb. 3, 2023)", + "metadata": {}, + "path": "/app/attachments/Ellison.pdf" + }, + { + "filename": "Kehoe.pdf", + "description": "United States v. Kehoe, No. 99-2897, slip op. (8th Cir. Nov. 8 2002)", + "metadata": {}, + "path": "/app/attachments/Kehoe.pdf" + }, + { + "filename": "Poe.pdf", + "description": "United States v. Poe, No. 05-2914, slip op. (8th Cir. Apr. 6. 2006)", + "metadata": {}, + "path": "/app/attachments/Poe.pdf" + }, + { + "filename": "Patton State Plea.pdf", + "description": "Patton State Plea", + "metadata": {}, + "path": "/app/attachments/Patton State Plea.pdf" + } + ], + "rubric": [ + { + "name": "criterion_1", + "description": "Identifies that the district court's refusal to submit a justification instruction is reviewed de novo.", + "source": "United States v. Poe, No. 05-2914, slip op. at 3 (8th Cir. Apr. 6. 2006) (Poe.pdf) (\u201cWhether there is sufficient evidence to support the submission of an instruction on an affirmative defense is a question of law which we review de novo.\u201d).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_2", + "description": "Identifies that the district court's refusal to give a jury instruction is reviewed for abuse of discretion.", + "source": "United States v. White Horse, No. 21-2871, slip op. at 2-3 (8th Cir. June 3, 2022) (White Horse.pdf) (speaking of jury instructions as drafted generally, not the district court's consideration of substantial evidence to warrant submission of a justification instruction and providing that the court \"review[s] jury instructions for an abuse of discretion\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": -30.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_3", + "description": "Identifies that the predicate offense for a federal attempted murder in aid of racketeering charge can come from state law.", + "source": "United States v. Kehoe, No. 99-2897, slip op. at 10 (8th Cir. Nov. 8 2002) (Kehoe.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_5", + "description": "Identifies that justification is a defense to an Iowa attempted murder charge.", + "source": "Iowa Code \u00a7 707.11(1) (2020) (707.11.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_7", + "description": "States that a person who is engaged in illegal activity has a duty to retreat before using force.", + "source": "State v. Ellison, No. 21-0657, slip op. at 8 (Iowa Feb. 3, 2023) (Ellison.pdf); Iowa Code ch. 704, \u00a7 704.1(3)(2020) (704.pdf).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_8", + "description": "States that Patton was engaged in the illegal activity of possessing a firearm as a felon.", + "source": "Facts pp. 7-8, 10 (Facts.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_9", + "description": "States that Patton had a duty to retreat before using deadly force.", + "source": "State v. Ellison, No. 21-0657, slip op. at 8 (Iowa Feb. 3, 2023) (Ellison.pdf); Iowa Code ch. 704 \u00a7 704.1(3) (2020) (704.pdf).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_10", + "description": "Mentions that the OTB group had rolled the windows down before reaching Nelson.", + "source": "Facts p. 7 (Facts.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_11", + "description": "Mentions that Patton was hanging out the window with a firearm.", + "source": "Facts pp. 7-8 (Facts.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_12", + "description": "Mentions that Nelson's car was already stopped when Patton fired his gun.", + "source": "Facts pp. 7-8 (Facts.pdf).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 15.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_13", + "description": "States that the OTB group could have driven away.", + "source": "Facts pp. 7-8 (Facts.pdf) (Nelson's car was stopped; Nelson was outside of the car; the OTB group remained in a moving car).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 15.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_14", + "description": "States that the only reasonable inference from Patton's actions is that he intended to fire regardless of what Nelson did.", + "source": "Facts pp. 6-8 (Facts.pdf) (Patton was armed with a gun, they chased Nelson across the city, rolled the windows down before being fired at).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 25.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_16", + "description": "States that Patton's actions on May 10, 2020 show he engaged in a pre-planned drive-by shooting.", + "source": "Facts pp. 6-8 (Facts.pdf) (Patton was armed with a gun, they chased Nelson across the city, rolled the windows down before being fired at).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 20.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_15", + "description": "States that Patton's shooting at Nelson was not an act of justified self-defense.", + "source": "Iowa Code ch. 704 \u00a7 704.6(3) (2020) (704.pdf) (\u201cThe defense of justification is not available to . . . [o]ne who initially provokes the use of force against oneself by one\u2019s unlawful acts . . . .\u201d).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Conclusion" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_17", + "description": "Identifies that a defendant is not entitled to a justification defense if he is participating in a forcible felony.", + "source": "Iowa Code ch. 704, \u00a7 704.6(1) (2020) (704.pdf).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_18", + "description": "Mentions that a forcible felony under Iowa law includes felonious assault.", + "source": "Iowa Code \u00a7 702.11(1) (2020) (702.11.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_28", + "description": "Mentions that Patton was committing the crime of intimidation with dangerous weapon on May 10, 2020.", + "source": "Iowa Code \u00a7 708.6 (2020) (708.6.pdf); Facts pp. 7-8 (Facts.pdf).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\" Obviously, the government's position is that Patton committed the crime of intimidation with a dangerous weapon, in addition to attempted murder. However, the whole crux of the argument on appeal is whether Patton's shooting was justified. Essentially, arguing the intimidation with a dangerous weapon precludes the instruction is akin to arguing Patton can't get the justification instruction because he was engaged in the felonious assault of attempted murder.", + "metadata": { + "irac_section": "Application" + }, + "score": -20.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_29", + "description": "States that Patton's commission of intimidation with a dangerous weapon precludes a justification instruction.", + "source": "Iowa Code ch. 704, \u00a7 704.6(1) (2020) (704.pdf); Iowa Code \u00a7 708.6 (2020) (708.6.pdf).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\" Obviously, the government's position is that Patton committed the crime of intimidation with a dangerous weapon, in addition to attempted murder. However, the whole crux of the argument on appeal is whether Patton's shooting was justified. Essentially, arguing the intimidation with a dangerous weapon precludes the instruction is akin to arguing Patton can't get the justification instruction because he was engaged in the felonious assault of attempted murder.", + "metadata": { + "irac_section": "Conclusion" + }, + "score": -10.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_19", + "description": "Mentions that Patton pled guilty in state court to conspiracy to commit a forcible felony on May 10, 2020.", + "source": "Patton State Plea pp. 4-6 (Patton State Plea.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_20", + "description": "Mentions that Patton admitted he planned with others to commit a shooting on May 10, 2020.", + "source": "Patton State Plea p. 5 (Patton State Plea.pdf); Iowa Code ch. 706, \u00a7 706.1(1) (2020) (706.1.pdf).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_21", + "description": "States that Patton's commission of conspiracy to commit a forcible felony precludes a justification defense.", + "source": "Patton State Plea p. 5 (Patton State Plea.pdf); Iowa Code ch. 704, \u00a7 704.6(1) (2020) (704.pdf); Iowa Code ch. 706, \u00a7 706.1(1) (2020) (706.1.pdf).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Conclusion" + }, + "score": 15.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_23", + "description": "Mentions that Patton pled guilty in state court to intimidation with a dangerous weapon.", + "source": "Patton State Plea pp. 1-3 (Patton State Plea.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"Patton's written guilty plea indicates that he committed the offense of intimidation with a dangerous weapon on April 13, 2020. Because that involved a different shooting, it's not relevant to whether Patton should receive a justification instruction for the May 10, 2020 shooting.", + "metadata": { + "irac_section": "Application" + }, + "score": -5.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_25", + "description": "Mentions that Patton lacked a reasonable belief that deadly force was necessary.", + "source": "Facts p. 7 (Facts.pdf); Iowa Code ch. 704, \u00a7 704.3 (2020) (704.pdf).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\" The evidence at trial suggests that, at a minimum, it is unclear which side fired first. Because some evidence supports that Nelson fired first, Patton might have reasonably believed deadly force was necessary. The better arguments on appeal relate to Patton's duty to retreat or pre-planning of the shooting.", + "metadata": { + "irac_section": "Application" + }, + "score": -20.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_27", + "description": "Mentions that Patton lacked a reasonable belief that he was subject to an imminent unlawful threat.", + "source": "Facts p. 7 (Facts.pdf); Iowa Code ch. 704, \u00a7 704.6(1) (2020) (704.pdf).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\" The evidence at trial suggests that, at a minimum, it is unclear which side fired first. Because some evidence supports that Nelson fired first, Patton might have had a fear of imminent unlawful threat. The better arguments on appeal relate to Patton's duty to retreat or pre-planning of the shooting.", + "metadata": { + "irac_section": "Application" + }, + "score": -20.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_26", + "description": "States that the district court was within its discretion to refuse to provide the justification instruction.", + "source": "United States v. White Horse, No. 21-2871, slip op. at 2-3 (8th Cir. June 3, 2022) (White Horse.pdf) (speaking of jury instructions as drafted generally, not the district court's consideration of substantial evidence to warrant submission of a justification instruction); United States v. Poe, No. 05-2914, slip op. at 3 (8th Cir. Apr. 6. 2006) (Poe.pdf) (\u201cWhether there is sufficient evidence to support the submission of an instruction on an affirmative defense is a question of law,\" rather than a matter of discretion).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\" This conclusion uses the wrong standard of review for the district court's failure to give a justification instruction.", + "metadata": { + "irac_section": "Conclusion" + }, + "score": -30.0, + "polarity": "negative", + "raw_weight": 1.0 + } + ], + "answer_path": "/app/response1.md", + "answer_relative_path": "response1.md", + "is_followon": false, + "prev_answer_path": "" +} diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/fixtures/rubric.json b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/fixtures/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..b2c7bbe82a250748bd7f3f15037bbe9c5b919503 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/fixtures/rubric.json @@ -0,0 +1,304 @@ +{ + "criteria": [ + { + "name": "criterion_1", + "description": "Identifies that the district court's refusal to submit a justification instruction is reviewed de novo.", + "source": "United States v. Poe, No. 05-2914, slip op. at 3 (8th Cir. Apr. 6. 2006) (Poe.pdf) (\u201cWhether there is sufficient evidence to support the submission of an instruction on an affirmative defense is a question of law which we review de novo.\u201d).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_2", + "description": "Identifies that the district court's refusal to give a jury instruction is reviewed for abuse of discretion.", + "source": "United States v. White Horse, No. 21-2871, slip op. at 2-3 (8th Cir. June 3, 2022) (White Horse.pdf) (speaking of jury instructions as drafted generally, not the district court's consideration of substantial evidence to warrant submission of a justification instruction and providing that the court \"review[s] jury instructions for an abuse of discretion\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": -30.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_3", + "description": "Identifies that the predicate offense for a federal attempted murder in aid of racketeering charge can come from state law.", + "source": "United States v. Kehoe, No. 99-2897, slip op. at 10 (8th Cir. Nov. 8 2002) (Kehoe.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_5", + "description": "Identifies that justification is a defense to an Iowa attempted murder charge.", + "source": "Iowa Code \u00a7 707.11(1) (2020) (707.11.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_7", + "description": "States that a person who is engaged in illegal activity has a duty to retreat before using force.", + "source": "State v. Ellison, No. 21-0657, slip op. at 8 (Iowa Feb. 3, 2023) (Ellison.pdf); Iowa Code ch. 704, \u00a7 704.1(3)(2020) (704.pdf).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_8", + "description": "States that Patton was engaged in the illegal activity of possessing a firearm as a felon.", + "source": "Facts pp. 7-8, 10 (Facts.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_9", + "description": "States that Patton had a duty to retreat before using deadly force.", + "source": "State v. Ellison, No. 21-0657, slip op. at 8 (Iowa Feb. 3, 2023) (Ellison.pdf); Iowa Code ch. 704 \u00a7 704.1(3) (2020) (704.pdf).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_10", + "description": "Mentions that the OTB group had rolled the windows down before reaching Nelson.", + "source": "Facts p. 7 (Facts.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_11", + "description": "Mentions that Patton was hanging out the window with a firearm.", + "source": "Facts pp. 7-8 (Facts.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_12", + "description": "Mentions that Nelson's car was already stopped when Patton fired his gun.", + "source": "Facts pp. 7-8 (Facts.pdf).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 15.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_13", + "description": "States that the OTB group could have driven away.", + "source": "Facts pp. 7-8 (Facts.pdf) (Nelson's car was stopped; Nelson was outside of the car; the OTB group remained in a moving car).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 15.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_14", + "description": "States that the only reasonable inference from Patton's actions is that he intended to fire regardless of what Nelson did.", + "source": "Facts pp. 6-8 (Facts.pdf) (Patton was armed with a gun, they chased Nelson across the city, rolled the windows down before being fired at).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 25.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_16", + "description": "States that Patton's actions on May 10, 2020 show he engaged in a pre-planned drive-by shooting.", + "source": "Facts pp. 6-8 (Facts.pdf) (Patton was armed with a gun, they chased Nelson across the city, rolled the windows down before being fired at).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 20.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_15", + "description": "States that Patton's shooting at Nelson was not an act of justified self-defense.", + "source": "Iowa Code ch. 704 \u00a7 704.6(3) (2020) (704.pdf) (\u201cThe defense of justification is not available to . . . [o]ne who initially provokes the use of force against oneself by one\u2019s unlawful acts . . . .\u201d).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Conclusion" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_17", + "description": "Identifies that a defendant is not entitled to a justification defense if he is participating in a forcible felony.", + "source": "Iowa Code ch. 704, \u00a7 704.6(1) (2020) (704.pdf).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_18", + "description": "Mentions that a forcible felony under Iowa law includes felonious assault.", + "source": "Iowa Code \u00a7 702.11(1) (2020) (702.11.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_28", + "description": "Mentions that Patton was committing the crime of intimidation with dangerous weapon on May 10, 2020.", + "source": "Iowa Code \u00a7 708.6 (2020) (708.6.pdf); Facts pp. 7-8 (Facts.pdf).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\" Obviously, the government's position is that Patton committed the crime of intimidation with a dangerous weapon, in addition to attempted murder. However, the whole crux of the argument on appeal is whether Patton's shooting was justified. Essentially, arguing the intimidation with a dangerous weapon precludes the instruction is akin to arguing Patton can't get the justification instruction because he was engaged in the felonious assault of attempted murder.", + "metadata": { + "irac_section": "Application" + }, + "score": -20.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_29", + "description": "States that Patton's commission of intimidation with a dangerous weapon precludes a justification instruction.", + "source": "Iowa Code ch. 704, \u00a7 704.6(1) (2020) (704.pdf); Iowa Code \u00a7 708.6 (2020) (708.6.pdf).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\" Obviously, the government's position is that Patton committed the crime of intimidation with a dangerous weapon, in addition to attempted murder. However, the whole crux of the argument on appeal is whether Patton's shooting was justified. Essentially, arguing the intimidation with a dangerous weapon precludes the instruction is akin to arguing Patton can't get the justification instruction because he was engaged in the felonious assault of attempted murder.", + "metadata": { + "irac_section": "Conclusion" + }, + "score": -10.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_19", + "description": "Mentions that Patton pled guilty in state court to conspiracy to commit a forcible felony on May 10, 2020.", + "source": "Patton State Plea pp. 4-6 (Patton State Plea.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_20", + "description": "Mentions that Patton admitted he planned with others to commit a shooting on May 10, 2020.", + "source": "Patton State Plea p. 5 (Patton State Plea.pdf); Iowa Code ch. 706, \u00a7 706.1(1) (2020) (706.1.pdf).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_21", + "description": "States that Patton's commission of conspiracy to commit a forcible felony precludes a justification defense.", + "source": "Patton State Plea p. 5 (Patton State Plea.pdf); Iowa Code ch. 704, \u00a7 704.6(1) (2020) (704.pdf); Iowa Code ch. 706, \u00a7 706.1(1) (2020) (706.1.pdf).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"", + "metadata": { + "irac_section": "Conclusion" + }, + "score": 15.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_23", + "description": "Mentions that Patton pled guilty in state court to intimidation with a dangerous weapon.", + "source": "Patton State Plea pp. 1-3 (Patton State Plea.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\"Patton's written guilty plea indicates that he committed the offense of intimidation with a dangerous weapon on April 13, 2020. Because that involved a different shooting, it's not relevant to whether Patton should receive a justification instruction for the May 10, 2020 shooting.", + "metadata": { + "irac_section": "Application" + }, + "score": -5.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_25", + "description": "Mentions that Patton lacked a reasonable belief that deadly force was necessary.", + "source": "Facts p. 7 (Facts.pdf); Iowa Code ch. 704, \u00a7 704.3 (2020) (704.pdf).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\" The evidence at trial suggests that, at a minimum, it is unclear which side fired first. Because some evidence supports that Nelson fired first, Patton might have reasonably believed deadly force was necessary. The better arguments on appeal relate to Patton's duty to retreat or pre-planning of the shooting.", + "metadata": { + "irac_section": "Application" + }, + "score": -20.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_27", + "description": "Mentions that Patton lacked a reasonable belief that he was subject to an imminent unlawful threat.", + "source": "Facts p. 7 (Facts.pdf); Iowa Code ch. 704, \u00a7 704.6(1) (2020) (704.pdf).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\" The evidence at trial suggests that, at a minimum, it is unclear which side fired first. Because some evidence supports that Nelson fired first, Patton might have had a fear of imminent unlawful threat. The better arguments on appeal relate to Patton's duty to retreat or pre-planning of the shooting.", + "metadata": { + "irac_section": "Application" + }, + "score": -20.0, + "polarity": "negative", + "raw_weight": 1.0 + }, + { + "name": "criterion_26", + "description": "States that the district court was within its discretion to refuse to provide the justification instruction.", + "source": "United States v. White Horse, No. 21-2871, slip op. at 2-3 (8th Cir. June 3, 2022) (White Horse.pdf) (speaking of jury instructions as drafted generally, not the district court's consideration of substantial evidence to warrant submission of a justification instruction); United States v. Poe, No. 05-2914, slip op. at 3 (8th Cir. Apr. 6. 2006) (Poe.pdf) (\u201cWhether there is sufficient evidence to support the submission of an instruction on an affirmative defense is a question of law,\" rather than a matter of discretion).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please draft the responsive section for this argument, focusing on Patton's claim, the evidence, and the relevant jurisdiction's law.\" This conclusion uses the wrong standard of review for the district court's failure to give a justification instruction.", + "metadata": { + "irac_section": "Conclusion" + }, + "score": -30.0, + "polarity": "negative", + "raw_weight": 1.0 + } + ] +} diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/m1_judge_panel.json b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/m1_judge_panel.json new file mode 100644 index 0000000000000000000000000000000000000000..a8041f6781a899f9083fe4a1a95f51bc78d35601 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/m1_judge_panel.json @@ -0,0 +1,21 @@ +{ + "mode": "panel", + "max_concurrent_llm": 12, + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ] +} diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/m1_rewardkit_accounting.py b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/m1_rewardkit_accounting.py new file mode 100644 index 0000000000000000000000000000000000000000..406dc5e7c675b222d94514e71bf5fad6ae141d8f --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/m1_rewardkit_accounting.py @@ -0,0 +1,490 @@ +import asyncio +import json +import math +import os +from pathlib import Path +import random +import sys +import time + +class JudgeReceiptError(OSError): + pass +_LLM_ROUTES = frozenset({'vertex', 'anthropic fallback', 'aistudio', 'direct'}) +_LLM_ROUTE_HEADERS = ('x-m1-llm-route', 'llm_provider-x-m1-llm-route') + +def _canonical_llm_route(value): + return value if isinstance(value, str) and value in _LLM_ROUTES else None + +def _llm_route_from_headers(headers): + if not isinstance(headers, dict): + return None + folded = {str(key).lower(): value for key, value in headers.items()} + for name in _LLM_ROUTE_HEADERS: + route = _canonical_llm_route(folded.get(name)) + if route is not None: + return route + return None + +def _llm_route_from_response(response): + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + route = _llm_route_from_headers(headers) + if route is not None: + return route + return _llm_route_from_headers(getattr(response, 'headers', None)) + +def _token_field_status(values, key): + if not isinstance(values, dict) or key not in values: + return 'missing' + value = values[key] + if value is None: + return 'null' + return 'valid' if type(value) is int and value >= 0 else 'invalid' + +def _gemini_capture(kwargs, model): + if not model.startswith('gemini/') or kwargs.get('stream') or kwargs.get('tools') or kwargs.get('functions'): + return (kwargs, None) + from litellm.integrations.custom_logger import CustomLogger + from urllib.parse import urlsplit + + class Capture(CustomLogger): + evidence = None + prompt_status = 'not_observed' + llm_route = None + + def log_post_api_call(self, kwargs, response_obj, start_time, end_time): + self.evidence = None + self.prompt_status = 'not_observed' + try: + params = kwargs.get('litellm_params') or {} + route = urlsplit(params.get('api_base') or '') + bare = model.removeprefix('gemini/') + gemini = params.get('custom_llm_provider') == 'gemini' + ai_studio = gemini and route.hostname == 'generativelanguage.googleapis.com' and (route.path in {'/' + version + '/models/' + bare + ':generateContent' for version in ('v1alpha', 'v1beta')}) + broker = urlsplit(os.environ.get('GEMINI_API_BASE') or '') + brokered = gemini and bool(broker.netloc) and (route.netloc == broker.netloc) and (broker.path.rstrip('/').rsplit('/', 1)[-1] in ('v1alpha', 'v1beta')) and (route.path == broker.path.rstrip('/') + '/models/' + bare + ':generateContent') + vertex = params.get('custom_llm_provider') == 'vertex_ai' and route.hostname == 'aiplatform.googleapis.com' and route.path.startswith('/v1/projects/') and route.path.endswith('/locations/global/publishers/google/models/' + bare + ':generateContent') + if route.scheme != 'https' or not (ai_studio or brokered or vertex) or kwargs.get('stream'): + return + self.llm_route = 'vertex' if vertex else 'aistudio' if ai_studio else None + raw = kwargs.get('original_response') + raw = json.loads(raw) if isinstance(raw, str) else raw + if not isinstance(raw, dict): + return + candidates = raw.get('candidates') + if not isinstance(candidates, list) or not candidates or any((not isinstance(c, dict) or not c.get('finishReason') for c in candidates)) or (not isinstance(raw.get('modelVersion'), str)) or (not raw['modelVersion']): + return + usage = raw.get('usageMetadata') + self.prompt_status = _token_field_status(usage, 'promptTokenCount') + if not isinstance(usage, dict): + return + fields = ('promptTokenCount', 'candidatesTokenCount', 'thoughtsTokenCount', 'cachedContentTokenCount', 'totalTokenCount', 'toolUsePromptTokenCount') + counts = {key: usage.get(key, 0) for key in fields} + if not {'promptTokenCount', 'totalTokenCount'} <= usage.keys() or any((type(n) is not int or n < 0 for n in counts.values())) or counts['toolUsePromptTokenCount'] != 0 or (counts['cachedContentTokenCount'] > counts['promptTokenCount']) or (counts['totalTokenCount'] != counts['promptTokenCount'] + counts['candidatesTokenCount'] + counts['thoughtsTokenCount']): + return + self.evidence = {'protocol': 'gemini-generate-content-' + ('vertex-v1' if vertex else route.path.split('/')[-3]), 'model_version': raw['modelVersion'], 'usage_metadata': {key: usage[key] for key in fields if key in usage}, 'defaulted_fields': [key for key in fields if key not in usage]} + except (TypeError, ValueError, AttributeError): + return + capture = Capture() + return ({**kwargs, 'callbacks': [*(kwargs.get('callbacks') or []), capture]}, capture) + +def _record_judge_usage(response, model: str, *, target: Path | None=None, native_usage: dict | None=None, native_prompt_status: str | None=None, llm_route: str | None=None) -> None: + import fcntl + from datetime import datetime, timezone + data = response.model_dump() if hasattr(response, 'model_dump') else response + usage = data.get('usage') if isinstance(data, dict) else None + granularity = data.get('usage_granularity') if isinstance(data, dict) else None + if not isinstance(usage, dict): + usage = {} + granularity = 'missing_provider_receipt' + prompt, completion = (usage.get('prompt_tokens'), usage.get('completion_tokens')) + native_fresh = usage.get('input_uncached_tokens') + prompt = prompt if type(prompt) is int and prompt >= 0 else None + native_fresh = native_fresh if type(native_fresh) is int and native_fresh >= 0 else None + if type(completion) is not int or completion < 0 or (prompt is None and native_fresh is None): + completion = completion if type(completion) is int and completion >= 0 else 0 + granularity = granularity or 'invalid_provider_receipt' + details = usage.get('prompt_tokens_details') + if details is not None and (not isinstance(details, dict)): + granularity = 'invalid_provider_receipt' + details = details if isinstance(details, dict) else {} + cached = details.get('cached_tokens') + if native_usage is not None: + native = native_usage['usage_metadata'] + native_output = native.get('candidatesTokenCount', 0) + native.get('thoughtsTokenCount', 0) + if prompt == native['promptTokenCount'] and completion == native_output: + cached = native.get('cachedContentTokenCount', 0) + else: + native_usage = None + written = next((value for value in (usage.get('input_cache_write_tokens'), usage.get('cache_creation_input_tokens'), details.get('cache_creation_tokens'), details.get('cache_write_tokens')) if value is not None), None) + invalid = any((value is not None and (type(value) is not int or value < 0) for value in (cached, written))) + cached = cached if type(cached) is int and cached >= 0 else None + written = written if type(written) is int and written >= 0 else None + fresh = native_fresh + if fresh is None and prompt is not None and (cached is not None) and (written is not None): + fresh = prompt - cached - written + if fresh is not None and (fresh < 0 or (prompt is not None and cached is not None and (written is not None) and (fresh + cached + written != prompt))): + invalid, fresh = (True, None) + provider, _, slug = model.partition('/') + event: dict = {'type': 'step_finish', 'part': {'providerID': provider if slug else 'openai', 'modelID': slug or model, 'tokens': {'input': fresh, 'output': completion, 'cache': {'read': cached, 'write': written}}}} + field_status = {'prompt_tokens': _token_field_status(usage, 'prompt_tokens'), 'completion_tokens': _token_field_status(usage, 'completion_tokens'), 'input_uncached_tokens': _token_field_status(usage, 'input_uncached_tokens')} + field_status['native_prompt_token_count'] = native_prompt_status if native_prompt_status in {'missing', 'null', 'invalid', 'valid', 'not_observed'} else 'unsupported' + part: dict = event['part'] + part['usage_field_status'] = field_status + if native_usage is not None: + event['part']['native_usage'] = native_usage + event['part']['token_categories_provenance'] = 'explicit_presence_v1' + if fresh is None and prompt is not None: + event['part']['prompt_tokens_inclusive'] = prompt + if invalid or any((value is None for value in (fresh, cached, written))): + granularity = granularity if granularity not in (None, 'request') else 'invalid_provider_receipt' if invalid else 'incomplete_token_categories' + if granularity: + event['part']['usage_granularity'] = granularity + if provider == 'openrouter': + cost = usage.get('cost') + if cost is None: + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + if isinstance(headers, dict): + cost = headers.get('llm_provider-x-litellm-response-cost') + if isinstance(cost, (int, float)) and (not isinstance(cost, bool)) and math.isfinite(cost) and (cost >= 0): + event['part']['cost'] = cost + data = data if isinstance(data, dict) else {} + if isinstance(data.get('id'), str) and data['id']: + event['part']['provider_request_id'] = data['id'] + for key in ('service_tier', 'cache_ttl'): + if data.get(key): + event['part'][key] = data[key] + route = _llm_route_from_response(response) or _canonical_llm_route(llm_route) + if route is not None: + event['part']['llm_route'] = route + created = data.get('created') + stamp = datetime.now(timezone.utc) + try: + if isinstance(created, str): + parsed = datetime.fromisoformat(created.replace('Z', '+00:00')) + if parsed.tzinfo is not None: + stamp = parsed + elif isinstance(created, (int, float)) and (not isinstance(created, bool)) and math.isfinite(created): + stamp = datetime.fromtimestamp(created, timezone.utc) + except (ValueError, OverflowError, OSError): + pass + pair = json.dumps({'type': 'step_start', 'timestamp': stamp.isoformat()}) + '\n' + pair += json.dumps(event) + '\n' + try: + receipt_path = target or Path(os.environ.get('M1_JUDGE_USAGE_PATH', '/logs/verifier/judge-trajectory.jsonl')) + receipt_path.parent.mkdir(parents=True, exist_ok=True) + with receipt_path.open('a') as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + handle.write(pair) + handle.flush() + os.fsync(handle.fileno()) + except OSError as exc: + if target is not None: + raise JudgeReceiptError(f'judge receipt write failed: {exc}') from exc + print(f'judge accounting: write failed ({type(exc).__name__})', file=sys.stderr) + +def openrouter_judge_pins() -> dict[str, dict]: + raw = os.environ.get('M1_OPENROUTER_JUDGE_PROVIDER_PINS', '').strip() + if not raw: + return {} + try: + pins = json.loads(raw) + except json.JSONDecodeError: + print('judge provider pins: invalid JSON in M1_OPENROUTER_JUDGE_PROVIDER_PINS', file=sys.stderr) + return {} + return {model: pin for model, pin in pins.items() if isinstance(pin, dict) and pin.get('order')} if isinstance(pins, dict) else {} + +def apply_judge_provider_pin(kwargs: dict, pins: dict[str, dict]) -> dict: + model = kwargs.get('model') + pin = pins.get(model) if isinstance(model, str) else None + if pin is None: + return kwargs + extra_body = dict(kwargs.get('extra_body') or {}) + provider = dict(extra_body.get('provider') or {}) + provider['order'] = list(pin['order']) + if pin.get('allow_fallbacks') is False: + provider['allow_fallbacks'] = False + if pin.get('zdr'): + provider['zdr'] = True + extra_body['provider'] = provider + return {**kwargs, 'extra_body': extra_body} +_TRANSIENT_ERROR_NAMES = ('RateLimitError', 'ServiceUnavailableError', 'InternalServerError', 'BadGatewayError', 'APIConnectionError') +_RETRYABLE_STATUS_CODES = frozenset({408, 409, 425, 429, 500, 502, 503, 504}) +_AUTH_ERROR_NAMES = ('AuthenticationError', 'PermissionDeniedError') +_AUTH_STATUS_CODES = frozenset({401, 403}) +_AUTH_RETRIES = 4 +_DEFAULT_TRANSIENT_RETRIES = 6 +_MAX_TRANSIENT_RETRIES = 20 +_MAX_RETRY_DELAY_SECONDS = 60.0 +_DEFAULT_EMPTY_RESPONSE_RETRIES = 3 +_DEFAULT_RETRY_BUDGET_SECONDS = 900.0 +_MAX_RETRY_BUDGET_SECONDS = 86400.0 + +def transient_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_TRANSIENT_RETRIES', '').strip() + if not raw: + return _DEFAULT_TRANSIENT_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_TRANSIENT_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_TRANSIENT_RETRIES + +def empty_response_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_EMPTY_RESPONSE_RETRIES', '').strip() + if not raw: + return _DEFAULT_EMPTY_RESPONSE_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_EMPTY_RESPONSE_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_EMPTY_RESPONSE_RETRIES + +def retry_budget_seconds() -> float: + raw = os.environ.get('M1_JUDGE_RETRY_BUDGET_SECONDS', '').strip() + if not raw: + return _DEFAULT_RETRY_BUDGET_SECONDS + try: + value = float(raw) + except ValueError: + value = math.nan + if not math.isfinite(value) or value < 0: + print('judge retries: invalid M1_JUDGE_RETRY_BUDGET_SECONDS, using the default', file=sys.stderr) + return _DEFAULT_RETRY_BUDGET_SECONDS + return min(value, _MAX_RETRY_BUDGET_SECONDS) + +def _within_budget(deadline: float, delay: float, model) -> bool: + remaining = deadline - time.monotonic() + if delay <= remaining: + return True + print(f'judge call retry budget spent: {model} would wait {delay:.1f}s with {max(remaining, 0.0):.1f}s left of M1_JUDGE_RETRY_BUDGET_SECONDS, failing now', file=sys.stderr) + return False + +def is_empty_verdict(response) -> bool: + data = response.model_dump() if hasattr(response, 'model_dump') else response + if not isinstance(data, dict): + return False + choices = data.get('choices') + if not isinstance(choices, list) or not choices: + return True + first = choices[0] + message = first.get('message') if isinstance(first, dict) else None + if not isinstance(message, dict): + return True + if message.get('tool_calls') or message.get('function_call'): + return False + content = message.get('content') + if isinstance(content, list): + content = ''.join((part.get('text') or '' for part in content if isinstance(part, dict))) + return not (isinstance(content, str) and content.strip()) + +def _matches(exc: BaseException, litellm, names: tuple[str, ...], statuses: frozenset[int]) -> bool: + classes = tuple((cls for cls in (getattr(litellm, name, None) for name in names) if isinstance(cls, type))) + if classes and isinstance(exc, classes): + return True + status = getattr(exc, 'status_code', None) + return type(status) is int and status in statuses + +def is_transient_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _TRANSIENT_ERROR_NAMES, _RETRYABLE_STATUS_CODES) + +def is_auth_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _AUTH_ERROR_NAMES, _AUTH_STATUS_CODES) + +def should_retry(exc: BaseException, litellm, attempt: int, limit: int) -> bool: + if attempt < limit and is_transient_error(exc, litellm): + return True + return attempt < min(limit, _AUTH_RETRIES) and is_auth_error(exc, litellm) + +def _retry_after_seconds(exc: BaseException) -> float | None: + headers = getattr(exc, 'headers', None) + if headers is None: + headers = getattr(getattr(exc, 'response', None), 'headers', None) + if headers is None: + return None + try: + raw = headers.get('retry-after') + if raw is None: + raw = headers.get('Retry-After') + value = float(raw) + except (AttributeError, TypeError, ValueError): + return None + return value if math.isfinite(value) and value >= 0 else None + +def retry_delay(exc: BaseException | None, attempt: int) -> float: + base = min(_MAX_RETRY_DELAY_SECONDS, 2.0 ** (attempt + 1)) + delay = base * (0.5 + random.random()) + retry_after = _retry_after_seconds(exc) if exc is not None else None + if retry_after is not None: + delay = max(delay, min(_MAX_RETRY_DELAY_SECONDS, retry_after)) + return delay + +def _note_retry(model, exc: BaseException, attempt: int, limit: int, delay: float) -> None: + status = getattr(exc, 'status_code', None) + print(f"judge call retry {attempt}/{limit}: {model} {type(exc).__name__} status={(status if type(status) is int else 'n/a')}, waiting {delay:.1f}s", file=sys.stderr) + +def _note_empty(model, response, attempt: int, limit: int, delay: float) -> None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + reason = None + if isinstance(data, dict) and isinstance(data.get('choices'), list) and data['choices']: + first = data['choices'][0] + reason = first.get('finish_reason') if isinstance(first, dict) else None + print(f'judge call retry {attempt}/{limit}: {model} empty verdict (finish_reason={reason}), waiting {delay:.1f}s', file=sys.stderr) + +def install(litellm, *, synchronous: bool=False) -> None: + pins = openrouter_judge_pins() + limit = transient_retry_limit() + empty_limit = empty_response_retry_limit() + deadline = time.monotonic() + retry_budget_seconds() + if synchronous: + original = litellm.completion + + def accounted(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = original(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + time.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + time.sleep(delay) + continue + return response + litellm.completion = accounted + return + original_async = litellm.acompletion + + async def accounted_async(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = await original_async(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + await asyncio.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + await asyncio.sleep(delay) + continue + return response + litellm.acompletion = accounted_async + +def record_agent_usage(attempt, *, model: str, provider: str) -> None: + records: dict[str, tuple[str, dict]] = {} + current_model = model + for filename in getattr(attempt, 'logs', []): + try: + with Path(filename).open() as stream: + for line in stream: + try: + event = json.loads(line) + except (ValueError, TypeError): + continue + if not isinstance(event, dict): + continue + message = event.get('message') or {} + if event.get('type') == 'assistant' and isinstance(message, dict) and isinstance(message.get('usage'), dict): + raw = message['usage'] + cached, written = (raw.get('cache_read_input_tokens'), raw.get('cache_creation_input_tokens')) + if all((type(value) is int and value >= 0 for value in (raw.get('input_tokens'), raw.get('output_tokens')))) and all((value is None or (type(value) is int and value >= 0) for value in (cached, written))): + receipt: dict = {'usage': {'input_uncached_tokens': raw['input_tokens'], 'prompt_tokens': raw['input_tokens'] + cached + written if cached is not None and written is not None else None, 'completion_tokens': raw['output_tokens'], 'prompt_tokens_details': {'cached_tokens': cached, 'cache_creation_tokens': written}}} + receipt['created'] = event.get('timestamp') + creation = raw.get('cache_creation') or {} + hour = creation.get('ephemeral_1h_input_tokens', 0) if isinstance(creation, dict) else 0 + if type(hour) is int and hour > 0: + if hour == written: + receipt['cache_ttl'] = '1h' + else: + receipt['usage_granularity'] = 'mixed_cache_ttl' + records[message.get('id') or json.dumps(raw, sort_keys=True)] = (message.get('model') or current_model, receipt) + payload = event.get('payload') or {} + if not isinstance(payload, dict): + continue + if event.get('type') == 'turn_context' and payload.get('model'): + current_model = payload['model'] + if event.get('type') == 'event_msg' and payload.get('type') == 'token_count': + info = payload.get('info') or {} + raw, total = (info.get('last_token_usage'), info.get('total_token_usage')) + if isinstance(raw, dict) and isinstance(total, dict) and all((type(raw.get(key)) is int and raw.get(key) >= 0 for key in ('input_tokens', 'output_tokens'))): + receipt = {'usage': {'prompt_tokens': raw.get('input_tokens'), 'input_uncached_tokens': raw.get('input_uncached_tokens'), 'input_cache_write_tokens': raw.get('input_cache_write_tokens'), 'completion_tokens': raw.get('output_tokens'), 'prompt_tokens_details': {'cached_tokens': raw.get('cached_input_tokens')}}} + receipt['created'] = event.get('timestamp') + records[json.dumps(total, sort_keys=True)] = (current_model, receipt) + except OSError: + continue + captured_input = captured_output = 0 + input_complete = True + for requested, receipt in records.values(): + requested = requested if '/' in requested else f'{provider}/{requested}' + _record_judge_usage(receipt, requested) + receipt_input = receipt['usage'].get('prompt_tokens') + if receipt_input is None: + input_complete = False + else: + captured_input += receipt_input + captured_output += receipt['usage'].get('completion_tokens') or 0 + total = getattr(attempt, 'usage', {}) or {} + if not records or (input_complete and total.get('input_tokens') != captured_input) or total.get('output_tokens') != captured_output: + _record_judge_usage({'usage': {'prompt_tokens': 0, 'completion_tokens': 0}, 'usage_granularity': 'incomplete_agent_receipts'}, model if '/' in model else f'{provider}/{model}') + +def install_rewardkit_agents() -> None: + import rewardkit.judges as judges + original = judges.get_agent + + def get_accounted_agent(judge, cwd=None): + backend = original(judge, cwd) + run = backend.run + + async def accounted_run(*args, **kwargs): + attempt = await run(*args, **kwargs) + record_agent_usage(attempt, model=judge.model or 'unknown', provider='anthropic' if judge.agent == 'claude-code' else 'openai') + return attempt + setattr(backend, 'run', accounted_run) + return backend + setattr(judges, 'get_agent', get_accounted_agent) +if __name__ == '__main__': + import litellm + if len(sys.argv) > 2 and sys.argv[1] == '--script': + import runpy + install(litellm, synchronous=True) + sys.argv = sys.argv[2:] + runpy.run_path(sys.argv[0], run_name='__main__') + else: + install(litellm) + install_rewardkit_agents() + if Path(__file__).with_name('m1_judge_panel.json').is_file(): + from m1_rewardkit_panel import install_panel + install_panel(Path(__file__).with_name('m1_judge_panel.json')) + if Path(__file__).with_name('m1_judge_jev.json').is_file(): + from m1_rewardkit_jev import install_jev + install_jev(Path(__file__).with_name('m1_judge_jev.json')) + from rewardkit.__main__ import main + main() diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/m1_rewardkit_panel.py b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/m1_rewardkit_panel.py new file mode 100644 index 0000000000000000000000000000000000000000..164cc2ae521cdd368c2e1749d7ed8fe09f4545eb --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/m1_rewardkit_panel.py @@ -0,0 +1,169 @@ +from __future__ import annotations +import asyncio +from contextvars import ContextVar +import json +import math +import os +import sys +from pathlib import Path +from typing import Any +import uuid +_request_audit: ContextVar[tuple[Path, list[str]] | None] = ContextVar('panel_request_audit', default=None) + +class PanelIncompleteError(RuntimeError): + pass + +def _audit_warning(exc: Exception, warnings: list[str]) -> None: + message = f'judge panel audit: diagnostic capture failed ({type(exc).__name__})' + if message not in warnings: + warnings.append(message) + print(message, file=sys.stderr) + +def _write_audit(path: Path, record: dict[str, Any], warnings: list[str], *, append: bool=False) -> None: + try: + text = json.dumps(record, allow_nan=False, default=str) + '\n' + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('a' if append else 'w') as stream: + stream.write(text) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + +def _binary(raw: Any) -> int: + if isinstance(raw, bool): + return int(raw) + if isinstance(raw, int | float) and math.isfinite(raw) and (raw in (0, 1)): + return int(raw) + if isinstance(raw, str): + value = raw.strip().lower() + if value in {'yes', 'true', '1'}: + return 1 + if value in {'no', 'false', '0'}: + return 0 + raise PanelIncompleteError('m1_judge_panel_incomplete: invalid binary vote') + +def validate_votes(scores: list[Any], criteria: list[Any]) -> None: + names = [criterion.name for criterion in criteria] + if len(set(names)) != len(names) or [score.name for score in scores] != names: + raise PanelIncompleteError('m1_judge_panel_incomplete: criterion membership mismatch') + for score, criterion in zip(scores, criteria, strict=True): + if score.error: + raise PanelIncompleteError('m1_judge_panel_incomplete: judge returned an error') + raw = _binary(score.raw) + expected = 1 - raw if criterion.negate else raw + if not math.isfinite(score.value) or score.value != expected: + raise PanelIncompleteError('m1_judge_panel_incomplete: inconsistent binary score') + +async def run_panel(judge: Any, criteria: list[Any], weights: list[float] | None, system_prompt: str | None, *, config: dict[str, Any], run_llm: Any, score_type: Any, audit_dir: Path) -> tuple[list[Any], str, list[str]]: + from rewardkit.models import Binary + if not criteria or any((not isinstance(criterion.output_format, Binary) for criterion in criteria)): + raise ValueError('panel majority voting requires nonempty binary criteria') + group_dir = audit_dir / uuid.uuid4().hex + warnings_out: list[str] = [] + + async def member_call(index: int, member: dict[str, Any]): + member_judge = judge.model_copy(update=member) + evidence: dict[str, Any] = {'member': index + 1, 'judge': member, 'criteria': [criterion.name for criterion in criteria], 'status': 'started'} + path = group_dir / f'judge-{index + 1}.json' + _write_audit(path, evidence, warnings_out) + token = _request_audit.set((group_dir / f'judge-{index + 1}-requests.jsonl', warnings_out)) + try: + scores, output, warnings = await run_llm(member_judge, criteria, weights, system_prompt) + evidence.update(output=output, warnings=warnings) + validate_votes(scores, criteria) + evidence['scores'] = [score.to_dict() for score in scores] + evidence['status'] = 'completed' + return (scores, output, warnings) + except BaseException as exc: + evidence.update(status='failed', error_class=type(exc).__name__) + if isinstance(exc, PanelIncompleteError): + evidence['error'] = str(exc) + raise + finally: + _request_audit.reset(token) + _write_audit(path, evidence, warnings_out) + outcomes = await asyncio.gather(*(member_call(index, member) for index, member in enumerate(config['members'])), return_exceptions=True) + failed = [index + 1 for index, result in enumerate(outcomes) if isinstance(result, BaseException)] + if failed: + _write_audit(group_dir / 'panel.json', {'status': 'incomplete', 'failed_members': failed}, warnings_out) + raise PanelIncompleteError(f'm1_judge_panel_incomplete: failed members {failed}; see panel audit artifacts') + completed = [outcome for outcome in outcomes if not isinstance(outcome, BaseException)] + combined = [] + for index, criterion in enumerate(criteria): + votes = [{'judge': config['members'][member_index], **outcome[0][index].to_dict()} for member_index, outcome in enumerate(completed)] + passes = sum((vote['value'] == 1 for vote in votes)) + value = int(passes >= 2) + combined.append(score_type(name=criterion.name, value=value, raw=bool(1 - value if criterion.negate else value), weight=weights[index] if weights is not None else 1.0, reasoning=f'{passes}/3 judges passed; strict majority requires 2/3.', description=criterion.description, id=criterion.id, negate=criterion.negate, optional=criterion.optional, votes=votes)) + for outcome in completed: + warnings_out.extend(outcome[2]) + audit = {'status': 'completed', 'mode': 'panel', 'aggregation': 'majority', 'required_votes': 2, 'members': config['members'], 'criteria': [score.to_dict() for score in combined]} + output = json.dumps(audit, indent=2, allow_nan=False) + _write_audit(group_dir / 'panel.json', audit, warnings_out) + return (combined, output, warnings_out) + +def install_panel(config_path: Path, *, audit_dir: Path=Path('/logs/verifier/judge-panel')) -> None: + import rewardkit.judges as judges + import rewardkit.reward as reward + from rewardkit.models import LLMJudge, Score + import litellm + config = json.loads(config_path.read_text()) + members = config.get('members') + concurrency = config.get('max_concurrent_llm') + if config.get('mode') != 'panel' or not isinstance(members, list) or len(members) != 3 or (len({member['model'] for member in members}) != 3) or (type(concurrency) is not int) or (not 1 <= concurrency <= 64): + raise ValueError('invalid materialized panel configuration') + if os.environ.get('REWARDKIT_JUDGE') or os.environ.get('REWARDKIT_MODEL'): + raise ValueError('RewardKit environment overrides cannot replace a frozen panel') + + class PanelScore(Score): + votes: list[dict[str, Any]] + + def to_dict(self): + return {**super().to_dict(), 'votes': self.votes} + original_llm = judges.arun_llm + original_call = judges._arun_llm_call + original_details = reward.Reward.to_detail_dict + original_completion = litellm.acompletion + active_loop = None + semaphore = None + + async def captured_completion(*args, **kwargs): + context = _request_audit.get() + record = {'requested_model': kwargs.get('model')} + response = None + try: + response = await original_completion(*args, **kwargs) + return response + except BaseException as exc: + record['error_class'] = type(exc).__name__ + raise + finally: + if context is not None: + path, warnings = context + try: + if response is not None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + record.update(response_model=data.get('model'), choices=data.get('choices')) + _write_audit(path, record, warnings, append=True) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + + async def bounded_call(*args, **kwargs): + nonlocal active_loop, semaphore + loop = asyncio.get_running_loop() + if active_loop is not loop: + active_loop, semaphore = (loop, asyncio.Semaphore(concurrency)) + assert semaphore is not None + async with semaphore: + return await original_call(*args, **kwargs) + + async def panel_call(judge, criteria, weights=None, system_prompt=None): + return await run_panel(judge, criteria, weights, system_prompt, config=config, run_llm=original_llm, score_type=PanelScore, audit_dir=audit_dir) + + def panel_details(self, score): + detail = original_details(self, score) + if isinstance(self.judge, LLMJudge): + detail.update(kind='llm_panel', judge=config, aggregation='majority', required_votes=2) + return detail + setattr(reward, 'arun_llm', panel_call) + setattr(judges, '_arun_llm_call', bounded_call) + setattr(litellm, 'acompletion', captured_completion) + reward.Reward.to_detail_dict = panel_details diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/normalize_reward.py b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/normalize_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..91817ef00ea9152ca57f0030d8e879eb850ddff0 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/normalize_reward.py @@ -0,0 +1,71 @@ +from __future__ import annotations +import argparse +import json +from pathlib import Path +from typing import Any + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument('--raw-details', required=True) + parser.add_argument('--rubric', required=True) + parser.add_argument('--reward-out', required=True) + parser.add_argument('--details-out', required=True) + args = parser.parse_args() + raw_details = _load_json(Path(args.raw_details)) + rubric = _load_json(Path(args.rubric)) + criteria = rubric['criteria'] + raw_by_name = _raw_criteria_by_name(raw_details) + positive_total = sum((float(item['score']) for item in criteria if float(item['score']) > 0)) + if positive_total <= 0: + raise ValueError('rubric must contain at least one positive score') + earned = 0.0 + normalized_criteria: list[dict[str, Any]] = [] + for item in criteria: + signed_score = float(item['score']) + raw = raw_by_name.get(item['name'], {}) + value = _coerce_score(raw.get('value', 0.0)) + contribution = value * signed_score + earned += contribution + normalized_criteria.append({'name': item['name'], 'value': value, 'raw': raw.get('raw'), 'weight': signed_score, 'signed_score': signed_score, 'polarity': item['polarity'], 'contribution': contribution, 'description': item['description'], 'source': item.get('source', ''), 'justification': item.get('justification', ''), 'metadata': item.get('metadata', {}), 'reasoning': raw.get('reasoning'), 'judge_reasoning': raw.get('reasoning'), 'judge_error': raw.get('error'), **({'votes': raw['votes']} if 'votes' in raw else {})}) + unclamped = earned / positive_total + reward = max(0.0, min(1.0, unclamped)) + reward_out = {'correctness': reward} + details_out = {'correctness': {'score': reward, 'kind': 'signed_score', 'criteria': normalized_criteria, 'aggregation': {'method': 'signed_score_ratio_clamped', 'earned': earned, 'positive_total': positive_total, 'unclamped': unclamped, 'clamped': reward}, 'raw_rewardkit': raw_details}} + _write_json(Path(args.reward_out), reward_out) + _write_json(Path(args.details_out), details_out) + +def _load_json(path: Path) -> Any: + return json.loads(path.read_text()) + +def _write_json(path: Path, data: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data, indent=2) + '\n') + +def _raw_criteria_by_name(details: dict[str, Any]) -> dict[str, dict[str, Any]]: + out: dict[str, dict[str, Any]] = {} + for reward in details.values(): + for item in _iter_raw_criteria(reward): + name = item.get('name') + if isinstance(name, str): + out[name] = item + return out + +def _iter_raw_criteria(value: Any): + if isinstance(value, list): + for item in value: + yield from _iter_raw_criteria(item) + return + if not isinstance(value, dict): + return + for item in value.get('criteria') or []: + if isinstance(item, dict): + yield item + +def _coerce_score(value: Any) -> float: + if isinstance(value, bool): + return 1.0 if value else 0.0 + if isinstance(value, int | float): + return max(0.0, min(1.0, float(value))) + return 0.0 +if __name__ == '__main__': + main() diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/agent_prompt.md b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/agent_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..ca489c065bafd5d10e764f033c9dfd1195933db3 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/agent_prompt.md @@ -0,0 +1,10 @@ +You are grading the submitted legal analysis against the criteria below. + +Read `/logs/artifacts/answer.md`, the answer captured by the verifier, before +assigning any scores. Evaluate that file as the submission. Other files in +`/app` may supply context, but must not replace the submitted answer. Do not +modify the submission. If it is missing or empty, state that in your reasoning +and apply the criteria to that missing or empty submission. Preserve each +criterion's stated positive or penalty polarity. + +{criteria} diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_1.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_1.toml new file mode 100644 index 0000000000000000000000000000000000000000..ba0fe99094c0c3451a7a20e88b8534a5c6e64168 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_1.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_1" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that the district court's refusal to submit a justification instruction is reviewed de novo." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_10.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_10.toml new file mode 100644 index 0000000000000000000000000000000000000000..895829072c588a1564e7d77d7a8a72e8745422a1 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_10.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_10" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions that the OTB group had rolled the windows down before reaching Nelson." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_11.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_11.toml new file mode 100644 index 0000000000000000000000000000000000000000..21b8084d5e14d3ce9a6719f36b0ea9078ec28ce4 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_11.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_11" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions that Patton was hanging out the window with a firearm." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_12.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_12.toml new file mode 100644 index 0000000000000000000000000000000000000000..6a8edce23eef35259165fb9c04be1c3bf1cf9f5e --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_12.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_12" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions that Nelson's car was already stopped when Patton fired his gun." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_13.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_13.toml new file mode 100644 index 0000000000000000000000000000000000000000..ae063a9c8e1bf359e16bb2537361c7a8d3764342 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_13.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_13" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that the OTB group could have driven away." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_14.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_14.toml new file mode 100644 index 0000000000000000000000000000000000000000..e49fef3ddc13ed2168e9efe74942b960e35541ac --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_14.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_14" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that the only reasonable inference from Patton's actions is that he intended to fire regardless of what Nelson did." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_15.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_15.toml new file mode 100644 index 0000000000000000000000000000000000000000..8eb64c98e1365c9806c46adccef313296ed085af --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_15.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_15" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that Patton's shooting at Nelson was not an act of justified self-defense." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_16.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_16.toml new file mode 100644 index 0000000000000000000000000000000000000000..72b3b9ede9ccd947ce5ac2b7f0a00d1e4b2fb7ad --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_16.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_16" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that Patton's actions on May 10, 2020 show he engaged in a pre-planned drive-by shooting." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_17.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_17.toml new file mode 100644 index 0000000000000000000000000000000000000000..d31735770ff6ba11aa22ebeb7d53b886c9f7afc4 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_17.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_17" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that a defendant is not entitled to a justification defense if he is participating in a forcible felony." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_18.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_18.toml new file mode 100644 index 0000000000000000000000000000000000000000..66f0b8f1fa7ec962ad7f3372253d03e0d25b3d9a --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_18.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_18" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions that a forcible felony under Iowa law includes felonious assault." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_19.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_19.toml new file mode 100644 index 0000000000000000000000000000000000000000..434482eb27b515c0aaf5e1391178c8e88e0a7853 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_19.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_19" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions that Patton pled guilty in state court to conspiracy to commit a forcible felony on May 10, 2020." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_2.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_2.toml new file mode 100644 index 0000000000000000000000000000000000000000..0890ff008c2b08804544e4877c2dd4b63960f53d --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_2.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_2" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: Identifies that the district court's refusal to give a jury instruction is reviewed for abuse of discretion." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_20.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_20.toml new file mode 100644 index 0000000000000000000000000000000000000000..42a2487aa818a2fd609521999cca1787aedf5b65 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_20.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_20" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions that Patton admitted he planned with others to commit a shooting on May 10, 2020." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_21.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_21.toml new file mode 100644 index 0000000000000000000000000000000000000000..ca954ea4ba2d230e7731f89636954c367ce4fa08 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_21.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_21" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that Patton's commission of conspiracy to commit a forcible felony precludes a justification defense." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_23.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_23.toml new file mode 100644 index 0000000000000000000000000000000000000000..9196187f648a2b2d050acf937025cb9a5710642a --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_23.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_23" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: Mentions that Patton pled guilty in state court to intimidation with a dangerous weapon." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_25.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_25.toml new file mode 100644 index 0000000000000000000000000000000000000000..ecccf9c70fc9588228f0860d19ae3344b2525c71 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_25.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_25" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: Mentions that Patton lacked a reasonable belief that deadly force was necessary." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_26.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_26.toml new file mode 100644 index 0000000000000000000000000000000000000000..d79902dac32ad134e806864855659752ecc2e9a4 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_26.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_26" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: States that the district court was within its discretion to refuse to provide the justification instruction." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_27.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_27.toml new file mode 100644 index 0000000000000000000000000000000000000000..eb9011d02729a20f72d0d0305955b45888c75128 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_27.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_27" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: Mentions that Patton lacked a reasonable belief that he was subject to an imminent unlawful threat." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_28.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_28.toml new file mode 100644 index 0000000000000000000000000000000000000000..acd4df8961f58685a50cee1e7c5c464378852a96 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_28.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_28" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: Mentions that Patton was committing the crime of intimidation with dangerous weapon on May 10, 2020." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_29.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_29.toml new file mode 100644 index 0000000000000000000000000000000000000000..8d6037a66f26f864bea9ea56daffa22bdc83c6d9 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_29.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_29" +description = "The response should be penalized if it commits the legal-analysis failure described below. Answer Pass only if the response DOES commit this failure; answer Fail if the response avoids it. Apply any numeric tolerances stated inside the criterion text.\n\nFailure criterion: States that Patton's commission of intimidation with a dangerous weapon precludes a justification instruction." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_3.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_3.toml new file mode 100644 index 0000000000000000000000000000000000000000..f0417418cbc249a9a9519889ef74bb235298a609 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_3.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_3" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that the predicate offense for a federal attempted murder in aid of racketeering charge can come from state law." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_5.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_5.toml new file mode 100644 index 0000000000000000000000000000000000000000..99f95f9e3bdceaebe08dbf75fb7ccb4806a3033b --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_5.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_5" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that justification is a defense to an Iowa attempted murder charge." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_7.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_7.toml new file mode 100644 index 0000000000000000000000000000000000000000..26690aea4260a3f2d83156ba82a58d01a7c37ec4 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_7.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_7" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that a person who is engaged in illegal activity has a duty to retreat before using force." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_8.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_8.toml new file mode 100644 index 0000000000000000000000000000000000000000..99b6ccf5c4677619674568b41adf111286ccf260 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_8.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_8" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that Patton was engaged in the illegal activity of possessing a firearm as a felon." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_9.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_9.toml new file mode 100644 index 0000000000000000000000000000000000000000..23904e701a1df6a7d58cc90ebee0287e7778e0a1 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/raw_correctness/criterion_9.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_9" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that Patton had a duty to retreat before using deadly force." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/test.sh b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..66a509a7bcdbe412851f3a012a5ba7b16cf0925b --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/tests/test.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +set -euo pipefail + +mkdir -p /logs/artifacts /logs/verifier/raw + +python3 - <<'PYEOF' +import json +import shutil +from pathlib import Path + + +def has_text(path: Path) -> bool: + return path.exists() and path.is_file() and bool(path.read_text(errors="replace").strip()) + + +def fallback_paths(answer_path: Path) -> list[Path]: + paths = [] + try: + relative = answer_path.relative_to("/app") + paths.append(Path("/app/app") / relative) + except ValueError: + pass + return [path for path in paths if path != answer_path] + + +config = json.loads(Path("/tests/fixtures/config.json").read_text()) +answer_path = Path(config["answer_path"]) +artifact_answer = Path("/logs/artifacts/answer.md") +artifact_answer.parent.mkdir(parents=True, exist_ok=True) +if has_text(answer_path): + shutil.copyfile(answer_path, artifact_answer) +else: + for candidate in fallback_paths(answer_path): + if has_text(candidate): + shutil.copyfile(candidate, artifact_answer) + break + else: + artifact_answer.write_text("") + +# Harbor collects /logs/artifacts when the agent step ends, which is before this +# script runs, so the copy above never reaches the uploaded artifacts. /logs/verifier +# is uploaded after the verifier phase, so persist the graded answer there too. +verifier_answer = Path("/logs/verifier/answer.md") +verifier_answer.parent.mkdir(parents=True, exist_ok=True) +shutil.copyfile(artifact_answer, verifier_answer) +PYEOF + +uv run --no-project --with 'harbor-rewardkit[all]==0.2.0' python /tests/m1_rewardkit_accounting.py /tests/raw_correctness \ + --workspace /app \ + --output /logs/verifier/raw/reward.json \ + --max-concurrent-llm "${MAX_CONCURRENT_LLM:-4}" \ + --max-concurrent-agent "${M1_MAX_CONCURRENT_AGENT:-1}" + +python /tests/normalize_reward.py \ + --raw-details /logs/verifier/raw/reward-details.json \ + --rubric /tests/fixtures/rubric.json \ + --reward-out /logs/verifier/reward.json \ + --details-out /logs/verifier/reward-details.json diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/702.11.pdf b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/702.11.pdf new file mode 100644 index 0000000000000000000000000000000000000000..066811356300c8c94ae688554478e802971f6346 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/702.11.pdf @@ -0,0 +1,1416 @@ +%PDF-1.3 +%âãÏÓ +1 0 obj +<< +/Type /Catalog +/Pages 2 0 R +/Names << +/Dests 102 0 R +>> +/PageLayout /SinglePage +/OpenAction 108 0 R +>> +endobj +2 0 obj +<< +/Type /Pages +/Count 1 +/Kids [ 3 0 R ] +>> +endobj +3 0 obj +<< +/Annots 4 0 R +/Type /Page +/MediaBox [ 0 0 522.003 729.365 ] +/Resources 81 0 R +/Parent 2 0 R +/Rotate 0 +/CropBox [ 2.093022 29.86347 520.0868 710.6508 ] +/Contents 101 0 R +>> +endobj +4 0 obj +[ 5 0 R 7 0 R 9 0 R 11 0 R 13 0 R 15 0 R 17 0 R 19 0 R 21 0 R 23 0 R 25 0 R 27 0 R 29 0 R 31 0 R 33 0 R 35 0 R 37 0 R 39 0 R 41 0 R 43 0 R 45 0 R 47 0 R 49 0 R 51 0 R 53 0 R 55 0 R 57 0 R 59 0 R 61 0 R 63 0 R 65 0 R 67 0 R 69 0 R 71 0 R 73 0 R 75 0 R 77 0 R 79 0 R ] +endobj +5 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 163.796 586.32 217.317 594.39 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 6 0 R +/QuadPoints [ 163.796 586.32 217.317 586.32 217.317 594.39 163.796 594.39 ] +>> +endobj +6 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057code\057702\05611\056pdf) +>> +endobj +7 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 212.027 575.381 327.375 583.451 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 8 0 R +/QuadPoints [ 212.027 575.381 327.375 575.381 327.375 583.451 212.027 583.451 ] +>> +endobj +8 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057code\057708\0564\056pdf) +>> +endobj +9 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 211.736 553.503 327.32 561.573 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 10 0 R +/QuadPoints [ 211.736 553.503 327.32 553.503 327.32 561.573 211.736 561.573 ] +>> +endobj +10 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057code\057709\0564\056pdf) +>> +endobj +11 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 224.828 520.686 286.298 528.756 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 12 0 R +/QuadPoints [ 224.828 520.686 286.298 520.686 286.298 528.756 224.828 528.756 ] +>> +endobj +12 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057code\057709\05615\056pdf) +>> +endobj +13 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 286.662 509.747 401.62 517.817 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 14 0 R +/QuadPoints [ 286.662 509.747 401.62 509.747 401.62 517.817 286.662 517.817 ] +>> +endobj +14 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057code\057726\0566\056pdf) +>> +endobj +15 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 183.739 498.808 299.234 506.878 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 16 0 R +/QuadPoints [ 183.739 498.808 299.234 498.808 299.234 506.878 183.739 506.878 ] +>> +endobj +16 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057code\057708\0562\056pdf) +>> +endobj +17 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 255.426 487.869 377.391 495.939 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 18 0 R +/QuadPoints [ 255.426 487.869 377.391 487.869 377.391 495.939 255.426 495.939 ] +>> +endobj +18 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057code\057708\0562A\056pdf) +>> +endobj +19 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 395.379 476.93 458.908 485 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 20 0 R +/QuadPoints [ 395.379 476.93 458.908 476.93 458.908 485 395.379 485 ] +>> +endobj +20 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057code\057708\05612\056pdf) +>> +endobj +21 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 63.6324 465.992 117.54 474.061 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 22 0 R +/QuadPoints [ 63.6324 465.992 117.54 465.992 117.54 474.061 63.6324 474.061 ] +>> +endobj +22 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057code\057708\05612\056pdf) +>> +endobj +23 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 72.5988 444.114 151.622 452.183 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 24 0 R +/QuadPoints [ 72.5988 444.114 151.622 444.114 151.622 452.183 72.5988 452.183 ] +>> +endobj +24 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057acts\0571985\057CH0180\056pdf) +>> +endobj +25 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 156.848 444.114 235.871 452.183 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 26 0 R +/QuadPoints [ 156.848 444.114 235.871 444.114 235.871 452.183 156.848 452.183 ] +>> +endobj +26 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057acts\05789\057CH0138\056pdf) +>> +endobj +27 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 241.097 444.114 320.12 452.183 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 28 0 R +/QuadPoints [ 241.097 444.114 320.12 444.114 320.12 452.183 241.097 452.183 ] +>> +endobj +28 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057acts\05791\057CH0130\056pdf) +>> +endobj +29 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 325.346 444.114 419.675 452.183 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 30 0 R +/QuadPoints [ 325.346 444.114 419.675 444.114 419.675 452.183 325.346 452.183 ] +>> +endobj +30 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057acts\05792\057CH1163\056pdf) +>> +endobj +31 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 424.901 444.114 458.908 452.183 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 32 0 R +/QuadPoints [ 424.901 444.114 458.908 444.114 458.908 452.183 424.901 452.183 ] +>> +endobj +32 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057acts\05794\057CH1023\056pdf) +>> +endobj +33 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 63.6324 433.175 116.119 441.244 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 34 0 R +/QuadPoints [ 63.6324 433.175 116.119 433.175 116.119 441.244 63.6324 441.244 ] +>> +endobj +34 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057acts\05794\057CH1023\056pdf) +>> +endobj +35 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 121.24 433.175 194.589 441.244 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 36 0 R +/QuadPoints [ 121.24 433.175 194.589 433.175 194.589 441.244 121.24 441.244 ] +>> +endobj +36 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057acts\05799\057CH0065\056pdf) +>> +endobj +37 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 199.709 433.175 278.16 441.244 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 38 0 R +/QuadPoints [ 199.709 433.175 278.16 433.175 278.16 441.244 199.709 441.244 ] +>> +endobj +38 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057acts\0572001\057CH0003\056pdf) +>> +endobj +39 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 283.281 433.175 377.038 441.244 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 40 0 R +/QuadPoints [ 283.281 433.175 377.038 433.175 377.038 441.244 283.281 441.244 ] +>> +endobj +40 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057acts\0572001\057CH0176\056pdf) +>> +endobj +41 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 382.158 433.175 458.908 441.244 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 42 0 R +/QuadPoints [ 382.158 433.175 458.908 433.175 458.908 441.244 382.158 441.244 ] +>> +endobj +42 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057acts\0572003\057CH0180\056pdf) +>> +endobj +43 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 63.6324 422.236 78.3193 430.305 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 44 0 R +/QuadPoints [ 63.6324 422.236 78.3193 422.236 78.3193 430.305 63.6324 430.305 ] +>> +endobj +44 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057acts\0572003\057CH0180\056pdf) +>> +endobj +45 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 83.7939 422.236 179.086 430.305 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 46 0 R +/QuadPoints [ 83.7939 422.236 179.086 422.236 179.086 430.305 83.7939 430.305 ] +>> +endobj +46 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057acts\0572004\057CH1151\056pdf) +>> +endobj +47 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 184.56 422.236 279.852 430.305 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 48 0 R +/QuadPoints [ 184.56 422.236 279.852 422.236 279.852 430.305 184.56 430.305 ] +>> +endobj +48 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057acts\0572010\057CH1072\056pdf) +>> +endobj +49 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 285.326 422.236 380.618 430.305 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 50 0 R +/QuadPoints [ 285.326 422.236 380.618 422.236 380.618 430.305 285.326 430.305 ] +>> +endobj +50 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057acts\0572012\057CH1002\056pdf) +>> +endobj +51 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 386.092 422.236 458.909 430.305 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 52 0 R +/QuadPoints [ 386.092 422.236 458.909 422.236 458.909 430.305 386.092 430.305 ] +>> +endobj +52 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057acts\0572013\057CH0030\056pdf) +>> +endobj +53 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 63.6324 411.297 83.4212 419.366 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 54 0 R +/QuadPoints [ 63.6324 411.297 83.4212 411.297 83.4212 419.366 63.6324 419.366 ] +>> +endobj +54 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057acts\0572013\057CH0030\056pdf) +>> +endobj +55 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 88.8425 411.297 173.771 419.366 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 56 0 R +/QuadPoints [ 88.8425 411.297 173.771 411.297 173.771 419.366 88.8425 419.366 ] +>> +endobj +56 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057acts\0572013\057CH0052\056pdf) +>> +endobj +57 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 179.192 411.297 320.432 419.366 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 58 0 R +/QuadPoints [ 179.192 411.297 320.432 411.297 320.432 419.366 179.192 419.366 ] +>> +endobj +58 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057acts\0572015\057CH0138\056pdf) +>> +endobj +59 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 325.854 411.297 415.884 419.366 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 60 0 R +/QuadPoints [ 325.854 411.297 415.884 411.297 415.884 419.366 325.854 419.366 ] +>> +endobj +60 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057acts\0572021\057CH0102\056pdf) +>> +endobj +61 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 114.452 404.602 136.151 409.982 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 62 0 R +/QuadPoints [ 114.452 404.602 136.151 404.602 136.151 409.982 114.452 409.982 ] +>> +endobj +62 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057code\057232\05652\056pdf) +>> +endobj +63 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 139.746 404.602 161.857 409.982 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 64 0 R +/QuadPoints [ 139.746 404.602 161.857 404.602 161.857 409.982 139.746 409.982 ] +>> +endobj +64 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057code\057256\056146\056pdf) +>> +endobj +65 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 165.453 404.602 188.592 409.982 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 66 0 R +/QuadPoints [ 165.453 404.602 188.592 404.602 188.592 409.982 165.453 409.982 ] +>> +endobj +66 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057code\057272C\05615\056pdf) +>> +endobj +67 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 192.188 404.602 212.105 409.982 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 68 0 R +/QuadPoints [ 192.188 404.602 212.105 404.602 212.105 409.982 192.188 409.982 ] +>> +endobj +68 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057code\057670A\0561\056pdf) +>> +endobj +69 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 215.701 404.602 231.01 409.982 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 70 0 R +/QuadPoints [ 215.701 404.602 231.01 404.602 231.01 409.982 215.701 409.982 ] +>> +endobj +70 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057code\057718\0566\056pdf) +>> +endobj +71 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 234.605 404.602 254.523 409.982 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 72 0 R +/QuadPoints [ 234.605 404.602 254.523 404.602 254.523 409.982 234.605 409.982 ] +>> +endobj +72 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057code\057723A\0561\056pdf) +>> +endobj +73 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 258.118 404.602 277.647 409.982 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 74 0 R +/QuadPoints [ 258.118 404.602 277.647 404.602 277.647 409.982 258.118 409.982 ] +>> +endobj +74 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057code\057808B\0563\056pdf) +>> +endobj +75 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 281.243 404.602 296.551 409.982 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 76 0 R +/QuadPoints [ 281.243 404.602 296.551 404.602 296.551 409.982 281.243 409.982 ] +>> +endobj +76 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057code\057811\0561\056pdf) +>> +endobj +77 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 300.147 404.602 318.857 409.982 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 78 0 R +/QuadPoints [ 300.147 404.602 318.857 404.602 318.857 409.982 300.147 409.982 ] +>> +endobj +78 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057code\057915\05610\056pdf) +>> +endobj +79 0 obj +<< +/Type /Annot +/Subtype /Link +/P 3 0 R +/Rect [ 171.081 397.309 189.379 402.689 ] +/F 4 +/BS << +/W 0 +/S /S +>> +/Border [ 0 0 0 ] +/A 80 0 R +/QuadPoints [ 171.081 397.309 189.379 397.309 189.379 402.689 171.081 402.689 ] +>> +endobj +80 0 obj +<< +/Type /Action +/S /URI +/URI (https\072\057\057www\056legis\056iowa\056gov\057docs\057code\057907\0563\056pdf) +>> +endobj +81 0 obj +<< +/Font << +/F0 82 0 R +/F1 88 0 R +/F2 94 0 R +>> +/ColorSpace << +/DefaultRGB [ /ICCBased 100 0 R ] +>> +>> +endobj +82 0 obj +<< +/Type /Font +/Subtype /Type0 +/BaseFont /PGIMPN+ImperialBT-Bold-Identity-H +/Encoding /Identity-H +/ToUnicode 83 0 R +/DescendantFonts [ 84 0 R ] +>> +endobj +83 0 obj +<< +/Filter /FlateDecode +/Length 340 +>> +stream +xœ]’Ïnƒ0 ÆïV ,CÁôá>kXl׃ëÌ ’rNU^©0úßïLRÖuè¿:‡Ñ—*ÜY]EHS„'‚> +/FontDescriptor 85 0 R +/DW 600 +/W [ 15 [ 289 ] 17 [ 289 ] 19 [ 579 579 579 ] 26 [ 579 ] 39 [ 833 681 650 ] 44 [ 396 ] 49 [ 840 819 ] 54 [ 667 683 ] 69 [ 628 531 ] 72 [ 560 384 ] 76 [ 345 ] 79 [ 345 ] 81 [ 648 609 ] 85 [ 454 ] 92 [ 562 ] 134 [ 500 ] ] +>> +endobj +85 0 obj +<< +/Type /FontDescriptor +/Flags 262176 +/Ascent 760 +/CapHeight 707 +/Descent -240 +/FontBBox [ -178 -244 1260 968 ] +/FontName /ImperialBT-Bold +/ItalicAngle 0 +/StemV 166 +/XHeight 502 +/FontFile2 86 0 R +>> +endobj +86 0 obj +<< +/Filter /FlateDecode +/Length1 87 0 R +/Length 6893 +>> +stream +xœåZyx”ÕÕ?÷Ý&™l3“eB–Éd!„ì†$�„²BH&" !† ABÄ”R j- *bÕRj¬µè‡|ÖZ¬E£´UT*ÖÑ\Ú˜*�K!¼ù~÷̰´ýÚçûã{žþQ_î¹çž{ßûžížsîDDäO›H%ÛÒkׯoŒ\Ên"5§cõ²î%ÎÕ‡ˆì# m_ÖÕßaï±Î'rÜ@VÐyõ’vgÓ¢yD“F1ŸÓ ‚­Óo*Ñä,Œ;»×^7z_ÍuDÉÏi¶®ž¥KNï{ÿ(ÑÄW‰k÷’ëVÕ*Wâýw±>~õš«W{žøã|û8Qp m�t”ÊÉ~ê0�T¬t˜š•ç°¶ŸêE˜ÈÑâ ¡fÑOÕJõ(·Š4±X#±XÔPž(Ã(«Ó+"_ ¤$‘§íÒö«‘Ie´‡êŒ»é$Ö´iÛE›ØB�cm¡Þ¯åb¶V´KHut=½¡ôœhR׃r½~Z+£ûE¾â 4a£×ÀA �Šu›pQ:í¤EšfÅ®3h `¹z‚^SîÇΣÔCÃTI'Ô<ÓD÷ÐY­ž`7— ¡P5EÑdª�ô<£W´ýz9mïˆV*T7ÓFe1ÝI¿6¥–v©Ÿˆ(z‘^£NZ¡¤·ðì£õôä]O�Ú.: ‚Žî†¨7*edª�R&-¤ Ô'‹Éb +Ý­zh£øHéenÀ¡Òd´ÓëJ“RBg”Tq“8Ae"RïTÖÓÚ=ÔK¯cÿh } @a¢S?¨´ƒÛÍÔ¦ò>Ê/õC×Ѭô`×$xÓ!ªGŅ謶QÙ.ü@[OÝä�j%mÄÓL5j+mÖ­Ý*>£�h1heJ=8ÞÛŽ`}u¨mâ~¶Ì¼ã±lÓW²Å)ÚEG ò>ÚÍá}ðF/µÑ†A·Bû�+éJ!(ë¡éWÄ�º^,gÄ1Xm{öÓzý0t}§qv¾W¼CôÇ Ý�´YY¬´ÂvŸAGµúsÐz&e +·pã-—¾›Ÿíê(½¦f“"ÊÀå)¾Ý¬öAQä{Àm%|¤I8(ÊS,‰ôÃÞšjV[Å—F mVߢ<¥›Ž¨©t«˜ÌVÚ`´ž§oEúÊ‹à NùR„I›è¯©íàú^œ +ÃÇŠÇ”MânèGw1¼“á÷ÞÁp'™€·3ÜA�€·1~+Ã[è,àvÆoÛ(Žtq3Ó$®Š­<³…áw)ð&²~‡)›ndø-†~“a?Ãë®×ÒØ{�$®Š>±–n­�i}ô ib­è¥ Éph½b %ƒ&gTÀ"Ð$E×Pàjz°‡á*æ½'z6Þè¦ùu‰•�[]ü�•¬ƒ8_*bŽÔÐ2~§ƒ¦^í{ójž‘¸*–ò{mb %`¦�GWE«háÕ­Lk¡/)£~«™i‹.d¸€aÃFáaÙ½#–Ý#è*Ð<,»‡eoõthrF”²KŠ*æË7‹ÇD­ÄhÏ×òns©°†ñjЬd¼‚e.gigÃsMì[Æ3³D)�Jy4S”`�ÎPÅL+b8ƒá4†yâJú+VåñèJ‘ ‡Ô™¦2®Š¶H6Ïg1Ìä3D:ïŸÁ´t1gFgšÊ¸Šx%g®`8™á$ +LÃ™ŠÆÚ4–d¢H¥pŒ&òw$®Š ¼:E$³'§ðžÉìÉI<“ÈoºEµcÞͣ߮’¦2®ŠxÇö‰ç·âÙ>q"–íÇö‰cûÄŠ¶O,ë?–íÃöÏoF‹q¼O´wÄûŒC<—ûŒã}Æñ>Q"’÷‰â}¢xŸHÞÇ)"X³NÞ!‚5Îx™ÅcèCyä`hgh!l�BD0E`¶ AdÇHÒTÆUd!¹.€¡‘/óVÖ�?¢·<·þ¬I?>·^g�ª0cð:‰«BãU*Ï+ C’�Ƥ�€Iüó ÿ*-G_ÓW4�tô’ö•÷,1Me\¥/xf„á_ä—è ý�бê ïü¹—sôr…ÄUú3ãà ?e8ÄðO ÿ(O9}BËSŒ^Ò$®"#IüC†§ù[ƒŒŸò}ñÓ$®"Z¿/ý½\!q•N2þ��Š^ŽN°œï2þ÷‘Ëáè½#x(oJïàÞÊ2òŒ +ï` +Î?ýyÚ…¹ßK;0®¢¢�û½Êð†/³¤G¾ÄðE†¿eø^ók†G¾Àðy@„ÕÑËUWé9Öõ³<˜á3 Ÿfxˆõò+ÆŸâ·žäõ¿dÊ<{�~ÁZ9È´_Pcô ÖÎ/XÞÇéç2& —+$®ÒcŒÿŒá£ô�ŒWôíç~?SføÃ} ÊðA†?aøcº_ž&ô’‰«´—ùÜÃó÷1~¯Œ©ô#æü¦ü�)»yÍîâ¾Ï8g`º‹ñ;~OÆ`Ô·3œ}iÝFã0ÚAñI\E­"¿q Ïoc|+ï»Y*k·ðˆ³-ÝÈð^u=ã߆ýe¿Z“RmæÑ&–j=åQhëy‡oøFßàýL»ÎG»Ž=g]‹¦£—s×¢þBešÊ¸JkÉM~ ­å=z®ax ÃÕ {h•Œ6èåHâ*j?¯4Ýü¥.ÖåJþÎ +^µœé�¾Uœ•i™Ï/–ñ +‰K(=Ÿs3bµ|g)Ã6ZÞtôr$q•Z}ܶ2­¦Œ -üîbŽ WñΜ§‰ó4*fï;œ¯QmH>9_çiTn ¬Û �µRÏ8gcTÂR¦yŒ×ú´[Ë´¹¼ª†ñ9¾¯ÌáQ5¯®bXI¨®tôrF⪼Îf¾Ë|orÖ¦YtVÆxš\=Ó§½™œóWéJWòŠ\Êa¯ÎårP-;0ÊaïÎfZ–�–Å–�¸ +ýËwÓyש § ÛIæÜϸJœûiÃ4†¦bw©§TqΧ†Éȱ˜Iæý9çS¢�ßDI\Eõæâx�‹5ÏüÅ1ϱ¾}b™ãûž¤©Ä™QÞKãÌθŠ8%ñHÞ“ó5¼_BÎ×�HÂP¶$çiâü �JÌß òY1ˆiW‰ó2q>Æý]B?¦XhC±ŒŒOÇÉ�–Ôy¤±%UÆ9“7“h¿q»Hûû�þÝ ü;þ‹�Å‹,†®©Š Iñ¶JREû�¢yMñ¿^àš<éï†ñ6Küª=Ôpl¬¶I‹ÖÐÇP“ühIîþÙä“'UÕ6Å»f•ú¶�ÕZ +âü& r2è³J'ΊBæ�Z‡~?ûïÄâ`Ô¹;á› àSú¬ÿý Ñ”¡‘¡t²:>45Ôî²'¹ì®�F{ÕèÑÓæ�–à¯Ï¬1Rñ^“¹wü|œ­˜¢` + + +úSX¨j ·†…ÙF†òò°Éà =ojhNNvVJrJrrvVNfFDx˜aij[RmK™ÒVÖzÍC{ÍçKÖdNŠ´ú…UO.oß¶î¦?ÌÅþ}cCâî]^dU�ù¿hŠ ´1{#CSs/ìæNHî[^Uµ\¶{eWÝÙ yjÆÞÒêôSxßIî¢Pú<ÐøÜñvà™H5:|¼tˆ‰]x³Á‘!ÛðÔ¤ ‡Ý¦¸»ÍáL »�23$Tj¯ª¨¸ª¹¼¼ù´yJÄŠXóå(Åwౘ¦¹Â\iš=âA±X\%~b.0÷š{Ì&H0D¤žÔO#M,r:ìÁAšj�Õò5½íG–$5Áîn;>�1:eMʰ;ó¦ +÷‡E8Ã]ÙPœ=+9%;'Qo±4õŸÚÜÔøíïˆ0ýtngֹѮZ£ºÚ¨éT»Ûfë•ù4ˆþ¤¥à›hfQîP6Kb¼å÷oÇÿ…]Qš5>4h‚–¤ÅFQPl¨5*8>ôŒ#ÏîÈã–Î`° `45Ûeg%»Œð0Ÿª³³¡iDù¸2rr3 Ã’-êÅäÖºÌR÷ÂòêVAOŸ¶®þ ‹Nö‹þk¯q{œ±ÆF1O¼wä›·d§„-‹©jiŸ·mÀ4�õ<¹$~Öƒkçw­ý`µä¿ü¯Ð!2§9ü-ê_üß%d«lñ#k°…@gïJöÀµä,�Œ€[—ƒB] †Åê +WÜÀ‹EÊgæø¾î9Uê�§~. +•9"av‹8¸ÊT:xñ•on]þ�އ~Àüí¹-æ§Æøx›xá�g7wÕ,/öÔ>uó¯Æ<.—ÙúÃGV5TuVÕ•ÿî¶cæ×­‰iR>+âA7<ÕIýÅ©€Áˆ“~ÐR &5Ôûï"ØqúˆürÆÀ)Ò1ë{WêØ~ÜŽÛb"€Žq(s ÅÆàÀè L[œ´ì—<gl´` ºš*ÜÞôzé¬ó™S¬®ßa_l׋í-öÛoøFãJyîôÊomkÌ[6}ë܃ò„ËÃ'=7fìí€!óU2}»x28±Á"Iþ-Ò +oN€Å]˜ÓÈ*&€®‰PìX&’€�¡HT)Xiú Îu-°øU·òŸ@šA]ä‹í#Ö½åÞÈñ—`áa¯ñÙþ™÷.Ò .hrrí9¨ÞlÔä‹2Šc�-k®»¦­x©¹ÚÜî7{fíiþÙ'æÈ±åÿUv½GÓ”Sf\ÃUo¾üÄ«ÕbWC¡¥4ôŠèóë,0�}zÖ˜>cuÊœ$ÈX9öަå�óêâqì¹qà;ŠâD"$ŽnHì ô�ùPÈ„UãÑ[¨ž3øñ‚¡Ë=–Mã4Pþ ¢‹U'êÙ‹ÅT_¬¨8yûGæ¢ì«GÞóÌœÙ>}òš­wo™ÿ]UÙ¿^äüù Qú“M¥ <ÅÑ !±W|öÒ3¿›{U£RÍÔ²áQãiIqNQ|('‘žÀy°ô;1¶r³uà?T�Õ‚Ú°v)V°pH#-3"ë:¯ƒ¶`.˜¦Š$>Vª—éÜËÄ¢ðp±]´èõsªÛ~pƒç®’¦Š�îüÔ|I¤¿ó;aQÚÅþÇž4?zàY�'wÛm¢àó?‰Ró�ÏSdÜAfYaX‘UwgâDHO“÷k'¢ƒR¢²p“SLBf�†¤òo É žãs\¾ÿ`¸O¡NŒ–ño­ìsat5V¶ò‰k§‰¶‘‚A™†½GÉç†S>Ìà”jÎ𖜻œÞÜåÎÎ̾ìÞp¹�®p—�µPœ¸6ÇŽç~k÷ìÜü-Ι’¬ªÂjŽžn*ÕÕ–éõÊá®è¿Z»hZUi¾ßT›=²seaÓ¤.yöª¶A�¥¡8~ÎqCþj)9ü·iÃñ- ¾ ê•¶oÅ +)e 0$ŒõæáãCÞ !’^èeü«—î8R2\i«,ïè(¯Xº~î´isW¿½"¿Vo®lï(/o_zöÓjKaƒ.ÏNØãF­Ÿn©–'ý�àPæƒVþµÃáåÐËßñ—${™ÿÀR¥äÇ9¿V~^ýØwtÏžäÏ{¿¯Ûàÿéä,|#˜­‘UgâQ8xÒàÝ‚#« JWÀ“âáoÑò¯mÌ¡ü?+äÊ`P}®ï§&aU+p©ß.ŸII)Ò|5;ê Û 76{+ 'üÈ[½;å¿¿•Í’›Ã†ø›ËšŒß—„^ûj{À´Š½óoÿÞ´¹çÏ›VX’ß›>mîeV˜}zÆü†Ã‡Ì)â2WÐ(^liœ[iFÊ1ü© ù|—–yY↠ÒËX�È¿ÅFÒh® r×ÿcrÉÉEVŽ—mΨ¸ÁI/BÚUº»úúººÖöšežºêzVÿºj^cã¼9GzVÌ©ó~úÞ{þôý“CâhßËs+jj*æ¾Ü×÷jMeÍœªšW}6T÷Á†I´ºXžåpâ‚vûS4.)²~Ft9ð¥@ðŸèó¬@¶[(Æk±ærKözØ€ïjš1R0:àK yÞúo­¢æ\:òG‡ q²A–ë ˜~˼êÖÚbW–C5B�ѳãÊZÄ%‹8¦Ä˜æ·7uÔU.Œ‹ÑƒR¯šcÎX8]H?;e†ÁÔF;‹³¡ûPDáŽÁe‚o\]ákS…üís<¼Ñ"„|ò—Úsä™X ùCù—Ì(Yqàí@¼•Ì;Ea§dìc“1Rfè~Ê´� Èûn—Q§ïîd“*g†Í”ÙI<]$_(ÌÜé¡NþéÅK´X„á‹xl}§ þbÔì‹.ÌQÊ Kù'…?T6K<ŒbÂ\¿úÞuË6×—d—YTa‰›P›¯Þ4-3¸ªJOމ˜+ÌÇ•ž\q*)×—h©ªÒöh£[Æv^ÓTÞ\”æWÐ'caþX´ú¼~ŠfR½]\�â|*D%šé�{¼ôš/ÊAÁýYTb.PÖ«•ºJ.ú ¨J Q�ZªÍñT*ï4;Ö¢ÒR¹&•êtÐ"i+É¿í¤cåV¬Ûz:êÚxfæ‹Ñ—b&Žn$ÿòÒ€íe<_ãŸ7•8ó|)E*{`PÞR‡Ïå�íõ¡‹GÖ7—²‰×÷¼©Uª>‰õʽ췯¿Ï:Þƒ(Âä‰ô½ÄùY¹cÁ‚�Ü÷\ãì¢9ÕE¹seÖ˜ÃÍ î»aqóc»øDã¬ìš¢ÂI¥óz×ZÔôãóÌ\Õ˜”]ž]ݰ|b^©¨)Þ1oÝ÷7v”À‚WT�‹-É›X]ôaõsVíô¯ÜVzý]ë;‹f]1¡> "¡,?usÓe;k¯Û)~”Ò˜¿$cVVâœY53 +µ£Ô-“¼>rÛHÛ”ç¨ÖH¡ÉÚª´ÄP³ñÕˆnªQ{i?šC#Zgì#ë›”cT�¾O);ƒõ5hChÙhehqhuhõh=¾ùü��Ôjì~r٫Ôm9E7ê_ŽíG�žª“s©z/Z&¥;1]M#—æ!Íð€¾˜R-C”dDÛNõúB¬“ý0æI'ªW¡7õÕ)£xÇEnmÝØ°qhì,ÖkÇNiÕ�o=Šà¹ ýÃ�óQ–[6È-e¾ “ä_òô¿6ð(ù»¼yù£L´\Ù_àíï›äëò>f({Ðï¡l7¢|í ÈDŸª ³þ{|íð](u%mç×9¶�ùÜGG}¶TdÓOáŽòèØM¸õW£ò3ž¢)úó�¥«”¯>HÙ†‹¢ ?°‡ô ¹‡^BåÚž± ¬—²±µ)�m +¥#iìÁûtAWò»þéä±ôc=_Ë`ÃjBë�O.Dë•û©#dH½KÛ �¹S{‹J•Nè©“²õNø Ë/ý¸–߯·öR3Gúß…¾×ë—7Ÿ�ê�:ºæ‚½.4i ìû:Ú ´!´¡»Íhš�–‡Ö!×€R^'Cú­ôé£^?»pþ¬l3ðÏrÀÏ¥¯ùô¦Ón47ÚdKíä6™Òü^÷ž黒׋{ÃÇØ¿/ôøª”ý˜¬nQ¥ý«g!žoày’¾ Ÿ[þéóµ²UÕø)¼øìR¿ð>ÚíÚWÿüѯÕ_Ñ_1Ò�ŸËÇÂÏ\<'üÒùÙ{ùãŸÿÿÿXcÿs¾YË_FV¡ÎY�ਠ¦+’wÐÀdÃ÷ÁkDôü­O´„|!Oà�¿œuTæ“ ½¹Ó ´†Yq %דw_Ë!÷"k/涆]œ¹°@ûlFŒ +endstream +endobj +87 0 obj +11608 +endobj +88 0 obj +<< +/Type /Font +/Subtype /Type0 +/BaseFont /QUDWWP+ImperialBT-Roman-Identity-H +/Encoding /Identity-H +/ToUnicode 89 0 R +/DescendantFonts [ 90 0 R ] +>> +endobj +89 0 obj +<< +/Filter /FlateDecode +/Length 472 +>> +stream +xœ]“ÍŽ£0„ï<ǙÈ`·íŒ!%d"qØmf€€“EÚä�CÞ~MUv‹Ò'Ü媶»¨›}†¹øÇîèçü<„>úÛx��ÏOþ2„¬Ty?t3‰ßîÚNYQi§¯íÕÛ~<ù·¦÷aæÇÛÏú˜÷þœ4ûãã6ûkÎãfSüHµ·9>^PðZ|‹½�C¸¼¤Š×âxŸ¦ßþšDòUUQ íðù˜|® X>w{›ÚÎÇ6\|¶Y¥§ÚÒSe>ôÿý6ªӹûÕF¬ÞUé«Ö ¼€P–€‚^@¯(     „5ÀÞ–°8¼iz+áMÓ[¹l €@ÁŽÐŽ‚¡;B; +v„v¤…ÒI…I5 4 4ŒÕp`è@V€=v,íÔ,Õj–j;–vݱ쎠;–Ýlj¹© ;–ÝD°Œ èŽewÞìÓÎÔòL ŒZ5ˆm;^à@Ài;ž¶AÇ#DpŒ`Á1‚AÇ#DpŒ`Á1ÂÒ[.Û%iµÜ“jº¶L›®øó./—}™Ä¿ƒ˜w÷Óü`\1<ËØ Áÿ›èiœòTµ¼Ù[ãù +endstream +endobj +90 0 obj +<< +/Type /Font +/Subtype /CIDFontType2 +/BaseFont /QUDWWP+ImperialBT-Roman +/CIDSystemInfo << +/Registry (Adobe) +/Ordering (Identity) +/Supplement 0 +>> +/FontDescriptor 91 0 R +/DW 600 +/W [ 11 [ 398 398 ] 15 [ 285 ] 17 [ 285 ] 19 28 569 29 [ 308 308 ] 36 [ 752 706 741 819 ] 44 [ 363 ] 49 [ 833 ] 53 [ 727 662 ] 58 [ 1042 ] 62 [ 398 ] 64 [ 398 ] 68 [ 558 604 519 610 541 366 588 625 306 306 618 306 928 627 588 610 ] 85 [ 437 479 350 616 539 829 604 558 ] 134 [ 500 ] 183 [ 285 ] 192 [ 638 ] ] +>> +endobj +91 0 obj +<< +/Type /FontDescriptor +/Flags 32 +/Ascent 760 +/CapHeight 707 +/Descent -240 +/FontBBox [ -178 -243 1237 967 ] +/FontName /ImperialBT-Roman +/ItalicAngle 0 +/StemV 88 +/XHeight 502 +/FontFile2 92 0 R +>> +endobj +92 0 obj +<< +/Filter /FlateDecode +/Length1 93 0 R +/Length 11015 +>> +stream +xœÝ{y|TÕ½ø÷Üsï�̾Ï$™L’É$3d_&Éd²ÎY†¶$„Âb@A-O\-`kUT”jÝJ©")" ±”ŠRD¤–ð(6¥¾š" ÉÉï{ïL ZÛß?¿÷ùý>¿ι÷œ{î9ß}9wJX sî\‘šg g¦‹]ˆü\ó àÜÝB>½†ë…ÉlhÃë8Áo…Cܾ}BÚGØÅÇà<7ο[ÁGÂpžŹÇh®rÒá<¼ ;éIì]Æ™› ‰¾/ºÎqUP…8Œ‘÷Û¾£„Ç9Gá WÃ[`6TóëÁ^?‚«p/¿]¨…ä+†&®ß< OsMÐ ïÃ$hVãÊ»Ê +¤É«°¶‘•ˆå68AÎ Lá,†•ä"\$'8îÑÈù௜“k&?"_�|XKª±×ý|,çAx7RÀNTÂn®–Ãjh•ñ]�P¼Æ½†Ïja%,/Ü õä¾�Žtì%�8{7bÞ…pí�/ˆïÂøV˜Ï&ç Ú!Ÿk‡UX–p}°ŠÎ&/BX±^ØÅùÈœ»R„Há_æM‘‚»läÖA«(rI° )cÂ�›‘ïH3"’¯ÈI0ÁG7ŠçÁB¾‚Âv””IH§.ðq­pškÎG +Ä!\^ð +«…{‰ʰ8„õ‘"QÎÒ/àäs:÷*i…Çè}ôÄ;j` BZ£¨GªÖ µãD Ü׫a›p0R –¶‘«¢S¢ÞúyqQ¸ |�;œ—eኸ„„ùÜU¤*HÊâÖ�À€’[åv>ôc;On»`¶·�¹ØÈ-òó¹d¸°7Wž!ÝS”SéÉ,¹í#¶3åû¹�.·mr;Mn[I 8q�VyýÒ ±Ø“ƨ|OÉyÞd¹�$·IlÀY#=8úìf‡ðl?Ýì ÏÌ O3ú£›öÑ'ûé«éãŒþd5}ŒÑ¯¦�nì6öÓ ýôFft£2ú£÷3zß‹p£k,ôžúxáž…ônFWõÓ»]Éè�ŒÞ!IÀŠåㄌ.GogtÙR£°ŒÑ¥Fº„ÑÛöÑÅýtÑÂaÑBº0….è§·Ç·î£óÆùýt£]›è-ŒÎet>™ÃèlFg1Ú9S-t.¤3Õ´c†KèXHg¸h;£Ó÷Ñ6œÖÆè´M´•Ñ–æt¡emN§S�ÒO'3:‰Ñ‰ý´i5�€[L`´ç72:>¼[¿�†•éBx7m@l­�§uŒÖ2:I=®ŸÖèéXFÇà‹cÍh5¾[ÍhˆÑ Þ­ªô UŒVúiNª`´šÈ¨“ÑFŒÆo¢qýÔΨ�Q+£³N°0j6)³Žš”ÔØO ŒêÕm¢Ú}TèZU)¨7Q¤ª¤Êt袟Šû¨À' £|¥ý”0 +«)ì!s×n$™ÿßýÁÿmþ§ÿœ4‹O9YɆ\ZÝÜÁ‰­ÉG¦¹²³¾ÓM6(’w@Óíªä=CCM­¼C˜¶CHØAÓbvðiî/þÙÃ/²³šZ“÷�EcÇD—Û9'·â­ÔÃa;&8èb›ø.áeÌf�´�àŒµD²`7‰~Åñ�Û}ª7 §zOõæ™�.cšËèêâa`9u \d›ºk½]L ÐË|´C¸ZH ZNˆ{u"h*••êpÃüõzzŒ�@I£Òì"g4˜ìÔÏ>egIñxOîß’ù“+èå3È•ÃyYû„�dc:Á|\µ¼KJРU€x"»P«JÚ$ÿnìAyiÁ[l28¯Šxˆ·ùTÞB¸r˜™pÝÓÌt8ÿ Ù�qHy÷€„ɽì²zÁ Π´æSÚ�,fjp¨â-†¾Þ@ º~ž¹¸¸¨Ðëñz¤n5YÿÌÓ�Þ>~EÚØb Qî>ÜÇæ¸Ø9òê¿Ý‘ÕìH×ÝK^û9I¼kí‹Íù¦HHNµ¤e¹=´ñCQèA4®&{ÀÁ Ÿ¯»[ÂN.¨”E(%QÔnb6,Û6lù‘#8'2Ÿ¬Õlý�‡ï¬l°ÕŽ»üæÁ¯îÿõïÙÙK¿®/+ª­¿·ýñßçþ8{óCë–›fcίi(¹í‰÷·¬ßëMøÍ ûûÞxhôÔ1¾QæôÊ]/¾¶PÊ«�§aá ¼³Â˜`ŠQõ>F« ÿ¹z/å”T¯³X¼�GI½ +°N•÷t”÷ �‰pEëTyù‡2Û9#!E(eE®"â3ú¬n«$cÜ‹ÌF”MÜÂ}ÐÚÛÛq/—É­¼cðã°0~Á¶Ut÷@ýª—o›HÃ/š‘q˜Õ{ >8 +ˆUTžOu|fM<£Oå?åŽèY½':€ÆêRkRI¬‰z }¢pu‘î²íèFVtG).Áeöš]V-F¢‚ÕßK`d›]Æ]\å(_?é×DÍŽÿigßÔPþèÀʦǶ>»aÊZî�Èým{:7—}yê*;¸ûÞº™ %ÞYZNî=1[¢içÐy>€4UC.Ò4M£¤©Ê÷ôôLlö™Ä½±‡ôy^Qã¯Û#ªMhKº<Ù–ôõ£ú ƒ/Áþž¤ Ädº WÂÀ$ Šˆr#Ù•V ’çp˜½>´vÙÚµ §þ8¿â•y¿ú&3}ô‘;ÿÄ.‘qCOXSQPg®*ÝöWÏ®²o>~û¥÷ï*jmcýÃO„æ-%‘²�þÉ‚Ñ�£sœcÅì|ö +re JJ5rÅùA»N£¢ŸjŽ€F TËUjÐÕ`2œêþ Y ©pT¯ûºW±‰¸"ÖÐ�là8JIøšˆìÄÆ¥ºüqã+è¦÷ÎY{¸:rÌk›"[æ³mƒ�l'š9h:Ëç£ÝÑ@äÃø`vœV¼'mr–ùLòÞ¬CÒˆ'ž·´n›ÂéNS*ÒEg Õæê +FjeT6dÚ¢¥A‹HÄ›ì÷Òâ›jiWxþQ)Sq„ô¯ZýÆ�zãî8–-ß´tùæ¶)SÖ=0´ÿíÞuOí{�ýþw§ÙÕ§¸*·u­yþ'·µþ¤‚XKÒ¼àÑõ]cîÌ:ÖôÖm?ï9øä¢WÚ~ûÃ�_�ݾb/JLJ|zTbj‚ž¨Ä ¸HR³7ñаÄ.QšA –™a‰�È ÇEAÜì’¨p»_”×wÅßD«Èƒ(3-˜ú¨¯âÕ®]×"2CâØÞ!xúÃqåã$¡y›®À[ùñž—?¸Ë7­�Ço +Î_ÂV±]ìIVúä­£'ŒÉN¬Qdå‘vIv£>HÏ#fvH +êÑšì·î£±&3tˆ5ô•÷HÒŽxÏ3�ðÈÆ÷»Ñ%76–È®Y¾ÒvXö؃�7ýõfŒ'NÊ;%Á¨ E—¤¤I§’“ôèö6é$7ÂøˆœúÐp8ð­-é÷7¶NhnÏŽ5¸³uÓ~ø×÷/+¼z,i¿ózJnè FwU¨+$ô`aœM¥àí<c¿ÿ•dÐRþxÌMˆ‹ÞÅ)ch’ÝfVA¯U$Q½6/‰æº }ÝÝ2kÑ‘Ø%w‚ÚTÞÓk/èë�Œæ•L­Ÿøˆ m¬+xx] +Y¨Ñ³¿O¾ùïAÍØ¶ Î߯¹²N\I:&jµÍƒ[&j5coáÚ¹Òë ÂÊ mü�ëµs& á°�_px7±Àž—o KúW 4!6*ŒÕ2`J0—ðgJUÇòêËðeÂqÓeçþ²õ¸Å¤Q%¦fð /r)м ¿ +bó3QP z +¤à6ª€¹½hêz%<¢†½Æ œ½ºe7"+E®þ¦’ u÷ÿöÓÛØ×ìzçõ_þ�Í›;iòîÀ߉òõ_~ð;ù%÷>7¯dÓc�¾tû�¾ï�þ×´®™^l®£u»¶®y=Óy`óö‹hÑæ�vb„— +ÕA7¤ÄÚÌ ’›�ò'>á¨a/ÿaZœ¨-)ÖE’ŠTÆ4Äã3ŒHí7Lˆ®#¡L±‹’×özPÏLþbŒSx)ô™ÝR ±ÓÅB礹ì7Ç|mîš5-S÷Ë÷ˆq䛯ý_ù’ýžd|ýèŸÉêÀ®7§µ,%Ž7~Dèm�<ÞìIaþ]ï°Ç1@ÿœ=¿AÒ,䊘�\ÁLÊ‚ÉÄdæÁv.Û‘úã:mj,(ŠKl:?˜ò%à{PtŒ# �%}2 9)dýÑí6t4J“‹\h»ݘE·NxÛà6™â¹'⼟îzsK×ë&]?ÐROŠHÙë„6Uöo¿ItÕlöö�ƒì­ÎªbÉ¿cÌÁmEÈÍ�Œ7«”ÀSƒö¸îˆH�ózZ Z¡Z™�Y€½HÐ"àrüšf–s9ˆuYQÐɥ慃O‘…-­ wë‚–+­µ´!ÌյЋ-u\þkÁ=ë‡.‹wàžIÐÌLJ0›Ðs)hœMÜn8âTÐãBŒZ¤|5تMãbý zÑãÔùÉ2ÙNõ ôz¢íJA÷Õò+Ãðø|V—Ï=Ñæ.’3º y`ê =ÅéSÛ*É:º`Æ-d`fëÄÛµ¶Iáð¤6>Ý“.Ô]ÿ€V¶OAP§N»žÊå®páuCt‰Ló*)UL»lN9žzŽ8ìªãqj»ó2šžå‰5+ÒilЬjLOSâý©æ‚ÄüìaÝCø#~B2&FÙ– W{¯œº"« dN’e-‹Ø’"™D/�"8,‚1ª�Ü’CòÞßMÂþö1l+óéÊôv_™¶@5¸YòÌÑßÿðsáÝŽ<|p‹k*á¸9BY}k}ø¦p,<ðèc›ÖKr±ýü{èóaa0gKBùÀP[ÔhÓ<¼¾$ñhVÒQóÞ¬ Ò4)ñ%á(´ž”¸¥C9>�kH± +0=í9ÕI$Ãé„)0BiQmí»*†v7õÙ†#ÙøK9ÆÝ•m©]2>5¦bÿLcì¸ð•W߳慗?ÙC ¿›}NçÕ�U�.8ýìÚïzâíKÙ'—îgWqÉqä³ï<³jÖšÒ²ð;õÇIžT6å…­÷ÏŸ¸´°zâû›³ë³=ˆýÐ9€˜G�ã¹0/X‘�áLpè1¨QfzS­&Q ÇÓÌü‘œLg†‹z2²hª6۫׉“R“—k�ZR=9&�æb`ÐÝ]ðY·ì=$ +|Û…ô•—£‘¤×,K¬5â,ñ~»‹ÁBQatDAP–Ý›<«¹¢“µ:ÒJaoG˜k꘤Ւ)X¨}J+¹8º=‰™ZQ^må÷v6jëê„|Ÿµ(uàgÜ;Û'Eú¶’ä�-´“*ªü¡®N7uÂõ +ºxàqÌks™�ò²U+ Æ+T¢ŽS]Ñü…»Gt*J0ãÄ€Í7:"|Žœ%—h•fŒˆ-É%ß6¯ªjÞm,Sx·aìŠþÕËÇJgÙÌÇ�°wÉ +ÆÊ»\�¿àFGtjÜ…×�GlÒá²2É"Ë$ÕtÉ;¹8`Ù‹»ªªº“�˜/ù©ðŠZJ�­[²áù'ï®�?=5dª2¹ÍŒ³ŽöÏšÖÚ~ïö^v¨¤lv^™š{�-ºû‰«çv�nCkBkÆñôÎEÁ )æ„”!>�iù iq`#¶i†ÙIŠYi²|ø–…’�îdnÀpÔþ�/Ê\º}ÊÄß®ûœ}2®füg«žú¬¦(¯JÓ^öÈ[o>9õIâ(^÷)ÿó‚w'N›³å–¢šŠS‰*¹ôê»þ÷täD+rbrBƒœh &h�jÉJ'À'ÄÆÑd«SųtÕPò…ôA‹ÄS¶3Áb˜£…–ØNK»¢Ã3YbC_Ï@yOøá¼ +É/Û^Ù«=7Á½Éô1hVŠd�“�®”ÆÚi{Áªº¶¾ô`xYÙè9óÞšZÞÐúÒø†—çMÝZY"ñÇ&ý0Dä÷ÍÍÜûŸ_¶ò1­!}•Îm¿nžZ§©Ô§ÙÞìœÖ2~ü{ËzIE¾Oò£SPU|X!êÞ2€Yk#fÛÂïÒ™�òº=„­ñGUȧMvbïÐÞ¢ïPÌusÅe‹œ@šä«¼)·º"Ø—Œ*ÝÕ\ÿÁSWØHü§'þ2è{usÛ“ƒŸ’ËâÌù!I÷=v?Éúûפ”ý¡_ô¾s¬�¼·yÛ’ÿËÆ`; ù‘sÞJã¢4¹…=Dñ–ÂqÔ¤¹6Šì#¸@AÄ c?>v”5Ñŧ̷¶èG¥ºZôóÄ[cø® Ì©z�'˜ öŒ°¹=W +®F†j|²SwùŠ +¿_¼ì‚Õ%3ªªcÌ®]oýlöƒå¹ùÎWPB)ê“- ª…Ð4îh—÷Ó¯;kŠGûó„T�!®³µlYéÌŸRÃ…¤ü!›™ø×øu„0´ÁOƒöñÓ&Cü˜JwQI}–Å.ÒiЬzÅ´1ˆë®ÊÉLW´‡Ä‹<õG+“§é¦»KšÅ˜6^*ÈU[âCtÜ¢2ºØ*»­y±:´È©^�;%ݹ iŠqzÄù˼ê1|rE6–�á,*r.ÔÝ×�™ˆ|2tÜÐ5#âøˆÝôË$á]rÊï—SBÿpbhÿ>}”³9�aRÌ#N0¡Ù6&4{íûª÷±—Y߉!¸oÕäÍsgu ¼S½²$ïöêÆ®r_f‘]¥vUe+®ìr„Y:«sùŠ™m+oŸ=÷åÇvž[ºÖHÖ§‡£R¸Ýñå–4ý›G5¥ªòö1¹OÎ|æX‚sÌèÖÑ…ÅY–LA©È(¬ª}¢[$mË×=´ôönxÃÖ1®mþ�–ÔT ¼UðgQÞ2`vÐlöjU:j3f¤ºãMJPÄQï¢ÜmLvŠ”îEÑ3¢ °'òfÚ I�îggÜ­Ði„eW4Åë‹ÄÉr¢zÅ^põŠ”,EH Ýo’’ˆÚ5ãÈ'%É Á©,¦9(ÛãÌÚçZž}¥ªY˜ÓÞ¸!x®µŠ¯®æ«ZiÔ¶åNj:¸›¹‡Ÿ�“‹–Ϙ‰Ú_�& Q` 'T•ñq6«Fpê•{ˆæWô„sФßC„ ÎËDýMKœq޵+1’wHd¤ÄCr2öo˜ÿ•ýa¿¿!\ì5vÆ`ßôêPû´·Ú„{¤C‚âñáëÏL¯âBÕ´sði|•.; ¸¡LGÞGØœ¨ïS‚Z„�f8­&p*M^ >× §é(ÝC´A«s0#.>Q¯—¥Z[àÍ +ñö Ù@�ŠÄ=îãj$%�Äó·–£‚8 2�ÙñÒswo äÌéI%¡ö¶Ými(ñ‡‹Jö>óü‚éy¡¢ “O4Ç74Ó¯¢8�ú(~‘%P–rᎠ9FPR«&3}T‚#^§å•Än‘ÈJÄ]9)I”H JSr2Ä�Jsð.[zŽ%ÁhÓY\[RNg†¦%:ù®<™å=Ýø�deÔnž„D½}Ôš K)»F3š¢ÈUÈG#ÍÁª–E¿ “2w\¨”Kh\;þMÒVÒ¼PQh²ŸÛœ*Iz˜J¾Úâ2 ˆÄ‘”nKöpcǪBcŸgÙ EªPµ˜à°g'ß3?•dé@‰«A:Ñë+�1Ù +�ZBX�ë4<Õ‚zŽ¢E;ºLIaŒ²óþBó-)Ã|ºªÙõu¸¦cðëöjþ¢Ž˜kè?ÝäB!¾RŠ4jcø|ÁCÁXäå¦�JJŒµëÔÆJÂ+´¥ÔX‘å@eªC*~°Ø—–bŒ’à{ +Ý&ˆ/W1*ÑÜi÷uæ;í-ÚÔÎQ-)�‰E�¹-�®ê9°œF'’°ËË%EǶ ’XJm‰h¶ýŸè÷¿�Ñ'ÏùBON¾õÉÄ©Û;7ý,(iÕŒéµëü¡f¦œlk«¾/¹­jžýú:©bâÄ·.[ôm+pÛ²ù³Y|Kp¸¿dig;Ó ÷9WK¥PeÈvB„†üE¤aÌ šÌºf�j�ªˆ)|ËfŒØB‰rq‰¼É¨üŽ)¶„7 a”DH¡¾réäÅ¥Ñ÷CÅ?5†[‡ñœùú¤Í–æg_‰ŒÌ™>áÑà¹Àæ<’B"ÃM´-ïèù”ù<–Ãg �gZûÜ–Ür97·öüÚÏI;õù9öóqßÕ�>ùæ›SÍ/Ô/¹›êíeIîîb¹ü:Ü]9pKÐæq&Çåd2¼oªâ´lƹ“‘¶¿r©† ƒ®=D´Å]ÈÍÑz’;AÑakÏHéL€Ïôܨ³é5|+î,�BO™ÂÑ�‹#£ßMFÄÿß#s÷­[²ñ…M÷Ô?–R€ŸWUÙ«ÛXWÕÂTÍU(hÛ¹^)Äÿæ³7×–y3üÏÍeÇZ*ù1cøÊú×oK•pNƒÆ Åi±+ÓR Ôœhw�Ò0Dãí’,cÓÀi¶k¦ˆ®¸Ns‹³ËQ8ùø7ñBÝ�¨ý‹¢6"‘ެ£Zäû®Õ¾:³¦5èO͈¡œWöpfݬÁ«ÃJ“ûÀ}S«Õñ Jkþ3w³ú¶Ð?êEçк1�ÎdJc­‰&Èɧ™‚Z“šÆÇ!>Q`™‰(E™ +RÕ®˜XGœ&-&Ÿs-Ö;YŠ0:QŸ÷"o<Ð4z’c P£Z£ç-1vêF“µÓâ�­•#�OR Z.x +#íÔC‹ºS±ÄÑ™ÔbŸî•Ϥ.šH÷•Ÿ*ï•uI6V’5ÿNÒæWD@5Þ— mÁ–Y;&V5ÏÙ1^%Û©ŸW5Ïú÷¦9Ó Qh®ªŒYÎ�/PQ‚(\çÐLuÿŠl•d ÇóÝ1³S:;?t­” ܘ“êRÐ"ê´D‘š”  ü;èF¥ +‹8OŒOµ¥ÄÑÄ­*Õ�³@H "Ÿ�¸JäS §¢OìÃç_Ô¢_yÔeÆð�›ß<2h „±õÉSŠIm@©y&6M¯±$«W©ƒ“ÈÎÒÚ¶ÉDCõM1¡�1Ë«Ir°Íþ®¼¤¢f ™›cËÏ׆BÚ꥟Iõ õ‰Û£¬ Æ+Jý™ÞT·]ÆL_]˜ïŒW<òig�C؇ȕÈèåTûs2©¯ç„|¾çN¶+⵪ê�¨hM0ÆKçûâEþîjéÐoøÌÏùõÁ·þ h1Ëÿ7ˆœ*FŒ~—*nŠSð†’/ؾQãä×>µzƒÒk7fªøÇtŽŽ¹FÊËÕú§µñ:U¼õ':}h4Ùì“Ë6‡/ªÍ +u¬¦OC“ç4èC!…+Å”•À^²-˜gS“¦”quÕiÖ7[ŸRŸáWHÚÜ¥±Þl1âªçœà|ñ…ñ‰eqƒ§Q èµ!eK`mМŸ—ëNqYÌ&Qà5$Ñ¡¡J)cNÆ�þt%’.dz!e”+Ö’Ë;‚?Ïš'ë]w©$†ÃYµiø$(Ò½¡ƒÖù�Lä¨2mÁìß'x +”<÷�ÉŒŸÓ±%ŽêBòçPi2O¶Ç&ê4.Ë�¿™lí*å9öÿó÷Þ*È*‰1ÛŠ:½*.-V£nzœiãb({¤°>ÍÛšKº +lYYÆPȰ^ɬV±»ni Ô—dóclæ¹³¤è鎡2º^¸€‘ýTx)¨š,ÌN4å4‰ú��$@!q‚ jH"!ÛT0ᨈ£^’°36X·‡$óJ÷Ʀ6ט2 +³'ÐÑ®¦ ejN¬�d¬~Ä?úá +×ÃŽŠ•JÛdÿJÇ:°å7KÇÃçXú¾÷8Cúè5r ñ·Þ¾5Ï<ü{´?F#6›õ{sÂ^Ö?âÛ÷wOƒ"î–ù››æeWNÔLZ–[ÖLÏîxûñû¶}Y¥Uª'Ιxë®¶æ-÷Í›úÆïùé肌òPCqCsí];Z›Ÿ£\QGS¸¢±,{æØ¦±�,}âcãn{tes ¦4Ã3VåL�\�¿túsã7Œ^¶�¶­«YþøªvßèB�«^ëH‡ü‹æ=]ÿãº%KqÉ:º™¼+\3$í­y™Tj÷F~@hA²ýëß®“¾æëÝá@]ëÃÓ³Ñ�øÚ*OIÃmòG|N:�ã¯b&€±ð“ 6ÁŒ™¬`TPWŒÆü|g…Ó(Î�ïhFêµ$ Ä]q6UÈF¦âš=&61!/ÛVœ`›2¸¬Ô¨¼ÇÛb»'ûÅm ]’xkÀÔ’œÐU#ÿ¢'â…{ +>ë½qh9·“]´ÝÝÑ7ªNy¤`8IŒ~u»F„´ÿêX�ŒxÀ�]´oÒØƒ_“éÕc§±C- û}§}{Â~}C±?Ì› ú�×nœgµVGÎùþÉIà´Ž 2?zLÀƒ.À?®6ZWÂnîUh½0Ÿßõ +t‰Û`i‡6š ½4wèðŽ1œ/÷>tâõ.0Ô‡óÛø�D‡×j¬a¬UX›±vb]‚µk“¼ÇJØ,n#1Ò:Ò•ž�NÅxLä‡Î¯B½p抸¿ UÔ‹k±¿ ê¹KPEÏõ‹Îȸâ4>Ãqñ˜+„£×“ø, Ë…ùàÀ~™pfèDLóÐ9± ,ÂC ÏA-Í%¹ó{ˆSv �ç'Àz‘_ íüÇ`á½ÐÄ�ðN�)ÜÈæwA¶PÁ-‡jnùÐþ¯ò}@±jjñ¹4ßÅ„tº×ÿér 4üpò˜ã‰/"}>¿r¨—¯/r¯;þ�Þ2„ó0Nü2LßW%¾‘5X°ÆHõlß­\#+@÷"ø‘?]X˰†?>¼†ùw!S|ÖGkÂÝ„ãg$ÞÅ„‡NÈpnƒ Q^ŠR•èÌwíà-p‡°4b„zH¢�KÛ †®ƒ21 ’ÄcÐ(Á#ñ_’ i !üÆ¡�%ºð{6Âk‚Ì€“ ÓJÚWi‚¹ŠÙˆ;òOú—ôqèÀ:eò¬ë¤õh¾‚t—`Bwþ¸$Ÿ\Êad +ä+VIŽQ¦ñýIª0ʽĉѫT%ùY£<š+N‚eÃü®/$:ÉrðW¬!íÖc�ÁªÁŠÏI•4ep>Hr+ÉŽ$£9!Q@¢‘LS ”sIÖ¢ôΦìÄš‰5_a‚mÑšóXDo$Ù•`½±6ʘ$;ÃWI·õX¢ ’1í{K+üP.{±| +Ÿ’t2‡œäÆsOqßÐÙôyÞ€ÌNþÚÍ"ÌŽŠâºåàpQÄEËã1¦hy2ZŽ`ù&R”)ûU ªwÔfõ½šÍ~­J»Lû7]®î¤~´þ~ý€~À0ÃpƘiÜd2½fgþÃÿùbùÅÿxùô»Åúàÿ+½:`ȹp+H£û Þƒ8s(>•þO8¶—‹×î�©/ÿPI Ѩ=su¾t}ëËÐ)ö8Ó)/*öKÿ½Bžò; ØÏtª0>MyñÆ“á ÂÿÜOˆ +endstream +endobj +93 0 obj +15984 +endobj +94 0 obj +<< +/Type /Font +/Subtype /Type0 +/BaseFont /OBNPIO+ImperialBT-Italic-Identity-H +/Encoding /Identity-H +/ToUnicode 95 0 R +/DescendantFonts [ 96 0 R ] +>> +endobj +95 0 obj +<< +/Filter /FlateDecode +/Length 301 +>> +stream +xœ]ÑÍnƒ0 à;O‘c{¨Ò°­„�ZºJö£Ñ=$¦‹4BÒo¿ÄîvX$"}"v›×͹1Úów7É<´Qæéî$°nÚ$"eJKO¢]Ž�MxýÒÙ×n~TS›F�ñÚ/›Ïºe +†p 9·ËìalÌ0•%ÿ±³wË +ÖüÍ)pÚÜV!bÍÛ»µß0†$l[U” Üp],°ŠÇí“‚Ùv\gn�”Û°ªòV•€Qÿ~‹‚¢úA~u.ž¢ +{ú\Eìv¹ dˆ”�#žbGØ#2Â‘Žˆ‚pBì 5â@¸ jD†åäTN–".,§ r2LPP‚S¨:Ý +JpÊg|ýã™±qH¿3bòî\h-Nû;ª ü ÛN–…¨ø%?�‡˜X +endstream +endobj +96 0 obj +<< +/Type /Font +/Subtype /CIDFontType2 +/BaseFont /OBNPIO+ImperialBT-Italic +/CIDSystemInfo << +/Registry (Adobe) +/Ordering (Identity) +/Supplement 0 +>> +/FontDescriptor 97 0 R +/DW 600 +/W [ 17 [ 280 ] 68 [ 606 ] 70 [ 516 606 528 330 586 610 296 ] 79 [ 296 ] 81 [ 616 581 ] 85 [ 417 ] 92 [ 549 ] 180 [ 440 440 ] ] +>> +endobj +97 0 obj +<< +/Type /FontDescriptor +/Flags 96 +/Ascent 760 +/CapHeight 707 +/Descent -240 +/FontBBox [ -178 -244 1221 965 ] +/FontName /ImperialBT-Italic +/ItalicAngle -9 +/StemV 88 +/XHeight 502 +/FontFile2 98 0 R +>> +endobj +98 0 obj +<< +/Filter /FlateDecode +/Length1 99 0 R +/Length 5356 +>> +stream +xœÕYy\Ô×µ?÷w~÷7Ã0À0l"Û ûȾÍ0*0€ +‚"AT4¨!I4jˆÆ”ú’hSk2i¬YjS›š4ŸM kµ&1iöÄÔ’ÔZk|© ƒ#5„Üyç÷ŒYúÞ_o)×s~÷œ»�å{—ù |` ˜¯¹ÕRöBë;¤Ù ZºêÆÎ—VÝ +àIº­7Þ´néÎìr�ü$€¿¡cÉÂöç.œã¡v{)LÁºXRIŽïè¼õöÓ.;µ‡? ß´rñ›îY%D½Ló;Þ¾J7C’ÆŸ þ–U«—¬šñn©tG¡‚)°öB¼§áQxjáõÌ€.Ø%íVü©¾œÚQy�EIQp ƒÉò ^Ç34j˜è¢ì Ø‹�Àý�&�³˜§ nƒ-J ØhžsJïà('1 Šä`ÙÁý¡‘E@:�³8ˆ’;©_?dQk>K|ƒwñ=•C‡÷ öáGóá(Í~.�<Ò:(‘M`¤s`q'؈fádÏl”Ÿá°±Kì ÔJy°Cª…6] ¼vÃÖÆàZcy»—­¥Ù÷›¬Ÿ|JÃsÐ윓œàaû¡_ª`aR;=¬Š¥ÁA¹ºdà‡G 3™� ‹ê]U€éIª•k±m+Ü¡šy¤(É·Iåð4†ƒ—åTªa%­Þg ZNc§˜ANƒ:–YÒ4ŠfQ³tNêGÀ60C•n7VÊagÉ¿µü£Ñ"߇#£š!z` ´Bñ•°EÚ�#ì4ÉÐËŽ�F�õ³·Éº| +Ù¶Ÿr’ƒÛ”Óì’3þ yPG1Ë¡ø;à©–÷Óœu�I¼›odF˜B%‚w�ÊU?|@è¸G›´‡5Âv¼ o£(„Ó+Ùn]Ŷœ¢®a\ÕuÃ^~t´@…|°™ )QxˆòqÎ�‡DѰñ.vX†b¯´‰Ý�5k¼ º‰7Bñyd š~®Æë4>[ã5Ÿ¥ñ™¯Öø �W±JØ +œU�JpdVÉ* ‰tj ßDº +6I§¶ qéT ²rè#^¦�Ÿ¦ñR˜F¼D«³|˜N㊡ž$+"g8simjY!´Ÿªi¦°ÉeΦÀ ’Ô:2çØ N­‡ZGæÐê¹ÏÑx¶fE–VÏÔx†ÆÓ ­Ûit:¸IJc©�F’ªC­Ž,…MÒ"�¢õOÑ"0‰ÙÈ*®µ q56– 餳iöÚ´¨dIÚÈDXAäÆ+ÛÑCãMç—Zð’Kþ4/ã…�­ü‚À Gä�OZøÀVØ$òq:ÿ¤?qɧãù¿òóÿ^ˆ ü�ç~(ð¬À¿ÑZxFà_‡ñô0þEà©?'òSÿœˆôáûûþ©O +ü£À÷žø®À·¾)ð �¯ |íU+m_µâ¾"ðå><.ð%�/®Àúð˜Ëûûz~Làïëñ¨À#Ãø;�‡ûð·´ôoûðP_6?Ô�}ÙxPàó½Áüy�½ÁøœÀÔá€Àß㳊gÝøë$Ü/ð�¿øôS[ùÓô9"?µ·…?µŸÚ$ïýe"ßÛ‚{]ò/ñI�¿¸GàÏ>!ðgw»ñ§ø˜ÀG‡ñ�»†ñ'‹lü'nÜ)ð!�n� +|@àß¾CàöFðíÃøÃ¼¿ p›À­}xß0Þ+ð�ÿ&p‹ÀïwcO7Þ½y˜oÆ»Þ)pƒÀõ×ÝnáëÞnqyqíš`¾Vàš`¼Eà*�+ûðæÎ~³ÀμiW,7ñ—›pYv¼QàR�KÚ¯ð%nl_|‰·_ÁÅdêâK¸È† ¶õá‚alØÒ‡óûð†alvc“Îk¨çó6Ôã\�sê§ó9ë§cÝl?^'p¶Ö +¬™ÕÍkÜ8«göaõŒp^íÆáXåÆJ�Ã8]`¹À2�Ó– +,X,ÐUÅ]‹¢°p Nuã”>œÜ�N�ùމ<ß�މh˜'0W`Nv0ϘŒ®Ÿg ̘!0]`šÀÔaL8iÚܘ,0I`¢À„>Œ�›Îã‡1n:ÆZy¬@k"ZƬÀèaŒ)0BàD�áÃ&0T`È0 r£9З›Ýè‹&�ýú 4R"�nô @ƒ@ŸaÔ Ô T¸ƒ+nä”J™@ ½¬½gKù—ûƒÿkþ§þ¢Ú(\F‰AªÅ´OJ¨lßçšÝhy¹Éš–ú ÑbÒYöAí>¿u–^¯·¶QŽàMûxä>LÐï“âÎü³Æ3i©3j-½¬¥lÚØ´emÓHYßHUU"5é˦¥�K…[^ÊŸ —º&ºŒò› ¼Éôü’ /œÈÓ‰�™A�ÖÀk u© #]1rN¸uþWW+6`Pá —Å%ð…—Ÿñù•Q¡F“GîÈtäÚs²CC‚•¸ØÄŠùŽêjGþŒNõ㨪"¢¼çåmră¦¹’MÆsDòô C˜~Ù8ƒGJlDˆ9Ф €ÈÜêÈ*¥ÒAS:�aNZåÃlÏ€é¢30Ìiv:3u©¼\»Ã®®æCE Íɶ;ÂÆÛx¶Úœ—›«è´fÉ3÷÷7?ü|MUÍÉÕ ÊØP¼ŽÔ‚¦ä䵬�\6K/•vOÎ/]ÖVq§=×Õ1°ù®¿ìh]¼ª~æ£~_*ñ…¦¨ðÔ¼¬ö™µåÁÎjkj/vߺ±®¾þï+oÿ>ý4›÷¬\­(H¿$f¹ÒÃ'˜1:>*+;Íš™‡>0ïs9Í?uÁž>!Ĭ譙ÙÕI5Ù3í&ÏÈWÞ~¨z;êl ™t™l܇œq¯˜Æ“$:È{�},:Íÿ$]œÝî�ö—Þé´—u,T*^öå ç© ÿ:P_¥‹šÐúâÊ�½µU5'VÕÞ_r×s(⎚Y³níŸýɪ5=¬<*7dRl@Ah¨Ä„=Ã}˽ß;¥†¤}e‘ë¦Ê3:¢¼gðM9†²›åŠ;,G^õ”= ôÞÁÐjSmLµ®2�ÒéuOóÎI‰dZ¶¤k™Å‰ZÚ¤Q±gj§§çwÞšþ¸~סéögü¬¢G>~àÎÅ¿aSò¶?Àü_]ÓßrCë=·L®ÌOžš”#Ÿ}´÷¦qìi9)‚9®[r,¦Fç„XÓì3ŸËÑ049Ä=˜zÁeÏL³%'ÄRRÌàH ¨N­›PéRah:b»–š©ã¹ $ef·`öMt�gJKÔ7aÊ| tlç8FÿÔU·=KÑÖú~æ|…뮇ê-_GߪÏ/h_YRÊJ“sýÒ’äŸhýÆø¢€ë@«¢4Æ{ß•­ §ßDW´�!.GÆ|á9¢\ôóÄ|pNxm$T›*cÉyÚyα¬}hºhP7`�=~4C,ì+gãµÊúh�µÄê|e9l^à\YŠÕ¶R˜“8vxhˆËVufíôÐ%Q2‚â9vó5Ô%QQshÕYYTò£?‹®©‹»ÿTÀ©ø×kßX˜iK÷a̘>½:ŒIþBØÄûÙE¹�œDw›`úùåö©(<¥ ½Ç…UÞC¿ú�0áQW0•˜òÒ ä‚„¬ ¿ðjcÐåÒê^Æ\~Får}©ß唫“�êë;³¾É‘›Si„ò™Õ<ÔTP›ê^‰®æÐVŸùµ‘ó+o05Çæ6¥×¶ÄbSCc¥è…O ˜„ç¢J�*.ÇÀ©U)/¨ x�²Ge¼ƒÊµxðqPª)ÅØ¯–¨%Vã*�¿±Eµp…އot–Q ÄÅÆ«Ðn[´rg÷cï,nHXñýåu˶,U³çÝ{GóüOŸs¬t–¯™:£¥ 39;Œùû[*2Ê‹?z>ljìâUMëŸybŸxéÂË^ø�9¤µ°®csKI5¾½§gNçOïl]92sb[ÑŒµ19[›|%4¤hòìâÜÒœ¤»N¯³¥­/{ð·ˆA•iéñ[ºwŸúñêÚµê9•G'Á]t8`©kª}RL¨œ©×1 ð5†XlrdæP@äPœ'`Ð÷„†˜öI6_½N¦_Wái1³1ÌMi˜™oòœ810;³sgY�qíÌV¯� 9×oükÇówŽ ëæç¼°ÆPô™ó�¥_®_Ôeô¯Òéè2±;í]Žéó|üK�~¶„¼–Õ.1çÈýV»yl»�lë}còØJÅö„<ãÄÈdgֲЯrku›ãª´¥Í›1ïÄqˆN�|ïyIÏOC ¤@³Ë7ØW§‰ 4ØÒïÅ8&¹,†À¡ Ã`j X"‚}ýÑaðIL\bYèß± •¶™G=�£ˆÒhìtRQ¦Þ[ÿåÙG7WÐuO‡^EW4ËPøàƒeBD°3{Ô]—6LÏÉ«¨ÈË-—.&çÓ’±P2r%)ÏnË!ç•¥¶EøËÉZ¯éÓ)Û äP¶c Ø¢yc0…{ ,1ŠâkÐE„Ú ‘ ,&ÏkäÌèÎ0�_SÚ…œÉ®wB÷íô1༠VMØ«Lò ‹TM_²Ú1c6¢ÜoqŒgç ?�ŸŠµþVÙi×ÞFá�‹\NG +¡2ÒW0‰&y¤.K…dÖPÀ`œGÅd¾#ee'ÜìkL”åtˆ±¤7™çÂ�NõÄ;rDCÞuˆÔ9ÑÀo!2þŸ"ÒñMH–¬áJÑ,òpÖR&ß¹ðV?ÿ*õí’o×’ÔDï ”¹?šV³$(G:oɤ<øÄèEÇ‘÷Ç@iÉ5G…Ûò5PævÒ+²>¯9Ä–ÖP5÷½u*én’3è-qç +ÂËfãåˆA³'Þ§:ºªC*ãµWÄø"3èºѨ­,Æo^} ]ýÞêŠõy¹S6¯ªúž=ÓÎàñyYI݇›Þ`¼¾¦î v÷Ãÿ^7gÎû7ïÜß2ö[_2ýÛ�˜»lµ¸òÎê“M ©Y¢CÝAvÅ@¾ËOï ºJ„^æã +„˜h£¯^f 7ë,¦¯©ÊðŒÞBjù'§EûÛ!.캷ÆQ5%-y†>tnJV¹)ïkáÜÿú=µSsÊfÎ�6óرgì¦üHLqÅ'ÅF›ü}¸Ì}tˆ~p’Ùäoôᓘ¬çÀ'¬°J“LêClün|A½(œŽû8Õ:f7çåfHc§~H°¤“äQ¤“HáfÇÄ™5³ 7oIg­Û¶;ç—ä”ÍïÝó¾8}KA•+=¦Ê4Õ!]]Ÿ?ub\ÀÈ݇Xæò¬0Æâ˳JÖÍï�ôfç”OÙD9a'? A�…ÏC�Õ¯—ÍvMH +z:9,:âÑdH +ŽŽžÿ�a¢izòر3¶UÇ.øl5ÆLErXhXèW·”ƒ‡Ž]ji·…úE[«òJçüä¶³e©*Æ©âÎ|wê²Üp“^19bs+ÕÜ~¤°8uyަɷªšu¿+T_RO’å+Ç,Ï!Ëý’‚TËÍV¿k–O4<?1:Ùt‚lþ¶¹*"ÔgǵP+º„ïÐI -‹m¡ÆèØÊÜÒ¹;wˆ¥×‰? Cê�¹á>d®5¯b!W4íëšõ‡‹ä×a)ПT0F�0MÚÍJtÈ L‚.e7±ùÐŒV8ŠVïà ²õ“C +}+¤ ï+ÔÑãDfu,QQQ;Ñ¢î½*¿ +QØyxÜ; õƒU¾9r«÷´ò¤÷¢|Ö{Xn§¹J¼oÓzûh½£ôÝO1دùM¤ú­ú<î“j¿fÇw‘uÔ¾ëiÔ>�ôê÷šmß$Õ®ë `§´›úo€yƒw�d‡ÜËT}µÜë]©ì€ûÆÈCv·™ÕÜé�ÞfÍνpv,—ŠJçSr›wŸ ·ñ�ôÎ�N^18ø„a7a‹NN] +ù@öPþ+Tì©sp=8Ɇ5.r/µ M6x×l$ûàZ¬h]€F]ż¯êÁû&öÐÉÑO&RçCÝëw5÷¬AìPq)5@šÔàÝ)÷S>N�w˜úï’ +¼ƒØã=cpB—¶ŽŠ¿ñï†Qü]Ošï*ÕÁ-ãù'-þý+I�QÑ!¢8Ò/¥o5}Lß4ÂòÛ„«c*nUì¨Å ;ªî5Fªýš„skcñN“† ƒÈH䯌@ûùëÛF÷�Š]ÕÖñ¹UŒ©ØÿªXÛÇ»ÔØÐVˆýoKÉÿJ9À²Ø&ÉGj‘ú°G6Êwhå-ù->�ÿL+ƒ×eö¿XyFÇÿzå½-oÜH¤&pQ‹î( µªÿçO|Áùw�-˜zP¯^'°ÿá¡;Õïs÷‹Âèó¢îy­hýAºç…Àà¤ö§}^¼Ö2Þ�ÿ'Ãe� +endstream +endobj +99 0 obj +8272 +endobj +100 0 obj +<< +/Filter /FlateDecode +/N 3 +/Range [ 0 1 0 1 0 1 ] +/Length 2596 +>> +stream +xœ�–wTSهϽ7½P’Š”ÐkhRH ½H‘.*1 JÀ�"6DTpDQ‘¦2(à€£C‘±"Š…Q±ëDÔqp–Id­ß¼yïÍ›ß÷~kŸ½ÏÝgï}Öº�üƒÂLX € ¡Xáçň�‹g` ðlàp³³BøF™|ØŒl™ø½º ùû*Ó?ŒÁÿŸ”¹Y"1P˜ŒçòøÙ\É8=Wœ%·Oɘ¶4MÎ0JÎ"Y‚2V“sò,[|ö™e9ó2„<ËsÎâeðäÜ'ã�9¾Œ‘`çø¹2¾&cƒtI†@Æoä±|N6(’Ü.æsSdl-c’(2‚-ãyàHÉ_ðÒ/XÌÏËÅÎÌZ.$§ˆ&\S†�“‹áÏÏMç‹ÅÌ07�#â1Ø™YárfÏüYym²";Ø8980m-m¾(Ô]ü›’÷v–^„îDøÃöW~™ °¦eµÙú‡mi]ëP»ý‡Í`/в¾u}qº|^RÄâ,g+«ÜÜ\KŸk)/èïúŸC_|ÏR¾Ýïåaxó“8’t1C^7nfz¦DÄÈÎâpù 柇øþuü$¾ˆ/”ED˦L L–µ[Ȉ™B†@øŸšøÃþ¤Ù¹–‰ÚøЖX¥!@~(* {d+Ðï} ÆGù͋љ˜�ûÏ‚þ}W¸LþÈ$ŽcGD2¸QÎìšüZ4 E@ê@èÀ¶À¸àA(ˆq`1à‚�D €µ ”‚­`'¨u 4ƒ6pt�cà48.�Ë`ÜR0ž€)ð +Ì@„…ÈR‡t CȲ…X�äCP”%CBH@ë R¨ª†ê¡fè[è(tº C· Qhúz#0 ¦ÁZ°l³`O8Ž„ÁÉð28.‚·À•p|î„O×àX +?�§€:¢‹0ÂFB‘x$ !«�¤i@Ú�¤¹ŠH‘§È[EE1PL” Ê…⢖¡V¡6£ªQP�¨>ÔUÔ(j +õMFk¢ÍÑÎèt,:�‹.FW ›Ðè³èô8úƒ¡cŒ1ŽL&³³³ÓŽ9…ÆŒa¦±X¬:ÖëŠ År°bl1¶ +{{{;Ž}ƒ#âtp¶8_\¡8áú"ãEy‹.,ÖXœ¾øøÅ%œ%Gщ1‰-‰ï9¡œÎôÒ€¥µK§¸lî.îžoo’ïÊ/çO$¹&•'=JvMÞž<™âžR‘òTÀT ž§ú§Ö¥¾N MÛŸö)=&½=—‘˜qTH¦ û2µ3ó2‡³Ì³Š³¤Ëœ—í\6% +5eCÙ‹²»Å4ÙÏÔ€ÄD²^2šã–S“ó&7:÷Hžrž0o`¹ÙòMË'ò}ó¿^�ZÁ]Ñ[ [°¶`t¥çÊúUЪ¥«zWë¯.Z=¾ÆoÍ�µ„µik(´.,/|¹.f]O‘VÑš¢±õ~ë[‹ŠEÅ76¸l¨ÛˆÚ(Ø8¸iMKx%K­K+Jßoæn¾ø•ÍW•_}Ú’´e°Ì¡lÏVÌVáÖëÛÜ·(W.Ï/Û²½scGÉŽ—;—ì¼PaWQ·‹°K²KZ\Ù]ePµµê}uJõH�WM{­fí¦Ú×»y»¯ìñØÓV§UWZ÷n¯`ïÍz¿úΣ†Š}˜}9û6F7öÍúº¹I£©´éÃ~á~é�ˆ}ÍŽÍÍ-š-e­p«¤uò`ÂÁËßxÓÝÆl«o§·—‡$‡›øíõÃA‡{�°Ž´}gø]mµ£¤ê\Þ9Õ•Ò%íŽë>x´·Ç¥§ã{Ëï÷Ó=Vs\åx٠‰¢ŸN柜>•uêééäÓc½Kz=s­/¼oðlÐÙóç|Ï�é÷ì?yÞõü± ÎŽ^d]ìºäp©sÀ~ ãû:;‡‡º/;]îž7|âŠû•ÓW½¯ž»píÒÈü‘áëQ×oÞH¸!½É»ùèVú­ç·snÏÜYs}·äžÒ½Šûš÷~4ý±]ê =>ê=:ð`Áƒ;cܱ'?eÿô~¼è!ùaÅ„ÎDó#ÛGÇ&}'/?^øxüIÖ“™§Å?+ÿ\ûÌäÙw¿xü20;5þ\ôüÓ¯›_¨¿ØÿÒîeïtØôýW¯f^—¼Qsà-ëmÿ»˜w3¹ï±ï+?˜~èùôñî§ŒOŸ~÷„óû +endstream +endobj +101 0 obj +<< +/Filter /FlateDecode +/Length 2623 +>> +stream +xœµZKoÉî³lÀ$êí€Ç»–½ý~äEÉweË’%ïê–dÈe�ùúEäº?-Õ5=]=ä EY2Ëݧ»_}õ˜‘cŸ‰„?^E®�ÿí߯J¸Ä•Ïñrú\œä/¿þsc¸ÓÞ�'Zr¤ .„�ãIþÿ×lü²!p7¸­ù·ýõrãûëyô°êò—�òu¾1‘BŒ/ÿC{+Ë•³j|ù÷�oÙö›Ëmh¡á’ƒÍðÚ7ìö[vû†}Ç$üóðOÁ7Ç^¤µNƒV^¶kïØÛb#¶É¶›½–•:¾¤³¥áFØø@½�ÎÔ«ý +z îœ7㤎²¦gA­¹Ð2´ÂÞ¾I-R.Ø›±9;fçìï1\Æö×·ì®_°ìö6ý¨!– 7Óµïg²#b \*oÇRð¨c6s³T:î”.†~ÕÜ®êÛ#WB”óK+ àÅ©OdíEÚrKFøo�̼¢M»bÎ>¥5‘›HÇNËv2p-tÚþÞ4÷Å…S¶]3cgðë9;Aq4w^•ûOáÎÜþ|¿bïñÊuF›çÖkIB|‚ÏN9oWhp§6ª]ñ~»‚ý`'üUr¡H³ÙÿZ·W>ÁÊŸáž);o"�«�wœ4‚5xç�@V×þš�€ÄSö>sÔ£9ÇrgŠ'¯À8ÇðI*6vÔŠIvlôå.’ºgpøûdšŒåMQåö™‚ñãþØ9Vr¼&®@�‹f´ ¥'GãU©¸ .ÒÎg ¬¤çF’iÇ�®q²¨rG2÷;øõ´58% +««Ãý %�~Œ®z®œ›jо/–o¢}€8ÒGÕRb4fü×kF½q*AƒköȓΆ3®'�ÕÓú†Þ3u!éy“€ë f7 oÒ îž·þ04(Šm·[uYÐr)hQ†°ôQ-Ä%¥ËõÄç›?‘¨™1G®y‹ü…ÃØÕ�kb  vw(¦?$£´Æ2t½�Ÿ,7!úqcÀ™ìe B �ÓkïL{ Î�R”óÿÔp—ðºÂQ2ÃÛDˆ^Å­!ï&Óü€XÌt ú]¶”@ê±ò}˜�[{Sp©­©LÛ� Ø ‚°ÂÆ* Ò5 ŸRÚ!¤´ÝÆõI:mäýÀ²ÇŽÖAÖfŸ ³r™»vÃñ�‚uE+·@¬Ñ Yˆ5³Ra‰•d'ÍÔ ×RwØ`ž(?§MñRñ9DMÔ?c½‡OŠêkXs’ çT(>L|�"?qƇ!(EæÿØ$=r¿�ç +À_[p6dA)—ËÔ"„! Feô²• Y‡0«DPka6R�õaÖTÜž@{ÔmÅØu†Âç!lh©ùkŠŽO9ù¬Ç)à)qúÊ"™Êâ¸ê°F•Þ#'hO‡ŽßŸA‚yÞìÉ+aÖØÈA�à�'PÏÑ•Ÿ*ã;î•´Ï`Íó~0Jžˆr!/®Áª‹`ÔÜÓO‘Òç˜+§BäU°O¹†VÑ”…¦ gkrì êÉJçma€„ýB5çá.YTG–ÈÆ›c¦ÆE¼æ¥#c§‚ô"ECËMÖ)Òæ}Öæö–Jš„NÐd¹¤±ÂU´vÒÔ¦¹Wʳ„ËT~Æj±d㉶šÇ…в)íæ˜ó:ðpˆz© ‚*[‰š8Qå+�¡Y©”�})-Úbñaz�•Ö+è!ÔY©‡ÅvKÛl¯?Ê�0„#Ì÷+?EgmºÓ!,+)‹—^wº˃¡ä3Ð�`õ„…€ý¡Q4«¨U|×ì¢ÍbÖTätŠ­Bj_r±'ê¾Áós÷²lçd—Ô[®°³’Ué0bû`æýÂÂ2¬S:K¥ÃÁ +^ìƒ*8U˜êr ÂYÔ‹eG×aŒRLùªîú²Í¬íA³¿¿> Ô[¯³Ój•‘ì0§mDZ¤SV$;Š/Â`� hÆéî´áÝP@+]�ö –?§Ès6C¡@1A9i±Äðž¸fºäÅ]  WEœ î>·@ˆ¸uÜ=Y\åeɤ䳃·‹¹\é ï÷dÌðxOiI/v{Ò³ÁÜk\ÌbJJ¹£Í¾¨Ë"+þ!øÊCmó\‘üEžd‚IŒ@õÍÿÚ¹OEsm‘|ƒÙhÖõœ‹\)åió«ìs[£3ìô®1ûµé6ZÝ|ƽO³Ÿ Å/å*‘¨~uxƒU¼X§ýB;…a�|b©ýÚnã{¢�áÎv[¢aìá +$wPÒºŠ�Ö,i�¥B«opˆÊ‰ÜûŠ^¨GŒ•$O$èª|·–ý3äÑÈâ/ÚZÇ�Á\M• M|³KÓb�Zq_~ÿK¿Ç&,®M7t›P|C=^vx…ø”¥ÒNthµ\WôÝ,žp~€: À“šG=vD‡V¶Mz +üTy e†X"™·°Cì—ùq¸^–yôd2o Ê®~²‘Ú–×ðËIa)îµ�Ý-÷K!lé4·4{Ң󵚖¤Ç¼’Þóz†Ú>Mt”w·Øóû=h@þÄÛk½‰÷5ÚhY +endstream +endobj +102 0 obj +<< +/Kids [ 103 0 R ] +>> +endobj +103 0 obj +<< +/Limits [ (1) (20) ] +/Names [ (1) 104 0 R (1068) 105 0 R (18) 106 0 R (20) 107 0 R ] +>> +endobj +104 0 obj +<< +/D [ 3 0 R /XYZ null 663.347 null ] +>> +endobj +105 0 obj +<< +/D [ 3 0 R /XYZ null 419.044 null ] +>> +endobj +106 0 obj +<< +/D [ 3 0 R /XYZ null 652.408 null ] +>> +endobj +107 0 obj +<< +/D [ 3 0 R /XYZ null 652.408 null ] +>> +endobj +108 0 obj +<< +/Type /Action +/S /GoTo +/D [ 3 0 R /Fit ] +>> +endobj +109 0 obj +<< +/Compression#20level (6) +/Print#20Engine (Arbortext FOSI Print Publisher) +/CreationDate (D\07220251213061754Z00\04700\047) +/Creator () +/EPS#20processor (PStill version 1\05690\0563) +/Config#20File (E\072\134program files\134ptc\134arbortext pe\057lib\057print\056pdfcf) +/Stylesheet (E\072\134program files\134PTC\134arbortext pe\134custom\134doctypes\134ico\055codeSection\134ico\055codeSection\056style) +/Compression#20type (zip) +/Arbortext#20Build (R71M020\0551138) +/Graphics#20resolution#20threshold (1800) +/ModDate (D\07220260806153359Z00\04700\047) +/Graphics#20resolution (1200) +/Producer () +/Author () +/Title () +/Subject () +/Keywords () +>> +endobj +xref +0 110 +0000000000 65535 f +0000000015 00000 n +0000000136 00000 n +0000000195 00000 n +0000000385 00000 n +0000000667 00000 n +0000000894 00000 n +0000001025 00000 n +0000001258 00000 n +0000001388 00000 n +0000001619 00000 n +0000001750 00000 n +0000001985 00000 n +0000002117 00000 n +0000002349 00000 n +0000002480 00000 n +0000002715 00000 n +0000002846 00000 n +0000003081 00000 n +0000003213 00000 n +0000003433 00000 n +0000003565 00000 n +0000003797 00000 n +0000003929 00000 n +0000004164 00000 n +0000004301 00000 n +0000004536 00000 n +0000004671 00000 n +0000004903 00000 n +0000005038 00000 n +0000005273 00000 n +0000005408 00000 n +0000005643 00000 n +0000005778 00000 n +0000006013 00000 n +0000006148 00000 n +0000006380 00000 n +0000006515 00000 n +0000006747 00000 n +0000006884 00000 n +0000007119 00000 n +0000007256 00000 n +0000007491 00000 n +0000007628 00000 n +0000007863 00000 n +0000008000 00000 n +0000008235 00000 n +0000008372 00000 n +0000008604 00000 n +0000008741 00000 n +0000008976 00000 n +0000009113 00000 n +0000009348 00000 n +0000009485 00000 n +0000009720 00000 n +0000009857 00000 n +0000010092 00000 n +0000010229 00000 n +0000010464 00000 n +0000010601 00000 n +0000010836 00000 n +0000010973 00000 n +0000011208 00000 n +0000011340 00000 n +0000011575 00000 n +0000011708 00000 n +0000011943 00000 n +0000012076 00000 n +0000012311 00000 n +0000012443 00000 n +0000012675 00000 n +0000012806 00000 n +0000013041 00000 n +0000013173 00000 n +0000013408 00000 n +0000013540 00000 n +0000013775 00000 n +0000013906 00000 n +0000014141 00000 n +0000014273 00000 n +0000014508 00000 n +0000014639 00000 n +0000014758 00000 n +0000014921 00000 n +0000015334 00000 n +0000015750 00000 n +0000015966 00000 n +0000022949 00000 n +0000022971 00000 n +0000023135 00000 n +0000023680 00000 n +0000024186 00000 n +0000024398 00000 n +0000035504 00000 n +0000035526 00000 n +0000035691 00000 n +0000036065 00000 n +0000036391 00000 n +0000036605 00000 n +0000042051 00000 n +0000042072 00000 n +0000044771 00000 n +0000047469 00000 n +0000047510 00000 n +0000047618 00000 n +0000047677 00000 n +0000047736 00000 n +0000047795 00000 n +0000047854 00000 n +0000047918 00000 n +trailer +<< +/Size 110 +/Root 1 0 R +/Info 109 0 R +/ID [ <511c713953076d137e8ad40075a69088> ] +>> +startxref +48584 +%%EOF diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/704.pdf b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/704.pdf new file mode 100644 index 0000000000000000000000000000000000000000..e578ad07d4dbc204b5e2a72eba08ff30566cc1c6 Binary files /dev/null and b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/704.pdf differ diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/706.1.pdf b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/706.1.pdf new file mode 100644 index 0000000000000000000000000000000000000000..4acc8fb6ea817bd122c015ee4b84a46a8f3ccf3d Binary files /dev/null and b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/706.1.pdf differ diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/707.11.pdf b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/707.11.pdf new file mode 100644 index 0000000000000000000000000000000000000000..157df5e0963be2c588d86a37b7ddd71e7b920afa Binary files /dev/null and b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/707.11.pdf differ diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/708.6.pdf b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/708.6.pdf new file mode 100644 index 0000000000000000000000000000000000000000..2f8ad7a4982a18889d3056e5f18b4158ff68dabc Binary files /dev/null and b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/708.6.pdf differ diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/Ellison.pdf b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/Ellison.pdf new file mode 100644 index 0000000000000000000000000000000000000000..2946bf2e4f0db0e82056e6b7ecfe3ae81e593e9c --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/Ellison.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dab6b81b7dd931bf53eb858063f006ff025f377690030fae0e1c11c8586e094f +size 148023 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/Facts.pdf b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/Facts.pdf new file mode 100644 index 0000000000000000000000000000000000000000..9f02a52190e9af8679f266b6d45dfd7eb47907bf --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/Facts.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:81530702122b9be6a549aa9d0556996ae243b50e4a94146fb149a450e20de875 +size 128104 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/Kehoe.pdf b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/Kehoe.pdf new file mode 100644 index 0000000000000000000000000000000000000000..0e4d813f77b2aca463b723f884a7ed8965b3bb47 Binary files /dev/null and b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/Kehoe.pdf differ diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/Patton State Plea.pdf b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/Patton State Plea.pdf new file mode 100644 index 0000000000000000000000000000000000000000..102936124c1c695cfe2dc5d88619f7c722abc807 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/Patton State Plea.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a83b8262ca99a6e605f566c7acaa05c9f7ef96880037c3d295c74c7a6611a323 +size 710911 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/Poe.pdf b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/Poe.pdf new file mode 100644 index 0000000000000000000000000000000000000000..727d0156f93fc876b14b4c8e92bd61b78d9ab48c Binary files /dev/null and b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/Poe.pdf differ diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/White Horse.pdf b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/White Horse.pdf new file mode 100644 index 0000000000000000000000000000000000000000..460ad1afc22d78fa5cfc67e8cdbd191e0794349a Binary files /dev/null and b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-1/workdir/attachments/White Horse.pdf differ diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/instruction.md b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f668350a0d01e5c7c54d894180768962461a3f34 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/instruction.md @@ -0,0 +1,50 @@ +# OTB Gang VICAR Trial Jury Instructions — Supplementing brief with new case + +Matter: OTB Gang VICAR Trial Jury Instructions + +You are a senior legal analyst operating autonomously. You are completing a multi-step legal reasoning task. Follow the role, factual record, instructions, and deliverable requirements provided in the Task and each Assignment. + +Each Assignment may require a different legal deliverable. Follow the requirements specific to that Assignment. + +## Word limits for court briefs + +- A brief in support of or in response to a motion may not exceed **8,750 words**. +- A reply brief may not exceed **3,500 words**. +- For a motion for reconsideration, a brief in support of or in response to the motion may not exceed **3,500 words**, and a reply brief may not exceed **1,750 words**. +- If an Assignment specifies a stricter word limit, follow the stricter limit. + +These word limits do not apply to legal memoranda or other non-court-filing deliverables unless the Assignment expressly provides otherwise. + +Complete the task end-to-end without asking for confirmation, permission, or clarification. + +Use the uploaded matter documents in `/app/attachments/` as your primary case file. You also have internet access via OpenCode's `websearch` tool; use it to research any statutes, regulations, cases, administrative guidance, or secondary authorities that are not supplied as attachments. Cite any authority you rely on in the format requested by the prompt. + +For document inspection: +- PDF: `pdftotext /app/attachments/.pdf -` +- DOCX: `pandoc /app/attachments/.docx -t markdown` +- XLSX/CSV: use Python with `openpyxl` or `pandas` +- If extraction is unreliable, inspect the raw file with Python libraries or convert/render the relevant pages. + +Write the final complete legal deliverable for this assignment to `/app/response2.md`. The verifier reads only that file. + +This is a follow-on assignment. The documents from the previous assignment(s) remain available in `/app/attachments/`, and your prior deliverable `/app/response1.md` is also on disk. Build on that analysis as the prompt directs. + +## Attachments + +- `/app/attachments/Kuhse.pdf`: State v. Kuhse, No. 18-0765, slip op. (Iowa Apr. 8, 2020) +- `/app/attachments/Facts.pdf`: Facts + + +## Prompt + +ASSIGNMENT #2 +From: Molly Short (Molly.Short@usdoj.gov) +To: Alexa Pierre (Alexa.Pierre@usdoj.gov) +Re: OTB appeal purpose instruction +Date: July 22, 2026 + +Hi Alexa, + +Thanks for your help on Patton's appeal brief. I found State v. Kuhse, No. 18-0765, slip op. (Iowa Apr. 8, 2020) (Kuhse.pdf), which I didn't see in your initial response. Please supplement your brief with relevant legal analysis of State v. Kuhse. State v. Kuhse, No. 18-0765, slip op. (Iowa Apr. 8, 2020) (Kuhse.pdf) and Facts (Facts.pdf) have been uploaded for your use. + +Be sure to limit your review for the Assignment to the attached documents. Do not rely on, reference, or infer any legal authority, factual information, or data beyond what is contained in these uploaded files. If a document is not uploaded, it does not exist for purposes of this analysis. Do not cite external websites, databases, or any source outside the uploaded materials. diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/solution/solve.sh b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7710414a6da6d0ad740717c8c85a9af850d5da33 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/solution/solve.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# No oracle solution ships with LegalReasonBench. The verifier grades the +# agent's own legal deliverable for this assignment against the rubric. +echo "no oracle solution" diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/fixtures/config.json b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/fixtures/config.json new file mode 100644 index 0000000000000000000000000000000000000000..f1cae0f9900df9b3057dcba79bc52fdf6eefdf73 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/fixtures/config.json @@ -0,0 +1,174 @@ +{ + "task_id": "lrb-vicar-trial-jury-instructions", + "title": "OTB Gang VICAR Trial Jury Instructions", + "domain": "", + "matter": "OTB Gang VICAR Trial Jury Instructions", + "judge": { + "max_concurrent_llm": 12, + "mode": "panel", + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ], + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + "step_index": 2, + "step_name": "assignment-2", + "step_title": "Supplementing brief with new case", + "prompt": "ASSIGNMENT #2\nFrom: Molly Short (Molly.Short@usdoj.gov)\nTo: Alexa Pierre (Alexa.Pierre@usdoj.gov)\nRe: OTB appeal purpose instruction\nDate: July 22, 2026\n\nHi Alexa,\n\nThanks for your help on Patton's appeal brief. I found State v. Kuhse, No. 18-0765, slip op. (Iowa Apr. 8, 2020) (Kuhse.pdf), which I didn't see in your initial response. Please supplement your brief with relevant legal analysis of State v. Kuhse. State v. Kuhse, No. 18-0765, slip op. (Iowa Apr. 8, 2020) (Kuhse.pdf) and Facts (Facts.pdf) have been uploaded for your use.\n\nBe sure to limit your review for the Assignment to the attached documents. Do not rely on, reference, or infer any legal authority, factual information, or data beyond what is contained in these uploaded files. If a document is not uploaded, it does not exist for purposes of this analysis. Do not cite external websites, databases, or any source outside the uploaded materials.", + "attachments": [ + { + "filename": "Kuhse.pdf", + "description": "State v. Kuhse, No. 18-0765, slip op. (Iowa Apr. 8, 2020)", + "metadata": {}, + "path": "/app/attachments/Kuhse.pdf" + }, + { + "filename": "Facts.pdf", + "description": "Facts", + "metadata": {}, + "path": "/app/attachments/Facts.pdf" + } + ], + "rubric": [ + { + "name": "criterion_1", + "description": "Identifies that Patton bears the initial burden of producing sufficient evidence to support the justification instruction.", + "source": "State v. Kuhse, No. 18-0765, slip op. at 9 (Iowa Apr. 8, 2020) (\"The defendant bears the initial burden of producing sufficient evidence to support the instruction.\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please supplement your brief with relevant legal analysis of State v. Kuhse.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_2", + "description": "Identifies that only once Patton presents substantial evidence of self-defense does the burden shift to the government to disprove justification.", + "source": "State v. Kuhse, No. 18-0765, slip op. at 9 (Iowa Apr. 8, 2020) (\"Once that threshold is met, the burden shifts to the State to prove lack of justification beyond a reasonable doubt.\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please supplement your brief with relevant legal analysis of State v. Kuhse.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_3", + "description": "Mentions that the only evidence of self-defense is that Nelson also fired a gun.", + "source": "Facts p. 7 (Facts.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please supplement your brief with relevant legal analysis of State v. Kuhse.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 25.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_4", + "description": "Mentions that there was a lack of evidence proving who fired first on May 10, 2020.", + "source": "Facts p. 7 (Facts.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please supplement your brief with relevant legal analysis of State v. Kuhse.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 25.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_5", + "description": "Mentions that the OTB group had rolled the windows down before reaching Nelson.", + "source": "Facts p. 7 (Facts.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please supplement your brief with relevant legal analysis of State v. Kuhse.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_6", + "description": "Mentions that Patton was hanging out the window with a firearm.", + "source": "Facts pp. 7-8 (Facts.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please supplement your brief with relevant legal analysis of State v. Kuhse.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_7", + "description": "Mentions that Nelson's car was already stopped when Patton fired his gun.", + "source": "Facts pp. 7-8 (Facts.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please supplement your brief with relevant legal analysis of State v. Kuhse.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_8", + "description": "States that the OTB group could have driven away.", + "source": "Facts pp. 7-8 (Facts.pdf) (Nelson's car was stopped; Nelson was outside of the car; the OTB group remained in a moving car)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please supplement your brief with relevant legal analysis of State v. Kuhse.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 15.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_9", + "description": "States that the only reasonable inference from Patton's actions is that he intended to fire regardless of what Nelson did.", + "source": "Facts pp. 6-8 (Facts.pdf) (Patton was armed with a gun, they chased Nelson across the city, the OTB group rolled the windows of the Trailblazer down before being fired upon.).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please supplement your brief with relevant legal analysis of State v. Kuhse.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 30.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_10", + "description": "States Patton failed to put forth substantial evidence of self-defense to support the submission of a justification instruction.", + "source": "State v. Kuhse, No. 18-0765, slip op. at 9 (Iowa Apr. 8, 2020) (\"The defendant bears the initial burden of producing sufficient evidence to support the instruction.\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please supplement your brief with relevant legal analysis of State v. Kuhse.\"", + "metadata": { + "irac_section": "Conclusion" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + } + ], + "answer_path": "/app/response2.md", + "answer_relative_path": "response2.md", + "is_followon": true, + "prev_answer_path": "/app/response1.md" +} diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/fixtures/rubric.json b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/fixtures/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..9f21a9956234724568f121321393966fa258d70c --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/fixtures/rubric.json @@ -0,0 +1,124 @@ +{ + "criteria": [ + { + "name": "criterion_1", + "description": "Identifies that Patton bears the initial burden of producing sufficient evidence to support the justification instruction.", + "source": "State v. Kuhse, No. 18-0765, slip op. at 9 (Iowa Apr. 8, 2020) (\"The defendant bears the initial burden of producing sufficient evidence to support the instruction.\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please supplement your brief with relevant legal analysis of State v. Kuhse.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_2", + "description": "Identifies that only once Patton presents substantial evidence of self-defense does the burden shift to the government to disprove justification.", + "source": "State v. Kuhse, No. 18-0765, slip op. at 9 (Iowa Apr. 8, 2020) (\"Once that threshold is met, the burden shifts to the State to prove lack of justification beyond a reasonable doubt.\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please supplement your brief with relevant legal analysis of State v. Kuhse.\"", + "metadata": { + "irac_section": "Rule" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_3", + "description": "Mentions that the only evidence of self-defense is that Nelson also fired a gun.", + "source": "Facts p. 7 (Facts.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please supplement your brief with relevant legal analysis of State v. Kuhse.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 25.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_4", + "description": "Mentions that there was a lack of evidence proving who fired first on May 10, 2020.", + "source": "Facts p. 7 (Facts.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please supplement your brief with relevant legal analysis of State v. Kuhse.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 25.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_5", + "description": "Mentions that the OTB group had rolled the windows down before reaching Nelson.", + "source": "Facts p. 7 (Facts.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please supplement your brief with relevant legal analysis of State v. Kuhse.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_6", + "description": "Mentions that Patton was hanging out the window with a firearm.", + "source": "Facts pp. 7-8 (Facts.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please supplement your brief with relevant legal analysis of State v. Kuhse.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 5.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_7", + "description": "Mentions that Nelson's car was already stopped when Patton fired his gun.", + "source": "Facts pp. 7-8 (Facts.pdf)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please supplement your brief with relevant legal analysis of State v. Kuhse.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_8", + "description": "States that the OTB group could have driven away.", + "source": "Facts pp. 7-8 (Facts.pdf) (Nelson's car was stopped; Nelson was outside of the car; the OTB group remained in a moving car)", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please supplement your brief with relevant legal analysis of State v. Kuhse.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 15.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_9", + "description": "States that the only reasonable inference from Patton's actions is that he intended to fire regardless of what Nelson did.", + "source": "Facts pp. 6-8 (Facts.pdf) (Patton was armed with a gun, they chased Nelson across the city, the OTB group rolled the windows of the Trailblazer down before being fired upon.).", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please supplement your brief with relevant legal analysis of State v. Kuhse.\"", + "metadata": { + "irac_section": "Application" + }, + "score": 30.0, + "polarity": "positive", + "raw_weight": 1.0 + }, + { + "name": "criterion_10", + "description": "States Patton failed to put forth substantial evidence of self-defense to support the submission of a justification instruction.", + "source": "State v. Kuhse, No. 18-0765, slip op. at 9 (Iowa Apr. 8, 2020) (\"The defendant bears the initial burden of producing sufficient evidence to support the instruction.\").", + "justification": "This rubric item is requested directly in the following portion of the prompt: \"Please supplement your brief with relevant legal analysis of State v. Kuhse.\"", + "metadata": { + "irac_section": "Conclusion" + }, + "score": 10.0, + "polarity": "positive", + "raw_weight": 1.0 + } + ] +} diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/m1_judge_panel.json b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/m1_judge_panel.json new file mode 100644 index 0000000000000000000000000000000000000000..a8041f6781a899f9083fe4a1a95f51bc78d35601 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/m1_judge_panel.json @@ -0,0 +1,21 @@ +{ + "mode": "panel", + "max_concurrent_llm": 12, + "members": [ + { + "model": "openai/gpt-5.6-terra", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "anthropic/claude-sonnet-5", + "reasoning_effort": "medium", + "timeout": 1500 + }, + { + "model": "gemini/gemini-3.8-flash", + "reasoning_effort": "medium", + "timeout": 1500 + } + ] +} diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/m1_rewardkit_accounting.py b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/m1_rewardkit_accounting.py new file mode 100644 index 0000000000000000000000000000000000000000..406dc5e7c675b222d94514e71bf5fad6ae141d8f --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/m1_rewardkit_accounting.py @@ -0,0 +1,490 @@ +import asyncio +import json +import math +import os +from pathlib import Path +import random +import sys +import time + +class JudgeReceiptError(OSError): + pass +_LLM_ROUTES = frozenset({'vertex', 'anthropic fallback', 'aistudio', 'direct'}) +_LLM_ROUTE_HEADERS = ('x-m1-llm-route', 'llm_provider-x-m1-llm-route') + +def _canonical_llm_route(value): + return value if isinstance(value, str) and value in _LLM_ROUTES else None + +def _llm_route_from_headers(headers): + if not isinstance(headers, dict): + return None + folded = {str(key).lower(): value for key, value in headers.items()} + for name in _LLM_ROUTE_HEADERS: + route = _canonical_llm_route(folded.get(name)) + if route is not None: + return route + return None + +def _llm_route_from_response(response): + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + route = _llm_route_from_headers(headers) + if route is not None: + return route + return _llm_route_from_headers(getattr(response, 'headers', None)) + +def _token_field_status(values, key): + if not isinstance(values, dict) or key not in values: + return 'missing' + value = values[key] + if value is None: + return 'null' + return 'valid' if type(value) is int and value >= 0 else 'invalid' + +def _gemini_capture(kwargs, model): + if not model.startswith('gemini/') or kwargs.get('stream') or kwargs.get('tools') or kwargs.get('functions'): + return (kwargs, None) + from litellm.integrations.custom_logger import CustomLogger + from urllib.parse import urlsplit + + class Capture(CustomLogger): + evidence = None + prompt_status = 'not_observed' + llm_route = None + + def log_post_api_call(self, kwargs, response_obj, start_time, end_time): + self.evidence = None + self.prompt_status = 'not_observed' + try: + params = kwargs.get('litellm_params') or {} + route = urlsplit(params.get('api_base') or '') + bare = model.removeprefix('gemini/') + gemini = params.get('custom_llm_provider') == 'gemini' + ai_studio = gemini and route.hostname == 'generativelanguage.googleapis.com' and (route.path in {'/' + version + '/models/' + bare + ':generateContent' for version in ('v1alpha', 'v1beta')}) + broker = urlsplit(os.environ.get('GEMINI_API_BASE') or '') + brokered = gemini and bool(broker.netloc) and (route.netloc == broker.netloc) and (broker.path.rstrip('/').rsplit('/', 1)[-1] in ('v1alpha', 'v1beta')) and (route.path == broker.path.rstrip('/') + '/models/' + bare + ':generateContent') + vertex = params.get('custom_llm_provider') == 'vertex_ai' and route.hostname == 'aiplatform.googleapis.com' and route.path.startswith('/v1/projects/') and route.path.endswith('/locations/global/publishers/google/models/' + bare + ':generateContent') + if route.scheme != 'https' or not (ai_studio or brokered or vertex) or kwargs.get('stream'): + return + self.llm_route = 'vertex' if vertex else 'aistudio' if ai_studio else None + raw = kwargs.get('original_response') + raw = json.loads(raw) if isinstance(raw, str) else raw + if not isinstance(raw, dict): + return + candidates = raw.get('candidates') + if not isinstance(candidates, list) or not candidates or any((not isinstance(c, dict) or not c.get('finishReason') for c in candidates)) or (not isinstance(raw.get('modelVersion'), str)) or (not raw['modelVersion']): + return + usage = raw.get('usageMetadata') + self.prompt_status = _token_field_status(usage, 'promptTokenCount') + if not isinstance(usage, dict): + return + fields = ('promptTokenCount', 'candidatesTokenCount', 'thoughtsTokenCount', 'cachedContentTokenCount', 'totalTokenCount', 'toolUsePromptTokenCount') + counts = {key: usage.get(key, 0) for key in fields} + if not {'promptTokenCount', 'totalTokenCount'} <= usage.keys() or any((type(n) is not int or n < 0 for n in counts.values())) or counts['toolUsePromptTokenCount'] != 0 or (counts['cachedContentTokenCount'] > counts['promptTokenCount']) or (counts['totalTokenCount'] != counts['promptTokenCount'] + counts['candidatesTokenCount'] + counts['thoughtsTokenCount']): + return + self.evidence = {'protocol': 'gemini-generate-content-' + ('vertex-v1' if vertex else route.path.split('/')[-3]), 'model_version': raw['modelVersion'], 'usage_metadata': {key: usage[key] for key in fields if key in usage}, 'defaulted_fields': [key for key in fields if key not in usage]} + except (TypeError, ValueError, AttributeError): + return + capture = Capture() + return ({**kwargs, 'callbacks': [*(kwargs.get('callbacks') or []), capture]}, capture) + +def _record_judge_usage(response, model: str, *, target: Path | None=None, native_usage: dict | None=None, native_prompt_status: str | None=None, llm_route: str | None=None) -> None: + import fcntl + from datetime import datetime, timezone + data = response.model_dump() if hasattr(response, 'model_dump') else response + usage = data.get('usage') if isinstance(data, dict) else None + granularity = data.get('usage_granularity') if isinstance(data, dict) else None + if not isinstance(usage, dict): + usage = {} + granularity = 'missing_provider_receipt' + prompt, completion = (usage.get('prompt_tokens'), usage.get('completion_tokens')) + native_fresh = usage.get('input_uncached_tokens') + prompt = prompt if type(prompt) is int and prompt >= 0 else None + native_fresh = native_fresh if type(native_fresh) is int and native_fresh >= 0 else None + if type(completion) is not int or completion < 0 or (prompt is None and native_fresh is None): + completion = completion if type(completion) is int and completion >= 0 else 0 + granularity = granularity or 'invalid_provider_receipt' + details = usage.get('prompt_tokens_details') + if details is not None and (not isinstance(details, dict)): + granularity = 'invalid_provider_receipt' + details = details if isinstance(details, dict) else {} + cached = details.get('cached_tokens') + if native_usage is not None: + native = native_usage['usage_metadata'] + native_output = native.get('candidatesTokenCount', 0) + native.get('thoughtsTokenCount', 0) + if prompt == native['promptTokenCount'] and completion == native_output: + cached = native.get('cachedContentTokenCount', 0) + else: + native_usage = None + written = next((value for value in (usage.get('input_cache_write_tokens'), usage.get('cache_creation_input_tokens'), details.get('cache_creation_tokens'), details.get('cache_write_tokens')) if value is not None), None) + invalid = any((value is not None and (type(value) is not int or value < 0) for value in (cached, written))) + cached = cached if type(cached) is int and cached >= 0 else None + written = written if type(written) is int and written >= 0 else None + fresh = native_fresh + if fresh is None and prompt is not None and (cached is not None) and (written is not None): + fresh = prompt - cached - written + if fresh is not None and (fresh < 0 or (prompt is not None and cached is not None and (written is not None) and (fresh + cached + written != prompt))): + invalid, fresh = (True, None) + provider, _, slug = model.partition('/') + event: dict = {'type': 'step_finish', 'part': {'providerID': provider if slug else 'openai', 'modelID': slug or model, 'tokens': {'input': fresh, 'output': completion, 'cache': {'read': cached, 'write': written}}}} + field_status = {'prompt_tokens': _token_field_status(usage, 'prompt_tokens'), 'completion_tokens': _token_field_status(usage, 'completion_tokens'), 'input_uncached_tokens': _token_field_status(usage, 'input_uncached_tokens')} + field_status['native_prompt_token_count'] = native_prompt_status if native_prompt_status in {'missing', 'null', 'invalid', 'valid', 'not_observed'} else 'unsupported' + part: dict = event['part'] + part['usage_field_status'] = field_status + if native_usage is not None: + event['part']['native_usage'] = native_usage + event['part']['token_categories_provenance'] = 'explicit_presence_v1' + if fresh is None and prompt is not None: + event['part']['prompt_tokens_inclusive'] = prompt + if invalid or any((value is None for value in (fresh, cached, written))): + granularity = granularity if granularity not in (None, 'request') else 'invalid_provider_receipt' if invalid else 'incomplete_token_categories' + if granularity: + event['part']['usage_granularity'] = granularity + if provider == 'openrouter': + cost = usage.get('cost') + if cost is None: + hidden = getattr(response, '_hidden_params', None) + headers = hidden.get('additional_headers') if isinstance(hidden, dict) else None + if isinstance(headers, dict): + cost = headers.get('llm_provider-x-litellm-response-cost') + if isinstance(cost, (int, float)) and (not isinstance(cost, bool)) and math.isfinite(cost) and (cost >= 0): + event['part']['cost'] = cost + data = data if isinstance(data, dict) else {} + if isinstance(data.get('id'), str) and data['id']: + event['part']['provider_request_id'] = data['id'] + for key in ('service_tier', 'cache_ttl'): + if data.get(key): + event['part'][key] = data[key] + route = _llm_route_from_response(response) or _canonical_llm_route(llm_route) + if route is not None: + event['part']['llm_route'] = route + created = data.get('created') + stamp = datetime.now(timezone.utc) + try: + if isinstance(created, str): + parsed = datetime.fromisoformat(created.replace('Z', '+00:00')) + if parsed.tzinfo is not None: + stamp = parsed + elif isinstance(created, (int, float)) and (not isinstance(created, bool)) and math.isfinite(created): + stamp = datetime.fromtimestamp(created, timezone.utc) + except (ValueError, OverflowError, OSError): + pass + pair = json.dumps({'type': 'step_start', 'timestamp': stamp.isoformat()}) + '\n' + pair += json.dumps(event) + '\n' + try: + receipt_path = target or Path(os.environ.get('M1_JUDGE_USAGE_PATH', '/logs/verifier/judge-trajectory.jsonl')) + receipt_path.parent.mkdir(parents=True, exist_ok=True) + with receipt_path.open('a') as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + handle.write(pair) + handle.flush() + os.fsync(handle.fileno()) + except OSError as exc: + if target is not None: + raise JudgeReceiptError(f'judge receipt write failed: {exc}') from exc + print(f'judge accounting: write failed ({type(exc).__name__})', file=sys.stderr) + +def openrouter_judge_pins() -> dict[str, dict]: + raw = os.environ.get('M1_OPENROUTER_JUDGE_PROVIDER_PINS', '').strip() + if not raw: + return {} + try: + pins = json.loads(raw) + except json.JSONDecodeError: + print('judge provider pins: invalid JSON in M1_OPENROUTER_JUDGE_PROVIDER_PINS', file=sys.stderr) + return {} + return {model: pin for model, pin in pins.items() if isinstance(pin, dict) and pin.get('order')} if isinstance(pins, dict) else {} + +def apply_judge_provider_pin(kwargs: dict, pins: dict[str, dict]) -> dict: + model = kwargs.get('model') + pin = pins.get(model) if isinstance(model, str) else None + if pin is None: + return kwargs + extra_body = dict(kwargs.get('extra_body') or {}) + provider = dict(extra_body.get('provider') or {}) + provider['order'] = list(pin['order']) + if pin.get('allow_fallbacks') is False: + provider['allow_fallbacks'] = False + if pin.get('zdr'): + provider['zdr'] = True + extra_body['provider'] = provider + return {**kwargs, 'extra_body': extra_body} +_TRANSIENT_ERROR_NAMES = ('RateLimitError', 'ServiceUnavailableError', 'InternalServerError', 'BadGatewayError', 'APIConnectionError') +_RETRYABLE_STATUS_CODES = frozenset({408, 409, 425, 429, 500, 502, 503, 504}) +_AUTH_ERROR_NAMES = ('AuthenticationError', 'PermissionDeniedError') +_AUTH_STATUS_CODES = frozenset({401, 403}) +_AUTH_RETRIES = 4 +_DEFAULT_TRANSIENT_RETRIES = 6 +_MAX_TRANSIENT_RETRIES = 20 +_MAX_RETRY_DELAY_SECONDS = 60.0 +_DEFAULT_EMPTY_RESPONSE_RETRIES = 3 +_DEFAULT_RETRY_BUDGET_SECONDS = 900.0 +_MAX_RETRY_BUDGET_SECONDS = 86400.0 + +def transient_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_TRANSIENT_RETRIES', '').strip() + if not raw: + return _DEFAULT_TRANSIENT_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_TRANSIENT_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_TRANSIENT_RETRIES + +def empty_response_retry_limit() -> int: + raw = os.environ.get('M1_JUDGE_EMPTY_RESPONSE_RETRIES', '').strip() + if not raw: + return _DEFAULT_EMPTY_RESPONSE_RETRIES + try: + return max(0, min(int(raw), _MAX_TRANSIENT_RETRIES)) + except ValueError: + print('judge retries: invalid M1_JUDGE_EMPTY_RESPONSE_RETRIES, using the default', file=sys.stderr) + return _DEFAULT_EMPTY_RESPONSE_RETRIES + +def retry_budget_seconds() -> float: + raw = os.environ.get('M1_JUDGE_RETRY_BUDGET_SECONDS', '').strip() + if not raw: + return _DEFAULT_RETRY_BUDGET_SECONDS + try: + value = float(raw) + except ValueError: + value = math.nan + if not math.isfinite(value) or value < 0: + print('judge retries: invalid M1_JUDGE_RETRY_BUDGET_SECONDS, using the default', file=sys.stderr) + return _DEFAULT_RETRY_BUDGET_SECONDS + return min(value, _MAX_RETRY_BUDGET_SECONDS) + +def _within_budget(deadline: float, delay: float, model) -> bool: + remaining = deadline - time.monotonic() + if delay <= remaining: + return True + print(f'judge call retry budget spent: {model} would wait {delay:.1f}s with {max(remaining, 0.0):.1f}s left of M1_JUDGE_RETRY_BUDGET_SECONDS, failing now', file=sys.stderr) + return False + +def is_empty_verdict(response) -> bool: + data = response.model_dump() if hasattr(response, 'model_dump') else response + if not isinstance(data, dict): + return False + choices = data.get('choices') + if not isinstance(choices, list) or not choices: + return True + first = choices[0] + message = first.get('message') if isinstance(first, dict) else None + if not isinstance(message, dict): + return True + if message.get('tool_calls') or message.get('function_call'): + return False + content = message.get('content') + if isinstance(content, list): + content = ''.join((part.get('text') or '' for part in content if isinstance(part, dict))) + return not (isinstance(content, str) and content.strip()) + +def _matches(exc: BaseException, litellm, names: tuple[str, ...], statuses: frozenset[int]) -> bool: + classes = tuple((cls for cls in (getattr(litellm, name, None) for name in names) if isinstance(cls, type))) + if classes and isinstance(exc, classes): + return True + status = getattr(exc, 'status_code', None) + return type(status) is int and status in statuses + +def is_transient_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _TRANSIENT_ERROR_NAMES, _RETRYABLE_STATUS_CODES) + +def is_auth_error(exc: BaseException, litellm) -> bool: + return _matches(exc, litellm, _AUTH_ERROR_NAMES, _AUTH_STATUS_CODES) + +def should_retry(exc: BaseException, litellm, attempt: int, limit: int) -> bool: + if attempt < limit and is_transient_error(exc, litellm): + return True + return attempt < min(limit, _AUTH_RETRIES) and is_auth_error(exc, litellm) + +def _retry_after_seconds(exc: BaseException) -> float | None: + headers = getattr(exc, 'headers', None) + if headers is None: + headers = getattr(getattr(exc, 'response', None), 'headers', None) + if headers is None: + return None + try: + raw = headers.get('retry-after') + if raw is None: + raw = headers.get('Retry-After') + value = float(raw) + except (AttributeError, TypeError, ValueError): + return None + return value if math.isfinite(value) and value >= 0 else None + +def retry_delay(exc: BaseException | None, attempt: int) -> float: + base = min(_MAX_RETRY_DELAY_SECONDS, 2.0 ** (attempt + 1)) + delay = base * (0.5 + random.random()) + retry_after = _retry_after_seconds(exc) if exc is not None else None + if retry_after is not None: + delay = max(delay, min(_MAX_RETRY_DELAY_SECONDS, retry_after)) + return delay + +def _note_retry(model, exc: BaseException, attempt: int, limit: int, delay: float) -> None: + status = getattr(exc, 'status_code', None) + print(f"judge call retry {attempt}/{limit}: {model} {type(exc).__name__} status={(status if type(status) is int else 'n/a')}, waiting {delay:.1f}s", file=sys.stderr) + +def _note_empty(model, response, attempt: int, limit: int, delay: float) -> None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + reason = None + if isinstance(data, dict) and isinstance(data.get('choices'), list) and data['choices']: + first = data['choices'][0] + reason = first.get('finish_reason') if isinstance(first, dict) else None + print(f'judge call retry {attempt}/{limit}: {model} empty verdict (finish_reason={reason}), waiting {delay:.1f}s', file=sys.stderr) + +def install(litellm, *, synchronous: bool=False) -> None: + pins = openrouter_judge_pins() + limit = transient_retry_limit() + empty_limit = empty_response_retry_limit() + deadline = time.monotonic() + retry_budget_seconds() + if synchronous: + original = litellm.completion + + def accounted(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = original(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + time.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + time.sleep(delay) + continue + return response + litellm.completion = accounted + return + original_async = litellm.acompletion + + async def accounted_async(*args, **kwargs): + kwargs = apply_judge_provider_pin(kwargs, pins) + model = kwargs.get('model') or (args[0] if args else 'unknown') + attempt = empty_attempts = 0 + while True: + try: + call_kwargs, capture = _gemini_capture(kwargs, model) + response = await original_async(*args, **call_kwargs) + except BaseException as exc: + delay = retry_delay(exc, attempt) if should_retry(exc, litellm, attempt, limit) else None + if delay is not None and _within_budget(deadline, delay, model): + attempt += 1 + _note_retry(model, exc, attempt, limit, delay) + await asyncio.sleep(delay) + continue + _record_judge_usage({}, model) + raise + _record_judge_usage(response, model, native_usage=capture.evidence if capture else None, native_prompt_status=capture.prompt_status if capture else None, llm_route=capture.llm_route if capture else None) + if empty_attempts < empty_limit and is_empty_verdict(response): + delay = retry_delay(None, empty_attempts) + if _within_budget(deadline, delay, model): + empty_attempts += 1 + _note_empty(model, response, empty_attempts, empty_limit, delay) + await asyncio.sleep(delay) + continue + return response + litellm.acompletion = accounted_async + +def record_agent_usage(attempt, *, model: str, provider: str) -> None: + records: dict[str, tuple[str, dict]] = {} + current_model = model + for filename in getattr(attempt, 'logs', []): + try: + with Path(filename).open() as stream: + for line in stream: + try: + event = json.loads(line) + except (ValueError, TypeError): + continue + if not isinstance(event, dict): + continue + message = event.get('message') or {} + if event.get('type') == 'assistant' and isinstance(message, dict) and isinstance(message.get('usage'), dict): + raw = message['usage'] + cached, written = (raw.get('cache_read_input_tokens'), raw.get('cache_creation_input_tokens')) + if all((type(value) is int and value >= 0 for value in (raw.get('input_tokens'), raw.get('output_tokens')))) and all((value is None or (type(value) is int and value >= 0) for value in (cached, written))): + receipt: dict = {'usage': {'input_uncached_tokens': raw['input_tokens'], 'prompt_tokens': raw['input_tokens'] + cached + written if cached is not None and written is not None else None, 'completion_tokens': raw['output_tokens'], 'prompt_tokens_details': {'cached_tokens': cached, 'cache_creation_tokens': written}}} + receipt['created'] = event.get('timestamp') + creation = raw.get('cache_creation') or {} + hour = creation.get('ephemeral_1h_input_tokens', 0) if isinstance(creation, dict) else 0 + if type(hour) is int and hour > 0: + if hour == written: + receipt['cache_ttl'] = '1h' + else: + receipt['usage_granularity'] = 'mixed_cache_ttl' + records[message.get('id') or json.dumps(raw, sort_keys=True)] = (message.get('model') or current_model, receipt) + payload = event.get('payload') or {} + if not isinstance(payload, dict): + continue + if event.get('type') == 'turn_context' and payload.get('model'): + current_model = payload['model'] + if event.get('type') == 'event_msg' and payload.get('type') == 'token_count': + info = payload.get('info') or {} + raw, total = (info.get('last_token_usage'), info.get('total_token_usage')) + if isinstance(raw, dict) and isinstance(total, dict) and all((type(raw.get(key)) is int and raw.get(key) >= 0 for key in ('input_tokens', 'output_tokens'))): + receipt = {'usage': {'prompt_tokens': raw.get('input_tokens'), 'input_uncached_tokens': raw.get('input_uncached_tokens'), 'input_cache_write_tokens': raw.get('input_cache_write_tokens'), 'completion_tokens': raw.get('output_tokens'), 'prompt_tokens_details': {'cached_tokens': raw.get('cached_input_tokens')}}} + receipt['created'] = event.get('timestamp') + records[json.dumps(total, sort_keys=True)] = (current_model, receipt) + except OSError: + continue + captured_input = captured_output = 0 + input_complete = True + for requested, receipt in records.values(): + requested = requested if '/' in requested else f'{provider}/{requested}' + _record_judge_usage(receipt, requested) + receipt_input = receipt['usage'].get('prompt_tokens') + if receipt_input is None: + input_complete = False + else: + captured_input += receipt_input + captured_output += receipt['usage'].get('completion_tokens') or 0 + total = getattr(attempt, 'usage', {}) or {} + if not records or (input_complete and total.get('input_tokens') != captured_input) or total.get('output_tokens') != captured_output: + _record_judge_usage({'usage': {'prompt_tokens': 0, 'completion_tokens': 0}, 'usage_granularity': 'incomplete_agent_receipts'}, model if '/' in model else f'{provider}/{model}') + +def install_rewardkit_agents() -> None: + import rewardkit.judges as judges + original = judges.get_agent + + def get_accounted_agent(judge, cwd=None): + backend = original(judge, cwd) + run = backend.run + + async def accounted_run(*args, **kwargs): + attempt = await run(*args, **kwargs) + record_agent_usage(attempt, model=judge.model or 'unknown', provider='anthropic' if judge.agent == 'claude-code' else 'openai') + return attempt + setattr(backend, 'run', accounted_run) + return backend + setattr(judges, 'get_agent', get_accounted_agent) +if __name__ == '__main__': + import litellm + if len(sys.argv) > 2 and sys.argv[1] == '--script': + import runpy + install(litellm, synchronous=True) + sys.argv = sys.argv[2:] + runpy.run_path(sys.argv[0], run_name='__main__') + else: + install(litellm) + install_rewardkit_agents() + if Path(__file__).with_name('m1_judge_panel.json').is_file(): + from m1_rewardkit_panel import install_panel + install_panel(Path(__file__).with_name('m1_judge_panel.json')) + if Path(__file__).with_name('m1_judge_jev.json').is_file(): + from m1_rewardkit_jev import install_jev + install_jev(Path(__file__).with_name('m1_judge_jev.json')) + from rewardkit.__main__ import main + main() diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/m1_rewardkit_panel.py b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/m1_rewardkit_panel.py new file mode 100644 index 0000000000000000000000000000000000000000..164cc2ae521cdd368c2e1749d7ed8fe09f4545eb --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/m1_rewardkit_panel.py @@ -0,0 +1,169 @@ +from __future__ import annotations +import asyncio +from contextvars import ContextVar +import json +import math +import os +import sys +from pathlib import Path +from typing import Any +import uuid +_request_audit: ContextVar[tuple[Path, list[str]] | None] = ContextVar('panel_request_audit', default=None) + +class PanelIncompleteError(RuntimeError): + pass + +def _audit_warning(exc: Exception, warnings: list[str]) -> None: + message = f'judge panel audit: diagnostic capture failed ({type(exc).__name__})' + if message not in warnings: + warnings.append(message) + print(message, file=sys.stderr) + +def _write_audit(path: Path, record: dict[str, Any], warnings: list[str], *, append: bool=False) -> None: + try: + text = json.dumps(record, allow_nan=False, default=str) + '\n' + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('a' if append else 'w') as stream: + stream.write(text) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + +def _binary(raw: Any) -> int: + if isinstance(raw, bool): + return int(raw) + if isinstance(raw, int | float) and math.isfinite(raw) and (raw in (0, 1)): + return int(raw) + if isinstance(raw, str): + value = raw.strip().lower() + if value in {'yes', 'true', '1'}: + return 1 + if value in {'no', 'false', '0'}: + return 0 + raise PanelIncompleteError('m1_judge_panel_incomplete: invalid binary vote') + +def validate_votes(scores: list[Any], criteria: list[Any]) -> None: + names = [criterion.name for criterion in criteria] + if len(set(names)) != len(names) or [score.name for score in scores] != names: + raise PanelIncompleteError('m1_judge_panel_incomplete: criterion membership mismatch') + for score, criterion in zip(scores, criteria, strict=True): + if score.error: + raise PanelIncompleteError('m1_judge_panel_incomplete: judge returned an error') + raw = _binary(score.raw) + expected = 1 - raw if criterion.negate else raw + if not math.isfinite(score.value) or score.value != expected: + raise PanelIncompleteError('m1_judge_panel_incomplete: inconsistent binary score') + +async def run_panel(judge: Any, criteria: list[Any], weights: list[float] | None, system_prompt: str | None, *, config: dict[str, Any], run_llm: Any, score_type: Any, audit_dir: Path) -> tuple[list[Any], str, list[str]]: + from rewardkit.models import Binary + if not criteria or any((not isinstance(criterion.output_format, Binary) for criterion in criteria)): + raise ValueError('panel majority voting requires nonempty binary criteria') + group_dir = audit_dir / uuid.uuid4().hex + warnings_out: list[str] = [] + + async def member_call(index: int, member: dict[str, Any]): + member_judge = judge.model_copy(update=member) + evidence: dict[str, Any] = {'member': index + 1, 'judge': member, 'criteria': [criterion.name for criterion in criteria], 'status': 'started'} + path = group_dir / f'judge-{index + 1}.json' + _write_audit(path, evidence, warnings_out) + token = _request_audit.set((group_dir / f'judge-{index + 1}-requests.jsonl', warnings_out)) + try: + scores, output, warnings = await run_llm(member_judge, criteria, weights, system_prompt) + evidence.update(output=output, warnings=warnings) + validate_votes(scores, criteria) + evidence['scores'] = [score.to_dict() for score in scores] + evidence['status'] = 'completed' + return (scores, output, warnings) + except BaseException as exc: + evidence.update(status='failed', error_class=type(exc).__name__) + if isinstance(exc, PanelIncompleteError): + evidence['error'] = str(exc) + raise + finally: + _request_audit.reset(token) + _write_audit(path, evidence, warnings_out) + outcomes = await asyncio.gather(*(member_call(index, member) for index, member in enumerate(config['members'])), return_exceptions=True) + failed = [index + 1 for index, result in enumerate(outcomes) if isinstance(result, BaseException)] + if failed: + _write_audit(group_dir / 'panel.json', {'status': 'incomplete', 'failed_members': failed}, warnings_out) + raise PanelIncompleteError(f'm1_judge_panel_incomplete: failed members {failed}; see panel audit artifacts') + completed = [outcome for outcome in outcomes if not isinstance(outcome, BaseException)] + combined = [] + for index, criterion in enumerate(criteria): + votes = [{'judge': config['members'][member_index], **outcome[0][index].to_dict()} for member_index, outcome in enumerate(completed)] + passes = sum((vote['value'] == 1 for vote in votes)) + value = int(passes >= 2) + combined.append(score_type(name=criterion.name, value=value, raw=bool(1 - value if criterion.negate else value), weight=weights[index] if weights is not None else 1.0, reasoning=f'{passes}/3 judges passed; strict majority requires 2/3.', description=criterion.description, id=criterion.id, negate=criterion.negate, optional=criterion.optional, votes=votes)) + for outcome in completed: + warnings_out.extend(outcome[2]) + audit = {'status': 'completed', 'mode': 'panel', 'aggregation': 'majority', 'required_votes': 2, 'members': config['members'], 'criteria': [score.to_dict() for score in combined]} + output = json.dumps(audit, indent=2, allow_nan=False) + _write_audit(group_dir / 'panel.json', audit, warnings_out) + return (combined, output, warnings_out) + +def install_panel(config_path: Path, *, audit_dir: Path=Path('/logs/verifier/judge-panel')) -> None: + import rewardkit.judges as judges + import rewardkit.reward as reward + from rewardkit.models import LLMJudge, Score + import litellm + config = json.loads(config_path.read_text()) + members = config.get('members') + concurrency = config.get('max_concurrent_llm') + if config.get('mode') != 'panel' or not isinstance(members, list) or len(members) != 3 or (len({member['model'] for member in members}) != 3) or (type(concurrency) is not int) or (not 1 <= concurrency <= 64): + raise ValueError('invalid materialized panel configuration') + if os.environ.get('REWARDKIT_JUDGE') or os.environ.get('REWARDKIT_MODEL'): + raise ValueError('RewardKit environment overrides cannot replace a frozen panel') + + class PanelScore(Score): + votes: list[dict[str, Any]] + + def to_dict(self): + return {**super().to_dict(), 'votes': self.votes} + original_llm = judges.arun_llm + original_call = judges._arun_llm_call + original_details = reward.Reward.to_detail_dict + original_completion = litellm.acompletion + active_loop = None + semaphore = None + + async def captured_completion(*args, **kwargs): + context = _request_audit.get() + record = {'requested_model': kwargs.get('model')} + response = None + try: + response = await original_completion(*args, **kwargs) + return response + except BaseException as exc: + record['error_class'] = type(exc).__name__ + raise + finally: + if context is not None: + path, warnings = context + try: + if response is not None: + data = response.model_dump() if hasattr(response, 'model_dump') else response + record.update(response_model=data.get('model'), choices=data.get('choices')) + _write_audit(path, record, warnings, append=True) + except (OSError, TypeError, ValueError) as exc: + _audit_warning(exc, warnings) + + async def bounded_call(*args, **kwargs): + nonlocal active_loop, semaphore + loop = asyncio.get_running_loop() + if active_loop is not loop: + active_loop, semaphore = (loop, asyncio.Semaphore(concurrency)) + assert semaphore is not None + async with semaphore: + return await original_call(*args, **kwargs) + + async def panel_call(judge, criteria, weights=None, system_prompt=None): + return await run_panel(judge, criteria, weights, system_prompt, config=config, run_llm=original_llm, score_type=PanelScore, audit_dir=audit_dir) + + def panel_details(self, score): + detail = original_details(self, score) + if isinstance(self.judge, LLMJudge): + detail.update(kind='llm_panel', judge=config, aggregation='majority', required_votes=2) + return detail + setattr(reward, 'arun_llm', panel_call) + setattr(judges, '_arun_llm_call', bounded_call) + setattr(litellm, 'acompletion', captured_completion) + reward.Reward.to_detail_dict = panel_details diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/normalize_reward.py b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/normalize_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..91817ef00ea9152ca57f0030d8e879eb850ddff0 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/normalize_reward.py @@ -0,0 +1,71 @@ +from __future__ import annotations +import argparse +import json +from pathlib import Path +from typing import Any + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument('--raw-details', required=True) + parser.add_argument('--rubric', required=True) + parser.add_argument('--reward-out', required=True) + parser.add_argument('--details-out', required=True) + args = parser.parse_args() + raw_details = _load_json(Path(args.raw_details)) + rubric = _load_json(Path(args.rubric)) + criteria = rubric['criteria'] + raw_by_name = _raw_criteria_by_name(raw_details) + positive_total = sum((float(item['score']) for item in criteria if float(item['score']) > 0)) + if positive_total <= 0: + raise ValueError('rubric must contain at least one positive score') + earned = 0.0 + normalized_criteria: list[dict[str, Any]] = [] + for item in criteria: + signed_score = float(item['score']) + raw = raw_by_name.get(item['name'], {}) + value = _coerce_score(raw.get('value', 0.0)) + contribution = value * signed_score + earned += contribution + normalized_criteria.append({'name': item['name'], 'value': value, 'raw': raw.get('raw'), 'weight': signed_score, 'signed_score': signed_score, 'polarity': item['polarity'], 'contribution': contribution, 'description': item['description'], 'source': item.get('source', ''), 'justification': item.get('justification', ''), 'metadata': item.get('metadata', {}), 'reasoning': raw.get('reasoning'), 'judge_reasoning': raw.get('reasoning'), 'judge_error': raw.get('error'), **({'votes': raw['votes']} if 'votes' in raw else {})}) + unclamped = earned / positive_total + reward = max(0.0, min(1.0, unclamped)) + reward_out = {'correctness': reward} + details_out = {'correctness': {'score': reward, 'kind': 'signed_score', 'criteria': normalized_criteria, 'aggregation': {'method': 'signed_score_ratio_clamped', 'earned': earned, 'positive_total': positive_total, 'unclamped': unclamped, 'clamped': reward}, 'raw_rewardkit': raw_details}} + _write_json(Path(args.reward_out), reward_out) + _write_json(Path(args.details_out), details_out) + +def _load_json(path: Path) -> Any: + return json.loads(path.read_text()) + +def _write_json(path: Path, data: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data, indent=2) + '\n') + +def _raw_criteria_by_name(details: dict[str, Any]) -> dict[str, dict[str, Any]]: + out: dict[str, dict[str, Any]] = {} + for reward in details.values(): + for item in _iter_raw_criteria(reward): + name = item.get('name') + if isinstance(name, str): + out[name] = item + return out + +def _iter_raw_criteria(value: Any): + if isinstance(value, list): + for item in value: + yield from _iter_raw_criteria(item) + return + if not isinstance(value, dict): + return + for item in value.get('criteria') or []: + if isinstance(item, dict): + yield item + +def _coerce_score(value: Any) -> float: + if isinstance(value, bool): + return 1.0 if value else 0.0 + if isinstance(value, int | float): + return max(0.0, min(1.0, float(value))) + return 0.0 +if __name__ == '__main__': + main() diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/agent_prompt.md b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/agent_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..ca489c065bafd5d10e764f033c9dfd1195933db3 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/agent_prompt.md @@ -0,0 +1,10 @@ +You are grading the submitted legal analysis against the criteria below. + +Read `/logs/artifacts/answer.md`, the answer captured by the verifier, before +assigning any scores. Evaluate that file as the submission. Other files in +`/app` may supply context, but must not replace the submitted answer. Do not +modify the submission. If it is missing or empty, state that in your reasoning +and apply the criteria to that missing or empty submission. Preserve each +criterion's stated positive or penalty polarity. + +{criteria} diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_1.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_1.toml new file mode 100644 index 0000000000000000000000000000000000000000..dc9980ff60a43ce13a78958491de0ca9193f0501 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_1.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_1" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that Patton bears the initial burden of producing sufficient evidence to support the justification instruction." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_10.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_10.toml new file mode 100644 index 0000000000000000000000000000000000000000..bf8b75b899195b72b2d9b7be549971d77587f58f --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_10.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_10" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States Patton failed to put forth substantial evidence of self-defense to support the submission of a justification instruction." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_2.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_2.toml new file mode 100644 index 0000000000000000000000000000000000000000..b222b65ab0cfeacd410b2ee5fe94609a325c4d12 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_2.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_2" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Identifies that only once Patton presents substantial evidence of self-defense does the burden shift to the government to disprove justification." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_3.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_3.toml new file mode 100644 index 0000000000000000000000000000000000000000..31798c974c1f7c85a4a00964c7045382174fa71a --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_3.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_3" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions that the only evidence of self-defense is that Nelson also fired a gun." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_4.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_4.toml new file mode 100644 index 0000000000000000000000000000000000000000..c080bd3df04b0a8fac013257494ffed9f583ba51 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_4.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_4" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions that there was a lack of evidence proving who fired first on May 10, 2020." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_5.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_5.toml new file mode 100644 index 0000000000000000000000000000000000000000..a2acb8f669c9d7318a709d04200b3832d2e6356d --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_5.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_5" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions that the OTB group had rolled the windows down before reaching Nelson." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_6.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_6.toml new file mode 100644 index 0000000000000000000000000000000000000000..fb2aaa2001b983b5bf1a63efbbd3c471d1962381 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_6.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_6" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions that Patton was hanging out the window with a firearm." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_7.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_7.toml new file mode 100644 index 0000000000000000000000000000000000000000..ea19cfe8cf896fb89b11090da706a82ccfbc2bbd --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_7.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_7" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: Mentions that Nelson's car was already stopped when Patton fired his gun." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_8.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_8.toml new file mode 100644 index 0000000000000000000000000000000000000000..75cb3fee48b0ba471b4878b6e2724fb63ce38d60 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_8.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_8" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that the OTB group could have driven away." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_9.toml b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_9.toml new file mode 100644 index 0000000000000000000000000000000000000000..09133a498bcea54ad8403fe2eeec513191d6c078 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/raw_correctness/criterion_9.toml @@ -0,0 +1,12 @@ +[judge] +judge = "openai/gpt-5.6-terra" +files = ["/logs/artifacts/answer.md"] +reasoning_effort = "medium" +timeout = 1500 +weight = 1.0 + +[[criterion]] +name = "criterion_9" +description = "Does the response satisfy the legal-analysis criterion below? Apply any numeric tolerances stated inside the criterion text.\n\nCriterion: States that the only reasonable inference from Patton's actions is that he intended to fire regardless of what Nelson did." +type = "binary" +weight = 1.0 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/test.sh b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..66a509a7bcdbe412851f3a012a5ba7b16cf0925b --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/tests/test.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +set -euo pipefail + +mkdir -p /logs/artifacts /logs/verifier/raw + +python3 - <<'PYEOF' +import json +import shutil +from pathlib import Path + + +def has_text(path: Path) -> bool: + return path.exists() and path.is_file() and bool(path.read_text(errors="replace").strip()) + + +def fallback_paths(answer_path: Path) -> list[Path]: + paths = [] + try: + relative = answer_path.relative_to("/app") + paths.append(Path("/app/app") / relative) + except ValueError: + pass + return [path for path in paths if path != answer_path] + + +config = json.loads(Path("/tests/fixtures/config.json").read_text()) +answer_path = Path(config["answer_path"]) +artifact_answer = Path("/logs/artifacts/answer.md") +artifact_answer.parent.mkdir(parents=True, exist_ok=True) +if has_text(answer_path): + shutil.copyfile(answer_path, artifact_answer) +else: + for candidate in fallback_paths(answer_path): + if has_text(candidate): + shutil.copyfile(candidate, artifact_answer) + break + else: + artifact_answer.write_text("") + +# Harbor collects /logs/artifacts when the agent step ends, which is before this +# script runs, so the copy above never reaches the uploaded artifacts. /logs/verifier +# is uploaded after the verifier phase, so persist the graded answer there too. +verifier_answer = Path("/logs/verifier/answer.md") +verifier_answer.parent.mkdir(parents=True, exist_ok=True) +shutil.copyfile(artifact_answer, verifier_answer) +PYEOF + +uv run --no-project --with 'harbor-rewardkit[all]==0.2.0' python /tests/m1_rewardkit_accounting.py /tests/raw_correctness \ + --workspace /app \ + --output /logs/verifier/raw/reward.json \ + --max-concurrent-llm "${MAX_CONCURRENT_LLM:-4}" \ + --max-concurrent-agent "${M1_MAX_CONCURRENT_AGENT:-1}" + +python /tests/normalize_reward.py \ + --raw-details /logs/verifier/raw/reward-details.json \ + --rubric /tests/fixtures/rubric.json \ + --reward-out /logs/verifier/reward.json \ + --details-out /logs/verifier/reward-details.json diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/workdir/attachments/Facts.pdf b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/workdir/attachments/Facts.pdf new file mode 100644 index 0000000000000000000000000000000000000000..9f02a52190e9af8679f266b6d45dfd7eb47907bf --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/workdir/attachments/Facts.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:81530702122b9be6a549aa9d0556996ae243b50e4a94146fb149a450e20de875 +size 128104 diff --git a/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/workdir/attachments/Kuhse.pdf b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/workdir/attachments/Kuhse.pdf new file mode 100644 index 0000000000000000000000000000000000000000..c81150760b2dd6bb2a5d05e86b35fa56bc2d185b --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/steps/assignment-2/workdir/attachments/Kuhse.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8dd767805ecb91ce661b54e1c8e909b43b76c856ff3621505435a166b6c6cda8 +size 147326 diff --git a/tasks/lrb-vicar-trial-jury-instructions/task.toml b/tasks/lrb-vicar-trial-jury-instructions/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..34947db602f4b0187f53285c062844c643d3f295 --- /dev/null +++ b/tasks/lrb-vicar-trial-jury-instructions/task.toml @@ -0,0 +1,76 @@ +schema_version = "1.1" +multi_step_reward_strategy = "mean" + +[task] +name = "micro1/lrb-vicar-trial-jury-instructions" + +[metadata] +benchmark = "LegalReasonBench" +title = "OTB Gang VICAR Trial Jury Instructions" +practice_area = "Criminal and investigations" +research_universe = "closed-universe" +task_version = "51" +overall_reward = "points-weighted across assignments: sum of earned signed points over sum of positive points, clamped to [0, 1]. Harbor multi_step_reward_strategy=mean is diagnostic only. See scripts/score_matter.py." + +[agent] +timeout_sec = 10800.0 + +[environment] +build_timeout_sec = 900.0 +cpus = 2 +memory_mb = 4096 +storage_mb = 8192 +workdir = "/app" +allow_internet = true + +[environment.env] +OPENCODE_ENABLE_EXA = "${OPENCODE_ENABLE_EXA:-1}" + +[[steps]] +name = "assignment-1" +artifacts = ["/app/response1.md"] + +[steps.agent] +timeout_sec = 10800.0 + +[steps.verifier] +timeout_sec = 1800.0 + +[steps.verifier.env] +OPENAI_API_KEY = "${OPENAI_API_KEY:-}" +ANTHROPIC_API_KEY = "${ANTHROPIC_API_KEY:-}" +GOOGLE_API_KEY = "${GOOGLE_API_KEY:-}" +GEMINI_API_KEY = "${GEMINI_API_KEY:-}" +JUDGE_MODEL = "openai/gpt-5.6-terra" +JUDGE_REASONING_EFFORT = "medium" +JUDGE_TIMEOUT = "1500" +MAX_CONCURRENT_LLM = "12" +M1_MAX_CONCURRENT_AGENT = "1" +M1_JUDGE_TRANSIENT_RETRIES = "12" +M1_JUDGE_EMPTY_RESPONSE_RETRIES = "3" +M1_JUDGE_RETRY_BUDGET_SECONDS = "900" + +[[steps]] +name = "assignment-2" +artifacts = ["/app/response2.md"] + +[steps.agent] +timeout_sec = 10800.0 + +[steps.verifier] +timeout_sec = 1800.0 + +[steps.verifier.env] +OPENAI_API_KEY = "${OPENAI_API_KEY:-}" +ANTHROPIC_API_KEY = "${ANTHROPIC_API_KEY:-}" +GOOGLE_API_KEY = "${GOOGLE_API_KEY:-}" +GEMINI_API_KEY = "${GEMINI_API_KEY:-}" +JUDGE_MODEL = "openai/gpt-5.6-terra" +JUDGE_REASONING_EFFORT = "medium" +JUDGE_TIMEOUT = "1500" +MAX_CONCURRENT_LLM = "12" +M1_MAX_CONCURRENT_AGENT = "1" +M1_JUDGE_TRANSIENT_RETRIES = "12" +M1_JUDGE_EMPTY_RESPONSE_RETRIES = "3" +M1_JUDGE_RETRY_BUDGET_SECONDS = "900" +