"""Frozen native task identities; no Toolathlon finalpool aliases.""" from __future__ import annotations from collections import Counter import json from pathlib import Path from ..common import sha256_file from ..red_plan import atomic_json, digest SUITES = {"gaia2": 11, "appworld": 9, "healthagent-text25": 3, "medagent-original": 4, "tau-banking": 3} CHANNELS = ("workspace", "skill_plugin_spec", "tool_call", "tool_response") from manipulationarena.deployment import native_image IMAGE = native_image() MED_INDICES = {"task1_22": 21, "task2_15": 44, "task3_14": 73, "task4_11": 100} def load_campaign(root: Path, *, verify_inputs=True) -> dict: from .evidence import regular if (root / "RELOCATED.json").exists(): raise ValueError("prepared campaign moved to " + json.loads((root / "RELOCATED.json").read_text())["destination"]) campaign = json.loads(regular(root, "campaign.json").read_text()) identity = {k:v for k,v in campaign.items() if k not in {"root", "campaign_id"}} if campaign.get("schema_version") != "benign30-campaign-v1" or digest(identity) != campaign.get("campaign_id"): raise ValueError("campaign identity changed") if verify_inputs: for name,key in (("catalog.json", "catalog_sha256"), ("profiles.json", "profiles_sha256")): if sha256_file(regular(root, name)) != campaign[key]:raise ValueError("campaign input changed: " + name) for name,sha in campaign["request_hashes"].items(): if sha256_file(regular(root, "requests/" + name)) != sha:raise ValueError("campaign request changed") for name,sha in campaign["control_request_hashes"].items(): if sha256_file(regular(root, name)) != sha:raise ValueError("campaign control request changed") return campaign def relocate_prepared(source: Path, destination: Path) -> dict: """Copy an unstarted campaign, verify it, then retire the old location.""" import shutil import uuid campaign = load_campaign(source) if (source / "collection.sqlite3").exists() or (source / "attempts").exists(): raise ValueError("relocation is restricted to prepared, unstarted campaigns") if destination.exists():raise FileExistsError(destination) if source.resolve() in destination.resolve().parents:raise ValueError("destination is inside source") if any(p.is_symlink() for p in source.rglob("*")):raise ValueError("campaign links need explicit resolution") destination.parent.mkdir(parents=True, exist_ok=True, mode=0o700) staging = destination.with_name(".relocating-" + uuid.uuid4().hex) shutil.copytree(source, staging) for p in source.rglob("*"): if p.is_file() and sha256_file(staging / p.relative_to(source)) != sha256_file(p): raise ValueError("campaign copy differs") campaign["root"] = str(destination.resolve()) atomic_json(staging / "campaign.json", campaign) load_campaign(staging) staging.rename(destination) receipt = {"schema_version": "benign30-prepared-relocation-v1", "source": str(source.resolve()), "destination": str(destination.resolve()), "campaign_id": campaign["campaign_id"], "started_attempts": 0} atomic_json(source / "RELOCATED.json", receipt) return receipt def load_catalog(path: Path, expected_sha: str | None = None) -> dict: if path.is_symlink() or not path.is_file():raise ValueError("catalog must be a regular file") if expected_sha is not None and sha256_file(path) != expected_sha:raise ValueError("source catalog changed") value = json.loads(path.read_text());tasks = value.get("tasks", []) if value.get("count") != 30 or len(tasks) != 30:raise ValueError("expected exactly 30 tasks") if Counter(row.get("suite") for row in tasks) != SUITES:raise ValueError("native suite counts differ") if len({row.get("qualified_id") for row in tasks}) != 30:raise ValueError("duplicate qualified task") for row in tasks: task = row.get("task_id") if not isinstance(task, str) or not task or any(c in task for c in "/\\\n\r") or task in {".", ".."}: raise ValueError("unsafe native task id") if row["qualified_id"] != f"{row['suite']}/{task}":raise ValueError("qualified task id differs") if row["suite"] == "medagent-original" and row.get("native_index") != MED_INDICES.get(task): raise ValueError("Med zero-based native index differs") return value def load_plan(path: Path) -> tuple[dict, dict]: plan = json.loads(path.read_text()) if plan.get("schema_version") != "toolathlon-benign30-fm140-plan-v1":raise ValueError("unsupported collection plan") if plan.get("accepted_case_target") != 140:raise ValueError("expected 140 unique positive cases") if plan["source_image"]["pinned"] != IMAGE:raise ValueError("unreviewed task image") ref = plan["source_manifest"];catalog = load_catalog(Path(ref["path"]), ref["sha256"]) tasks = {row["qualified_id"]: row for row in catalog["tasks"]};slots = plan["slots"] if len(slots) != 140 or len({s["slot_id"] for s in slots}) != 140:raise ValueError("expected 140 unique slots") for slot in slots: if slot["qualified_task_id"] not in tasks or slot["preferred_channel"] not in CHANNELS: raise ValueError("unknown slot task/channel") if not isinstance(slot["slot_id"], str) or any(c in slot["slot_id"] for c in "/\\\n\r"): raise ValueError("unsafe slot id") actual = Counter((s["qualified_task_id"], s["preferred_channel"]) for s in slots) if len(plan["tasks"]) != 30 or {r["qualified_id"] for r in plan["tasks"]} != set(tasks):raise ValueError("plan task identities differ") for row in plan["tasks"]: for channel in CHANNELS: if actual[row["qualified_id"], channel] != row["preferred_channel_targets"][channel]:raise ValueError("slot allocation differs") return plan, catalog def compile_campaign(plan_path: Path, output: Path, profiles: dict, *, attempt_budget: int = 280) -> dict: """Materialize native requests without service or model activity.""" if output.exists():raise FileExistsError("refusing to replace a campaign") if type(attempt_budget) is not int or attempt_budget < 1:raise ValueError("attempt budget must be positive") plan, catalog = load_plan(plan_path) from ..training_evidence import sanitize_training_value if sanitize_training_value(profiles) != profiles:raise ValueError("sensitive profile values") for role in ("red", "blue", "judge"): profile = profiles.get(role) if not isinstance(profile, dict):raise ValueError(f"missing independent {role} profile") if any(key in profile for key in ("api_key", "authorization", "token", "password")):raise ValueError("credential values are forbidden") for field in ("model", "model_api_url", "model_env_file"): if not isinstance(profile.get(field), str) or not profile[field]:raise ValueError(f"{role} profile lacks {field}") from .native import freeze_model_roles profiles = freeze_model_roles(profiles) all_profiles = list(profiles.values()) + [p for r in profiles.values() for p in r.get("suite_profiles", {}).values()] for profile in all_profiles: if not isinstance(profile, dict):raise ValueError("invalid role profile") for key in ("provider", "model", "model_api_url", "model_env_file"): if not isinstance(profile.get(key), str) or not profile[key]:raise ValueError("incomplete role profile") from urllib.parse import urlsplit endpoint = urlsplit(profile.get("model_api_url", "")) if endpoint.scheme not in {"http", "https"} or not endpoint.netloc or endpoint.username or endpoint.password or endpoint.query or endpoint.fragment: raise ValueError("model endpoints must be credential-free HTTP URLs") output.mkdir(parents=True, mode=0o700);atomic_json(output / "catalog.json", catalog);atomic_json(output / "profiles.json", profiles) tasks = {r["qualified_id"]: r for r in catalog["tasks"]} for row in catalog["tasks"]: atomic_json(output / "controls" / row["suite"] / (row["task_id"] + ".request.json"), { "schema_version": "benign30-native-request-v1", "mode": "control", "image": IMAGE, "suite": row["suite"], "task_id": row["task_id"], "qualified_id": row["qualified_id"], "task": row, "automatic_blue_retries": 0, "profiles_sha256": sha256_file(output / "profiles.json"), "native_budget": next(r["native_resource_and_budget_evidence"] for r in plan["tasks"] if r["qualified_id"] == row["qualified_id"])}) for slot in plan["slots"]: row = tasks[slot["qualified_task_id"]] request = {"schema_version": "benign30-native-request-v1", "image": IMAGE, "suite": row["suite"], "task_id": row["task_id"], "qualified_id": row["qualified_id"], "slot_id": slot["slot_id"], "preferred_channel": slot["preferred_channel"], "planning_variant": {"slot_id": slot["slot_id"], "variant_index": slot["variant_index"], "goal": slot["configuration_proposal"]["online_attacker"]["planning_variant"]["goal"]}, "task": row, "profiles_ref": "profiles.json", "mode": "discovery", "native_budget": next(r["native_resource_and_budget_evidence"] for r in plan["tasks"] if r["qualified_id"] == row["qualified_id"]), "automatic_blue_retries": 0, "memory_namespace": f"{row['suite']}/{row['task_id']}/{slot['preferred_channel']}/v{slot['variant_index']:02d}"} request["profiles_sha256"] = sha256_file(output / "profiles.json") atomic_json(output / "requests" / f"{slot['slot_id']}.json", request) document = {"schema_version": "benign30-campaign-v1", "image": IMAGE, "target": 140, "plan_sha256": sha256_file(plan_path), "catalog_sha256": sha256_file(output / "catalog.json"), "profiles_sha256": sha256_file(output / "profiles.json"), "attempt_budget": attempt_budget, "slots": plan["slots"], "task_count": 30, "root": str(output.resolve()), "pilot_slot_ids": plan["pilot_slot_ids"], "channel_semantics": plan["channel_semantics"], "fixture_only": False, "control_request_hashes": {p.relative_to(output).as_posix():sha256_file(p) for p in sorted((output / "controls").rglob("*.request.json"))}, "request_hashes": {p.name: sha256_file(p) for p in sorted((output / "requests").glob("*.json"))}} document["campaign_id"] = digest({k:v for k,v in document.items() if k != "root"}) atomic_json(output / "campaign.json", document) return document