diff --git a/.gitattributes b/.gitattributes index 8cbdfe09e4dfd062497e5c6a0264ee23cf8a00c3..364170eb7dfa29bcf10e29ab5a04c7a491a9835b 100644 --- a/.gitattributes +++ b/.gitattributes @@ -164,3 +164,36 @@ tasks/cuad-dd-elandiainternationalinc-04-25-2007-ex-10-8f8ca97f-v3/environment/i tasks/cuad-dd-elfbeauty-inc-07-02-2020-ex-10-1-coopera-4857c747/environment/inputs/ELFBEAUTY_INC_07_02_2020-EX-10.1-COOPERATION_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -text tasks/cuad-dd-euromediaholdingscorp-20070215-10sb12g-e-28af50c4/environment/inputs/EuromediaHoldingsCorp_20070215_10SB12G_EX-10.B_01__525118_EX-10.B_01__Content_License_Agreement.pdf filter=lfs diff=lfs merge=lfs -text tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/environment/inputs/FIBROGENINC_10_01_2014-EX-10.11-COLLABORATION_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/environment/inputs/FTENETWORKS_INC_02_18_2016-EX-99.4-STRATEGIC_ALLIANCE_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/environment/inputs/FulucaiProductionsLtd_20131223_10-Q_EX-10.9_8368347_EX-10.9_Content_License_Agreement.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/environment/inputs/GlobalTechnologiesGroupInc_20050928_10KSB_EX-10.9_4148808_EX-10.9_Content_License_Agreement.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/environment/inputs/GluMobileInc_20070319_S-1A_EX-10.09_436630_EX-10.09_Content_License_Agreement1.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/environment/inputs/GOLDRESOURCECORP_12_11_2008-EX-10.1-STRATEGIC_ALLIANCE_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/environment/inputs/GpaqAcquisitionHoldingsInc_20200123_S-4A_EX-10.6_11951677_EX-10.6_License_Agreement.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/environment/inputs/GRIDIRONBIONUTRIENTS_INC_02_05_2020-EX-10.3-SUPPLY_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/environment/inputs/HEALTHGATEDATACORP_11_24_1999-EX-10.1-HOSTING_AND_MANAGEMENT_AGREEMENT_1.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/environment/inputs/IbioInc_20200313_8-K_EX-10.1_12052678_EX-10.1_Development_Agreement.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/environment/inputs/IdeanomicsInc_20160330_10-K_EX-10.26_9512211_EX-10.26_Content_License_Agreement.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/environment/inputs/IDREAMSKYTECHNOLOGYLTD_07_03_2014-EX-10.39-Cooperation_Agreement_on_Mobile_Game_Business.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/environment/inputs/IGENEBIOTECHNOLOGYINC_05_13_2003-EX-1-JOINT_VENTURE_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/environment/inputs/ImineCorp_20180725_S-1_EX-10.5_11275970_EX-10.5_Distributor_Agreement.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/environment/inputs/ImpresseCorp_20000322_S-1A_EX-10.11_5199234_EX-10.11_Co-Branding_Agreement.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/environment/inputs/INTERNATIONALFASTFOODCORP_04_04_1997-EX-99-FRANCHISE_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/environment/inputs/INTERSECTENT_INC_05_11_2020-EX-10.1-SUPPLY_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/environment/inputs/IOVANCEBIOTHERAPEUTICS_INC_08_03_2017-EX-10.1-STRATEGIC_ALLIANCE_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/environment/inputs/JINGWEIINTERNATIONALLTD_10_04_2007-EX-10.7-INTELLECTUAL_PROPERTY_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/environment/inputs/LejuHoldingsLtd_20140121_DRS_on_F-1__EX-10.26_8473102_EX-10.26_Content_License_Agreement1.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/environment/inputs/LOYALTYPOINTINC_11_16_2004-EX-10.2-RESELLER_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/environment/inputs/Magenta_Therapeutics_Inc._-_Master_Development_and_Manufacturing_Agreement.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/environment/inputs/OFGBANCORP_03_28_2007-EX-10.23-OUTSOURCING_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/environment/inputs/OLDAPIWIND-DOWNLTD_01_08_2016-EX-1.3-AGENCY_AGREEMENT1.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/environment/inputs/ParatekPharmaceuticalsInc_20170505_10-KA_EX-10.29_10323872_EX-10.29_Outsourcing_Agreement.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/environment/inputs/PelicanDeliversInc_20200211_S-1_EX-10.3_11975895_EX-10.3_Development_Agreement2.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/environment/inputs/PREMIERBIOMEDICALINC_05_14_2020-EX-10.2-INTELLECTUAL_PROPERTY_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/environment/inputs/RareElementResourcesLtd_20171019_SC_13D_EX-99.4_10897534_EX-99.4_Intellectual_Property_Agreement.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/environment/inputs/REGANHOLDINGCORP_03_31_2008-EX-10-LICENSE_AND_HOSTING_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/environment/inputs/ReynoldsConsumerProductsInc_20200121_S-1A_EX-10.22_11948918_EX-10.22_Service_Agreement.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/environment/inputs/RUBIOSRESTAURANTSINC_03_31_2008-EX-10.75-SPONSORSHIP_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/environment/inputs/SCOUTCAMINC_05_12_2020-EX-10.22-SERVICES_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/environment/inputs/SPIENERGYCO_LTD_03_09_2011-EX-99.5-OPERATIONS_AND_MAINTENANCE_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -text +tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/environment/inputs/StampscomInc_20001114_10-Q_EX-10.47_2631630_EX-10.47_Co-Branding_Agreement.pdf filter=lfs diff=lfs merge=lfs -text diff --git a/tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/solution/solve.sh b/tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/task.toml b/tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ec85623686f6c2e181f175d7ecc01a7e2db42116 --- /dev/null +++ b/tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "FIBROGENINC_10_01_2014-EX-10.11-COLLABORATION AGREEMENT.PDF:agreement_date,exclusivity,most_favored_nation,audit_rights,ip_ownership_assignment,liquidated_damages,source_code_escrow,no_solicit_of_employees" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/tests/expected.json b/tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..4d16740dedc7da6beae391775ad911592ce892e1 --- /dev/null +++ b/tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/tests/expected.json @@ -0,0 +1,60 @@ +{ + "checks": [ + { + "id": "agreement_date", + "type": "answer", + "field": "agreement_date", + "kind": "date", + "value": "2005-06-01" + }, + { + "id": "exclusivity", + "type": "answer", + "field": "exclusivity", + "kind": "bool", + "value": true + }, + { + "id": "most_favored_nation", + "type": "answer", + "field": "most_favored_nation", + "kind": "bool", + "value": false + }, + { + "id": "audit_rights", + "type": "answer", + "field": "audit_rights", + "kind": "bool", + "value": true + }, + { + "id": "ip_ownership_assignment", + "type": "answer", + "field": "ip_ownership_assignment", + "kind": "bool", + "value": true + }, + { + "id": "liquidated_damages", + "type": "answer", + "field": "liquidated_damages", + "kind": "bool", + "value": true + }, + { + "id": "source_code_escrow", + "type": "answer", + "field": "source_code_escrow", + "kind": "bool", + "value": false + }, + { + "id": "no_solicit_of_employees", + "type": "answer", + "field": "no_solicit_of_employees", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/tests/grade.py b/tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/tests/test.sh b/tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/validation/openenv.json b/tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/environment/inputs/FTENETWORKS_INC_02_18_2016-EX-99.4-STRATEGIC_ALLIANCE_AGREEMENT.pdf b/tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/environment/inputs/FTENETWORKS_INC_02_18_2016-EX-99.4-STRATEGIC_ALLIANCE_AGREEMENT.pdf new file mode 100644 index 0000000000000000000000000000000000000000..63f094ac30f501636d27739c301f3135e288ec54 --- /dev/null +++ b/tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/environment/inputs/FTENETWORKS_INC_02_18_2016-EX-99.4-STRATEGIC_ALLIANCE_AGREEMENT.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d2fe1782e48ca203e5e9a287f8b81009ec4acd8db89c910304b03bd2d6b06909 +size 125249 diff --git a/tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/instruction.md b/tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ef98a5dc36ef78d7d2d239a0e21e9952ea01db37 --- /dev/null +++ b/tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/instruction.md @@ -0,0 +1,23 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/FTENETWORKS_INC_02_18_2016-EX-99.4-STRATEGIC_ALLIANCE_AGREEMENT.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Expiration date** (`expiration_date`): The date the initial term ends, before any renewal. +2. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party. +3. **Most favored nation** (`most_favored_nation`): If a third party gets better terms on the licensing or sale of the technology, goods or services in the contract, the buyer under this contract is entitled to those better terms. +4. **Insurance** (`insurance`): One party must maintain insurance for the benefit of the counterparty. +5. **Liquidated damages** (`liquidated_damages`): Either party can be awarded liquidated damages for breach, or a fee on termination of the contract (a termination fee). +6. **Source code escrow** (`source_code_escrow`): One party must deposit its source code with a third-party escrow agent for release to the counterparty on certain events such as bankruptcy or insolvency. +7. **Non-disparagement** (`non_disparagement`): A party must not disparage the counterparty. +8. **Revenue or profit sharing** (`revenue_profit_sharing`): One party must share revenue or profit with the counterparty for any technology, goods or services. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`expiration_date`, `anti_assignment`, `most_favored_nation`, `insurance`, `liquidated_damages`, `source_code_escrow`, `non_disparagement`, `revenue_profit_sharing`). diff --git a/tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/solution/files/answer.json b/tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..16cdb7c01ec57a97dcb97a507279e7d49b7d440c --- /dev/null +++ b/tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/solution/files/answer.json @@ -0,0 +1,10 @@ +{ + "expiration_date": "2019-02-16", + "anti_assignment": "Yes", + "most_favored_nation": "No", + "insurance": "Yes", + "liquidated_damages": "Yes", + "source_code_escrow": "No", + "non_disparagement": "No", + "revenue_profit_sharing": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/solution/solve.sh b/tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/task.toml b/tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..760142cab7fc0f27632d4f733f23ce45449a671d --- /dev/null +++ b/tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "FTENETWORKS,INC_02_18_2016-EX-99.4-STRATEGIC ALLIANCE AGREEMENT.PDF:expiration_date,anti_assignment,most_favored_nation,insurance,liquidated_damages,source_code_escrow,non_disparagement,revenue_profit_sharing" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/tests/expected.json b/tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..75c076adb043fdae10cee877d2dd6e68eff77f0f --- /dev/null +++ b/tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/tests/expected.json @@ -0,0 +1,60 @@ +{ + "checks": [ + { + "id": "expiration_date", + "type": "answer", + "field": "expiration_date", + "kind": "date", + "value": "2019-02-16" + }, + { + "id": "anti_assignment", + "type": "answer", + "field": "anti_assignment", + "kind": "bool", + "value": true + }, + { + "id": "most_favored_nation", + "type": "answer", + "field": "most_favored_nation", + "kind": "bool", + "value": false + }, + { + "id": "insurance", + "type": "answer", + "field": "insurance", + "kind": "bool", + "value": true + }, + { + "id": "liquidated_damages", + "type": "answer", + "field": "liquidated_damages", + "kind": "bool", + "value": true + }, + { + "id": "source_code_escrow", + "type": "answer", + "field": "source_code_escrow", + "kind": "bool", + "value": false + }, + { + "id": "non_disparagement", + "type": "answer", + "field": "non_disparagement", + "kind": "bool", + "value": false + }, + { + "id": "revenue_profit_sharing", + "type": "answer", + "field": "revenue_profit_sharing", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/tests/grade.py b/tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/tests/test.sh b/tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/validation/openenv.json b/tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/environment/inputs/FulucaiProductionsLtd_20131223_10-Q_EX-10.9_8368347_EX-10.9_Content_License_Agreement.pdf b/tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/environment/inputs/FulucaiProductionsLtd_20131223_10-Q_EX-10.9_8368347_EX-10.9_Content_License_Agreement.pdf new file mode 100644 index 0000000000000000000000000000000000000000..79d302d7a574e1ffbc98e011972883d0dc509d58 --- /dev/null +++ b/tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/environment/inputs/FulucaiProductionsLtd_20131223_10-Q_EX-10.9_8368347_EX-10.9_Content_License_Agreement.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6a030ed8d8f65605e86f7e6e48316aa823800a0b5ece674ad7fea0147e1a00ad +size 110262 diff --git a/tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/instruction.md b/tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b56aa54e328b4f51961b5892479b721b72470245 --- /dev/null +++ b/tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/instruction.md @@ -0,0 +1,22 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/FulucaiProductionsLtd_20131223_10-Q_EX-10.9_8368347_EX-10.9_Content_License_Agreement.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Agreement date** (`agreement_date`): The date of the contract: the date it is dated or entered into, as stated in the document. +2. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +3. **Exclusivity** (`exclusivity`): There is an exclusive dealing commitment with the counterparty: a commitment to procure all requirements from one party, or a prohibition on licensing or selling to third parties or on working with other parties, during or after the contract. An exclusive license, appointment or territory granted to the counterparty counts. +4. **Termination for convenience** (`termination_for_convenience`): A party can terminate the contract without cause, solely by giving notice and letting a waiting period expire. +5. **Most favored nation** (`most_favored_nation`): If a third party gets better terms on the licensing or sale of the technology, goods or services in the contract, the buyer under this contract is entitled to those better terms. +6. **Audit rights** (`audit_rights`): A party has the right to audit the books, records or physical locations of the counterparty to check compliance with the contract. +7. **Non-disparagement** (`non_disparagement`): A party must not disparage the counterparty. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`agreement_date`, `governing_law`, `exclusivity`, `termination_for_convenience`, `most_favored_nation`, `audit_rights`, `non_disparagement`). diff --git a/tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/solution/files/answer.json b/tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..45c7cc72c788b36f6523889f371d0675bc25f143 --- /dev/null +++ b/tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/solution/files/answer.json @@ -0,0 +1,9 @@ +{ + "agreement_date": "2012-11-15", + "governing_law": "Florida", + "exclusivity": "Yes", + "termination_for_convenience": "No", + "most_favored_nation": "No", + "audit_rights": "Yes", + "non_disparagement": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/solution/solve.sh b/tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/task.toml b/tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0fcfe652691ee3660b46c47f9db38b1009866c3d --- /dev/null +++ b/tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "FulucaiProductionsLtd_20131223_10-Q_EX-10.9_8368347_EX-10.9_Content License Agreement.pdf:agreement_date,governing_law,exclusivity,termination_for_convenience,most_favored_nation,audit_rights,non_disparagement" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/tests/expected.json b/tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..055428211885150fe5b679981e800abfe6a41ddd --- /dev/null +++ b/tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/tests/expected.json @@ -0,0 +1,59 @@ +{ + "checks": [ + { + "id": "agreement_date", + "type": "answer", + "field": "agreement_date", + "kind": "date", + "value": "2012-11-15" + }, + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "Florida", + "accept": [ + "Florida", + "State of Florida", + "Florida, USA", + "Florida, United States" + ] + }, + { + "id": "exclusivity", + "type": "answer", + "field": "exclusivity", + "kind": "bool", + "value": true + }, + { + "id": "termination_for_convenience", + "type": "answer", + "field": "termination_for_convenience", + "kind": "bool", + "value": false + }, + { + "id": "most_favored_nation", + "type": "answer", + "field": "most_favored_nation", + "kind": "bool", + "value": false + }, + { + "id": "audit_rights", + "type": "answer", + "field": "audit_rights", + "kind": "bool", + "value": true + }, + { + "id": "non_disparagement", + "type": "answer", + "field": "non_disparagement", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/tests/grade.py b/tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/tests/test.sh b/tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/validation/openenv.json b/tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/environment/inputs/GlobalTechnologiesGroupInc_20050928_10KSB_EX-10.9_4148808_EX-10.9_Content_License_Agreement.pdf b/tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/environment/inputs/GlobalTechnologiesGroupInc_20050928_10KSB_EX-10.9_4148808_EX-10.9_Content_License_Agreement.pdf new file mode 100644 index 0000000000000000000000000000000000000000..4870156e23fa3032c84cf2ffbcc24b8371bb2d06 --- /dev/null +++ b/tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/environment/inputs/GlobalTechnologiesGroupInc_20050928_10KSB_EX-10.9_4148808_EX-10.9_Content_License_Agreement.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b668fc77aeeae09a02221d0032814a43c160b5d5b4ab2a1ab9915a73e567f525 +size 203465 diff --git a/tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/instruction.md b/tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b151caffd58a04893ef60a5aec9f7dbb23c4fcca --- /dev/null +++ b/tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/instruction.md @@ -0,0 +1,23 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/GlobalTechnologiesGroupInc_20050928_10KSB_EX-10.9_4148808_EX-10.9_Content_License_Agreement.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +2. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party. +3. **Cap on liability** (`cap_on_liability`): The contract limits a party's liability for breach: a maximum recoverable amount, an exclusion of categories of damages (for example indirect, consequential or lost-profit damages), or a time limit for the counterparty to bring claims. +4. **Most favored nation** (`most_favored_nation`): If a third party gets better terms on the licensing or sale of the technology, goods or services in the contract, the buyer under this contract is entitled to those better terms. +5. **Audit rights** (`audit_rights`): A party has the right to audit the books, records or physical locations of the counterparty to check compliance with the contract. +6. **Liquidated damages** (`liquidated_damages`): Either party can be awarded liquidated damages for breach, or a fee on termination of the contract (a termination fee). +7. **Source code escrow** (`source_code_escrow`): One party must deposit its source code with a third-party escrow agent for release to the counterparty on certain events such as bankruptcy or insolvency. +8. **License grant** (`license_grant`): One party grants a license to its counterparty. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`governing_law`, `anti_assignment`, `cap_on_liability`, `most_favored_nation`, `audit_rights`, `liquidated_damages`, `source_code_escrow`, `license_grant`). diff --git a/tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/solution/files/answer.json b/tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..d257593f536e2576301311f9f4fbcebed7f0df02 --- /dev/null +++ b/tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/solution/files/answer.json @@ -0,0 +1,10 @@ +{ + "governing_law": "Florida", + "anti_assignment": "Yes", + "cap_on_liability": "Yes", + "most_favored_nation": "No", + "audit_rights": "No", + "liquidated_damages": "No", + "source_code_escrow": "No", + "license_grant": "Yes" +} \ No newline at end of file diff --git a/tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/solution/solve.sh b/tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/task.toml b/tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..74a364ef55b7560cbf8fe4ce74209e3e3c1150e3 --- /dev/null +++ b/tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "GlobalTechnologiesGroupInc_20050928_10KSB_EX-10.9_4148808_EX-10.9_Content License Agreement.pdf:governing_law,anti_assignment,cap_on_liability,most_favored_nation,audit_rights,liquidated_damages,source_code_escrow,license_grant" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/tests/expected.json b/tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..481f3c062b5b2695329bc2d9af24d48ad524e915 --- /dev/null +++ b/tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/tests/expected.json @@ -0,0 +1,66 @@ +{ + "checks": [ + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "Florida", + "accept": [ + "Florida", + "State of Florida", + "Florida, USA", + "Florida, United States" + ] + }, + { + "id": "anti_assignment", + "type": "answer", + "field": "anti_assignment", + "kind": "bool", + "value": true + }, + { + "id": "cap_on_liability", + "type": "answer", + "field": "cap_on_liability", + "kind": "bool", + "value": true + }, + { + "id": "most_favored_nation", + "type": "answer", + "field": "most_favored_nation", + "kind": "bool", + "value": false + }, + { + "id": "audit_rights", + "type": "answer", + "field": "audit_rights", + "kind": "bool", + "value": false + }, + { + "id": "liquidated_damages", + "type": "answer", + "field": "liquidated_damages", + "kind": "bool", + "value": false + }, + { + "id": "source_code_escrow", + "type": "answer", + "field": "source_code_escrow", + "kind": "bool", + "value": false + }, + { + "id": "license_grant", + "type": "answer", + "field": "license_grant", + "kind": "bool", + "value": true + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/tests/grade.py b/tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/tests/test.sh b/tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/validation/openenv.json b/tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/environment/inputs/GluMobileInc_20070319_S-1A_EX-10.09_436630_EX-10.09_Content_License_Agreement1.pdf b/tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/environment/inputs/GluMobileInc_20070319_S-1A_EX-10.09_436630_EX-10.09_Content_License_Agreement1.pdf new file mode 100644 index 0000000000000000000000000000000000000000..9a9c7a04e2234bba8ffe3ba0153997ad4b220e1b --- /dev/null +++ b/tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/environment/inputs/GluMobileInc_20070319_S-1A_EX-10.09_436630_EX-10.09_Content_License_Agreement1.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fee1c562facd69bcb9d76c614d36fc83bf9d69f8299d6a2bdb83e09789807c93 +size 327959 diff --git a/tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/instruction.md b/tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cdb8ffcb499032291bd8ca2dee53af4aa6ab690c --- /dev/null +++ b/tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/instruction.md @@ -0,0 +1,23 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/GluMobileInc_20070319_S-1A_EX-10.09_436630_EX-10.09_Content_License_Agreement1.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Expiration date** (`expiration_date`): The date the initial term ends, before any renewal. +2. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +3. **Cap on liability** (`cap_on_liability`): The contract limits a party's liability for breach: a maximum recoverable amount, an exclusion of categories of damages (for example indirect, consequential or lost-profit damages), or a time limit for the counterparty to bring claims. +4. **Most favored nation** (`most_favored_nation`): If a third party gets better terms on the licensing or sale of the technology, goods or services in the contract, the buyer under this contract is entitled to those better terms. +5. **Audit rights** (`audit_rights`): A party has the right to audit the books, records or physical locations of the counterparty to check compliance with the contract. +6. **IP ownership assignment** (`ip_ownership_assignment`): Intellectual property created by one party becomes the property of the counterparty, under the contract terms or on the occurrence of certain events. +7. **Insurance** (`insurance`): One party must maintain insurance for the benefit of the counterparty. +8. **Revenue or profit sharing** (`revenue_profit_sharing`): One party must share revenue or profit with the counterparty for any technology, goods or services. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`expiration_date`, `governing_law`, `cap_on_liability`, `most_favored_nation`, `audit_rights`, `ip_ownership_assignment`, `insurance`, `revenue_profit_sharing`). diff --git a/tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/solution/files/answer.json b/tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..db975d364eb65745a6245c82a1cc9cbc3bf9e568 --- /dev/null +++ b/tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/solution/files/answer.json @@ -0,0 +1,10 @@ +{ + "expiration_date": "2006-12-31", + "governing_law": "California", + "cap_on_liability": "Yes", + "most_favored_nation": "No", + "audit_rights": "Yes", + "ip_ownership_assignment": "Yes", + "insurance": "No", + "revenue_profit_sharing": "Yes" +} \ No newline at end of file diff --git a/tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/solution/solve.sh b/tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/task.toml b/tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d212ed87a414cfa5a61f23ec0df9c8f81e19c23f --- /dev/null +++ b/tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "GluMobileInc_20070319_S-1A_EX-10.09_436630_EX-10.09_Content License Agreement1.pdf:expiration_date,governing_law,cap_on_liability,most_favored_nation,audit_rights,ip_ownership_assignment,insurance,revenue_profit_sharing" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/tests/expected.json b/tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..b36a6fb077fb8c1fab65800ca2fda985a9ae896b --- /dev/null +++ b/tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/tests/expected.json @@ -0,0 +1,66 @@ +{ + "checks": [ + { + "id": "expiration_date", + "type": "answer", + "field": "expiration_date", + "kind": "date", + "value": "2006-12-31" + }, + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "California", + "accept": [ + "California", + "State of California", + "California, USA", + "California, United States" + ] + }, + { + "id": "cap_on_liability", + "type": "answer", + "field": "cap_on_liability", + "kind": "bool", + "value": true + }, + { + "id": "most_favored_nation", + "type": "answer", + "field": "most_favored_nation", + "kind": "bool", + "value": false + }, + { + "id": "audit_rights", + "type": "answer", + "field": "audit_rights", + "kind": "bool", + "value": true + }, + { + "id": "ip_ownership_assignment", + "type": "answer", + "field": "ip_ownership_assignment", + "kind": "bool", + "value": true + }, + { + "id": "insurance", + "type": "answer", + "field": "insurance", + "kind": "bool", + "value": false + }, + { + "id": "revenue_profit_sharing", + "type": "answer", + "field": "revenue_profit_sharing", + "kind": "bool", + "value": true + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/tests/grade.py b/tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/tests/test.sh b/tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/validation/openenv.json b/tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/environment/inputs/GOLDRESOURCECORP_12_11_2008-EX-10.1-STRATEGIC_ALLIANCE_AGREEMENT.pdf b/tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/environment/inputs/GOLDRESOURCECORP_12_11_2008-EX-10.1-STRATEGIC_ALLIANCE_AGREEMENT.pdf new file mode 100644 index 0000000000000000000000000000000000000000..1915a9c31459945e98ccf26dce440cb6a1f272d8 --- /dev/null +++ b/tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/environment/inputs/GOLDRESOURCECORP_12_11_2008-EX-10.1-STRATEGIC_ALLIANCE_AGREEMENT.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dc8efd92da2f9edc2121eef659268eb2c4d3a6ca17db04c84bd72903ccb3f98f +size 171967 diff --git a/tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/instruction.md b/tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a4422a430d5a313171f7f8600a83f61127dcd4c8 --- /dev/null +++ b/tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/instruction.md @@ -0,0 +1,22 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/GOLDRESOURCECORP_12_11_2008-EX-10.1-STRATEGIC_ALLIANCE_AGREEMENT.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +2. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party. +3. **Non-compete** (`non_compete`): A party is restricted from competing with the counterparty or from operating in a certain geography, business or technology sector. +4. **Most favored nation** (`most_favored_nation`): Does entering a later agreement with a third party entitle HOC to materially more favourable standstill terms under the strategic alliance? +5. **Insurance** (`insurance`): Does the agreement require the Company to maintain liability insurance for a director nominated by HOC, subject to the conditions in Article 5? +6. **Source code escrow** (`source_code_escrow`): One party must deposit its source code with a third-party escrow agent for release to the counterparty on certain events such as bankruptcy or insolvency. +7. **Non-disparagement** (`non_disparagement`): A party must not disparage the counterparty. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`governing_law`, `anti_assignment`, `non_compete`, `most_favored_nation`, `insurance`, `source_code_escrow`, `non_disparagement`). diff --git a/tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/solution/files/answer.json b/tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..67cccc115765c77b651ad2ce660d327e95fc33b2 --- /dev/null +++ b/tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/solution/files/answer.json @@ -0,0 +1,9 @@ +{ + "governing_law": "New York", + "anti_assignment": "Yes", + "non_compete": "No", + "most_favored_nation": "Yes", + "insurance": "Yes", + "source_code_escrow": "No", + "non_disparagement": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/solution/solve.sh b/tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/task.toml b/tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b6655837293f55b0c4e6bd2e6e6b9670a1dc49be --- /dev/null +++ b/tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "GOLDRESOURCECORP_12_11_2008-EX-10.1-STRATEGIC ALLIANCE AGREEMENT.PDF:governing_law,anti_assignment,non_compete,most_favored_nation,insurance,source_code_escrow,non_disparagement" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/tests/expected.json b/tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..5bac486af664585aea6164b0d0627f29a9c31ab6 --- /dev/null +++ b/tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/tests/expected.json @@ -0,0 +1,59 @@ +{ + "checks": [ + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "New York", + "accept": [ + "New York", + "State of New York", + "New York, USA", + "New York, United States" + ] + }, + { + "id": "anti_assignment", + "type": "answer", + "field": "anti_assignment", + "kind": "bool", + "value": true + }, + { + "id": "non_compete", + "type": "answer", + "field": "non_compete", + "kind": "bool", + "value": false + }, + { + "id": "most_favored_nation", + "type": "answer", + "field": "most_favored_nation", + "kind": "bool", + "value": true + }, + { + "id": "insurance", + "type": "answer", + "field": "insurance", + "kind": "bool", + "value": true + }, + { + "id": "source_code_escrow", + "type": "answer", + "field": "source_code_escrow", + "kind": "bool", + "value": false + }, + { + "id": "non_disparagement", + "type": "answer", + "field": "non_disparagement", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/tests/grade.py b/tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/tests/test.sh b/tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/validation/openenv.json b/tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/environment/inputs/GpaqAcquisitionHoldingsInc_20200123_S-4A_EX-10.6_11951677_EX-10.6_License_Agreement.pdf b/tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/environment/inputs/GpaqAcquisitionHoldingsInc_20200123_S-4A_EX-10.6_11951677_EX-10.6_License_Agreement.pdf new file mode 100644 index 0000000000000000000000000000000000000000..36b0eb96cff70864ae4c0587ea479dc783e874c3 --- /dev/null +++ b/tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/environment/inputs/GpaqAcquisitionHoldingsInc_20200123_S-4A_EX-10.6_11951677_EX-10.6_License_Agreement.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f4e98d86568f818283da3ffba389eb543de84e7e71089b631bdc40c8ead896b8 +size 218517 diff --git a/tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/instruction.md b/tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..68cc4b113533f9d1888690eb569c2594d8fc8092 --- /dev/null +++ b/tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/instruction.md @@ -0,0 +1,23 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/GpaqAcquisitionHoldingsInc_20200123_S-4A_EX-10.6_11951677_EX-10.6_License_Agreement.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Renewal term** (`renewal_term_months`): the length of each renewal or extension term that follows the initial term, in months, as a JSON number (for example `12` for one year). +2. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party. +3. **Audit rights** (`audit_rights`): A party has the right to audit the books, records or physical locations of the counterparty to check compliance with the contract. +4. **Right of first refusal, offer or negotiation** (`right_of_first_refusal`): One party has a right of first refusal, first offer or first negotiation to purchase, license, market or distribute equity, technology, assets, products or services. +5. **Source code escrow** (`source_code_escrow`): One party must deposit its source code with a third-party escrow agent for release to the counterparty on certain events such as bankruptcy or insolvency. +6. **No-solicit of employees** (`no_solicit_of_employees`): A party is restricted from soliciting or hiring employees or contractors of the counterparty, during or after the contract. +7. **Non-disparagement** (`non_disparagement`): A party must not disparage the counterparty. +8. **License grant** (`license_grant`): One party grants a license to its counterparty. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`renewal_term_months`, `anti_assignment`, `audit_rights`, `right_of_first_refusal`, `source_code_escrow`, `no_solicit_of_employees`, `non_disparagement`, `license_grant`). diff --git a/tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/solution/files/answer.json b/tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..ba8fb09ec30f92e17031760e0415bf5ba3f96114 --- /dev/null +++ b/tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/solution/files/answer.json @@ -0,0 +1,10 @@ +{ + "renewal_term_months": 60, + "anti_assignment": "Yes", + "audit_rights": "No", + "right_of_first_refusal": "Yes", + "source_code_escrow": "No", + "no_solicit_of_employees": "No", + "non_disparagement": "No", + "license_grant": "Yes" +} \ No newline at end of file diff --git a/tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/solution/solve.sh b/tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/task.toml b/tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e50f66f976461f3af7ef72be45f480d452d733c9 --- /dev/null +++ b/tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "GpaqAcquisitionHoldingsInc_20200123_S-4A_EX-10.6_11951677_EX-10.6_License Agreement.pdf:renewal_term_months,anti_assignment,audit_rights,right_of_first_refusal,source_code_escrow,no_solicit_of_employees,non_disparagement,license_grant" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/tests/expected.json b/tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..8cbf9186c0fa3f0bb5fabaedbc2f4b35cbd46da4 --- /dev/null +++ b/tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/tests/expected.json @@ -0,0 +1,62 @@ +{ + "checks": [ + { + "id": "renewal_term_months", + "type": "answer", + "field": "renewal_term_months", + "kind": "number", + "value": 60, + "abs_tol": 0, + "rel_tol": 0 + }, + { + "id": "anti_assignment", + "type": "answer", + "field": "anti_assignment", + "kind": "bool", + "value": true + }, + { + "id": "audit_rights", + "type": "answer", + "field": "audit_rights", + "kind": "bool", + "value": false + }, + { + "id": "right_of_first_refusal", + "type": "answer", + "field": "right_of_first_refusal", + "kind": "bool", + "value": true + }, + { + "id": "source_code_escrow", + "type": "answer", + "field": "source_code_escrow", + "kind": "bool", + "value": false + }, + { + "id": "no_solicit_of_employees", + "type": "answer", + "field": "no_solicit_of_employees", + "kind": "bool", + "value": false + }, + { + "id": "non_disparagement", + "type": "answer", + "field": "non_disparagement", + "kind": "bool", + "value": false + }, + { + "id": "license_grant", + "type": "answer", + "field": "license_grant", + "kind": "bool", + "value": true + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/tests/grade.py b/tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/tests/test.sh b/tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/validation/openenv.json b/tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/environment/inputs/GRIDIRONBIONUTRIENTS_INC_02_05_2020-EX-10.3-SUPPLY_AGREEMENT.pdf b/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/environment/inputs/GRIDIRONBIONUTRIENTS_INC_02_05_2020-EX-10.3-SUPPLY_AGREEMENT.pdf new file mode 100644 index 0000000000000000000000000000000000000000..f099be13a1cf020095b14f9b09758c928e575657 --- /dev/null +++ b/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/environment/inputs/GRIDIRONBIONUTRIENTS_INC_02_05_2020-EX-10.3-SUPPLY_AGREEMENT.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d93ea7019265bd2ddf010d47e5571ddc248cf6228671372f27b685f9f7e90c23 +size 114695 diff --git a/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/instruction.md b/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9dcefa5a0e248c616092afacbdbd216ce640ee38 --- /dev/null +++ b/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/instruction.md @@ -0,0 +1,23 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/GRIDIRONBIONUTRIENTS_INC_02_05_2020-EX-10.3-SUPPLY_AGREEMENT.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Agreement date** (`agreement_date`): The date of the contract: the date it is dated or entered into, as stated in the document; if the only dates given for it are the parties' signature dates and these differ, the date of the last signature. +2. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +3. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party. +4. **Non-compete** (`non_compete`): A party is restricted from competing with the counterparty or from operating in a certain geography, business or technology sector. +5. **Termination for convenience** (`termination_for_convenience`): A party can terminate the contract without cause, either at will or solely by giving notice and letting a waiting period expire. +6. **Right of first refusal, offer or negotiation** (`right_of_first_refusal`): One party has a right of first refusal, first offer or first negotiation to purchase, license, market or distribute equity, technology, assets, products or services. +7. **Insurance** (`insurance`): One party must maintain insurance for the benefit of the counterparty. +8. **Liquidated damages** (`liquidated_damages`): Either party can be awarded liquidated damages for breach, or a fee on termination of the contract (a termination fee). + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`agreement_date`, `governing_law`, `anti_assignment`, `non_compete`, `termination_for_convenience`, `right_of_first_refusal`, `insurance`, `liquidated_damages`). diff --git a/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/solution/files/answer.json b/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..a01e3036948875cde3a2ee45498d5c6d1874e289 --- /dev/null +++ b/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/solution/files/answer.json @@ -0,0 +1,10 @@ +{ + "agreement_date": "2020-01-27", + "governing_law": "Colorado", + "anti_assignment": "Yes", + "non_compete": "No", + "termination_for_convenience": "Yes", + "right_of_first_refusal": "No", + "insurance": "No", + "liquidated_damages": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/solution/solve.sh b/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/task.toml b/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5fa4a4969b9b5148a213ae716f765da928e5480c --- /dev/null +++ b/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/task.toml @@ -0,0 +1,47 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "GRIDIRONBIONUTRIENTS,INC_02_05_2020-EX-10.3-SUPPLY AGREEMENT.PDF:agreement_date,governing_law,anti_assignment,non_compete,termination_for_convenience,right_of_first_refusal,insurance,liquidated_damages" +task_kind = "single-contract-checklist" + +[metadata.apex_gap.rewrite] +change = "{\"add_conventions\": [], \"correct\": {}, \"evidence\": \"runs/apex-knowledge/task-supply/key-verification/decisions/cuad.json\", \"from\": \"runs/apex-knowledge/wave3/cuad/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60\", \"reason\": \"agreement_date: adjudication: reworded to close an open reading (text of adjudicator A); termination_for_convenience: adjudication: reworded to close an open reading (text of adjudicator A)\", \"remove\": [], \"rewrite\": {\"agreement_date\": \"1. **Agreement date** (`agreement_date`): The date of the contract: the date it is dated or entered into, as stated in the document; if the only dates given for it are the parties' signature dates and these differ, the date of the last signature.\", \"termination_for_convenience\": \"5. **Termination for convenience** (`termination_for_convenience`): A party can terminate the contract without cause, either at will or solely by giving notice and letting a waiting period expire.\"}, \"v1_task_id\": \"cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60\"}" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/tests/expected.json b/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..47fccba06490bdbc297b40c96706d4105df5a013 --- /dev/null +++ b/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/tests/expected.json @@ -0,0 +1,66 @@ +{ + "checks": [ + { + "id": "agreement_date", + "type": "answer", + "field": "agreement_date", + "kind": "date", + "value": "2020-01-27" + }, + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "Colorado", + "accept": [ + "Colorado", + "State of Colorado", + "Colorado, USA", + "Colorado, United States" + ] + }, + { + "id": "anti_assignment", + "type": "answer", + "field": "anti_assignment", + "kind": "bool", + "value": true + }, + { + "id": "non_compete", + "type": "answer", + "field": "non_compete", + "kind": "bool", + "value": false + }, + { + "id": "termination_for_convenience", + "type": "answer", + "field": "termination_for_convenience", + "kind": "bool", + "value": true + }, + { + "id": "right_of_first_refusal", + "type": "answer", + "field": "right_of_first_refusal", + "kind": "bool", + "value": false + }, + { + "id": "insurance", + "type": "answer", + "field": "insurance", + "kind": "bool", + "value": false + }, + { + "id": "liquidated_damages", + "type": "answer", + "field": "liquidated_damages", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/tests/grade.py b/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/tests/test.sh b/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/validation/openenv.json b/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/environment/inputs/HEALTHGATEDATACORP_11_24_1999-EX-10.1-HOSTING_AND_MANAGEMENT_AGREEMENT_1.pdf b/tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/environment/inputs/HEALTHGATEDATACORP_11_24_1999-EX-10.1-HOSTING_AND_MANAGEMENT_AGREEMENT_1.pdf new file mode 100644 index 0000000000000000000000000000000000000000..cf94f69f38439778edcadbbab2d45e566b311eb7 --- /dev/null +++ b/tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/environment/inputs/HEALTHGATEDATACORP_11_24_1999-EX-10.1-HOSTING_AND_MANAGEMENT_AGREEMENT_1.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a55ca7b2dca2d31487beb2e8022a49449a8f637a5e2c5933441e768e80546a80 +size 164793 diff --git a/tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/instruction.md b/tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a373d6c1755f89b5ff94904fab581997d2469f94 --- /dev/null +++ b/tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/instruction.md @@ -0,0 +1,22 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/HEALTHGATEDATACORP_11_24_1999-EX-10.1-HOSTING_AND_MANAGEMENT_AGREEMENT_1.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Effective date** (`effective_date`): The date the contract becomes effective or its term commences. +2. **Expiration date** (`expiration_date`): The date the initial term ends, before any renewal. +3. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +4. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party. +5. **Right of first refusal, offer or negotiation** (`right_of_first_refusal`): One party has a right of first refusal, first offer or first negotiation to purchase, license, market or distribute equity, technology, assets, products or services. +6. **Source code escrow** (`source_code_escrow`): One party must deposit its source code with a third-party escrow agent for release to the counterparty on certain events such as bankruptcy or insolvency. +7. **No-solicit of employees** (`no_solicit_of_employees`): A party is restricted from soliciting or hiring employees or contractors of the counterparty, during or after the contract. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`effective_date`, `expiration_date`, `governing_law`, `anti_assignment`, `right_of_first_refusal`, `source_code_escrow`, `no_solicit_of_employees`). diff --git a/tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/solution/files/answer.json b/tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..1e351c03647e2d59136b3a3128c0c99576115541 --- /dev/null +++ b/tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/solution/files/answer.json @@ -0,0 +1,9 @@ +{ + "effective_date": "1998-01-01", + "expiration_date": "2000-02-28", + "governing_law": "England", + "anti_assignment": "Yes", + "right_of_first_refusal": "No", + "source_code_escrow": "Yes", + "no_solicit_of_employees": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/solution/solve.sh b/tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/task.toml b/tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8149764553a8083fd66e35d55f7fe3c26ff5d35d --- /dev/null +++ b/tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "HEALTHGATEDATACORP_11_24_1999-EX-10.1-HOSTING AND MANAGEMENT AGREEMENT (1).pdf:effective_date,expiration_date,governing_law,anti_assignment,right_of_first_refusal,source_code_escrow,no_solicit_of_employees" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/tests/expected.json b/tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..a49d87384ffd3976866e4251f2c03494414f9a8d --- /dev/null +++ b/tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/tests/expected.json @@ -0,0 +1,58 @@ +{ + "checks": [ + { + "id": "effective_date", + "type": "answer", + "field": "effective_date", + "kind": "date", + "value": "1998-01-01" + }, + { + "id": "expiration_date", + "type": "answer", + "field": "expiration_date", + "kind": "date", + "value": "2000-02-28" + }, + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "England", + "accept": [ + "England", + "England and Wales", + "England & Wales" + ] + }, + { + "id": "anti_assignment", + "type": "answer", + "field": "anti_assignment", + "kind": "bool", + "value": true + }, + { + "id": "right_of_first_refusal", + "type": "answer", + "field": "right_of_first_refusal", + "kind": "bool", + "value": false + }, + { + "id": "source_code_escrow", + "type": "answer", + "field": "source_code_escrow", + "kind": "bool", + "value": true + }, + { + "id": "no_solicit_of_employees", + "type": "answer", + "field": "no_solicit_of_employees", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/tests/grade.py b/tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..f9c9197d521d2bb8a537a6467bf30c433b7bcd26 --- /dev/null +++ b/tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/tests/grade.py @@ -0,0 +1,295 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def same_cell(a, b): + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + if not same_cell(want[sheet][name].value, got[sheet][name].value): + return False, f"{sheet}!{name}: want {want[sheet][name].value!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + ok = number_ok(got, want, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) if got is not None else False + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/tests/test.sh b/tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/validation/openenv.json b/tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/environment/inputs/IbioInc_20200313_8-K_EX-10.1_12052678_EX-10.1_Development_Agreement.pdf b/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/environment/inputs/IbioInc_20200313_8-K_EX-10.1_12052678_EX-10.1_Development_Agreement.pdf new file mode 100644 index 0000000000000000000000000000000000000000..a52e0c21beecbf29b12f2b13f1be5fcb953b4182 --- /dev/null +++ b/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/environment/inputs/IbioInc_20200313_8-K_EX-10.1_12052678_EX-10.1_Development_Agreement.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b79d33af39e0de3f3a41c8ed8578b3aef1fbb101de2e79cb6a435dbdb51ca155 +size 202726 diff --git a/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/instruction.md b/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e858f8a9c86067029f9c9275025f327eabad90c0 --- /dev/null +++ b/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/instruction.md @@ -0,0 +1,23 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/IbioInc_20200313_8-K_EX-10.1_12052678_EX-10.1_Development_Agreement.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Agreement date** (`agreement_date`): The date of the contract: the date it is dated or entered into, as stated in the document; if the only dates given for it are the parties' signature dates and these differ, the date of the last signature. +2. **Effective date** (`effective_date`): The date the contract becomes effective or its term commences. +3. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +4. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party. +5. **Most favored nation** (`most_favored_nation`): If a third party gets better terms on the licensing or sale of the technology, goods or services in the contract, the buyer under this contract is entitled to those better terms. +6. **Audit rights** (`audit_rights`): A party has the right to audit the books, records or physical locations of the counterparty to check compliance with the contract. +7. **No-solicit of employees** (`no_solicit_of_employees`): A party is restricted from soliciting or hiring employees or contractors of the counterparty, during or after the contract. +8. **License grant** (`license_grant`): One party grants a license to its counterparty. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`agreement_date`, `effective_date`, `governing_law`, `anti_assignment`, `most_favored_nation`, `audit_rights`, `no_solicit_of_employees`, `license_grant`). diff --git a/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/solution/files/answer.json b/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..aacb6c1780054d6006aa8a9b5d8d5c7a30752911 --- /dev/null +++ b/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/solution/files/answer.json @@ -0,0 +1,10 @@ +{ + "agreement_date": "2018-08-08", + "effective_date": "2018-08-08", + "governing_law": "Texas", + "anti_assignment": "Yes", + "most_favored_nation": "No", + "audit_rights": "No", + "no_solicit_of_employees": "No", + "license_grant": "Yes" +} \ No newline at end of file diff --git a/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/solution/solve.sh b/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/task.toml b/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b40c99ed7633ff61bec73415bc7924a6583d6412 --- /dev/null +++ b/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/task.toml @@ -0,0 +1,47 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "IbioInc_20200313_8-K_EX-10.1_12052678_EX-10.1_Development Agreement.pdf:agreement_date,effective_date,governing_law,anti_assignment,most_favored_nation,audit_rights,no_solicit_of_employees,license_grant" +task_kind = "single-contract-checklist" + +[metadata.apex_gap.rewrite] +change = "{\"add_conventions\": [], \"correct\": {}, \"evidence\": \"runs/apex-knowledge/task-supply/key-verification/decisions/cuad.json\", \"from\": \"runs/apex-knowledge/wave1/cuad/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c\", \"reason\": \"agreement_date: adjudication: reworded to close an open reading (text of adjudicator A)\", \"remove\": [], \"rewrite\": {\"agreement_date\": \"1. **Agreement date** (`agreement_date`): The date of the contract: the date it is dated or entered into, as stated in the document; if the only dates given for it are the parties' signature dates and these differ, the date of the last signature.\"}, \"v1_task_id\": \"cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c\"}" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/tests/expected.json b/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..851fa9a607fd70558f3e86a9774674d13e989edc --- /dev/null +++ b/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/tests/expected.json @@ -0,0 +1,66 @@ +{ + "checks": [ + { + "id": "agreement_date", + "type": "answer", + "field": "agreement_date", + "kind": "date", + "value": "2018-08-08" + }, + { + "id": "effective_date", + "type": "answer", + "field": "effective_date", + "kind": "date", + "value": "2018-08-08" + }, + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "Texas", + "accept": [ + "Texas", + "State of Texas", + "Texas, USA", + "Texas, United States" + ] + }, + { + "id": "anti_assignment", + "type": "answer", + "field": "anti_assignment", + "kind": "bool", + "value": true + }, + { + "id": "most_favored_nation", + "type": "answer", + "field": "most_favored_nation", + "kind": "bool", + "value": false + }, + { + "id": "audit_rights", + "type": "answer", + "field": "audit_rights", + "kind": "bool", + "value": false + }, + { + "id": "no_solicit_of_employees", + "type": "answer", + "field": "no_solicit_of_employees", + "kind": "bool", + "value": false + }, + { + "id": "license_grant", + "type": "answer", + "field": "license_grant", + "kind": "bool", + "value": true + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/tests/grade.py b/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/tests/test.sh b/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/validation/openenv.json b/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/environment/inputs/IdeanomicsInc_20160330_10-K_EX-10.26_9512211_EX-10.26_Content_License_Agreement.pdf b/tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/environment/inputs/IdeanomicsInc_20160330_10-K_EX-10.26_9512211_EX-10.26_Content_License_Agreement.pdf new file mode 100644 index 0000000000000000000000000000000000000000..4cbc37e17884b6c330cf42b6f6245ca4fc4979c3 --- /dev/null +++ b/tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/environment/inputs/IdeanomicsInc_20160330_10-K_EX-10.26_9512211_EX-10.26_Content_License_Agreement.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:70a096f54dc6627a28c12d1ff75efce19f6b54d781b7b69fd322ca811e38f0ce +size 266980 diff --git a/tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/instruction.md b/tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a5c3da151ab43e509b4ac9f93f968d36ac6de25a --- /dev/null +++ b/tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/instruction.md @@ -0,0 +1,23 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/IdeanomicsInc_20160330_10-K_EX-10.26_9512211_EX-10.26_Content_License_Agreement.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Agreement date** (`agreement_date`): The date of the contract: the date it is dated or entered into, as stated in the document. +2. **Effective date** (`effective_date`): The date the contract becomes effective or its term commences. +3. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +4. **Cap on liability** (`cap_on_liability`): The contract limits a party's liability for breach: a maximum recoverable amount, an exclusion of categories of damages (for example indirect, consequential or lost-profit damages), or a time limit for the counterparty to bring claims. +5. **Most favored nation** (`most_favored_nation`): If a third party gets better terms on the licensing or sale of the technology, goods or services in the contract, the buyer under this contract is entitled to those better terms. +6. **Right of first refusal, offer or negotiation** (`right_of_first_refusal`): One party has a right of first refusal, first offer or first negotiation to purchase, license, market or distribute equity, technology, assets, products or services. +7. **Source code escrow** (`source_code_escrow`): One party must deposit its source code with a third-party escrow agent for release to the counterparty on certain events such as bankruptcy or insolvency. +8. **No-solicit of employees** (`no_solicit_of_employees`): A party is restricted from soliciting or hiring employees or contractors of the counterparty, during or after the contract. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`agreement_date`, `effective_date`, `governing_law`, `cap_on_liability`, `most_favored_nation`, `right_of_first_refusal`, `source_code_escrow`, `no_solicit_of_employees`). diff --git a/tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/solution/files/answer.json b/tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..e9a11c779d7e879c8f7c7ea07739ca5e4eb2f08a --- /dev/null +++ b/tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/solution/files/answer.json @@ -0,0 +1,10 @@ +{ + "agreement_date": "2015-12-21", + "effective_date": "2015-12-21", + "governing_law": "New York", + "cap_on_liability": "Yes", + "most_favored_nation": "No", + "right_of_first_refusal": "Yes", + "source_code_escrow": "No", + "no_solicit_of_employees": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/solution/solve.sh b/tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/task.toml b/tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5ac1d69895c56af322c88f556bce19bd93a41d2f --- /dev/null +++ b/tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "IdeanomicsInc_20160330_10-K_EX-10.26_9512211_EX-10.26_Content License Agreement.pdf:agreement_date,effective_date,governing_law,cap_on_liability,most_favored_nation,right_of_first_refusal,source_code_escrow,no_solicit_of_employees" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/tests/expected.json b/tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..e0fd25187dec021440ab9a7484ef7cca5913c257 --- /dev/null +++ b/tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/tests/expected.json @@ -0,0 +1,66 @@ +{ + "checks": [ + { + "id": "agreement_date", + "type": "answer", + "field": "agreement_date", + "kind": "date", + "value": "2015-12-21" + }, + { + "id": "effective_date", + "type": "answer", + "field": "effective_date", + "kind": "date", + "value": "2015-12-21" + }, + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "New York", + "accept": [ + "New York", + "State of New York", + "New York, USA", + "New York, United States" + ] + }, + { + "id": "cap_on_liability", + "type": "answer", + "field": "cap_on_liability", + "kind": "bool", + "value": true + }, + { + "id": "most_favored_nation", + "type": "answer", + "field": "most_favored_nation", + "kind": "bool", + "value": false + }, + { + "id": "right_of_first_refusal", + "type": "answer", + "field": "right_of_first_refusal", + "kind": "bool", + "value": true + }, + { + "id": "source_code_escrow", + "type": "answer", + "field": "source_code_escrow", + "kind": "bool", + "value": false + }, + { + "id": "no_solicit_of_employees", + "type": "answer", + "field": "no_solicit_of_employees", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/tests/grade.py b/tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/tests/test.sh b/tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/validation/openenv.json b/tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/environment/inputs/IDREAMSKYTECHNOLOGYLTD_07_03_2014-EX-10.39-Cooperation_Agreement_on_Mobile_Game_Business.pdf b/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/environment/inputs/IDREAMSKYTECHNOLOGYLTD_07_03_2014-EX-10.39-Cooperation_Agreement_on_Mobile_Game_Business.pdf new file mode 100644 index 0000000000000000000000000000000000000000..394ef58ddaba00d0fd92001a193ef12e2663d7dc --- /dev/null +++ b/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/environment/inputs/IDREAMSKYTECHNOLOGYLTD_07_03_2014-EX-10.39-Cooperation_Agreement_on_Mobile_Game_Business.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c1336673650746e71e23482b54c47570062dad1f5b04c6f469ba9648197ffdab +size 189924 diff --git a/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/instruction.md b/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..09eabca88ee5651d43b172ff491d3d7a7d28de1b --- /dev/null +++ b/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/instruction.md @@ -0,0 +1,20 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/IDREAMSKYTECHNOLOGYLTD_07_03_2014-EX-10.39-Cooperation_Agreement_on_Mobile_Game_Business.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Effective date** (`effective_date`): The date the contract becomes effective or its term commences. +2. **Renewal term** (`renewal_term_months`): the length of each renewal or extension term that follows the initial term, in months, as a JSON number (for example `12` for one year). +3. **Change of control** (`change_of_control`): One party has the right to terminate, or consent or notice of the counterparty is required, if that party undergoes a change of control (a merger, stock sale, transfer of all or substantially all of its assets or business, or assignment by operation of law). +4. **No-solicit of employees** (`no_solicit_of_employees`): A party is restricted from soliciting or hiring employees or contractors of the counterparty, during or after the contract. +5. **Revenue or profit sharing** (`revenue_profit_sharing`): One party must share revenue or profit with the counterparty for any technology, goods or services. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`effective_date`, `renewal_term_months`, `change_of_control`, `no_solicit_of_employees`, `revenue_profit_sharing`). diff --git a/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/solution/files/answer.json b/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..a35f80e1ee31091c4a25817a4a24782dc07000ef --- /dev/null +++ b/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/solution/files/answer.json @@ -0,0 +1,7 @@ +{ + "effective_date": "2013-01-01", + "renewal_term_months": 12, + "change_of_control": "Yes", + "no_solicit_of_employees": "No", + "revenue_profit_sharing": "Yes" +} \ No newline at end of file diff --git a/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/solution/solve.sh b/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/task.toml b/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c06aac632a0c1c9685dab6fa7d701c6526e03af8 --- /dev/null +++ b/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/task.toml @@ -0,0 +1,47 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "IDREAMSKYTECHNOLOGYLTD_07_03_2014-EX-10.39-Cooperation Agreement on Mobile Game Business.PDF:effective_date,renewal_term_months,change_of_control,right_of_first_refusal,no_solicit_of_employees,revenue_profit_sharing" +task_kind = "single-contract-checklist" + +[metadata.apex_gap.rewrite] +change = "{\"add_conventions\": [], \"correct\": {}, \"evidence\": \"runs/apex-knowledge/task-supply/key-verification/decisions/cuad.json\", \"from\": \"runs/apex-knowledge/wave2/cuad/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0\", \"reason\": \"right_of_first_refusal: adjudication: key corrected False -> True | adjudicated rewording not used, question removed: definition widened to any priority right, to fit this contract's clause\", \"remove\": [\"right_of_first_refusal\"], \"rewrite\": {}, \"v1_task_id\": \"cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0\"}" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/tests/expected.json b/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..e6d5a17638b4714ab0b5d403086f68093336f8f7 --- /dev/null +++ b/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/tests/expected.json @@ -0,0 +1,41 @@ +{ + "checks": [ + { + "id": "effective_date", + "type": "answer", + "field": "effective_date", + "kind": "date", + "value": "2013-01-01" + }, + { + "id": "renewal_term_months", + "type": "answer", + "field": "renewal_term_months", + "kind": "number", + "value": 12, + "abs_tol": 0, + "rel_tol": 0 + }, + { + "id": "change_of_control", + "type": "answer", + "field": "change_of_control", + "kind": "bool", + "value": true + }, + { + "id": "no_solicit_of_employees", + "type": "answer", + "field": "no_solicit_of_employees", + "kind": "bool", + "value": false + }, + { + "id": "revenue_profit_sharing", + "type": "answer", + "field": "revenue_profit_sharing", + "kind": "bool", + "value": true + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/tests/grade.py b/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/tests/test.sh b/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/validation/openenv.json b/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/environment/inputs/IGENEBIOTECHNOLOGYINC_05_13_2003-EX-1-JOINT_VENTURE_AGREEMENT.pdf b/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/environment/inputs/IGENEBIOTECHNOLOGYINC_05_13_2003-EX-1-JOINT_VENTURE_AGREEMENT.pdf new file mode 100644 index 0000000000000000000000000000000000000000..fa58845dd9b5935ca987da19e848912d208e40af --- /dev/null +++ b/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/environment/inputs/IGENEBIOTECHNOLOGYINC_05_13_2003-EX-1-JOINT_VENTURE_AGREEMENT.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3779151ccd99f9de506db17e6869bcd03f66c5db15aa7d43a7e0c548e9b1d748 +size 146982 diff --git a/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/instruction.md b/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..76419ca55c60895138c25a34412fa332cf0fe662 --- /dev/null +++ b/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/instruction.md @@ -0,0 +1,21 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/IGENEBIOTECHNOLOGYINC_05_13_2003-EX-1-JOINT_VENTURE_AGREEMENT.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Agreement date** (`agreement_date`): The date of the contract: the date it is dated or entered into, as stated in the document. +2. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party. +3. **Exclusivity** (`exclusivity`): There is an exclusive dealing commitment with the counterparty: a commitment to procure all requirements from one party, or a prohibition on licensing or selling to third parties or on working with other parties, during or after the contract. An exclusive license, appointment or territory granted to the counterparty counts. +4. **Insurance** (`insurance`): One party must maintain insurance for the benefit of the counterparty. +5. **Source code escrow** (`source_code_escrow`): One party must deposit its source code with a third-party escrow agent for release to the counterparty on certain events such as bankruptcy or insolvency. +6. **No-solicit of employees** (`no_solicit_of_employees`): A party is restricted from soliciting or hiring employees or contractors of the counterparty, during or after the contract. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`agreement_date`, `anti_assignment`, `exclusivity`, `insurance`, `source_code_escrow`, `no_solicit_of_employees`). diff --git a/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/solution/files/answer.json b/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..4b865ec60fb702fed14caea945ef76c30b2881c2 --- /dev/null +++ b/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/solution/files/answer.json @@ -0,0 +1,8 @@ +{ + "agreement_date": "2003-03-18", + "anti_assignment": "Yes", + "exclusivity": "Yes", + "insurance": "No", + "source_code_escrow": "No", + "no_solicit_of_employees": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/solution/solve.sh b/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/task.toml b/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..756fb0424bfaa31c8bf9700f12b1d0caf950e013 --- /dev/null +++ b/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/task.toml @@ -0,0 +1,47 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "IGENEBIOTECHNOLOGYINC_05_13_2003-EX-1-JOINT VENTURE AGREEMENT.PDF:agreement_date,effective_date,anti_assignment,exclusivity,most_favored_nation,insurance,source_code_escrow,no_solicit_of_employees" +task_kind = "single-contract-checklist" + +[metadata.apex_gap.rewrite] +change = "{\"add_conventions\": [], \"correct\": {}, \"evidence\": \"runs/apex-knowledge/task-supply/key-verification/decisions/cuad.json\", \"from\": \"runs/apex-knowledge/wave3/cuad/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb\", \"reason\": \"effective_date: adjudicated rewording not used, question removed: definition names this contract's joint-venture commencement date; most_favored_nation: adjudication unresolved (cuad-1-A, cuad-1-B, cuad-1-C)\", \"remove\": [\"effective_date\", \"most_favored_nation\"], \"rewrite\": {}, \"v1_task_id\": \"cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb\"}" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/tests/expected.json b/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..d227243891eab3b4b5b5236f7cc81cbc7d0a90b1 --- /dev/null +++ b/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/tests/expected.json @@ -0,0 +1,46 @@ +{ + "checks": [ + { + "id": "agreement_date", + "type": "answer", + "field": "agreement_date", + "kind": "date", + "value": "2003-03-18" + }, + { + "id": "anti_assignment", + "type": "answer", + "field": "anti_assignment", + "kind": "bool", + "value": true + }, + { + "id": "exclusivity", + "type": "answer", + "field": "exclusivity", + "kind": "bool", + "value": true + }, + { + "id": "insurance", + "type": "answer", + "field": "insurance", + "kind": "bool", + "value": false + }, + { + "id": "source_code_escrow", + "type": "answer", + "field": "source_code_escrow", + "kind": "bool", + "value": false + }, + { + "id": "no_solicit_of_employees", + "type": "answer", + "field": "no_solicit_of_employees", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/tests/grade.py b/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/tests/test.sh b/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/validation/openenv.json b/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2/environment/inputs/IMAGEWARESYSTEMSINC_12_20_1999-EX-10.22-MAINTENANCE_AGREEMENT.pdf b/tasks/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2/environment/inputs/IMAGEWARESYSTEMSINC_12_20_1999-EX-10.22-MAINTENANCE_AGREEMENT.pdf new file mode 100644 index 0000000000000000000000000000000000000000..79d37ab90fc13a728ea4876d989a6384dac7366f Binary files /dev/null and b/tasks/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2/environment/inputs/IMAGEWARESYSTEMSINC_12_20_1999-EX-10.22-MAINTENANCE_AGREEMENT.pdf differ diff --git a/tasks/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2/instruction.md b/tasks/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..648e124ab000caa7ac183d3b13c00ce4230274ce --- /dev/null +++ b/tasks/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2/instruction.md @@ -0,0 +1,22 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/IMAGEWARESYSTEMSINC_12_20_1999-EX-10.22-MAINTENANCE_AGREEMENT.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Effective date** (`effective_date`): The date the contract becomes effective or its term commences. +2. **Renewal term** (`renewal_term_months`): the length of each renewal or extension term that follows the initial term, in months, as a JSON number (for example `12` for one year). +3. **Change of control** (`change_of_control`): One party has the right to terminate, or consent or notice of the counterparty is required, if that party undergoes a change of control (a merger, stock sale, transfer of all or substantially all of its assets or business, or assignment by operation of law). +4. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party. +5. **Cap on liability** (`cap_on_liability`): The contract limits a party's liability for breach: a maximum recoverable amount, an exclusion of categories of damages (for example indirect, consequential or lost-profit damages), or a time limit for the counterparty to bring claims. +6. **Most favored nation** (`most_favored_nation`): If a third party gets better terms on the licensing or sale of the technology, goods or services in the contract, the buyer under this contract is entitled to those better terms. +7. **Source code escrow** (`source_code_escrow`): One party must deposit its source code with a third-party escrow agent for release to the counterparty on certain events such as bankruptcy or insolvency. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`effective_date`, `renewal_term_months`, `change_of_control`, `anti_assignment`, `cap_on_liability`, `most_favored_nation`, `source_code_escrow`). diff --git a/tasks/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2/solution/files/answer.json b/tasks/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..731a7d96c77806510f75705d1cd61cea03e3bf7d --- /dev/null +++ b/tasks/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2/solution/files/answer.json @@ -0,0 +1,9 @@ +{ + "effective_date": "1993-12-10", + "renewal_term_months": 12, + "change_of_control": "No", + "anti_assignment": "Yes", + "cap_on_liability": "Yes", + "most_favored_nation": "No", + "source_code_escrow": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2/solution/solve.sh b/tasks/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2/task.toml b/tasks/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f6891208a56a97d086f489ecbad7f231a15fe9c1 --- /dev/null +++ b/tasks/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "IMAGEWARESYSTEMSINC_12_20_1999-EX-10.22-MAINTENANCE AGREEMENT.PDF:effective_date,renewal_term_months,change_of_control,anti_assignment,cap_on_liability,most_favored_nation,source_code_escrow" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2/tests/expected.json b/tasks/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..822f915e0ac20d6086a759f136f02aaa888162fe --- /dev/null +++ b/tasks/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2/tests/expected.json @@ -0,0 +1,55 @@ +{ + "checks": [ + { + "id": "effective_date", + "type": "answer", + "field": "effective_date", + "kind": "date", + "value": "1993-12-10" + }, + { + "id": "renewal_term_months", + "type": "answer", + "field": "renewal_term_months", + "kind": "number", + "value": 12, + "abs_tol": 0, + "rel_tol": 0 + }, + { + "id": "change_of_control", + "type": "answer", + "field": "change_of_control", + "kind": "bool", + "value": false + }, + { + "id": "anti_assignment", + "type": "answer", + "field": "anti_assignment", + "kind": "bool", + "value": true + }, + { + "id": "cap_on_liability", + "type": "answer", + "field": "cap_on_liability", + "kind": "bool", + "value": true + }, + { + "id": "most_favored_nation", + "type": "answer", + "field": "most_favored_nation", + "kind": "bool", + "value": false + }, + { + "id": "source_code_escrow", + "type": "answer", + "field": "source_code_escrow", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2/tests/grade.py b/tasks/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..b25905557330a4d0f95daffdb53db00a8e326999 --- /dev/null +++ b/tasks/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2/tests/grade.py @@ -0,0 +1,332 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + if type(got) not in (int, float): + return False, f"{key}: expected a JSON number in months" + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2/tests/test.sh b/tasks/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2/validation/openenv.json b/tasks/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-imagewaresystemsinc-12-20-1999-ex-10-22--9b0b5125-v2/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/environment/inputs/ImineCorp_20180725_S-1_EX-10.5_11275970_EX-10.5_Distributor_Agreement.pdf b/tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/environment/inputs/ImineCorp_20180725_S-1_EX-10.5_11275970_EX-10.5_Distributor_Agreement.pdf new file mode 100644 index 0000000000000000000000000000000000000000..cc72f89947e6ac648e12e9aa6aa8bf6a70adcdad --- /dev/null +++ b/tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/environment/inputs/ImineCorp_20180725_S-1_EX-10.5_11275970_EX-10.5_Distributor_Agreement.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:570c3ae4bdf0b54427ed4bde77bdf9b63eeef613c206a65efce575d84e153921 +size 147750 diff --git a/tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/instruction.md b/tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2e09ea44deffc89cd123a831e3bc532536dc92f8 --- /dev/null +++ b/tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/instruction.md @@ -0,0 +1,21 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/ImineCorp_20180725_S-1_EX-10.5_11275970_EX-10.5_Distributor_Agreement.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Agreement date** (`agreement_date`): The date of the contract: the date it is dated or entered into, as stated in the document. +2. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +3. **Cap on liability** (`cap_on_liability`): The contract limits a party's liability for breach: a maximum recoverable amount, an exclusion of categories of damages (for example indirect, consequential or lost-profit damages), or a time limit for the counterparty to bring claims. +4. **Most favored nation** (`most_favored_nation`): If a third party gets better terms on the licensing or sale of the technology, goods or services in the contract, the buyer under this contract is entitled to those better terms. +5. **Right of first refusal, offer or negotiation** (`right_of_first_refusal`): One party has a right of first refusal, first offer or first negotiation to purchase, license, market or distribute equity, technology, assets, products or services. +6. **Minimum commitment** (`minimum_commitment`): Does the agreement impose a minimum number of units on an individual purchase order? + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`agreement_date`, `governing_law`, `cap_on_liability`, `most_favored_nation`, `right_of_first_refusal`, `minimum_commitment`). diff --git a/tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/solution/files/answer.json b/tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..75b7ce6c70057d19aa43ec4f461bc3b0ba658785 --- /dev/null +++ b/tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/solution/files/answer.json @@ -0,0 +1,8 @@ +{ + "agreement_date": "2018-07-19", + "governing_law": "Indiana", + "cap_on_liability": "Yes", + "most_favored_nation": "No", + "right_of_first_refusal": "No", + "minimum_commitment": "Yes" +} \ No newline at end of file diff --git a/tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/solution/solve.sh b/tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/task.toml b/tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c1a2fe931649480e2d6c29d6e8ab1fd3a3ed3ad3 --- /dev/null +++ b/tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "ImineCorp_20180725_S-1_EX-10.5_11275970_EX-10.5_Distributor Agreement.pdf:agreement_date,governing_law,cap_on_liability,most_favored_nation,right_of_first_refusal,minimum_commitment" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/tests/expected.json b/tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..1bae3653d626fa7e72416b418f6cee6f333c5ffc --- /dev/null +++ b/tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/tests/expected.json @@ -0,0 +1,52 @@ +{ + "checks": [ + { + "id": "agreement_date", + "type": "answer", + "field": "agreement_date", + "kind": "date", + "value": "2018-07-19" + }, + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "Indiana", + "accept": [ + "Indiana", + "State of Indiana", + "Indiana, USA", + "Indiana, United States" + ] + }, + { + "id": "cap_on_liability", + "type": "answer", + "field": "cap_on_liability", + "kind": "bool", + "value": true + }, + { + "id": "most_favored_nation", + "type": "answer", + "field": "most_favored_nation", + "kind": "bool", + "value": false + }, + { + "id": "right_of_first_refusal", + "type": "answer", + "field": "right_of_first_refusal", + "kind": "bool", + "value": false + }, + { + "id": "minimum_commitment", + "type": "answer", + "field": "minimum_commitment", + "kind": "bool", + "value": true + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/tests/grade.py b/tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/tests/test.sh b/tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/validation/openenv.json b/tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/environment/inputs/ImpresseCorp_20000322_S-1A_EX-10.11_5199234_EX-10.11_Co-Branding_Agreement.pdf b/tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/environment/inputs/ImpresseCorp_20000322_S-1A_EX-10.11_5199234_EX-10.11_Co-Branding_Agreement.pdf new file mode 100644 index 0000000000000000000000000000000000000000..fed3b7c4f69ece6fb01413d11a3a68facb9848c7 --- /dev/null +++ b/tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/environment/inputs/ImpresseCorp_20000322_S-1A_EX-10.11_5199234_EX-10.11_Co-Branding_Agreement.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e5811ba26708c1dad49c49ccc8eb932e2ae64146c0dbd0be4b253c6611d2d106 +size 140076 diff --git a/tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/instruction.md b/tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5c6a606c0ba6731639e5a3c4ac77b992854d26c1 --- /dev/null +++ b/tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/instruction.md @@ -0,0 +1,23 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/ImpresseCorp_20000322_S-1A_EX-10.11_5199234_EX-10.11_Co-Branding_Agreement.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Agreement date** (`agreement_date`): The date of the contract: the date it is dated or entered into, as stated in the document. +2. **Effective date** (`effective_date`): The date the contract becomes effective or its term commences. +3. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +4. **Most favored nation** (`most_favored_nation`): If a third party gets better terms on the licensing or sale of the technology, goods or services in the contract, the buyer under this contract is entitled to those better terms. +5. **Audit rights** (`audit_rights`): A party has the right to audit the books, records or physical locations of the counterparty to check compliance with the contract. +6. **Source code escrow** (`source_code_escrow`): One party must deposit its source code with a third-party escrow agent for release to the counterparty on certain events such as bankruptcy or insolvency. +7. **Non-disparagement** (`non_disparagement`): A party must not disparage the counterparty. +8. **License grant** (`license_grant`): One party grants a license to its counterparty. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`agreement_date`, `effective_date`, `governing_law`, `most_favored_nation`, `audit_rights`, `source_code_escrow`, `non_disparagement`, `license_grant`). diff --git a/tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/solution/files/answer.json b/tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..f51cef0104d02a9917505bc99bef9f05cbf292e2 --- /dev/null +++ b/tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/solution/files/answer.json @@ -0,0 +1,10 @@ +{ + "agreement_date": "2000-03-03", + "effective_date": "2000-03-03", + "governing_law": "Delaware", + "most_favored_nation": "No", + "audit_rights": "Yes", + "source_code_escrow": "No", + "non_disparagement": "No", + "license_grant": "Yes" +} \ No newline at end of file diff --git a/tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/solution/solve.sh b/tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/task.toml b/tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..57b3cec93a64cd4b6afdfba0f6239b5be6bb7fc4 --- /dev/null +++ b/tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "ImpresseCorp_20000322_S-1A_EX-10.11_5199234_EX-10.11_Co-Branding Agreement.pdf:agreement_date,effective_date,governing_law,most_favored_nation,audit_rights,source_code_escrow,non_disparagement,license_grant" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/tests/expected.json b/tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..44f2686107d55b7abc9370f8445773ddf532afee --- /dev/null +++ b/tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/tests/expected.json @@ -0,0 +1,66 @@ +{ + "checks": [ + { + "id": "agreement_date", + "type": "answer", + "field": "agreement_date", + "kind": "date", + "value": "2000-03-03" + }, + { + "id": "effective_date", + "type": "answer", + "field": "effective_date", + "kind": "date", + "value": "2000-03-03" + }, + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "Delaware", + "accept": [ + "Delaware", + "State of Delaware", + "Delaware, USA", + "Delaware, United States" + ] + }, + { + "id": "most_favored_nation", + "type": "answer", + "field": "most_favored_nation", + "kind": "bool", + "value": false + }, + { + "id": "audit_rights", + "type": "answer", + "field": "audit_rights", + "kind": "bool", + "value": true + }, + { + "id": "source_code_escrow", + "type": "answer", + "field": "source_code_escrow", + "kind": "bool", + "value": false + }, + { + "id": "non_disparagement", + "type": "answer", + "field": "non_disparagement", + "kind": "bool", + "value": false + }, + { + "id": "license_grant", + "type": "answer", + "field": "license_grant", + "kind": "bool", + "value": true + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/tests/grade.py b/tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/tests/test.sh b/tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/validation/openenv.json b/tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/environment/inputs/INTERNATIONALFASTFOODCORP_04_04_1997-EX-99-FRANCHISE_AGREEMENT.pdf b/tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/environment/inputs/INTERNATIONALFASTFOODCORP_04_04_1997-EX-99-FRANCHISE_AGREEMENT.pdf new file mode 100644 index 0000000000000000000000000000000000000000..bd5e4494ac91691a7d9982a79db48ae17d643cd0 --- /dev/null +++ b/tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/environment/inputs/INTERNATIONALFASTFOODCORP_04_04_1997-EX-99-FRANCHISE_AGREEMENT.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f0bd160801278dde2dd342a8416d158eaf86a7c74b059a737bee973c5e38861 +size 144849 diff --git a/tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/instruction.md b/tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f8af588ed69deb672b6ac08776ddf0408e4543f3 --- /dev/null +++ b/tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/instruction.md @@ -0,0 +1,23 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/INTERNATIONALFASTFOODCORP_04_04_1997-EX-99-FRANCHISE_AGREEMENT.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- For governing law, return two US state names separated by a slash, in the document order requested (for example `Delaware / Maine`). + +Checklist: + +1. **Governing law** (`governing_law`): Which US states are named in section 19.3’s substantive choice-of-law sentence and in Schedule 1’s Governing Law entry, respectively? Report both state names in that order, even if the provisions conflict. +2. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party. +3. **Cap on liability** (`cap_on_liability`): The contract limits a party's liability for breach: a maximum recoverable amount, an exclusion of categories of damages (for example indirect, consequential or lost-profit damages), or a time limit for the counterparty to bring claims. +4. **Most favored nation** (`most_favored_nation`): If a third party gets better terms on the licensing or sale of the technology, goods or services in the contract, the buyer under this contract is entitled to those better terms. +5. **Right of first refusal, offer or negotiation** (`right_of_first_refusal`): One party has a right of first refusal, first offer or first negotiation to purchase, license, market or distribute equity, technology, assets, products or services. +6. **Insurance** (`insurance`): One party must maintain insurance for the benefit of the counterparty. +7. **Liquidated damages** (`liquidated_damages`): Either party can be awarded liquidated damages for breach, or a fee on termination of the contract (a termination fee). +8. **Source code escrow** (`source_code_escrow`): One party must deposit its source code with a third-party escrow agent for release to the counterparty on certain events such as bankruptcy or insolvency. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`governing_law`, `anti_assignment`, `cap_on_liability`, `most_favored_nation`, `right_of_first_refusal`, `insurance`, `liquidated_damages`, `source_code_escrow`). diff --git a/tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/solution/files/answer.json b/tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..181012d4adad456fa4a14aec37692d8b23a1c7e0 --- /dev/null +++ b/tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/solution/files/answer.json @@ -0,0 +1,10 @@ +{ + "governing_law": "Florida / New York", + "anti_assignment": "Yes", + "cap_on_liability": "Yes", + "most_favored_nation": "No", + "right_of_first_refusal": "Yes", + "insurance": "Yes", + "liquidated_damages": "No", + "source_code_escrow": "No" +} diff --git a/tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/solution/solve.sh b/tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/task.toml b/tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1d05110558bf2e2ad71ea8c91d3a73c94a31d366 --- /dev/null +++ b/tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "INTERNATIONALFASTFOODCORP_04_04_1997-EX-99-FRANCHISE AGREEMENT.PDF:governing_law,anti_assignment,cap_on_liability,most_favored_nation,right_of_first_refusal,insurance,liquidated_damages,source_code_escrow" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/tests/expected.json b/tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..87d7a3d2b2dd8642de7c9fb2eed5c1d028775ea9 --- /dev/null +++ b/tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/tests/expected.json @@ -0,0 +1,64 @@ +{ + "checks": [ + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "Florida / New York", + "accept": [ + "Florida / New York", + "Florida/New York" + ] + }, + { + "id": "anti_assignment", + "type": "answer", + "field": "anti_assignment", + "kind": "bool", + "value": true + }, + { + "id": "cap_on_liability", + "type": "answer", + "field": "cap_on_liability", + "kind": "bool", + "value": true + }, + { + "id": "most_favored_nation", + "type": "answer", + "field": "most_favored_nation", + "kind": "bool", + "value": false + }, + { + "id": "right_of_first_refusal", + "type": "answer", + "field": "right_of_first_refusal", + "kind": "bool", + "value": true + }, + { + "id": "insurance", + "type": "answer", + "field": "insurance", + "kind": "bool", + "value": true + }, + { + "id": "liquidated_damages", + "type": "answer", + "field": "liquidated_damages", + "kind": "bool", + "value": false + }, + { + "id": "source_code_escrow", + "type": "answer", + "field": "source_code_escrow", + "kind": "bool", + "value": false + } + ] +} diff --git a/tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/tests/grade.py b/tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/tests/test.sh b/tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/validation/openenv.json b/tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/environment/inputs/INTERSECTENT_INC_05_11_2020-EX-10.1-SUPPLY_AGREEMENT.pdf b/tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/environment/inputs/INTERSECTENT_INC_05_11_2020-EX-10.1-SUPPLY_AGREEMENT.pdf new file mode 100644 index 0000000000000000000000000000000000000000..fbca629db64ec7d8dcb4cb83ba110c5afbb003ed --- /dev/null +++ b/tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/environment/inputs/INTERSECTENT_INC_05_11_2020-EX-10.1-SUPPLY_AGREEMENT.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b69198b1a68092ce20b6b1aa48d80f34c99caecafdd00fa121610dcae55e7f6d +size 163456 diff --git a/tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/instruction.md b/tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..38a077a0eb1b7ade87ba6dcc04e141ad228a4e0f --- /dev/null +++ b/tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/instruction.md @@ -0,0 +1,21 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/INTERSECTENT_INC_05_11_2020-EX-10.1-SUPPLY_AGREEMENT.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Agreement date** (`agreement_date`): The date of the contract: the date it is dated or entered into, as stated in the document. +2. **Effective date** (`effective_date`): The date the contract becomes effective or its term commences. +3. **Change of control** (`change_of_control`): Does the agreement allow a company that acquires or merges with either party and does not wish to continue the relationship to make a contract buyout payment? +4. **Cap on liability** (`cap_on_liability`): The contract limits a party's liability for breach: a maximum recoverable amount, an exclusion of categories of damages (for example indirect, consequential or lost-profit damages), or a time limit for the counterparty to bring claims. +5. **Source code escrow** (`source_code_escrow`): One party must deposit its source code with a third-party escrow agent for release to the counterparty on certain events such as bankruptcy or insolvency. +6. **No-solicit of employees** (`no_solicit_of_employees`): A party is restricted from soliciting or hiring employees or contractors of the counterparty, during or after the contract. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`agreement_date`, `effective_date`, `change_of_control`, `cap_on_liability`, `source_code_escrow`, `no_solicit_of_employees`). diff --git a/tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/solution/files/answer.json b/tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..a3ecee82fc56fe59ae80c879e1a308d6817fe44f --- /dev/null +++ b/tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/solution/files/answer.json @@ -0,0 +1,8 @@ +{ + "agreement_date": "2020-01-20", + "effective_date": "2020-01-20", + "change_of_control": "Yes", + "cap_on_liability": "Yes", + "source_code_escrow": "No", + "no_solicit_of_employees": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/solution/solve.sh b/tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/task.toml b/tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1e1633ad81da61434734170f4106497ebe3fc778 --- /dev/null +++ b/tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "INTERSECTENT,INC_05_11_2020-EX-10.1-SUPPLY AGREEMENT.PDF:agreement_date,effective_date,change_of_control,cap_on_liability,source_code_escrow,no_solicit_of_employees" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/tests/expected.json b/tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..ff8c30b40a3666361d0c609dce840c4964b8642f --- /dev/null +++ b/tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/tests/expected.json @@ -0,0 +1,46 @@ +{ + "checks": [ + { + "id": "agreement_date", + "type": "answer", + "field": "agreement_date", + "kind": "date", + "value": "2020-01-20" + }, + { + "id": "effective_date", + "type": "answer", + "field": "effective_date", + "kind": "date", + "value": "2020-01-20" + }, + { + "id": "change_of_control", + "type": "answer", + "field": "change_of_control", + "kind": "bool", + "value": true + }, + { + "id": "cap_on_liability", + "type": "answer", + "field": "cap_on_liability", + "kind": "bool", + "value": true + }, + { + "id": "source_code_escrow", + "type": "answer", + "field": "source_code_escrow", + "kind": "bool", + "value": false + }, + { + "id": "no_solicit_of_employees", + "type": "answer", + "field": "no_solicit_of_employees", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/tests/grade.py b/tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/tests/test.sh b/tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/validation/openenv.json b/tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/environment/inputs/IOVANCEBIOTHERAPEUTICS_INC_08_03_2017-EX-10.1-STRATEGIC_ALLIANCE_AGREEMENT.pdf b/tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/environment/inputs/IOVANCEBIOTHERAPEUTICS_INC_08_03_2017-EX-10.1-STRATEGIC_ALLIANCE_AGREEMENT.pdf new file mode 100644 index 0000000000000000000000000000000000000000..504d9b614583a4a5c023c43d6c080527bfddba6b --- /dev/null +++ b/tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/environment/inputs/IOVANCEBIOTHERAPEUTICS_INC_08_03_2017-EX-10.1-STRATEGIC_ALLIANCE_AGREEMENT.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:79f8b3c2f8f0209d566d5021267cce43adfab7064e820d1cfa944f381dc9b0f6 +size 186508 diff --git a/tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/instruction.md b/tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..69d311df1c72e910722409e68a0461a19b59c0fd --- /dev/null +++ b/tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/instruction.md @@ -0,0 +1,23 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/IOVANCEBIOTHERAPEUTICS_INC_08_03_2017-EX-10.1-STRATEGIC_ALLIANCE_AGREEMENT.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Effective date** (`effective_date`): The date the contract becomes effective or its term commences. +2. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +3. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party. +4. **Cap on liability** (`cap_on_liability`): The contract limits a party's liability for breach: a maximum recoverable amount, an exclusion of categories of damages (for example indirect, consequential or lost-profit damages), or a time limit for the counterparty to bring claims. +5. **Most favored nation** (`most_favored_nation`): If a third party gets better terms on the licensing or sale of the technology, goods or services in the contract, the buyer under this contract is entitled to those better terms. +6. **IP ownership assignment** (`ip_ownership_assignment`): Intellectual property created by one party becomes the property of the counterparty, under the contract terms or on the occurrence of certain events. +7. **Right of first refusal, offer or negotiation** (`right_of_first_refusal`): One party has a right of first refusal, first offer or first negotiation to purchase, license, market or distribute equity, technology, assets, products or services. +8. **Non-disparagement** (`non_disparagement`): A party must not disparage the counterparty. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`effective_date`, `governing_law`, `anti_assignment`, `cap_on_liability`, `most_favored_nation`, `ip_ownership_assignment`, `right_of_first_refusal`, `non_disparagement`). diff --git a/tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/solution/files/answer.json b/tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..73ea753aa64eb9b6faf43e1337db0a81a33dd98d --- /dev/null +++ b/tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/solution/files/answer.json @@ -0,0 +1,10 @@ +{ + "effective_date": "2017-04-17", + "governing_law": "Texas", + "anti_assignment": "Yes", + "cap_on_liability": "Yes", + "most_favored_nation": "No", + "ip_ownership_assignment": "Yes", + "right_of_first_refusal": "No", + "non_disparagement": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/solution/solve.sh b/tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/task.toml b/tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7477559d273be4e07b7fc052d7abac36f4000616 --- /dev/null +++ b/tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "IOVANCEBIOTHERAPEUTICS,INC_08_03_2017-EX-10.1-STRATEGIC ALLIANCE AGREEMENT.PDF:effective_date,governing_law,anti_assignment,cap_on_liability,most_favored_nation,ip_ownership_assignment,right_of_first_refusal,non_disparagement" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/tests/expected.json b/tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..657139dec48d6b2398ae245b2ee079fc1fb903bb --- /dev/null +++ b/tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/tests/expected.json @@ -0,0 +1,66 @@ +{ + "checks": [ + { + "id": "effective_date", + "type": "answer", + "field": "effective_date", + "kind": "date", + "value": "2017-04-17" + }, + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "Texas", + "accept": [ + "Texas", + "State of Texas", + "Texas, USA", + "Texas, United States" + ] + }, + { + "id": "anti_assignment", + "type": "answer", + "field": "anti_assignment", + "kind": "bool", + "value": true + }, + { + "id": "cap_on_liability", + "type": "answer", + "field": "cap_on_liability", + "kind": "bool", + "value": true + }, + { + "id": "most_favored_nation", + "type": "answer", + "field": "most_favored_nation", + "kind": "bool", + "value": false + }, + { + "id": "ip_ownership_assignment", + "type": "answer", + "field": "ip_ownership_assignment", + "kind": "bool", + "value": true + }, + { + "id": "right_of_first_refusal", + "type": "answer", + "field": "right_of_first_refusal", + "kind": "bool", + "value": false + }, + { + "id": "non_disparagement", + "type": "answer", + "field": "non_disparagement", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/tests/grade.py b/tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/tests/test.sh b/tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/validation/openenv.json b/tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/environment/inputs/JINGWEIINTERNATIONALLTD_10_04_2007-EX-10.7-INTELLECTUAL_PROPERTY_AGREEMENT.pdf b/tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/environment/inputs/JINGWEIINTERNATIONALLTD_10_04_2007-EX-10.7-INTELLECTUAL_PROPERTY_AGREEMENT.pdf new file mode 100644 index 0000000000000000000000000000000000000000..7f2d26dd11a432245a0502e51cd0634c50dcac0d --- /dev/null +++ b/tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/environment/inputs/JINGWEIINTERNATIONALLTD_10_04_2007-EX-10.7-INTELLECTUAL_PROPERTY_AGREEMENT.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:83226499244bbc8261754af249560a56829f0504c983c65d8de7ba8f2f8d2c8a +size 152880 diff --git a/tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/instruction.md b/tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c5495d10f12d8a612416a825c476ec33749a71d4 --- /dev/null +++ b/tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/instruction.md @@ -0,0 +1,21 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/JINGWEIINTERNATIONALLTD_10_04_2007-EX-10.7-INTELLECTUAL_PROPERTY_AGREEMENT.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Agreement date** (`agreement_date`): The date of the contract: the date it is dated or entered into, as stated in the document. +2. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +3. **Change of control** (`change_of_control`): One party has the right to terminate, or consent or notice of the counterparty is required, if that party undergoes a change of control (a merger, stock sale, transfer of all or substantially all of its assets or business, or assignment by operation of law). +4. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party. +5. **Termination for convenience** (`termination_for_convenience`): A party can terminate the contract without cause, solely by giving notice and letting a waiting period expire. +6. **Source code escrow** (`source_code_escrow`): One party must deposit its source code with a third-party escrow agent for release to the counterparty on certain events such as bankruptcy or insolvency. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`agreement_date`, `governing_law`, `change_of_control`, `anti_assignment`, `termination_for_convenience`, `source_code_escrow`). diff --git a/tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/solution/files/answer.json b/tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..104ad0fe6c6e99bdacacc98e241da1b521f59fc5 --- /dev/null +++ b/tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/solution/files/answer.json @@ -0,0 +1,8 @@ +{ + "agreement_date": "2007-02-08", + "governing_law": "People's Republic of China", + "change_of_control": "No", + "anti_assignment": "Yes", + "termination_for_convenience": "Yes", + "source_code_escrow": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/solution/solve.sh b/tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/task.toml b/tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..68d896da8fad46ead5696b34ceabe4942e811354 --- /dev/null +++ b/tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "JINGWEIINTERNATIONALLTD_10_04_2007-EX-10.7-INTELLECTUAL PROPERTY AGREEMENT.PDF:agreement_date,governing_law,change_of_control,anti_assignment,termination_for_convenience,source_code_escrow" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/tests/expected.json b/tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..db9ed203938e2933c3ca9b3b151e013d074d6409 --- /dev/null +++ b/tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/tests/expected.json @@ -0,0 +1,52 @@ +{ + "checks": [ + { + "id": "agreement_date", + "type": "answer", + "field": "agreement_date", + "kind": "date", + "value": "2007-02-08" + }, + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "People's Republic of China", + "accept": [ + "People's Republic of China", + "China", + "PRC", + "the PRC" + ] + }, + { + "id": "change_of_control", + "type": "answer", + "field": "change_of_control", + "kind": "bool", + "value": false + }, + { + "id": "anti_assignment", + "type": "answer", + "field": "anti_assignment", + "kind": "bool", + "value": true + }, + { + "id": "termination_for_convenience", + "type": "answer", + "field": "termination_for_convenience", + "kind": "bool", + "value": true + }, + { + "id": "source_code_escrow", + "type": "answer", + "field": "source_code_escrow", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/tests/grade.py b/tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/tests/test.sh b/tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/validation/openenv.json b/tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/environment/inputs/LejuHoldingsLtd_20140121_DRS_on_F-1__EX-10.26_8473102_EX-10.26_Content_License_Agreement1.pdf b/tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/environment/inputs/LejuHoldingsLtd_20140121_DRS_on_F-1__EX-10.26_8473102_EX-10.26_Content_License_Agreement1.pdf new file mode 100644 index 0000000000000000000000000000000000000000..0d26efef2c16cdc4cedc4dd37b90812441a2b268 --- /dev/null +++ b/tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/environment/inputs/LejuHoldingsLtd_20140121_DRS_on_F-1__EX-10.26_8473102_EX-10.26_Content_License_Agreement1.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a062c0d4fdaa3213b6638704171de288dd6d885901d13c21359a86f7cb9df184 +size 224717 diff --git a/tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/instruction.md b/tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..229c43f76b78111f45da91c5ce15f7fe401d4773 --- /dev/null +++ b/tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/instruction.md @@ -0,0 +1,21 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/LejuHoldingsLtd_20140121_DRS_on_F-1__EX-10.26_8473102_EX-10.26_Content_License_Agreement1.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +2. **Change of control** (`change_of_control`): One party has the right to terminate, or consent or notice of the counterparty is required, if that party undergoes a change of control (a merger, stock sale, transfer of all or substantially all of its assets or business, or assignment by operation of law). +3. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party. +4. **Audit rights** (`audit_rights`): A party has the right to audit the books, records or physical locations of the counterparty to check compliance with the contract. +5. **Insurance** (`insurance`): One party must maintain insurance for the benefit of the counterparty. +6. **Minimum commitment** (`minimum_commitment`): One party must buy a minimum order size, amount or number of units per time period from the counterparty. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`governing_law`, `change_of_control`, `anti_assignment`, `audit_rights`, `insurance`, `minimum_commitment`). diff --git a/tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/solution/files/answer.json b/tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..1d0355f167a30b113c6e0345160319fc85166625 --- /dev/null +++ b/tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/solution/files/answer.json @@ -0,0 +1,8 @@ +{ + "governing_law": "People's Republic of China", + "change_of_control": "Yes", + "anti_assignment": "Yes", + "audit_rights": "No", + "insurance": "No", + "minimum_commitment": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/solution/solve.sh b/tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/task.toml b/tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fed8b27561499ec3a8dc17325aa8a502711e8ab4 --- /dev/null +++ b/tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "LejuHoldingsLtd_20140121_DRS (on F-1)_EX-10.26_8473102_EX-10.26_Content License Agreement1.pdf:governing_law,change_of_control,anti_assignment,audit_rights,insurance,minimum_commitment" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/tests/expected.json b/tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..8624d56f1e35aeccb99099b2ba2c9b1cd0290e64 --- /dev/null +++ b/tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/tests/expected.json @@ -0,0 +1,52 @@ +{ + "checks": [ + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "People's Republic of China", + "accept": [ + "People's Republic of China", + "China", + "PRC", + "the PRC" + ] + }, + { + "id": "change_of_control", + "type": "answer", + "field": "change_of_control", + "kind": "bool", + "value": true + }, + { + "id": "anti_assignment", + "type": "answer", + "field": "anti_assignment", + "kind": "bool", + "value": true + }, + { + "id": "audit_rights", + "type": "answer", + "field": "audit_rights", + "kind": "bool", + "value": false + }, + { + "id": "insurance", + "type": "answer", + "field": "insurance", + "kind": "bool", + "value": false + }, + { + "id": "minimum_commitment", + "type": "answer", + "field": "minimum_commitment", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/tests/grade.py b/tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/tests/test.sh b/tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/validation/openenv.json b/tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018/environment/inputs/LinkPlusCorp_20050802_8-K_EX-10_3240252_EX-10_Affiliate_Agreement.pdf b/tasks/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018/environment/inputs/LinkPlusCorp_20050802_8-K_EX-10_3240252_EX-10_Affiliate_Agreement.pdf new file mode 100644 index 0000000000000000000000000000000000000000..7165417fe9c005496784f157a9cda54de26e5620 Binary files /dev/null and b/tasks/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018/environment/inputs/LinkPlusCorp_20050802_8-K_EX-10_3240252_EX-10_Affiliate_Agreement.pdf differ diff --git a/tasks/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018/instruction.md b/tasks/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6819c216d90e4ac73a2faabb63df17a849abda30 --- /dev/null +++ b/tasks/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018/instruction.md @@ -0,0 +1,22 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/LinkPlusCorp_20050802_8-K_EX-10_3240252_EX-10_Affiliate_Agreement.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Effective date** (`effective_date`): The date the contract becomes effective or its term commences. +2. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party. +3. **Audit rights** (`audit_rights`): A party has the right to audit the books, records or physical locations of the counterparty to check compliance with the contract. +4. **Right of first refusal, offer or negotiation** (`right_of_first_refusal`): One party has a right of first refusal, first offer or first negotiation to purchase, license, market or distribute equity, technology, assets, products or services. +5. **Insurance** (`insurance`): One party must maintain insurance for the benefit of the counterparty. +6. **Minimum commitment** (`minimum_commitment`): One party must buy a minimum order size, amount or number of units per time period from the counterparty. +7. **Non-disparagement** (`non_disparagement`): A party must not disparage the counterparty. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`effective_date`, `anti_assignment`, `audit_rights`, `right_of_first_refusal`, `insurance`, `minimum_commitment`, `non_disparagement`). diff --git a/tasks/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018/solution/files/answer.json b/tasks/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..c0a7988bb4bc3422cb0d25486e9167b2dd88b0ea --- /dev/null +++ b/tasks/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018/solution/files/answer.json @@ -0,0 +1,9 @@ +{ + "effective_date": "2005-07-15", + "anti_assignment": "Yes", + "audit_rights": "Yes", + "right_of_first_refusal": "Yes", + "insurance": "No", + "minimum_commitment": "No", + "non_disparagement": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018/solution/solve.sh b/tasks/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018/task.toml b/tasks/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..eb0de127daa7fd260874313d371a5254a646a8c1 --- /dev/null +++ b/tasks/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "LinkPlusCorp_20050802_8-K_EX-10_3240252_EX-10_Affiliate Agreement.pdf:effective_date,anti_assignment,audit_rights,right_of_first_refusal,insurance,minimum_commitment,non_disparagement" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018/tests/expected.json b/tasks/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..2f3a4cc1a66ff6ee351234eaa97c7389abe4c4c3 --- /dev/null +++ b/tasks/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018/tests/expected.json @@ -0,0 +1,53 @@ +{ + "checks": [ + { + "id": "effective_date", + "type": "answer", + "field": "effective_date", + "kind": "date", + "value": "2005-07-15" + }, + { + "id": "anti_assignment", + "type": "answer", + "field": "anti_assignment", + "kind": "bool", + "value": true + }, + { + "id": "audit_rights", + "type": "answer", + "field": "audit_rights", + "kind": "bool", + "value": true + }, + { + "id": "right_of_first_refusal", + "type": "answer", + "field": "right_of_first_refusal", + "kind": "bool", + "value": true + }, + { + "id": "insurance", + "type": "answer", + "field": "insurance", + "kind": "bool", + "value": false + }, + { + "id": "minimum_commitment", + "type": "answer", + "field": "minimum_commitment", + "kind": "bool", + "value": false + }, + { + "id": "non_disparagement", + "type": "answer", + "field": "non_disparagement", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018/tests/grade.py b/tasks/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..f9c9197d521d2bb8a537a6467bf30c433b7bcd26 --- /dev/null +++ b/tasks/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018/tests/grade.py @@ -0,0 +1,295 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def same_cell(a, b): + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + if not same_cell(want[sheet][name].value, got[sheet][name].value): + return False, f"{sheet}!{name}: want {want[sheet][name].value!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + ok = number_ok(got, want, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) if got is not None else False + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018/tests/test.sh b/tasks/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018/validation/openenv.json b/tasks/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-linkpluscorp-20050802-8-k-ex-10-3240252--23828018/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/environment/inputs/LOYALTYPOINTINC_11_16_2004-EX-10.2-RESELLER_AGREEMENT.pdf b/tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/environment/inputs/LOYALTYPOINTINC_11_16_2004-EX-10.2-RESELLER_AGREEMENT.pdf new file mode 100644 index 0000000000000000000000000000000000000000..c12d90681e530917040c8149fe4e7e59ba0c7961 --- /dev/null +++ b/tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/environment/inputs/LOYALTYPOINTINC_11_16_2004-EX-10.2-RESELLER_AGREEMENT.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3dfe8e61fc1cf051bc2646c19099b51d3c780070c8f2b69b0c53ae53db7bedcb +size 132047 diff --git a/tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/instruction.md b/tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..42b0792d6e237206090a696329b7424507683ed4 --- /dev/null +++ b/tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/instruction.md @@ -0,0 +1,22 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/LOYALTYPOINTINC_11_16_2004-EX-10.2-RESELLER_AGREEMENT.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Expiration date** (`expiration_date`): The date the initial term ends, before any renewal. +2. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +3. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party. +4. **Cap on liability** (`cap_on_liability`): The contract limits a party's liability for breach: a maximum recoverable amount, an exclusion of categories of damages (for example indirect, consequential or lost-profit damages), or a time limit for the counterparty to bring claims. +5. **Right of first refusal, offer or negotiation** (`right_of_first_refusal`): One party has a right of first refusal, first offer or first negotiation to purchase, license, market or distribute equity, technology, assets, products or services. +6. **Minimum commitment** (`minimum_commitment`): One party must buy a minimum order size, amount or number of units per time period from the counterparty. +7. **Source code escrow** (`source_code_escrow`): One party must deposit its source code with a third-party escrow agent for release to the counterparty on certain events such as bankruptcy or insolvency. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`expiration_date`, `governing_law`, `anti_assignment`, `cap_on_liability`, `right_of_first_refusal`, `minimum_commitment`, `source_code_escrow`). diff --git a/tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/solution/files/answer.json b/tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..4b3e881744e3a0691bbd4196c1f2c3690f13824b --- /dev/null +++ b/tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/solution/files/answer.json @@ -0,0 +1,9 @@ +{ + "expiration_date": "2009-07-31", + "governing_law": "Missouri", + "anti_assignment": "Yes", + "cap_on_liability": "Yes", + "right_of_first_refusal": "No", + "minimum_commitment": "Yes", + "source_code_escrow": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/solution/solve.sh b/tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/task.toml b/tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5896beef40a7b4b8c6f4381ecf303246395c0ce9 --- /dev/null +++ b/tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "LOYALTYPOINTINC_11_16_2004-EX-10.2-RESELLER AGREEMENT.PDF:expiration_date,governing_law,anti_assignment,cap_on_liability,right_of_first_refusal,minimum_commitment,source_code_escrow" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/tests/expected.json b/tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..b0ae16648abca14258dc9db601e9a3fb767abd3b --- /dev/null +++ b/tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/tests/expected.json @@ -0,0 +1,59 @@ +{ + "checks": [ + { + "id": "expiration_date", + "type": "answer", + "field": "expiration_date", + "kind": "date", + "value": "2009-07-31" + }, + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "Missouri", + "accept": [ + "Missouri", + "State of Missouri", + "Missouri, USA", + "Missouri, United States" + ] + }, + { + "id": "anti_assignment", + "type": "answer", + "field": "anti_assignment", + "kind": "bool", + "value": true + }, + { + "id": "cap_on_liability", + "type": "answer", + "field": "cap_on_liability", + "kind": "bool", + "value": true + }, + { + "id": "right_of_first_refusal", + "type": "answer", + "field": "right_of_first_refusal", + "kind": "bool", + "value": false + }, + { + "id": "minimum_commitment", + "type": "answer", + "field": "minimum_commitment", + "kind": "bool", + "value": true + }, + { + "id": "source_code_escrow", + "type": "answer", + "field": "source_code_escrow", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/tests/grade.py b/tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/tests/test.sh b/tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/validation/openenv.json b/tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091/environment/inputs/LUCIDINC_04_15_2011-EX-10.9-DISTRIBUTOR_AGREEMENT.pdf b/tasks/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091/environment/inputs/LUCIDINC_04_15_2011-EX-10.9-DISTRIBUTOR_AGREEMENT.pdf new file mode 100644 index 0000000000000000000000000000000000000000..1242c2f9376d7c9f248132f6eaff7e69c8af3269 Binary files /dev/null and b/tasks/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091/environment/inputs/LUCIDINC_04_15_2011-EX-10.9-DISTRIBUTOR_AGREEMENT.pdf differ diff --git a/tasks/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091/instruction.md b/tasks/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..16f6e15fa4ac37c66653662065b947dee9fbcc84 --- /dev/null +++ b/tasks/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091/instruction.md @@ -0,0 +1,22 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/LUCIDINC_04_15_2011-EX-10.9-DISTRIBUTOR_AGREEMENT.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +2. **Cap on liability** (`cap_on_liability`): The contract limits a party's liability for breach: a maximum recoverable amount, an exclusion of categories of damages (for example indirect, consequential or lost-profit damages), or a time limit for the counterparty to bring claims. +3. **Exclusivity** (`exclusivity`): There is an exclusive dealing commitment with the counterparty: a commitment to procure all requirements from one party, or a prohibition on licensing or selling to third parties or on working with other parties, during or after the contract. An exclusive license, appointment or territory granted to the counterparty counts. +4. **Right of first refusal, offer or negotiation** (`right_of_first_refusal`): One party has a right of first refusal, first offer or first negotiation to purchase, license, market or distribute equity, technology, assets, products or services. +5. **Insurance** (`insurance`): One party must maintain insurance for the benefit of the counterparty. +6. **Minimum commitment** (`minimum_commitment`): One party must buy a minimum order size, amount or number of units per time period from the counterparty. +7. **Source code escrow** (`source_code_escrow`): One party must deposit its source code with a third-party escrow agent for release to the counterparty on certain events such as bankruptcy or insolvency. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`governing_law`, `cap_on_liability`, `exclusivity`, `right_of_first_refusal`, `insurance`, `minimum_commitment`, `source_code_escrow`). diff --git a/tasks/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091/solution/files/answer.json b/tasks/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..da8c3f51d659aaf124f0894a64132ae2a644791c --- /dev/null +++ b/tasks/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091/solution/files/answer.json @@ -0,0 +1,9 @@ +{ + "governing_law": "New York", + "cap_on_liability": "Yes", + "exclusivity": "Yes", + "right_of_first_refusal": "No", + "insurance": "No", + "minimum_commitment": "Yes", + "source_code_escrow": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091/solution/solve.sh b/tasks/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091/task.toml b/tasks/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..973746aca6c5ecda2d94396f1c5c06573531dfd5 --- /dev/null +++ b/tasks/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "LUCIDINC_04_15_2011-EX-10.9-DISTRIBUTOR AGREEMENT.PDF:governing_law,cap_on_liability,exclusivity,right_of_first_refusal,insurance,minimum_commitment,source_code_escrow" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091/tests/expected.json b/tasks/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..7e5c29189f84ae8fe734c16e4119997bac022de9 --- /dev/null +++ b/tasks/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091/tests/expected.json @@ -0,0 +1,59 @@ +{ + "checks": [ + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "New York", + "accept": [ + "New York", + "State of New York", + "New York, USA", + "New York, United States" + ] + }, + { + "id": "cap_on_liability", + "type": "answer", + "field": "cap_on_liability", + "kind": "bool", + "value": true + }, + { + "id": "exclusivity", + "type": "answer", + "field": "exclusivity", + "kind": "bool", + "value": true + }, + { + "id": "right_of_first_refusal", + "type": "answer", + "field": "right_of_first_refusal", + "kind": "bool", + "value": false + }, + { + "id": "insurance", + "type": "answer", + "field": "insurance", + "kind": "bool", + "value": false + }, + { + "id": "minimum_commitment", + "type": "answer", + "field": "minimum_commitment", + "kind": "bool", + "value": true + }, + { + "id": "source_code_escrow", + "type": "answer", + "field": "source_code_escrow", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091/tests/grade.py b/tasks/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091/tests/test.sh b/tasks/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091/validation/openenv.json b/tasks/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-lucidinc-04-15-2011-ex-10-9-distributor--7bfe0091/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/environment/inputs/Magenta_Therapeutics_Inc._-_Master_Development_and_Manufacturing_Agreement.pdf b/tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/environment/inputs/Magenta_Therapeutics_Inc._-_Master_Development_and_Manufacturing_Agreement.pdf new file mode 100644 index 0000000000000000000000000000000000000000..486204b458a568487d9fb0331c8c8a10019da23d --- /dev/null +++ b/tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/environment/inputs/Magenta_Therapeutics_Inc._-_Master_Development_and_Manufacturing_Agreement.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ed2310df56a88bab8c743ec2df99abac8acf1120c51a82f9127eb8fe79fdba8a +size 191255 diff --git a/tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/instruction.md b/tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..747689cebd8146e72de1989679833f0f6d2d684d --- /dev/null +++ b/tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/instruction.md @@ -0,0 +1,21 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/Magenta_Therapeutics_Inc._-_Master_Development_and_Manufacturing_Agreement.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Effective date** (`effective_date`): The date the contract becomes effective or its term commences. +2. **Termination for convenience** (`termination_for_convenience`): A party can terminate the contract without cause, solely by giving notice and letting a waiting period expire. +3. **Most favored nation** (`most_favored_nation`): If a third party gets better terms on the licensing or sale of the technology, goods or services in the contract, the buyer under this contract is entitled to those better terms. +4. **Right of first refusal, offer or negotiation** (`right_of_first_refusal`): One party has a right of first refusal, first offer or first negotiation to purchase, license, market or distribute equity, technology, assets, products or services. +5. **Non-disparagement** (`non_disparagement`): A party must not disparage the counterparty. +6. **License grant** (`license_grant`): One party grants a license to its counterparty. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`effective_date`, `termination_for_convenience`, `most_favored_nation`, `right_of_first_refusal`, `non_disparagement`, `license_grant`). diff --git a/tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/solution/files/answer.json b/tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..3b854cbef24e2c4e21a38e59129b5740d47979b4 --- /dev/null +++ b/tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/solution/files/answer.json @@ -0,0 +1,8 @@ +{ + "effective_date": "2018-02-13", + "termination_for_convenience": "Yes", + "most_favored_nation": "No", + "right_of_first_refusal": "No", + "non_disparagement": "No", + "license_grant": "Yes" +} \ No newline at end of file diff --git a/tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/solution/solve.sh b/tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/task.toml b/tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..deddc14babf9142b8525793da05b2b01cd0b26b2 --- /dev/null +++ b/tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "Magenta Therapeutics, Inc. - Master Development and Manufacturing Agreement.PDF:effective_date,termination_for_convenience,most_favored_nation,right_of_first_refusal,non_disparagement,license_grant" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/tests/expected.json b/tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..3dcd34e173bd3f678b638cc43dcbbf642b7fdaf0 --- /dev/null +++ b/tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/tests/expected.json @@ -0,0 +1,46 @@ +{ + "checks": [ + { + "id": "effective_date", + "type": "answer", + "field": "effective_date", + "kind": "date", + "value": "2018-02-13" + }, + { + "id": "termination_for_convenience", + "type": "answer", + "field": "termination_for_convenience", + "kind": "bool", + "value": true + }, + { + "id": "most_favored_nation", + "type": "answer", + "field": "most_favored_nation", + "kind": "bool", + "value": false + }, + { + "id": "right_of_first_refusal", + "type": "answer", + "field": "right_of_first_refusal", + "kind": "bool", + "value": false + }, + { + "id": "non_disparagement", + "type": "answer", + "field": "non_disparagement", + "kind": "bool", + "value": false + }, + { + "id": "license_grant", + "type": "answer", + "field": "license_grant", + "kind": "bool", + "value": true + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/tests/grade.py b/tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/tests/test.sh b/tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/validation/openenv.json b/tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f/environment/inputs/MANAKOASERVICESCORP_11_21_2007-EX-7.5-STRATEGIC_ALLIANCE_AGREEMENT.pdf b/tasks/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f/environment/inputs/MANAKOASERVICESCORP_11_21_2007-EX-7.5-STRATEGIC_ALLIANCE_AGREEMENT.pdf new file mode 100644 index 0000000000000000000000000000000000000000..41874c49659e28a72f3ae236b260bacb9c934471 Binary files /dev/null and b/tasks/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f/environment/inputs/MANAKOASERVICESCORP_11_21_2007-EX-7.5-STRATEGIC_ALLIANCE_AGREEMENT.pdf differ diff --git a/tasks/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f/instruction.md b/tasks/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..170db63f03f4cff67978d815f7caf457ce5796bb --- /dev/null +++ b/tasks/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f/instruction.md @@ -0,0 +1,22 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/MANAKOASERVICESCORP_11_21_2007-EX-7.5-STRATEGIC_ALLIANCE_AGREEMENT.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Agreement date** (`agreement_date`): The date of the contract: the date it is dated or entered into, as stated in the document. +2. **Change of control** (`change_of_control`): One party has the right to terminate, or consent or notice of the counterparty is required, if that party undergoes a change of control (a merger, stock sale, transfer of all or substantially all of its assets or business, or assignment by operation of law). +3. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party. +4. **Termination for convenience** (`termination_for_convenience`): A party can terminate the contract without cause, solely by giving notice and letting a waiting period expire. +5. **Minimum commitment** (`minimum_commitment`): One party must buy a minimum order size, amount or number of units per time period from the counterparty. +6. **No-solicit of employees** (`no_solicit_of_employees`): A party is restricted from soliciting or hiring employees or contractors of the counterparty, during or after the contract. +7. **Non-disparagement** (`non_disparagement`): A party must not disparage the counterparty. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`agreement_date`, `change_of_control`, `anti_assignment`, `termination_for_convenience`, `minimum_commitment`, `no_solicit_of_employees`, `non_disparagement`). diff --git a/tasks/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f/solution/files/answer.json b/tasks/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..2aa5347631dba7dd4bb81e7eabd80ba2c27ca667 --- /dev/null +++ b/tasks/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f/solution/files/answer.json @@ -0,0 +1,9 @@ +{ + "agreement_date": "2006-06-14", + "change_of_control": "No", + "anti_assignment": "Yes", + "termination_for_convenience": "Yes", + "minimum_commitment": "No", + "no_solicit_of_employees": "Yes", + "non_disparagement": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f/solution/solve.sh b/tasks/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f/task.toml b/tasks/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ce8853b5332895565d5906b24fbbebdcdba2454f --- /dev/null +++ b/tasks/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "MANAKOASERVICESCORP_11_21_2007-EX-7.5-STRATEGIC ALLIANCE AGREEMENT.PDF:agreement_date,change_of_control,anti_assignment,termination_for_convenience,minimum_commitment,no_solicit_of_employees,non_disparagement" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f/tests/expected.json b/tasks/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..fe848a76fdb01c1b628aba83654d998708b7fbbc --- /dev/null +++ b/tasks/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f/tests/expected.json @@ -0,0 +1,53 @@ +{ + "checks": [ + { + "id": "agreement_date", + "type": "answer", + "field": "agreement_date", + "kind": "date", + "value": "2006-06-14" + }, + { + "id": "change_of_control", + "type": "answer", + "field": "change_of_control", + "kind": "bool", + "value": false + }, + { + "id": "anti_assignment", + "type": "answer", + "field": "anti_assignment", + "kind": "bool", + "value": true + }, + { + "id": "termination_for_convenience", + "type": "answer", + "field": "termination_for_convenience", + "kind": "bool", + "value": true + }, + { + "id": "minimum_commitment", + "type": "answer", + "field": "minimum_commitment", + "kind": "bool", + "value": false + }, + { + "id": "no_solicit_of_employees", + "type": "answer", + "field": "no_solicit_of_employees", + "kind": "bool", + "value": true + }, + { + "id": "non_disparagement", + "type": "answer", + "field": "non_disparagement", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f/tests/grade.py b/tasks/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f/tests/test.sh b/tasks/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f/validation/openenv.json b/tasks/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-manakoaservicescorp-11-21-2007-ex-7-5-st-28cc4e3f/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2/environment/inputs/MJBIOTECH_INC_12_06_2018-EX-99.01-JOINT_VENTURE_AGREEMENT.pdf b/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2/environment/inputs/MJBIOTECH_INC_12_06_2018-EX-99.01-JOINT_VENTURE_AGREEMENT.pdf new file mode 100644 index 0000000000000000000000000000000000000000..590df0c9e93dc5a798ee34033be122d75fe17d64 Binary files /dev/null and b/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2/environment/inputs/MJBIOTECH_INC_12_06_2018-EX-99.01-JOINT_VENTURE_AGREEMENT.pdf differ diff --git a/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2/instruction.md b/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..960d375338d761638dff0405ef3828ddd5af730f --- /dev/null +++ b/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2/instruction.md @@ -0,0 +1,22 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/MJBIOTECH_INC_12_06_2018-EX-99.01-JOINT_VENTURE_AGREEMENT.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Agreement date** (`agreement_date`): The date of the contract: the date it is dated or entered into, as stated in the document. +2. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +3. **Termination for convenience** (`termination_for_convenience`): A party can terminate the contract without cause, solely by giving notice and letting a waiting period expire. +4. **Most favored nation** (`most_favored_nation`): If a third party gets better terms on the licensing or sale of the technology, goods or services in the contract, the buyer under this contract is entitled to those better terms. +5. **Insurance** (`insurance`): One party must maintain insurance for the benefit of the counterparty. +6. **No-solicit of employees** (`no_solicit_of_employees`): A party is restricted from soliciting or hiring employees or contractors of the counterparty, during or after the contract. +7. **License grant** (`license_grant`): One party grants a license to its counterparty. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`agreement_date`, `governing_law`, `termination_for_convenience`, `most_favored_nation`, `insurance`, `no_solicit_of_employees`, `license_grant`). diff --git a/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2/solution/files/answer.json b/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..1b96d807a39d6bdd1333ca49c7aa51eb577d99a5 --- /dev/null +++ b/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2/solution/files/answer.json @@ -0,0 +1,9 @@ +{ + "agreement_date": "2018-11-27", + "governing_law": "Florida", + "termination_for_convenience": "Yes", + "most_favored_nation": "No", + "insurance": false, + "no_solicit_of_employees": "No", + "license_grant": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2/solution/solve.sh b/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2/task.toml b/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..794d476d3e365dfa32f88ccda4e4b4eac476eb3a --- /dev/null +++ b/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2/task.toml @@ -0,0 +1,50 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "MJBIOTECH,INC_12_06_2018-EX-99.01-JOINT VENTURE AGREEMENT.PDF:agreement_date,governing_law,termination_for_convenience,most_favored_nation,audit_rights,insurance,no_solicit_of_employees,license_grant" +task_kind = "single-contract-checklist" + +[metadata.apex_gap.repair] +fixes = "{\"insurance\": {\"action\": \"correct\", \"reason\": \"The only insurance clause (s.59) says the Joint Venture 'may acquire insurance' for participants, a permission rather than a duty to maintain insurance for the counterparty.\", \"value\": false}}" + +[metadata.apex_gap.rewrite] +change = "{\"add_conventions\": [], \"correct\": {}, \"evidence\": \"runs/apex-knowledge/task-supply/key-verification/decisions/cuad.json\", \"from\": \"runs/apex-knowledge/wave1/cuad/repair/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1\", \"reason\": \"audit_rights: adjudicated rewording not used, question removed: definition widened to a joint venture's books, to fit this contract's clause\", \"remove\": [\"audit_rights\"], \"rewrite\": {}, \"v1_task_id\": \"cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1\"}" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2/tests/expected.json b/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..f9682f713976853200ab912d4a1c3fc5a7dfee31 --- /dev/null +++ b/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2/tests/expected.json @@ -0,0 +1,59 @@ +{ + "checks": [ + { + "id": "agreement_date", + "type": "answer", + "field": "agreement_date", + "kind": "date", + "value": "2018-11-27" + }, + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "Florida", + "accept": [ + "Florida", + "State of Florida", + "Florida, USA", + "Florida, United States" + ] + }, + { + "id": "termination_for_convenience", + "type": "answer", + "field": "termination_for_convenience", + "kind": "bool", + "value": true + }, + { + "id": "most_favored_nation", + "type": "answer", + "field": "most_favored_nation", + "kind": "bool", + "value": false + }, + { + "id": "insurance", + "type": "answer", + "field": "insurance", + "kind": "bool", + "value": false + }, + { + "id": "no_solicit_of_employees", + "type": "answer", + "field": "no_solicit_of_employees", + "kind": "bool", + "value": false + }, + { + "id": "license_grant", + "type": "answer", + "field": "license_grant", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2/tests/grade.py b/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2/tests/test.sh b/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2/validation/openenv.json b/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-mjbiotech-inc-12-06-2018-ex-99-01-joint--3d6458f1-v2/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2/environment/inputs/NEOMEDIATECHNOLOGIESINC_12_15_2005-EX-16.1-DISTRIBUTOR_AGREEMENT.pdf b/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2/environment/inputs/NEOMEDIATECHNOLOGIESINC_12_15_2005-EX-16.1-DISTRIBUTOR_AGREEMENT.pdf new file mode 100644 index 0000000000000000000000000000000000000000..ee572c002ea9035f1d9182d04e84b339769b41f8 Binary files /dev/null and b/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2/environment/inputs/NEOMEDIATECHNOLOGIESINC_12_15_2005-EX-16.1-DISTRIBUTOR_AGREEMENT.pdf differ diff --git a/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2/instruction.md b/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..06bd96832b8959e08663a9910e7c3be30a4b8a2e --- /dev/null +++ b/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2/instruction.md @@ -0,0 +1,21 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/NEOMEDIATECHNOLOGIESINC_12_15_2005-EX-16.1-DISTRIBUTOR_AGREEMENT.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Expiration date** (`expiration_date`): The date the initial term ends, before any renewal. +2. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +3. **Exclusivity** (`exclusivity`): There is an exclusive dealing commitment with the counterparty: a commitment to procure all requirements from one party, or a prohibition on licensing or selling to third parties or on working with other parties, during or after the contract. An exclusive license, appointment or territory granted to the counterparty counts. +4. **Most favored nation** (`most_favored_nation`): If a third party gets better terms on the licensing or sale of the technology, goods or services in the contract, the buyer under this contract is entitled to those better terms. +5. **Right of first refusal, offer or negotiation** (`right_of_first_refusal`): One party has a right of first refusal, first offer or first negotiation to purchase, license, market or distribute equity, technology, assets, products or services. +6. **Source code escrow** (`source_code_escrow`): One party must deposit its source code with a third-party escrow agent for release to the counterparty on certain events such as bankruptcy or insolvency. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`expiration_date`, `governing_law`, `exclusivity`, `most_favored_nation`, `right_of_first_refusal`, `source_code_escrow`). diff --git a/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2/solution/files/answer.json b/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..abeb56e4a231ca80d24121aa6f4a28b485aa106e --- /dev/null +++ b/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2/solution/files/answer.json @@ -0,0 +1,8 @@ +{ + "expiration_date": "2006-12-31", + "governing_law": "People's Republic of China", + "exclusivity": "Yes", + "most_favored_nation": "No", + "right_of_first_refusal": "No", + "source_code_escrow": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2/solution/solve.sh b/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2/task.toml b/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..502139a8771d40197852242dbba34b0e4410c17d --- /dev/null +++ b/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2/task.toml @@ -0,0 +1,50 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "NEOMEDIATECHNOLOGIESINC_12_15_2005-EX-16.1-DISTRIBUTOR AGREEMENT.PDF:expiration_date,governing_law,anti_assignment,exclusivity,most_favored_nation,right_of_first_refusal,source_code_escrow" +task_kind = "single-contract-checklist" + +[metadata.apex_gap.repair] +fixes = "{\"anti_assignment\": {\"action\": \"drop\", \"reason\": \"The agreement has no clause on assigning the contract, and Recital B says the Distributor title 'will be automatically switched to the WFOE' once that subsidiary exists. The only 'assign' terms are the section 10.1 grant of a 'nonassignable and nontransferable right to use the PPG Trademarks', a non-transferable license term with no consent or notice requirement, and the section 19.2(iii) termination trigger where Distributor 'assigns or attempts to assign its business assets for the benefit of creditors', an insolvency event. Whether a non-assignable licence counts as a restriction on assignment depends on the reader, so the label is not settled.\"}}" + +[metadata.apex_gap.rewrite] +change = "{\"add_conventions\": [], \"correct\": {}, \"evidence\": \"runs/apex-knowledge/task-supply/key-verification/decisions/cuad.json\", \"from\": \"runs/apex-knowledge/wave1/cuad/repair-2/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5\", \"reason\": \"anti_assignment: asked but no check grades it (an earlier repair dropped the check)\", \"remove\": [\"anti_assignment\"], \"rewrite\": {}, \"v1_task_id\": \"cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5\"}" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2/tests/expected.json b/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..c1d01dd10948934e6e9a31bde139b78be0d5b3c8 --- /dev/null +++ b/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2/tests/expected.json @@ -0,0 +1,52 @@ +{ + "checks": [ + { + "id": "expiration_date", + "type": "answer", + "field": "expiration_date", + "kind": "date", + "value": "2006-12-31" + }, + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "People's Republic of China", + "accept": [ + "People's Republic of China", + "China", + "PRC", + "the PRC" + ] + }, + { + "id": "exclusivity", + "type": "answer", + "field": "exclusivity", + "kind": "bool", + "value": true + }, + { + "id": "most_favored_nation", + "type": "answer", + "field": "most_favored_nation", + "kind": "bool", + "value": false + }, + { + "id": "right_of_first_refusal", + "type": "answer", + "field": "right_of_first_refusal", + "kind": "bool", + "value": false + }, + { + "id": "source_code_escrow", + "type": "answer", + "field": "source_code_escrow", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2/tests/grade.py b/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2/tests/test.sh b/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2/validation/openenv.json b/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-neomediatechnologiesinc-12-15-2005-ex-16-06544ab5-v2/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/environment/inputs/OFGBANCORP_03_28_2007-EX-10.23-OUTSOURCING_AGREEMENT.pdf b/tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/environment/inputs/OFGBANCORP_03_28_2007-EX-10.23-OUTSOURCING_AGREEMENT.pdf new file mode 100644 index 0000000000000000000000000000000000000000..50f6fd82a3f7a4df11ea434ff1ea77767d18302b --- /dev/null +++ b/tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/environment/inputs/OFGBANCORP_03_28_2007-EX-10.23-OUTSOURCING_AGREEMENT.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a42e82a22b576b402cda7a519fbb485b4ca0fc800d02b87a9e1f9d4871d708b5 +size 291223 diff --git a/tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/instruction.md b/tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..920c5a2875d3e9ee8123c9fa9ce4d5e4a5e2a9dd --- /dev/null +++ b/tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/instruction.md @@ -0,0 +1,23 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/OFGBANCORP_03_28_2007-EX-10.23-OUTSOURCING_AGREEMENT.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Effective date** (`effective_date`): The date the contract becomes effective or its term commences. +2. **Cap on liability** (`cap_on_liability`): The contract limits a party's liability for breach: a maximum recoverable amount, an exclusion of categories of damages (for example indirect, consequential or lost-profit damages), or a time limit for the counterparty to bring claims. +3. **Termination for convenience** (`termination_for_convenience`): A party can terminate the contract without cause, solely by giving notice and letting a waiting period expire. +4. **Most favored nation** (`most_favored_nation`): If a third party gets better terms on the licensing or sale of the technology, goods or services in the contract, the buyer under this contract is entitled to those better terms. +5. **Right of first refusal, offer or negotiation** (`right_of_first_refusal`): One party has a right of first refusal, first offer or first negotiation to purchase, license, market or distribute equity, technology, assets, products or services. +6. **No-solicit of employees** (`no_solicit_of_employees`): A party is restricted from soliciting or hiring employees or contractors of the counterparty, during or after the contract. +7. **Non-disparagement** (`non_disparagement`): A party must not disparage the counterparty. +8. **License grant** (`license_grant`): One party grants a license to its counterparty. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`effective_date`, `cap_on_liability`, `termination_for_convenience`, `most_favored_nation`, `right_of_first_refusal`, `no_solicit_of_employees`, `non_disparagement`, `license_grant`). diff --git a/tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/solution/files/answer.json b/tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..04d9ca5b61f8b7b1c1d10e1eaf6f04f455f549c4 --- /dev/null +++ b/tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/solution/files/answer.json @@ -0,0 +1,10 @@ +{ + "effective_date": "2007-01-26", + "cap_on_liability": "Yes", + "termination_for_convenience": "Yes", + "most_favored_nation": "No", + "right_of_first_refusal": "No", + "no_solicit_of_employees": "Yes", + "non_disparagement": "No", + "license_grant": "Yes" +} \ No newline at end of file diff --git a/tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/solution/solve.sh b/tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/task.toml b/tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..478ce0436f0075c8ec69d071de9be1cae3169c1d --- /dev/null +++ b/tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "OFGBANCORP_03_28_2007-EX-10.23-OUTSOURCING AGREEMENT.PDF:effective_date,cap_on_liability,termination_for_convenience,most_favored_nation,right_of_first_refusal,no_solicit_of_employees,non_disparagement,license_grant" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/tests/expected.json b/tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..de61bbf4c64513a9d4657b8abd80b9b9c46aa045 --- /dev/null +++ b/tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/tests/expected.json @@ -0,0 +1,60 @@ +{ + "checks": [ + { + "id": "effective_date", + "type": "answer", + "field": "effective_date", + "kind": "date", + "value": "2007-01-26" + }, + { + "id": "cap_on_liability", + "type": "answer", + "field": "cap_on_liability", + "kind": "bool", + "value": true + }, + { + "id": "termination_for_convenience", + "type": "answer", + "field": "termination_for_convenience", + "kind": "bool", + "value": true + }, + { + "id": "most_favored_nation", + "type": "answer", + "field": "most_favored_nation", + "kind": "bool", + "value": false + }, + { + "id": "right_of_first_refusal", + "type": "answer", + "field": "right_of_first_refusal", + "kind": "bool", + "value": false + }, + { + "id": "no_solicit_of_employees", + "type": "answer", + "field": "no_solicit_of_employees", + "kind": "bool", + "value": true + }, + { + "id": "non_disparagement", + "type": "answer", + "field": "non_disparagement", + "kind": "bool", + "value": false + }, + { + "id": "license_grant", + "type": "answer", + "field": "license_grant", + "kind": "bool", + "value": true + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/tests/grade.py b/tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/tests/test.sh b/tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/validation/openenv.json b/tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/environment/inputs/OLDAPIWIND-DOWNLTD_01_08_2016-EX-1.3-AGENCY_AGREEMENT1.pdf b/tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/environment/inputs/OLDAPIWIND-DOWNLTD_01_08_2016-EX-1.3-AGENCY_AGREEMENT1.pdf new file mode 100644 index 0000000000000000000000000000000000000000..9996659bd269ac0bce9cac1ddb01dd1241cf49ff --- /dev/null +++ b/tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/environment/inputs/OLDAPIWIND-DOWNLTD_01_08_2016-EX-1.3-AGENCY_AGREEMENT1.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:70d4ce0ed47fa5ac36934dccda08550963b76354fe5c4cfb2388332d4a44bf5f +size 235483 diff --git a/tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/instruction.md b/tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b75600d330fb133172be6b595dc22e13614fb6a5 --- /dev/null +++ b/tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/instruction.md @@ -0,0 +1,21 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/OLDAPIWIND-DOWNLTD_01_08_2016-EX-1.3-AGENCY_AGREEMENT1.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Agreement date** (`agreement_date`): The date of the contract: the date it is dated or entered into, as stated in the document. +2. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +3. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party. +4. **Exclusivity** (`exclusivity`): There is an exclusive dealing commitment with the counterparty: a commitment to procure all requirements from one party, or a prohibition on licensing or selling to third parties or on working with other parties, during or after the contract. An exclusive license, appointment or territory granted to the counterparty counts. +5. **Source code escrow** (`source_code_escrow`): One party must deposit its source code with a third-party escrow agent for release to the counterparty on certain events such as bankruptcy or insolvency. +6. **Non-disparagement** (`non_disparagement`): A party must not disparage the counterparty. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`agreement_date`, `governing_law`, `anti_assignment`, `exclusivity`, `source_code_escrow`, `non_disparagement`). diff --git a/tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/solution/files/answer.json b/tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..3a1adc063ded05eded6c645c6556141ef1b67e3d --- /dev/null +++ b/tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/solution/files/answer.json @@ -0,0 +1,8 @@ +{ + "agreement_date": "2015-05-21", + "governing_law": "Ontario, Canada", + "anti_assignment": "Yes", + "exclusivity": "Yes", + "source_code_escrow": "No", + "non_disparagement": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/solution/solve.sh b/tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/task.toml b/tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cbafd7c1d5020230b5c15fe207c968e86644f897 --- /dev/null +++ b/tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "OLDAPIWIND-DOWNLTD_01_08_2016-EX-1.3-AGENCY AGREEMENT1.pdf:agreement_date,governing_law,anti_assignment,exclusivity,source_code_escrow,non_disparagement" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/tests/expected.json b/tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..657b79a0417b7643a4b237bb4fc5638956ad0b25 --- /dev/null +++ b/tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/tests/expected.json @@ -0,0 +1,51 @@ +{ + "checks": [ + { + "id": "agreement_date", + "type": "answer", + "field": "agreement_date", + "kind": "date", + "value": "2015-05-21" + }, + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "Ontario, Canada", + "accept": [ + "Ontario, Canada", + "Ontario", + "Province of Ontario" + ] + }, + { + "id": "anti_assignment", + "type": "answer", + "field": "anti_assignment", + "kind": "bool", + "value": true + }, + { + "id": "exclusivity", + "type": "answer", + "field": "exclusivity", + "kind": "bool", + "value": true + }, + { + "id": "source_code_escrow", + "type": "answer", + "field": "source_code_escrow", + "kind": "bool", + "value": false + }, + { + "id": "non_disparagement", + "type": "answer", + "field": "non_disparagement", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/tests/grade.py b/tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..f9c9197d521d2bb8a537a6467bf30c433b7bcd26 --- /dev/null +++ b/tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/tests/grade.py @@ -0,0 +1,295 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def same_cell(a, b): + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + if not same_cell(want[sheet][name].value, got[sheet][name].value): + return False, f"{sheet}!{name}: want {want[sheet][name].value!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + ok = number_ok(got, want, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) if got is not None else False + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/tests/test.sh b/tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/validation/openenv.json b/tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/environment/inputs/ParatekPharmaceuticalsInc_20170505_10-KA_EX-10.29_10323872_EX-10.29_Outsourcing_Agreement.pdf b/tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/environment/inputs/ParatekPharmaceuticalsInc_20170505_10-KA_EX-10.29_10323872_EX-10.29_Outsourcing_Agreement.pdf new file mode 100644 index 0000000000000000000000000000000000000000..b4b1ae58addd7d96c7879b70b251555c74b5a409 --- /dev/null +++ b/tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/environment/inputs/ParatekPharmaceuticalsInc_20170505_10-KA_EX-10.29_10323872_EX-10.29_Outsourcing_Agreement.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:efdc607a19a80f5dd4d5a385baf876a08c5e51fdbaa08bc8332f16c422d4ae7e +size 322773 diff --git a/tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/instruction.md b/tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d654664935fd6c7057a9b3d38bd43093f001b566 --- /dev/null +++ b/tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/instruction.md @@ -0,0 +1,22 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/ParatekPharmaceuticalsInc_20170505_10-KA_EX-10.29_10323872_EX-10.29_Outsourcing_Agreement.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Agreement date** (`agreement_date`): The date of the contract: the date it is dated or entered into, as stated in the document. +2. **Effective date** (`effective_date`): The date the contract becomes effective or its term commences. +3. **Most favored nation** (`most_favored_nation`): If a third party gets better terms on the licensing or sale of the technology, goods or services in the contract, the buyer under this contract is entitled to those better terms. +4. **IP ownership assignment** (`ip_ownership_assignment`): Intellectual property created by one party becomes the property of the counterparty, under the contract terms or on the occurrence of certain events. +5. **Source code escrow** (`source_code_escrow`): One party must deposit its source code with a third-party escrow agent for release to the counterparty on certain events such as bankruptcy or insolvency. +6. **No-solicit of employees** (`no_solicit_of_employees`): A party is restricted from soliciting or hiring employees or contractors of the counterparty, during or after the contract. +7. **License grant** (`license_grant`): One party grants a license to its counterparty. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`agreement_date`, `effective_date`, `most_favored_nation`, `ip_ownership_assignment`, `source_code_escrow`, `no_solicit_of_employees`, `license_grant`). diff --git a/tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/solution/files/answer.json b/tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..078c7c7ff19585de979890682ea123c83f567e4d --- /dev/null +++ b/tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/solution/files/answer.json @@ -0,0 +1,9 @@ +{ + "agreement_date": "2016-12-30", + "effective_date": "2016-12-30", + "most_favored_nation": "No", + "ip_ownership_assignment": "Yes", + "source_code_escrow": "No", + "no_solicit_of_employees": "No", + "license_grant": "Yes" +} \ No newline at end of file diff --git a/tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/solution/solve.sh b/tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/task.toml b/tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a2e7d5d6d5565495c755d61cbbad56ccfb063eda --- /dev/null +++ b/tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "ParatekPharmaceuticalsInc_20170505_10-KA_EX-10.29_10323872_EX-10.29_Outsourcing Agreement.pdf:agreement_date,effective_date,most_favored_nation,ip_ownership_assignment,source_code_escrow,no_solicit_of_employees,license_grant" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/tests/expected.json b/tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..153159f5eb10bd504f310f180e418cb7985fe063 --- /dev/null +++ b/tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/tests/expected.json @@ -0,0 +1,53 @@ +{ + "checks": [ + { + "id": "agreement_date", + "type": "answer", + "field": "agreement_date", + "kind": "date", + "value": "2016-12-30" + }, + { + "id": "effective_date", + "type": "answer", + "field": "effective_date", + "kind": "date", + "value": "2016-12-30" + }, + { + "id": "most_favored_nation", + "type": "answer", + "field": "most_favored_nation", + "kind": "bool", + "value": false + }, + { + "id": "ip_ownership_assignment", + "type": "answer", + "field": "ip_ownership_assignment", + "kind": "bool", + "value": true + }, + { + "id": "source_code_escrow", + "type": "answer", + "field": "source_code_escrow", + "kind": "bool", + "value": false + }, + { + "id": "no_solicit_of_employees", + "type": "answer", + "field": "no_solicit_of_employees", + "kind": "bool", + "value": false + }, + { + "id": "license_grant", + "type": "answer", + "field": "license_grant", + "kind": "bool", + "value": true + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/tests/grade.py b/tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/tests/test.sh b/tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/validation/openenv.json b/tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/environment/inputs/PelicanDeliversInc_20200211_S-1_EX-10.3_11975895_EX-10.3_Development_Agreement2.pdf b/tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/environment/inputs/PelicanDeliversInc_20200211_S-1_EX-10.3_11975895_EX-10.3_Development_Agreement2.pdf new file mode 100644 index 0000000000000000000000000000000000000000..2704c1723e6ffbc7478ef2eb5ca9b0fc65343b43 --- /dev/null +++ b/tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/environment/inputs/PelicanDeliversInc_20200211_S-1_EX-10.3_11975895_EX-10.3_Development_Agreement2.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1338a48b6fb2c762619462dc43c7d4435e85359d7fe46aae238dfe8f077243be +size 182538 diff --git a/tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/instruction.md b/tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4c992a53a15284f9f8526f6b5149adf8d2a6ed61 --- /dev/null +++ b/tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/instruction.md @@ -0,0 +1,23 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/PelicanDeliversInc_20200211_S-1_EX-10.3_11975895_EX-10.3_Development_Agreement2.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Agreement date** (`agreement_date`): The date of the contract: the date it is dated or entered into, as stated in the document. +2. **Effective date** (`effective_date`): The date the contract becomes effective or its term commences. +3. **Change of control** (`change_of_control`): One party has the right to terminate, or consent or notice of the counterparty is required, if that party undergoes a change of control (a merger, stock sale, transfer of all or substantially all of its assets or business, or assignment by operation of law). +4. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party. +5. **Non-compete** (`non_compete`): A party is restricted from competing with the counterparty or from operating in a certain geography, business or technology sector. +6. **Termination for convenience** (`termination_for_convenience`): A party can terminate the contract without cause, solely by giving notice and letting a waiting period expire. +7. **IP ownership assignment** (`ip_ownership_assignment`): Intellectual property created by one party becomes the property of the counterparty, under the contract terms or on the occurrence of certain events. +8. **Liquidated damages** (`liquidated_damages`): Either party can be awarded liquidated damages for breach, or a fee on termination of the contract (a termination fee). + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`agreement_date`, `effective_date`, `change_of_control`, `anti_assignment`, `non_compete`, `termination_for_convenience`, `ip_ownership_assignment`, `liquidated_damages`). diff --git a/tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/solution/files/answer.json b/tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..7b97e0138deb39e835512054e5f330842b9d834b --- /dev/null +++ b/tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/solution/files/answer.json @@ -0,0 +1,10 @@ +{ + "agreement_date": "2018-12-03", + "effective_date": "2018-12-03", + "change_of_control": "No", + "anti_assignment": "Yes", + "non_compete": "No", + "termination_for_convenience": "Yes", + "ip_ownership_assignment": "Yes", + "liquidated_damages": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/solution/solve.sh b/tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/task.toml b/tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f53140add33a83d59365f3bb410fcb19439b9608 --- /dev/null +++ b/tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "PelicanDeliversInc_20200211_S-1_EX-10.3_11975895_EX-10.3_Development Agreement2.pdf:agreement_date,effective_date,change_of_control,anti_assignment,non_compete,termination_for_convenience,ip_ownership_assignment,liquidated_damages" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/tests/expected.json b/tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..65463c0fadbc5793754f338a968763d20d40b8b4 --- /dev/null +++ b/tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/tests/expected.json @@ -0,0 +1,60 @@ +{ + "checks": [ + { + "id": "agreement_date", + "type": "answer", + "field": "agreement_date", + "kind": "date", + "value": "2018-12-03" + }, + { + "id": "effective_date", + "type": "answer", + "field": "effective_date", + "kind": "date", + "value": "2018-12-03" + }, + { + "id": "change_of_control", + "type": "answer", + "field": "change_of_control", + "kind": "bool", + "value": false + }, + { + "id": "anti_assignment", + "type": "answer", + "field": "anti_assignment", + "kind": "bool", + "value": true + }, + { + "id": "non_compete", + "type": "answer", + "field": "non_compete", + "kind": "bool", + "value": false + }, + { + "id": "termination_for_convenience", + "type": "answer", + "field": "termination_for_convenience", + "kind": "bool", + "value": true + }, + { + "id": "ip_ownership_assignment", + "type": "answer", + "field": "ip_ownership_assignment", + "kind": "bool", + "value": true + }, + { + "id": "liquidated_damages", + "type": "answer", + "field": "liquidated_damages", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/tests/grade.py b/tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/tests/test.sh b/tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/validation/openenv.json b/tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028/environment/inputs/PharmagenInc_20120803_8-KA_EX-10.1_7693204_EX-10.1_Endorsement_Agreement.pdf b/tasks/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028/environment/inputs/PharmagenInc_20120803_8-KA_EX-10.1_7693204_EX-10.1_Endorsement_Agreement.pdf new file mode 100644 index 0000000000000000000000000000000000000000..9a3019187e6dbfa51d500ebe4a7ead2bd624a132 Binary files /dev/null and b/tasks/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028/environment/inputs/PharmagenInc_20120803_8-KA_EX-10.1_7693204_EX-10.1_Endorsement_Agreement.pdf differ diff --git a/tasks/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028/instruction.md b/tasks/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..941466324b146a98c5a9dd292c2a9095530877a9 --- /dev/null +++ b/tasks/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028/instruction.md @@ -0,0 +1,21 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/PharmagenInc_20120803_8-KA_EX-10.1_7693204_EX-10.1_Endorsement_Agreement.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +2. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party. +3. **Most favored nation** (`most_favored_nation`): If a third party gets better terms on the licensing or sale of the technology, goods or services in the contract, the buyer under this contract is entitled to those better terms. +4. **Insurance** (`insurance`): One party must maintain insurance for the benefit of the counterparty. +5. **No-solicit of employees** (`no_solicit_of_employees`): A party is restricted from soliciting or hiring employees or contractors of the counterparty, during or after the contract. +6. **Revenue or profit sharing** (`revenue_profit_sharing`): One party must share revenue or profit with the counterparty for any technology, goods or services. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`governing_law`, `anti_assignment`, `most_favored_nation`, `insurance`, `no_solicit_of_employees`, `revenue_profit_sharing`). diff --git a/tasks/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028/solution/files/answer.json b/tasks/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..7bcbaf08c6fb1eced858fe49bae908deaea53b81 --- /dev/null +++ b/tasks/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028/solution/files/answer.json @@ -0,0 +1,8 @@ +{ + "governing_law": "Georgia", + "anti_assignment": "Yes", + "most_favored_nation": "No", + "insurance": "Yes", + "no_solicit_of_employees": "No", + "revenue_profit_sharing": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028/solution/solve.sh b/tasks/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028/task.toml b/tasks/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f2a1ed97aad9efc4a065e1cd672409af1bea59b1 --- /dev/null +++ b/tasks/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "PharmagenInc_20120803_8-KA_EX-10.1_7693204_EX-10.1_Endorsement Agreement.pdf:governing_law,anti_assignment,most_favored_nation,insurance,no_solicit_of_employees,revenue_profit_sharing" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028/tests/expected.json b/tasks/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..6155566db19d68b9e0b20cddc2625bbd0d9ba48a --- /dev/null +++ b/tasks/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028/tests/expected.json @@ -0,0 +1,52 @@ +{ + "checks": [ + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "Georgia", + "accept": [ + "Georgia", + "State of Georgia", + "Georgia, USA", + "Georgia, United States" + ] + }, + { + "id": "anti_assignment", + "type": "answer", + "field": "anti_assignment", + "kind": "bool", + "value": true + }, + { + "id": "most_favored_nation", + "type": "answer", + "field": "most_favored_nation", + "kind": "bool", + "value": false + }, + { + "id": "insurance", + "type": "answer", + "field": "insurance", + "kind": "bool", + "value": true + }, + { + "id": "no_solicit_of_employees", + "type": "answer", + "field": "no_solicit_of_employees", + "kind": "bool", + "value": false + }, + { + "id": "revenue_profit_sharing", + "type": "answer", + "field": "revenue_profit_sharing", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028/tests/grade.py b/tasks/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028/tests/test.sh b/tasks/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028/validation/openenv.json b/tasks/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-pharmageninc-20120803-8-ka-ex-10-1-76932-1b7bc028/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/environment/inputs/PREMIERBIOMEDICALINC_05_14_2020-EX-10.2-INTELLECTUAL_PROPERTY_AGREEMENT.pdf b/tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/environment/inputs/PREMIERBIOMEDICALINC_05_14_2020-EX-10.2-INTELLECTUAL_PROPERTY_AGREEMENT.pdf new file mode 100644 index 0000000000000000000000000000000000000000..2df7713a54f5f29003b4618e006704dc0ea8f00b --- /dev/null +++ b/tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/environment/inputs/PREMIERBIOMEDICALINC_05_14_2020-EX-10.2-INTELLECTUAL_PROPERTY_AGREEMENT.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:551960215a8c5708ea4a24cd4e2ee2aae6534853894f6cf6368b303d49a9e7f1 +size 102705 diff --git a/tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/instruction.md b/tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0813f68e246f289be3d02fce006c15ed0a3fdfa4 --- /dev/null +++ b/tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/instruction.md @@ -0,0 +1,23 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/PREMIERBIOMEDICALINC_05_14_2020-EX-10.2-INTELLECTUAL_PROPERTY_AGREEMENT.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Agreement date** (`agreement_date`): The date of the contract: the date it is dated or entered into, as stated in the document. +2. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +3. **Exclusivity** (`exclusivity`): There is an exclusive dealing commitment with the counterparty: a commitment to procure all requirements from one party, or a prohibition on licensing or selling to third parties or on working with other parties, during or after the contract. An exclusive license, appointment or territory granted to the counterparty counts. +4. **Right of first refusal, offer or negotiation** (`right_of_first_refusal`): One party has a right of first refusal, first offer or first negotiation to purchase, license, market or distribute equity, technology, assets, products or services. +5. **Liquidated damages** (`liquidated_damages`): Either party can be awarded liquidated damages for breach, or a fee on termination of the contract (a termination fee). +6. **Source code escrow** (`source_code_escrow`): One party must deposit its source code with a third-party escrow agent for release to the counterparty on certain events such as bankruptcy or insolvency. +7. **Non-disparagement** (`non_disparagement`): A party must not disparage the counterparty. +8. **License grant** (`license_grant`): One party grants a license to its counterparty. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`agreement_date`, `governing_law`, `exclusivity`, `right_of_first_refusal`, `liquidated_damages`, `source_code_escrow`, `non_disparagement`, `license_grant`). diff --git a/tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/solution/files/answer.json b/tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..29e0e953275c30fc02841f8921a0622b57ff515f --- /dev/null +++ b/tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/solution/files/answer.json @@ -0,0 +1,10 @@ +{ + "agreement_date": "2020-05-12", + "governing_law": "Pennsylvania", + "exclusivity": "Yes", + "right_of_first_refusal": "No", + "liquidated_damages": "No", + "source_code_escrow": "No", + "non_disparagement": "No", + "license_grant": "Yes" +} \ No newline at end of file diff --git a/tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/solution/solve.sh b/tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/task.toml b/tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3b11d036b508abd48295993c8659ce3dae9bed62 --- /dev/null +++ b/tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "PREMIERBIOMEDICALINC_05_14_2020-EX-10.2-INTELLECTUAL PROPERTY AGREEMENT.PDF:agreement_date,governing_law,exclusivity,right_of_first_refusal,liquidated_damages,source_code_escrow,non_disparagement,license_grant" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/tests/expected.json b/tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..e99e478d0e5f44f07dd2fbb973160378007da73e --- /dev/null +++ b/tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/tests/expected.json @@ -0,0 +1,67 @@ +{ + "checks": [ + { + "id": "agreement_date", + "type": "answer", + "field": "agreement_date", + "kind": "date", + "value": "2020-05-12" + }, + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "Pennsylvania", + "accept": [ + "Pennsylvania", + "State of Pennsylvania", + "Pennsylvania, USA", + "Pennsylvania, United States", + "Commonwealth of Pennsylvania" + ] + }, + { + "id": "exclusivity", + "type": "answer", + "field": "exclusivity", + "kind": "bool", + "value": true + }, + { + "id": "right_of_first_refusal", + "type": "answer", + "field": "right_of_first_refusal", + "kind": "bool", + "value": false + }, + { + "id": "liquidated_damages", + "type": "answer", + "field": "liquidated_damages", + "kind": "bool", + "value": false + }, + { + "id": "source_code_escrow", + "type": "answer", + "field": "source_code_escrow", + "kind": "bool", + "value": false + }, + { + "id": "non_disparagement", + "type": "answer", + "field": "non_disparagement", + "kind": "bool", + "value": false + }, + { + "id": "license_grant", + "type": "answer", + "field": "license_grant", + "kind": "bool", + "value": true + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/tests/grade.py b/tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/tests/test.sh b/tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/validation/openenv.json b/tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/environment/inputs/RareElementResourcesLtd_20171019_SC_13D_EX-99.4_10897534_EX-99.4_Intellectual_Property_Agreement.pdf b/tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/environment/inputs/RareElementResourcesLtd_20171019_SC_13D_EX-99.4_10897534_EX-99.4_Intellectual_Property_Agreement.pdf new file mode 100644 index 0000000000000000000000000000000000000000..338db56b42d8f3aaaa44a1b74f1fd738fc00ac79 --- /dev/null +++ b/tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/environment/inputs/RareElementResourcesLtd_20171019_SC_13D_EX-99.4_10897534_EX-99.4_Intellectual_Property_Agreement.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dc26906de897464aacabde5c10965acfc7a78c7e5aaae6f058687fa5a725e8c2 +size 180502 diff --git a/tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/instruction.md b/tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..052f81c8a9697185db49a8d08f7e1ab437de7a0b --- /dev/null +++ b/tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/instruction.md @@ -0,0 +1,23 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/RareElementResourcesLtd_20171019_SC_13D_EX-99.4_10897534_EX-99.4_Intellectual_Property_Agreement.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Agreement date** (`agreement_date`): The date of the contract: the date it is dated or entered into, as stated in the document. +2. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +3. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party. +4. **Audit rights** (`audit_rights`): A party has the right to audit the books, records or physical locations of the counterparty to check compliance with the contract. +5. **IP ownership assignment** (`ip_ownership_assignment`): Intellectual property created by one party becomes the property of the counterparty, under the contract terms or on the occurrence of certain events. +6. **Liquidated damages** (`liquidated_damages`): Either party can be awarded liquidated damages for breach, or a fee on termination of the contract (a termination fee). +7. **Non-disparagement** (`non_disparagement`): A party must not disparage the counterparty. +8. **License grant** (`license_grant`): One party grants a license to its counterparty. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`agreement_date`, `governing_law`, `anti_assignment`, `audit_rights`, `ip_ownership_assignment`, `liquidated_damages`, `non_disparagement`, `license_grant`). diff --git a/tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/solution/files/answer.json b/tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..ddee806e89499de14de985de46a1648eaea22810 --- /dev/null +++ b/tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/solution/files/answer.json @@ -0,0 +1,10 @@ +{ + "agreement_date": "2017-10-02", + "governing_law": "New York", + "anti_assignment": "Yes", + "audit_rights": "No", + "ip_ownership_assignment": "Yes", + "liquidated_damages": "No", + "non_disparagement": "No", + "license_grant": "Yes" +} \ No newline at end of file diff --git a/tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/solution/solve.sh b/tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/task.toml b/tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..47a6a6a101aac6e90ee0a7fb90751f317f1fce66 --- /dev/null +++ b/tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "RareElementResourcesLtd_20171019_SC 13D_EX-99.4_10897534_EX-99.4_Intellectual Property Agreement.pdf:agreement_date,governing_law,anti_assignment,audit_rights,ip_ownership_assignment,liquidated_damages,non_disparagement,license_grant" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/tests/expected.json b/tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..0eb5cd280f34c9949ccb439f2b7c57b71c874a87 --- /dev/null +++ b/tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/tests/expected.json @@ -0,0 +1,66 @@ +{ + "checks": [ + { + "id": "agreement_date", + "type": "answer", + "field": "agreement_date", + "kind": "date", + "value": "2017-10-02" + }, + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "New York", + "accept": [ + "New York", + "State of New York", + "New York, USA", + "New York, United States" + ] + }, + { + "id": "anti_assignment", + "type": "answer", + "field": "anti_assignment", + "kind": "bool", + "value": true + }, + { + "id": "audit_rights", + "type": "answer", + "field": "audit_rights", + "kind": "bool", + "value": false + }, + { + "id": "ip_ownership_assignment", + "type": "answer", + "field": "ip_ownership_assignment", + "kind": "bool", + "value": true + }, + { + "id": "liquidated_damages", + "type": "answer", + "field": "liquidated_damages", + "kind": "bool", + "value": false + }, + { + "id": "non_disparagement", + "type": "answer", + "field": "non_disparagement", + "kind": "bool", + "value": false + }, + { + "id": "license_grant", + "type": "answer", + "field": "license_grant", + "kind": "bool", + "value": true + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/tests/grade.py b/tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/tests/test.sh b/tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/validation/openenv.json b/tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/environment/inputs/REGANHOLDINGCORP_03_31_2008-EX-10-LICENSE_AND_HOSTING_AGREEMENT.pdf b/tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/environment/inputs/REGANHOLDINGCORP_03_31_2008-EX-10-LICENSE_AND_HOSTING_AGREEMENT.pdf new file mode 100644 index 0000000000000000000000000000000000000000..165a63d7e7be28b4e5be11d9e0e0fe809094b6d8 --- /dev/null +++ b/tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/environment/inputs/REGANHOLDINGCORP_03_31_2008-EX-10-LICENSE_AND_HOSTING_AGREEMENT.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ff5d0005e19d6ad0a813165968c7999ca06257a6b57d4a9c3e2461480287b170 +size 157149 diff --git a/tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/instruction.md b/tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8fdc9abb6450c64961cab22f5f52667d3ae6a4ac --- /dev/null +++ b/tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/instruction.md @@ -0,0 +1,22 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/REGANHOLDINGCORP_03_31_2008-EX-10-LICENSE_AND_HOSTING_AGREEMENT.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Agreement date** (`agreement_date`): The date of the contract: the date it is dated or entered into, as stated in the document. +2. **Effective date** (`effective_date`): The date the contract becomes effective or its term commences. +3. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +4. **Cap on liability** (`cap_on_liability`): The contract limits a party's liability for breach: a maximum recoverable amount, an exclusion of categories of damages (for example indirect, consequential or lost-profit damages), or a time limit for the counterparty to bring claims. +5. **Non-compete** (`non_compete`): A party is restricted from competing with the counterparty or from operating in a certain geography, business or technology sector. +6. **Insurance** (`insurance`): One party must maintain insurance for the benefit of the counterparty. +7. **Liquidated damages** (`liquidated_damages`): Either party can be awarded liquidated damages for breach, or a fee on termination of the contract (a termination fee). + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`agreement_date`, `effective_date`, `governing_law`, `cap_on_liability`, `non_compete`, `insurance`, `liquidated_damages`). diff --git a/tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/solution/files/answer.json b/tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..9f04641d781acafcdd6c933f22831af8fdabb7d1 --- /dev/null +++ b/tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/solution/files/answer.json @@ -0,0 +1,9 @@ +{ + "agreement_date": "2007-10-17", + "effective_date": "2007-10-17", + "governing_law": "Georgia", + "cap_on_liability": "Yes", + "non_compete": "No", + "insurance": "Yes", + "liquidated_damages": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/solution/solve.sh b/tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/task.toml b/tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4e0c6b322d386b629fceabc93774a4ff6a37f9ec --- /dev/null +++ b/tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "REGANHOLDINGCORP_03_31_2008-EX-10-LICENSE AND HOSTING AGREEMENT.PDF:agreement_date,effective_date,governing_law,cap_on_liability,non_compete,insurance,liquidated_damages" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/tests/expected.json b/tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..83eb8854aa8c44411005aec7532719fe585fb23d --- /dev/null +++ b/tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/tests/expected.json @@ -0,0 +1,59 @@ +{ + "checks": [ + { + "id": "agreement_date", + "type": "answer", + "field": "agreement_date", + "kind": "date", + "value": "2007-10-17" + }, + { + "id": "effective_date", + "type": "answer", + "field": "effective_date", + "kind": "date", + "value": "2007-10-17" + }, + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "Georgia", + "accept": [ + "Georgia", + "State of Georgia", + "Georgia, USA", + "Georgia, United States" + ] + }, + { + "id": "cap_on_liability", + "type": "answer", + "field": "cap_on_liability", + "kind": "bool", + "value": true + }, + { + "id": "non_compete", + "type": "answer", + "field": "non_compete", + "kind": "bool", + "value": false + }, + { + "id": "insurance", + "type": "answer", + "field": "insurance", + "kind": "bool", + "value": true + }, + { + "id": "liquidated_damages", + "type": "answer", + "field": "liquidated_damages", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/tests/grade.py b/tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/tests/test.sh b/tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/validation/openenv.json b/tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/environment/inputs/ReynoldsConsumerProductsInc_20200121_S-1A_EX-10.22_11948918_EX-10.22_Service_Agreement.pdf b/tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/environment/inputs/ReynoldsConsumerProductsInc_20200121_S-1A_EX-10.22_11948918_EX-10.22_Service_Agreement.pdf new file mode 100644 index 0000000000000000000000000000000000000000..d545953c930200879e5bfec464f2ed5de6765e3d --- /dev/null +++ b/tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/environment/inputs/ReynoldsConsumerProductsInc_20200121_S-1A_EX-10.22_11948918_EX-10.22_Service_Agreement.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:06c01ec95512aca3c7e67cc6aaf99fe121c6ab50db7fb7c8d1f3797dad2f0098 +size 361141 diff --git a/tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/instruction.md b/tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e0227889ee263018a0d0e931637915d96e04a87f --- /dev/null +++ b/tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/instruction.md @@ -0,0 +1,22 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/ReynoldsConsumerProductsInc_20200121_S-1A_EX-10.22_11948918_EX-10.22_Service_Agreement.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +2. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party. +3. **Audit rights** (`audit_rights`): A party has the right to audit the books, records or physical locations of the counterparty to check compliance with the contract. +4. **Right of first refusal, offer or negotiation** (`right_of_first_refusal`): One party has a right of first refusal, first offer or first negotiation to purchase, license, market or distribute equity, technology, assets, products or services. +5. **Insurance** (`insurance`): One party must maintain insurance for the benefit of the counterparty. +6. **Source code escrow** (`source_code_escrow`): One party must deposit its source code with a third-party escrow agent for release to the counterparty on certain events such as bankruptcy or insolvency. +7. **Non-disparagement** (`non_disparagement`): A party must not disparage the counterparty. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`governing_law`, `anti_assignment`, `audit_rights`, `right_of_first_refusal`, `insurance`, `source_code_escrow`, `non_disparagement`). diff --git a/tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/solution/files/answer.json b/tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..e5f068eee151c660fb208667860228ee757a66d8 --- /dev/null +++ b/tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/solution/files/answer.json @@ -0,0 +1,9 @@ +{ + "governing_law": "Illinois", + "anti_assignment": "Yes", + "audit_rights": "Yes", + "right_of_first_refusal": "No", + "insurance": "Yes", + "source_code_escrow": "No", + "non_disparagement": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/solution/solve.sh b/tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/task.toml b/tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8e6ef1f6c547a1171e0e51a80887690722a285e3 --- /dev/null +++ b/tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "ReynoldsConsumerProductsInc_20200121_S-1A_EX-10.22_11948918_EX-10.22_Service Agreement.pdf:governing_law,anti_assignment,audit_rights,right_of_first_refusal,insurance,source_code_escrow,non_disparagement" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/tests/expected.json b/tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..e7bcfdca2d4d737477da63b717d2905f7ac932b9 --- /dev/null +++ b/tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/tests/expected.json @@ -0,0 +1,59 @@ +{ + "checks": [ + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "Illinois", + "accept": [ + "Illinois", + "State of Illinois", + "Illinois, USA", + "Illinois, United States" + ] + }, + { + "id": "anti_assignment", + "type": "answer", + "field": "anti_assignment", + "kind": "bool", + "value": true + }, + { + "id": "audit_rights", + "type": "answer", + "field": "audit_rights", + "kind": "bool", + "value": true + }, + { + "id": "right_of_first_refusal", + "type": "answer", + "field": "right_of_first_refusal", + "kind": "bool", + "value": false + }, + { + "id": "insurance", + "type": "answer", + "field": "insurance", + "kind": "bool", + "value": true + }, + { + "id": "source_code_escrow", + "type": "answer", + "field": "source_code_escrow", + "kind": "bool", + "value": false + }, + { + "id": "non_disparagement", + "type": "answer", + "field": "non_disparagement", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/tests/grade.py b/tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..f9c9197d521d2bb8a537a6467bf30c433b7bcd26 --- /dev/null +++ b/tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/tests/grade.py @@ -0,0 +1,295 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def same_cell(a, b): + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + if not same_cell(want[sheet][name].value, got[sheet][name].value): + return False, f"{sheet}!{name}: want {want[sheet][name].value!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + ok = number_ok(got, want, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) if got is not None else False + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/tests/test.sh b/tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/validation/openenv.json b/tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/environment/inputs/RUBIOSRESTAURANTSINC_03_31_2008-EX-10.75-SPONSORSHIP_AGREEMENT.pdf b/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/environment/inputs/RUBIOSRESTAURANTSINC_03_31_2008-EX-10.75-SPONSORSHIP_AGREEMENT.pdf new file mode 100644 index 0000000000000000000000000000000000000000..c5515a563e13c7eb91a2262773a85263fe06082e --- /dev/null +++ b/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/environment/inputs/RUBIOSRESTAURANTSINC_03_31_2008-EX-10.75-SPONSORSHIP_AGREEMENT.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8bd92ff32b70a5548fbde0be7306c8dc3cd51d680f7866d44f1c52a76ba1156d +size 133614 diff --git a/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/instruction.md b/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5cfeac29578a6b2f7e33b0ec623f7e5676561f5b --- /dev/null +++ b/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/instruction.md @@ -0,0 +1,22 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/RUBIOSRESTAURANTSINC_03_31_2008-EX-10.75-SPONSORSHIP_AGREEMENT.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Agreement date** (`agreement_date`): The date of the contract: the date it is dated or entered into, as stated in the document. +2. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +3. **Cap on liability** (`cap_on_liability`): The contract limits a party's liability for breach: a maximum recoverable amount, an exclusion of categories of damages (for example indirect, consequential or lost-profit damages), or a time limit for the counterparty to bring claims. +4. **Right of first refusal, offer or negotiation** (`right_of_first_refusal`): One party has a right of first refusal, first offer or first negotiation to purchase, license, market or distribute equity, technology, assets, products or services. +5. **Source code escrow** (`source_code_escrow`): One party must deposit its source code with a third-party escrow agent for release to the counterparty on certain events such as bankruptcy or insolvency. +6. **Non-disparagement** (`non_disparagement`): A party must not disparage the counterparty. +7. **License grant** (`license_grant`): One party grants a license to its counterparty. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`agreement_date`, `governing_law`, `cap_on_liability`, `right_of_first_refusal`, `source_code_escrow`, `non_disparagement`, `license_grant`). diff --git a/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/solution/files/answer.json b/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..42d8055f63fe3f6851456cd7f59f6b4ca537a2c0 --- /dev/null +++ b/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/solution/files/answer.json @@ -0,0 +1,9 @@ +{ + "agreement_date": "2008-03-21", + "governing_law": "California", + "cap_on_liability": "Yes", + "right_of_first_refusal": "No", + "source_code_escrow": "No", + "non_disparagement": "No", + "license_grant": "Yes" +} \ No newline at end of file diff --git a/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/solution/solve.sh b/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/task.toml b/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2d20427b67ab2b04038a9c91e2e14330d3b2cfad --- /dev/null +++ b/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/task.toml @@ -0,0 +1,50 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "RUBIOSRESTAURANTSINC_03_31_2008-EX-10.75-SPONSORSHIP AGREEMENT.PDF:agreement_date,governing_law,cap_on_liability,exclusivity,right_of_first_refusal,source_code_escrow,non_disparagement,license_grant" +task_kind = "single-contract-checklist" + +[metadata.apex_gap.repair] +fixes = "{\"exclusivity\": {\"action\": \"drop\", \"reason\": \"General Provisions section 14 says 'No marketing exclusivity in any category ... is conferred or implied by this Agreement except to the extent explicitly set forth in the Agreement Summary'. The filed Agreement Summary grants none but has confidential-treatment redactions, so the answer cannot be determined from the PDF.\"}}" + +[metadata.apex_gap.rewrite] +change = "{\"add_conventions\": [], \"correct\": {}, \"evidence\": \"runs/apex-knowledge/task-supply/key-verification/decisions/cuad.json\", \"from\": \"runs/apex-knowledge/wave2/cuad/repair/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea\", \"reason\": \"exclusivity: asked but no check grades it (an earlier repair dropped the check)\", \"remove\": [\"exclusivity\"], \"rewrite\": {}, \"v1_task_id\": \"cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea\"}" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/tests/expected.json b/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..a1dce4c75f1c7361a674584d59fa4cd038165b1a --- /dev/null +++ b/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/tests/expected.json @@ -0,0 +1,59 @@ +{ + "checks": [ + { + "id": "agreement_date", + "type": "answer", + "field": "agreement_date", + "kind": "date", + "value": "2008-03-21" + }, + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "California", + "accept": [ + "California", + "State of California", + "California, USA", + "California, United States" + ] + }, + { + "id": "cap_on_liability", + "type": "answer", + "field": "cap_on_liability", + "kind": "bool", + "value": true + }, + { + "id": "right_of_first_refusal", + "type": "answer", + "field": "right_of_first_refusal", + "kind": "bool", + "value": false + }, + { + "id": "source_code_escrow", + "type": "answer", + "field": "source_code_escrow", + "kind": "bool", + "value": false + }, + { + "id": "non_disparagement", + "type": "answer", + "field": "non_disparagement", + "kind": "bool", + "value": false + }, + { + "id": "license_grant", + "type": "answer", + "field": "license_grant", + "kind": "bool", + "value": true + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/tests/grade.py b/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/tests/test.sh b/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/validation/openenv.json b/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/environment/inputs/SCOUTCAMINC_05_12_2020-EX-10.22-SERVICES_AGREEMENT.pdf b/tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/environment/inputs/SCOUTCAMINC_05_12_2020-EX-10.22-SERVICES_AGREEMENT.pdf new file mode 100644 index 0000000000000000000000000000000000000000..6c360ed789742c5d248a7d344768496db96ae849 --- /dev/null +++ b/tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/environment/inputs/SCOUTCAMINC_05_12_2020-EX-10.22-SERVICES_AGREEMENT.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bcb7399a73880b9148638872e7945820dae7a9fe640498fb082bcb59f4d6241c +size 101359 diff --git a/tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/instruction.md b/tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..96e3f8f2d160db13cabc5807bc3e9b95c3eb3ba1 --- /dev/null +++ b/tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/instruction.md @@ -0,0 +1,23 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/SCOUTCAMINC_05_12_2020-EX-10.22-SERVICES_AGREEMENT.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Agreement date** (`agreement_date`): The date of the contract: the date it is dated or entered into, as stated in the document. +2. **Effective date** (`effective_date`): The date the contract becomes effective or its term commences. +3. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +4. **Change of control** (`change_of_control`): One party has the right to terminate, or consent or notice of the counterparty is required, if that party undergoes a change of control (a merger, stock sale, transfer of all or substantially all of its assets or business, or assignment by operation of law). +5. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party. +6. **Termination for convenience** (`termination_for_convenience`): A party can terminate the contract without cause, solely by giving notice and letting a waiting period expire. +7. **Insurance** (`insurance`): One party must maintain insurance for the benefit of the counterparty. +8. **License grant** (`license_grant`): One party grants a license to its counterparty. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`agreement_date`, `effective_date`, `governing_law`, `change_of_control`, `anti_assignment`, `termination_for_convenience`, `insurance`, `license_grant`). diff --git a/tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/solution/files/answer.json b/tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..0445e2419acc2f256b516be5e19413013dfe1b03 --- /dev/null +++ b/tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/solution/files/answer.json @@ -0,0 +1,10 @@ +{ + "agreement_date": "2019-04-01", + "effective_date": "2019-04-01", + "governing_law": "New York", + "change_of_control": "No", + "anti_assignment": "Yes", + "termination_for_convenience": "Yes", + "insurance": "No", + "license_grant": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/solution/solve.sh b/tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/task.toml b/tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e1efee6f24a57711e91b9f8ad737efdf3d61cc3b --- /dev/null +++ b/tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "SCOUTCAMINC_05_12_2020-EX-10.22-SERVICES AGREEMENT.PDF:agreement_date,effective_date,governing_law,change_of_control,anti_assignment,termination_for_convenience,insurance,license_grant" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/tests/expected.json b/tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..8250af607a4b63e7576d2feefe8cd4a7231dc497 --- /dev/null +++ b/tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/tests/expected.json @@ -0,0 +1,66 @@ +{ + "checks": [ + { + "id": "agreement_date", + "type": "answer", + "field": "agreement_date", + "kind": "date", + "value": "2019-04-01" + }, + { + "id": "effective_date", + "type": "answer", + "field": "effective_date", + "kind": "date", + "value": "2019-04-01" + }, + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "New York", + "accept": [ + "New York", + "State of New York", + "New York, USA", + "New York, United States" + ] + }, + { + "id": "change_of_control", + "type": "answer", + "field": "change_of_control", + "kind": "bool", + "value": false + }, + { + "id": "anti_assignment", + "type": "answer", + "field": "anti_assignment", + "kind": "bool", + "value": true + }, + { + "id": "termination_for_convenience", + "type": "answer", + "field": "termination_for_convenience", + "kind": "bool", + "value": true + }, + { + "id": "insurance", + "type": "answer", + "field": "insurance", + "kind": "bool", + "value": false + }, + { + "id": "license_grant", + "type": "answer", + "field": "license_grant", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/tests/grade.py b/tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..f9c9197d521d2bb8a537a6467bf30c433b7bcd26 --- /dev/null +++ b/tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/tests/grade.py @@ -0,0 +1,295 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def same_cell(a, b): + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + if not same_cell(want[sheet][name].value, got[sheet][name].value): + return False, f"{sheet}!{name}: want {want[sheet][name].value!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + ok = number_ok(got, want, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) if got is not None else False + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/tests/test.sh b/tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/validation/openenv.json b/tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2/environment/inputs/SLOVAKWIRELESSFINANCECOBV_03_28_2001-EX-4._B_II_.3-Maintenance_and_support_contract_for_SICAP_R_modules.pdf b/tasks/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2/environment/inputs/SLOVAKWIRELESSFINANCECOBV_03_28_2001-EX-4._B_II_.3-Maintenance_and_support_contract_for_SICAP_R_modules.pdf new file mode 100644 index 0000000000000000000000000000000000000000..5ffff5bf0ae004e0c97db1f48a8a753b14d3bf86 Binary files /dev/null and b/tasks/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2/environment/inputs/SLOVAKWIRELESSFINANCECOBV_03_28_2001-EX-4._B_II_.3-Maintenance_and_support_contract_for_SICAP_R_modules.pdf differ diff --git a/tasks/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2/instruction.md b/tasks/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0d9c06f3e60c41b043fbc77974b6a7fa6dc08aef --- /dev/null +++ b/tasks/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2/instruction.md @@ -0,0 +1,23 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/SLOVAKWIRELESSFINANCECOBV_03_28_2001-EX-4._B_II_.3-Maintenance_and_support_contract_for_SICAP_R_modules.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Effective date** (`effective_date`): The date the contract becomes effective or its term commences. +2. **Renewal term** (`renewal_term_months`): the length of each renewal or extension term that follows the initial term, in months, as a JSON number (for example `12` for one year). +3. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party. +4. **Cap on liability** (`cap_on_liability`): The contract limits a party's liability for breach: a maximum recoverable amount, an exclusion of categories of damages (for example indirect, consequential or lost-profit damages), or a time limit for the counterparty to bring claims. +5. **Insurance** (`insurance`): One party must maintain insurance for the benefit of the counterparty. +6. **Liquidated damages** (`liquidated_damages`): Either party can be awarded liquidated damages for breach, or a fee on termination of the contract (a termination fee). +7. **Source code escrow** (`source_code_escrow`): One party must deposit its source code with a third-party escrow agent for release to the counterparty on certain events such as bankruptcy or insolvency. +8. **Non-disparagement** (`non_disparagement`): A party must not disparage the counterparty. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`effective_date`, `renewal_term_months`, `anti_assignment`, `cap_on_liability`, `insurance`, `liquidated_damages`, `source_code_escrow`, `non_disparagement`). diff --git a/tasks/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2/solution/files/answer.json b/tasks/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..3621567456dd7bc3db2802d591e390d4e7e1a2ef --- /dev/null +++ b/tasks/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2/solution/files/answer.json @@ -0,0 +1,10 @@ +{ + "effective_date": "2000-10-06", + "renewal_term_months": 12, + "anti_assignment": "Yes", + "cap_on_liability": "Yes", + "insurance": "No", + "liquidated_damages": "No", + "source_code_escrow": "No", + "non_disparagement": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2/solution/solve.sh b/tasks/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2/task.toml b/tasks/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..636bf829061e492c2a9ace46eeb83947a17cae5a --- /dev/null +++ b/tasks/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "SLOVAKWIRELESSFINANCECOBV_03_28_2001-EX-4.(B)(II).3-Maintenance and support contract for SICAP(R) modules.PDF:effective_date,renewal_term_months,anti_assignment,cap_on_liability,insurance,liquidated_damages,source_code_escrow,non_disparagement" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2/tests/expected.json b/tasks/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..de423896bb0bd7cf8092830fd958a4a3cdfaf0a9 --- /dev/null +++ b/tasks/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2/tests/expected.json @@ -0,0 +1,62 @@ +{ + "checks": [ + { + "id": "effective_date", + "type": "answer", + "field": "effective_date", + "kind": "date", + "value": "2000-10-06" + }, + { + "id": "renewal_term_months", + "type": "answer", + "field": "renewal_term_months", + "kind": "number", + "value": 12, + "abs_tol": 0, + "rel_tol": 0 + }, + { + "id": "anti_assignment", + "type": "answer", + "field": "anti_assignment", + "kind": "bool", + "value": true + }, + { + "id": "cap_on_liability", + "type": "answer", + "field": "cap_on_liability", + "kind": "bool", + "value": true + }, + { + "id": "insurance", + "type": "answer", + "field": "insurance", + "kind": "bool", + "value": false + }, + { + "id": "liquidated_damages", + "type": "answer", + "field": "liquidated_damages", + "kind": "bool", + "value": false + }, + { + "id": "source_code_escrow", + "type": "answer", + "field": "source_code_escrow", + "kind": "bool", + "value": false + }, + { + "id": "non_disparagement", + "type": "answer", + "field": "non_disparagement", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2/tests/grade.py b/tasks/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..b25905557330a4d0f95daffdb53db00a8e326999 --- /dev/null +++ b/tasks/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2/tests/grade.py @@ -0,0 +1,332 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + if type(got) not in (int, float): + return False, f"{key}: expected a JSON number in months" + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2/tests/test.sh b/tasks/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2/validation/openenv.json b/tasks/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-slovakwirelessfinancecobv-03-28-2001-ex--aca6620c-v2/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/environment/inputs/SPIENERGYCO_LTD_03_09_2011-EX-99.5-OPERATIONS_AND_MAINTENANCE_AGREEMENT.pdf b/tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/environment/inputs/SPIENERGYCO_LTD_03_09_2011-EX-99.5-OPERATIONS_AND_MAINTENANCE_AGREEMENT.pdf new file mode 100644 index 0000000000000000000000000000000000000000..958eef41090b593da069e6a750a3d4f33e269005 --- /dev/null +++ b/tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/environment/inputs/SPIENERGYCO_LTD_03_09_2011-EX-99.5-OPERATIONS_AND_MAINTENANCE_AGREEMENT.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1f2579784eea0a2c58583294e7319c070be0b4bdee20811f6adb2defb5eaddb6 +size 140519 diff --git a/tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/instruction.md b/tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6f4721f5915a228fffc7b5d92eb08b72867193fa --- /dev/null +++ b/tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/instruction.md @@ -0,0 +1,21 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/SPIENERGYCO_LTD_03_09_2011-EX-99.5-OPERATIONS_AND_MAINTENANCE_AGREEMENT.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Agreement date** (`agreement_date`): The date of the contract: the date it is dated or entered into, as stated in the document. +2. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +3. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party. +4. **Right of first refusal, offer or negotiation** (`right_of_first_refusal`): One party has a right of first refusal, first offer or first negotiation to purchase, license, market or distribute equity, technology, assets, products or services. +5. **Insurance** (`insurance`): One party must maintain insurance for the benefit of the counterparty. +6. **Non-disparagement** (`non_disparagement`): A party must not disparage the counterparty. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`agreement_date`, `governing_law`, `anti_assignment`, `right_of_first_refusal`, `insurance`, `non_disparagement`). diff --git a/tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/solution/files/answer.json b/tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..0e6ec827f78de6e84150738e26256950159e6676 --- /dev/null +++ b/tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/solution/files/answer.json @@ -0,0 +1,8 @@ +{ + "agreement_date": "2009-12-11", + "governing_law": "California", + "anti_assignment": "Yes", + "right_of_first_refusal": "No", + "insurance": "Yes", + "non_disparagement": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/solution/solve.sh b/tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/task.toml b/tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2a91b67e3e53503a9cea7bf5fc3c2058b0e94583 --- /dev/null +++ b/tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "SPIENERGYCO,LTD_03_09_2011-EX-99.5-OPERATIONS AND MAINTENANCE AGREEMENT.PDF:agreement_date,governing_law,anti_assignment,right_of_first_refusal,insurance,non_disparagement" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/tests/expected.json b/tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..128598f4515a9a8cca6e6c2007eb8cde71eb67fe --- /dev/null +++ b/tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/tests/expected.json @@ -0,0 +1,52 @@ +{ + "checks": [ + { + "id": "agreement_date", + "type": "answer", + "field": "agreement_date", + "kind": "date", + "value": "2009-12-11" + }, + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "California", + "accept": [ + "California", + "State of California", + "California, USA", + "California, United States" + ] + }, + { + "id": "anti_assignment", + "type": "answer", + "field": "anti_assignment", + "kind": "bool", + "value": true + }, + { + "id": "right_of_first_refusal", + "type": "answer", + "field": "right_of_first_refusal", + "kind": "bool", + "value": false + }, + { + "id": "insurance", + "type": "answer", + "field": "insurance", + "kind": "bool", + "value": true + }, + { + "id": "non_disparagement", + "type": "answer", + "field": "non_disparagement", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/tests/grade.py b/tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..f9c9197d521d2bb8a537a6467bf30c433b7bcd26 --- /dev/null +++ b/tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/tests/grade.py @@ -0,0 +1,295 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def same_cell(a, b): + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + if not same_cell(want[sheet][name].value, got[sheet][name].value): + return False, f"{sheet}!{name}: want {want[sheet][name].value!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + ok = number_ok(got, want, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) if got is not None else False + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/tests/test.sh b/tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/validation/openenv.json b/tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77/environment/inputs/STAMPSCOMINC_06_24_1999-EX-10.18-SPONSORSHIP_AGREEMENT.pdf b/tasks/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77/environment/inputs/STAMPSCOMINC_06_24_1999-EX-10.18-SPONSORSHIP_AGREEMENT.pdf new file mode 100644 index 0000000000000000000000000000000000000000..2caf2a5498c313c4dbecd7d866323a80d04e82df Binary files /dev/null and b/tasks/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77/environment/inputs/STAMPSCOMINC_06_24_1999-EX-10.18-SPONSORSHIP_AGREEMENT.pdf differ diff --git a/tasks/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77/instruction.md b/tasks/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..569adc257d98f82e9bf011c77afa793d60c1afb8 --- /dev/null +++ b/tasks/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77/instruction.md @@ -0,0 +1,22 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/STAMPSCOMINC_06_24_1999-EX-10.18-SPONSORSHIP_AGREEMENT.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Agreement date** (`agreement_date`): The date of the contract: the date it is dated or entered into, as stated in the document. +2. **Effective date** (`effective_date`): The date the contract becomes effective or its term commences. +3. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +4. **Cap on liability** (`cap_on_liability`): The contract limits a party's liability for breach: a maximum recoverable amount, an exclusion of categories of damages (for example indirect, consequential or lost-profit damages), or a time limit for the counterparty to bring claims. +5. **Source code escrow** (`source_code_escrow`): One party must deposit its source code with a third-party escrow agent for release to the counterparty on certain events such as bankruptcy or insolvency. +6. **Non-disparagement** (`non_disparagement`): A party must not disparage the counterparty. +7. **License grant** (`license_grant`): One party grants a license to its counterparty. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`agreement_date`, `effective_date`, `governing_law`, `cap_on_liability`, `source_code_escrow`, `non_disparagement`, `license_grant`). diff --git a/tasks/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77/solution/files/answer.json b/tasks/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..c01c83a681afad9c24506824bb3c9e1a5edcbd83 --- /dev/null +++ b/tasks/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77/solution/files/answer.json @@ -0,0 +1,9 @@ +{ + "agreement_date": "1999-05-14", + "effective_date": "1999-05-14", + "governing_law": "California", + "cap_on_liability": "Yes", + "source_code_escrow": "No", + "non_disparagement": "No", + "license_grant": "Yes" +} \ No newline at end of file diff --git a/tasks/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77/solution/solve.sh b/tasks/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77/task.toml b/tasks/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ea859e1432e69e974041c2e4843fffd3789bf40a --- /dev/null +++ b/tasks/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "STAMPSCOMINC_06_24_1999-EX-10.18-SPONSORSHIP AGREEMENT.PDF:agreement_date,effective_date,governing_law,cap_on_liability,source_code_escrow,non_disparagement,license_grant" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77/tests/expected.json b/tasks/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..d5ba956a5845b1c83ba6cc0d4065c4b2dc3ccf7b --- /dev/null +++ b/tasks/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77/tests/expected.json @@ -0,0 +1,59 @@ +{ + "checks": [ + { + "id": "agreement_date", + "type": "answer", + "field": "agreement_date", + "kind": "date", + "value": "1999-05-14" + }, + { + "id": "effective_date", + "type": "answer", + "field": "effective_date", + "kind": "date", + "value": "1999-05-14" + }, + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "California", + "accept": [ + "California", + "State of California", + "California, USA", + "California, United States" + ] + }, + { + "id": "cap_on_liability", + "type": "answer", + "field": "cap_on_liability", + "kind": "bool", + "value": true + }, + { + "id": "source_code_escrow", + "type": "answer", + "field": "source_code_escrow", + "kind": "bool", + "value": false + }, + { + "id": "non_disparagement", + "type": "answer", + "field": "non_disparagement", + "kind": "bool", + "value": false + }, + { + "id": "license_grant", + "type": "answer", + "field": "license_grant", + "kind": "bool", + "value": true + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77/tests/grade.py b/tasks/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77/tests/test.sh b/tasks/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77/validation/openenv.json b/tasks/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-stampscominc-06-24-1999-ex-10-18-sponsor-f2a2db77/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/environment/inputs/StampscomInc_20001114_10-Q_EX-10.47_2631630_EX-10.47_Co-Branding_Agreement.pdf b/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/environment/inputs/StampscomInc_20001114_10-Q_EX-10.47_2631630_EX-10.47_Co-Branding_Agreement.pdf new file mode 100644 index 0000000000000000000000000000000000000000..32ddb3068298e0aec07f577261e3e87e279c18ef --- /dev/null +++ b/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/environment/inputs/StampscomInc_20001114_10-Q_EX-10.47_2631630_EX-10.47_Co-Branding_Agreement.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dba376bec8ed2e068df7609343b413005e2c0facb23ac2d3ed993d23c784ad9c +size 213838 diff --git a/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/instruction.md b/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..158905c6ca223c7c128cb0d49862594605eeb243 --- /dev/null +++ b/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/instruction.md @@ -0,0 +1,22 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/StampscomInc_20001114_10-Q_EX-10.47_2631630_EX-10.47_Co-Branding_Agreement.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Agreement date** (`agreement_date`): The date of the contract: the date it is dated or entered into, as stated in the document. +2. **Renewal term** (`renewal_term_months`): the length of each renewal or extension term that follows the initial term, in months, as a JSON number (for example `12` for one year). +3. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +4. **Cap on liability** (`cap_on_liability`): The contract limits a party's liability for breach: a maximum recoverable amount, an exclusion of categories of damages (for example indirect, consequential or lost-profit damages), or a time limit for the counterparty to bring claims. +5. **Audit rights** (`audit_rights`): A party has the right to audit the books, records or physical locations of the counterparty to check compliance with the contract. +6. **Right of first refusal, offer or negotiation** (`right_of_first_refusal`): One party has a right of first refusal, first offer or first negotiation to purchase, license, market or distribute equity, technology, assets, products or services. +7. **Non-disparagement** (`non_disparagement`): A party must not disparage the counterparty. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`agreement_date`, `renewal_term_months`, `governing_law`, `cap_on_liability`, `audit_rights`, `right_of_first_refusal`, `non_disparagement`). diff --git a/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/solution/files/answer.json b/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..a86a4680b45119e7df3b726d75c438733b3c2380 --- /dev/null +++ b/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/solution/files/answer.json @@ -0,0 +1,9 @@ +{ + "agreement_date": "1999-04-27", + "renewal_term_months": 24, + "governing_law": "California", + "cap_on_liability": "Yes", + "audit_rights": "Yes", + "right_of_first_refusal": "No", + "non_disparagement": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/solution/solve.sh b/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/task.toml b/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8ab049b9dcfd429110264205d42386db014a4ecd --- /dev/null +++ b/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/task.toml @@ -0,0 +1,47 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "StampscomInc_20001114_10-Q_EX-10.47_2631630_EX-10.47_Co-Branding Agreement.pdf:agreement_date,renewal_term_months,governing_law,cap_on_liability,non_compete,audit_rights,right_of_first_refusal,non_disparagement" +task_kind = "single-contract-checklist" + +[metadata.apex_gap.rewrite] +change = "{\"add_conventions\": [], \"correct\": {}, \"evidence\": \"runs/apex-knowledge/task-supply/key-verification/decisions/cuad.json\", \"from\": \"runs/apex-knowledge/wave2/cuad/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c\", \"reason\": \"non_compete: adjudication: key corrected False -> True | adjudicated rewording not used, question removed: definition widened to customer solicitation, which CUAD labels as a separate category\", \"remove\": [\"non_compete\"], \"rewrite\": {}, \"v1_task_id\": \"cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c\"}" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/tests/expected.json b/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..65444e0f6c58220bdc7e54a085959f5a0a832a4d --- /dev/null +++ b/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/tests/expected.json @@ -0,0 +1,61 @@ +{ + "checks": [ + { + "id": "agreement_date", + "type": "answer", + "field": "agreement_date", + "kind": "date", + "value": "1999-04-27" + }, + { + "id": "renewal_term_months", + "type": "answer", + "field": "renewal_term_months", + "kind": "number", + "value": 24, + "abs_tol": 0, + "rel_tol": 0 + }, + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "California", + "accept": [ + "California", + "State of California", + "California, USA", + "California, United States" + ] + }, + { + "id": "cap_on_liability", + "type": "answer", + "field": "cap_on_liability", + "kind": "bool", + "value": true + }, + { + "id": "audit_rights", + "type": "answer", + "field": "audit_rights", + "kind": "bool", + "value": true + }, + { + "id": "right_of_first_refusal", + "type": "answer", + "field": "right_of_first_refusal", + "kind": "bool", + "value": false + }, + { + "id": "non_disparagement", + "type": "answer", + "field": "non_disparagement", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/tests/grade.py b/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/tests/test.sh b/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/validation/openenv.json b/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2/environment/inputs/SteelVaultCorp_20081224_10-K_EX-10.16_3074935_EX-10.16_Affiliate_Agreement.pdf b/tasks/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2/environment/inputs/SteelVaultCorp_20081224_10-K_EX-10.16_3074935_EX-10.16_Affiliate_Agreement.pdf new file mode 100644 index 0000000000000000000000000000000000000000..69b3182d0d250763fccc27f6dae0c8e0cf9e9dcc Binary files /dev/null and b/tasks/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2/environment/inputs/SteelVaultCorp_20081224_10-K_EX-10.16_3074935_EX-10.16_Affiliate_Agreement.pdf differ diff --git a/tasks/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2/instruction.md b/tasks/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6e1110908b26cc76f7aca3084ed22c7fe6fe2e16 --- /dev/null +++ b/tasks/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2/instruction.md @@ -0,0 +1,23 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/SteelVaultCorp_20081224_10-K_EX-10.16_3074935_EX-10.16_Affiliate_Agreement.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Effective date** (`effective_date`): The date the contract becomes effective or its term commences. +2. **Cap on liability** (`cap_on_liability`): The contract limits a party's liability for breach: a maximum recoverable amount, an exclusion of categories of damages (for example indirect, consequential or lost-profit damages), or a time limit for the counterparty to bring claims. +3. **Restrictions on competitor promotions** (`non_compete`): Does the agreement bar the Marketing Affiliate from marketing similar products from competing companies on a landing page containing the Equidata or Marketing Affiliate link? +4. **Most favored nation** (`most_favored_nation`): If a third party gets better terms on the licensing or sale of the technology, goods or services in the contract, the buyer under this contract is entitled to those better terms. +5. **Audit rights** (`audit_rights`): A party has the right to audit the books, records or physical locations of the counterparty to check compliance with the contract. +6. **IP ownership assignment** (`ip_ownership_assignment`): Intellectual property created by one party becomes the property of the counterparty, under the contract terms or on the occurrence of certain events. +7. **Source code escrow** (`source_code_escrow`): One party must deposit its source code with a third-party escrow agent for release to the counterparty on certain events such as bankruptcy or insolvency. +8. **Non-disparagement** (`non_disparagement`): A party must not disparage the counterparty. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`effective_date`, `cap_on_liability`, `non_compete`, `most_favored_nation`, `audit_rights`, `ip_ownership_assignment`, `source_code_escrow`, `non_disparagement`). diff --git a/tasks/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2/solution/files/answer.json b/tasks/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..0d2bcb247ef60050a79c54ab977d2b970ab08404 --- /dev/null +++ b/tasks/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2/solution/files/answer.json @@ -0,0 +1,10 @@ +{ + "effective_date": "2008-10-01", + "cap_on_liability": "Yes", + "non_compete": "Yes", + "most_favored_nation": "No", + "audit_rights": "Yes", + "ip_ownership_assignment": "No", + "source_code_escrow": "No", + "non_disparagement": "No" +} diff --git a/tasks/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2/solution/solve.sh b/tasks/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2/task.toml b/tasks/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..49721d1cb1c246039438bfa9fc75ee25063fcd75 --- /dev/null +++ b/tasks/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "SteelVaultCorp_20081224_10-K_EX-10.16_3074935_EX-10.16_Affiliate Agreement.pdf:effective_date,cap_on_liability,non_compete,most_favored_nation,audit_rights,ip_ownership_assignment,source_code_escrow,non_disparagement" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2/tests/expected.json b/tasks/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..b2cb2902948766cad32a3b5213abc80a03ed09aa --- /dev/null +++ b/tasks/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2/tests/expected.json @@ -0,0 +1,60 @@ +{ + "checks": [ + { + "id": "effective_date", + "type": "answer", + "field": "effective_date", + "kind": "date", + "value": "2008-10-01" + }, + { + "id": "cap_on_liability", + "type": "answer", + "field": "cap_on_liability", + "kind": "bool", + "value": true + }, + { + "id": "non_compete", + "type": "answer", + "field": "non_compete", + "kind": "bool", + "value": true + }, + { + "id": "most_favored_nation", + "type": "answer", + "field": "most_favored_nation", + "kind": "bool", + "value": false + }, + { + "id": "audit_rights", + "type": "answer", + "field": "audit_rights", + "kind": "bool", + "value": true + }, + { + "id": "ip_ownership_assignment", + "type": "answer", + "field": "ip_ownership_assignment", + "kind": "bool", + "value": false + }, + { + "id": "source_code_escrow", + "type": "answer", + "field": "source_code_escrow", + "kind": "bool", + "value": false + }, + { + "id": "non_disparagement", + "type": "answer", + "field": "non_disparagement", + "kind": "bool", + "value": false + } + ] +} diff --git a/tasks/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2/tests/grade.py b/tasks/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2/tests/test.sh b/tasks/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2/validation/openenv.json b/tasks/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab4d83382376835efe9e39522074a971ddd1bad --- /dev/null +++ b/tasks/cuad-dd-steelvaultcorp-20081224-10-k-ex-10-16-30-d51f12bd-v2/validation/openenv.json @@ -0,0 +1,26 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "legal-documents", + "pdf-extraction" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/cuad-dd-sykeshealthplanservicesinc-04-24-1998-ex-3fcbeabc/environment/inputs/SYKESHEALTHPLANSERVICESINC_04_24_1998-EX-10.14-OUTSOURCING_AGREEMENT.pdf b/tasks/cuad-dd-sykeshealthplanservicesinc-04-24-1998-ex-3fcbeabc/environment/inputs/SYKESHEALTHPLANSERVICESINC_04_24_1998-EX-10.14-OUTSOURCING_AGREEMENT.pdf new file mode 100644 index 0000000000000000000000000000000000000000..f69d512d8c23f91b0249c00ac647820298eb1094 Binary files /dev/null and b/tasks/cuad-dd-sykeshealthplanservicesinc-04-24-1998-ex-3fcbeabc/environment/inputs/SYKESHEALTHPLANSERVICESINC_04_24_1998-EX-10.14-OUTSOURCING_AGREEMENT.pdf differ diff --git a/tasks/cuad-dd-sykeshealthplanservicesinc-04-24-1998-ex-3fcbeabc/instruction.md b/tasks/cuad-dd-sykeshealthplanservicesinc-04-24-1998-ex-3fcbeabc/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..95556aa5dd053db5897da873ef0c94c30783eb31 --- /dev/null +++ b/tasks/cuad-dd-sykeshealthplanservicesinc-04-24-1998-ex-3fcbeabc/instruction.md @@ -0,0 +1,23 @@ +You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/SYKESHEALTHPLANSERVICESINC_04_24_1998-EX-10.14-OUTSOURCING_AGREEMENT.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer. + +Answer formats: + +- Dates are strings in `YYYY-MM-DD` form. +- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise. +- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales). + +Checklist: + +1. **Effective date** (`effective_date`): The date the contract becomes effective or its term commences. +2. **Expiration date** (`expiration_date`): The date the initial term ends, before any renewal. +3. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract. +4. **Change of control** (`change_of_control`): One party has the right to terminate, or consent or notice of the counterparty is required, if that party undergoes a change of control (a merger, stock sale, transfer of all or substantially all of its assets or business, or assignment by operation of law). +5. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party. +6. **Non-compete** (`non_compete`): A party is restricted from competing with the counterparty or from operating in a certain geography, business or technology sector. +7. **Audit rights** (`audit_rights`): A party has the right to audit the books, records or physical locations of the counterparty to check compliance with the contract. +8. **Insurance** (`insurance`): One party must maintain insurance for the benefit of the counterparty. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`effective_date`, `expiration_date`, `governing_law`, `change_of_control`, `anti_assignment`, `non_compete`, `audit_rights`, `insurance`). diff --git a/tasks/cuad-dd-sykeshealthplanservicesinc-04-24-1998-ex-3fcbeabc/solution/files/answer.json b/tasks/cuad-dd-sykeshealthplanservicesinc-04-24-1998-ex-3fcbeabc/solution/files/answer.json new file mode 100644 index 0000000000000000000000000000000000000000..953c0e4d3d58dbd95b748707346dd95161c6c832 --- /dev/null +++ b/tasks/cuad-dd-sykeshealthplanservicesinc-04-24-1998-ex-3fcbeabc/solution/files/answer.json @@ -0,0 +1,10 @@ +{ + "effective_date": "1998-01-01", + "expiration_date": "1998-12-31", + "governing_law": "Florida", + "change_of_control": "No", + "anti_assignment": "Yes", + "non_compete": "No", + "audit_rights": "Yes", + "insurance": "No" +} \ No newline at end of file diff --git a/tasks/cuad-dd-sykeshealthplanservicesinc-04-24-1998-ex-3fcbeabc/solution/solve.sh b/tasks/cuad-dd-sykeshealthplanservicesinc-04-24-1998-ex-3fcbeabc/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/cuad-dd-sykeshealthplanservicesinc-04-24-1998-ex-3fcbeabc/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/cuad-dd-sykeshealthplanservicesinc-04-24-1998-ex-3fcbeabc/task.toml b/tasks/cuad-dd-sykeshealthplanservicesinc-04-24-1998-ex-3fcbeabc/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..894ba978ac99c0d6aaf8ca12e28c9f6af812b923 --- /dev/null +++ b/tasks/cuad-dd-sykeshealthplanservicesinc-04-24-1998-ex-3fcbeabc/task.toml @@ -0,0 +1,44 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/cuad-dd-sykeshealthplanservicesinc-04-24-1998-ex-3fcbeabc" + +[metadata.apex_gap] +capability_tags = ["legal-documents", "pdf-extraction"] +job = "corporate-law" +source = "theatticusproject/cuad" +source_license = "CC-BY-4.0" +source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1" +source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)" +source_task_id = "SYKESHEALTHPLANSERVICESINC_04_24_1998-EX-10.14-OUTSOURCING AGREEMENT.PDF:effective_date,expiration_date,governing_law,change_of_control,anti_assignment,non_compete,audit_rights,insurance" +task_kind = "single-contract-checklist" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/cuad-dd-sykeshealthplanservicesinc-04-24-1998-ex-3fcbeabc/tests/expected.json b/tasks/cuad-dd-sykeshealthplanservicesinc-04-24-1998-ex-3fcbeabc/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..cad10a2c307c8931bc2973489341e41b77173b23 --- /dev/null +++ b/tasks/cuad-dd-sykeshealthplanservicesinc-04-24-1998-ex-3fcbeabc/tests/expected.json @@ -0,0 +1,66 @@ +{ + "checks": [ + { + "id": "effective_date", + "type": "answer", + "field": "effective_date", + "kind": "date", + "value": "1998-01-01" + }, + { + "id": "expiration_date", + "type": "answer", + "field": "expiration_date", + "kind": "date", + "value": "1998-12-31" + }, + { + "id": "governing_law", + "type": "answer", + "field": "governing_law", + "kind": "text", + "value": "Florida", + "accept": [ + "Florida", + "State of Florida", + "Florida, USA", + "Florida, United States" + ] + }, + { + "id": "change_of_control", + "type": "answer", + "field": "change_of_control", + "kind": "bool", + "value": false + }, + { + "id": "anti_assignment", + "type": "answer", + "field": "anti_assignment", + "kind": "bool", + "value": true + }, + { + "id": "non_compete", + "type": "answer", + "field": "non_compete", + "kind": "bool", + "value": false + }, + { + "id": "audit_rights", + "type": "answer", + "field": "audit_rights", + "kind": "bool", + "value": true + }, + { + "id": "insurance", + "type": "answer", + "field": "insurance", + "kind": "bool", + "value": false + } + ] +} \ No newline at end of file diff --git a/tasks/cuad-dd-sykeshealthplanservicesinc-04-24-1998-ex-3fcbeabc/tests/grade.py b/tasks/cuad-dd-sykeshealthplanservicesinc-04-24-1998-ex-3fcbeabc/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/cuad-dd-sykeshealthplanservicesinc-04-24-1998-ex-3fcbeabc/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main())