#!/usr/bin/env python3 """Materialize a gold-free filesystem root for GeoDisaster test execution.""" from __future__ import annotations import argparse import hashlib import json import os import shutil from collections import defaultdict from pathlib import Path from typing import Any from eval_isolation import ( DEFAULT_OUTPUT, ROOT, agent_input_surface, audit_agent_rows, path_entries, private_path, read_jsonl, ) def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as stream: for block in iter(lambda: stream.read(1024 * 1024), b""): digest.update(block) return digest.hexdigest() def inside(path: Path, parent: Path) -> bool: try: path.relative_to(parent) return True except ValueError: return False def safe_relative(path_value: str) -> Path: relative = Path(path_value) if relative.is_absolute() or ".." in relative.parts: raise ValueError(f"unsafe declared path: {path_value}") if private_path(path_value): raise ValueError(f"private path reached bundle builder: {path_value}") return relative def validate_public_question_json(path: Path, relative: Path) -> None: """Reject legacy private hints in a question sidecar before packaging.""" if path.suffix.lower() != ".json" or "questions" not in relative.parts: return payload = json.loads(path.read_text(encoding="utf-8")) forbidden = { "aoi_type_hidden", "gt_path_hidden", "gt_link", "oracle_trajectory_link", "expected_final_answer", "final_answer", } def walk(value: Any, prefix: str = "") -> list[str]: found: list[str] = [] if isinstance(value, dict): for key, child in value.items(): field = f"{prefix}.{key}" if prefix else str(key) if key in forbidden: found.append(field) found.extend(walk(child, field)) elif isinstance(value, list): for index, child in enumerate(value): found.extend(walk(child, f"{prefix}[{index}]")) return found violations = walk(payload) if violations: raise ValueError(f"private fields in public question sidecar {relative}: {violations}") def declared_files(source_root: Path, rows: list[dict[str, Any]]) -> tuple[dict[Path, set[str]], list[str]]: selected: dict[Path, set[str]] = defaultdict(set) missing_optional: set[str] = set() missing_required: set[str] = set() for row in rows: record_id = str(row["id"]) for entry in path_entries(agent_input_surface(row)): relative = safe_relative(str(entry["path"])) source = source_root / relative optional = bool(entry.get("optional")) if not source.exists(): (missing_optional if optional else missing_required).add(relative.as_posix()) continue if source.is_symlink(): raise ValueError(f"symlinks are not allowed in an isolated bundle: {relative}") if source.is_file(): validate_public_question_json(source, relative) selected[relative].add(record_id) continue if not source.is_dir(): raise ValueError(f"unsupported declared input type: {relative}") for candidate in source.rglob("*"): if not candidate.is_file(): continue child = candidate.relative_to(source_root) if candidate.is_symlink(): raise ValueError(f"symlinks are not allowed in an isolated bundle: {child}") if private_path(child.as_posix()): continue selected[child].add(record_id) if missing_required: raise RuntimeError(f"required inputs missing: {sorted(missing_required)[:10]}") return dict(selected), sorted(missing_optional) def install_file(source: Path, destination: Path, mode: str) -> None: destination.parent.mkdir(parents=True, exist_ok=True) if mode == "hardlink": os.link(source, destination) else: shutil.copy2(source, destination) def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--source-root", type=Path, default=ROOT) parser.add_argument("--inputs", type=Path, default=DEFAULT_OUTPUT) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--mode", choices=("copy", "hardlink"), default="copy") args = parser.parse_args() source_root = args.source_root.resolve() output = args.output.resolve() if output == source_root or inside(output, source_root) or inside(source_root, output): raise ValueError("--output must be separate from, and not contain, the source repository") if output.exists() and any(output.iterdir()): raise ValueError("--output must not exist or must be empty") output.mkdir(parents=True, exist_ok=True) rows = read_jsonl(args.inputs.resolve()) audit = audit_agent_rows(rows) if not audit["ready"]: raise RuntimeError(f"agent-visible input audit failed: {audit}") files, missing_optional = declared_files(source_root, rows) manifest_entries = [] for relative in sorted(files, key=lambda item: item.as_posix()): source = source_root / relative destination = output / relative install_file(source, destination, args.mode) manifest_entries.append( { "path": relative.as_posix(), "bytes": source.stat().st_size, "sha256": sha256(source), "declared_by": sorted(files[relative]), } ) input_destination = output / "data/core/geodisaster_2921_test_inputs.jsonl" install_file(args.inputs.resolve(), input_destination, args.mode) manifest = { "schema_version": "geodisaster_isolated_test_bundle_v1", "records": len(rows), "files": len(manifest_entries), "bytes": sum(entry["bytes"] for entry in manifest_entries), "missing_optional_paths": missing_optional, "strict_runtime_environment": { "GEODISASTER_DATASET_ROOT": str(output), "GEODISASTER_STRICT_DATA_ROOT": "1", }, "input_audit": audit, "entries": manifest_entries, } manifest_path = output / "evaluation_bundle_manifest.json" manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8") print( json.dumps( { "output": str(output), "records": len(rows), "files": len(manifest_entries), "bytes": manifest["bytes"], "missing_optional": len(missing_optional), "private_paths": len(audit["private_declared_paths"]), "ready": True, }, indent=2, ) ) if __name__ == "__main__": main()