"""Outcome-blind runtime and executor preflight for frozen E09.""" from __future__ import annotations from dataclasses import asdict from hashlib import sha256 import importlib.metadata import json import platform from pathlib import Path import shutil import subprocess import sys import tempfile import time from typing import Any from agent_harness.lm_studio import LMStudioClient from agent_harness.lm_studio_management import LMStudioResidencyManager, LMStudioServer from agent_harness.pilot import research_code_revision from agent_harness.protocol_experiment import ProtocolWorkspace from agent_harness.specs import ( load_edit_interfaces, load_experiments, load_models, load_repositories, load_task_split, load_tasks, validate_configuration_tree, ) from agent_harness.study2_experiment import tokenizer_for PACKAGES = ("numpy", "pytest", "scipy", "statsmodels", "tokenizers") def _command(arguments: list[str], cwd: Path | None = None) -> dict[str, Any]: result = subprocess.run( arguments, cwd=cwd, text=True, capture_output=True, check=False, timeout=180, ) return { "command": arguments, "returncode": result.returncode, "stdout": result.stdout, "stderr": result.stderr, } def _tool_probe(client: LMStudioClient, model_key: str) -> dict[str, Any]: response = client.chat_completions( model_key, [ { "role": "system", "content": "This is an outcome-blind runtime preflight. Call the required tool once.", }, { "role": "user", "content": "Call preflight_echo with marker MODEL_TOOL_OK. Do not answer in prose.", }, ], tools=[ { "type": "function", "function": { "name": "preflight_echo", "description": "Return the exact requested runtime marker.", "parameters": { "type": "object", "properties": {"marker": {"type": "string"}}, "required": ["marker"], "additionalProperties": False, }, }, } ], max_tokens=2_048, seed=0, ) try: message = response["choices"][0]["message"] function = message["tool_calls"][0]["function"] raw = function["arguments"] arguments = raw if isinstance(raw, dict) else json.loads(raw) except (KeyError, IndexError, TypeError, json.JSONDecodeError) as exc: raise RuntimeError("model did not return a valid preflight tool call") from exc if function.get("name") != "preflight_echo" or arguments != { "marker": "MODEL_TOOL_OK" }: raise RuntimeError(f"unexpected tool preflight payload: {function}") serialized = json.dumps(response, sort_keys=True, separators=(",", ":")) return { "tool_name": function["name"], "arguments": arguments, "finish_reason": response["choices"][0].get("finish_reason"), "usage": response.get("usage", {}), "response_sha256": sha256(serialized.encode()).hexdigest(), } def _executor_conformance(root: Path) -> dict[str, Any]: task = load_tasks(root)["TASK_CR_001"] interfaces = load_edit_interfaces(root) with tempfile.TemporaryDirectory(prefix="agent-harness-e09-preflight-") as temporary: tree = Path(temporary) target = tree / "example.go" target.write_text("package example\n\nconst value = 1\n", encoding="utf-8") for arguments in (["git", "init", "-q"], ["git", "add", "example.go"]): result = _command(arguments, tree) if result["returncode"]: raise RuntimeError(f"executor preflight git setup failed: {result}") records: dict[str, Any] = {} patch_workspace = ProtocolWorkspace(tree, ("example.go",), task, 2) patch = """--- a/example.go +++ b/example.go @@ -1,3 +1,3 @@ package example -const value = 1 +const value = 2 """ patch_result = patch_workspace.apply_patch(patch) if not patch_result["accepted"]: raise RuntimeError(f"P001 executor conformance failed: {patch_result}") records["P001"] = { "interface": asdict(interfaces["P001"]), "accepted": True, "final_patch_sha256": sha256( patch_workspace.final_patch().encode() ).hexdigest(), } target.write_text("package example\n\nconst value = 1\n", encoding="utf-8") replace_workspace = ProtocolWorkspace(tree, ("example.go",), task, 2) replace_result = replace_workspace.replace_text( "example.go", "value = 1", "value = 2" ) records["P002"] = { "interface": asdict(interfaces["P002"]), "accepted": replace_result["accepted"], "final_patch_sha256": sha256( replace_workspace.final_patch().encode() ).hexdigest(), } target.write_text("package example\n\nconst value = 1\n", encoding="utf-8") write_workspace = ProtocolWorkspace(tree, ("example.go",), task, 2) write_result = write_workspace.write_file( "example.go", "package example\n\nconst value = 2\n" ) records["P003"] = { "interface": asdict(interfaces["P003"]), "accepted": write_result["accepted"], "final_patch_sha256": sha256( write_workspace.final_patch().encode() ).hexdigest(), } if not all(record["accepted"] for record in records.values()): raise RuntimeError(f"an edit executor failed deterministic conformance: {records}") return records def run(root: Path) -> dict[str, Any]: revision = research_code_revision(root) errors, warnings = validate_configuration_tree(root) if errors or warnings: raise RuntimeError(f"configuration failed: errors={errors}, warnings={warnings}") if (root / "results" / "raw" / "E09").exists(): raise RuntimeError("E09 raw directory exists before outcome-blind preflight") audit = json.loads((root / "docs" / "STUDY3_DESIGN_AUDIT.json").read_text()) if audit.get("planned_cells") != 540 or not audit.get("outcome_blind"): raise RuntimeError("Study 3 design audit is not a valid 540-cell freeze") experiment = load_experiments(root)["E09"] split = load_task_split(root / "tasks" / "splits" / "study3_protocol.txt") if experiment.cells_per_task() * len(split) != 540: raise RuntimeError("E09 execution plan is not exactly 540 cells") disk = shutil.disk_usage(root) if disk.free < 20 * 1024**3: raise RuntimeError(f"less than 20 GiB free before Study 3: {disk.free} bytes") models = load_models(root) repositories = load_repositories(root) server = LMStudioServer(port=1234) server_state = server.ensure_running() residency = LMStudioResidencyManager( models["M002"].base_url, models["M002"].api_token_env, timeout_seconds=1_800, ) report: dict[str, Any] = { "schema_version": 1, "study": "Study 3 / E09", "outcome_blind": True, "research_code_revision": revision, "design_sha256": audit["design_sha256"], "planned_cells": 540, "started_unix": time.time(), "platform": platform.platform(), "python": sys.version, "torch_used": False, "disk": {"total": disk.total, "used": disk.used, "free": disk.free}, "lms_version": _command([str(server.cli_path), "--version"]), "server_start": server_state, "dependencies": { package: importlib.metadata.version(package) for package in PACKAGES }, "executor_conformance": _executor_conformance(root), "repositories": {}, "models": {}, } try: residency.unload_all() for repository_id, repository in sorted(repositories.items()): observed = _command( ["git", "rev-parse", "HEAD"], cwd=root / repository.local_path ) if observed["returncode"] or observed["stdout"].strip() != repository.pinned_head: raise RuntimeError(f"repository head mismatch: {repository_id}: {observed}") report["repositories"][repository_id] = { "spec": asdict(repository), "observed_head": observed["stdout"].strip(), } for model_id in experiment.model_ids: model = models[model_id] transition = residency.ensure_exclusive( model.expected_inference_key, model.context_length ) client = LMStudioClient(model, timeout_seconds=1_800) discovery, resolved = client.resolve() tokenizer = tokenizer_for(model) report["models"][model_id] = { "spec": asdict(model), "config_hash": model.config_hash, "transition": transition.to_dict(), "resolved": resolved.to_dict(), "discovery_errors": discovery.endpoint_errors, "tokenizer_path": str(tokenizer.path), "tokenizer_sha256": tokenizer.sha256, "tool_probe": _tool_probe(client, resolved.inference_key), "unload": residency.unload_all().to_dict(), } report["passed"] = True return report finally: cleanup_errors: list[str] = [] try: report["final_unload"] = residency.unload_all().to_dict() except Exception as cleanup_error: cleanup_errors.append(f"unload_all: {cleanup_error}") try: status = server.status() report["server_stop"] = ( server.stop() if status["running"] else {"action": "already_stopped", "status": status} ) except Exception as cleanup_error: cleanup_errors.append(f"server_stop: {cleanup_error}") report["cleanup_errors"] = cleanup_errors report["finished_unix"] = time.time() def main() -> None: root = Path(__file__).resolve().parents[1] output = root / "results" / "reports" / "study3_preflight.json" output.parent.mkdir(parents=True, exist_ok=True) report: dict[str, Any] = {} try: report = run(root) except Exception as exc: report = {**report, "passed": False, "error": repr(exc)} output.write_text( json.dumps(report, indent=2, sort_keys=True, default=str) + "\n", encoding="utf-8", ) raise output.write_text( json.dumps(report, indent=2, sort_keys=True, default=str) + "\n", encoding="utf-8", ) print(json.dumps({"passed": True, "report": str(output)}, indent=2)) if __name__ == "__main__": main()