"""Prepare evaluator-owned base/gold/candidate source trees and test materials.""" import argparse import json from pathlib import Path import shutil import subprocess from common import ROOT, contained, load_task, run, sha256 from prepare_workspace import prepare from fetch_sources import fetch def apply_patch(repository, path): run("git", "-C", str(repository), "apply", "--check", str(path)) run("git", "-C", str(repository), "apply", str(path)) def stage(task, output, cache_root, world, candidates=None): output = Path(output).resolve() if output.exists(): raise ValueError(f"Output already exists: {output}") if output.is_relative_to(ROOT) or ROOT.is_relative_to(output): raise ValueError("Evaluator directory must remain outside the release") task_root = contained(ROOT / "instances", task["instance_id"]) contract = json.loads((task_root / task["evaluation"]["path"]).read_text()) if contract["kind"] != "command_contract": raise ValueError("Native contracts require their task-specific adapters; this entry point handles command contracts") candidates = candidates or {} keys = {r["key"] for r in task["repositories"]} if set(candidates) - keys: raise ValueError("Candidate patch references an unknown repository") if world != "candidate" and candidates: raise ValueError("Candidate patches require --world candidate") for ref in task["artifacts"]: path = contained(task_root, ref["path"]) if sha256(path) != ref["sha256"]: raise ValueError(f"Artifact changed: {path}") patch_variants = {} compatibility = task_root / "evaluation/test-preparation.json" if compatibility.is_file(): configuration = json.loads(compatibility.read_text()) if configuration["schema_version"] != 1 or configuration["instance_id"] != task["instance_id"]: raise ValueError("Test preparation contract does not match the task") refs = {ref["path"]: ref for ref in task["artifacts"]} for variant in configuration["patch_variants"]: repo = next((r for r in task["repositories"] if r["key"] == variant["repository"]), None) if not repo or variant["original"] not in repo["test_patches"]: raise ValueError("Compatibility variant is not a declared test patch") key = (repo["key"], variant["original"]["path"]) if key in patch_variants: raise ValueError("Duplicate test compatibility declaration") for alternative in variant["alternatives"]: if refs.get(alternative["path"]) != alternative: raise ValueError("Compatibility test artifact differs") patch_variants[key] = variant["alternatives"] applied_test_variants = [] prepare(task, cache_root, output / "sources") caches = fetch(task, cache_root) files_root = output / "files" files_root.mkdir() mounts = [] for entry in contract["commands"]: if entry.get("evaluation_config"): config = contained(files_root, entry["repository"] + ".evaluation.config.mjs") config.write_text(entry["evaluation_config"]) for repo in task["repositories"]: source = contained(output / "sources", repo["workspace_path"]) # Evaluators may inspect pinned base Git blobs. Import only that shallow # base; prepare_workspace still gives agents an independent history. run("git", "-C", str(source), "fetch", "--depth=1", "--no-tags", str(caches[repo["key"]]), repo["base_commit"]) run("git", "-C", str(source), "checkout", "-B", "main", repo["base_commit"]) if run("git", "-C", str(source), "rev-parse", "HEAD", capture=True).strip() != repo["base_commit"]: raise ValueError("Evaluator base revision differs from pinned source") if world == "gold": apply_patch(source, contained(task_root, repo["gold_patch"]["path"])) elif world == "candidate" and repo["key"] in candidates: apply_patch(source, Path(candidates[repo["key"]]).resolve()) for ref in repo["test_patches"]: choices = [ref, *patch_variants.get((repo["key"], ref["path"]), [])] selected = None for choice in choices: path = contained(task_root, choice["path"]) checked = subprocess.run(["git", "-C", str(source), "apply", "--check", str(path)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) if checked.returncode == 0: apply_patch(source, path) selected = choice break if selected is None: raise ValueError(f"Frozen test patch and its declared compatibility variants do not apply: {ref['path']}") applied_test_variants.append({"repository": repo["key"], "original": ref["path"], "applied": selected["path"]}) mounts.append({"source": str(source), "target": repo["container_path"], "read_only": False}) for ref in contract["test_files"]: source = contained(task_root, ref["path"]) if ref.get("original_container_path"): target = contained(output / "image-probes", ref["path"]) target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(source, target) target.chmod(0o755) mounts.append({"source": str(target), "target": ref["original_container_path"], "read_only": True}) else: name = ref.get("original_path") if not name: raise ValueError(f"No container layout supplied for {ref['path']}") target = contained(files_root, name) target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(source, target) if target.suffix == ".sh": target.chmod(0o755) mounts.append({"source": str(files_root), "target": "/crossrepo-patches", "read_only": True}) contract["evaluation_world"] = {"base": "all_buggy", "gold": "all_fixed", "candidate": "candidate"}[world] (output / "contract.json").write_text(json.dumps(contract, indent=2) + "\n") (output / "mounts.json").write_text(json.dumps(mounts, indent=2) + "\n") (output / "preparation.json").write_text(json.dumps({"instance_id": task["instance_id"], "world": world, "contract_sha256": sha256(output / "contract.json"), "test_patch_applications": applied_test_variants, "source_histories": "Shallow pinned base objects imported only in evaluator sources; reference/test patches applied only here. Agent sources retain independent histories."}, indent=2) + "\n") return output def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--instance-id", required=True) parser.add_argument("--output-dir", type=Path, required=True) parser.add_argument("--source-cache", type=Path) parser.add_argument("--world", choices=["base", "gold", "candidate"], default="base") parser.add_argument("--candidate-patches", type=Path, help="JSON object mapping repository keys to patch paths; relative paths use the JSON file's directory") args = parser.parse_args() candidates = None if args.candidate_patches: values = json.loads(args.candidate_patches.read_text()) candidates = {key: str((args.candidate_patches.resolve().parent / value).resolve()) for key, value in values.items()} task = load_task(args.instance_id) stage(task, args.output_dir, args.source_cache or ROOT / ".cache/source-repos" / task["instance_id"], args.world, candidates) if __name__ == "__main__": main()