File size: 4,487 Bytes
0e239c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
"""Run a command contract inside its prepared evaluation container."""
import argparse
import json
import os
from pathlib import Path
import subprocess
import time


def execute(contract, output, environment_setup=None):
    if contract["kind"] != "command_contract":
        raise ValueError("Native contracts require a task-specific adapter")
    output = Path(output)
    output.mkdir(parents=True, exist_ok=True)
    commands = contract["commands"]
    def ordered_by(field):
        return sorted(enumerate(commands), key=lambda item: (
            item[1][field] if item[1].get(field) is not None else item[0], item[0]))
    source_order = ordered_by("setup_order")
    ordered = ordered_by("evaluation_setup_order")
    records = []
    infrastructure_failed = False
    tests_failed = False

    def command(entry, phase, text, cwd=None):
        if not text:
            return True
        environment = dict(os.environ)
        environment.update({key: str(value) for key, value in (entry.get("environment") or {}).items()})
        text = text.replace("{{WORLD}}", contract["evaluation_world"])
        working = cwd or entry.get("test_cwd") or entry["container_path"]
        filename = f"{len(records):03d}-{entry['repository']}-{phase}.log"
        started = time.time()
        try:
            with (output / filename).open("w") as log:
                process = subprocess.run(["/bin/bash", "-o", "pipefail", "-c", text], cwd=working,
                    env=environment, stdout=log, stderr=subprocess.STDOUT, timeout=3600)
            code = process.returncode
        except (OSError, subprocess.TimeoutExpired) as error:
            with (output / filename).open("a") as log:
                log.write(str(error) + "\n")
            code = 125
        records.append({"repository": entry["repository"], "phase": phase, "exit_code": code,
                        "elapsed_seconds": round(time.time() - started, 3), "log": filename})
        return code == 0

    try:
        if environment_setup and not command({"repository": "environment", "container_path": "/"},
                                             "environment-setup", environment_setup):
            infrastructure_failed = True
        for _, entry in (source_order if not infrastructure_failed else []):
            if not command(entry, "source-setup", entry.get("setup_command"), entry["container_path"]):
                infrastructure_failed = True
                break
        if not infrastructure_failed:
            for _, entry in ordered:
                if not command(entry, "evaluation-setup", entry.get("evaluation_setup_command"), entry.get("evaluation_setup_cwd")):
                    infrastructure_failed = True
                    break
        if not infrastructure_failed:
            for _, entry in ordered:
                if not command(entry, "ready", entry.get("evaluation_ready_command")):
                    infrastructure_failed = True
        if not infrastructure_failed:
            for phase in ("pass_to_pass", "fail_to_pass"):
                for entry in commands:
                    if not command(entry, phase, entry.get(phase)):
                        tests_failed = True
    finally:
        for _, entry in reversed(ordered):
            if not command(entry, "teardown", entry.get("evaluation_teardown_command")):
                infrastructure_failed = True
        summary = {"instance_id": contract["instance_id"], "evaluation_world": contract["evaluation_world"],
                   "infrastructure_failed": infrastructure_failed, "test_commands_failed": tests_failed, "verdict_scope": "Command execution only; native case inventories and task-specific acceptance rules must be checked separately.", "commands": records}
        (output / "summary.json").write_text(json.dumps(summary, indent=2) + "\n")
    # Exit codes alone are execution evidence, not a native case inventory verdict.
    return 2 if infrastructure_failed else 1 if tests_failed else 0


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--contract", type=Path, required=True)
    parser.add_argument("--output-dir", type=Path, required=True)
    parser.add_argument("--environment-setup", help="Verified task environment preparation command; runs before frozen source setup")
    args = parser.parse_args()
    raise SystemExit(execute(json.loads(args.contract.read_text()), args.output_dir, args.environment_setup))