Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(verse): add the Unreal wrapper scripts, machine lock and toolchain doctor (#1121)
Ruben Lütke528e5e97765b
diff --git a/scripts/unreal/_common.py b/scripts/unreal/_common.pynew file mode 100644index 0000000000..7034301850--- /dev/null+++ b/scripts/unreal/_common.py@@ -0,0 +1,154 @@+"""Shared paths, limits and helpers of the Unreal wrapper scripts.++Every build, test, capture and cook of the Unreal Verse goes through+``scripts/unreal/*.py`` (docs/verse/unreal/orchestration.md 0.5 and 3.3).+This module holds what they share: where the engine, the project and the+toolchain pins are, the machine limits of orchestration.md section 4, and a+small ``run`` helper the tests replace.+"""++from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+import time+from collections.abc import Mapping, Sequence+from dataclasses import dataclass+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parents[2]+UNREAL_ROOT = REPO_ROOT / "unreal"+PROJECT_DIR = UNREAL_ROOT / "Verse"+PROJECT_FILE = PROJECT_DIR / "Verse.uproject"+TOOLCHAINS_FILE = UNREAL_ROOT / "Toolchain" / "toolchains.json"++#: Machine limits, orchestration.md section 4 (start values until step 0.8).+LOCK_HOLDERS = 1+MAX_PARALLEL_ACTIONS = 10+MAX_HEADLESS_JOBS = 4+MAX_RENDERED_JOBS = 1+MIN_FREE_GB = 40+MAX_HOLD_MINUTES = 90+QUEUE_DEPTH_WARN = 8++#: Build output folders of one worktree; the shared DDC is never among them.+BUILD_OUTPUT_DIRS = ("Binaries", "Intermediate", "Saved")++ENGINE_ENV = "DODAIOS_UE_ROOT"+DEFAULT_ENGINE_ROOT = Path("C:/Program Files/Epic Games/UE_5.7")+++class UnrealScriptError(RuntimeError):+ """A wrapper script cannot do what it was asked; the message says why."""+++@dataclass(frozen=True)+class Completed:+ returncode: int+ stdout: str = ""+ stderr: str = ""+++def log(message: str) -> None:+ print(f"[unreal] {message}", flush=True)+++def load_toolchains(path: Path = TOOLCHAINS_FILE) -> dict:+ return json.loads(path.read_text(encoding="utf-8"))+++def engine_root(env: Mapping[str, str] | None = None) -> Path:+ """The Unreal install: ``DODAIOS_UE_ROOT`` when set, else the pinned default."""+ env = os.environ if env is None else env+ override = env.get(ENGINE_ENV, "").strip()+ if override:+ return Path(override)+ try:+ pinned = load_toolchains()["engine"]["windows_root"]+ except (OSError, KeyError, ValueError):+ return DEFAULT_ENGINE_ROOT+ return Path(pinned)+++def build_bat(root: Path) -> Path:+ return root / "Engine" / "Build" / "BatchFiles" / "Build.bat"+++def run_uat_bat(root: Path) -> Path:+ return root / "Engine" / "Build" / "BatchFiles" / "RunUAT.bat"+++def editor_cmd(root: Path) -> Path:+ return root / "Engine" / "Binaries" / "Win64" / "UnrealEditor-Cmd.exe"+++def project_file(worktree: Path = REPO_ROOT) -> Path:+ return worktree / "unreal" / "Verse" / "Verse.uproject"+++def current_branch(worktree: Path = REPO_ROOT) -> str:+ result = run(["git", "-C", str(worktree), "rev-parse", "--abbrev-ref", "HEAD"], capture=True)+ name = result.stdout.strip() if result.returncode == 0 else ""+ return name or "detached"+++def safe_name(text: str) -> str:+ """A string usable as one folder name (branch slashes become dashes)."""+ cleaned = "".join(ch if ch.isalnum() or ch in "-_." else "-" for ch in text)+ return cleaned.strip("-.") or "run"+++def run_stamp() -> str:+ return time.strftime("%Y%m%d-%H%M%S")+++def free_gb(path: Path) -> float:+ probe = path+ while not probe.exists() and probe != probe.parent:+ probe = probe.parent+ return shutil.disk_usage(probe).free / 1e9+++def require_free_disk(path: Path, minimum: float = MIN_FREE_GB) -> None:+ free = free_gb(path)+ if free < minimum:+ raise UnrealScriptError(+ f"only {free:.1f} GB free on the drive of {path}; builds need {minimum} GB. "+ "Ask the orchestrator to clean merged worktrees (worktree.py remove)."+ )+++def run(+ command: Sequence[str],+ *,+ cwd: Path | None = None,+ env: Mapping[str, str] | None = None,+ capture: bool = False,+ timeout: float | None = None,+) -> Completed:+ """Run one command; the tests replace this function."""+ try:+ result = subprocess.run(+ list(command),+ cwd=str(cwd) if cwd else None,+ env=dict(env) if env is not None else None,+ capture_output=capture,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=timeout,+ check=False,+ )+ except FileNotFoundError as exc:+ return Completed(127, "", str(exc))+ except subprocess.TimeoutExpired:+ return Completed(124, "", f"timed out after {timeout} s")+ return Completed(result.returncode, result.stdout or "", result.stderr or "")+++def exit_with(error: Exception) -> int:+ print(f"[unreal] error: {error}", file=sys.stderr, flush=True)+ return 2diff --git a/scripts/unreal/build.py b/scripts/unreal/build.pynew file mode 100644index 0000000000..0d0b6cf2c0--- /dev/null+++ b/scripts/unreal/build.py@@ -0,0 +1,139 @@+#!/usr/bin/env python3+"""Build the Unreal Verse under the machine lock, or clean a worktree's output.++The only build entry for agents (docs/verse/unreal/orchestration.md 3.3 and+5.1); nobody calls UBT directly.++ python scripts/unreal/build.py editor # VerseEditor Win64 Development+ python scripts/unreal/build.py game # Verse Win64 Development+ python scripts/unreal/build.py linux # Verse Linux Development (cross)+ python scripts/unreal/build.py editor game # several, one lock hold each+ python scripts/unreal/build.py clean # delete Binaries/, Intermediate/, Saved/++A build refuses to start with less than 40 GB free (orchestration.md 4) and+the Linux build refuses to start without ``LINUX_MULTIARCH_ROOT``+(``doctor.py`` says how to fix both).+"""++from __future__ import annotations++import argparse+import os+import shutil+import sys+import time+from collections.abc import Callable, Mapping, Sequence+from pathlib import Path++if __package__ in (None, ""):+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++from scripts.unreal import _common as common+from scripts.unreal import with_lock++#: target name -> (UBT target, platform, configuration)+TARGETS: dict[str, tuple[str, str, str]] = {+ "editor": ("VerseEditor", "Win64", "Development"),+ "game": ("Verse", "Win64", "Development"),+ "linux": ("Verse", "Linux", "Development"),+}+LINUX_ENV = "LINUX_MULTIARCH_ROOT"+++def command_for(target: str, engine: Path, project: Path) -> list[str]:+ name, platform, configuration = TARGETS[target]+ return [+ str(common.build_bat(engine)),+ name,+ platform,+ configuration,+ f"-Project={project}",+ "-WaitMutex",+ "-NoHotReloadFromIDE",+ f"-MaxParallelActions={common.MAX_PARALLEL_ACTIONS}",+ ]+++def check_prerequisites(target: str, engine: Path, worktree: Path, env: Mapping[str, str]) -> None:+ if not common.build_bat(engine).is_file():+ raise common.UnrealScriptError(+ f"no Unreal install at {engine} (set {common.ENGINE_ENV}; run doctor.py)"+ )+ if not common.project_file(worktree).is_file():+ raise common.UnrealScriptError(f"no project at {common.project_file(worktree)}")+ if target == "linux" and not env.get(LINUX_ENV, "").strip():+ raise common.UnrealScriptError(+ f"{LINUX_ENV} is not set: the Linux cross toolchain is missing (run doctor.py)"+ )+ common.require_free_disk(worktree)+++def build(+ targets: Sequence[str],+ *,+ worktree: Path = common.REPO_ROOT,+ env: Mapping[str, str] | None = None,+ runner: Callable[..., int] = with_lock.run_locked,+) -> int:+ env = os.environ if env is None else env+ engine = common.engine_root(env)+ project = common.project_file(worktree)+ for target in targets:+ check_prerequisites(target, engine, worktree, env)+ for target in targets:+ command = command_for(target, engine, project)+ common.log(f"build {target}: {' '.join(command)}")+ started = time.monotonic()+ code = runner(command, label=f"build {target} ({worktree.name})", cwd=worktree)+ minutes = (time.monotonic() - started) / 60+ verdict = "OK" if code == 0 else f"FAILED (exit {code})"+ common.log(f"build {target}: {verdict} in {minutes:.1f} min")+ if code != 0:+ return code+ return 0+++def clean(+ worktree: Path = common.REPO_ROOT,+ *,+ remove: Callable[[Path], None] = shutil.rmtree,+) -> list[Path]:+ """Delete this worktree's build output; never the shared DDC."""+ project_dir = worktree / "unreal" / "Verse"+ roots = [project_dir]+ plugins = project_dir / "Plugins"+ if plugins.is_dir():+ roots += [p for p in plugins.iterdir() if p.is_dir()]+ removed: list[Path] = []+ for root in roots:+ for name in common.BUILD_OUTPUT_DIRS:+ target = root / name+ if target.is_dir() and not target.is_symlink():+ remove(target)+ removed.append(target)+ for path in removed:+ common.log(f"clean: removed {path}")+ if not removed:+ common.log("clean: nothing to remove")+ return removed+++def main(argv: Sequence[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument("targets", nargs="+", choices=[*TARGETS, "clean"])+ parser.add_argument("--worktree", type=Path, default=common.REPO_ROOT)+ options = parser.parse_args(argv)+ worktree = options.worktree.resolve()+ if "clean" in options.targets:+ if len(options.targets) > 1:+ parser.error("clean runs on its own")+ clean(worktree)+ return 0+ try:+ return build(options.targets, worktree=worktree)+ except common.UnrealScriptError as error:+ return common.exit_with(error)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/unreal/doctor.py b/scripts/unreal/doctor.pynew file mode 100644index 0000000000..ccee0bd699--- /dev/null+++ b/scripts/unreal/doctor.py@@ -0,0 +1,311 @@+#!/usr/bin/env python3+"""Check that this box has the toolchain the Unreal Verse needs. Installs nothing.++Reads the pins in ``unreal/Toolchain/toolchains.json`` and the engine's own+requirement files (``Engine/Config/Windows/Windows_SDK.json`` and+``Engine/Config/Linux/Linux_SDK.json``), then checks the engine version, the+Visual Studio Build Tools, the MSVC compiler (the real ``cl.exe`` version,+which is what the engine compares with its banned list), the Windows SDK,+.NET Framework and its targeting packs, git-lfs, the Linux cross toolchain,+free disk space and the lock folder (docs/verse/unreal/orchestration.md 0.1).++ python scripts/unreal/doctor.py # every check+ python scripts/unreal/doctor.py --target win64 # skip the Linux toolchain+ python scripts/unreal/doctor.py --json++Exit code 0 when no check fails, 1 otherwise.+"""++from __future__ import annotations++import argparse+import json+import os+import re+import sys+from collections.abc import Callable, Sequence+from dataclasses import asdict, dataclass+from pathlib import Path++if __package__ in (None, ""):+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++from scripts.unreal import _common as common+from scripts.unreal import with_lock++VSWHERE = Path("C:/Program Files (x86)/Microsoft Visual Studio/Installer/vswhere.exe")+NETFX_KEY = r"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full"+++@dataclass+class Check:+ name: str+ status: str # "ok" | "fail" | "skip"+ detail: str+ fix: str = ""+++def version_tuple(text: str) -> tuple[int, ...]:+ return tuple(int(p) for p in re.findall(r"\d+", text))+++def in_range(version: str, spec: str) -> bool:+ """``spec`` is ``low-high`` as in the engine's SDK files (inclusive)."""+ low, _, high = spec.partition("-")+ value = version_tuple(version)+ return version_tuple(low) <= value <= version_tuple(high or low)+++@dataclass+class Probe:+ """Everything doctor reads from the machine; the tests replace it."""++ run: Callable[..., common.Completed] = common.run+ exists: Callable[[Path], bool] = Path.exists+ read_text: Callable[[Path], str] = lambda p: p.read_text(encoding="utf-8-sig")+ listdir: Callable[[Path], list[str]] = lambda p: sorted(os.listdir(p)) if p.is_dir() else []+ env: dict | None = None+ free_gb: Callable[[Path], float] = common.free_gb+ netfx_release: Callable[[], int | None] = lambda: _registry_release()+ is_windows: bool = os.name == "nt"++ def getenv(self, name: str) -> str:+ return (os.environ if self.env is None else self.env).get(name, "")+++def _registry_release() -> int | None:+ try:+ import winreg++ with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, NETFX_KEY) as key:+ return int(winreg.QueryValueEx(key, "Release")[0])+ except (ImportError, OSError, ValueError):+ return None+++def _engine_json(engine: Path, relative: str, probe: Probe) -> dict:+ try:+ return json.loads(probe.read_text(engine / relative))+ except (OSError, ValueError):+ return {}+++def check_engine(pins: dict, engine: Path, probe: Probe, project: Path) -> list[Check]:+ want = pins["engine"]["version"]+ try:+ data = json.loads(probe.read_text(engine / "Engine" / "Build" / "Build.version"))+ have = f"{data['MajorVersion']}.{data['MinorVersion']}.{data['PatchVersion']}"+ except (OSError, ValueError, KeyError):+ return [Check("engine", "fail", f"no Unreal Engine at {engine}",+ f"install UE {want} from the launcher or set {common.ENGINE_ENV}")]+ checks = [Check("engine", "ok" if have == want else "fail", f"UE {have} at {engine}",+ "" if have == want else f"install UE {want}")]+ try:+ association = json.loads(probe.read_text(project)).get("EngineAssociation", "")+ except (OSError, ValueError):+ association = ""+ want_assoc = pins["engine"]["association"]+ checks.append(Check("uproject", "ok" if association == want_assoc else "fail",+ f"EngineAssociation {association or '?'} (want {want_assoc})"))+ return checks+++def _vs_installs(probe: Probe) -> list[dict]:+ if not probe.exists(VSWHERE):+ return []+ result = probe.run([str(VSWHERE), "-products", "*", "-all", "-format", "json", "-utf8"],+ capture=True)+ try:+ return json.loads(result.stdout) if result.returncode == 0 else []+ except ValueError:+ return []+++def cl_version(cl: Path, probe: Probe) -> str | None:+ """The toolset version of ``cl.exe`` (compiler 19.44.35229 -> 14.44.35229)."""+ result = probe.run([str(cl)], capture=True)+ match = re.search(r"Version 19\.(\d+)\.(\d+)", result.stderr + result.stdout)+ return f"14.{match.group(1)}.{match.group(2)}" if match else None+++def check_msvc(pins: dict, engine: Path, probe: Probe) -> list[Check]:+ installs = _vs_installs(probe)+ want_vs = pins["visual_studio"]["min_version"]+ good_vs = [i for i in installs+ if version_tuple(i.get("installationVersion", "0")) >= version_tuple(want_vs)]+ if not good_vs:+ found = ", ".join(i.get("installationVersion", "?") for i in installs) or "none"+ return [Check("visual-studio", "fail", f"VS 2022 {want_vs}+ not found (found: {found})",+ "install Visual Studio 2022 Build Tools with the C++ x64 workload")]+ checks = [Check("visual-studio", "ok",+ ", ".join(f"{i.get('productId', '?').rsplit('.', 1)[-1]} "+ f"{i.get('installationVersion')}" for i in good_vs))]+ sdk = _engine_json(engine, "Engine/Config/Windows/Windows_SDK.json", probe)+ banned = sdk.get("BannedVisualCppVersions", [])+ family, minimum = pins["msvc"]["family"], pins["msvc"]["min_version"]+ seen: list[str] = []+ for install in good_vs:+ tools = Path(install["installationPath"]) / "VC" / "Tools" / "MSVC"+ for folder in probe.listdir(tools):+ if not folder.startswith(family + "."):+ seen.append(folder)+ continue+ cl = tools / folder / "bin" / "Hostx64" / "x64" / "cl.exe"+ version = cl_version(cl, probe) if probe.exists(cl) else None+ seen.append(f"{folder} (cl {version or '?'})")+ if not version:+ continue+ if any(in_range(version, spec) for spec in banned):+ continue+ if version_tuple(version) >= version_tuple(minimum):+ return checks + [Check("msvc", "ok", f"MSVC {version} in {tools / folder}")]+ return checks + [Check(+ "msvc", "fail",+ f"no MSVC {family} at {minimum}+ outside the engine's banned list "+ f"(found: {', '.join(seen) or 'none'})",+ f"add the MSVC v143 {family} x64/x86 build tools in the Visual Studio Installer",+ )]+++def check_windows_sdk(pins: dict, engine: Path, probe: Probe) -> list[Check]:+ want = pins["windows_sdk"]["version"]+ root = Path(pins["windows_sdk"]["root"])+ missing = [sub for sub in ("Include", "Lib") if not probe.exists(root / sub / want)]+ engine_main = _engine_json(engine, "Engine/Config/Windows/Windows_SDK.json", probe).get(+ "MainVersion", want)+ detail = f"Windows SDK {want} at {root}"+ if engine_main != want:+ return [Check("windows-sdk", "fail",+ f"pin {want} differs from the engine's MainVersion {engine_main}",+ "update unreal/Toolchain/toolchains.json")]+ if missing:+ return [Check("windows-sdk", "fail", f"{detail}: missing {', '.join(missing)}",+ f"add the Windows 11 SDK {want} in the Visual Studio Installer")]+ return [Check("windows-sdk", "ok", detail)]+++def check_netfx(pins: dict, probe: Probe) -> list[Check]:+ spec = pins["netfx"]+ release = probe.netfx_release()+ checks = []+ if release is None or release < spec["min_release"]:+ checks.append(Check("netfx-runtime", "fail",+ f".NET Framework release {release} < {spec['min_release']}",+ f"install .NET Framework {spec['runtime']}"))+ else:+ checks.append(Check("netfx-runtime", "ok",+ f".NET Framework release {release} ({spec['runtime']}+)"))+ root = Path(spec["reference_root"])+ missing = [p for p in spec["targeting_packs"] if not probe.exists(root / p)]+ checks.append(Check(+ "netfx-targeting", "fail" if missing else "ok",+ f"targeting packs {', '.join(spec['targeting_packs'])}"+ + (f": missing {', '.join(missing)}" if missing else ""),+ "add the .NET Framework targeting packs in the Visual Studio Installer" if missing else "",+ ))+ return checks+++def check_git_lfs(pins: dict, probe: Probe) -> list[Check]:+ want = pins["git_lfs"]["min_version"]+ result = probe.run(["git", "lfs", "version"], capture=True)+ match = re.search(r"git-lfs/(\d+\.\d+\.\d+)", result.stdout)+ if result.returncode != 0 or not match:+ return [Check("git-lfs", "fail", "git lfs not found", f"install git-lfs {want}+")]+ have = match.group(1)+ ok = version_tuple(have) >= version_tuple(want)+ return [Check("git-lfs", "ok" if ok else "fail", f"git-lfs {have} (want {want}+)",+ "" if ok else f"update git-lfs to {want}+")]+++def check_linux(pins: dict, engine: Path, probe: Probe) -> list[Check]:+ spec = pins["linux"]+ engine_main = _engine_json(engine, "Engine/Config/Linux/Linux_SDK.json", probe).get(+ "MainVersion", spec["sdk"])+ if engine_main != spec["sdk"]:+ return [Check("linux-toolchain", "fail",+ f"pin {spec['sdk']} differs from the engine's {engine_main}",+ "update unreal/Toolchain/toolchains.json")]+ root = probe.getenv(spec["env"]).strip()+ fix = (f"install the engine's Linux cross toolchain {spec['sdk']} and set "+ f"{spec['env']} to its folder")+ if not root:+ return [Check("linux-toolchain", "fail", f"{spec['env']} is not set", fix)]+ path = Path(root)+ clang = path / "x86_64-unknown-linux-gnu" / "bin" / "clang++.exe"+ if not probe.exists(clang):+ return [Check("linux-toolchain", "fail", f"no {clang}", fix)]+ if spec["sdk"] not in str(path):+ return [Check("linux-toolchain", "fail",+ f"{spec['env']}={root} does not name {spec['sdk']}", fix)]+ return [Check("linux-toolchain", "ok", f"{spec['sdk']} at {root}")]+++def check_disk(pins: dict, worktree: Path, probe: Probe) -> list[Check]:+ want = pins["disk"]["min_free_gb"]+ free = probe.free_gb(worktree)+ return [Check("disk", "ok" if free >= want else "fail", f"{free:.0f} GB free (want {want})",+ "" if free >= want else "remove merged worktrees with worktree.py remove")]+++def check_lock_dir(probe: Probe) -> list[Check]:+ folder = with_lock.lock_dir(probe.env)+ try:+ folder.mkdir(parents=True, exist_ok=True)+ marker = folder / f".doctor-{os.getpid()}"+ marker.write_text("ok", encoding="utf-8")+ marker.unlink()+ except OSError as error:+ return [Check("lock-dir", "fail", f"{folder} not writable: {error}")]+ return [Check("lock-dir", "ok", str(folder))]+++def diagnose(+ targets: Sequence[str] = ("win64", "linux"),+ *,+ probe: Probe | None = None,+ pins: dict | None = None,+ worktree: Path = common.REPO_ROOT,+) -> list[Check]:+ probe = probe or Probe()+ pins = pins or common.load_toolchains()+ engine = common.engine_root(probe.env)+ checks: list[Check] = []+ if not probe.is_windows:+ checks.append(Check("windows", "skip", "not Windows: engine and MSVC checks skipped"))+ else:+ checks += check_engine(pins, engine, probe, common.project_file(worktree))+ checks += check_msvc(pins, engine, probe)+ checks += check_windows_sdk(pins, engine, probe)+ checks += check_netfx(pins, probe)+ if "linux" in targets:+ checks += check_linux(pins, engine, probe)+ else:+ checks.append(Check("linux-toolchain", "skip", "not requested (--target win64)"))+ checks += check_git_lfs(pins, probe)+ checks += check_disk(pins, worktree, probe)+ checks += check_lock_dir(probe)+ return checks+++def main(argv: Sequence[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument("--target", choices=["all", "win64", "linux"], default="all")+ parser.add_argument("--json", action="store_true")+ options = parser.parse_args(argv)+ targets = ("win64", "linux") if options.target == "all" else (options.target,)+ checks = diagnose(targets)+ failed = [c for c in checks if c.status == "fail"]+ if options.json:+ print(json.dumps({"ok": not failed, "checks": [asdict(c) for c in checks]}, indent=1))+ else:+ for c in checks:+ print(f"{c.status.upper():5} {c.name:16} {c.detail}")+ if c.fix and c.status == "fail":+ print(f"{'':22}fix: {c.fix}")+ print("doctor: GREEN" if not failed else f"doctor: RED ({len(failed)} failing)")+ return 0 if not failed else 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/unreal/screenshot.py b/scripts/unreal/screenshot.pynew file mode 100644index 0000000000..6ffa763398--- /dev/null+++ b/scripts/unreal/screenshot.py@@ -0,0 +1,82 @@+#!/usr/bin/env python3+"""Run a ``Verse.Visual.*`` suite on the GPU under the machine lock.++The only screenshot entry for agents (docs/verse/unreal/orchestration.md 5.3).++ python scripts/unreal/screenshot.py --suite Verse.Visual.Hangar++One rendered process at a time (orchestration.md 4). The game window opens+off the person's monitors, so nothing appears on their desktop and their+desktop is never captured. The automation framework compares each shot with+the ground truth in ``unreal/Verse/Tests/GroundTruth/Win64/``; reports and+shots land in ``unreal/Verse/Saved/Harness/proof/<branch>/<run>/`` and are+never committed. Pass rules are the ones of ``test.py``.+"""++from __future__ import annotations++import argparse+import sys+from collections.abc import Sequence+from pathlib import Path++if __package__ in (None, ""):+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++from scripts.unreal import _common as common+from scripts.unreal import test as automation++SUITE_PREFIX = "Verse.Visual."+#: Far outside any monitor layout, so the window never covers the person's work.+OFFSCREEN = ("-WinX=-32000", "-WinY=-32000")+++def render_args(width: int = 1920, height: int = 1080) -> list[str]:+ return [+ "-game",+ "-d3d12",+ "-windowed",+ f"-ResX={width}",+ f"-ResY={height}",+ *OFFSCREEN,+ "-benchmark",+ "-fps=30",+ ]+++def proof_dir(worktree: Path) -> Path:+ branch = common.safe_name(common.current_branch(worktree))+ return worktree / "unreal" / "Verse" / "Saved" / "Harness" / "proof" / branch+++def capture(+ suite: str, *, worktree: Path = common.REPO_ROOT, **kwargs+) -> list[automation.RunResult]:+ if not suite.startswith(SUITE_PREFIX):+ raise common.UnrealScriptError(+ f"visual suites are named {SUITE_PREFIX}<Suite>, got {suite!r}"+ )+ return automation.run_tests(+ suite,+ worktree=worktree,+ rendered=True,+ extra=render_args(),+ report_base=proof_dir(worktree),+ **kwargs,+ )+++def main(argv: Sequence[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument("--suite", required=True, help="for example Verse.Visual.Hangar")+ parser.add_argument("--worktree", type=Path, default=common.REPO_ROOT)+ options = parser.parse_args(argv)+ try:+ results = capture(options.suite, worktree=options.worktree.resolve())+ except common.UnrealScriptError as error:+ return common.exit_with(error)+ return automation.summarize(results)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/unreal/smoke.py b/scripts/unreal/smoke.pynew file mode 100644index 0000000000..718d83e508--- /dev/null+++ b/scripts/unreal/smoke.py@@ -0,0 +1,172 @@+#!/usr/bin/env python3+"""Package the Verse and smoke-test the packaged build under the machine lock.++The packaged-build smoke test of docs/verse/unreal/orchestration.md 5.6.++ python scripts/unreal/smoke.py # package, then run with the GPU+ python scripts/unreal/smoke.py --nullrhi # same run without rendering+ python scripts/unreal/smoke.py --skip-package # reuse Saved/Smoke++Steps, all inside one lock hold:++1. ``RunUAT BuildCookRun`` for Win64 Development into+ ``unreal/Verse/Saved/Smoke`` (``--skip-package`` reuses it).+2. ``scripts/unreal/fake_bridge.py --token <random>`` (G0.11) serves+ ``verse.bridge/1`` with synthetic data.+3. ``Saved/Smoke/Windows/Verse.exe -VerseSmoke=<stages>`` with+ ``DODAIOS_VERSE_TOKEN`` set, its window off the person's monitors.++Pass: package exit code 0; the game exits 0 within the time limit; its log+has a ``VerseSmoke: stage <name> OK`` line for every requested stage and no+fatal error, ensure or crash.+"""++from __future__ import annotations++import argparse+import os+import re+import secrets+import subprocess+import sys+from collections.abc import Callable, Sequence+from pathlib import Path++if __package__ in (None, ""):+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++from scripts.unreal import _common as common+from scripts.unreal import test as automation+from scripts.unreal import with_lock++DEFAULT_STAGES = ("boot", "hangar", "arena30s")+TOKEN_ENV = "DODAIOS_VERSE_TOKEN" # noqa: S105 - the variable name, not a secret+GAME_TIMEOUT_S = 10 * 60+FAKE_BRIDGE = common.REPO_ROOT / "scripts" / "unreal" / "fake_bridge.py"+++def archive_dir(worktree: Path) -> Path:+ return worktree / "unreal" / "Verse" / "Saved" / "Smoke"+++def package_command(engine: Path, project: Path, archive: Path) -> list[str]:+ return [+ str(common.run_uat_bat(engine)),+ "BuildCookRun",+ f"-project={project}",+ "-platform=Win64",+ "-clientconfig=Development",+ "-build",+ "-cook",+ "-stage",+ "-pak",+ "-iostore",+ "-archive",+ f"-archivedirectory={archive}",+ "-unattended",+ "-utf8output",+ "-nocompileeditor",+ ]+++def game_command(exe: Path, stages: Sequence[str], log_path: Path, nullrhi: bool) -> list[str]:+ command = [+ str(exe),+ "-windowed",+ "-ResX=1280",+ "-ResY=720",+ "-WinX=-32000",+ "-WinY=-32000",+ f"-VerseSmoke={','.join(stages)}",+ "-log",+ f"-abslog={log_path}",+ "-unattended",+ ]+ if nullrhi:+ command.append("-nullrhi")+ return command+++def missing_stages(log_path: Path, stages: Sequence[str]) -> list[str]:+ try:+ text = log_path.read_text(encoding="utf-8", errors="replace")+ except OSError:+ return list(stages)+ return [s for s in stages if not re.search(rf"VerseSmoke: stage {re.escape(s)} OK", text)]+++def smoke(+ *,+ worktree: Path = common.REPO_ROOT,+ stages: Sequence[str] = DEFAULT_STAGES,+ nullrhi: bool = False,+ skip_package: bool = False,+ runner: Callable[..., common.Completed] = common.run,+ popen: Callable[..., subprocess.Popen] = subprocess.Popen,+ lock_factory: Callable[..., with_lock.MachineLock] = with_lock.MachineLock,+ fake_bridge: Path = FAKE_BRIDGE,+) -> list[str]:+ """Run the smoke test; return the problems found (empty means pass)."""+ engine = common.engine_root()+ project = common.project_file(worktree)+ archive = archive_dir(worktree)+ exe = archive / "Windows" / "Verse.exe"+ if not fake_bridge.is_file():+ raise common.UnrealScriptError(+ f"{fake_bridge} is missing; the fake bridge lands with G0.11"+ )+ if not skip_package:+ common.require_free_disk(worktree)+ token = secrets.token_hex(16)+ log_path = archive / f"smoke-{common.run_stamp()}.log"+ problems: list[str] = []+ with lock_factory(f"smoke ({worktree.name})", "smoke.py"):+ if not skip_package:+ command = package_command(engine, project, archive)+ common.log(f"package: {' '.join(command)}")+ packaged = runner(command, cwd=worktree)+ if packaged.returncode != 0:+ return [f"BuildCookRun exited with {packaged.returncode}"]+ if not exe.is_file():+ return [f"no packaged game at {exe}"]+ log_path.parent.mkdir(parents=True, exist_ok=True)+ bridge = popen([sys.executable, str(fake_bridge), "--token", token], cwd=str(worktree))+ try:+ env = dict(os.environ, **{TOKEN_ENV: token})+ command = game_command(exe, stages, log_path, nullrhi)+ common.log(f"run: {' '.join(command)}")+ game = runner(command, cwd=archive, env=env, timeout=GAME_TIMEOUT_S)+ finally:+ bridge.terminate()+ try:+ bridge.wait(timeout=10)+ except subprocess.TimeoutExpired:+ bridge.kill()+ if game.returncode != 0:+ problems.append(f"Verse.exe exited with {game.returncode}")+ problems += [f"stage {s} not reported OK" for s in missing_stages(log_path, stages)]+ problems += [f"log: {line}" for line in automation.scan_log(log_path)]+ return problems+++def main(argv: Sequence[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument("--nullrhi", action="store_true", help="run the game without rendering")+ parser.add_argument("--skip-package", action="store_true", help="reuse Saved/Smoke")+ parser.add_argument("--stages", default=",".join(DEFAULT_STAGES))+ parser.add_argument("--worktree", type=Path, default=common.REPO_ROOT)+ options = parser.parse_args(argv)+ stages = [s.strip() for s in options.stages.split(",") if s.strip()]+ try:+ problems = smoke(worktree=options.worktree.resolve(), stages=stages,+ nullrhi=options.nullrhi, skip_package=options.skip_package)+ except common.UnrealScriptError as error:+ return common.exit_with(error)+ for problem in problems:+ common.log(f"PROBLEM {problem}")+ common.log("PASS" if not problems else "FAIL")+ return 0 if not problems else 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/unreal/test.py b/scripts/unreal/test.pynew file mode 100644index 0000000000..31bbf5156e--- /dev/null+++ b/scripts/unreal/test.py@@ -0,0 +1,229 @@+#!/usr/bin/env python3+"""Run Unreal automation tests headless (``-nullrhi``) under the machine lock.++The only automation entry for agents (docs/verse/unreal/orchestration.md 5.2).++ python scripts/unreal/test.py "Verse.Combat+Verse.Contract"+ python scripts/unreal/test.py "Verse.Core+Verse.Contract" --jobs 2++A run passes only when every editor process exits 0, its ``index.json``+reports zero failed and zero not-run tests, every part of the filter matched+at least one test, and no log holds a fatal error, an ensure or a crash.+``--jobs`` (at most 4) splits the filter parts over several headless editors+inside one lock hold. Reports land in ``unreal/Verse/Saved/Automation/``.+"""++from __future__ import annotations++import argparse+import json+import re+import sys+from collections.abc import Callable, Sequence+from concurrent.futures import ThreadPoolExecutor+from dataclasses import dataclass, field+from pathlib import Path++if __package__ in (None, ""):+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++from scripts.unreal import _common as common+from scripts.unreal import with_lock++#: Log lines that fail a run whatever the report says.+LOG_FAILURES = (+ re.compile(r"Fatal error"),+ re.compile(r"=== Critical error: ==="),+ re.compile(r"Ensure condition failed"),+ re.compile(r"Unhandled Exception"),+ re.compile(r"appError called"),+)+PASS_STATES = {"Success", "SuccessWithWarnings"}+PROCESS_TIMEOUT_S = 60 * 60+++@dataclass+class RunResult:+ filter: str+ returncode: int+ report_dir: Path+ log_path: Path+ passed: int = 0+ failed: list[str] = field(default_factory=list)+ not_run: list[str] = field(default_factory=list)+ unmatched: list[str] = field(default_factory=list)+ log_hits: list[str] = field(default_factory=list)+ problems: list[str] = field(default_factory=list)++ @property+ def ok(self) -> bool:+ return not (self.problems or self.failed or self.not_run or self.unmatched or self.log_hits)+++def split_filter(text: str) -> list[str]:+ parts = [p.strip() for p in text.split("+")]+ parts = [p for p in parts if p]+ if not parts:+ raise common.UnrealScriptError("empty test filter")+ for part in parts:+ if not re.fullmatch(r"[A-Za-z0-9_.]+", part):+ raise common.UnrealScriptError(f"bad filter part {part!r}")+ return parts+++def shard(parts: Sequence[str], jobs: int) -> list[list[str]]:+ jobs = max(1, min(jobs, common.MAX_HEADLESS_JOBS, len(parts)))+ groups: list[list[str]] = [[] for _ in range(jobs)]+ for index, part in enumerate(parts):+ groups[index % jobs].append(part)+ return groups+++def command_for(engine: Path, project: Path, test_filter: str, report_dir: Path, log_path: Path,+ extra: Sequence[str] = ()) -> list[str]:+ return [+ str(common.editor_cmd(engine)),+ str(project),+ f"-ExecCmds=Automation RunTests {test_filter}; Quit",+ "-TestExit=Automation Test Queue Empty",+ "-unattended",+ "-nullrhi",+ "-nosound",+ "-nosplash",+ "-NoP4",+ "-stdout",+ "-FullStdOutLogOutput",+ f"-ReportExportPath={report_dir}",+ f"-abslog={log_path}",+ *extra,+ ]+++def read_report(report_dir: Path) -> dict | None:+ index = report_dir / "index.json"+ try:+ return json.loads(index.read_text(encoding="utf-8-sig"))+ except (OSError, ValueError):+ return None+++def scan_log(log_path: Path) -> list[str]:+ try:+ lines = log_path.read_text(encoding="utf-8", errors="replace").splitlines()+ except OSError:+ return []+ return [line.strip() for line in lines if any(p.search(line) for p in LOG_FAILURES)][:20]+++def evaluate(result: RunResult, parts: Sequence[str]) -> RunResult:+ if result.returncode != 0:+ result.problems.append(f"editor exited with {result.returncode}")+ report = read_report(result.report_dir)+ if report is None:+ result.problems.append(f"no readable index.json in {result.report_dir}")+ tests: list[dict] = []+ else:+ tests = list(report.get("tests") or [])+ for test in tests:+ name = test.get("fullTestPath") or test.get("testDisplayName") or "?"+ state = test.get("state", "")+ if state in PASS_STATES:+ result.passed += 1+ elif state in ("NotRun", "Skipped", "InProcess", ""):+ result.not_run.append(name)+ else:+ result.failed.append(name)+ if report is not None:+ paths = [str(t.get("fullTestPath", "")) for t in tests]+ # RunTests matches by name prefix, so a part matched when some test starts with it.+ result.unmatched = [p for p in parts if not any(x.startswith(p) for x in paths)]+ result.log_hits = scan_log(result.log_path)+ return result+++def run_tests(+ test_filter: str,+ *,+ jobs: int = 1,+ worktree: Path = common.REPO_ROOT,+ rendered: bool = False,+ extra: Sequence[str] = (),+ runner: Callable[..., common.Completed] = common.run,+ lock_factory: Callable[..., with_lock.MachineLock] = with_lock.MachineLock,+ stamp: str | None = None,+ report_base: Path | None = None,+) -> list[RunResult]:+ parts = split_filter(test_filter)+ engine = common.engine_root()+ project = common.project_file(worktree)+ if not common.editor_cmd(engine).is_file():+ raise common.UnrealScriptError(f"no UnrealEditor-Cmd.exe under {engine} (run doctor.py)")+ if not project.is_file():+ raise common.UnrealScriptError(f"no project at {project}")+ groups = shard(parts, 1 if rendered else jobs)+ stamp = stamp or common.run_stamp()+ base = report_base or worktree / "unreal" / "Verse" / "Saved" / "Automation"+ planned: list[tuple[RunResult, list[str], list[str]]] = []+ for index, group in enumerate(groups):+ joined = "+".join(group)+ report_dir = base / f"{stamp}-{index}"+ report_dir.mkdir(parents=True, exist_ok=True)+ log_path = report_dir / "run.log"+ command = command_for(engine, project, joined, report_dir, log_path, extra)+ if rendered:+ command.remove("-nullrhi")+ planned.append((RunResult(joined, -1, report_dir, log_path), group, command))++ def launch(item: tuple[RunResult, list[str], list[str]]) -> RunResult:+ result, group, command = item+ common.log(f"test {result.filter}: {' '.join(command)}")+ completed = runner(command, cwd=worktree, timeout=PROCESS_TIMEOUT_S)+ result.returncode = completed.returncode+ return evaluate(result, group)++ label = f"test {test_filter} ({worktree.name})"+ with lock_factory(label, test_filter):+ with ThreadPoolExecutor(max_workers=len(planned)) as pool:+ return list(pool.map(launch, planned))+++def summarize(results: Sequence[RunResult]) -> int:+ ok = all(r.ok for r in results)+ for r in results:+ common.log(+ f"{r.filter}: {r.passed} passed, {len(r.failed)} failed, {len(r.not_run)} not run"+ f" report: {r.report_dir}"+ )+ for name in r.failed:+ common.log(f" FAILED {name}")+ for name in r.not_run:+ common.log(f" NOT RUN {name}")+ for part in r.unmatched:+ common.log(f" NO MATCH {part} (the filter matched no test)")+ for line in r.log_hits:+ common.log(f" LOG {line}")+ for problem in r.problems:+ common.log(f" PROBLEM {problem}")+ total = sum(r.passed for r in results)+ common.log(f"{'PASS' if ok else 'FAIL'}: {total} passed")+ return 0 if ok else 1+++def main(argv: Sequence[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument("filter", help='test filter, parts joined with "+"')+ parser.add_argument("--jobs", type=int, default=1,+ help=f"headless editors in parallel (max {common.MAX_HEADLESS_JOBS})")+ parser.add_argument("--worktree", type=Path, default=common.REPO_ROOT)+ options = parser.parse_args(argv)+ if not 1 <= options.jobs <= common.MAX_HEADLESS_JOBS:+ parser.error(f"--jobs must be 1..{common.MAX_HEADLESS_JOBS}")+ try:+ results = run_tests(options.filter, jobs=options.jobs, worktree=options.worktree.resolve())+ except common.UnrealScriptError as error:+ return common.exit_with(error)+ return summarize(results)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/unreal/with_lock.py b/scripts/unreal/with_lock.pynew file mode 100644index 0000000000..26bd03c72a--- /dev/null+++ b/scripts/unreal/with_lock.py@@ -0,0 +1,323 @@+#!/usr/bin/env python3+"""Hold the machine-wide ``gpu-heavy`` lock around one heavy job.++One compile, cook, package, commandlet, Blender export or cook, rendered test+or balance run uses the box at a time (docs/verse/unreal/orchestration.md+section 4, architecture.md 8.2). Every Unreal wrapper script and the Blender+runner (``scripts/verse/blender.py``) take this same lock.++- The lock is an OS file lock on ``C:/demo/.locks/gpu-heavy.lock``+ (``DODAIOS_LOCK_DIR`` overrides the folder). The OS releases it when the+ holder dies, so a crashed job never blocks the box.+- Waiters queue in FIFO order with one ticket file each in+ ``gpu-heavy.queue/``; they wait, they never fail. Tickets of dead processes+ are dropped.+- The holder writes holder, command, start time and PID to+ ``gpu-heavy.holder.json`` for the queue view (``with_lock.py status``).+- A hold is timed out after 90 minutes with a loud log line: the wrapped job+ of this process is stopped and the lock released. Other processes are never+ killed; a waiter that sees an older hold only says so.+- Nested use is free: a job started under the lock inherits+ ``DODAIOS_GPU_LOCK_HELD`` and does not queue for the lock its parent holds.++ python scripts/unreal/with_lock.py --label cook -- python scripts/verse/cook.py hangar+ python scripts/unreal/with_lock.py status+"""++from __future__ import annotations++import argparse+import contextlib+import json+import os+import socket+import subprocess+import sys+import time+from collections.abc import Callable, Iterator, Sequence+from pathlib import Path++if __package__ in (None, ""):+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++from filelock import FileLock, Timeout++from scripts.unreal import _common as common++LOCK_NAME = "gpu-heavy"+LOCK_DIR_ENV = "DODAIOS_LOCK_DIR"+HELD_ENV = "DODAIOS_GPU_LOCK_HELD"+DEFAULT_LOCK_DIR = Path("C:/demo/.locks")+++class LockTimeout(common.UnrealScriptError):+ """The caller set a wait limit and the lock did not come free in time."""+++def lock_dir(env: dict[str, str] | None = None) -> Path:+ env = os.environ if env is None else env+ override = env.get(LOCK_DIR_ENV, "").strip()+ if override:+ return Path(override)+ if os.name == "nt":+ return DEFAULT_LOCK_DIR+ return Path.home() / ".cache" / "dodaios" / "locks"+++def pid_alive(pid: int) -> bool:+ """True while a process with this PID runs (never signals it)."""+ if pid <= 0:+ return False+ if os.name == "nt":+ import ctypes++ kernel32 = ctypes.windll.kernel32+ handle = kernel32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION+ if not handle:+ return False+ try:+ code = ctypes.c_ulong()+ if not kernel32.GetExitCodeProcess(handle, ctypes.byref(code)):+ return False+ return code.value == 259 # STILL_ACTIVE+ finally:+ kernel32.CloseHandle(handle)+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ return False+ except PermissionError:+ return True+ return True+++def _read_json(path: Path) -> dict | None:+ try:+ return json.loads(path.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return None+++class MachineLock:+ """Context manager for the ``gpu-heavy`` lock with a FIFO queue."""++ def __init__(+ self,+ label: str,+ command: Sequence[str] | str | None = None,+ *,+ directory: Path | None = None,+ wait_timeout: float | None = None,+ poll: float = 2.0,+ clock: Callable[[], float] = time.monotonic,+ sleep: Callable[[float], None] = time.sleep,+ alive: Callable[[int], bool] = pid_alive,+ pid: int | None = None,+ echo: Callable[[str], None] = common.log,+ ) -> None:+ self.label = label+ self.command = command if isinstance(command, str) else " ".join(command or ())+ self.directory = directory or lock_dir()+ self.wait_timeout = wait_timeout+ self.poll = poll+ self.clock = clock+ self.sleep = sleep+ self.alive = alive+ self.pid = os.getpid() if pid is None else pid+ self.echo = echo+ self.lock_path = self.directory / f"{LOCK_NAME}.lock"+ self.holder_path = self.directory / f"{LOCK_NAME}.holder.json"+ self.queue_dir = self.directory / f"{LOCK_NAME}.queue"+ self._lock = FileLock(str(self.lock_path))+ self._ticket: Path | None = None+ self._nested = False+ self._previous_env: str | None = None+ self.waited = 0.0++ # --- queue ---------------------------------------------------------------++ def tickets(self) -> list[Path]:+ """Live tickets in FIFO order; tickets of dead processes are removed."""+ live: list[Path] = []+ for ticket in sorted(self.queue_dir.glob("*.json")):+ data = _read_json(ticket)+ pid = int(data.get("pid", 0)) if data else 0+ if ticket == self._ticket or (pid and self.alive(pid)):+ live.append(ticket)+ else:+ ticket.unlink(missing_ok=True)+ return live++ def _enqueue(self) -> Path:+ self.queue_dir.mkdir(parents=True, exist_ok=True)+ ticket = self.queue_dir / f"{time.time_ns():020d}-{self.pid}.json"+ payload = {"pid": self.pid, "label": self.label, "command": self.command,+ "queued": time.strftime("%Y-%m-%dT%H:%M:%S")}+ ticket.write_text(json.dumps(payload), encoding="utf-8")+ self._ticket = ticket+ return ticket++ def _is_nested(self) -> bool:+ held = os.environ.get(HELD_ENV, "")+ path, _, pid = held.rpartition("|")+ if not path or Path(path) != self.lock_path or not pid.isdigit():+ return False+ return self.alive(int(pid))++ # --- acquire / release ---------------------------------------------------++ def acquire(self) -> None:+ if self._is_nested():+ self._nested = True+ return+ self.directory.mkdir(parents=True, exist_ok=True)+ ticket = self._enqueue()+ started = self.clock()+ announced = False+ stale_warned = False+ try:+ while True:+ queue = self.tickets()+ if queue and queue[0] == ticket:+ try:+ self._lock.acquire(timeout=0)+ break+ except Timeout:+ pass+ waited = self.clock() - started+ if self.wait_timeout is not None and waited > self.wait_timeout:+ raise LockTimeout(+ f"{LOCK_NAME} lock not acquired within {self.wait_timeout:.0f} s"+ )+ holder = _read_json(self.holder_path) or {}+ if not announced:+ position = queue.index(ticket) + 1 if ticket in queue else len(queue)+ self.echo(+ f"waiting for the {LOCK_NAME} lock (held by {holder.get('holder', '?')}, "+ f"pid {holder.get('pid', '?')}); place {position} of {len(queue)}"+ )+ if len(queue) > common.QUEUE_DEPTH_WARN:+ self.echo(+ f"LOCK QUEUE DEEP: {len(queue)} waiters (limit "+ f"{common.QUEUE_DEPTH_WARN}); stop starting build-heavy sub-tasks"+ )+ announced = True+ held_for = time.time() - float(holder.get("started_epoch", time.time()))+ if not stale_warned and held_for > common.MAX_HOLD_MINUTES * 60:+ self.echo(+ f"LOCK HELD TOO LONG: pid {holder.get('pid', '?')} has held the "+ f"{LOCK_NAME} lock for {held_for / 60:.0f} min; still waiting, "+ "nothing is killed"+ )+ stale_warned = True+ self.sleep(self.poll)+ finally:+ if not self._lock.is_locked:+ ticket.unlink(missing_ok=True)+ self._ticket = None+ self.waited = self.clock() - started+ ticket.unlink(missing_ok=True)+ self._ticket = None+ holder = {+ "holder": self.label,+ "command": self.command,+ "pid": self.pid,+ "host": socket.gethostname(),+ "started": time.strftime("%Y-%m-%dT%H:%M:%S"),+ "started_epoch": time.time(),+ }+ self.holder_path.write_text(json.dumps(holder, indent=1), encoding="utf-8")+ self._previous_env = os.environ.get(HELD_ENV)+ os.environ[HELD_ENV] = f"{self.lock_path}|{self.pid}"++ def release(self) -> None:+ if self._nested:+ self._nested = False+ return+ if self._previous_env is None:+ os.environ.pop(HELD_ENV, None)+ else:+ os.environ[HELD_ENV] = self._previous_env+ self.holder_path.unlink(missing_ok=True)+ if self._lock.is_locked:+ self._lock.release()++ @property+ def nested(self) -> bool:+ return self._nested++ def __enter__(self) -> MachineLock:+ self.acquire()+ return self++ def __exit__(self, *_exc: object) -> None:+ self.release()+++def held(label: str, command: Sequence[str] | str | None = None, **kwargs) -> Iterator[MachineLock]:+ with MachineLock(label, command, **kwargs) as lock:+ yield lock+++def run_locked(+ command: Sequence[str],+ *,+ label: str,+ cwd: Path | None = None,+ env: dict[str, str] | None = None,+ max_hold_minutes: float = common.MAX_HOLD_MINUTES,+ popen: Callable[..., subprocess.Popen] = subprocess.Popen,+ lock_factory: Callable[..., MachineLock] = MachineLock,+) -> int:+ """Run ``command`` under the lock; stop it after ``max_hold_minutes``."""+ with lock_factory(label, command):+ child_env = dict(os.environ if env is None else env)+ child_env[HELD_ENV] = os.environ.get(HELD_ENV, "")+ process = popen(list(command), cwd=str(cwd) if cwd else None, env=child_env)+ try:+ return process.wait(timeout=max_hold_minutes * 60)+ except subprocess.TimeoutExpired:+ common.log(+ f"LOCK HOLD TIMEOUT: '{label}' ran past {max_hold_minutes:.0f} min; "+ "stopping this job and releasing the lock"+ )+ process.kill()+ process.wait()+ return 124+ except KeyboardInterrupt:+ process.kill()+ process.wait()+ raise+++def status(directory: Path | None = None, alive: Callable[[int], bool] = pid_alive) -> dict:+ lock = MachineLock("status", directory=directory, alive=alive)+ holder = _read_json(lock.holder_path)+ if holder and not alive(int(holder.get("pid", 0))):+ holder = None+ queue = [_read_json(t) or {} for t in lock.tickets()] if lock.queue_dir.exists() else []+ return {"lock": str(lock.lock_path), "holder": holder, "queue": queue}+++def main(argv: Sequence[str] | None = None) -> int:+ argv = list(sys.argv[1:] if argv is None else argv)+ if argv[:1] == ["status"]:+ print(json.dumps(status(), indent=1))+ return 0+ command: list[str] = []+ if "--" in argv:+ split = argv.index("--")+ argv, command = argv[:split], argv[split + 1 :]+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument("--label", default="", help="who holds the lock (default: the command)")+ parser.add_argument("--max-hold-minutes", type=float, default=common.MAX_HOLD_MINUTES)+ options = parser.parse_args(argv)+ if not command:+ parser.error("give the command after --")+ label = options.label or Path(command[0]).name+ return run_locked(command, label=label, max_hold_minutes=options.max_hold_minutes)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/unreal/worktree.py b/scripts/unreal/worktree.pynew file mode 100644index 0000000000..a5af14821e--- /dev/null+++ b/scripts/unreal/worktree.py@@ -0,0 +1,221 @@+#!/usr/bin/env python3+"""Create or remove the worktree of one Unreal Verse sub-task.++docs/verse/unreal/orchestration.md 3.1:++ python scripts/unreal/worktree.py new wp01-2-recoil-curve+ git fetch origin+ git worktree add -b claude/verse-wp01-2-recoil-curve C:/demo/wt/<short-id> origin/main+ git config lfs.fetchexclude "" (in the new worktree)+ python scripts/unreal/worktree.py remove <path or short-id>+ 1. build.py clean in that worktree (never the shared DDC)+ 2. unlink every node_modules junction or link, never delete through it+ 3. git worktree remove <path> (never --force)++Slugs are ``wp<nn>-<k>-<slug>`` for package sub-tasks (``k`` may carry a+letter, ``wp02-4a-...``) and ``int-<slug>`` for integration work. Worktree+paths stay short because Unreal paths under ``Intermediate/`` hit the Windows+path limit: ``<short-id>`` has at most 12 characters. ``DODAIOS_WORKTREE_ROOT``+overrides ``C:/demo/wt``.+"""++from __future__ import annotations++import argparse+import os+import re+import stat+import sys+from collections.abc import Callable, Iterator, Sequence+from pathlib import Path++if __package__ in (None, ""):+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++from scripts.unreal import _common as common+from scripts.unreal import build++ROOT_ENV = "DODAIOS_WORKTREE_ROOT"+DEFAULT_ROOT = Path("C:/demo/wt")+BRANCH_PREFIX = "claude/verse-"+MAX_ID = 12+SLUG = re.compile(r"(wp(0[1-9]|1[0-9]|2[0-2])-[1-9][0-9]*[a-z]?|int)-[a-z0-9]+(-[a-z0-9]+)*")+#: Folders never walked while looking for node_modules links.+_SKIP_WALK = {".git", "node_modules", "Binaries", "Intermediate", "Saved", "DerivedDataCache",+ ".venv", "venv", "__pycache__"}+_WALK_DEPTH = 6+_WINDOWS = os.name == "nt"+++def worktree_root(env: dict[str, str] | None = None) -> Path:+ env = os.environ if env is None else env+ override = env.get(ROOT_ENV, "").strip()+ if override:+ return Path(override)+ return DEFAULT_ROOT if os.name == "nt" else Path.home() / "wt"+++def validate_slug(slug: str) -> str:+ if not SLUG.fullmatch(slug):+ raise common.UnrealScriptError(+ f"bad slug {slug!r}: use wp<nn>-<k>-<words> (nn 01-22) or int-<words>, "+ "lower case, words joined by '-'"+ )+ return slug+++def short_id(slug: str, taken: Callable[[str], bool] = lambda _id: False) -> str:+ """At most 12 characters from the slug, unique under the worktree root."""+ base = slug[:MAX_ID].rstrip("-")+ if not taken(base):+ return base+ for n in range(2, 100):+ suffix = str(n)+ candidate = base[: MAX_ID - len(suffix) - 1].rstrip("-") + "-" + suffix+ if not taken(candidate):+ return candidate+ raise common.UnrealScriptError(f"no free short id for {slug!r} under the worktree root")+++def _git(*args: str, cwd: Path = common.REPO_ROOT, runner=None) -> common.Completed:+ runner = runner or common.run+ return runner(["git", "-C", str(cwd), *args], capture=True)+++def _check(result: common.Completed, what: str) -> common.Completed:+ if result.returncode != 0:+ detail = (result.stderr or result.stdout).strip()+ raise common.UnrealScriptError(f"{what} failed: {detail}")+ return result+++def new(+ slug: str,+ *,+ root: Path | None = None,+ wt_id: str | None = None,+ runner: Callable[..., common.Completed] | None = None,+) -> Path:+ validate_slug(slug)+ root = root or worktree_root()+ branch = BRANCH_PREFIX + slug+ if wt_id is not None:+ if not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,11}", wt_id):+ raise common.UnrealScriptError(f"bad --id {wt_id!r}: 1-12 of a-z, 0-9, '-'")+ if (root / wt_id).exists():+ raise common.UnrealScriptError(f"{root / wt_id} already exists")+ chosen = wt_id+ else:+ chosen = short_id(slug, taken=lambda c: (root / c).exists())+ path = root / chosen+ _check(_git("fetch", "origin", runner=runner), "git fetch origin")+ exists = _git("rev-parse", "--verify", "--quiet", f"refs/heads/{branch}", runner=runner)+ if exists.returncode == 0:+ raise common.UnrealScriptError(f"branch {branch} already exists; pick another slug")+ root.mkdir(parents=True, exist_ok=True)+ _check(+ _git("worktree", "add", "-b", branch, str(path), "origin/main", runner=runner),+ "git worktree add",+ )+ _check(_git("config", "lfs.fetchexclude", "", cwd=path, runner=runner),+ "git config lfs.fetchexclude")+ common.log(f"worktree {path} on {branch} (from origin/main)")+ return path+++def _is_link(path: Path) -> bool:+ try:+ info = os.lstat(path)+ except OSError:+ return False+ if stat.S_ISLNK(info.st_mode):+ return True+ attributes = getattr(info, "st_file_attributes", 0)+ return bool(attributes & getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400))+++def node_modules_links(top: Path, depth: int = _WALK_DEPTH) -> Iterator[Path]:+ """Every ``node_modules`` that is a junction or symlink, without following any."""+ stack = [(top, 0)]+ while stack:+ folder, level = stack.pop()+ try:+ entries = list(os.scandir(folder))+ except OSError:+ continue+ for entry in entries:+ path = Path(entry.path)+ if entry.name == "node_modules" and _is_link(path):+ yield path+ continue+ if level + 1 >= depth or entry.name in _SKIP_WALK or _is_link(path):+ continue+ if entry.is_dir(follow_symlinks=False):+ stack.append((path, level + 1))+++def unlink_link(path: Path, runner: Callable[..., common.Completed] | None = None) -> None:+ """Remove the link itself; its target stays untouched."""+ if _WINDOWS:+ _check((runner or common.run)(["cmd", "/c", "rmdir", str(path)], capture=True),+ f"rmdir {path}")+ else:+ path.unlink()+++def registered_worktrees(runner=None) -> list[Path]:+ listing = _check(_git("worktree", "list", "--porcelain", runner=runner), "git worktree list")+ return [Path(line[len("worktree "):]) for line in listing.stdout.splitlines()+ if line.startswith("worktree ")]+++def resolve_target(target: str, root: Path) -> Path:+ candidate = Path(target)+ if not candidate.is_absolute():+ candidate = root / target if not candidate.exists() else candidate+ return candidate.resolve()+++def remove(+ target: str,+ *,+ root: Path | None = None,+ runner: Callable[..., common.Completed] | None = None,+ cleaner: Callable[[Path], object] = build.clean,+) -> Path:+ path = resolve_target(target, root or worktree_root())+ registered = [p.resolve() for p in registered_worktrees(runner)]+ if path not in registered:+ raise common.UnrealScriptError(f"{path} is not a worktree of this repository")+ if registered and path == registered[0]:+ raise common.UnrealScriptError(f"{path} is the main checkout; it is never removed")+ cleaner(path)+ for link in node_modules_links(path):+ common.log(f"unlink {link}")+ unlink_link(link, runner)+ _check(_git("worktree", "remove", str(path), runner=runner), "git worktree remove")+ common.log(f"removed worktree {path}")+ return path+++def main(argv: Sequence[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ commands = parser.add_subparsers(dest="action", required=True)+ make = commands.add_parser("new", help="create a sub-task worktree from origin/main")+ make.add_argument("slug", help="wp<nn>-<k>-<words> or int-<words>")+ make.add_argument("--id", dest="wt_id", help="short folder name (max 12 characters)")+ drop = commands.add_parser("remove", help="clean and remove a worktree")+ drop.add_argument("target", help="worktree path or short id")+ options = parser.parse_args(argv)+ try:+ if options.action == "new":+ new(options.slug, wt_id=options.wt_id)+ else:+ remove(options.target)+ except common.UnrealScriptError as error:+ return common.exit_with(error)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/verse/blender.py b/scripts/verse/blender.pyindex 4fc2f692e1..ec50d10776 100644--- a/scripts/verse/blender.py+++ b/scripts/verse/blender.py@@ -10,8 +10,9 @@ Library and CLI. Every Blender job of the pipeline goes through `run()`:`scripts/verse` on `sys.path` (so builders can `import lib.scene`), picks theCycles device (OptiX, then CUDA, then CPU) and runs the target script as`__main__`. A Python exception inside Blender exits with code 1.-- Heavy jobs hold a cross-process GPU lock (`art/verse/.cache/gpu.lock`), so- only one Cycles render runs at a time on the shared GPU; other callers wait.+- Heavy jobs hold the machine-wide `gpu-heavy` lock of+ `scripts/unreal/with_lock.py`, so only one Cycles render, Unreal build or+ cook runs at a time on the shared box; other callers wait.- The Blender log streams to the console and to a log file.CLI:@@ -24,7 +25,6 @@ CLI:from __future__ import annotationsimport argparse-import jsonimport osimport shutilimport subprocess@@ -37,13 +37,10 @@ from contextlib import contextmanagerfrom dataclasses import dataclassfrom pathlib import Path-from filelock import FileLock, Timeout-REPO_ROOT = Path(__file__).resolve().parents[2]ART_ROOT = REPO_ROOT / "art" / "verse"CACHE_ROOT = ART_ROOT / ".cache"LOG_ROOT = CACHE_ROOT / "logs"-GPU_LOCK_PATH = CACHE_ROOT / "gpu.lock"BOOTSTRAP = Path(__file__).with_name("_bootstrap.py")DEFAULT_BLENDER = Path("C:/Program Files/Blender Foundation/Blender 5.0/blender.exe")DONE_MARKER = "[verse] bootstrap: done"@@ -83,30 +80,28 @@ def find_blender() -> Path:@contextmanagerdef gpu_lock(label: str, timeout: float | None = None) -> Iterator[None]:- """Hold the machine-wide GPU lock; wait while another job renders."""- GPU_LOCK_PATH.parent.mkdir(parents=True, exist_ok=True)- owner_path = GPU_LOCK_PATH.with_suffix(".owner")- lock = FileLock(str(GPU_LOCK_PATH))- started = time.monotonic()- announced = False- while True:- try:- lock.acquire(timeout=5)- break- except Timeout:- waited = time.monotonic() - started- if timeout is not None and waited > timeout:- raise BlenderError(f"GPU lock not acquired within {timeout:.0f} s") from None- if not announced:- holder = owner_path.read_text(encoding="utf-8") if owner_path.exists() else "?"- print(f"[verse] waiting for the GPU lock (held by {holder.strip()})", flush=True)- announced = True+ """Hold the machine-wide ``gpu-heavy`` lock; wait while another job runs.++ The same lock as Unreal builds, cooks and rendered tests+ (``scripts/unreal/with_lock.py``), so a Cycles render never runs beside a+ compile. Inside a job that already holds it the lock is not taken again.+ """+ if str(REPO_ROOT) not in sys.path:+ sys.path.insert(0, str(REPO_ROOT))+ from scripts.unreal.with_lock import LockTimeout, MachineLock++ lock = MachineLock(+ f"blender {label}",+ wait_timeout=timeout,+ echo=lambda message: print(f"[verse] {message}", flush=True),+ )+ try:+ lock.acquire()+ except LockTimeout as error:+ raise BlenderError(str(error)) from Nonetry:- owner = {"pid": os.getpid(), "job": label, "since": time.strftime("%H:%M:%S")}- owner_path.write_text(json.dumps(owner), encoding="utf-8")yieldfinally:- owner_path.unlink(missing_ok=True)lock.release()diff --git a/tests/unit/unreal/__init__.py b/tests/unit/unreal/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tests/unit/unreal/test_unreal_build_and_run.py b/tests/unit/unreal/test_unreal_build_and_run.pynew file mode 100644index 0000000000..53ca2c214d--- /dev/null+++ b/tests/unit/unreal/test_unreal_build_and_run.py@@ -0,0 +1,354 @@+"""build.py, test.py, screenshot.py and smoke.py of scripts/unreal (G0.6).++Pure logic: the engine is a fake folder, every process call is recorded, and+the lock is a stand-in, so nothing here starts Unreal.+"""++from __future__ import annotations++import contextlib+import json+from pathlib import Path++import pytest++from scripts.unreal import _common as common+from scripts.unreal import build, screenshot, smoke, with_lock+from scripts.unreal import test as automation+++def engine(tmp_path, monkeypatch):+ root = tmp_path / "UE_5.7"+ for path in (common.build_bat(root), common.run_uat_bat(root), common.editor_cmd(root)):+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("", encoding="utf-8")+ monkeypatch.setenv(common.ENGINE_ENV, str(root))+ return root+++def _env(engine: Path) -> dict[str, str]:+ return {common.ENGINE_ENV: str(engine)}+++def worktree(tmp_path):+ tree = tmp_path / "wt"+ project = common.project_file(tree)+ project.parent.mkdir(parents=True)+ project.write_text("{}", encoding="utf-8")+ return tree+++class _Lock:+ taken: list[str] = []++ def __init__(self, label, command=None):+ self.label = label++ def __enter__(self):+ _Lock.taken.append(self.label)+ return self++ def __exit__(self, *exc):+ return None++[email protected](autouse=True)+def _reset_lock():+ _Lock.taken = []+++# --- build.py ----------------------------------------------------------------+++def test_the_editor_build_is_the_plan_command(engine, worktree):+ command = build.command_for("editor", engine, common.project_file(worktree))+ assert command[:4] == [str(common.build_bat(engine)), "VerseEditor", "Win64", "Development"]+ assert f"-Project={common.project_file(worktree)}" in command+ assert "-WaitMutex" in command+ assert "-NoHotReloadFromIDE" in command+ assert "-MaxParallelActions=10" in command+++def test_game_and_linux_targets(engine, worktree):+ project = common.project_file(worktree)+ assert build.command_for("game", engine, project)[1:4] == ["Verse", "Win64", "Development"]+ assert build.command_for("linux", engine, project)[1:4] == ["Verse", "Linux", "Development"]+++def test_builds_run_under_the_lock_one_per_target_and_stop_at_the_first_failure(+ engine, worktree, monkeypatch+):+ monkeypatch.setattr(common, "free_gb", lambda _p: 500.0)+ calls = []++ def runner(command, *, label, cwd):+ calls.append((command[1], label))+ return 1 if command[1] == "VerseEditor" else 0++ code = build.build(["editor", "game"], worktree=worktree, env=_env(engine), runner=runner)+ assert code == 1+ assert [c[0] for c in calls] == ["VerseEditor"], "the game build never started"+ assert calls[0][1].startswith("build editor")+ assert build.build(["game"], worktree=worktree, env=_env(engine), runner=runner) == 0+++def test_the_linux_build_needs_the_cross_toolchain(engine, worktree, monkeypatch):+ monkeypatch.setattr(common, "free_gb", lambda _p: 500.0)+ with pytest.raises(common.UnrealScriptError, match="LINUX_MULTIARCH_ROOT"):+ build.build(["linux"], worktree=worktree, env=_env(engine), runner=lambda *a, **k: 0)+++def test_a_build_refuses_to_start_below_forty_gigabytes_free(engine, worktree, monkeypatch):+ monkeypatch.setattr(common, "free_gb", lambda _p: 39.0)+ ran = []+ with pytest.raises(common.UnrealScriptError, match="40 GB"):+ build.build(["editor"], worktree=worktree, env=_env(engine),+ runner=lambda *a, **k: ran.append(1))+ assert not ran+++def test_a_build_without_an_engine_says_so(tmp_path, worktree, monkeypatch):+ monkeypatch.setenv(common.ENGINE_ENV, str(tmp_path / "nowhere"))+ with pytest.raises(common.UnrealScriptError, match="no Unreal install"):+ build.build(["editor"], worktree=worktree, runner=lambda *a, **k: 0)+++def test_clean_removes_only_the_worktree_build_output(tmp_path):+ tree = tmp_path / "wt"+ project = tree / "unreal" / "Verse"+ keep = [project / "Source", project / "Content", project / "DerivedDataCache"]+ drop = [project / name for name in common.BUILD_OUTPUT_DIRS]+ drop.append(project / "Plugins" / "Thing" / "Intermediate")+ for folder in keep + drop:+ folder.mkdir(parents=True)+ (folder / "f.txt").write_text("x", encoding="utf-8")+ removed = build.clean(tree)+ assert sorted(removed) == sorted(drop)+ assert all(not p.exists() for p in drop)+ assert all(p.exists() for p in keep)+++def test_clean_runs_on_its_own():+ with pytest.raises(SystemExit):+ build.main(["clean", "editor"])+++# --- test.py -----------------------------------------------------------------+++def test_filters_split_on_plus_and_reject_odd_characters():+ assert automation.split_filter("Verse.Combat+Verse.Contract") == [+ "Verse.Combat", "Verse.Contract"]+ for bad in ("", "+", "Verse;Quit", "Verse Combat"):+ with pytest.raises(common.UnrealScriptError):+ automation.split_filter(bad)+++def test_jobs_never_exceed_four_headless_processes():+ parts = [f"Verse.M{i}" for i in range(9)]+ groups = automation.shard(parts, 8)+ assert len(groups) == 4+ assert sorted(p for g in groups for p in g) == sorted(parts)+ assert automation.shard(parts[:2], 4) == [["Verse.M0"], ["Verse.M1"]]+++def test_the_headless_command_is_the_plan_command(engine, tmp_path):+ command = automation.command_for(engine, Path("P.uproject"), "Verse.Core", tmp_path,+ tmp_path / "run.log")+ assert command[0] == str(common.editor_cmd(engine))+ assert "-ExecCmds=Automation RunTests Verse.Core; Quit" in command+ assert "-TestExit=Automation Test Queue Empty" in command+ for flag in ("-unattended", "-nullrhi", "-nosound", "-nosplash", "-NoP4", "-stdout"):+ assert flag in command+ assert f"-ReportExportPath={tmp_path}" in command+++def _report(folder: Path, tests: list[tuple[str, str]]) -> None:+ folder.mkdir(parents=True, exist_ok=True)+ payload = {"tests": [{"fullTestPath": name, "state": state} for name, state in tests]}+ # Unreal writes the report with a byte-order mark.+ (folder / "index.json").write_text(json.dumps(payload), encoding="utf-8-sig")+++def _result(tmp_path, code=0) -> automation.RunResult:+ return automation.RunResult("f", code, tmp_path, tmp_path / "run.log")+++def test_a_clean_report_passes(tmp_path):+ _report(tmp_path, [("Verse.Core.Smoke", "Success"), ("Verse.Contract.Enum", "Success")])+ result = automation.evaluate(_result(tmp_path), ["Verse.Core", "Verse.Contract"])+ assert result.ok and result.passed == 2+++ ("tests", "parts", "code", "log", "field"),+ [+ ([("Verse.Core.A", "Fail")], ["Verse.Core"], 0, "", "failed"),+ ([("Verse.Core.A", "NotRun")], ["Verse.Core"], 0, "", "not_run"),+ ([("Verse.Core.A", "Success")], ["Verse.Core", "Verse.Nothing"], 0, "", "unmatched"),+ ([("Verse.Core.A", "Success")], ["Verse.Core"], 0, "Ensure condition failed", "log_hits"),+ ([("Verse.Core.A", "Success")], ["Verse.Core"], 0, "Fatal error: boom", "log_hits"),+ ([("Verse.Core.A", "Success")], ["Verse.Core"], 3, "", "problems"),+ ],+)+def test_every_failure_kind_fails_the_run(tmp_path, tests, parts, code, log, field):+ _report(tmp_path, tests)+ (tmp_path / "run.log").write_text(log, encoding="utf-8")+ result = automation.evaluate(_result(tmp_path, code), parts)+ assert not result.ok+ assert getattr(result, field)+++def test_a_missing_report_fails(tmp_path):+ result = automation.evaluate(_result(tmp_path), ["Verse.Core"])+ assert not result.ok and "index.json" in result.problems[0]+++def test_run_tests_holds_the_lock_once_and_writes_one_report_per_job(engine, worktree):+ commands = []++ def runner(command, *, cwd, timeout):+ commands.append(command)+ report = Path(next(a for a in command if a.startswith("-ReportExportPath="))+ .split("=", 1)[1])+ exec_cmd = next(a for a in command if a.startswith("-ExecCmds="))+ names = exec_cmd.split("RunTests ", 1)[1].split(";")[0].split("+")+ _report(report, [(f"{n}.Case", "Success") for n in names])+ return common.Completed(0)++ results = automation.run_tests("Verse.Core+Verse.Contract", jobs=2, worktree=worktree,+ runner=runner, lock_factory=_Lock, stamp="t")+ assert len(_Lock.taken) == 1+ assert len(commands) == 2+ assert all(r.ok for r in results)+ assert automation.summarize(results) == 0+ assert results[0].report_dir == worktree / "unreal" / "Verse" / "Saved" / "Automation" / "t-0"+++# --- screenshot.py -----------------------------------------------------------+++def test_screenshots_render_off_screen_without_nullrhi_into_the_proof_folder(+ engine, worktree, monkeypatch+):+ monkeypatch.setattr(common, "current_branch", lambda _w: "claude/verse-wp10-1-shots")+ commands = []++ def runner(command, *, cwd, timeout):+ commands.append(command)+ report = Path(next(a for a in command if a.startswith("-ReportExportPath="))+ .split("=", 1)[1])+ _report(report, [("Verse.Visual.Hangar.Bay", "Success")])+ return common.Completed(0)++ results = screenshot.capture("Verse.Visual.Hangar", worktree=worktree, runner=runner,+ lock_factory=_Lock, stamp="s")+ command = commands[0]+ assert "-nullrhi" not in command+ for flag in ("-game", "-d3d12", "-windowed", "-ResX=1920", "-ResY=1080", "-WinX=-32000"):+ assert flag in command+ proof = worktree / "unreal" / "Verse" / "Saved" / "Harness" / "proof"+ assert results[0].report_dir == proof / "claude-verse-wp10-1-shots" / "s-0"+ assert "Screenshots" not in results[0].report_dir.parts+++def test_only_visual_suites_are_captured(worktree):+ with pytest.raises(common.UnrealScriptError, match="Verse.Visual"):+ screenshot.capture("Verse.Core", worktree=worktree)+++# --- smoke.py ----------------------------------------------------------------+++class _Bridge:+ def __init__(self):+ self.terminated = False++ def terminate(self):+ self.terminated = True++ def wait(self, timeout=None):+ return 0++ def kill(self):+ pass+++def _smoke_setup(worktree, tmp_path, log_text, game_code=0, package_code=0):+ fake_bridge = tmp_path / "fake_bridge.py"+ fake_bridge.write_text("", encoding="utf-8")+ exe = smoke.archive_dir(worktree) / "Windows" / "Verse.exe"+ seen: dict = {"commands": [], "bridge": _Bridge()}++ def runner(command, *, cwd, env=None, timeout=None):+ seen["commands"].append(command)+ if command[1] == "BuildCookRun":+ exe.parent.mkdir(parents=True, exist_ok=True)+ exe.write_text("", encoding="utf-8")+ return common.Completed(package_code)+ seen["token"] = env[smoke.TOKEN_ENV]+ log = Path(next(a for a in command if a.startswith("-abslog=")).split("=", 1)[1])+ log.write_text(log_text, encoding="utf-8")+ return common.Completed(game_code)++ def popen(command, cwd=None):+ seen["bridge_command"] = command+ return seen["bridge"]++ kwargs = dict(worktree=worktree, runner=runner, popen=popen, lock_factory=_Lock,+ fake_bridge=fake_bridge)+ return seen, kwargs+++ALL_STAGES = "".join(f"LogVerse: VerseSmoke: stage {s} OK\n" for s in smoke.DEFAULT_STAGES)+++def test_a_full_smoke_run_passes(engine, worktree, tmp_path, monkeypatch):+ monkeypatch.setattr(common, "free_gb", lambda _p: 500.0)+ seen, kwargs = _smoke_setup(worktree, tmp_path, ALL_STAGES)+ assert smoke.smoke(**kwargs) == []+ package, game = seen["commands"]+ assert "-iostore" in package and "-pak" in package and "-nocompileeditor" in package+ assert "-VerseSmoke=boot,hangar,arena30s" in game+ assert seen["bridge_command"][-2:] == ["--token", seen["token"]]+ assert len(seen["token"]) == 32+ assert seen["bridge"].terminated+ assert len(_Lock.taken) == 1+++def test_smoke_reports_missing_stages_crashes_and_exit_codes(engine, worktree, tmp_path,+ monkeypatch):+ monkeypatch.setattr(common, "free_gb", lambda _p: 500.0)+ log = "VerseSmoke: stage boot OK\nFatal error: [File:x]\n"+ _seen, kwargs = _smoke_setup(worktree, tmp_path, log, game_code=3)+ problems = smoke.smoke(nullrhi=True, **kwargs)+ assert "Verse.exe exited with 3" in problems+ assert "stage hangar not reported OK" in problems+ assert any(p.startswith("log: Fatal error") for p in problems)+++def test_a_failed_package_stops_the_smoke_run(engine, worktree, tmp_path, monkeypatch):+ monkeypatch.setattr(common, "free_gb", lambda _p: 500.0)+ seen, kwargs = _smoke_setup(worktree, tmp_path, ALL_STAGES, package_code=1)+ assert smoke.smoke(**kwargs) == ["BuildCookRun exited with 1"]+ assert len(seen["commands"]) == 1+++def test_smoke_needs_the_fake_bridge(engine, worktree, tmp_path):+ with pytest.raises(common.UnrealScriptError, match="G0.11"):+ smoke.smoke(worktree=worktree, fake_bridge=tmp_path / "missing.py")+++def test_the_game_command_adds_nullrhi_only_when_asked(tmp_path):+ exe, log = tmp_path / "Verse.exe", tmp_path / "log.txt"+ assert "-nullrhi" not in smoke.game_command(exe, ["boot"], log, nullrhi=False)+ assert "-nullrhi" in smoke.game_command(exe, ["boot"], log, nullrhi=True)+++def test_the_real_lock_class_fits_the_factory_signature(tmp_path):+ with contextlib.ExitStack() as stack:+ lock = with_lock.MachineLock("label", "command", directory=tmp_path)+ stack.enter_context(lock)+ assert lock.holder_path.exists()diff --git a/tests/unit/unreal/test_unreal_with_lock.py b/tests/unit/unreal/test_unreal_with_lock.pynew file mode 100644index 0000000000..fafeefe14e--- /dev/null+++ b/tests/unit/unreal/test_unreal_with_lock.py@@ -0,0 +1,240 @@+"""The machine-wide gpu-heavy lock of scripts/unreal/with_lock.py (G0.6)."""++from __future__ import annotations++import json+import os+import subprocess++import pytest++from scripts.unreal import _common as common+from scripts.unreal import with_lock++[email protected](autouse=True)+def _clean_env(monkeypatch):+ monkeypatch.delenv(with_lock.HELD_ENV, raising=False)+++def _lock(tmp_path, pid=1000, alive=lambda _pid: True, messages=None, **kwargs):+ sink = [] if messages is None else messages+ kwargs.setdefault("poll", 0)+ return with_lock.MachineLock(+ "job", ["cmd", "arg"], directory=tmp_path, pid=pid, alive=alive,+ echo=sink.append, **kwargs,+ )+++def test_the_plan_limits_are_one_holder_and_a_ninety_minute_hold():+ assert common.LOCK_HOLDERS == 1+ assert common.MAX_HOLD_MINUTES == 90+ assert common.MAX_PARALLEL_ACTIONS == 10+ assert common.MAX_HEADLESS_JOBS == 4+ assert common.QUEUE_DEPTH_WARN == 8+++def test_the_lock_lives_in_the_shared_machine_folder_unless_overridden():+ if os.name == "nt":+ assert with_lock.lock_dir({}) == with_lock.DEFAULT_LOCK_DIR+ assert str(with_lock.lock_dir({with_lock.LOCK_DIR_ENV: "X:/locks"})).replace("\\", "/") == (+ "X:/locks"+ )+++def test_the_holder_file_says_who_what_when_and_pid_and_goes_on_release(tmp_path):+ lock = _lock(tmp_path)+ with lock:+ holder = json.loads(lock.holder_path.read_text(encoding="utf-8"))+ assert holder["holder"] == "job"+ assert holder["command"] == "cmd arg"+ assert holder["pid"] == 1000+ assert holder["started"]+ assert os.environ[with_lock.HELD_ENV].endswith("|1000")+ assert not list(lock.queue_dir.glob("*.json")), "the ticket goes once the lock is held"+ assert not lock.holder_path.exists()+ assert with_lock.HELD_ENV not in os.environ+++def test_waiters_queue_first_in_first_out(tmp_path):+ queue = tmp_path / "gpu-heavy.queue"+ queue.mkdir()+ older = queue / f"{1:020d}-77.json"+ older.write_text(json.dumps({"pid": 77, "label": "older"}), encoding="utf-8")+ sleeps: list[int] = []++ def sleep(_seconds):+ sleeps.append(1)+ assert len(sleeps) < 50, "never got the lock"+ if len(sleeps) == 3:+ older.unlink() # the older waiter had its turn and left++ lock = _lock(tmp_path, alive=lambda pid: pid in (77, 1000), sleep=sleep)+ lock.acquire()+ try:+ assert len(sleeps) == 3, "the free lock was taken while an older ticket waited"+ finally:+ lock.release()+++def test_tickets_of_dead_processes_are_dropped(tmp_path):+ queue = tmp_path / "gpu-heavy.queue"+ queue.mkdir()+ dead = queue / f"{1:020d}-55.json"+ dead.write_text(json.dumps({"pid": 55}), encoding="utf-8")+ lock = _lock(tmp_path, alive=lambda pid: pid != 55, sleep=lambda _s: pytest.fail("waited"))+ with lock:+ assert not dead.exists()+++def test_a_waiter_waits_on_a_busy_lock_and_a_wait_limit_cleans_its_ticket(tmp_path):+ messages: list[str] = []+ first = _lock(tmp_path, pid=1)+ first.acquire()+ try:+ now = [0.0]++ def sleep(_s):+ now[0] += 10++ # pid 1 counts as dead here only so the second lock does not read the+ # first one's marker in this same test process as its own parent's.+ second = _lock(tmp_path, pid=2, clock=lambda: now[0], sleep=sleep, wait_timeout=35,+ messages=messages, alive=lambda pid: pid != 1)+ with pytest.raises(with_lock.LockTimeout):+ second.acquire()+ assert now[0] > 30, "it waited before giving up"+ assert any("waiting for the gpu-heavy lock" in m and "held by job" in m for m in messages)+ assert not list(second.queue_dir.glob("*.json"))+ finally:+ first.release()+++def test_a_hold_past_ninety_minutes_is_reported_loudly_and_nothing_is_killed(tmp_path):+ messages: list[str] = []+ first = _lock(tmp_path, pid=1)+ first.acquire()+ try:+ holder = json.loads(first.holder_path.read_text(encoding="utf-8"))+ holder["started_epoch"] -= 91 * 60+ first.holder_path.write_text(json.dumps(holder), encoding="utf-8")+ now = [0.0]+ second = _lock(tmp_path, pid=2, wait_timeout=5, messages=messages,+ clock=lambda: now[0], sleep=lambda _s: now.__setitem__(0, now[0] + 1),+ alive=lambda pid: pid != 1)+ with pytest.raises(with_lock.LockTimeout):+ second.acquire()+ assert any("LOCK HELD TOO LONG" in m and "nothing is killed" in m for m in messages)+ assert first.holder_path.exists(), "the long hold is still in place"+ finally:+ first.release()+++def test_a_deep_queue_tells_the_orchestrator_to_stop_scheduling_builds(tmp_path):+ queue = tmp_path / "gpu-heavy.queue"+ queue.mkdir()+ for n in range(common.QUEUE_DEPTH_WARN + 1):+ (queue / f"{n:020d}-{500 + n}.json").write_text(json.dumps({"pid": 500 + n}), "utf-8")+ messages: list[str] = []+ now = [0.0]+ lock = _lock(tmp_path, wait_timeout=1, messages=messages, clock=lambda: now[0],+ sleep=lambda _s: now.__setitem__(0, now[0] + 1))+ with pytest.raises(with_lock.LockTimeout):+ lock.acquire()+ assert any("LOCK QUEUE DEEP" in m for m in messages)+++def test_a_job_under_the_lock_does_not_queue_for_it_again(tmp_path):+ outer = _lock(tmp_path, pid=1)+ outer.acquire()+ try:+ inner = _lock(tmp_path, pid=2, sleep=lambda _s: pytest.fail("nested lock waited"))+ with inner:+ assert inner.nested+ assert not list(inner.queue_dir.glob("*.json"))+ assert outer.holder_path.exists(), "the inner release left the outer hold alone"+ finally:+ outer.release()+++def test_a_held_marker_of_a_dead_process_is_not_trusted(tmp_path, monkeypatch):+ monkeypatch.setenv(with_lock.HELD_ENV, f"{tmp_path / 'gpu-heavy.lock'}|4242")+ lock = _lock(tmp_path, pid=1, alive=lambda pid: pid != 4242)+ with lock:+ assert not lock.nested+ assert lock.holder_path.exists()+++def test_a_running_process_is_alive_and_a_free_pid_is_not():+ assert with_lock.pid_alive(os.getpid())+ assert not with_lock.pid_alive(0)+++class _FakeProcess:+ def __init__(self, timeout=False):+ self.timeout = timeout+ self.killed = False+ self.calls = 0++ def wait(self, timeout=None):+ self.calls += 1+ if self.timeout and self.calls == 1:+ raise subprocess.TimeoutExpired("cmd", timeout)+ return -9 if self.killed else 0++ def kill(self):+ self.killed = True+++def _factory(tmp_path):+ return lambda label, command: _lock(tmp_path, pid=os.getpid())+++def test_run_locked_runs_the_command_inside_the_hold_and_hands_down_the_marker(tmp_path):+ seen = {}++ def popen(command, cwd=None, env=None):+ seen["command"] = command+ seen["held"] = env[with_lock.HELD_ENV]+ seen["holder_file"] = (tmp_path / "gpu-heavy.holder.json").exists()+ return _FakeProcess()++ code = with_lock.run_locked(["a", "b"], label="x", popen=popen,+ lock_factory=_factory(tmp_path))+ assert code == 0+ assert seen == {"command": ["a", "b"], "held": seen["held"], "holder_file": True}+ assert seen["held"].endswith(f"|{os.getpid()}")+ assert not (tmp_path / "gpu-heavy.holder.json").exists()+++def test_run_locked_stops_only_its_own_job_after_the_hold_limit(tmp_path, capsys):+ process = _FakeProcess(timeout=True)+ code = with_lock.run_locked(["slow"], label="slow", popen=lambda *a, **k: process,+ lock_factory=_factory(tmp_path), max_hold_minutes=0.01)+ assert code == 124+ assert process.killed+ assert "LOCK HOLD TIMEOUT" in capsys.readouterr().out+ assert not (tmp_path / "gpu-heavy.holder.json").exists()+++def test_status_lists_the_live_holder_and_queue(tmp_path):+ with _lock(tmp_path, pid=os.getpid()):+ report = with_lock.status(tmp_path, alive=lambda _pid: True)+ assert report["holder"]["holder"] == "job"+ assert report["queue"] == []+ assert with_lock.status(tmp_path, alive=lambda _pid: True)["holder"] is None+++def test_the_cli_needs_a_command():+ with pytest.raises(SystemExit):+ with_lock.main(["--label", "x"])+++def test_the_blender_runner_takes_the_same_machine_lock(tmp_path, monkeypatch):+ from scripts.verse import blender++ monkeypatch.setenv(with_lock.LOCK_DIR_ENV, str(tmp_path))+ with blender.gpu_lock("cook hangar"):+ holder = json.loads((tmp_path / "gpu-heavy.holder.json").read_text(encoding="utf-8"))+ assert holder["holder"] == "blender cook hangar"+ assert not (tmp_path / "gpu-heavy.holder.json").exists()diff --git a/tests/unit/unreal/test_unreal_worktree_and_doctor.py b/tests/unit/unreal/test_unreal_worktree_and_doctor.pynew file mode 100644index 0000000000..3d5e97f46f--- /dev/null+++ b/tests/unit/unreal/test_unreal_worktree_and_doctor.py@@ -0,0 +1,276 @@+"""worktree.py and doctor.py of scripts/unreal (G0.6, G0.1); git and the box are faked."""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from scripts.unreal import _common as common+from scripts.unreal import doctor, worktree++# --- worktree.py -------------------------------------------------------------+++ "slug", ["wp01-2-recoil-curve", "wp22-1-installer", "wp02-4a-rewind", "int-wire-combat"]+)+def test_plan_slugs_are_accepted(slug):+ assert worktree.validate_slug(slug) == slug+++ "slug", ["wp23-1-x", "wp1-1-x", "wp01-x", "WP01-1-x", "wp01-1-", "feature-x", "wp01-1-a_b"]+)+def test_other_slugs_are_refused(slug):+ with pytest.raises(common.UnrealScriptError):+ worktree.validate_slug(slug)+++def test_short_ids_have_at_most_twelve_characters_and_never_collide():+ assert worktree.short_id("wp01-2-recoil-curve") == "wp01-2-recoi"+ assert worktree.short_id("int-a") == "int-a"+ taken = {"wp01-2-recoi", "wp01-2-rec-2"}+ chosen = worktree.short_id("wp01-2-recoil-curve", taken=taken.__contains__)+ assert chosen == "wp01-2-rec-3"+ assert len(chosen) <= worktree.MAX_ID+ assert not worktree.short_id("wp01-2-abcde-x").endswith("-")+++class _Git:+ def __init__(self, fail=None, branch_exists=False, listing=""):+ self.calls: list[list[str]] = []+ self.fail = fail+ self.branch_exists = branch_exists+ self.listing = listing++ def __call__(self, command, capture=False, **_kw):+ self.calls.append(command)+ if command[0] == "git" and "rev-parse" in command:+ return common.Completed(0 if self.branch_exists else 1)+ if command[0] == "git" and command[3:5] == ["worktree", "list"]:+ return common.Completed(0, self.listing)+ if self.fail and self.fail in command:+ return common.Completed(1, "", "boom")+ return common.Completed(0)+++def test_new_fetches_branches_off_origin_main_and_fetches_every_lfs_object(tmp_path):+ git = _Git()+ path = worktree.new("wp05-3-blood-decal", root=tmp_path, runner=git)+ assert path == tmp_path / "wp05-3-blood"+ commands = [c[3:] for c in git.calls]+ assert commands[0] == ["fetch", "origin"]+ assert ["worktree", "add", "-b", "claude/verse-wp05-3-blood-decal", str(path),+ "origin/main"] in commands+ last = git.calls[-1]+ assert last[1:3] == ["-C", str(path)]+ assert last[3:] == ["config", "lfs.fetchexclude", ""]+++def test_new_refuses_an_existing_branch_and_a_bad_id(tmp_path):+ with pytest.raises(common.UnrealScriptError, match="already exists"):+ worktree.new("int-x", root=tmp_path, runner=_Git(branch_exists=True))+ with pytest.raises(common.UnrealScriptError, match="--id"):+ worktree.new("int-x", root=tmp_path, wt_id="far-too-long-id", runner=_Git())+++def test_new_stops_when_the_fetch_fails(tmp_path):+ git = _Git(fail="fetch")+ with pytest.raises(common.UnrealScriptError, match="git fetch origin failed"):+ worktree.new("int-x", root=tmp_path, runner=git)+ assert not any("add" in c for c in git.calls)+++def _listing(*paths: Path) -> str:+ return "".join(f"worktree {p}\nHEAD 0\nbranch refs/heads/x\n\n" for p in paths)+++def test_remove_cleans_then_unlinks_node_modules_then_removes_the_worktree(tmp_path, monkeypatch):+ main, tree = tmp_path / "main", tmp_path / "wt" / "int-x"+ for folder in (main, tree / "dodaios" / "ui" / "node_modules", tree / "real" / "nm"):+ folder.mkdir(parents=True)+ link = tree / "dodaios" / "ui" / "node_modules"+ monkeypatch.setattr(worktree, "_is_link", lambda p: p == link)+ order: list[str] = []+ git = _Git(listing=_listing(main, tree))++ def runner(command, capture=False, **kw):+ if command[:3] == ["cmd", "/c", "rmdir"]:+ order.append(f"unlink {Path(command[3]).name}")+ return common.Completed(0)+ if "remove" in command:+ order.append("git worktree remove")+ return git(command, capture=capture, **kw)++ monkeypatch.setattr(worktree, "_WINDOWS", True)+ worktree.remove(str(tree), runner=runner, cleaner=lambda p: order.append(f"clean {p.name}"))+ assert order == ["clean int-x", "unlink node_modules", "git worktree remove"]+ assert not any("--force" in c for c in git.calls)+++def test_remove_never_touches_the_main_checkout_or_a_foreign_folder(tmp_path):+ main, other = tmp_path / "main", tmp_path / "other"+ main.mkdir()+ other.mkdir()+ git = _Git(listing=_listing(main))+ with pytest.raises(common.UnrealScriptError, match="main checkout"):+ worktree.remove(str(main), runner=git, cleaner=lambda p: pytest.fail("cleaned"))+ with pytest.raises(common.UnrealScriptError, match="not a worktree"):+ worktree.remove(str(other), runner=git, cleaner=lambda p: pytest.fail("cleaned"))+++def test_the_link_walk_never_descends_into_node_modules_or_build_output(tmp_path, monkeypatch):+ plain = tmp_path / "a" / "node_modules"+ nested = plain / "pkg" / "node_modules"+ hidden = tmp_path / "unreal" / "Verse" / "Intermediate" / "node_modules"+ for folder in (nested, hidden):+ folder.mkdir(parents=True)+ monkeypatch.setattr(worktree, "_is_link", lambda p: p in (nested, hidden))+ assert list(worktree.node_modules_links(tmp_path)) == []+++# --- doctor.py ---------------------------------------------------------------++PINS = json.loads(common.TOOLCHAINS_FILE.read_text(encoding="utf-8"))+ENGINE = Path("E:/UE")+VS = Path("E:/VS")+WINDOWS_SDK_JSON = {+ "MainVersion": "10.0.22621.0",+ "BannedVisualCppVersions": ["14.44.0-14.44.35210", "14.40.0-14.43.99999"],+}+++def _box(cl="19.44.35229", vs="17.14.37827.9", lfs="3.7.1", release=533509, linux_root=None,+ missing=()):+ files = {+ ENGINE / "Engine" / "Build" / "Build.version": json.dumps(+ {"MajorVersion": 5, "MinorVersion": 7, "PatchVersion": 1}),+ ENGINE / "Engine/Config/Windows/Windows_SDK.json": json.dumps(WINDOWS_SDK_JSON),+ ENGINE / "Engine/Config/Linux/Linux_SDK.json": json.dumps(+ {"MainVersion": PINS["linux"]["sdk"]}),+ common.project_file(common.REPO_ROOT): json.dumps({"EngineAssociation": "5.7"}),+ }+ sdk_root = Path(PINS["windows_sdk"]["root"])+ ref_root = Path(PINS["netfx"]["reference_root"])+ cl_path = VS / "VC" / "Tools" / "MSVC" / "14.44.35207" / "bin" / "Hostx64" / "x64" / "cl.exe"+ present = {doctor.VSWHERE, cl_path, sdk_root / "Include" / "10.0.22621.0",+ sdk_root / "Lib" / "10.0.22621.0", ref_root / "v4.6.2", ref_root / "v4.8.1"}+ env = {common.ENGINE_ENV: str(ENGINE)}+ if linux_root:+ env["LINUX_MULTIARCH_ROOT"] = linux_root+ present.add(Path(linux_root) / "x86_64-unknown-linux-gnu" / "bin" / "clang++.exe")+ present -= set(missing)++ def run(command, capture=False, **_kw):+ if command[0] == str(doctor.VSWHERE):+ return common.Completed(0, json.dumps([{+ "installationPath": str(VS), "installationVersion": vs,+ "productId": "Microsoft.VisualStudio.Product.BuildTools"}]))+ if command[0] == str(cl_path):+ return common.Completed(0, "", f"Microsoft (R) C/C++ Optimizing Compiler Version "+ f"{cl} for x64\n")+ if command[:3] == ["git", "lfs", "version"]:+ return common.Completed(0, f"git-lfs/{lfs} (GitHub; windows amd64)\n")+ return common.Completed(1)++ def read_text(path):+ if path in files:+ return files[path]+ raise OSError(path)++ return doctor.Probe(+ run=run,+ exists=lambda p: p in present,+ read_text=read_text,+ listdir=lambda p: ["14.44.35207"] if p == VS / "VC" / "Tools" / "MSVC" else [],+ env=env,+ free_gb=lambda _p: 200.0,+ netfx_release=lambda: release,+ is_windows=True,+ )+++def _status(checks):+ return {c.name: c.status for c in checks}+++def test_this_box_as_of_today_is_green_for_win64(tmp_path, monkeypatch):+ monkeypatch.setenv("DODAIOS_LOCK_DIR", str(tmp_path))+ probe = _box()+ probe.env["DODAIOS_LOCK_DIR"] = str(tmp_path)+ checks = doctor.diagnose(["win64"], probe=probe, pins=PINS)+ assert [c for c in checks if c.status == "fail"] == []+ assert _status(checks)["linux-toolchain"] == "skip"+++def test_a_missing_linux_toolchain_is_red_with_a_fix(tmp_path):+ probe = _box()+ probe.env["DODAIOS_LOCK_DIR"] = str(tmp_path)+ linux = next(c for c in doctor.diagnose(probe=probe, pins=PINS) if c.name == "linux-toolchain")+ assert linux.status == "fail" and "LINUX_MULTIARCH_ROOT" in linux.detail+ assert PINS["linux"]["sdk"] in linux.fix+++def test_an_installed_linux_toolchain_is_green(tmp_path):+ root = f"E:/UnrealToolchains/{PINS['linux']['sdk']}"+ probe = _box(linux_root=root)+ probe.env["DODAIOS_LOCK_DIR"] = str(tmp_path)+ assert _status(doctor.diagnose(probe=probe, pins=PINS))["linux-toolchain"] == "ok"+++ ("kwargs", "name"),+ [+ ({"cl": "19.44.35207"}, "msvc"), # inside the engine's banned range+ ({"cl": "19.42.34433"}, "msvc"),+ ({"vs": "17.8.0"}, "visual-studio"),+ ({"lfs": "3.4.0"}, "git-lfs"),+ ({"release": 528040}, "netfx-runtime"),+ ({"missing": [Path(PINS["netfx"]["reference_root"]) / "v4.6.2"]}, "netfx-targeting"),+ ({"missing": [Path(PINS["windows_sdk"]["root"]) / "Lib" / "10.0.22621.0"]},+ "windows-sdk"),+ ],+)+def test_each_wrong_tool_turns_its_check_red(tmp_path, kwargs, name):+ probe = _box(**kwargs)+ probe.env["DODAIOS_LOCK_DIR"] = str(tmp_path)+ assert _status(doctor.diagnose(["win64"], probe=probe, pins=PINS))[name] == "fail"+++def test_low_disk_and_a_wrong_engine_are_red(tmp_path):+ probe = _box()+ probe.env["DODAIOS_LOCK_DIR"] = str(tmp_path)+ probe.free_gb = lambda _p: 12.0+ pins = json.loads(json.dumps(PINS))+ pins["engine"]["version"] = "5.7.2"+ status = _status(doctor.diagnose(["win64"], probe=probe, pins=pins))+ assert status["disk"] == "fail"+ assert status["engine"] == "fail"+++def test_version_ranges_follow_the_engine_file_format():+ assert doctor.in_range("14.44.35207", "14.44.0-14.44.35210")+ assert not doctor.in_range("14.44.35229", "14.44.0-14.44.35210")+ assert doctor.in_range("10.0.22621.0", "10.0.22621.0")+++def test_the_pins_match_the_plan_and_the_shared_limits():+ assert PINS["schema"] == "verse.toolchains/1"+ assert PINS["engine"]["version"] == "5.7.1"+ assert PINS["disk"]["min_free_gb"] == common.MIN_FREE_GB+ assert PINS["msvc"]["family"] == "14.44"+++def test_the_pins_match_the_installed_engine_when_there_is_one():+ engine = common.engine_root()+ sdk = engine / "Engine" / "Config" / "Windows" / "Windows_SDK.json"+ if not sdk.is_file():+ pytest.skip("no Unreal install on this machine")+ windows = json.loads(sdk.read_text(encoding="utf-8-sig"))+ linux = json.loads((engine / "Engine/Config/Linux/Linux_SDK.json").read_text("utf-8-sig"))+ assert windows["MainVersion"] == PINS["windows_sdk"]["version"]+ assert linux["MainVersion"] == PINS["linux"]["sdk"]+ assert not any(doctor.in_range(PINS["msvc"]["min_version"], s)+ for s in windows["BannedVisualCppVersions"])diff --git a/unreal/Toolchain/toolchains.json b/unreal/Toolchain/toolchains.jsonnew file mode 100644index 0000000000..1901c3b827--- /dev/null+++ b/unreal/Toolchain/toolchains.json@@ -0,0 +1,37 @@+{+ "schema": "verse.toolchains/1",+ "about": "Toolchain pins of the Unreal Verse (docs/verse/unreal/architecture.md 8.1). scripts/unreal/doctor.py checks the box against them and against the engine's own Windows_SDK.json and Linux_SDK.json.",+ "engine": {+ "version": "5.7.1",+ "association": "5.7",+ "windows_root": "C:/Program Files/Epic Games/UE_5.7"+ },+ "visual_studio": {+ "min_version": "17.14",+ "workloads_note": "VS 2022 Build Tools with the C++ x64 tools of the MSVC family below and the Windows SDK below"+ },+ "msvc": {+ "family": "14.44",+ "min_version": "14.44.35211"+ },+ "windows_sdk": {+ "version": "10.0.22621.0",+ "root": "C:/Program Files (x86)/Windows Kits/10"+ },+ "netfx": {+ "runtime": "4.8.1",+ "min_release": 533320,+ "targeting_packs": ["v4.6.2", "v4.8.1"],+ "reference_root": "C:/Program Files (x86)/Reference Assemblies/Microsoft/Framework/.NETFramework"+ },+ "git_lfs": {+ "min_version": "3.7.1"+ },+ "linux": {+ "sdk": "v26_clang-20.1.8-rockylinux8",+ "env": "LINUX_MULTIARCH_ROOT"+ },+ "disk": {+ "min_free_gb": 40+ }+}