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 harness lanes, balance gates, netcode, perf and capture tools (#1139)
Ruben Lütke59f6b7f27be3
diff --git a/.github/actionlint.yaml b/.github/actionlint.yamlnew file mode 100644index 0000000000..6a450b16b5--- /dev/null+++ b/.github/actionlint.yaml@@ -0,0 +1,5 @@+# actionlint configuration (run by ci.yml static gates).+self-hosted-runner:+ # The Unreal box (architecture.md 8.2): unreal-build, unreal-gauntlet, unreal-perf.+ labels:+ - unrealdiff --git a/.github/workflows/unreal-build.yml b/.github/workflows/unreal-build.ymlnew file mode 100644index 0000000000..d44cf2bb65--- /dev/null+++ b/.github/workflows/unreal-build.yml@@ -0,0 +1,119 @@+# unreal-build: compile and test the Unreal Verse on the self-hosted runner (architecture.md+# 8.2, 8.3; work-packages.md WP10.2, WP10.3). Fork pull requests never reach the runner: the+# only pull_request job is guarded on the head repository (A10.2).+name: unreal-build++on:+ pull_request:+ paths:+ - "unreal/**"+ - "art/verse/**"+ - "scripts/unreal/**"+ - ".github/workflows/unreal-build.yml"+ merge_group:+ push:+ branches: [main]+ paths:+ - "unreal/**"+ - "art/verse/**"+ - "scripts/unreal/**"+ workflow_dispatch:++permissions:+ contents: read++# One concurrency group per ref: GitHub keeps only one pending run per group, so a shared+# group would let a newer merge-queue entry cancel an older pending one. Machine-wide+# serialisation (one Unreal job at a time, also against local agent builds) is the job of+# scripts/unreal/with_lock.py, which every Unreal step goes through.+concurrency:+ group: unreal-build-${{ github.ref }}+ cancel-in-progress: false++jobs:+ changes:+ name: unreal-build (path filter)+ runs-on: ubuntu-24.04+ timeout-minutes: 5+ outputs:+ unreal: ${{ steps.diff.outputs.unreal }}+ steps:+ - id: diff+ name: Unreal paths in this change+ env:+ GH_TOKEN: ${{ github.token }}+ EVENT: ${{ github.event_name }}+ REPO: ${{ github.repository }}+ BASE: ${{ github.event.merge_group.base_sha }}+ HEAD: ${{ github.event.merge_group.head_sha }}+ run: |+ # Only merge-queue entries are filtered here; the other triggers carry their own+ # path filter or run on a schedule. Any doubt (API error, 300+ files) means run.+ if [ "$EVENT" != "merge_group" ]; then+ echo "unreal=true" >> "$GITHUB_OUTPUT"+ exit 0+ fi+ if ! files=$(gh api "repos/$REPO/compare/$BASE...$HEAD" --jq '.files[].filename'); then+ echo "unreal=true" >> "$GITHUB_OUTPUT"+ exit 0+ fi+ count=$(printf '%s\n' "$files" | grep -c . || true)+ pattern='^(unreal/|art/verse/|docs/verse/unreal/|scripts/unreal/|\.github/workflows/unreal-)'+ if [ "$count" -ge 300 ] || printf '%s\n' "$files" | grep -qE "$pattern"; then+ echo "unreal=true" >> "$GITHUB_OUTPUT"+ else+ echo "unreal=false" >> "$GITHUB_OUTPUT"+ echo "no Unreal path in this queue entry; the lane is skipped"+ fi++ win64:+ name: unreal-build (Win64 Editor + Game, automation, netcode)+ needs: changes+ if: needs.changes.outputs.unreal == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)+ runs-on: [self-hosted, windows, unreal]+ timeout-minutes: 240+ defaults:+ run:+ shell: pwsh+ steps:+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0+ with:+ lfs: true+ persist-credentials: false+ - name: Toolchain+ run: python scripts/unreal/doctor.py --target win64+ - name: Build Win64 Development Editor+ run: python scripts/unreal/build.py editor+ - name: Build Win64 Development Game+ run: python scripts/unreal/build.py game+ - name: Automation tests under -nullrhi+ run: python scripts/unreal/test.py "Verse" --jobs 4+ - name: Netcode smoke (dedicated + 2 lagged clients, 2 minutes)+ run: python scripts/unreal/netcode.py --iris on+ - name: Upload reports+ if: always()+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2+ with:+ name: unreal-build-reports+ path: |+ unreal/Verse/Saved/Automation/+ unreal/Verse/Saved/Harness/netcode/+ if-no-files-found: warn+ retention-days: 14++ linux:+ name: unreal-build (Linux Game, cross)+ if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository+ needs: win64+ runs-on: [self-hosted, windows, unreal]+ timeout-minutes: 180+ defaults:+ run:+ shell: pwsh+ steps:+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0+ with:+ lfs: true+ persist-credentials: false+ - name: Build Linux Development Game (cross toolchain, LINUX_MULTIARCH_ROOT)+ run: python scripts/unreal/build.py linuxdiff --git a/.github/workflows/unreal-gauntlet.yml b/.github/workflows/unreal-gauntlet.ymlnew file mode 100644index 0000000000..013ed5d6f7--- /dev/null+++ b/.github/workflows/unreal-gauntlet.yml@@ -0,0 +1,115 @@+# unreal-gauntlet: headless bot-vs-bot balance runs and their gates (contracts/bot.md 11;+# architecture.md 8.3; work-packages.md WP10.5). The merge queue runs the short subset of+# bot.md 11.4 (BG1, BG2, BG4 for spray, camper, rusher, wallspam, BG11), nightly runs all.+# No pull_request trigger: fork code never reaches the self-hosted runner.+name: unreal-gauntlet++on:+ merge_group:+ schedule:+ - cron: "0 0 * * *"+ workflow_dispatch:+ inputs:+ mode:+ description: "queue or nightly"+ default: queue+ type: choice+ options: [queue, nightly]++permissions:+ contents: read++# One concurrency group per ref (a shared group keeps only one pending run and cancels the+# rest); scripts/unreal/with_lock.py serialises the Unreal work on the machine.+concurrency:+ group: unreal-gauntlet-${{ github.ref }}+ cancel-in-progress: false++jobs:+ changes:+ name: unreal-gauntlet (path filter)+ runs-on: ubuntu-24.04+ timeout-minutes: 5+ outputs:+ unreal: ${{ steps.diff.outputs.unreal }}+ steps:+ - id: diff+ name: Unreal paths in this change+ env:+ GH_TOKEN: ${{ github.token }}+ EVENT: ${{ github.event_name }}+ REPO: ${{ github.repository }}+ BASE: ${{ github.event.merge_group.base_sha }}+ HEAD: ${{ github.event.merge_group.head_sha }}+ run: |+ # Only merge-queue entries are filtered here; the other triggers carry their own+ # path filter or run on a schedule. Any doubt (API error, 300+ files) means run.+ if [ "$EVENT" != "merge_group" ]; then+ echo "unreal=true" >> "$GITHUB_OUTPUT"+ exit 0+ fi+ if ! files=$(gh api "repos/$REPO/compare/$BASE...$HEAD" --jq '.files[].filename'); then+ echo "unreal=true" >> "$GITHUB_OUTPUT"+ exit 0+ fi+ count=$(printf '%s\n' "$files" | grep -c . || true)+ pattern='^(unreal/|art/verse/|docs/verse/unreal/|scripts/unreal/|\.github/workflows/unreal-)'+ if [ "$count" -ge 300 ] || printf '%s\n' "$files" | grep -qE "$pattern"; then+ echo "unreal=true" >> "$GITHUB_OUTPUT"+ else+ echo "unreal=false" >> "$GITHUB_OUTPUT"+ echo "no Unreal path in this queue entry; the lane is skipped"+ fi++ gauntlet:+ name: unreal-gauntlet+ needs: changes+ if: needs.changes.outputs.unreal == 'true'+ runs-on: [self-hosted, windows, unreal]+ timeout-minutes: 300+ defaults:+ run:+ shell: pwsh+ env:+ MODE: ${{ github.event_name == 'schedule' && 'nightly' || inputs.mode || 'queue' }}+ steps:+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0+ with:+ lfs: true+ persist-credentials: false+ - name: Build Win64 Development Editor+ run: python scripts/unreal/build.py editor+ # F2, F3 and BR1 come from automation tests (bot.md 10). Until WP07/WP08 add them the+ # filter matches nothing and this step fails; BG11 then reports not_run, never pass.+ - name: Fairness automation tests (F2, F3, BR1)+ continue-on-error: true+ run: python scripts/unreal/test.py "Verse.Bot.Fairness+Verse.Combat.Perception+Verse.Bot.Brain.Replay" --jobs 3+ # Queue: 40 bouts per pairing (balance.QUEUE_BOUTS). The bout table records the 95 %+ # interval this gives (queueHalfWidth: about +-0.15 bout share, +-0.03 kill share at+ # 22 kills per bout); the queue gates are one-sided and catch large regressions only.+ - name: Balance run and gates+ run: |+ $checks = 'unreal/Verse/Saved/Automation'+ if ($env:MODE -eq 'nightly') {+ python scripts/unreal/balance.py --set all --nightly --jobs 4 --seed $env:GITHUB_RUN_NUMBER `+ --checks-from-automation $checks+ } else {+ python scripts/unreal/balance.py --set ladder --set tricks --tricks spray,camper,rusher,wallspam `+ --gates BG1,BG2,BG4,BG11 --bouts 40 --jobs 4 --seed $env:GITHUB_RUN_NUMBER `+ --checks-from-automation $checks+ }+ exit $LASTEXITCODE+ - name: Nightly netcode with Iris on and off+ if: env.MODE == 'nightly'+ run: python scripts/unreal/netcode.py --iris both+ - name: Upload reports+ if: always()+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2+ with:+ name: unreal-gauntlet-reports+ path: |+ unreal/Verse/Saved/Harness/balance/**/report.json+ unreal/Verse/Saved/Harness/balance/**/fire_audit.log+ unreal/Verse/Saved/Harness/netcode/+ if-no-files-found: warn+ retention-days: 30diff --git a/.github/workflows/unreal-perf.yml b/.github/workflows/unreal-perf.ymlnew file mode 100644index 0000000000..7a2c01677a--- /dev/null+++ b/.github/workflows/unreal-perf.yml@@ -0,0 +1,48 @@+# unreal-perf: nightly GPU perf capture of the fixed replay against architecture.md 7, plus+# the reference-view screenshots and palette shares (art-pipeline.md 8.1, 14). Runs only in+# the quiet hours and skips when the person used the machine in the last 5 minutes+# (scripts/unreal/perf.py). No pull_request trigger.+name: unreal-perf++on:+ schedule:+ - cron: "30 1 * * *"+ workflow_dispatch:++permissions:+ contents: read++# Schedule and manual runs only. One group per ref; with_lock.py serialises the machine.+concurrency:+ group: unreal-perf-${{ github.ref }}+ cancel-in-progress: false++jobs:+ perf:+ name: unreal-perf+ runs-on: [self-hosted, windows, unreal]+ timeout-minutes: 120+ defaults:+ run:+ shell: pwsh+ steps:+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0+ with:+ lfs: true+ persist-credentials: false+ - name: Build Win64 Development Editor+ run: python scripts/unreal/build.py editor+ - name: Perf replay, two runs (budgets and A10.5 stability)+ run: python scripts/unreal/perf.py run --profile 1440p --runs 2+ - name: Reference views and palette shares+ run: python scripts/unreal/capture.py shots --wp WP10 --subtask 10.7+ - name: Upload perf and screenshots+ if: always()+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2+ with:+ name: unreal-perf+ path: |+ unreal/Verse/Saved/Harness/perf/+ unreal/Verse/Saved/Harness/proof/WP10/+ if-no-files-found: warn+ retention-days: 30diff --git a/.github/workflows/unreal-static.yml b/.github/workflows/unreal-static.ymlnew file mode 100644index 0000000000..15b1ba8c76--- /dev/null+++ b/.github/workflows/unreal-static.yml@@ -0,0 +1,103 @@+# unreal-static: the GitHub-hosted static lane of the Unreal Verse (architecture.md 8.3,+# work-packages.md WP10.1). LFS off, no engine, at most 5 minutes. A required check only+# through the CI gate job the integration owner wires into ci.yml (architecture.md 8.2).+name: unreal-static++on:+ pull_request:+ paths:+ - "unreal/**"+ - "art/verse/**"+ - "docs/verse/unreal/**"+ - "scripts/unreal/**"+ - "tests/unit/unreal_scripts/**"+ - ".github/workflows/unreal-*.yml"+ merge_group:+ push:+ branches: [main]+ paths:+ - "unreal/**"+ - "art/verse/**"+ - "docs/verse/unreal/**"+ - "scripts/unreal/**"+ - ".github/workflows/unreal-*.yml"+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: unreal-static-${{ github.ref }}+ cancel-in-progress: true++jobs:+ static:+ name: unreal-static+ runs-on: ubuntu-24.04+ timeout-minutes: 5+ steps:+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0+ with:+ fetch-depth: 0+ lfs: false+ persist-credentials: false+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: "3.11"+ - name: Install the checkers' dependencies+ run: python -m pip install --disable-pip-version-check -q pyyaml jsonschema filelock numpy pillow pytest+ - name: Find the base commit+ id: base+ env:+ EVENT: ${{ github.event_name }}+ PR_BASE: ${{ github.event.pull_request.base.sha }}+ MQ_BASE: ${{ github.event.merge_group.base_sha }}+ PUSH_BEFORE: ${{ github.event.before }}+ run: |+ case "$EVENT" in+ pull_request) base="$PR_BASE" ;;+ merge_group) base="$MQ_BASE" ;;+ push) base="$PUSH_BEFORE" ;;+ *) base="$(git rev-parse HEAD~1)" ;;+ esac+ if ! git cat-file -e "$base^{commit}" 2>/dev/null; then base="$(git rev-parse HEAD~1)"; fi+ echo "sha=$base" >> "$GITHUB_OUTPUT"+ - name: Build.cs DAG+ run: python scripts/unreal/check_build_dag.py+ - name: Forbidden names (tracked files, added lines, commit messages)+ env:+ BASE: ${{ steps.base.outputs.sha }}+ run: |+ python scripts/unreal/check_forbidden_names.py+ python scripts/unreal/check_forbidden_names.py --diff "$BASE"+ - name: Forbidden names (PR title)+ if: github.event_name == 'pull_request'+ env:+ TITLE: ${{ github.event.pull_request.title }}+ run: printf '%s\n' "$TITLE" | python scripts/unreal/check_forbidden_names.py --stdin+ - name: Forbidden folder names and engine content+ run: python scripts/unreal/check_forbidden_names.py --folders+ - name: Bot isolation (F1) and perception symmetry (F6)+ run: python scripts/unreal/check_bot_isolation.py+ - name: LFS pointers, remote objects, size gate+ env:+ BASE: ${{ steps.base.outputs.sha }}+ GITHUB_TOKEN: ${{ github.token }}+ run: python scripts/unreal/check_lfs.py --diff "$BASE"+ - name: clang-format (changed lines)+ env:+ BASE: ${{ steps.base.outputs.sha }}+ run: |+ if ! command -v git-clang-format >/dev/null; then echo "::warning::git-clang-format missing"; exit 0; fi+ out="$(git clang-format --style=file:unreal/Verse/Harness/clang-format.yml --diff "$BASE" -- 'unreal/Verse/Source/*.h' 'unreal/Verse/Source/*.cpp' || true)"+ case "$out" in+ ""|*"no modified files to format"*|*"clang-format did not modify any files"*) echo "clang-format: clean" ;;+ *) printf '%s\n' "$out"; echo "::error::run git clang-format with unreal/Verse/Harness/clang-format.yml"; exit 1 ;;+ esac+ - name: Licence ledger and art text checks+ run: |+ if [ -f scripts/unreal/check_art_text.py ]; then python scripts/unreal/check_art_text.py; else echo "art text checks land with G0.7"; fi+ - name: Workflow policy (permissions, SHA pins, gate needs)+ run: python scripts/ci/check_workflow_policy.py+ - name: Harness script tests and fork safety (A10.2)+ run: python -m pytest -q -p no:cacheprovider --noconftest tests/unit/unreal_scriptsdiff --git a/scripts/unreal/balance.py b/scripts/unreal/balance.pynew file mode 100644index 0000000000..2ffb869dbb--- /dev/null+++ b/scripts/unreal/balance.py@@ -0,0 +1,1653 @@+#!/usr/bin/env python3+"""Headless bot-vs-bot balance runs and their gates (docs/verse/unreal/contracts/bot.md 10, 11).++The driver plans pairings for the named sets, writes one ``verse.scenario/1``+file per job, runs up to ``--jobs`` headless editors as dedicated servers under+the machine lock (bot.md 11.1, orchestration.md 4), reads the ``verse.bout/1``+lines the ``UVerseBalanceGauntletController`` writes, and turns them into the+``verse.balance/1`` report with the gates BG1-BG12, F1-F7, L1 and BR1.++ python scripts/unreal/balance.py --set ladder --bouts 200 --seed 7 --jobs 4+ python scripts/unreal/balance.py --set ladder --set tricks --tricks spray,camper \\+ --gates BG1,BG2,BG4,BG11 --bouts 40 # the merge-queue subset+ python scripts/unreal/balance.py --set all --patch tiers_patch.json+ python scripts/unreal/balance.py --from-bouts <dir> # gates from recorded bouts, no run+ python scripts/unreal/balance.py --plan --set all # print the plan only+ python scripts/unreal/balance.py --speed # measure x real time, write the bout table++Seeds: every pairing gets ``sha256(run seed, pairing id)``, every match of it+``sha256(pairing seed, match)``. A unit (one match of one pairing) is the+smallest piece of work, so the result is the same for any ``--jobs``.+"""++from __future__ import annotations++import argparse+import hashlib+import json+import math+import os+import re+import statistics+import subprocess+import sys+import time+from collections.abc import Callable, Iterable, Mapping, Sequence+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 check_bot_isolation++HARNESS_DIR = common.PROJECT_DIR / "Harness"+SETS_FILE = HARNESS_DIR / "balance" / "sets.json"+BOUT_TABLE_FILE = HARNESS_DIR / "balance" / "bout_table.json"+PERSON_MODELS_FILE = common.PROJECT_DIR / "Data" / "bot" / "person_models.json"+L1_FIELDS_FILE = HARNESS_DIR / "fairness" / "match_memory_fields.json"+SCHEMA_DIR = HARNESS_DIR / "schema"++SET_NAMES = ("ladder", "humans", "tricks", "elite", "cross", "learning", "adaptive", "fairness")+GATE_IDS = (+ "BG1",+ "BG2",+ "BG3",+ "BG4",+ "BG5",+ "BG6",+ "BG7",+ "BG8",+ "BG9",+ "BG10",+ "BG11",+ "BG12",+ "F1",+ "F2",+ "F3",+ "F4",+ "F5",+ "F6",+ "F7",+ "L1",+ "BR1",+)+Z95 = 1.959963984540054+HALF_WIDTH = 0.06+RANGE_BINS = ((0, 5), (5, 10), (10, 20), (20, 35), (35, math.inf))+PROCESS_TIMEOUT_S = 80 * 60+DEFAULT_KILLS_PER_BOUT = 22.0+F5_MIN_WINDOWS = 2000+F5_FACING_DEG = 15.0+F5_MAX_EXCESS = 0.05+#: L1 (bot.md 10): the scan runs after a 30-minute match; the bout has no kill cap.+L1_MATCH_S = 1800.0+NO_KILL_CAP = 1_000_000+#: The end reason of a scenario every unit of which was played (speed.json "end").+END_ALL_PLAYED = "all units played"+#: Bouts per pairing in the merge queue (unreal-gauntlet.yml). Shorter than the table's+#: +-0.06 count on purpose: the queue gates are one-sided and catch large regressions; the+#: bout table records the interval width this count gives.+QUEUE_BOUTS = 40+#: balance.py --speed caps each bout at this much match time.+SPEED_BOUT_LIMIT_S = 120.0+#: Automation tests that carry the external fairness verdicts (bot.md 10): a test counts for a+#: gate when its path holds ``.<gate id>`` or one of the words.+FAIRNESS_TESTS = {+ "F2": ("PerceptBoundary",),+ "F3": ("Counterfactual",),+ "BR1": ("BrainReplay",),+}+++# --- statistics ---+++def wilson(successes: int, trials: int, z: float = Z95) -> tuple[float, float] | None:+ """Wilson score 95 % interval of a proportion; None without trials."""+ if trials <= 0:+ return None+ p = successes / trials+ denom = 1 + z * z / trials+ centre = (p + z * z / (2 * trials)) / denom+ half = z * math.sqrt(p * (1 - p) / trials + z * z / (4 * trials * trials)) / denom+ return (max(0.0, centre - half), min(1.0, centre + half))+++def trials_for_half_width(p: float, half_width: float = HALF_WIDTH, z: float = Z95) -> int:+ """Trials so the normal 95 % interval at proportion ``p`` is at most +-half_width."""+ p = min(max(p, 0.0), 1.0)+ return max(1, math.ceil(z * z * p * (1 - p) / (half_width * half_width)))+++def _ratio(num: float, den: float) -> float | None:+ return None if den <= 0 else num / den+++def _median(values: Sequence[float]) -> float | None:+ return statistics.median(values) if values else None+++def stable_seed(*parts: object) -> int:+ text = "\x1f".join(str(p) for p in parts)+ return int.from_bytes(hashlib.sha256(text.encode("utf-8")).digest()[:4], "big")+++# --- configuration ---+++def load_json(path: Path) -> dict:+ return json.loads(path.read_text(encoding="utf-8"))+++def load_config(sets_file: Path = SETS_FILE, models_file: Path = PERSON_MODELS_FILE) -> dict:+ cfg = load_json(sets_file)+ models = load_json(models_file)+ cfg["models"] = sorted(models["models"])+ cfg["tricks"] = list(models["tricks"])+ return cfg+++def slot_label(slot: Mapping) -> str:+ if slot["kind"] == "bot":+ label = slot["tier"]+ return label if slot.get("learning", True) else f"{label}-nolearn"+ base = slot.get("model") or slot.get("tier")+ trick = slot.get("trick")+ if trick and slot.get("model"):+ return f"{base}+{trick}"+ return trick or base+++def _bot(tier: str, learning: bool = True) -> dict:+ slot = {"kind": "bot", "tier": tier}+ if not learning:+ slot["learning"] = False+ return slot+++def _model(model: str | None = None, trick: str | None = None, tier: str | None = None) -> dict:+ slot: dict = {"kind": "model"}+ if model:+ slot["model"] = model+ if tier:+ slot["tier"] = tier+ if trick:+ slot["trick"] = trick+ return slot+++@dataclass+class Pairing:+ id: str+ set: str+ a: dict+ b: dict+ matches: int | None = None+ bouts_per_match: int | None = None+ match_time_limit_s: float | None = None+ scenario: str | None = None+ same_process: bool = False+ kills_to_win: int | None = None++ def to_json(self) -> dict:+ return {"id": self.id, "set": self.set, "a": self.a, "b": self.b}+++def _pair(set_name: str, a: dict, b: dict, suffix: str = "", **kw) -> Pairing:+ return Pairing(f"{slot_label(a)}_vs_{slot_label(b)}{suffix}", set_name, a, b, **kw)+++def build_pairings(+ sets: Iterable[str], cfg: Mapping, tricks: Sequence[str] | None = None+) -> list[Pairing]:+ """Pairings of the named sets in a fixed order, no duplicates (A is the side under test)."""+ names = list(SET_NAMES) if "all" in sets else [s for s in SET_NAMES if s in sets]+ trick_ids = [t for t in cfg["tricks"] if not tricks or t in tricks]+ tiers = cfg["tiers"]+ out: list[Pairing] = []+ for name in names:+ if name == "ladder":+ out += [+ _pair(name, _bot("hard"), _bot("normal")),+ _pair(name, _bot("elite"), _bot("hard")),+ _pair(name, _bot("elite"), _bot("normal")),+ ]+ out += [_pair(name, _bot(t), _bot(t)) for t in tiers]+ elif name == "humans":+ out += [+ _pair(name, _model("skilled"), _bot("elite")),+ _pair(name, _model("skilled"), _bot("normal")),+ _pair(name, _model("average"), _bot("normal")),+ ]+ elif name == "tricks":+ out += [_pair(name, _model(tier="hard", trick=t), _bot("hard")) for t in trick_ids]+ elif name == "elite":+ out.append(_pair(name, _model("skilled"), _bot("elite")))+ out += [_pair(name, _model("skilled", trick=t), _bot("elite")) for t in trick_ids]+ elif name == "cross":+ sides = [_bot(t) for t in tiers] + [_model(m) for m in cfg["models"]]+ out += [+ _pair(name, a, b) for a in sides for b in sides if slot_label(a) != slot_label(b)+ ]+ elif name == "learning":+ learn = cfg["learning"]+ for opp in learn["opponents"]:+ out.append(_pair(name, _bot(learn["bot"]), _model(tier="hard", trick=opp)))+ out.append(+ _pair(name, _bot(learn["bot"], learning=False), _model(tier="hard", trick=opp))+ )+ reset = cfg["reset"]+ out.append(+ _pair(+ name,+ _bot(reset["bot"]),+ _model(tier="hard", trick=reset["opponent"]),+ ".reset",+ matches=2,+ same_process=True,+ )+ )+ elif name == "adaptive":+ out += [_pair(name, _bot("adaptive"), _model(m)) for m in cfg["adaptive"]["opponents"]]+ elif name == "fairness":+ out.append(+ _pair(+ name,+ _bot("hard"),+ _model(tier="hard", trick="repeek"),+ ".l1",+ matches=1,+ bouts_per_match=1,+ match_time_limit_s=L1_MATCH_S,+ kills_to_win=NO_KILL_CAP,+ same_process=True,+ )+ )+ for scen in sorted(cfg.get("scenarios", {})):+ script = load_json(HARNESS_DIR / "balance" / cfg["scenarios"][scen])+ out.append(+ Pairing(+ scen,+ name,+ script["a"],+ script["b"],+ matches=1,+ bouts_per_match=1,+ match_time_limit_s=float(script["durationS"]),+ scenario=scen,+ )+ )+ seen: set[str] = set()+ unique = []+ for p in out:+ if p.id not in seen:+ seen.add(p.id)+ unique.append(p)+ return unique+++# --- planning ---+++@dataclass+class Unit:+ pairing: Pairing+ match: int+ seed: int+ bouts: int++ def to_json(self, cfg: Mapping, patch: Mapping | None) -> dict:+ unit = {+ "pairing": self.pairing.id,+ "set": self.pairing.set,+ "match": self.match,+ "seed": self.seed,+ "bouts": self.bouts,+ "a": self.pairing.a,+ "b": self.pairing.b,+ "killsToWin": int(self.pairing.kills_to_win or cfg.get("killsToWin", 15)),+ "matchTimeLimitS": float(+ self.pairing.match_time_limit_s or cfg.get("matchTimeLimitS", 600)+ ),+ }+ if self.pairing.scenario:+ unit["scenario"] = self.pairing.scenario+ if patch:+ unit["tierPatch"] = dict(patch)+ return unit+++def plan_units(+ pairings: Sequence[Pairing], bouts: int, run_seed: int, bouts_per_match: int+) -> list[Unit]:+ units: list[Unit] = []+ for p in pairings:+ per_match = p.bouts_per_match or bouts_per_match+ matches = p.matches or max(1, math.ceil(bouts / per_match))+ pseed = stable_seed(run_seed, p.id)+ left = bouts if p.matches is None and p.bouts_per_match is None else per_match * matches+ for m in range(matches):+ n = per_match if p.matches or p.bouts_per_match else min(per_match, left)+ left -= n+ if n > 0:+ units.append(Unit(p, m, stable_seed(pseed, m), n))+ return units+++def shard_units(units: Sequence[Unit], jobs: int) -> list[list[Unit]]:+ """Units over ``jobs`` processes by bout count, keeping same-process pairings together."""+ jobs = max(1, min(jobs, common.MAX_HEADLESS_JOBS))+ groups: list[list[Unit]] = []+ index: dict[str, int] = {}+ for u in units:+ if u.pairing.same_process:+ if u.pairing.id not in index:+ index[u.pairing.id] = len(groups)+ groups.append([])+ groups[index[u.pairing.id]].append(u)+ else:+ groups.append([u])+ shards: list[list[Unit]] = [[] for _ in range(jobs)]+ load = [0] * jobs+ for group in sorted(groups, key=lambda g: -sum(u.bouts for u in g)):+ k = min(range(jobs), key=lambda i: (load[i], i))+ shards[k].extend(group)+ load[k] += sum(u.bouts for u in group)+ for shard in shards:+ shard.sort(key=lambda u: (u.pairing.id, u.match))+ return [s for s in shards if s]+++def scenario_document(+ run: str,+ job: int,+ units: Sequence[Unit],+ cfg: Mapping,+ out_dir: Path,+ patch: Mapping | None,+ trace_bearing: bool,+) -> dict:+ return {+ "schema": "verse.scenario/1",+ "run": run,+ "job": job,+ "map": cfg["map"],+ "output": str(out_dir),+ "maxWallS": PROCESS_TIMEOUT_S - 60,+ "trace": {"bearing": trace_bearing, "fireAudit": True},+ "units": [u.to_json(cfg, patch) for u in units],+ }+++def command_for(+ engine: Path, project: Path, map_path: str, scenario: Path, log_path: Path+) -> list[str]:+ """The dedicated-server command of bot.md 11.1."""+ return [+ str(common.editor_cmd(engine)),+ str(project),+ map_path,+ "-server",+ "-nullrhi",+ "-nosound",+ "-unattended",+ "-benchmark",+ "-fps=60",+ f"-VerseHarness={scenario}",+ "-NoP4",+ "-nosplash",+ "-stdout",+ "-FullStdOutLogOutput",+ f"-abslog={log_path}",+ ]+++# --- reading results ---+++def read_bouts(root: Path) -> list[dict]:+ bouts: list[dict] = []+ for path in sorted(root.rglob("bouts.jsonl")):+ for line in path.read_text(encoding="utf-8").splitlines():+ line = line.strip()+ if line:+ bouts.append(json.loads(line))+ return bouts+++FIRE_AUDIT_TAG = "[VerseFireAudit]"+_AUDIT_FIELD = re.compile(r"\b(\w+)\"?\s*[=:]\s*\"?([\w.:\-]+)")+++def parse_fire_audit(text: str) -> tuple[list[tuple[float, str]], int]:+ """Bot shots of ``[VerseFireAudit]`` log lines as ``(ServerTimeMs, mode)``, plus unparsed lines.++ ``FVerseBotFireAudit { ServerTimeMs, Mode, ... }`` and its log format belong to VerseBot+ (WP08). VerseBot cannot know harness pairing, match or bout ids, so the harness+ attributes each line itself: it reads the two fields it needs, ``ServerTimeMs`` and+ ``Mode`` (key=value or JSON after the tag, keys in any case, an enum prefix such as+ ``EVerseBotFireMode::`` dropped) and maps the time onto the bout windows+ (``serverStartMs``/``serverEndMs``) that UVerseBalanceGauntletController writes. The tag and+ these two field names are a contract request to the integration owner.+ """+ shots: list[tuple[float, str]] = []+ unparsed = 0+ modes = {m.lower(): m for m in AUDIT_MODES}+ for line in text.splitlines():+ at = line.find(FIRE_AUDIT_TAG)+ if at < 0:+ continue+ fields = {k.lower(): v for k, v in _AUDIT_FIELD.findall(line[at + len(FIRE_AUDIT_TAG) :])}+ try:+ server_ms = float(fields["servertimems"])+ except (KeyError, ValueError):+ unparsed += 1+ continue+ mode = fields.get("mode", "").split("::")[-1]+ shots.append((server_ms, modes.get(mode.lower(), "Unclassified")))+ return shots, unparsed+++def attribute_fire_audit(bouts: list[dict], shots: Sequence[tuple[float, str]]) -> int:+ """Counts each shot into the bout of the same process whose server window holds it.++ Returns the number of shots outside every window (bouts follow each other without a gap,+ so any such shot is an attribution failure and fails F4).+ """+ windows = sorted(+ (float(b["serverStartMs"]), float(b["serverEndMs"]), b)+ for b in bouts+ if "serverStartMs" in b and "serverEndMs" in b+ )+ outside = 0+ for server_ms, mode in shots:+ bout = next((b for lo, hi, b in windows if lo <= server_ms <= hi), None)+ if bout is None:+ outside += 1+ continue+ audit = bout.setdefault("fireAudit", {})+ audit[mode] = audit.get(mode, 0) + 1+ return outside+++# --- aggregation ---++AUDIT_MODES = ("Visible", "Suppression", "Prefire", "WallShot")+++def _is_bot(slot: Mapping) -> bool:+ return slot.get("kind") == "bot"+++def aggregate(+ pairings: Sequence[Pairing],+ bouts: Sequence[dict],+ reset_window_s: float = 300.0,+ kill_window: Sequence[int] = (30, 60),+) -> list[dict]:+ by_pairing: dict[str, list[dict]] = {}+ for b in bouts:+ by_pairing.setdefault(b["pairing"], []).append(b)+ out = []+ for p in pairings:+ rows = sorted(by_pairing.get(p.id, []), key=lambda b: (b["match"], b["bout"]))+ out.append(_pairing_metrics(p, rows, reset_window_s, kill_window))+ return out+++def _side_sum(rows: Sequence[dict], side: str, key: str) -> int:+ return sum(int(r[side].get(key) or 0) for r in rows)+++def _pairing_metrics(+ p: Pairing, rows: Sequence[dict], reset_window_s: float, kill_window: Sequence[int]+) -> dict:+ n = len(rows)+ wins_a = sum(1 for r in rows if r["winner"] == "A")+ kills = [+ dict(k, match=r["match"], mt=float(r.get("matchTimeStartS", 0.0)) + float(k["t"]))+ for r in rows+ for k in r.get("kills", [])+ ]+ kills_a = sum(1 for k in kills if k["killer"] == "A")+ kills_b = len(kills) - kills_a+ side0 = [r for r in rows if r["winner"] in ("A", "B")]+ side0_wins = sum(1 for r in side0 if (r["winner"] == "A") == (int(r["spawnSideA"]) == 0))+ metrics: dict = {+ "id": p.id,+ "set": p.set,+ "a": p.a,+ "b": p.b,+ "bouts": n,+ "kills": len(kills),+ "boutWinRateA": _ratio(wins_a, n),+ "boutWinRateA95": _interval(wilson(wins_a, n)),+ "killShareA": _ratio(kills_a, len(kills)),+ "killShareA95": _interval(wilson(kills_a, len(kills))),+ "spawnSide0WinRate": _ratio(side0_wins, len(side0)),+ "spawnSide0": [side0_wins, len(side0)],+ "matchTimeS": round(sum(float(r["durationS"]) for r in rows), 3),+ }+ per_side = {"a": kills_a, "b": kills_b}+ deaths = {"a": _side_sum(rows, "a", "deaths"), "b": _side_sum(rows, "b", "deaths")}+ lives = {s: deaths[s] + n for s in ("a", "b")}+ kills_of = {+ "a": [k for k in kills if k["killer"] == "A"],+ "b": [k for k in kills if k["killer"] == "B"],+ }+ metrics["kd"] = {s: _round(_ratio(per_side[s], max(deaths[s], 1))) for s in ("a", "b")}+ metrics["ttkS"] = {+ s: _round(_median([float(k["ttkS"]) for k in kills_of[s] if "ttkS" in k]))+ for s in ("a", "b")+ }+ contact = {+ s: [float(t) for r in rows for t in r[s].get("timeToContactS", [])] for s in ("a", "b")+ }+ metrics["timeToContactS"] = {s: _round(_median(contact[s])) for s in ("a", "b")}+ metrics["timeToContactSamples"] = contact["a"] + contact["b"]+ metrics["accuracy"] = {+ s: _round(_ratio(_side_sum(rows, s, "hits"), _side_sum(rows, s, "shots")))+ for s in ("a", "b")+ }+ for name, pred in (+ ("headshotShare", lambda k: k.get("headshot")),+ ("wallKillShare", lambda k: k.get("wall")),+ ("finisherShare", lambda k: k.get("cause") == "finisher"),+ ("knifeShare", lambda k: k.get("cause") == "melee"),+ ):+ metrics[name] = {+ s: _round(_ratio(sum(1 for k in kills_of[s] if pred(k)), len(kills_of[s])))+ for s in ("a", "b")+ }+ for key in ("bulwarkUses", "breachUses", "reloadsInFight"):+ metrics[key] = {s: _round(_ratio(_side_sum(rows, s, key), lives[s])) for s in ("a", "b")}+ hist = {f"{lo}-{hi}" if hi != math.inf else f"{lo}+": 0 for lo, hi in RANGE_BINS}+ for k in kills:+ if "rangeM" in k:+ r = float(k["rangeM"])+ for (lo, hi), name in zip(RANGE_BINS, hist, strict=True):+ if lo <= r < hi:+ hist[name] += 1+ break+ metrics["engagementRangeHist"] = hist+ metrics["spawnKills"] = sum(1 for k in kills if k.get("spawnKill"))+ audit: dict = {}+ bot_sides = [s for s, slot in (("a", p.a), ("b", p.b)) if _is_bot(slot)]+ for s in bot_sides:+ modes = {m: 0 for m in AUDIT_MODES}+ shots = _side_sum(rows, s, "shots")+ for r in rows:+ for mode, count in (r[s].get("fireAudit") or {}).items():+ if mode in modes:+ modes[mode] += int(count)+ modes["Unclassified"] = max(0, shots - sum(modes.values()))+ modes["shots"] = shots+ audit[s] = modes+ if bot_sides:+ # Audit lines attributed by bout window (attribute_fire_audit) carry no side.+ total = {m: sum(audit[s][m] for s in bot_sides) for m in AUDIT_MODES}+ for r in rows:+ for mode, count in (r.get("fireAudit") or {}).items():+ if mode in total:+ total[mode] += int(count)+ shots = sum(audit[s]["shots"] for s in bot_sides)+ total["Unclassified"] = max(0, shots - sum(total.values()))+ total["shots"] = shots+ audit["bots"] = total+ metrics["fireAudit"] = audit+ metrics["learningDelta"] = _round(_learning_delta(rows, kills))+ metrics["adaptiveTrace"] = [float(v) for r in rows for v in r.get("adaptiveTrace", [])]+ metrics["killWindowB"] = _kill_window_share(kills, kill_window)+ metrics["resetWindow"] = _reset_window(kills, reset_window_s)+ bot_ms = [r[s].get("botMsP99") for r in rows for s in ("a", "b")]+ bot_ms = [float(v) for v in bot_ms if v is not None]+ metrics["botMsP99"] = max(bot_ms) if bot_ms else None+ metrics["stuckEvents"] = _side_sum(rows, "a", "stuckEvents") + _side_sum(+ rows, "b", "stuckEvents"+ )+ nav = [r[s].get("navFailures") for r in rows for s in ("a", "b")]+ metrics["navFailures"] = (+ sum(int(v) for v in nav if v is not None) if any(v is not None for v in nav) else None+ )+ metrics["shots"] = _side_sum(rows, "a", "shots") + _side_sum(rows, "b", "shots")+ metrics["f7Violations"] = (+ sum(int(r["f7Violations"]) for r in rows)+ if p.scenario and rows and all("f7Violations" in r for r in rows)+ else None+ )+ metrics["bearingWindows"] = [w for r in rows for w in r.get("bearingWindows", [])]+ if p.scenario:+ metrics["scenario"] = p.scenario+ storm = [r["storm"] for r in rows if r.get("storm")]+ if storm:+ metrics["storm"] = storm[-1]+ return metrics+++def _interval(ci: tuple[float, float] | None) -> list[float] | None:+ return None if ci is None else [round(ci[0], 6), round(ci[1], 6)]+++def _round(value: float | None, digits: int = 6) -> float | None:+ return None if value is None else round(value, digits)+++def _learning_delta(rows: Sequence[dict], kills: Sequence[dict]) -> float | None:+ """A's kill share in the second half of each match minus the first half (pooled)."""+ halves = {0: [0, 0], 1: [0, 0]}+ lengths: dict[int, float] = {}+ for r in rows:+ end = float(r.get("matchTimeStartS", 0.0)) + float(r["durationS"])+ lengths[r["match"]] = max(lengths.get(r["match"], 0.0), end)+ for k in kills:+ half = 1 if k["mt"] >= lengths.get(k["match"], 0.0) / 2 else 0+ halves[half][0] += 1 if k["killer"] == "A" else 0+ halves[half][1] += 1+ first, second = (_ratio(*halves[0]), _ratio(*halves[1]))+ if first is None or second is None:+ return None+ return second - first+++def _kill_window_share(kills: Sequence[dict], window: Sequence[int]) -> list[int]:+ """[B kills, all kills] over kills ``window[0]+1 .. window[1]`` of each match (BG10)."""+ lo, hi = window+ b = total = 0+ per_match: dict[int, list[dict]] = {}+ for k in kills:+ per_match.setdefault(k["match"], []).append(k)+ for seq in per_match.values():+ seq.sort(key=lambda k: k["mt"])+ for k in seq[lo:hi]:+ total += 1+ b += 1 if k["killer"] == "B" else 0+ return [b, total]+++def _reset_window(kills: Sequence[dict], window_s: float) -> dict[str, list[int]]:+ """Per match: [A kills, all kills] in the first ``window_s`` of match time (BG9)."""+ out: dict[str, list[int]] = {}+ for k in kills:+ if k["mt"] < window_s:+ cell = out.setdefault(str(k["match"]), [0, 0])+ cell[0] += 1 if k["killer"] == "A" else 0+ cell[1] += 1+ return out+++# --- fairness helpers ---+++def _angle_diff(a: float, b: float) -> float:+ return abs((a - b + 180.0) % 360.0 - 180.0)+++def f5_statistic(+ windows: Sequence[Sequence[float]], facing_deg: float = F5_FACING_DEG+) -> float | None:+ """Rate of facing within ``facing_deg`` of the true bearing minus the rate against the decoy."""+ if not windows:+ return None+ true_hits = sum(1 for f, t, _d in windows if _angle_diff(f, t) <= facing_deg)+ decoy_hits = sum(1 for f, _t, d in windows if _angle_diff(f, d) <= facing_deg)+ return (true_hits - decoy_hits) / len(windows)+++def _inside(path: Path, folders: Sequence[Path]) -> bool:+ resolved = path.resolve()+ return any(resolved == f or f in resolved.parents for f in folders)+++def l1_scan(+ roots: Iterable[Path],+ fields: Sequence[str],+ since: float,+ bridge_frames: Iterable[str] = (),+ exclude: Iterable[Path] = (),+) -> list[str]:+ """Files under ``roots`` written since ``since`` or bridge frames that hold match memory.++ ``exclude`` names folders the harness itself writes during the run (the run folder with its+ job logs, scenarios and bout records); engine process logs (``*.log`` under ``Logs``) are+ exempt too. Everything else the run left behind is scanned.+ """+ hits: list[str] = []+ needles = [f.encode("utf-8") for f in fields]+ skip = [Path(f).resolve() for f in exclude]+ for root in roots:+ if not root.exists():+ continue+ for path in root.rglob("*"):+ try:+ if not path.is_file() or path.stat().st_mtime < since:+ continue+ if _inside(path, skip):+ continue+ if path.suffix.lower() == ".log" and "Logs" in path.parts:+ continue+ data = path.read_bytes()+ except OSError:+ continue+ for needle, name in zip(needles, fields, strict=True):+ if needle in data:+ hits.append(f"{path}: holds match-memory field {name}")+ for number, frame in enumerate(bridge_frames, 1):+ for name in fields:+ if name in frame:+ hits.append(f"bridge frame {number}: carries match-memory field {name}")+ return hits+++# --- gates ---+++@dataclass+class Gate:+ id: str+ status: str+ detail: str+ values: dict = field(default_factory=dict)++ def to_json(self) -> dict:+ return {"id": self.id, "status": self.status, "detail": self.detail, "values": self.values}+++def _no_combat(m: Mapping | None) -> bool:+ return m is not None and m["bouts"] > 0 and m["kills"] == 0 and m.get("shots", 0) == 0+++def _need(metrics: Mapping[str, dict], gate: str, ids: Sequence[str]) -> Gate | None:+ """A not_run or fail gate when a pairing it needs is missing, unplayed or killless."""+ missing = [i for i in ids if i not in metrics or metrics[i]["bouts"] == 0]+ if missing:+ return Gate(gate, "not_run", "pairings not played: " + ", ".join(missing))+ idle = [i for i in ids if _no_combat(metrics[i])]+ if idle:+ return Gate(+ gate, "not_run", "no shots fired (null brain until WP08 lands): " + ", ".join(idle)+ )+ killless = [i for i in ids if metrics[i]["kills"] == 0]+ if killless:+ return Gate(gate, "fail", "no kills in: " + ", ".join(killless))+ return None+++def _verdict(gate: str, checks: Sequence[tuple[str, bool]], values: dict) -> Gate:+ failed = [text for text, ok in checks if not ok]+ if failed:+ return Gate(gate, "fail", "; ".join(failed), values)+ return Gate(gate, "pass", "; ".join(text for text, _ in checks), values)+++def _fmt(x: float | None) -> str:+ return "n/a" if x is None else f"{x:.3f}"+++def gate_ladder(metrics: Mapping[str, dict], gate: str, pid: str) -> Gate:+ blocked = _need(metrics, gate, [pid])+ if blocked:+ return blocked+ m = metrics[pid]+ wr, lo = m["boutWinRateA"], m["killShareA95"][0]+ return _verdict(+ gate,+ [+ (f"{pid} boutWinRateA {_fmt(wr)} >= 0.75", wr >= 0.75),+ (f"{pid} killShareA lower {_fmt(lo)} >= 0.56", lo >= 0.56),+ ],+ {"boutWinRateA": wr, "killShareLower": lo},+ )+++def gate_bg3(metrics: Mapping[str, dict], tiers: Sequence[str]) -> Gate:+ blocked = _need(metrics, "BG3", ["elite_vs_normal"])+ if blocked:+ return blocked+ m = metrics["elite_vs_normal"]+ checks = [+ (+ f"elite_vs_normal boutWinRateA {_fmt(m['boutWinRateA'])} >= 0.90",+ m["boutWinRateA"] >= 0.90,+ ),+ (f"elite_vs_normal killShareA {_fmt(m['killShareA'])} <= 0.85", m["killShareA"] <= 0.85),+ ]+ side0 = [0, 0]+ for t in tiers:+ pid = f"{t}_vs_{t}"+ mm = metrics.get(pid)+ if not mm or mm["bouts"] == 0 or mm["kills"] == 0:+ checks.append((f"mirror {pid} not played", False))+ continue+ ks = mm["killShareA"]+ checks.append(+ (f"mirror {pid} killShareA {_fmt(ks)} in 0.5 +- 0.06", abs(ks - 0.5) <= HALF_WIDTH)+ )+ side0[0] += mm["spawnSide0"][0]+ side0[1] += mm["spawnSide0"][1]+ rate = _ratio(*side0)+ checks.append(+ (+ f"spawn side 0 win rate {_fmt(rate)} in 0.5 +- 0.06",+ rate is not None and abs(rate - 0.5) <= HALF_WIDTH,+ )+ )+ return _verdict("BG3", checks, {"spawnSide0WinRate": rate})+++def gate_bg4(metrics: Mapping[str, dict], tricks: Sequence[str]) -> Gate:+ ids = [f"{t}_vs_hard" for t in tricks if f"{t}_vs_hard" in metrics]+ if not ids:+ return Gate("BG4", "not_run", "no trick pairings played")+ blocked = _need(metrics, "BG4", ids)+ if blocked:+ return blocked+ checks = []+ for pid in ids:+ m = metrics[pid]+ checks.append(+ (f"{pid} boutWinRateA {_fmt(m['boutWinRateA'])} <= 0.50", m["boutWinRateA"] <= 0.50)+ )+ checks.append(+ (+ f"{pid} killShareA upper {_fmt(m['killShareA95'][1])} <= 0.55",+ m["killShareA95"][1] <= 0.55,+ )+ )+ return _verdict("BG4", checks, {"tricks": len(ids)})+++def gate_bg5(metrics: Mapping[str, dict], tricks: Sequence[str]) -> Gate:+ ids = [f"skilled+{t}_vs_elite" for t in tricks if f"skilled+{t}_vs_elite" in metrics]+ if not ids:+ return Gate("BG5", "not_run", "no skilled+trick pairings played")+ blocked = _need(metrics, "BG5", ["skilled_vs_elite", *ids])+ if blocked:+ return blocked+ base = metrics["skilled_vs_elite"]["killShareA"]+ checks = [+ (+ f"{pid} killShareA {_fmt(metrics[pid]['killShareA'])} <= {_fmt(base)} + 0.05",+ metrics[pid]["killShareA"] <= base + 0.05,+ )+ for pid in ids+ ]+ return _verdict("BG5", checks, {"baseKillShare": base})+++def gate_bg6(metrics: Mapping[str, dict]) -> Gate:+ blocked = _need(metrics, "BG6", ["skilled_vs_elite", "skilled_vs_normal"])+ if blocked:+ return blocked+ ks_e = metrics["skilled_vs_elite"]["killShareA"]+ ks_n = metrics["skilled_vs_normal"]["killShareA"]+ return _verdict(+ "BG6",+ [+ (+ f"skilled_vs_elite killShareA {_fmt(ks_e)} in 0.40 +- 0.06",+ abs(ks_e - 0.40) <= HALF_WIDTH + 1e-12,+ ),+ (f"skilled_vs_normal killShareA {_fmt(ks_n)} >= 0.70", ks_n >= 0.70),+ ],+ {"skilledVsElite": ks_e, "skilledVsNormal": ks_n},+ )+++def gate_bg7(metrics: Mapping[str, dict]) -> Gate:+ blocked = _need(metrics, "BG7", ["average_vs_normal"])+ if blocked:+ return blocked+ ks = metrics["average_vs_normal"]["killShareA"]+ return _verdict(+ "BG7",+ [(f"average_vs_normal killShareA {_fmt(ks)} in 0.45-0.65", 0.45 <= ks <= 0.65)],+ {"killShareA": ks},+ )+++def gate_bg8(metrics: Mapping[str, dict], cfg: Mapping) -> Gate:+ bot = cfg["learning"]["bot"]+ on = [f"{bot}_vs_{o}" for o in cfg["learning"]["opponents"]]+ off = [f"{bot}-nolearn_vs_{o}" for o in cfg["learning"]["opponents"]]+ blocked = _need(metrics, "BG8", on + off)+ if blocked:+ return blocked+ checks = []+ for a, b in zip(on, off, strict=True):+ delta = metrics[a]["learningDelta"]+ checks.append(+ (f"{a} learningDelta {_fmt(delta)} >= +0.05", delta is not None and delta >= 0.05)+ )+ gap = metrics[a]["killShareA"] - metrics[b]["killShareA"]+ checks.append((f"{b} is {_fmt(gap)} worse for the bot (>= 0.03)", gap >= 0.03))+ return _verdict("BG8", checks, {})+++def gate_bg9(metrics: Mapping[str, dict], cfg: Mapping) -> Gate:+ pid = f"{cfg['reset']['bot']}_vs_{cfg['reset']['opponent']}.reset"+ blocked = _need(metrics, "BG9", [pid])+ if blocked:+ return blocked+ window = metrics[pid]["resetWindow"]+ first, second = window.get("0"), window.get("1")+ if not first or not second or not first[1] or not second[1]:+ return Gate(+ "BG9",+ "fail",+ f"{pid}: both matches need kills in the first {cfg['reset']['windowS']} s",+ )+ ci = wilson(first[0], first[1])+ p2 = second[0] / second[1]+ return _verdict(+ "BG9",+ [+ (+ f"match 2 share {_fmt(p2)} inside match 1 interval [{_fmt(ci[0])}, {_fmt(ci[1])}]",+ ci[0] <= p2 <= ci[1],+ )+ ],+ {"match1": first, "match2": second},+ )+++def gate_bg10(metrics: Mapping[str, dict], cfg: Mapping) -> Gate:+ ids = [f"adaptive_vs_{o}" for o in cfg["adaptive"]["opponents"]]+ blocked = _need(metrics, "BG10", ids)+ if blocked:+ return blocked+ checks = []+ lo, hi = cfg["adaptive"]["killWindow"]+ for pid in ids:+ b, total = metrics[pid]["killWindowB"]+ share = _ratio(b, total)+ checks.append(+ (+ f"{pid} person kill share over kills {lo}-{hi} {_fmt(share)} in 0.40-0.60",+ share is not None and 0.40 <= share <= 0.60,+ )+ )+ trace = metrics[pid]["adaptiveTrace"]+ if not trace:+ checks.append((f"{pid} has no adaptive trace", False))+ continue+ checks.append((f"{pid} s within [0, 1]", all(0.0 <= s <= 1.0 for s in trace)))+ step = max((abs(b2 - a2) for a2, b2 in zip(trace, trace[1:], strict=False)), default=0.0)+ checks.append((f"{pid} largest step {_fmt(step)} <= 0.05", step <= 0.05 + 1e-12))+ return _verdict("BG10", checks, {})+++def _bot_audit(m: Mapping) -> list[Mapping]:+ audit = m.get("fireAudit") or {}+ return [audit["bots"]] if "bots" in audit else list(audit.values())+++def gate_f4(metrics: Mapping[str, dict], unattributed: int = 0) -> Gate:+ played = [m for m in metrics.values() if m["bouts"]]+ if not played:+ return Gate("F4", "not_run", "no bouts played")+ unclassified = sum(a.get("Unclassified", 0) for m in played for a in _bot_audit(m))+ shots = sum(a.get("shots", 0) for m in played for a in _bot_audit(m))+ if shots == 0 and unattributed == 0:+ return Gate("F4", "not_run", "no bot shot fired (null brain until WP08 lands)")+ return _verdict(+ "F4",+ [+ (f"unclassified bot shots {unclassified} of {shots} == 0", unclassified == 0),+ (f"audit lines outside every bout window {unattributed} == 0", unattributed == 0),+ ],+ {"botShots": shots, "unclassified": unclassified, "unattributed": unattributed},+ )+++def gate_f5(metrics: Mapping[str, dict]) -> Gate:+ windows = [w for m in metrics.values() for w in m.get("bearingWindows", [])]+ if len(windows) < F5_MIN_WINDOWS:+ return Gate(+ "F5", "not_run", f"{len(windows)} no-percept windows, need {F5_MIN_WINDOWS} (nightly)"+ )+ stat = f5_statistic(windows)+ return _verdict(+ "F5",+ [(f"hidden-bearing excess {_fmt(stat)} <= {F5_MAX_EXCESS}", stat <= F5_MAX_EXCESS)],+ {"windows": len(windows), "excess": stat},+ )+++def gate_f7(metrics: Mapping[str, dict]) -> Gate:+ m = metrics.get("wall_opened_unseen")+ if not m or not m["bouts"]:+ return Gate("F7", "not_run", "scenario wall_opened_unseen not played")+ if m["f7Violations"] is None:+ return Gate(+ "F7", "not_run", "wall_opened_unseen ran without a plan watch (needs WP06, WP08)"+ )+ return _verdict(+ "F7",+ [(f"plans through the unseen opening: {m['f7Violations']}", m["f7Violations"] == 0)],+ {},+ )+++def gate_bg12(metrics: Mapping[str, dict]) -> Gate:+ played = [m for m in metrics.values() if m["bouts"]]+ if not played:+ return Gate("BG12", "not_run", "no bouts played")+ if all(_no_combat(m) for m in played) and not any(m["timeToContactSamples"] for m in played):+ return Gate("BG12", "not_run", "no contact in any bout (null brain until WP08 lands)")+ contact = [t for m in played for t in m["timeToContactSamples"]]+ median = _median(contact)+ minutes = sum(m["matchTimeS"] for m in played) / 60.0+ stuck = sum(m["stuckEvents"] for m in played)+ per_10 = stuck / (minutes / 10.0) if minutes > 0 else 0.0+ bot_ms = [m["botMsP99"] for m in played if m["botMsP99"] is not None]+ checks = [+ (f"timeToContactS median {_fmt(median)} <= 25", median is not None and median <= 25.0),+ (f"stuckEvents {per_10:.3f} per 10 min <= 1", per_10 <= 1.0),+ ]+ if bot_ms:+ checks.append((f"botMsP99 {_fmt(max(bot_ms))} <= 0.5", max(bot_ms) <= 0.5))+ else:+ checks.append(("botMsP99 not measured (needs VerseBot timing)", True))+ return _verdict("BG12", checks, {"contactMedianS": median, "stuckPer10Min": per_10})+++def gate_static(gate: str, findings: Sequence[str], what: str) -> Gate:+ if findings:+ return Gate(+ gate, "fail", f"{what}: " + "; ".join(findings[:10]), {"findings": len(findings)}+ )+ return Gate(gate, "pass", f"{what}: clean")+++def gate_external(gate: str, checks: Mapping[str, Mapping], what: str) -> Gate:+ """A gate whose verdict comes from another test run (``--checks`` file)."""+ entry = checks.get(gate)+ if not entry:+ return Gate(gate, "not_run", f"{what}: no result supplied")+ return Gate(gate, entry.get("status", "not_run"), entry.get("detail", what))+++def checks_from_automation(root: Path) -> dict[str, dict]:+ """F2, F3 and BR1 verdicts from every automation ``index.json`` under ``root``.++ A gate passes when every test that carries it succeeded, fails when one did not, and is+ left out (not_run) when no test carries it yet.+ """+ found: dict[str, list[tuple[str, str]]] = {g: [] for g in FAIRNESS_TESTS}+ for index in sorted(root.rglob("index.json")) if root.exists() else []:+ try:+ tests = json.loads(index.read_text(encoding="utf-8-sig")).get("tests", [])+ except (OSError, ValueError):+ continue+ for test in tests:+ path = str(test.get("fullTestPath", ""))+ for gate, words in FAIRNESS_TESTS.items():+ parts = path.split(".")+ if gate in parts or any(w in path for w in words):+ found[gate].append((path, str(test.get("state", ""))))+ checks: dict[str, dict] = {}+ for gate, rows in found.items():+ if not rows:+ continue+ bad = [path for path, state in rows if state != "Success"]+ checks[gate] = {+ "status": "fail" if bad else "pass",+ "detail": (f"failed: {', '.join(bad[:5])}" if bad else f"{len(rows)} tests passed"),+ }+ return checks+++def gate_bg11(parts: Mapping[str, Gate], nightly: bool) -> Gate:+ want = ["F3", "F4"] + (["F5", "F7", "L1"] if nightly else [])+ states = {g: parts[g].status for g in want if g in parts}+ failed = [g for g, s in states.items() if s == "fail"]+ if failed:+ return Gate("BG11", "fail", "failed: " + ", ".join(failed), states)+ missing = [g for g in want if states.get(g) != "pass"]+ if missing:+ passed = [g for g in want if states.get(g) == "pass"]+ detail = "not run: " + ", ".join(missing)+ if passed:+ detail += "; passed: " + ", ".join(passed)+ return Gate("BG11", "not_run", detail, states)+ return Gate("BG11", "pass", "passed: " + ", ".join(want), states)+++def evaluate_gates(+ metrics_list: Sequence[dict],+ cfg: Mapping,+ *,+ checks: Mapping[str, Mapping] | None = None,+ l1_findings: Sequence[str] | None = None,+ nightly: bool = False,+ static_root: Path | None = None,+ only: Iterable[str] | None = None,+ audit_unattributed: int = 0,+) -> list[Gate]:+ metrics = {m["id"]: m for m in metrics_list}+ checks = checks or {}+ source = static_root or (common.PROJECT_DIR / "Source")+ gates: dict[str, Gate] = {+ "BG1": gate_ladder(metrics, "BG1", "hard_vs_normal"),+ "BG2": gate_ladder(metrics, "BG2", "elite_vs_hard"),+ "BG3": gate_bg3(metrics, cfg["tiers"]),+ "BG4": gate_bg4(metrics, cfg["tricks"]),+ "BG5": gate_bg5(metrics, cfg["tricks"]),+ "BG6": gate_bg6(metrics),+ "BG7": gate_bg7(metrics),+ "BG8": gate_bg8(metrics, cfg),+ "BG9": gate_bg9(metrics, cfg),+ "BG10": gate_bg10(metrics, cfg),+ "F1": gate_static("F1", check_bot_isolation.check_isolation(source), "bot isolation"),+ "F2": gate_external("F2", checks, "percept boundary automation tests"),+ "F3": gate_external("F3", checks, "counterfactual invariance automation test"),+ "F4": gate_f4(metrics, audit_unattributed),+ "F5": gate_f5(metrics),+ "F6": gate_static("F6", check_bot_isolation.check_symmetry(source), "perception symmetry"),+ "F7": gate_f7(metrics),+ "BR1": gate_external("BR1", checks, "brain replay unit test"),+ "BG12": gate_bg12(metrics),+ }+ if l1_findings is None:+ gates["L1"] = gate_external("L1", checks, "no-persistence scan")+ else:+ gates["L1"] = gate_static("L1", l1_findings, "no-persistence scan")+ gates["BG11"] = gate_bg11(gates, nightly)+ wanted = list(only) if only else list(GATE_IDS)+ return [gates[g] for g in GATE_IDS if g in wanted]+++# --- report ---+++def build_report(+ run: str,+ seed: int,+ sets: Sequence[str],+ metrics: Sequence[dict],+ gates: Sequence[Gate],+ *,+ bouts: int | None,+ jobs: int,+ patch: Mapping | None,+ speed: Mapping | None,+ fire_audit_log: str | None = None,+) -> dict:+ return {+ "schema": "verse.balance/1",+ "run": run,+ "created": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),+ "seed": seed,+ "sets": list(sets),+ "bouts": bouts,+ "jobs": jobs,+ "patch": dict(patch) if patch else None,+ "speed": dict(speed) if speed else None,+ "pairings": list(metrics),+ "gates": [g.to_json() for g in gates],+ "fireAuditLog": fire_audit_log,+ }+++def validate(document: Mapping, schema_name: str) -> list[str]:+ try:+ import jsonschema+ except ImportError: # pragma: no cover - CI installs it+ return []+ schema = load_json(SCHEMA_DIR / schema_name)+ validator = jsonschema.Draft202012Validator(schema)+ return [+ f"{'/'.join(str(p) for p in e.absolute_path)}: {e.message}"+ for e in validator.iter_errors(document)+ ]+++# --- speed and bout table (RK1) ---+++def speed_summary(speed_docs: Sequence[Mapping]) -> dict | None:+ docs = [d for d in speed_docs if float(d.get("wallS", 0)) > 0]+ if not docs:+ return None+ per_process = [float(d["simS"]) / float(d["wallS"]) for d in docs]+ ram = [float(d["peakRamMb"]) for d in docs if d.get("peakRamMb")]+ return {+ "processes": len(docs),+ "xRealTimePerProcess": round(min(per_process), 3),+ "xRealTimeMean": round(statistics.mean(per_process), 3),+ "simS": round(sum(float(d["simS"]) for d in docs), 3),+ "wallS": round(max(float(d["wallS"]) for d in docs), 3),+ "startupS": round(max(float(d.get("startupS", 0.0)) for d in docs), 3),+ "peakRamMbPerProcess": round(max(ram), 1) if ram else None,+ "targetXRealTime": 20.0,+ "meetsTarget": min(per_process) >= 20.0,+ }+++#: The proportion at each gate's decision threshold, and whether its trials are bouts or kills.+GATE_TRIALS = {+ "BG1": (0.75, "bouts"),+ "BG2": (0.75, "bouts"),+ "BG3": (0.90, "bouts"),+ "BG4": (0.50, "bouts"),+ "BG5": (0.45, "kills"),+ "BG6": (0.40, "kills"),+ "BG7": (0.55, "kills"),+ "BG8": (0.50, "kills"),+ "BG9": (0.50, "kills"),+ "BG10": (0.50, "kills"),+}+++def bout_table(+ speed: Mapping,+ *,+ kills_per_bout: float = DEFAULT_KILLS_PER_BOUT,+ bout_sim_s: float = 240.0,+ jobs: int = common.MAX_HEADLESS_JOBS,+ pairings_per_gate: Mapping[str, int] | None = None,+ provisional: str | None = None,+ queue_bouts: int = QUEUE_BOUTS,+) -> dict:+ """Bouts per pairing for a 95 % interval of at most +-0.06, and their wall time.++ ``provisional`` names why the speed sample does not stand for a real bout (null brain,+ a default kill count, bouts cut by the speed-mode time limit); the wall-time rows are then+ left out (``null``) instead of reporting a number that is far too low.+ """+ x = float(speed["xRealTimePerProcess"])+ rows = {}+ for gate, (p, unit) in GATE_TRIALS.items():+ trials = trials_for_half_width(p)+ bouts = trials if unit == "bouts" else math.ceil(trials / kills_per_bout)+ pairings = (pairings_per_gate or {}).get(gate, 1)+ wall_h = bouts * pairings * bout_sim_s / x / jobs / 3600.0+ rows[gate] = {+ "p": p,+ "trials": trials,+ "unit": unit,+ "boutsPerPairing": bouts,+ "pairings": pairings,+ "wallHours": None if provisional else round(wall_h, 2),+ }+ bout_lo, bout_hi = wilson(round(queue_bouts * 0.5), queue_bouts) or (0.0, 1.0)+ kills = round(queue_bouts * kills_per_bout)+ kill_lo, kill_hi = wilson(round(kills * 0.5), kills) or (0.0, 1.0)+ return {+ "schema": "verse.bout_table/1",+ "halfWidth": HALF_WIDTH,+ "xRealTimePerProcess": x,+ "killsPerBout": kills_per_bout,+ "boutSimS": bout_sim_s,+ "jobs": jobs,+ "provisional": provisional,+ "gates": rows,+ "fullWidthQueueBouts": max(rows[g]["boutsPerPairing"] for g in ("BG1", "BG2", "BG4")),+ "queueBouts": queue_bouts,+ "queueHalfWidth": {+ "boutShare": round((bout_hi - bout_lo) / 2, 3),+ "killShare": round((kill_hi - kill_lo) / 2, 3),+ },+ "nightlyBouts": max(r["boutsPerPairing"] for r in rows.values()),+ }+++def pairings_per_gate(cfg: Mapping) -> dict[str, int]:+ n_tricks = len(cfg["tricks"])+ return {+ "BG1": 1,+ "BG2": 1,+ "BG3": 1 + len(cfg["tiers"]),+ "BG4": n_tricks,+ "BG5": n_tricks + 1,+ "BG6": 2,+ "BG7": 1,+ "BG8": 2 * len(cfg["learning"]["opponents"]),+ "BG9": 1,+ "BG10": len(cfg["adaptive"]["opponents"]),+ }+++# --- running ---+++Launcher = Callable[[list[str], Path], "subprocess.Popen"]+++def _launch(command: list[str], log_path: Path) -> subprocess.Popen:+ sink = open(log_path.with_suffix(".stdout.txt"), "w", encoding="utf-8", errors="replace") # noqa: SIM115+ return subprocess.Popen(command, stdout=sink, stderr=subprocess.STDOUT) # noqa: S603+++def run_jobs(+ shards: Sequence[Sequence[Unit]],+ cfg: Mapping,+ run_dir: Path,+ run: str,+ *,+ patch: Mapping | None,+ trace_bearing: bool,+ engine: Path,+ project: Path,+ launcher: Launcher = _launch,+ lock_factory: Callable[..., object] | None = None,+ timeout_s: float = PROCESS_TIMEOUT_S,+) -> list[dict]:+ """Run one headless editor per shard inside one lock hold; returns per-job status."""+ from scripts.unreal import with_lock++ lock_factory = lock_factory or with_lock.MachineLock+ jobs = []+ for k, shard in enumerate(shards):+ job_dir = run_dir / f"job{k}"+ job_dir.mkdir(parents=True, exist_ok=True)+ scenario = scenario_document(run, k, shard, cfg, job_dir, patch, trace_bearing)+ problems = validate(scenario, "scenario.schema.json")+ if problems:+ raise common.UnrealScriptError(+ "scenario does not match verse.scenario/1: " + problems[0]+ )+ path = job_dir / "scenario.json"+ path.write_text(json.dumps(scenario, indent=2), encoding="utf-8")+ jobs.append((k, path, job_dir / f"job{k}.log"))+ results = []+ with lock_factory("balance", f"balance.py {run} ({len(jobs)} jobs)"):+ started = time.monotonic()+ procs = [+ (k, launcher(command_for(engine, project, cfg["map"], path, log), log), log)+ for k, path, log in jobs+ ]+ for k, proc, log in procs:+ left = max(1.0, timeout_s - (time.monotonic() - started))+ try:+ code = proc.wait(timeout=left)+ except subprocess.TimeoutExpired:+ common.log(f"balance job {k} ran past {timeout_s / 60:.0f} min; stopping it")+ proc.kill()+ code = proc.wait()+ results.append({"job": k, "returncode": code, "log": str(log)})+ return results+++def _read_bout_file(path: Path) -> list[dict]:+ if not path.exists():+ return []+ lines = path.read_text(encoding="utf-8").splitlines()+ return [json.loads(line) for line in lines if line.strip()]+++def collect(run_dir: Path) -> tuple[list[dict], list[dict], str, int]:+ """Bouts, speed documents, the fire-audit log path and the unattributed audit line count.++ Audit lines are attributed per process folder (``job<k>/``): its log and its bouts share+ one server clock.+ """+ bouts: list[dict] = []+ audit_lines: list[str] = []+ unattributed = 0+ folders = sorted(+ {p.parent for p in run_dir.rglob("bouts.jsonl")}+ | {p.parent for p in run_dir.rglob("job*.log")}+ )+ for folder in folders:+ job_bouts = _read_bout_file(folder / "bouts.jsonl")+ text = "\n".join(+ p.read_text(encoding="utf-8", errors="replace") for p in sorted(folder.glob("job*.log"))+ )+ shots, unparsed = parse_fire_audit(text)+ unattributed += unparsed + attribute_fire_audit(job_bouts, shots)+ audit_lines += [line for line in text.splitlines() if FIRE_AUDIT_TAG in line]+ bouts += job_bouts+ speed_docs = [load_json(p) for p in sorted(run_dir.rglob("speed.json"))]+ audit_log = run_dir / "fire_audit.log"+ audit_log.write_text("\n".join(audit_lines) + ("\n" if audit_lines else ""), encoding="utf-8")+ return bouts, speed_docs, str(audit_log), unattributed+++def planned_units(run_dir: Path) -> dict[tuple[str, int], int]:+ """(pairing, match) -> planned bouts, from the run's scenario files."""+ plan: dict[tuple[str, int], int] = {}+ for path in sorted(run_dir.rglob("scenario.json")):+ for unit in load_json(path).get("units", []):+ plan[(unit["pairing"], int(unit["match"]))] = int(unit["bouts"])+ return plan+++def completeness(+ run_dir: Path,+ bouts: Sequence[dict],+ speed_docs: Sequence[Mapping],+ results: Sequence[Mapping] = (),+) -> list[str]:+ """Why the run is short: failed or killed jobs, early ends, units with missing bouts."""+ problems = [+ f"job {r['job']} exited {r['returncode']} (log {r['log']})"+ for r in results+ if r.get("returncode") != 0+ ]+ for doc in speed_docs:+ end = doc.get("end", "")+ if doc.get("failed") or end != END_ALL_PLAYED:+ problems.append(f"job {doc.get('job')} ended early: {end or 'no end reason'}")+ played: dict[tuple[str, int], int] = {}+ for b in bouts:+ key = (b["pairing"], int(b["match"]))+ played[key] = played.get(key, 0) + 1+ for (pairing, match), want in sorted(planned_units(run_dir).items()):+ got = played.get((pairing, match), 0)+ if got < want:+ problems.append(f"unit {pairing}#{match}: {got} of {want} bouts")+ return problems+++def summarize(gates: Sequence[Gate]) -> int:+ for g in gates:+ print(f"{g.id:5s} {g.status.upper():8s} {g.detail}")+ failed = [g.id for g in gates if g.status == "fail"]+ if failed:+ print(f"balance: FAIL ({', '.join(failed)})")+ return 1+ print("balance: OK (no gate failed)")+ return 0+++def main(argv: Sequence[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument(+ "--set",+ dest="sets",+ action="append",+ choices=[*SET_NAMES, "all"],+ help="Pairing set (repeatable).",+ )+ parser.add_argument(+ "--bouts", type=int, help="Bouts per pairing (default: the bout table's nightly count)."+ )+ parser.add_argument("--seed", type=int, default=1, help="Run seed.")+ parser.add_argument("--patch", type=Path, help="Tier patch JSON applied in every unit.")+ parser.add_argument(+ "--jobs",+ type=int,+ default=common.MAX_HEADLESS_JOBS,+ help="Parallel headless processes (max 4).",+ )+ parser.add_argument("--tricks", help="Comma list limiting the trick pairings.")+ parser.add_argument("--gates", help="Comma list of gate ids to report.")+ parser.add_argument("--nightly", action="store_true", help="BG11 also requires F5, F7 and L1.")+ parser.add_argument(+ "--checks", type=Path, help="JSON {gate: {status, detail}} for F2, F3, BR1, L1."+ )+ parser.add_argument(+ "--checks-from-automation",+ type=Path,+ help="Folder of automation reports (index.json) that give F2, F3 and BR1.",+ )+ parser.add_argument(+ "--from-bouts", type=Path, help="Recompute the report from a run folder; no run."+ )+ parser.add_argument("--plan", action="store_true", help="Print the units per job and exit.")+ parser.add_argument(+ "--speed", action="store_true", help="Measure x real time and write the bout table."+ )+ parser.add_argument(+ "--out", type=Path, help="Run folder (default Saved/Harness/balance/<run>)."+ )+ parser.add_argument("--map", help="Map override (default: sets.json, the hangar).")+ parser.add_argument("--worktree", type=Path, default=common.REPO_ROOT)+ args = parser.parse_args(argv)++ cfg = load_config()+ if args.map:+ cfg["map"] = args.map+ tricks = [t for t in (args.tricks or "").split(",") if t] or None+ only = [g for g in (args.gates or "").split(",") if g] or None+ if only and set(only) - set(GATE_IDS):+ return common.exit_with(+ common.UnrealScriptError(f"unknown gate ids: {sorted(set(only) - set(GATE_IDS))}")+ )+ patch = load_json(args.patch) if args.patch else None+ checks = load_json(args.checks) if args.checks else {}+ if args.checks_from_automation:+ checks = {**checks_from_automation(args.checks_from_automation), **checks}+ sets = args.sets or (["ladder"] if args.speed else ["all"])+ if args.speed:+ sets = ["ladder"]+ pairings = build_pairings(sets, cfg, tricks)+ default_bouts = 2 if args.speed else _table_bouts()+ bouts = args.bouts or default_bouts+ run = f"{common.run_stamp()}-{'speed' if args.speed else '-'.join(sets)}-s{args.seed}"+ run_dir = (+ args.out or (args.worktree / "unreal" / "Verse" / "Saved" / "Harness" / "balance" / run)+ ).resolve()++ if args.from_bouts:+ run_dir = args.from_bouts.resolve()+ bouts_list, speed_docs, audit_log, unattributed = collect(run_dir)+ incomplete = completeness(run_dir, bouts_list, speed_docs)+ played = {b["pairing"] for b in bouts_list}+ pairings = [p for p in build_pairings(["all"], cfg, tricks) if p.id in played] or pairings+ else:+ units = plan_units(pairings, bouts, args.seed, int(cfg.get("boutsPerMatch", 10)))+ if args.speed:+ units = units[: max(1, args.jobs)]+ for u in units:+ u.pairing.match_time_limit_s = SPEED_BOUT_LIMIT_S+ shards = shard_units(units, args.jobs)+ if args.plan:+ for k, shard in enumerate(shards):+ print(f"job{k}: " + ", ".join(f"{u.pairing.id}#{u.match}x{u.bouts}" for u in shard))+ return 0+ try:+ engine = common.engine_root()+ project = common.project_file(args.worktree.resolve())+ results = run_jobs(+ shards,+ cfg,+ run_dir,+ run,+ patch=patch,+ trace_bearing=args.nightly,+ engine=engine,+ project=project,+ )+ except common.UnrealScriptError as error:+ return common.exit_with(error)+ bouts_list, speed_docs, audit_log, unattributed = collect(run_dir)+ incomplete = completeness(run_dir, bouts_list, speed_docs, results)+ for problem in incomplete:+ common.log(f"incomplete run: {problem}")++ speed = speed_summary(speed_docs)+ if args.speed:+ if not speed:+ return common.exit_with(+ common.UnrealScriptError("no speed.json written; see the job logs")+ )+ sim_bouts = [float(b["durationS"]) for b in bouts_list] or [240.0]+ kills = [len(b.get("kills", [])) for b in bouts_list]+ measured_kills = bool(kills) and statistics.mean(kills) > 0+ kpb = statistics.mean(kills) if measured_kills else DEFAULT_KILLS_PER_BOUT+ why = []+ if all(not b.get("kills") for b in bouts_list):+ why.append("null brain (no kill in any bout)")+ if not measured_kills:+ why.append(f"killsPerBout is the default {DEFAULT_KILLS_PER_BOUT:g}")+ if any(float(b["durationS"]) >= SPEED_BOUT_LIMIT_S - 0.5 for b in bouts_list):+ why.append(f"bouts cut at the {SPEED_BOUT_LIMIT_S:g} s speed-mode limit")+ table = bout_table(+ speed,+ kills_per_bout=kpb,+ bout_sim_s=max(statistics.mean(sim_bouts), 1.0),+ jobs=max(1, args.jobs),+ pairings_per_gate=pairings_per_gate(cfg),+ provisional="; ".join(why) or None,+ )+ table["measured"] = {+ "run": run,+ "speed": speed,+ "nullBrain": all(not b.get("kills") for b in bouts_list),+ }+ (run_dir / "speed_report.json").write_text(json.dumps(table, indent=2), encoding="utf-8")+ print(json.dumps(table, indent=2))+ return 1 if incomplete else 0++ started = min((p.stat().st_mtime for p in run_dir.rglob("scenario.json")), default=time.time())+ l1 = None+ if any(p.id.endswith(".l1") for p in pairings):+ fields = load_json(L1_FIELDS_FILE)["fields"]+ roots = [args.worktree / "unreal" / "Verse" / "Saved"]+ data_dir = os.environ.get("DODAIOS_DATA_DIR")+ if data_dir:+ roots.append(Path(data_dir))+ l1 = l1_scan(roots, fields, started, exclude=[run_dir])+ metrics = aggregate(+ pairings, bouts_list, float(cfg["reset"]["windowS"]), cfg["adaptive"]["killWindow"]+ )+ gates = evaluate_gates(+ metrics,+ cfg,+ checks=checks,+ l1_findings=l1,+ nightly=args.nightly,+ only=only,+ audit_unattributed=unattributed,+ )+ report = build_report(+ run,+ args.seed,+ sets,+ metrics,+ gates,+ bouts=bouts,+ jobs=args.jobs,+ patch=patch,+ speed=speed,+ fire_audit_log=audit_log,+ )+ report["incomplete"] = incomplete+ problems = validate(report, "balance.schema.json")+ if problems:+ return common.exit_with(+ common.UnrealScriptError("report does not match verse.balance/1: " + problems[0])+ )+ run_dir.mkdir(parents=True, exist_ok=True)+ (run_dir / "report.json").write_text(json.dumps(report, indent=2), encoding="utf-8")+ common.log(f"report: {run_dir / 'report.json'}")+ code = summarize(gates)+ if incomplete:+ print(f"balance: FAIL (incomplete run: {len(incomplete)} problems, see report.json)")+ return 1+ return code+++def _table_bouts() -> int:+ try:+ return int(load_json(BOUT_TABLE_FILE)["nightlyBouts"])+ except (OSError, KeyError, ValueError):+ return 200+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/unreal/capture.py b/scripts/unreal/capture.pynew file mode 100644index 0000000000..a7b2172ac4--- /dev/null+++ b/scripts/unreal/capture.py@@ -0,0 +1,303 @@+#!/usr/bin/env python3+"""Scripted-camera screenshots, palette share measurement and the evidence folder layout.++``shots`` renders the reference views of ``unreal/Verse/Harness/capture/cameras.json``+(or another ``verse.capture/1`` file): one rendered game process per map, under+the machine lock, window off the person's monitors, UI hidden. ``VerseHarness``+places the camera at each view, waits for shader compiles and streaming, then+writes ``<view>.png``. Every shot is measured against the Military-Industrial Noir+palette (``contracts/art-pipeline.md`` 8.1 caps, 8.3 rendered-pixel ban), and a+``manifest.json`` lands beside the images in the evidence folder+``unreal/Verse/Saved/Harness/proof/WP<nn>/<sub-task>/`` (work-packages.md 0.4).++ python scripts/unreal/capture.py shots --wp WP12 --subtask 12.3 [--view hangar_floor]+ python scripts/unreal/capture.py palette shot.png [more.png ...]+ python scripts/unreal/capture.py proof-dir --wp WP10 --subtask 10.8+"""++from __future__ import annotations++import argparse+import json+import re+import subprocess+import sys+from collections.abc import 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++CAMERAS_FILE = common.PROJECT_DIR / "Harness" / "capture" / "cameras.json"+RUN_TIMEOUT_S = 20 * 60++#: art-pipeline.md 8.1: role -> (sRGB hexes, min share, max share). None = no bound.+PALETTE: dict[str, tuple[tuple[str, ...], float | None, float | None]] = {+ "void_black": (("#0B0C0E",), 0.25, 0.45),+ "blackened_steel": (("#16171A",), 0.15, 0.30),+ "graphite": (("#2A2D31",), 0.10, 0.25),+ "gunmetal": (("#3B3F47",), 0.05, 0.15),+ "concrete": (("#5E6368", "#6A6C6B"), 0.05, 0.20),+ "oil_grime": (("#121212",), None, None),+ "worn_steel": (("#A9ADB2",), None, 0.03),+ "work_light": (("#F2F4F5", "#D9DDE0"), 0.03, 0.08),+ "signal_red": (("#E3242B",), None, 0.015),+ "amber": (("#F2A33A",), None, 0.008),+ "hazard_yellow": (("#D9B23A",), None, 0.01),+ "brand_gold": (("#C8A24A",), None, 0.005),+}+#: A pixel belongs to its nearest role when within this CIE76 distance, else "other".+MATCH_DELTA_E = 12.0+#: art-pipeline.md 8.3 rendered-pixel rule.+BANNED_HUE = (160.0, 330.0)+BANNED_SAT = 0.25+BANNED_VALUE = 0.08+MAX_SAMPLE_PIXELS = 1_000_000+++def _hex_rgb(text: str) -> tuple[int, int, int]:+ text = text.lstrip("#")+ return int(text[0:2], 16), int(text[2:4], 16), int(text[4:6], 16)+++def srgb_to_lab(rgb): # numpy array (..., 3) of 0-255 -> CIELAB (D65)+ import numpy as np++ c = np.asarray(rgb, dtype=np.float64) / 255.0+ lin = np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)+ m = np.array([[0.4124, 0.3576, 0.1805], [0.2126, 0.7152, 0.0722], [0.0193, 0.1192, 0.9505]])+ xyz = lin @ m.T / np.array([0.95047, 1.0, 1.08883])+ f = np.where(xyz > 216 / 24389, np.cbrt(xyz), (24389 / 27 * xyz + 16) / 116)+ return np.stack(+ [116 * f[..., 1] - 16, 500 * (f[..., 0] - f[..., 1]), 200 * (f[..., 1] - f[..., 2])], -1+ )+++def banned_mask(rgb):+ """Pixels the rendered-pixel rule bans: hue 160-330 deg, saturation > 0.25, value > 0.08."""+ import numpy as np++ c = np.asarray(rgb, dtype=np.float64) / 255.0+ mx, mn = c.max(-1), c.min(-1)+ delta = mx - mn+ sat = np.where(mx > 0, delta / np.where(mx > 0, mx, 1), 0)+ r, g, b = c[..., 0], c[..., 1], c[..., 2]+ safe = np.where(delta > 0, delta, 1)+ hue = np.where(+ mx == r, ((g - b) / safe) % 6, np.where(mx == g, (b - r) / safe + 2, (r - g) / safe + 4)+ )+ hue = np.where(delta > 0, hue * 60.0, 0.0)+ return (+ (hue >= BANNED_HUE[0]) & (hue <= BANNED_HUE[1]) & (sat > BANNED_SAT) & (mx > BANNED_VALUE)+ )+++def measure(pixels) -> dict:+ """Palette shares, cap verdicts and banned-pixel count of an (H, W, 3) uint8 array."""+ import numpy as np++ flat = np.asarray(pixels)[..., :3].reshape(-1, 3)+ if len(flat) > MAX_SAMPLE_PIXELS:+ step = int(np.ceil(len(flat) / MAX_SAMPLE_PIXELS))+ flat = flat[::step]+ roles, refs = [], []+ for role, (hexes, _lo, _hi) in PALETTE.items():+ for h in hexes:+ roles.append(role)+ refs.append(_hex_rgb(h))+ lab = srgb_to_lab(flat)+ ref_lab = srgb_to_lab(np.array(refs))+ dist = np.linalg.norm(lab[:, None, :] - ref_lab[None, :, :], axis=-1)+ nearest = dist.argmin(1)+ matched = dist[np.arange(len(flat)), nearest] <= MATCH_DELTA_E+ total = len(flat)+ shares = {role: 0.0 for role in PALETTE}+ for idx, role in enumerate(roles):+ shares[role] += float(((nearest == idx) & matched).sum()) / total+ shares["other"] = float((~matched).sum()) / total+ caps = []+ for role, (_hexes, lo, hi) in PALETTE.items():+ share = shares[role]+ status = "fail" if hi is not None and share > hi else "pass"+ caps.append(+ {+ "role": role,+ "share": round(share, 5),+ "min": lo,+ "max": hi,+ "status": status,+ "belowRange": lo is not None and share < lo,+ }+ )+ banned = int(banned_mask(flat).sum())+ return {+ "pixels": total,+ "shares": {k: round(v, 5) for k, v in shares.items()},+ "caps": caps,+ "bannedPixels": banned,+ "pass": banned == 0 and all(c["status"] == "pass" for c in caps),+ }+++def measure_file(path: Path) -> dict:+ import numpy as np+ from PIL import Image++ with Image.open(path) as image:+ pixels = np.asarray(image.convert("RGB"))+ result = measure(pixels)+ result["file"] = str(path)+ return result+++def proof_dir(worktree: Path, wp: str, subtask: str) -> Path:+ """``unreal/Verse/Saved/Harness/proof/WP<nn>/<sub-task>/`` (work-packages.md 0.4)."""+ if not re.fullmatch(r"WP\d{2}", wp):+ raise common.UnrealScriptError(f"package id must look like WP07, got {wp!r}")+ if not re.fullmatch(r"\d{1,2}\.\d{1,2}[a-z]?", subtask):+ raise common.UnrealScriptError(f"sub-task must look like 7.3 or 7.3a, got {subtask!r}")+ return worktree / "unreal" / "Verse" / "Saved" / "Harness" / "proof" / wp / subtask+++def views_by_map(doc: Mapping, only: Sequence[str] | None = None) -> dict[str, list[dict]]:+ groups: dict[str, list[dict]] = {}+ for view in doc["views"]:+ if only and view["id"] not in only:+ continue+ groups.setdefault(view["map"], []).append(view)+ return groups+++def command_for(+ engine: Path,+ project: Path,+ map_path: str,+ capture_file: Path,+ out_dir: Path,+ log: Path,+ width: int = 1920,+ height: int = 1080,+) -> list[str]:+ return [+ str(common.editor_cmd(engine)),+ str(project),+ map_path,+ "-game",+ "-d3d12",+ "-windowed",+ f"-ResX={width}",+ f"-ResY={height}",+ "-WinX=-20000",+ "-WinY=-20000",+ "-unattended",+ "-nosound",+ "-NoP4",+ f"-VerseCapture={capture_file}",+ f"-VerseCaptureOut={out_dir}",+ f"-abslog={log}",+ ]+++def shots(doc: Mapping, out_dir: Path, worktree: Path, only: Sequence[str] | None = None) -> dict:+ from scripts.unreal import with_lock++ engine, project = common.engine_root(), common.project_file(worktree)+ out_dir.mkdir(parents=True, exist_ok=True)+ runs = []+ for k, (map_path, views) in enumerate(views_by_map(doc, only).items()):+ capture_file = out_dir / f"capture{k}.json"+ part = {+ "schema": "verse.capture/1",+ "id": f"{doc['id']}.{k}",+ "map": map_path,+ "views": views,+ "settleFrames": doc.get("settleFrames", 30),+ }+ capture_file.write_text(json.dumps(part, indent=2), encoding="utf-8")+ log = out_dir / f"capture{k}.log"+ command = command_for(engine, project, map_path, capture_file, out_dir, log)+ with with_lock.MachineLock("capture", " ".join(command[:3])):+ try:+ code = subprocess.run(+ command,+ timeout=RUN_TIMEOUT_S,+ check=False, # noqa: S603+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ ).returncode+ except subprocess.TimeoutExpired:+ code = 124+ runs.append({"map": map_path, "returncode": code, "log": str(log)})+ images = []+ for view in [v for vs in views_by_map(doc, only).values() for v in vs]:+ png = out_dir / f"{view['id']}.png"+ entry = {+ "view": view["id"],+ "deck": view.get("deck"),+ "file": str(png),+ "exists": png.exists(),+ }+ if png.exists():+ entry["palette"] = measure_file(png)+ images.append(entry)+ manifest = {+ "schema": "verse.proof/1",+ "branch": common.current_branch(worktree),+ "created": common.run_stamp(),+ "runs": runs,+ "images": images,+ "pass": all(r["returncode"] == 0 for r in runs) and all(i["exists"] for i in images),+ }+ (out_dir / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")+ return manifest+++def main(argv: Sequence[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ sub = parser.add_subparsers(dest="cmd", required=True)+ shots_p = sub.add_parser("shots")+ shots_p.add_argument("--views", type=Path, default=CAMERAS_FILE)+ shots_p.add_argument("--view", action="append", help="Only these view ids (repeatable).")+ shots_p.add_argument("--wp", default="WP10")+ shots_p.add_argument("--subtask", default="10.8")+ shots_p.add_argument("--worktree", type=Path, default=common.REPO_ROOT)+ pal_p = sub.add_parser("palette")+ pal_p.add_argument("images", type=Path, nargs="+")+ dir_p = sub.add_parser("proof-dir")+ dir_p.add_argument("--wp", required=True)+ dir_p.add_argument("--subtask", required=True)+ dir_p.add_argument("--worktree", type=Path, default=common.REPO_ROOT)+ args = parser.parse_args(argv)+ try:+ if args.cmd == "proof-dir":+ path = proof_dir(args.worktree.resolve(), args.wp, args.subtask)+ path.mkdir(parents=True, exist_ok=True)+ print(path)+ return 0+ if args.cmd == "palette":+ results = [measure_file(p) for p in args.images]+ print(json.dumps(results, indent=2))+ return 0 if all(r["pass"] for r in results) else 1+ out = proof_dir(args.worktree.resolve(), args.wp, args.subtask)+ manifest = shots(+ json.loads(args.views.read_text(encoding="utf-8")),+ out,+ args.worktree.resolve(),+ args.view,+ )+ except common.UnrealScriptError as error:+ return common.exit_with(error)+ for image in manifest["images"]:+ verdict = image.get("palette", {})+ print(+ f"{image['view']}: {'ok' if image['exists'] else 'MISSING'} "+ f"banned={verdict.get('bannedPixels', 'n/a')} palette={verdict.get('pass', 'n/a')}"+ )+ print(f"capture: {'OK' if manifest['pass'] else 'FAIL'} ({out / 'manifest.json'})")+ return 0 if manifest["pass"] else 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/unreal/check_bot_isolation.py b/scripts/unreal/check_bot_isolation.pynew file mode 100644index 0000000000..bce1bdcfe9--- /dev/null+++ b/scripts/unreal/check_bot_isolation.py@@ -0,0 +1,237 @@+#!/usr/bin/env python3+"""Static fairness checks F1 (isolation) and F6 (symmetry) of contracts/bot.md section 10.++F1: ``Source/VerseBot/**`` never reads the truth about the opponent. It uses+none of ``GetPlayerPawn``, ``GetPlayerCharacter``, ``GetPlayerController``,+actor iterators, ``GetAllActorsOfClass`` or ``GetActorOfClass`` over pawns, a+generic ``TActorIterator<AActor>``/``TActorRange<AActor>`` in a file that casts to+a pawn, ``GetPawn()`` on another controller,+another actor's ability system component, ``IVersePieceQuery::GetPieceState``+outside ``FVersePieceBelief``; no EQS context returns an ``AVerseCharacter``;+raw world traces only on ``VerseSight`` or through ``TestSight``. That sight+traces ignore pawn capsules is a property of the ``VerseSight`` channel set-up and+is checked at run time by F2, not here.++F6: the harness person models read the same ``FVersePerceptFrame`` under the+same rules as the bot: the model controller subscribes to ``OnPerceptFrame``+(naming the type is not enough), and hearing ranges come from ``DA_Audibility``+(``UVerseAudibilityTable``), never from numbers in code.++Comments and string literals are stripped before matching.++ python scripts/unreal/check_bot_isolation.py # F1 and F6 on the repo+ python scripts/unreal/check_bot_isolation.py --source <dir>+"""++from __future__ import annotations++import argparse+import re+import sys+from collections.abc import Iterable, Iterator+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parents[2]+DEFAULT_SOURCE = REPO_ROOT / "unreal" / "Verse" / "Source"+SOURCE_SUFFIXES = (".h", ".cpp", ".inl")+#: Fakes and tests may build any world they like; the rules apply to shipped bot code.+EXEMPT_PARTS = ("Tests",)++_COMMENT = re.compile(r"//[^\n]*|/\*.*?\*/", re.S)+_STRING = re.compile(r'"(?:\\.|[^"\\\n])*"')++PAWNISH = r"(?:AVerseCharacter|ACharacter|APawn|AVerseDefaultCharacter)"++#: (rule id, pattern, message). Patterns run on comment- and string-free text.+RULES: tuple[tuple[str, re.Pattern[str], str], ...] = (+ ("F1.player-pawn", re.compile(r"\bGetPlayerPawn\s*\("), "GetPlayerPawn reads the opponent"),+ (+ "F1.player-character",+ re.compile(r"\bGetPlayerCharacter\s*\("),+ "GetPlayerCharacter reads the opponent",+ ),+ (+ "F1.player-controller",+ re.compile(r"\bGet(?:First)?PlayerController(?:Iterator)?\s*\("),+ "GetPlayerController reaches the person's controller",+ ),+ (+ "F1.actor-iterator",+ re.compile(rf"\bT(?:Actor|Object)(?:Iterator|Range)\s*<\s*{PAWNISH}\s*>"),+ "an actor iterator over pawns",+ ),+ (+ "F1.all-actors",+ re.compile(rf"\bGetAllActors(?:OfClass|WithInterface|WithTag)?\s*\([^;]*{PAWNISH}"),+ "GetAllActorsOfClass on pawns",+ ),+ (+ "F1.actor-of-class",+ re.compile(rf"\bGetActors?OfClass\s*(?:<\s*{PAWNISH}\s*>|\([^;]*{PAWNISH})"),+ "GetActorOfClass on pawns",+ ),+ (+ "F1.other-pawn",+ re.compile(r"(?<!\bthis)(?:->|\.)\s*GetPawn\s*(?:<[^>]*>)?\s*\("),+ "GetPawn() on a controller other than its own",+ ),+ (+ "F1.other-asc",+ re.compile(+ r"GetAbilitySystemComponentFromActor\s*\(\s*(?!GetPawn\s*\(\s*\)\s*\))"+ r"|(?<!GetPawn\(\))(?<!\bthis)->\s*GetAbilitySystemComponent\s*\("+ ),+ "attribute reads on a non-own ability component",+ ),+ (+ "F1.raw-trace",+ re.compile(+ r"\b(?:LineTrace|Sweep|Overlap)(?:Single|Multi|Test|Any)\w*\s*\((?![^;]*VerseSight)"+ ),+ "a raw world trace that is not on VerseSight (use IVersePenetrationQuery::TestSight)",+ ),+)+GENERIC_ITERATOR = re.compile(r"\bT(?:Actor|Object)(?:Iterator|Range)\s*<\s*(?:AActor|UObject)\s*>")+PAWN_CAST = re.compile(rf"\bCast(?:Checked)?\s*<\s*{PAWNISH}\s*>")+PERCEPT_SUBSCRIBE = re.compile(r"\bOnPerceptFrame\s*(?:\.|->)\s*Add\w*\s*\(")+PIECE_STATE = re.compile(r"\bGetPieceState\s*\(")+EQS_CONTEXT = re.compile(r"\bUEnvQueryContext\w*")+EQS_PAWN = re.compile(r"\bAVerseCharacter\b")+HEARING_NUMBER = re.compile(+ r"\b\w*(?:Hear|Audib)\w*(?:Range|Radius|Distance)\w*\s*(?:=|\{|\()\s*-?\d+(?:\.\d*)?f?\b"+)+AUDIBILITY = re.compile(r"\bUVerseAudibilityTable\b|\bDA_Audibility\b|\bAudibilityTable\b")+PERCEPT_FRAME = re.compile(r"\bFVersePerceptFrame\b")+++def strip_code(text: str) -> str:+ """Text with comments and string literals blanked (line numbers kept)."""++ def blank(match: re.Match[str]) -> str:+ return re.sub(r"[^\n]", " ", match.group(0))++ return _STRING.sub(blank, _COMMENT.sub(blank, text))+++def _line_of(text: str, offset: int) -> int:+ return text.count("\n", 0, offset) + 1+++def source_files(root: Path) -> Iterator[Path]:+ if not root.exists():+ return+ for path in sorted(root.rglob("*")):+ if path.suffix in SOURCE_SUFFIXES and not any(p in EXEMPT_PARTS for p in path.parts):+ yield path+++def _rel(path: Path, base: Path) -> str:+ try:+ return path.relative_to(base).as_posix()+ except ValueError:+ return path.as_posix()+++def scan_rules(+ path: Path, base: Path, rules: Iterable[tuple[str, re.Pattern[str], str]]+) -> list[str]:+ code = strip_code(path.read_text(encoding="utf-8", errors="replace"))+ findings = []+ for rule, pattern, message in rules:+ for match in pattern.finditer(code):+ findings.append(+ f"{_rel(path, base)}:{_line_of(code, match.start())}: {rule}: {message}"+ )+ return findings+++def check_isolation(source: Path = DEFAULT_SOURCE) -> list[str]:+ """F1 findings for ``<source>/VerseBot``."""+ bot = source / "VerseBot"+ findings: list[str] = []+ for path in source_files(bot):+ findings += scan_rules(path, source, RULES)+ code = strip_code(path.read_text(encoding="utf-8", errors="replace"))+ if "PieceBelief" not in path.name:+ for match in PIECE_STATE.finditer(code):+ findings.append(+ f"{_rel(path, source)}:{_line_of(code, match.start())}: F1.piece-state: "+ "IVersePieceQuery::GetPieceState outside FVersePieceBelief"+ )+ if PAWN_CAST.search(code):+ for match in GENERIC_ITERATOR.finditer(code):+ findings.append(+ f"{_rel(path, source)}:{_line_of(code, match.start())}: F1.actor-iterator: "+ "a generic actor iterator in a file that casts to a pawn"+ )+ if EQS_CONTEXT.search(code):+ for match in EQS_PAWN.finditer(code):+ findings.append(+ f"{_rel(path, source)}:{_line_of(code, match.start())}: F1.eqs-context: "+ "an EQS context names AVerseCharacter"+ )+ return findings+++def _model_files(source: Path) -> list[Path]:+ harness = source / "VerseHarness"+ return [p for p in source_files(harness) if "Model" in p.name or "Trick" in p.name]+++def check_symmetry(source: Path = DEFAULT_SOURCE) -> list[str]:+ """F6 findings: person models perceive like the bot; hearing ranges come from DA_Audibility."""+ findings: list[str] = []+ models = _model_files(source)+ for path in models:+ findings += [f.replace(": F1.", ": F6.model.", 1) for f in scan_rules(path, source, RULES)]+ model_code = [strip_code(p.read_text(encoding="utf-8", errors="replace")) for p in models]+ if models and not any(PERCEPT_FRAME.search(code) for code in model_code):+ findings.append(+ "VerseHarness: F6.model-input: person models do not read FVersePerceptFrame"+ )+ if models and not any(PERCEPT_SUBSCRIBE.search(code) for code in model_code):+ findings.append(+ "VerseHarness: F6.model-subscribe: no person model subscribes to OnPerceptFrame, "+ "so no frame ever reaches it"+ )+ hearing_dirs = [source / "VerseBot", source / "VerseCombat" / "Private" / "Perception"]+ for directory in hearing_dirs:+ for path in source_files(directory):+ code = strip_code(path.read_text(encoding="utf-8", errors="replace"))+ for match in HEARING_NUMBER.finditer(code):+ findings.append(+ f"{_rel(path, source)}:{_line_of(code, match.start())}: F6.hearing-literal: "+ "a hearing range in code; read it from DA_Audibility"+ )+ mentions_hearing = re.search(r"\bHear(?:ing|d)\w*", code) and re.search(+ r"\b(?:Range|Radius)\b|RangeM\b", code+ )+ if mentions_hearing and not AUDIBILITY.search(code):+ findings.append(+ f"{_rel(path, source)}: F6.hearing-source: hearing ranges without "+ "UVerseAudibilityTable (DA_Audibility)"+ )+ return findings+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument("--source", type=Path, default=DEFAULT_SOURCE)+ parser.add_argument("--only", choices=("F1", "F6"))+ args = parser.parse_args(argv)+ findings: list[str] = []+ if args.only in (None, "F1"):+ findings += check_isolation(args.source)+ if args.only in (None, "F6"):+ findings += check_symmetry(args.source)+ for line in findings:+ print(f"check_bot_isolation: {line}")+ if findings:+ print("The bot and the person models see the world only through percepts (bot.md 10).")+ return 1+ print("check_bot_isolation: clean (F1, F6)")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/unreal/check_forbidden_names.py b/scripts/unreal/check_forbidden_names.pyindex f45fa26f09..9c6f204c4f 100644--- a/scripts/unreal/check_forbidden_names.py+++ b/scripts/unreal/check_forbidden_names.py@@ -20,6 +20,14 @@ entry ``some name``.# added lines + commit messagesecho "feat(verse): ..." | python scripts/unreal/check_forbidden_names.py --stdinpython scripts/unreal/check_forbidden_names.py --hash "two words"+ python scripts/unreal/check_forbidden_names.py --folders # banned folders, engine content+ python scripts/unreal/check_forbidden_names.py --hash-file extra.sha256 FILE...+ # an extra list (tests plant one)++``--folders`` fails on a folder under ``unreal/`` or ``art/verse/`` named like a+folder the root ``.gitignore`` or the junk gate bans, in any case (architecture.md+8.4; the engine-required ``unreal/Verse/Build/`` is the one exception), and on+engine sample content paths (art-pipeline.md 11)."""from __future__ import annotations@@ -170,6 +178,59 @@ def scan_diff(base: str, hashes: set[str]) -> list[str]:_SELF = "scripts/unreal/forbidden_names.sha256"+#: Folder names banned under unreal/ and art/verse/ (architecture.md 8.4), compared lower-case.+BANNED_FOLDERS = frozenset(+ {+ "build",+ "models",+ "env",+ "logs",+ "dist",+ "secrets",+ "credentials",+ "traces",+ "blobs",+ "video",+ "videos",+ "film",+ "films",+ "renders",+ "evidence",+ "recordings",+ "screenshots",+ }+)+FOLDER_SCOPE = ("unreal/", "art/verse/")+FOLDER_EXCEPTIONS = ("unreal/Verse/Build/",)+#: Engine content packs and sample characters (art-pipeline.md 11, 12.3).+ENGINE_CONTENT = re.compile(+ r"(?:^|/)(?:StarterContent|Mannequins?)(?:/|$)|(?:^|/)(?:SKM_Manny|SKM_Quinn|SK_Mannequin)[^/]*$",+ re.I,+)+++def scan_folders(paths: Iterable[str]) -> list[str]:+ """Banned folder names and engine-content paths among repo-relative file paths."""+ findings: set[str] = set()+ for rel in paths:+ rel = rel.replace("\\", "/")+ if not rel.startswith(FOLDER_SCOPE):+ continue+ if ENGINE_CONTENT.search(rel):+ findings.add(f"{rel}: engine sample content is never used (art-pipeline 11)")+ if rel.startswith(FOLDER_EXCEPTIONS):+ rest = rel[len("unreal/Verse/Build/") :]+ parts = rest.split("/")[:-1]+ prefix = "unreal/Verse/Build/"+ else:+ parts = rel.split("/")[:-1]+ prefix = ""+ for depth, name in enumerate(parts):+ if name.lower() in BANNED_FOLDERS:+ folder = prefix + "/".join(parts[: depth + 1])+ findings.add(f"{folder}/: folder name '{name}' is banned (architecture 8.4)")+ return sorted(findings)+def main(argv: list[str] | None = None) -> int:parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])@@ -177,6 +238,18 @@ def main(argv: list[str] | None = None) -> int:parser.add_argument("--diff", metavar="BASE", help="Scan added lines and commits since BASE.")parser.add_argument("--stdin", action="store_true", help="Scan text from stdin.")parser.add_argument("--hash", metavar="PHRASE", action="append", help="Print entry hashes.")+ parser.add_argument(+ "--hash-file",+ type=Path,+ action="append",+ default=[],+ help="An extra hash list (repeatable).",+ )+ parser.add_argument(+ "--folders",+ action="store_true",+ help="Check folder names and engine-content paths of tracked files.",+ )args = parser.parse_args(argv)for stream in (sys.stdout, sys.stderr):if hasattr(stream, "reconfigure"):@@ -187,7 +260,18 @@ def main(argv: list[str] | None = None) -> int:for h in sorted(entry_hashes(phrase)):print(h)return 0+ if args.folders:+ listed = args.paths or [p for p in _git("ls-files", "--", *FOLDER_SCOPE).splitlines() if p]+ found = scan_folders(listed)+ for line in found:+ print(f"check_forbidden_names: {line}")+ if found:+ return 1+ print(f"check_forbidden_names: folders clean ({len(listed)} paths)")+ return 0hashes = load_hashes()+ for extra in args.hash_file:+ hashes |= load_hashes(extra)if args.stdin:findings = [f"stdin: forbidden name ({hit})" for hit in scan_text(sys.stdin.read(), hashes)]elif args.diff:diff --git a/scripts/unreal/check_lfs.py b/scripts/unreal/check_lfs.pynew file mode 100644index 0000000000..b10748cf62--- /dev/null+++ b/scripts/unreal/check_lfs.py@@ -0,0 +1,250 @@+#!/usr/bin/env python3+"""LFS pointer, remote object and size gate of the ``unreal-static`` lane.++Fails when, among the checked paths (architecture.md 8.4, art-pipeline.md 10):++* a ``.uasset``, ``.umap`` or other LFS-routed file is committed as content,+ not as a Git LFS pointer;+* a pointer's object is missing on the remote (pushed without ``git lfs push``);+* one LFS object is larger than 50 MB (warns from 20 MB);+* the LFS objects a pull request adds sum to more than 200 MB+ (``DODAIOS_LFS_GROWTH_APPROVED=1`` is the integration owner's approval);+* a file that is not an LFS pointer is larger than 5 MB.++It reads blobs from Git, so it works with LFS off (``lfs: false`` checkout).++ python scripts/unreal/check_lfs.py --diff origin/main # paths changed since the base+ python scripts/unreal/check_lfs.py # every tracked path in scope+ python scripts/unreal/check_lfs.py --no-remote # skip the remote object check+"""++from __future__ import annotations++import argparse+import base64+import json+import os+import re+import subprocess+import sys+import urllib.error+import urllib.request+from collections.abc import Callable, Iterable, Sequence+from dataclasses import dataclass+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parents[2]+SCOPE = ("unreal/", "art/verse/")+MB = 1024 * 1024+WARN_BYTES = 20 * MB+FAIL_BYTES = 50 * MB+PR_GROWTH_BYTES = 200 * MB+PLAIN_FAIL_BYTES = 5 * MB+#: Always binary in the Unreal tree; they must reach Git as LFS pointers.+BINARY_SUFFIXES = (".uasset", ".umap", ".ubulk", ".uexp", ".upk")+POINTER_HEAD = b"version https://git-lfs.github.com/spec/v1"+_OID = re.compile(rb"^oid sha256:([0-9a-f]{64})$", re.M)+_SIZE = re.compile(rb"^size (\d+)$", re.M)+GROWTH_ENV = "DODAIOS_LFS_GROWTH_APPROVED"+++@dataclass(frozen=True)+class Pointer:+ path: str+ oid: str+ size: int+++def git(*args: str, cwd: Path = REPO_ROOT, data: bytes | None = None) -> bytes:+ proc = subprocess.run( # noqa: S603+ ["git", *args], # noqa: S607+ cwd=cwd,+ input=data,+ capture_output=True,+ check=True,+ )+ return proc.stdout+++def parse_pointer(path: str, blob: bytes) -> Pointer | None:+ if not blob.startswith(POINTER_HEAD) or len(blob) > 1024:+ return None+ oid, size = _OID.search(blob), _SIZE.search(blob)+ if not oid or not size:+ return None+ return Pointer(path, oid.group(1).decode(), int(size.group(1)))+++def changed_paths(base: str, cwd: Path = REPO_ROOT) -> list[str]:+ out = git("diff", "--name-only", "--diff-filter=AMR", f"{base}...HEAD", "--", *SCOPE, cwd=cwd)+ return [p for p in out.decode("utf-8").splitlines() if p]+++def tracked_paths(cwd: Path = REPO_ROOT) -> list[str]:+ return [p for p in git("ls-files", "--", *SCOPE, cwd=cwd).decode("utf-8").splitlines() if p]+++def lfs_routed(paths: Sequence[str], cwd: Path = REPO_ROOT) -> set[str]:+ if not paths:+ return set()+ out = git(+ "check-attr", "--stdin", "-z", "filter", cwd=cwd, data="\0".join(paths).encode() + b"\0"+ )+ parts = out.split(b"\0")+ routed = set()+ for i in range(0, len(parts) - 2, 3):+ if parts[i + 2] == b"lfs":+ routed.add(parts[i].decode("utf-8"))+ return routed+++def blob_head(rev: str, path: str, cwd: Path = REPO_ROOT) -> tuple[int, bytes]:+ size = int(git("cat-file", "-s", f"{rev}:{path}", cwd=cwd).strip())+ head = git("cat-file", "blob", f"{rev}:{path}", cwd=cwd)[:1024] if size <= 1024 else b""+ return size, head+++def check_paths(+ paths: Iterable[str], rev: str = "HEAD", cwd: Path = REPO_ROOT+) -> tuple[list[str], list[str], list[Pointer]]:+ """(errors, warnings, pointers) for ``paths`` as committed at ``rev``."""+ paths = sorted(set(paths))+ routed = lfs_routed(paths, cwd)+ errors: list[str] = []+ warnings: list[str] = []+ pointers: list[Pointer] = []+ for path in paths:+ try:+ size, head = blob_head(rev, path, cwd)+ except subprocess.CalledProcessError:+ continue # deleted at rev+ pointer = parse_pointer(path, head) if head else None+ must_be_lfs = path in routed or path.lower().endswith(BINARY_SUFFIXES)+ if pointer:+ pointers.append(pointer)+ if pointer.size > FAIL_BYTES:+ errors.append(+ f"{path}: LFS object of {pointer.size / MB:.1f} MB is over the 50 MB cap"+ )+ elif pointer.size > WARN_BYTES:+ warnings.append(+ f"{path}: LFS object of {pointer.size / MB:.1f} MB (warn from 20 MB)"+ )+ if path not in routed:+ warnings.append(+ f"{path}: an LFS pointer on a path .gitattributes does not route to LFS"+ )+ continue+ if must_be_lfs:+ errors.append(+ f"{path}: committed as content, not as a Git LFS pointer (run git lfs install)"+ )+ elif size > PLAIN_FAIL_BYTES:+ errors.append(+ f"{path}: {size / MB:.1f} MB plain file; over 5 MB must be an LFS pointer"+ )+ return errors, warnings, pointers+++def growth_errors(pointers: Sequence[Pointer], env: dict[str, str] | None = None) -> list[str]:+ env = os.environ if env is None else env+ total = sum(p.size for p in {p.oid: p for p in pointers}.values())+ if total > PR_GROWTH_BYTES and env.get(GROWTH_ENV) != "1":+ return [f"LFS growth {total / MB:.1f} MB is over 200 MB; the integration owner approves it"]+ return []+++# --- remote objects ---++Fetch = Callable[[str, bytes, dict[str, str]], dict]+++def batch_url(remote_url: str) -> str:+ url = remote_url.strip()+ match = re.match(r"^git@([^:]+):(.+?)(?:\.git)?/?$", url)+ if match:+ url = f"https://{match.group(1)}/{match.group(2)}"+ url = re.sub(r"^https://[^@/]+@", "https://", url).rstrip("/")+ if not url.endswith(".git"):+ url += ".git"+ return f"{url}/info/lfs/objects/batch"+++def _http_fetch(url: str, body: bytes, headers: dict[str, str]) -> dict:+ request = urllib.request.Request(url, data=body, headers=headers, method="POST") # noqa: S310+ with urllib.request.urlopen(request, timeout=60) as response: # noqa: S310+ return json.loads(response.read().decode("utf-8"))+++def missing_on_remote(+ pointers: Sequence[Pointer],+ remote_url: str,+ *,+ fetch: Fetch = _http_fetch,+ token: str | None = None,+) -> list[str]:+ """Paths whose object the remote's LFS batch API does not have."""+ unique = {p.oid: p for p in pointers}+ if not unique:+ return []+ headers = {+ "Accept": "application/vnd.git-lfs+json",+ "Content-Type": "application/vnd.git-lfs+json",+ }+ if token:+ headers["Authorization"] = (+ "Basic " + base64.b64encode(f"x-access-token:{token}".encode()).decode()+ )+ errors: list[str] = []+ items = list(unique.values())+ for start in range(0, len(items), 100):+ chunk = items[start : start + 100]+ body = json.dumps(+ {+ "operation": "download",+ "transfers": ["basic"],+ "objects": [{"oid": p.oid, "size": p.size} for p in chunk],+ }+ ).encode("utf-8")+ try:+ answer = fetch(batch_url(remote_url), body, headers)+ except (urllib.error.URLError, OSError, ValueError) as exc:+ return [f"LFS batch API unreachable ({exc}); cannot prove the objects were pushed"]+ by_oid = {o.get("oid"): o for o in answer.get("objects", [])}+ for p in chunk:+ obj = by_oid.get(p.oid)+ if obj is None or obj.get("error") or "actions" not in obj:+ code = (obj or {}).get("error", {}).get("code", "absent")+ errors.append(+ f"{p.path}: LFS object {p.oid[:12]} missing on the remote ({code}); "+ "run git lfs push"+ )+ return errors+++def main(argv: Sequence[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument("--diff", metavar="BASE", help="Check paths changed since BASE (PR mode).")+ parser.add_argument("--no-remote", action="store_true", help="Skip the remote object check.")+ parser.add_argument("--remote", default="origin")+ parser.add_argument("paths", nargs="*")+ args = parser.parse_args(argv)+ paths = args.paths or (changed_paths(args.diff) if args.diff else tracked_paths())+ errors, warnings, pointers = check_paths(paths)+ if args.diff:+ errors += growth_errors(pointers)+ if pointers and not args.no_remote:+ url = git("remote", "get-url", args.remote).decode().strip()+ errors += missing_on_remote(pointers, url, token=os.environ.get("GITHUB_TOKEN"))+ for line in warnings:+ print(f"check_lfs: warning: {line}")+ for line in errors:+ print(f"check_lfs: {line}")+ if errors:+ return 1+ print(f"check_lfs: clean ({len(paths)} paths, {len(pointers)} LFS pointers)")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/unreal/done_check.py b/scripts/unreal/done_check.pynew file mode 100644index 0000000000..d65db78d48--- /dev/null+++ b/scripts/unreal/done_check.py@@ -0,0 +1,229 @@+#!/usr/bin/env python3+"""Unreal lane status for the repo done gate (architecture.md 8.3, docs/agent-done-gate.md).++A change that touches ``unreal/**``, ``art/verse/**``, ``docs/verse/unreal/**``,+``scripts/unreal/**`` or an ``unreal-*`` workflow is done only when the Unreal+lanes that cover it are green on the commit, and a visible change has a harness+screenshot of its own work package, taken after the commit, under+``Saved/Harness/proof/<WP>/<sub-task>/``. The work package comes from ``--wp``,+the PR body's ``Work-Package:`` line or the branch name (``claude/verse-wp10-...``).+This script says+which lanes the change needs, asks GitHub for their latest run on the commit, and+answers ``DONE``, ``NOT DONE`` (exit 1) or ``n/a`` (no Unreal path, exit 0).+``scripts/agent_done_gate.py`` calls it (the hook line belongs to the+integration owner).++ python scripts/unreal/done_check.py # HEAD against origin/main+ python scripts/unreal/done_check.py --commit <sha> --base origin/main --json+ python scripts/unreal/done_check.py --wp WP12+"""++from __future__ import annotations++import argparse+import json+import re+import subprocess+import sys+from collections.abc import Callable, Sequence+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parents[2]+UNREAL_PREFIXES = (+ "unreal/",+ "art/verse/",+ "docs/verse/unreal/",+ "scripts/unreal/",+ ".github/workflows/unreal-",+)+#: Paths whose change needs a compile and the automation tests.+BUILD_PREFIXES = (+ "unreal/Verse/Source/",+ "unreal/Verse/Config/",+ "unreal/Verse/Content/",+ "unreal/Verse/Verse.uproject",+ "unreal/Verse/Plugins/",+)+#: Paths whose change is visible and needs a screenshot of the running build.+VISIBLE_PREFIXES = ("unreal/Verse/Content/", "art/verse/", "unreal/Verse/Art/")+LANES = {"static": "unreal-static.yml", "build": "unreal-build.yml"}+GREEN = {"success"}++Runner = Callable[[Sequence[str]], str]+++def _run(command: Sequence[str]) -> str:+ proc = subprocess.run(+ list(command),+ cwd=REPO_ROOT,+ capture_output=True,+ text=True, # noqa: S603+ encoding="utf-8",+ errors="replace",+ check=True,+ )+ return proc.stdout+++def _quiet(command: Sequence[str]) -> str:+ try:+ return _run(command)+ except (subprocess.CalledProcessError, FileNotFoundError):+ return ""+++def changed(base: str, commit: str, run: Runner = _run) -> list[str]:+ out = run(["git", "diff", "--name-only", f"{base}...{commit}"])+ return [p for p in out.splitlines() if p]+++def needed_lanes(paths: Sequence[str]) -> list[str]:+ unreal = [p for p in paths if p.startswith(UNREAL_PREFIXES)]+ if not unreal:+ return []+ lanes = ["static"]+ if any(p.startswith(BUILD_PREFIXES) for p in unreal):+ lanes.append("build")+ return lanes+++def is_visible(paths: Sequence[str]) -> bool:+ return any(p.startswith(VISIBLE_PREFIXES) for p in paths)+++def lane_status(workflow: str, commit: str, run: Runner = _run) -> dict:+ try:+ out = run(+ [+ "gh",+ "run",+ "list",+ "--workflow",+ workflow,+ "--commit",+ commit,+ "--limit",+ "5",+ "--json",+ "status,conclusion,url,event,headSha,createdAt",+ ]+ )+ runs = json.loads(out or "[]")+ except (subprocess.CalledProcessError, FileNotFoundError, ValueError) as exc:+ return {"workflow": workflow, "state": "unknown", "detail": f"gh failed: {exc}"}+ if not runs:+ return {"workflow": workflow, "state": "missing", "detail": "no run on this commit"}+ latest = max(runs, key=lambda r: r.get("createdAt", ""))+ if latest.get("status") != "completed":+ return {"workflow": workflow, "state": "running", "detail": latest.get("url", "")}+ state = "green" if latest.get("conclusion") in GREEN else "red"+ return {+ "workflow": workflow,+ "state": state,+ "detail": latest.get("url", ""),+ "conclusion": latest.get("conclusion"),+ }+++WP_PATTERN = re.compile(r"\bWP(\d{1,2})\b", re.I)+++def work_package(explicit: str | None, branch: str = "", pr_body: str = "") -> str | None:+ """``WPnn`` from ``--wp``, the PR body's ``Work-Package:`` line, or the branch name."""+ if explicit:+ match = WP_PATTERN.search(explicit)+ return f"WP{int(match.group(1)):02d}" if match else explicit+ for line in pr_body.splitlines():+ if line.lower().startswith("work-package:"):+ match = WP_PATTERN.search(line)+ if match:+ return f"WP{int(match.group(1)):02d}"+ match = re.search(r"verse-wp(\d{1,2})", branch, re.I)+ return f"WP{int(match.group(1)):02d}" if match else None+++def has_screenshot(worktree: Path, wp: str | None, since: float) -> bool:+ """A PNG under ``proof/<WP>/<sub-task>/`` written after ``since`` (the commit time)."""+ if not wp:+ return False+ proof = worktree / "unreal" / "Verse" / "Saved" / "Harness" / "proof"+ for folder in (proof / wp, proof / wp.replace("WP0", "WP")):+ if not folder.is_dir():+ continue+ for png in folder.glob("*/**/*.png"):+ try:+ if png.stat().st_mtime >= since:+ return True+ except OSError:+ continue+ return False+++def evaluate(+ paths: Sequence[str],+ commit: str,+ worktree: Path,+ run: Runner = _run,+ *,+ wp: str | None = None,+ since: float = 0.0,+) -> dict:+ lanes = needed_lanes(paths)+ if not lanes:+ return {"verdict": "n/a", "lanes": [], "detail": "no Unreal path changed"}+ statuses = [lane_status(LANES[lane], commit, run) for lane in lanes]+ problems = [+ f"{s['workflow']}: {s['state']} {s.get('detail', '')}".strip()+ for s in statuses+ if s["state"] != "green"+ ]+ visible = is_visible(paths)+ if visible and not has_screenshot(worktree, wp, since):+ problems.append(+ f"visible change without a harness screenshot of {wp or 'its work package'} "+ "taken after the commit (scripts/unreal/capture.py shots --wp <WP> --subtask <n>)"+ )+ return {+ "verdict": "NOT DONE" if problems else "DONE",+ "lanes": statuses,+ "visible": visible,+ "problems": problems,+ }+++def main(argv: Sequence[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument("--base", default="origin/main")+ parser.add_argument("--commit", default="HEAD")+ parser.add_argument("--worktree", type=Path, default=REPO_ROOT)+ parser.add_argument("--json", action="store_true")+ parser.add_argument("--wp", help="Work package (WP10); default from the PR or the branch.")+ args = parser.parse_args(argv)+ try:+ commit = _run(["git", "rev-parse", args.commit]).strip()+ paths = changed(args.base, commit)+ except subprocess.CalledProcessError as exc:+ print(f"done_check: git failed: {exc}", file=sys.stderr)+ return 2+ since = float(_run(["git", "show", "-s", "--format=%ct", commit]).strip() or 0)+ wp = args.wp+ if not wp:+ branch = _quiet(["git", "rev-parse", "--abbrev-ref", "HEAD"])+ body = _quiet(["gh", "pr", "view", "--json", "body", "--jq", ".body"])+ wp = work_package(None, branch, body)+ result = evaluate(paths, commit, args.worktree, wp=wp, since=since)+ result["workPackage"] = wp+ result["commit"] = commit+ if args.json:+ print(json.dumps(result, indent=2))+ else:+ for lane in result["lanes"]:+ print(f"done_check: {lane['workflow']}: {lane['state']} {lane.get('detail', '')}")+ for problem in result.get("problems", []):+ print(f"done_check: {problem}")+ print(f"done_check: {result['verdict']}")+ return 1 if result["verdict"] == "NOT DONE" else 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/unreal/netcode.py b/scripts/unreal/netcode.pynew file mode 100644index 0000000000..35c070e5a4--- /dev/null+++ b/scripts/unreal/netcode.py@@ -0,0 +1,281 @@+#!/usr/bin/env python3+"""Netcode test: a dedicated server plus two lagged clients (architecture.md 3, 8.3; RK2-RK4).++The editor runs as dedicated server (binary installs cannot build Server+targets) and two ``-game -nullrhi`` clients join it with packet lag 60 ms,+variance 10 ms and 1 % loss. A client autopilot in ``VerseHarness`` moves each+client pawn with seeded input. After the run (2 minutes by default) the logs+are parsed for movement corrections (``p.NetShowCorrections``), the+``[VerseCounter]`` lines (reconcile counters of the combat prediction) and+crashes, and the gates of ``unreal/Verse/Harness/netcode/netcode.json`` apply.++ python scripts/unreal/netcode.py # PR / merge-queue smoke, Iris on+ python scripts/unreal/netcode.py --iris both # nightly: Iris on and off+ python scripts/unreal/netcode.py --parse <run> # gates from the logs of a finished run+"""++from __future__ import annotations++import argparse+import json+import re+import subprocess+import sys+import time+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++CONFIG_FILE = common.PROJECT_DIR / "Harness" / "netcode" / "netcode.json"+CLIENT_CORRECTION = re.compile(r"\*\*\* Client: Error for")+SERVER_CORRECTION = re.compile(r"\*\*\* Server: Error for")+JOIN = re.compile(r"Join succeeded")+COUNTER = re.compile(r"\[VerseCounter\]\s+([A-Za-z0-9_.]+)=(-?\d+(?:\.\d+)?)")+READY = "[VerseNet] server ready"+LOG_FAILURES = (+ re.compile(r"Fatal error"),+ re.compile(r"Ensure condition failed"),+ re.compile(r"Unhandled Exception"),+ re.compile(r"=== Critical error: ==="),+)+STARTUP_TIMEOUT_S = 300+++def load_config(path: Path = CONFIG_FILE) -> dict:+ return json.loads(path.read_text(encoding="utf-8"))+++def emulation_cmds(net: dict) -> str:+ return ",".join(+ [+ f"Net PktLag={net['PktLag']}",+ f"Net PktLagVariance={net['PktLagVariance']}",+ f"Net PktLoss={net['PktLoss']}",+ "p.NetShowCorrections 1",+ ]+ )+++def server_command(+ engine: Path, project: Path, cfg: dict, log: Path, duration: int, iris: bool+) -> list[str]:+ return [+ str(common.editor_cmd(engine)),+ str(project),+ f"{cfg['map']}?listen",+ "-server",+ "-nullrhi",+ "-nosound",+ "-unattended",+ "-NoP4",+ f"-port={cfg['port']}",+ f"-VerseNetDuration={duration}",+ f"-UseIrisReplication={1 if iris else 0}",+ "-ExecCmds=p.NetShowCorrections 1",+ f"-abslog={log}",+ ]+++def client_command(+ engine: Path, project: Path, cfg: dict, log: Path, duration: int, iris: bool, seed: int+) -> list[str]:+ return [+ str(common.editor_cmd(engine)),+ str(project),+ f"127.0.0.1:{cfg['port']}",+ "-game",+ "-nullrhi",+ "-nosound",+ "-unattended",+ "-NoP4",+ "-windowed",+ f"-VerseNetAutopilot={seed}",+ f"-VerseNetDuration={duration + 15}",+ f"-UseIrisReplication={1 if iris else 0}",+ f"-ExecCmds={emulation_cmds(cfg['netEmulation'])}",+ f"-abslog={log}",+ ]+++def parse_log(text: str) -> dict:+ counters: dict[str, float] = {}+ for name, value in COUNTER.findall(text):+ counters[name] = counters.get(name, 0.0) + float(value)+ return {+ "clientCorrections": len(CLIENT_CORRECTION.findall(text)),+ "serverCorrections": len(SERVER_CORRECTION.findall(text)),+ "joins": len(JOIN.findall(text)),+ "counters": counters,+ "failures": [p.pattern for p in LOG_FAILURES if p.search(text)],+ }+++def evaluate(server: dict, clients: Sequence[dict], duration_s: float, gates: dict) -> dict:+ minutes = max(duration_s / 60.0, 1e-9)+ corrections = sum(c["clientCorrections"] for c in clients)+ per_client_minute = corrections / max(len(clients), 1) / minutes+ reconcile_failures = sum(+ c["counters"].get("reconcileFailures", 0.0) for c in [server, *clients]+ )+ failures = [f for part in [server, *clients] for f in part["failures"]]+ checks = [+ (+ f"clients joined {server['joins']} >= {gates['clientsConnectedMin']}",+ server["joins"] >= gates["clientsConnectedMin"],+ ),+ (+ f"corrections per client minute {per_client_minute:.2f} "+ f"<= {gates['correctionsPerClientMinuteMax']}",+ per_client_minute <= gates["correctionsPerClientMinuteMax"],+ ),+ (+ f"reconcile failures {reconcile_failures:.0f} <= {gates['reconcileFailuresMax']}",+ reconcile_failures <= gates["reconcileFailuresMax"],+ ),+ (f"no fatal, ensure or crash ({len(failures)} found)", not failures),+ ]+ return {+ "pass": all(ok for _, ok in checks),+ "checks": [{"check": text, "ok": ok} for text, ok in checks],+ "correctionsPerClientMinute": round(per_client_minute, 3),+ "serverCorrections": server["serverCorrections"],+ "reconcile": {+ k: v+ for part in [server, *clients]+ for k, v in part["counters"].items()+ if "econcile" in k+ },+ }+++def parse_run(run_dir: Path, cfg: dict, duration: float) -> dict:+ out = {}+ for variant in sorted(p for p in run_dir.iterdir() if p.is_dir()):+ server = parse_log(_read(variant / "server.log"))+ clients = [parse_log(_read(p)) for p in sorted(variant.glob("client*.log"))]+ out[variant.name] = evaluate(server, clients, duration, cfg["gates"])+ return out+++def _read(path: Path) -> str:+ return path.read_text(encoding="utf-8", errors="replace") if path.exists() else ""+++def _wait_ready(+ log: Path, proc: subprocess.Popen, timeout_s: float, sleep: Callable[[float], None] = time.sleep+) -> bool:+ deadline = time.monotonic() + timeout_s+ while time.monotonic() < deadline:+ if proc.poll() is not None:+ return False+ if READY in _read(log):+ return True+ sleep(2.0)+ return False+++def run_variant(+ variant_dir: Path,+ cfg: dict,+ duration: int,+ iris: bool,+ engine: Path,+ project: Path,+ popen: Callable[..., subprocess.Popen] = subprocess.Popen,+) -> None:+ variant_dir.mkdir(parents=True, exist_ok=True)+ server_log = variant_dir / "server.log"+ procs = [+ popen(+ server_command(engine, project, cfg, server_log, duration, iris),+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ )+ ]+ try:+ if not _wait_ready(server_log, procs[0], STARTUP_TIMEOUT_S):+ common.log("netcode: the server did not report ready; parsing what it logged")+ return+ for k in range(int(cfg["clients"])):+ log = variant_dir / f"client{k}.log"+ procs.append(+ popen(+ client_command(engine, project, cfg, log, duration, iris, 1000 + k),+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ )+ )+ limit = duration + STARTUP_TIMEOUT_S+ for proc in procs:+ try:+ proc.wait(timeout=limit)+ except subprocess.TimeoutExpired:+ proc.kill()+ proc.wait()+ finally:+ for proc in procs:+ if proc.poll() is None:+ proc.kill()+ proc.wait()+++def main(argv: Sequence[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument("--duration", type=int, help="Seconds of play (default from netcode.json).")+ parser.add_argument("--iris", choices=("on", "off", "both"), default="on")+ parser.add_argument("--parse", type=Path, help="Evaluate a finished run folder; no run.")+ parser.add_argument("--map", help="Map override (default: netcode.json, the hangar).")+ parser.add_argument("--worktree", type=Path, default=common.REPO_ROOT)+ args = parser.parse_args(argv)+ cfg = load_config()+ if args.map:+ cfg["map"] = args.map+ duration = args.duration or int(cfg["durationS"])+ if args.parse:+ run_dir = args.parse.resolve()+ else:+ from scripts.unreal import with_lock++ run_dir = (+ args.worktree+ / "unreal"+ / "Verse"+ / "Saved"+ / "Harness"+ / "netcode"+ / common.run_stamp()+ ).resolve()+ variants = {"on": [True], "off": [False], "both": [True, False]}[args.iris]+ engine, project = common.engine_root(), common.project_file(args.worktree.resolve())+ with with_lock.MachineLock("netcode", f"netcode.py --iris {args.iris}"):+ for iris in variants:+ run_variant(+ run_dir / f"iris-{'on' if iris else 'off'}",+ cfg,+ duration,+ iris,+ engine,+ project,+ )+ result = parse_run(run_dir, cfg, duration)+ report = {+ "schema": "verse.netcode_report/1",+ "run": run_dir.name,+ "durationS": duration,+ "variants": result,+ }+ (run_dir / "report.json").write_text(json.dumps(report, indent=2), encoding="utf-8")+ ok = bool(result) and all(v["pass"] for v in result.values())+ for name, verdict in result.items():+ for check in verdict["checks"]:+ print(f"{name}: {'OK ' if check['ok'] else 'FAIL'} {check['check']}")+ print(f"netcode: {'OK' if ok else 'FAIL'} ({run_dir / 'report.json'})")+ return 0 if ok else 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/unreal/perf.py b/scripts/unreal/perf.pynew file mode 100644index 0000000000..b76a4516e4--- /dev/null+++ b/scripts/unreal/perf.py@@ -0,0 +1,452 @@+#!/usr/bin/env python3+"""Perf capture of the fixed bot-vs-bot replay against the budgets of architecture.md 7.++``run`` launches one rendered game process (D3D12, window off the person's+monitors) that plays ``unreal/Verse/Harness/perf/replay.json``: a seeded duel+seen along a fixed camera path. ``VerseHarness`` starts the CSV profiler after+the warm-up, so shader compiles stay out of the numbers, takes the replay's+screenshot and stops the profiler before it exits. VRAM is sampled through+NVML (``nvidia-smi``), system RAM through the process. The run happens only+in the nightly quiet hours and when nobody used the machine for 5 minutes+(architecture.md 8.2) unless ``--force``.++ python scripts/unreal/perf.py run --profile 1440p+ python scripts/unreal/perf.py compare <a/perf.json> <b/perf.json> # A10.5: <= 3 %+ python scripts/unreal/perf.py parse <profile.csv> # stats of one CSV+"""++from __future__ import annotations++import argparse+import csv+import datetime as dt+import json+import math+import os+import shutil+import subprocess+import sys+import threading+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++PERF_DIR = common.PROJECT_DIR / "Harness" / "perf"+BUDGETS_FILE = PERF_DIR / "budgets.json"+REPLAY_FILE = PERF_DIR / "replay.json"+RUN_TIMEOUT_S = 30 * 60+#: CSV profiler columns, in order of preference.+FRAME_COLUMNS = ("FrameTime",)+GAME_COLUMNS = ("GameThreadTime",)+RENDER_COLUMNS = ("RenderThreadTime",)+GPU_COLUMNS = ("GPUTime", "GPU/Total")+PHYSICS_PREFIXES = ("Physics", "Exclusive/GameThread/Physics", "ChaosPhysics")+++def load_json(path: Path) -> dict:+ return json.loads(path.read_text(encoding="utf-8"))+++# --- quiet hours ---+++def idle_seconds() -> float:+ """Seconds since the last keyboard or mouse input (Windows); infinity elsewhere."""+ if os.name != "nt":+ return math.inf+ import ctypes++ class LastInputInfo(ctypes.Structure):+ _fields_ = [("cbSize", ctypes.c_uint), ("dwTime", ctypes.c_uint)]++ info = LastInputInfo()+ info.cbSize = ctypes.sizeof(info)+ if not ctypes.windll.user32.GetLastInputInfo(ctypes.byref(info)):+ return 0.0+ return (ctypes.windll.kernel32.GetTickCount() - info.dwTime) / 1000.0+++def in_window(now: dt.time, start: str, end: str) -> bool:+ lo = dt.time.fromisoformat(start)+ hi = dt.time.fromisoformat(end)+ return lo <= now < hi if lo <= hi else (now >= lo or now < hi)+++def quiet_reason(+ quiet: Mapping, now: dt.datetime | None = None, idle: float | None = None+) -> str | None:+ """None when a GPU capture may run now, else why not."""+ now = now or dt.datetime.now()+ if not in_window(now.time(), quiet["start"], quiet["end"]):+ return f"outside the nightly window {quiet['start']}-{quiet['end']}"+ idle = idle_seconds() if idle is None else idle+ if idle < float(quiet["idleMinutes"]) * 60:+ need = quiet["idleMinutes"]+ return f"the person used the machine {idle / 60:.1f} min ago (needs {need} min)"+ return None+++# --- CSV and stats ---+++def percentile(values: Sequence[float], q: float) -> float | None:+ if not values:+ return None+ ordered = sorted(values)+ k = (len(ordered) - 1) * q+ lo, hi = math.floor(k), math.ceil(k)+ return ordered[lo] if lo == hi else ordered[lo] + (ordered[hi] - ordered[lo]) * (k - lo)+++def _column(rows: Sequence[Mapping[str, str]], names: Sequence[str]) -> list[float]:+ if not rows:+ return []+ for name in names:+ if name in rows[0]:+ return [float(r[name]) for r in rows if _is_number(r.get(name))]+ return []+++def _is_number(text: str | None) -> bool:+ try:+ float(text or "")+ except ValueError:+ return False+ return True+++def read_csv(path: Path) -> list[dict[str, str]]:+ """Frame rows of an Unreal CSV profile (the trailing metadata rows are dropped)."""+ with path.open(encoding="utf-8", errors="replace", newline="") as handle:+ rows = list(csv.DictReader(handle))+ return [r for r in rows if _is_number(r.get("FrameTime"))]+++def frame_stats(rows: Sequence[Mapping[str, str]]) -> dict:+ frame = _column(rows, FRAME_COLUMNS)+ game = _column(rows, GAME_COLUMNS)+ physics_cols = [c for c in (rows[0] if rows else {}) if c.startswith(PHYSICS_PREFIXES)]+ physics = (+ [sum(float(r[c]) for c in physics_cols if _is_number(r.get(c))) for r in rows]+ if physics_cols+ else []+ )+ mean_ms = sum(frame) / len(frame) if frame else None+ return {+ "frames": len(frame),+ "fpsAvg": round(1000.0 / mean_ms, 3) if mean_ms else None,+ "frameMsAvg": round(mean_ms, 4) if mean_ms else None,+ "frameMsP99": _r(percentile(frame, 0.99)),+ "gameThreadMsAvg": _r(sum(game) / len(game)) if game else None,+ "gameThreadMsP99": _r(percentile(game, 0.99)),+ "renderThreadMsAvg": _r(_mean(_column(rows, RENDER_COLUMNS))),+ "gpuMsAvg": _r(_mean(_column(rows, GPU_COLUMNS))),+ "physicsMsAvg": _r(_mean(physics)),+ }+++def _mean(values: Sequence[float]) -> float | None:+ return sum(values) / len(values) if values else None+++def _r(value: float | None) -> float | None:+ return None if value is None else round(value, 4)+++def check_budgets(stats: Mapping, memory: Mapping, budgets: Mapping, profile: str) -> list[dict]:+ target = budgets["profiles"][profile]+ rows = [+ ("fpsAvg", stats.get("fpsAvg"), ">=", target["fpsAvgMin"]),+ ("frameMsP99", stats.get("frameMsP99"), "<=", target["p99FrameMsMax"]),+ ("gameThreadMsAvg", stats.get("gameThreadMsAvg"), "<=", budgets["gameThreadMsMax"]),+ ("physicsMsAvg", stats.get("physicsMsAvg"), "<=", budgets["physicsMsMax"]),+ ("vramMbPeak", memory.get("vramMbPeak"), "<=", budgets["vramVisibleMbMax"]),+ ("ramMbPeak", memory.get("ramMbPeak"), "<=", budgets["systemRamVisibleMbMax"]),+ ]+ out = []+ for name, value, op, limit in rows:+ if value is None:+ out.append({"budget": name, "value": None, "limit": limit, "status": "not_measured"})+ continue+ ok = value >= limit if op == ">=" else value <= limit+ out.append(+ {+ "budget": name,+ "value": value,+ "limit": limit,+ "op": op,+ "status": "pass" if ok else "fail",+ }+ )+ return out+++#: architecture.md 7 budgets this run does not check, listed in perf.json so a pass is never+#: read as covering them.+UNCHECKED_BUDGETS = (+ "GPU frame split at 1440p (Nanite + base pass, Lumen, shadows, translucency, post + TSR)",+ "bot at most 0.5 ms per server tick (needs VerseBot timing, WP08)",+ "VRAM Panel / Dormant 3 GB / 2 GB and System RAM Dormant 1.5 GB",+ "Dormant CPU, cold start, Dormant to Visible (verse host, WP17)",+ "panel stream and bridge counters (WP16, WP20)",+ "destruction: 400 active debris bodies, 64 fracture events/s (counters, WP06)",+ "network, size and floor (netcode test, package step, probe)",+)+++def run_verdict(+ code: int, stats: Mapping, budget_rows: Sequence[Mapping]+) -> tuple[bool, list[str]]:+ """Pass only when the replay ran, gave frame stats and every budget was measured and met.++ A budget that could not be measured makes the run incomplete, which is not a pass.+ """+ incomplete = []+ if code != 0:+ incomplete.append(f"replay exited {code}")+ if not stats:+ incomplete.append("no CSV profile")+ incomplete += [+ f"{r['budget']} not measured" for r in budget_rows if r["status"] == "not_measured"+ ]+ failed = any(r["status"] == "fail" for r in budget_rows)+ return (not incomplete and not failed), incomplete+++def compare(a: Mapping, b: Mapping, max_rel: float = 0.03) -> dict:+ """A10.5: two runs of the same replay differ by at most ``max_rel`` in fps and p99."""+ out = {"pass": True, "metrics": {}}+ for key in ("fpsAvg", "frameMsP99"):+ va, vb = a["stats"].get(key), b["stats"].get(key)+ if not va or not vb:+ out["metrics"][key] = {"a": va, "b": vb, "relDelta": None}+ out["pass"] = False+ continue+ rel = abs(va - vb) / max(va, vb)+ out["metrics"][key] = {"a": va, "b": vb, "relDelta": round(rel, 5)}+ out["pass"] = out["pass"] and rel <= max_rel+ return out+++# --- memory sampling ---+++def gpu_memory_used_mb(run: Callable[..., common.Completed] = common.run) -> float | None:+ if not shutil.which("nvidia-smi"):+ return None+ result = run(+ ["nvidia-smi", "--query-gpu=memory.used", "--format=csv,noheader,nounits"], capture=True+ )+ try:+ return float(result.stdout.strip().splitlines()[0])+ except (IndexError, ValueError):+ return None+++def process_vram_mb(pid: int, run: Callable[..., common.Completed] = common.run) -> float | None:+ """VRAM of one process from ``nvidia-smi -q -d PIDS``; None when the driver does not say.++ Under the Windows WDDM driver model the per-process figure is often "Not available"; the+ sampler then falls back to whole-GPU use minus the baseline and records that method.+ """+ if not shutil.which("nvidia-smi"):+ return None+ result = run(["nvidia-smi", "-q", "-d", "PIDS"], capture=True)+ return parse_process_vram(result.stdout or "", pid)+++def parse_process_vram(text: str, pid: int) -> float | None:+ current = None+ for raw in text.splitlines():+ line = raw.strip()+ key, _, value = line.partition(":")+ key, value = key.strip().lower(), value.strip()+ if key == "process id":+ current = int(value) if value.isdigit() else None+ elif key == "used gpu memory" and current == pid:+ number = value.split()[0] if value else ""+ try:+ return float(number)+ except ValueError:+ return None+ return None+++def process_ram_mb(pid: int) -> float | None:+ try:+ import psutil+ except ImportError:+ return None+ try:+ return psutil.Process(pid).memory_info().rss / (1024 * 1024)+ except psutil.Error:+ return None+++class Sampler(threading.Thread):+ def __init__(self, pid: int, period_s: float = 2.0) -> None:+ super().__init__(daemon=True)+ self.pid = pid+ self.period = period_s+ self.baseline = gpu_memory_used_mb()+ self.vram_peak: float | None = None+ self.ram_peak: float | None = None+ #: "process" (per-process VRAM) or "device-delta" (whole GPU minus the baseline; other+ #: GPU users such as STT or local models shift it).+ self.vram_method: str | None = None+ self.stop = threading.Event()++ def run(self) -> None:+ while not self.stop.wait(self.period):+ own = process_vram_mb(self.pid)+ if own is not None:+ self.vram_method = "process"+ self.vram_peak = max(self.vram_peak or 0.0, own)+ elif self.vram_method != "process":+ vram = gpu_memory_used_mb()+ if vram is not None and self.baseline is not None:+ self.vram_method = "device-delta"+ self.vram_peak = max(self.vram_peak or 0.0, vram - self.baseline)+ ram = process_ram_mb(self.pid)+ if ram is not None:+ self.ram_peak = max(self.ram_peak or 0.0, ram)+++# --- run ---+++def command_for(+ engine: Path, project: Path, replay: Path, profile: Mapping, shots_dir: Path, log: Path+) -> list[str]:+ return [+ str(common.editor_cmd(engine)),+ str(project),+ load_json(replay)["map"],+ "-game",+ "-d3d12",+ "-windowed",+ f"-ResX={profile['resX']}",+ f"-ResY={profile['resY']}",+ "-WinX=-20000",+ "-WinY=-20000",+ "-unattended",+ "-nosound",+ "-NoP4",+ "-csvGpuStats",+ f"-VerseCapture={replay}",+ f"-VerseCaptureOut={shots_dir}",+ "-VersePerf",+ "-ExecCmds=r.VSync 0,t.MaxFPS 0,r.Streaming.PoolSize 3072",+ f"-abslog={log}",+ ]+++def newest_csv(project_dir: Path, since: float) -> Path | None:+ folder = project_dir / "Saved" / "Profiling" / "CSV"+ found = (+ [p for p in folder.glob("*.csv") if p.stat().st_mtime >= since] if folder.exists() else []+ )+ return max(found, key=lambda p: p.stat().st_mtime) if found else None+++def run_once(out_dir: Path, profile_name: str, budgets: Mapping, worktree: Path) -> dict:+ from scripts.unreal import with_lock++ engine, project = common.engine_root(), common.project_file(worktree)+ profile = budgets["profiles"][profile_name]+ out_dir.mkdir(parents=True, exist_ok=True)+ log = out_dir / "perf.log"+ command = command_for(engine, project, REPLAY_FILE, profile, out_dir, log)+ with with_lock.MachineLock("perf", " ".join(command[:3])):+ started = time.time()+ proc = subprocess.Popen(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) # noqa: S603+ sampler = Sampler(proc.pid)+ sampler.start()+ try:+ code = proc.wait(timeout=RUN_TIMEOUT_S)+ except subprocess.TimeoutExpired:+ proc.kill()+ code = proc.wait()+ sampler.stop.set()+ sampler.join(timeout=5)+ csv_path = newest_csv(project.parent, started)+ stats = frame_stats(read_csv(csv_path)) if csv_path else {}+ memory = {+ "vramMbPeak": _r(sampler.vram_peak),+ "ramMbPeak": _r(sampler.ram_peak),+ "vramMethod": sampler.vram_method,+ }+ budget_rows = check_budgets(stats, memory, budgets, profile_name)+ passed, incomplete = run_verdict(code, stats, budget_rows)+ report = {+ "schema": "verse.perf/1",+ "profile": profile_name,+ "returncode": code,+ "csv": str(csv_path) if csv_path else None,+ "stats": stats,+ "memory": memory,+ "budgets": budget_rows,+ "screenshots": sorted(str(p) for p in out_dir.glob("*.png")),+ "incomplete": incomplete,+ "unchecked": list(UNCHECKED_BUDGETS),+ "pass": passed,+ }+ (out_dir / "perf.json").write_text(json.dumps(report, indent=2), encoding="utf-8")+ return report+++def main(argv: Sequence[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ sub = parser.add_subparsers(dest="cmd", required=True)+ run_p = sub.add_parser("run")+ run_p.add_argument("--profile", default="1440p")+ run_p.add_argument("--runs", type=int, default=1, help="2 also checks run-to-run stability.")+ run_p.add_argument("--force", action="store_true", help="Ignore the quiet hours.")+ run_p.add_argument("--worktree", type=Path, default=common.REPO_ROOT)+ cmp_p = sub.add_parser("compare")+ cmp_p.add_argument("a", type=Path)+ cmp_p.add_argument("b", type=Path)+ parse_p = sub.add_parser("parse")+ parse_p.add_argument("csv", type=Path)+ args = parser.parse_args(argv)+ budgets = load_json(BUDGETS_FILE)++ if args.cmd == "parse":+ print(json.dumps(frame_stats(read_csv(args.csv)), indent=2))+ return 0+ if args.cmd == "compare":+ result = compare(load_json(args.a), load_json(args.b), budgets["stabilityMaxRelDelta"])+ print(json.dumps(result, indent=2))+ return 0 if result["pass"] else 1+ reason = None if args.force else quiet_reason(budgets["quietHours"])+ if reason:+ print(f"perf: skipped, {reason}")+ return 0+ base = (+ args.worktree / "unreal" / "Verse" / "Saved" / "Harness" / "perf" / common.run_stamp()+ ).resolve()+ reports = [+ run_once(base / f"run{k}", args.profile, budgets, args.worktree.resolve())+ for k in range(args.runs)+ ]+ ok = all(r["pass"] for r in reports)+ if len(reports) >= 2:+ stability = compare(reports[0], reports[1], budgets["stabilityMaxRelDelta"])+ (base / "stability.json").write_text(json.dumps(stability, indent=2), encoding="utf-8")+ ok = ok and stability["pass"]+ for k, r in enumerate(reports):+ for row in r["budgets"]:+ print(+ f"run{k} {row['status']:12s} {row['budget']} {row['value']} (limit {row['limit']})"+ )+ print(f"perf: {'OK' if ok else 'FAIL'} ({base})")+ return 0 if ok else 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/unit/unreal_scripts/__init__.py b/tests/unit/unreal_scripts/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tests/unit/unreal_scripts/fixtures/balance_run/fire_audit.log b/tests/unit/unreal_scripts/fixtures/balance_run/fire_audit.lognew file mode 100644index 0000000000..e69de29bb2diff --git a/tests/unit/unreal_scripts/fixtures/balance_run/job0/bouts.jsonl b/tests/unit/unreal_scripts/fixtures/balance_run/job0/bouts.jsonlnew file mode 100644index 0000000000..42f8e8a292--- /dev/null+++ b/tests/unit/unreal_scripts/fixtures/balance_run/job0/bouts.jsonl@@ -0,0 +1,4 @@+{"schema": "verse.bout/1", "pairing": "hard_vs_normal", "match": 0, "bout": 0, "seed": 100, "spawnSideA": 0, "winner": "A", "durationS": 200.0, "matchTimeStartS": 0.0, "kills": [{"t": 10.0, "killer": "A", "cause": "bolt", "headshot": true, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 11.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 12.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 13.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 14.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 15.0, "killer": "A", "cause": "bolt", "headshot": true, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 16.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 17.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 18.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 19.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 20.0, "killer": "A", "cause": "bolt", "headshot": true, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 21.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 22.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 23.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 24.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 40.0, "killer": "B", "cause": "melee", "headshot": false, "wall": false, "rangeM": 1.0, "ttkS": 0.4, "spawnKill": true}, {"t": 41.0, "killer": "B", "cause": "melee", "headshot": false, "wall": false, "rangeM": 1.0, "ttkS": 0.4, "spawnKill": false}, {"t": 42.0, "killer": "B", "cause": "melee", "headshot": false, "wall": false, "rangeM": 1.0, "ttkS": 0.4, "spawnKill": false}], "a": {"kills": 15, "deaths": 3, "shots": 100, "hits": 40, "headshotHits": 0, "timeToContactS": [5.0, 7.0], "bulwarkUses": 0, "breachUses": 0, "reloadsInFight": 0, "fireAudit": {"Visible": 100}, "botMsP99": 0.3, "stuckEvents": 0, "navFailures": 0}, "b": {"kills": 3, "deaths": 15, "shots": 80, "hits": 20, "headshotHits": 0, "timeToContactS": [6.0], "bulwarkUses": 0, "breachUses": 0, "reloadsInFight": 0, "fireAudit": {"Visible": 80}, "botMsP99": 0.3, "stuckEvents": 0, "navFailures": 0}, "adaptiveTrace": []}+{"schema": "verse.bout/1", "pairing": "hard_vs_normal", "match": 0, "bout": 1, "seed": 101, "spawnSideA": 1, "winner": "A", "durationS": 200.0, "matchTimeStartS": 200.0, "kills": [{"t": 10.0, "killer": "A", "cause": "bolt", "headshot": true, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 11.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 12.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 13.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 14.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 15.0, "killer": "A", "cause": "bolt", "headshot": true, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 16.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 17.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 18.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 19.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 20.0, "killer": "A", "cause": "bolt", "headshot": true, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 21.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 22.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 23.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 24.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 40.0, "killer": "B", "cause": "melee", "headshot": false, "wall": false, "rangeM": 1.0, "ttkS": 0.4, "spawnKill": true}, {"t": 41.0, "killer": "B", "cause": "melee", "headshot": false, "wall": false, "rangeM": 1.0, "ttkS": 0.4, "spawnKill": false}, {"t": 42.0, "killer": "B", "cause": "melee", "headshot": false, "wall": false, "rangeM": 1.0, "ttkS": 0.4, "spawnKill": false}, {"t": 43.0, "killer": "B", "cause": "melee", "headshot": false, "wall": false, "rangeM": 1.0, "ttkS": 0.4, "spawnKill": false}, {"t": 44.0, "killer": "B", "cause": "melee", "headshot": false, "wall": false, "rangeM": 1.0, "ttkS": 0.4, "spawnKill": false}], "a": {"kills": 15, "deaths": 5, "shots": 100, "hits": 40, "headshotHits": 0, "timeToContactS": [5.0, 7.0], "bulwarkUses": 0, "breachUses": 0, "reloadsInFight": 0, "fireAudit": {"Visible": 100}, "botMsP99": 0.3, "stuckEvents": 0, "navFailures": 0}, "b": {"kills": 5, "deaths": 15, "shots": 80, "hits": 20, "headshotHits": 0, "timeToContactS": [6.0], "bulwarkUses": 0, "breachUses": 0, "reloadsInFight": 0, "fireAudit": {"Visible": 80}, "botMsP99": 0.3, "stuckEvents": 0, "navFailures": 0}, "adaptiveTrace": []}+{"schema": "verse.bout/1", "pairing": "hard_vs_normal", "match": 0, "bout": 2, "seed": 102, "spawnSideA": 0, "winner": "A", "durationS": 200.0, "matchTimeStartS": 400.0, "kills": [{"t": 10.0, "killer": "A", "cause": "bolt", "headshot": true, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 11.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 12.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 13.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 14.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 15.0, "killer": "A", "cause": "bolt", "headshot": true, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 16.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 17.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 18.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 19.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 20.0, "killer": "A", "cause": "bolt", "headshot": true, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 21.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 22.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 23.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 24.0, "killer": "A", "cause": "bolt", "headshot": false, "wall": false, "rangeM": 12.0, "ttkS": 0.5, "spawnKill": false}, {"t": 40.0, "killer": "B", "cause": "melee", "headshot": false, "wall": false, "rangeM": 1.0, "ttkS": 0.4, "spawnKill": true}, {"t": 41.0, "killer": "B", "cause": "melee", "headshot": false, "wall": false, "rangeM": 1.0, "ttkS": 0.4, "spawnKill": false}], "a": {"kills": 15, "deaths": 2, "shots": 100, "hits": 40, "headshotHits": 0, "timeToContactS": [5.0, 7.0], "bulwarkUses": 0, "breachUses": 0, "reloadsInFight": 0, "fireAudit": {"Visible": 100}, "botMsP99": 0.3, "stuckEvents": 0, "navFailures": 0}, "b": {"kills": 2, "deaths": 15, "shots": 80, "hits": 20, "headshotHits": 0, "timeToContactS": [6.0], "bulwarkUses": 0, "breachUses": 0, "reloadsInFight": 0, "fireAudit": {"Visible": 80}, "botMsP99": 0.3, "stuckEvents": 0, "navFailures": 0}, "adaptiveTrace": []}+{"schema": "verse.bout/1", "pairing": "hard_vs_normal", "match": 0, "bout": 3, "seed": 103, "spawnSideA": 1, "winner": "B", "durationS": 200.0, "matchTimeStartS": 600.0, "kills": [{"t": 40.0, "killer": "B", "cause": "melee", "headshot": false, "wall": false, "rangeM": 1.0, "ttkS": 0.4, "spawnKill": true}, {"t": 41.0, "killer": "B", "cause": "melee", "headshot": false, "wall": false, "rangeM": 1.0, "ttkS": 0.4, "spawnKill": false}, {"t": 42.0, "killer": "B", "cause": "melee", "headshot": false, "wall": false, "rangeM": 1.0, "ttkS": 0.4, "spawnKill": false}, {"t": 43.0, "killer": "B", "cause": "melee", "headshot": false, "wall": false, "rangeM": 1.0, "ttkS": 0.4, "spawnKill": false}, {"t": 44.0, "killer": "B", "cause": "melee", "headshot": false, "wall": false, "rangeM": 1.0, "ttkS": 0.4, "spawnKill": false}], "a": {"kills": 0, "deaths": 5, "shots": 100, "hits": 40, "headshotHits": 0, "timeToContactS": [5.0, 7.0], "bulwarkUses": 0, "breachUses": 0, "reloadsInFight": 0, "fireAudit": {"Visible": 100}, "botMsP99": 0.3, "stuckEvents": 0, "navFailures": 0}, "b": {"kills": 5, "deaths": 0, "shots": 80, "hits": 20, "headshotHits": 0, "timeToContactS": [6.0], "bulwarkUses": 0, "breachUses": 0, "reloadsInFight": 0, "fireAudit": {"Visible": 80}, "botMsP99": 0.3, "stuckEvents": 0, "navFailures": 0}, "adaptiveTrace": []}diff --git a/tests/unit/unreal_scripts/test_balance.py b/tests/unit/unreal_scripts/test_balance.pynew file mode 100644index 0000000000..b910c335a8--- /dev/null+++ b/tests/unit/unreal_scripts/test_balance.py@@ -0,0 +1,570 @@+"""Gate math, planning and seeding of scripts/unreal/balance.py (WP10.5, A10.4)."""++from __future__ import annotations++import json+import math+from pathlib import Path++import pytest++from scripts.unreal import balance++FIXTURE_RUN = Path(__file__).parent / "fixtures" / "balance_run"++[email protected](scope="module")+def cfg():+ return balance.load_config()+++def _hand_wilson(k: int, n: int) -> tuple[float, float]:+ z = 1.959963984540054+ p = k / n+ denom = 1 + z * z / n+ centre = (p + z * z / (2 * n)) / denom+ half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / denom+ return centre - half, centre + half+++def test_wilson_matches_the_hand_formula_and_a_known_value():+ lo, hi = balance.wilson(45, 60)+ assert (lo, hi) == pytest.approx(_hand_wilson(45, 60))+ assert lo == pytest.approx(0.6277, abs=1e-4)+ assert hi == pytest.approx(0.8422, abs=1e-4)+ assert balance.wilson(0, 0) is None+ assert balance.wilson(0, 10)[0] == 0.0+ assert balance.wilson(10, 10)[1] == pytest.approx(1.0)+++def test_trials_for_half_width_gives_267_at_one_half():+ assert balance.trials_for_half_width(0.5) == 267+ assert balance.trials_for_half_width(0.75) == 201+ assert balance.trials_for_half_width(0.9) == 97+++def test_sets_build_the_contract_pairings(cfg):+ ladder = [p.id for p in balance.build_pairings(["ladder"], cfg)]+ assert ladder[:3] == ["hard_vs_normal", "elite_vs_hard", "elite_vs_normal"]+ assert {"normal_vs_normal", "hard_vs_hard", "elite_vs_elite"} <= set(ladder)+ tricks = balance.build_pairings(["tricks"], cfg)+ assert len(tricks) == 17+ assert all(p.id.endswith("_vs_hard") and p.a["tier"] == "hard" for p in tricks)+ elite = [p.id for p in balance.build_pairings(["elite"], cfg)]+ assert "skilled_vs_elite" in elite and "skilled+spray_vs_elite" in elite and len(elite) == 18+ learning = [p.id for p in balance.build_pairings(["learning"], cfg)]+ assert "hard_vs_repeek" in learning and "hard-nolearn_vs_repeek" in learning+ assert "hard_vs_repeek.reset" in learning+ allp = [p.id for p in balance.build_pairings(["all"], cfg)]+ assert len(allp) == len(set(allp))+ assert "wall_opened_unseen" in allp and "destruction_storm" in allp+ assert "adaptive_vs_skilled" in allp and "average_vs_normal" in allp+++def test_trick_filter_limits_the_queue_subset(cfg):+ picked = balance.build_pairings(["tricks"], cfg, ["spray", "camper"])+ assert [p.id for p in picked] == ["spray_vs_hard", "camper_vs_hard"]+++def test_units_are_seeded_the_same_for_any_job_count(cfg):+ pairings = balance.build_pairings(["ladder"], cfg)+ units = balance.plan_units(pairings, 25, run_seed=7, bouts_per_match=10)+ assert sum(u.bouts for u in units if u.pairing.id == "hard_vs_normal") == 25+ seeds = {(u.pairing.id, u.match): u.seed for u in units}+ for jobs in (1, 2, 4):+ shards = balance.shard_units(units, jobs)+ assert len(shards) == jobs+ flat = {(u.pairing.id, u.match): u.seed for s in shards for u in s}+ assert flat == seeds+ other = balance.plan_units(pairings, 25, run_seed=8, bouts_per_match=10)+ assert [u.seed for u in other] != [u.seed for u in units]+++def test_jobs_are_capped_at_the_machine_limit(cfg):+ units = balance.plan_units(balance.build_pairings(["all"], cfg), 10, 1, 10)+ assert len(balance.shard_units(units, 16)) == 4+++def test_reset_pairing_stays_in_one_process(cfg):+ units = balance.plan_units(balance.build_pairings(["learning"], cfg), 20, 1, 10)+ shards = balance.shard_units(units, 4)+ holders = [k for k, s in enumerate(shards) if any(u.pairing.id.endswith(".reset") for u in s)]+ assert len(holders) == 1+ reset = [u for u in shards[holders[0]] if u.pairing.id.endswith(".reset")]+ assert [u.match for u in reset] == [0, 1]+++def test_scenario_documents_validate_against_the_schema(cfg, tmp_path):+ units = balance.plan_units(balance.build_pairings(["all"], cfg), 4, 1, 10)+ for k, shard in enumerate(balance.shard_units(units, 4)):+ doc = balance.scenario_document("r", k, shard, cfg, tmp_path, {"hard": {}}, True)+ assert balance.validate(doc, "scenario.schema.json") == []+++def test_command_is_the_dedicated_server_of_bot_md_11_1(tmp_path):+ cmd = balance.command_for(+ Path("E"), Path("P.uproject"), "/Game/M", tmp_path / "s.json", tmp_path / "l.log"+ )+ for flag in ("-server", "-nullrhi", "-nosound", "-unattended", "-benchmark", "-fps=60"):+ assert flag in cmd+ assert any(c.startswith("-VerseHarness=") for c in cmd)+++def test_fixture_bouts_give_the_hand_calculated_metrics(cfg):+ bouts, _speed, _log, _out = balance.collect(FIXTURE_RUN)+ pairing = next(p for p in balance.build_pairings(["ladder"], cfg) if p.id == "hard_vs_normal")+ (m,) = balance.aggregate([pairing], bouts)+ assert m["bouts"] == 4 and m["kills"] == 60+ assert m["boutWinRateA"] == 0.75+ assert m["killShareA"] == 0.75+ assert m["killShareA95"] == pytest.approx(list(_hand_wilson(45, 60)), abs=1e-6)+ assert m["spawnSide0WinRate"] == 0.75+ assert m["kd"] == {"a": 3.0, "b": pytest.approx(1 / 3, abs=1e-6)}+ assert m["accuracy"] == {"a": 0.4, "b": 0.25}+ assert m["headshotShare"]["a"] == pytest.approx(9 / 45)+ assert m["knifeShare"]["b"] == 1.0+ assert m["spawnKills"] == 4+ assert m["timeToContactS"] == {"a": 6.0, "b": 6.0}+ assert m["engagementRangeHist"]["10-20"] == 45 and m["engagementRangeHist"]["0-5"] == 15+ # First half of the 800 s match: A 30 of 38 kills; second half: A 15 of 22.+ assert m["learningDelta"] == pytest.approx(15 / 22 - 30 / 38, abs=1e-6)+ assert m["fireAudit"]["a"]["Unclassified"] == 0+++def test_gates_on_the_fixture_equal_the_hand_calculation(cfg, tmp_path):+ bouts, _speed, _log, _out = balance.collect(FIXTURE_RUN)+ metrics = balance.aggregate(balance.build_pairings(["ladder"], cfg), bouts)+ gates = {g.id: g for g in balance.evaluate_gates(metrics, cfg, static_root=tmp_path)}+ assert gates["BG1"].status == "pass"+ assert gates["BG1"].values == {+ "boutWinRateA": 0.75,+ "killShareLower": pytest.approx(0.6277, abs=1e-4),+ }+ assert gates["BG2"].status == "not_run"+ assert gates["F4"].status == "pass" and gates["F4"].values["unclassified"] == 0+ assert gates["BG12"].status == "pass" and gates["BG12"].values["contactMedianS"] == 6.0+ assert gates["F1"].status == "pass" and gates["F6"].status == "pass"+ # F3 comes from an automation run; without it BG11 is not a pass.+ assert gates["BG11"].status == "not_run" and "F3" in gates["BG11"].detail+ checks = {"F3": {"status": "pass", "detail": "20 seeds"}}+ gates = {+ g.id: g for g in balance.evaluate_gates(metrics, cfg, static_root=tmp_path, checks=checks)+ }+ assert gates["BG11"].status == "pass"+++def _m(pid, **kw):+ base = {+ "id": pid,+ "bouts": 100,+ "kills": 400,+ "shots": 1000,+ "boutWinRateA": 0.5,+ "killShareA": 0.5,+ "killShareA95": [0.45, 0.55],+ "spawnSide0": [50, 100],+ "learningDelta": 0.0,+ "adaptiveTrace": [],+ "killWindowB": [0, 0],+ "resetWindow": {},+ "fireAudit": {},+ "timeToContactSamples": [10.0],+ "matchTimeS": 6000.0,+ "stuckEvents": 0,+ "botMsP99": None,+ "bearingWindows": [],+ "f7Violations": None,+ }+ base.update(kw)+ return base+++def test_bg1_fails_on_the_lower_bound(cfg, tmp_path):+ metrics = [_m("hard_vs_normal", boutWinRateA=0.8, killShareA95=[0.55, 0.65])]+ gate = {g.id: g for g in balance.evaluate_gates(metrics, cfg, static_root=tmp_path)}["BG1"]+ assert gate.status == "fail" and "lower" in gate.detail+++def test_bg4_and_bg5_use_the_trick_bounds(cfg, tmp_path):+ metrics = [+ _m("spray_vs_hard", boutWinRateA=0.5, killShareA95=[0.4, 0.55]),+ _m("camper_vs_hard", boutWinRateA=0.52, killShareA95=[0.4, 0.5]),+ _m("skilled_vs_elite", killShareA=0.40),+ _m("skilled+spray_vs_elite", killShareA=0.46),+ ]+ gates = {g.id: g for g in balance.evaluate_gates(metrics, cfg, static_root=tmp_path)}+ assert gates["BG4"].status == "fail" and "camper_vs_hard boutWinRateA" in gates["BG4"].detail+ assert gates["BG5"].status == "fail"+ metrics[3]["killShareA"] = 0.45+ gates = {g.id: g for g in balance.evaluate_gates(metrics, cfg, static_root=tmp_path)}+ assert gates["BG5"].status == "pass"+++def test_bg6_bg7_bands(cfg, tmp_path):+ metrics = [+ _m("skilled_vs_elite", killShareA=0.46),+ _m("skilled_vs_normal", killShareA=0.70),+ _m("average_vs_normal", killShareA=0.66),+ ]+ gates = {g.id: g for g in balance.evaluate_gates(metrics, cfg, static_root=tmp_path)}+ assert gates["BG6"].status == "pass"+ assert gates["BG7"].status == "fail"+++def test_bg8_bg9_bg10(cfg, tmp_path):+ metrics = []+ for opp in ("repeek", "watcher", "camper"):+ metrics.append(_m(f"hard_vs_{opp}", learningDelta=0.06, killShareA=0.60))+ metrics.append(_m(f"hard-nolearn_vs_{opp}", killShareA=0.56))+ metrics.append(_m("hard_vs_repeek.reset", resetWindow={"0": [30, 50], "1": [29, 50]}))+ metrics.append(_m("adaptive_vs_skilled", killWindowB=[15, 30], adaptiveTrace=[0.5, 0.53, 0.55]))+ metrics.append(_m("adaptive_vs_average", killWindowB=[11, 30], adaptiveTrace=[0.5, 0.56]))+ gates = {g.id: g for g in balance.evaluate_gates(metrics, cfg, static_root=tmp_path)}+ assert gates["BG8"].status == "pass"+ assert gates["BG9"].status == "pass"+ assert gates["BG10"].status == "fail"+ assert "adaptive_vs_average person kill share" in gates["BG10"].detail+ assert "largest step 0.060" in gates["BG10"].detail+++def test_bg3_needs_the_mirrors_and_spawn_side(cfg, tmp_path):+ metrics = [+ _m("elite_vs_normal", boutWinRateA=0.92, killShareA=0.8),+ _m("normal_vs_normal", spawnSide0=[30, 50]),+ _m("hard_vs_hard", spawnSide0=[30, 50]),+ _m("elite_vs_elite", spawnSide0=[30, 50]),+ ]+ gates = {g.id: g for g in balance.evaluate_gates(metrics, cfg, static_root=tmp_path)}+ assert gates["BG3"].status == "fail" and "spawn side" in gates["BG3"].detail+++def test_null_brain_runs_report_not_run_instead_of_fail(cfg, tmp_path):+ metrics = [+ _m(+ "hard_vs_normal",+ kills=0,+ shots=0,+ boutWinRateA=0.0,+ killShareA=None,+ killShareA95=None,+ timeToContactSamples=[],+ )+ ]+ gates = {g.id: g for g in balance.evaluate_gates(metrics, cfg, static_root=tmp_path)}+ assert gates["BG1"].status == "not_run" and "null brain" in gates["BG1"].detail+ assert gates["BG12"].status == "not_run"+++def test_f4_f5_f7_l1(cfg, tmp_path):+ windows = [[0.0, 5.0, 100.0]] * 1000 + [[0.0, 100.0, 5.0]] * 1000+ metrics = [+ _m(+ "hard_vs_normal",+ fireAudit={"a": {"Unclassified": 2, "shots": 10}},+ bearingWindows=windows,+ ),+ _m("wall_opened_unseen", f7Violations=1),+ ]+ gates = {+ g.id: g+ for g in balance.evaluate_gates(+ metrics,+ cfg,+ static_root=tmp_path,+ l1_findings=["x: holds match-memory field"],+ nightly=True,+ )+ }+ assert gates["F4"].status == "fail"+ assert gates["F5"].status == "pass" and gates["F5"].values["excess"] == 0.0+ assert gates["F7"].status == "fail"+ assert gates["L1"].status == "fail"+ assert gates["BG11"].status == "fail"+++def test_f5_statistic_is_true_minus_decoy():+ assert balance.f5_statistic([[10, 12, 200], [10, 200, 200], [0, 359, 180]]) == pytest.approx(+ 2 / 3+ )+ assert balance.f5_statistic([]) is None+++def test_l1_scan_finds_match_memory_in_new_files(tmp_path):+ old = tmp_path / "old.json"+ old.write_text("PeekHabits", encoding="utf-8")+ import os+ import time++ os.utime(old, (time.time() - 3600, time.time() - 3600))+ since = time.time() - 60+ (tmp_path / "SaveGames").mkdir()+ (tmp_path / "SaveGames" / "slot.sav").write_bytes(b"..PositionHeatmap..")+ hits = balance.l1_scan(+ [tmp_path], ["PositionHeatmap", "PeekHabits"], since, ['{"t":"duel.result"}']+ )+ assert len(hits) == 1 and "PositionHeatmap" in hits[0]+ # The run's own job folder is exempt; a bot log elsewhere is not.+ run = tmp_path / "Harness" / "balance" / "r1" / "job0"+ run.mkdir(parents=True)+ (run / "job0.log").write_text("PeekHabits", encoding="utf-8")+ (run / "bouts.jsonl").write_text("PeekHabits", encoding="utf-8")+ (tmp_path / "Bot").mkdir()+ (tmp_path / "Bot" / "bot.log").write_text("PeekHabits", encoding="utf-8")+ hits = balance.l1_scan(+ [tmp_path], ["PeekHabits"], since, exclude=[tmp_path / "Harness" / "balance" / "r1"]+ )+ assert len(hits) == 1 and "bot.log" in hits[0]+ assert balance.l1_scan([], ["PeekHabits"], since, ['{"PeekHabits":1}'])+++def test_fire_audit_lines_are_attributed_by_server_window():+ text = (+ "x [VerseFireAudit] ServerTimeMs=1500 Mode=Visible bTargetVisible=1\n"+ '[VerseFireAudit] {"serverTimeMs": 2500, "mode": "EVerseBotFireMode::WallShot"}\n'+ "[VerseFireAudit] ServerTimeMs=2600 Mode=Guess\n"+ "[VerseFireAudit] ServerTimeMs=9000 Mode=Visible\n"+ "[VerseFireAudit] Mode=Visible\nnoise\n"+ )+ shots, unparsed = balance.parse_fire_audit(text)+ assert shots == [+ (1500.0, "Visible"),+ (2500.0, "WallShot"),+ (2600.0, "Unclassified"),+ (9000.0, "Visible"),+ ]+ assert unparsed == 1+ bouts = [+ {"bout": 0, "serverStartMs": 1000, "serverEndMs": 2000, "a": {}, "b": {}},+ {"bout": 1, "serverStartMs": 2000, "serverEndMs": 3000, "a": {}, "b": {}},+ ]+ assert balance.attribute_fire_audit(bouts, shots) == 1+ assert bouts[0]["fireAudit"] == {"Visible": 1}+ assert bouts[1]["fireAudit"] == {"WallShot": 1, "Unclassified": 1}+++def test_f4_counts_window_attributed_shots_against_bot_shots(cfg):+ pairing = next(p for p in balance.build_pairings(["ladder"], cfg) if p.id == "hard_vs_normal")+ bout = {+ "pairing": pairing.id,+ "match": 0,+ "bout": 0,+ "spawnSideA": 0,+ "winner": "none",+ "durationS": 10.0,+ "kills": [],+ "a": {"shots": 3},+ "b": {"shots": 2},+ "fireAudit": {"Visible": 4},+ }+ (m,) = balance.aggregate([pairing], [bout])+ assert m["fireAudit"]["bots"] == {+ "Visible": 4,+ "Suppression": 0,+ "Prefire": 0,+ "WallShot": 0,+ "Unclassified": 1,+ "shots": 5,+ }+ assert balance.gate_f4({m["id"]: m}).status == "fail"+ bout["fireAudit"] = {"Visible": 4, "Prefire": 1}+ (m,) = balance.aggregate([pairing], [bout])+ assert balance.gate_f4({m["id"]: m}).status == "pass"+ assert balance.gate_f4({m["id"]: m}, unattributed=2).status == "fail"+++def test_f4_with_no_bot_shot_is_not_run():+ m = _m("hard_vs_normal", fireAudit={"bots": {"Unclassified": 0, "shots": 0}})+ gate = balance.gate_f4({"hard_vs_normal": m})+ assert gate.status == "not_run" and "null brain" in gate.detail+++def test_bg11_passes_only_when_every_part_passed():+ def parts(**states):+ return {g: balance.Gate(g, s, "") for g, s in states.items()}++ assert balance.gate_bg11(parts(F3="pass", F4="pass"), False).status == "pass"+ assert balance.gate_bg11(parts(F3="not_run", F4="pass"), False).status == "not_run"+ assert balance.gate_bg11(parts(F3="fail", F4="not_run"), False).status == "fail"+ nightly = parts(F3="pass", F4="pass", F5="pass", F7="not_run", L1="pass")+ gate = balance.gate_bg11(nightly, True)+ assert gate.status == "not_run" and "F7" in gate.detail+++def _job(run: Path, k: int, units: list[dict], bouts: list[dict], speed: dict | None) -> None:+ job = run / f"job{k}"+ job.mkdir(parents=True)+ (job / "scenario.json").write_text(json.dumps({"units": units}), encoding="utf-8")+ (job / "bouts.jsonl").write_text("".join(json.dumps(b) + "\n" for b in bouts), encoding="utf-8")+ if speed is not None:+ (job / "speed.json").write_text(json.dumps(speed), encoding="utf-8")+++def test_completeness_names_crashed_jobs_guards_and_short_units(tmp_path):+ run = tmp_path / "run"+ full = {"pairing": "p", "match": 0, "bouts": 2}+ short = {"pairing": "q", "match": 1, "bouts": 3}+ _job(run, 0, [full], [{"pairing": "p", "match": 0}] * 2, {"job": 0, "end": "all units played"})+ _job(+ run,+ 1,+ [short],+ [{"pairing": "q", "match": 1}],+ {"job": 1, "end": "wall-clock guard reached"},+ )+ bouts = [{"pairing": "p", "match": 0}] * 2 + [{"pairing": "q", "match": 1}]+ speed = [json.loads((run / f"job{k}" / "speed.json").read_text()) for k in (0, 1)]+ results = [+ {"job": 0, "returncode": 0, "log": "l0"},+ {"job": 1, "returncode": 3, "log": "l1"},+ ]+ problems = balance.completeness(run, bouts, speed, results)+ assert any("job 1 exited 3" in p for p in problems)+ assert any("wall-clock guard" in p for p in problems)+ assert any("q#1: 1 of 3 bouts" in p for p in problems)+ assert not any("p#0" in p for p in problems)+++def test_from_bouts_fails_a_short_run(tmp_path):+ run = tmp_path / "run"+ lines = (FIXTURE_RUN / "job0" / "bouts.jsonl").read_text(encoding="utf-8").splitlines()+ unit = {"pairing": "hard_vs_normal", "match": 0, "bouts": len(lines) + 1}+ _job(run, 0, [unit], [json.loads(x) for x in lines], {"job": 0, "end": "all units played"})+ code = balance.main(["--from-bouts", str(run), "--gates", "BG1", "--worktree", str(tmp_path)])+ assert code == 1+ report = json.loads((run / "report.json").read_text(encoding="utf-8"))+ assert report["incomplete"] == [+ f"unit hard_vs_normal#0: {len(lines)} of {len(lines) + 1} bouts"+ ]+++def test_checks_from_automation_reports(tmp_path):+ report = tmp_path / "Automation" / "20261102-1"+ report.mkdir(parents=True)+ tests = [+ {"fullTestPath": "Verse.Bot.Fairness.Counterfactual.Seed1", "state": "Success"},+ {"fullTestPath": "Verse.Bot.Fairness.Counterfactual.Seed2", "state": "Fail"},+ {"fullTestPath": "Verse.Combat.Perception.F2.Opaque", "state": "Success"},+ {"fullTestPath": "Verse.Harness.World.TierAndPatch", "state": "Success"},+ ]+ (report / "index.json").write_text(json.dumps({"tests": tests}), encoding="utf-8-sig")+ checks = balance.checks_from_automation(tmp_path / "Automation")+ assert checks["F3"]["status"] == "fail" and "Seed2" in checks["F3"]["detail"]+ assert checks["F2"]["status"] == "pass"+ assert "BR1" not in checks+ assert balance.checks_from_automation(tmp_path / "missing") == {}+++def test_l1_pairing_is_one_30_minute_match_without_a_kill_cap(cfg):+ (pairing,) = [p for p in balance.build_pairings(["fairness"], cfg) if p.id.endswith(".l1")]+ (unit,) = balance.plan_units([pairing], 200, 1, 10)+ doc = unit.to_json(cfg, None)+ assert doc["matchTimeLimitS"] == 1800.0 and doc["bouts"] == 1+ assert doc["killsToWin"] >= 1_000_000+++def test_queue_bout_count_matches_the_workflow():+ workflow = (+ Path(__file__).resolve().parents[3] / ".github" / "workflows" / "unreal-gauntlet.yml"+ ).read_text(encoding="utf-8")+ assert f"--bouts {balance.QUEUE_BOUTS} " in workflow+ table = json.loads(balance.BOUT_TABLE_FILE.read_text(encoding="utf-8"))+ assert table["queueBouts"] == balance.QUEUE_BOUTS+ assert table["provisional"] and all(row["wallHours"] is None for row in table["gates"].values())+++def test_report_matches_the_balance_schema(cfg, tmp_path):+ bouts, _speed, log, _out = balance.collect(FIXTURE_RUN)+ metrics = balance.aggregate(balance.build_pairings(["ladder"], cfg), bouts)+ gates = balance.evaluate_gates(metrics, cfg, static_root=tmp_path)+ report = balance.build_report(+ "r",+ 1,+ ["ladder"],+ metrics,+ gates,+ bouts=4,+ jobs=1,+ patch=None,+ speed=None,+ fire_audit_log=log,+ )+ assert balance.validate(report, "balance.schema.json") == []+ json.dumps(report)+++def test_from_bouts_cli_writes_a_report_and_passes(tmp_path):+ run = tmp_path / "run"+ (run / "job0").mkdir(parents=True)+ (run / "job0" / "bouts.jsonl").write_text(+ (FIXTURE_RUN / "job0" / "bouts.jsonl").read_text(encoding="utf-8"), encoding="utf-8"+ )+ code = balance.main(+ ["--from-bouts", str(run), "--gates", "BG1,F4", "--worktree", str(tmp_path)]+ )+ assert code == 0+ report = json.loads((run / "report.json").read_text(encoding="utf-8"))+ assert [g["id"] for g in report["gates"]] == ["BG1", "F4"]+++def test_speed_summary_and_bout_table(cfg):+ speed = balance.speed_summary(+ [+ {"simS": 2400, "wallS": 100, "startupS": 30, "peakRamMb": 2000},+ {"simS": 2000, "wallS": 100},+ ]+ )+ assert speed["xRealTimePerProcess"] == 20.0 and speed["meetsTarget"]+ table = balance.bout_table(+ speed,+ kills_per_bout=22,+ bout_sim_s=240,+ jobs=4,+ pairings_per_gate=balance.pairings_per_gate(cfg),+ )+ assert table["gates"]["BG4"]["boutsPerPairing"] == 267+ assert table["gates"]["BG6"]["boutsPerPairing"] == math.ceil(257 / 22)+ assert table["fullWidthQueueBouts"] == 267+ assert table["queueBouts"] == balance.QUEUE_BOUTS+ assert table["queueHalfWidth"]["boutShare"] == pytest.approx(0.148, abs=0.002)+ assert table["gates"]["BG1"]["wallHours"] is not None and table["provisional"] is None+ rough = balance.bout_table(speed, provisional="null brain")+ assert rough["provisional"] == "null brain"+ assert all(row["wallHours"] is None for row in rough["gates"].values())+ assert balance.speed_summary([]) is None+++def test_run_jobs_writes_scenarios_and_launches_under_the_lock(cfg, tmp_path):+ held = []++ class Lock:+ def __init__(self, label, command):+ held.append(label)++ def __enter__(self):+ return self++ def __exit__(self, *exc):+ held.append("released")++ class Proc:+ def wait(self, timeout=None):+ return 0++ launched = []+ units = balance.plan_units(balance.build_pairings(["ladder"], cfg), 2, 1, 10)+ shards = balance.shard_units(units, 2)+ result = balance.run_jobs(+ shards,+ cfg,+ tmp_path,+ "r",+ patch=None,+ trace_bearing=False,+ engine=Path("E"),+ project=Path("P"),+ launcher=lambda cmd, log: launched.append(cmd) or Proc(),+ lock_factory=Lock,+ )+ assert held == ["balance", "released"]+ assert len(launched) == 2 and all(r["returncode"] == 0 for r in result)+ assert (tmp_path / "job0" / "scenario.json").exists()diff --git a/tests/unit/unreal_scripts/test_static_lane.py b/tests/unit/unreal_scripts/test_static_lane.pynew file mode 100644index 0000000000..0a7a01ee0c--- /dev/null+++ b/tests/unit/unreal_scripts/test_static_lane.py@@ -0,0 +1,315 @@+"""A10.1 and A10.2: the unreal-static checks fail each planted case; workflows are fork-safe."""++from __future__ import annotations++import json+import subprocess+from pathlib import Path++import pytest+import yaml++from scripts.unreal import check_build_dag, check_forbidden_names, check_lfs++REPO = Path(__file__).resolve().parents[3]+WORKFLOWS = REPO / ".github" / "workflows"+UNREAL_WORKFLOWS = (+ "unreal-static.yml",+ "unreal-build.yml",+ "unreal-gauntlet.yml",+ "unreal-perf.yml",+)+#: A made-up word that is only ever forbidden by the test's own hash list.+PLANTED = "zorblaxion"+++def _git(cwd: Path, *args: str, data: bytes | None = None) -> str:+ return subprocess.run(+ ["git", *args], cwd=cwd, input=data, capture_output=True, check=True+ ).stdout.decode()+++def repo(tmp_path):+ _git(tmp_path, "init", "-q", "-b", "main")+ _git(tmp_path, "config", "user.email", "[email protected]")+ _git(tmp_path, "config", "user.name", "ci")+ (tmp_path / "unreal" / "Verse").mkdir(parents=True)+ (tmp_path / "unreal" / "Verse" / ".gitattributes").write_text(+ "*.uasset filter=lfs diff=lfs merge=lfs -text\n"+ "*.umap filter=lfs diff=lfs merge=lfs -text\n",+ encoding="utf-8",+ )+ (tmp_path / "unreal" / "Verse" / "README.txt").write_text("base\n", encoding="utf-8")+ _git(tmp_path, "add", "-A")+ _git(tmp_path, "commit", "-q", "-m", "base")+ return tmp_path+++def _pointer(oid: str, size: int) -> bytes:+ return f"version https://git-lfs.github.com/spec/v1\noid sha256:{oid}\nsize {size}\n".encode()+++def _commit(repo: Path, rel: str, data: bytes) -> None:+ path = repo / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ # Write the blob as-is (no LFS filter in the test repo): -c filter.lfs.* off.+ path.write_bytes(data)+ _git(+ repo,+ "-c",+ "filter.lfs.process=",+ "-c",+ "filter.lfs.clean=cat",+ "-c",+ "filter.lfs.required=false",+ "add",+ rel,+ )+ _git(repo, "commit", "-q", "-m", f"add {rel}")+++# --- forbidden names ---+++def test_a_planted_name_fails_through_a_test_only_hash(tmp_path):+ hash_file = tmp_path / "planted.sha256"+ hash_file.write_text("\n".join(sorted(check_forbidden_names.entry_hashes(PLANTED))) + "\n")+ hashes = check_forbidden_names.load_hashes(hash_file)+ assert check_forbidden_names.scan_text(f"class AZorblaxionRifle; // {PLANTED}", hashes)+ assert check_forbidden_names.scan_text("UVerseBalanceGauntletController", hashes) == []+ # The real list never contains the planted word.+ assert not check_forbidden_names.scan_text(PLANTED, check_forbidden_names.load_hashes())+++def test_forbidden_names_cli_takes_an_extra_hash_file(tmp_path, monkeypatch, capsys):+ hash_file = tmp_path / "planted.sha256"+ hash_file.write_text("\n".join(sorted(check_forbidden_names.entry_hashes(PLANTED))) + "\n")+ target = REPO / "unreal" / "Verse" / "Harness" / "schema" / "bout.schema.json"+ rel = target.relative_to(REPO).as_posix()+ assert check_forbidden_names.main(["--hash-file", str(hash_file), rel]) == 0+ monkeypatch.setattr(check_forbidden_names, "REPO_ROOT", tmp_path)+ (tmp_path / "unreal").mkdir()+ (tmp_path / "unreal" / "x.cpp").write_text(f"// the {PLANTED} carbine\n", encoding="utf-8")+ assert check_forbidden_names.main(["--hash-file", str(hash_file), "unreal/x.cpp"]) == 1+ assert "forbidden name" in capsys.readouterr().out+++ "folder", ["Renders", "renders", "Screenshots", "Evidence", "models", "Build"]+)+def test_banned_folder_names_fail_in_any_case(folder):+ found = check_forbidden_names.scan_folders([f"unreal/Verse/Content/{folder}/T_A.uasset"])+ assert found and folder in found[0]+++def test_the_engine_build_folder_is_the_one_exception():+ assert check_forbidden_names.scan_folders(["unreal/Verse/Build/Windows/Verse.ico"]) == []+ assert check_forbidden_names.scan_folders(["unreal/Verse/Build/Renders/x.png"])+ assert check_forbidden_names.scan_folders(["dodaios/build/x.py"]) == []+++def test_engine_sample_content_fails():+ assert check_forbidden_names.scan_folders(["unreal/Verse/Content/StarterContent/a.uasset"])+ assert check_forbidden_names.scan_folders(+ ["unreal/Verse/Content/Chars/SKM_Manny_Simple.uasset"]+ )+++# --- LFS ---+++def test_a_non_pointer_uasset_fails(repo):+ _commit(repo, "unreal/Verse/Content/Verse/A.uasset", b"\x00\x01binary uasset content")+ errors, _warnings, pointers = check_lfs.check_paths(+ ["unreal/Verse/Content/Verse/A.uasset"], cwd=repo+ )+ assert errors and "not as a Git LFS pointer" in errors[0]+ assert pointers == []+++def test_a_51_mb_lfs_object_fails_and_21_mb_warns(repo):+ _commit(repo, "unreal/Verse/Content/Big.uasset", _pointer("a" * 64, 51 * 1024 * 1024))+ _commit(repo, "unreal/Verse/Content/Mid.uasset", _pointer("b" * 64, 21 * 1024 * 1024))+ errors, warnings, pointers = check_lfs.check_paths(+ ["unreal/Verse/Content/Big.uasset", "unreal/Verse/Content/Mid.uasset"], cwd=repo+ )+ assert len(pointers) == 2+ assert any("Big.uasset" in e and "50 MB" in e for e in errors)+ assert any("Mid.uasset" in w for w in warnings)+ assert not any("Mid.uasset" in e for e in errors)+++def test_a_big_plain_file_fails(repo):+ _commit(repo, "unreal/Verse/Data/huge.json", b"0" * (6 * 1024 * 1024))+ errors, _w, _p = check_lfs.check_paths(["unreal/Verse/Data/huge.json"], cwd=repo)+ assert errors and "5 MB" in errors[0]+++def test_pr_growth_over_200_mb_needs_approval():+ pointers = [check_lfs.Pointer(f"p{i}", f"{i:064x}", 45 * 1024 * 1024) for i in range(5)]+ assert check_lfs.growth_errors(pointers, env={})+ assert check_lfs.growth_errors(pointers, env={check_lfs.GROWTH_ENV: "1"}) == []+++def test_a_pointer_whose_object_is_missing_on_the_remote_fails():+ present, missing = "c" * 64, "d" * 64+ seen = {}++ def fetch(url, body, headers):+ seen["url"] = url+ objs = json.loads(body)["objects"]+ return {+ "objects": [+ {"oid": o["oid"], "size": o["size"], "actions": {"download": {}}}+ if o["oid"] == present+ else {+ "oid": o["oid"],+ "size": o["size"],+ "error": {"code": 404, "message": "Object does not exist"},+ }+ for o in objs+ ]+ }++ pointers = [+ check_lfs.Pointer("a.uasset", present, 10),+ check_lfs.Pointer("b.uasset", missing, 10),+ ]+ errors = check_lfs.missing_on_remote(+ pointers, "https://github.com/Dodaios/Dodaios.git", fetch=fetch+ )+ assert len(errors) == 1 and "b.uasset" in errors[0] and "404" in errors[0]+ assert seen["url"] == "https://github.com/Dodaios/Dodaios.git/info/lfs/objects/batch"+++def test_batch_url_forms():+ assert (+ check_lfs.batch_url("[email protected]:Dodaios/Dodaios.git")+ == "https://github.com/Dodaios/Dodaios.git/info/lfs/objects/batch"+ )+ assert (+ check_lfs.batch_url("https://[email protected]/Dodaios/Dodaios")+ == "https://github.com/Dodaios/Dodaios.git/info/lfs/objects/batch"+ )+++def test_an_unreachable_remote_fails_closed():+ def fetch(url, body, headers):+ raise OSError("offline")++ errors = check_lfs.missing_on_remote(+ [check_lfs.Pointer("a", "e" * 64, 1)], "https://x/y", fetch=fetch+ )+ assert errors and "unreachable" in errors[0]+++# --- Build.cs DAG ---+++def test_a_new_build_cs_edge_fails(tmp_path):+ source = REPO / "unreal" / "Verse" / "Source"+ copy = tmp_path / "Source"+ for path in source.rglob("*.Build.cs"):+ target = copy / path.relative_to(source)+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_text(path.read_text(encoding="utf-8"), encoding="utf-8")+ assert check_build_dag.main(["--source", str(copy)]) == 0+ gore = copy / "VerseGore" / "VerseGore.Build.cs"+ text = gore.read_text(encoding="utf-8")+ gore.write_text(text.replace('"VerseCore"', '"VerseCore", "VerseCombat"', 1), encoding="utf-8")+ assert check_build_dag.main(["--source", str(copy)]) == 1+++# --- workflows (A10.2) ---+++def _load(name: str) -> dict:+ return yaml.safe_load((WORKFLOWS / name).read_text(encoding="utf-8"))+++def _triggers(workflow: dict) -> dict:+ on = workflow.get("on", workflow.get(True))+ if isinstance(on, str):+ return {on: None}+ if isinstance(on, list):+ return {k: None for k in on}+ return on or {}+++FORK_GUARD = "github.event.pull_request.head.repo.full_name == github.repository"+++def fork_findings(name: str, workflow: dict) -> list[str]:+ """Self-hosted jobs reachable from a fork pull request."""+ triggers = _triggers(workflow)+ findings = []+ if "pull_request_target" in triggers:+ findings.append(f"{name}: pull_request_target is never allowed on an Unreal lane")+ for job_id, job in workflow.get("jobs", {}).items():+ runs_on = job.get("runs-on", [])+ labels = [runs_on] if isinstance(runs_on, str) else list(runs_on)+ if "self-hosted" not in labels:+ continue+ if "pull_request" in triggers and FORK_GUARD not in str(job.get("if", "")):+ findings.append(f"{name}/{job_id}: self-hosted job runs on fork pull requests")+ return findings++[email protected]("name", UNREAL_WORKFLOWS)+def test_no_self_hosted_job_runs_for_a_fork_pull_request(name):+ assert fork_findings(name, _load(name)) == []+++def test_the_fork_check_catches_an_unguarded_job():+ bad = {True: {"pull_request": {}}, "jobs": {"b": {"runs-on": ["self-hosted", "windows"]}}}+ assert fork_findings("bad.yml", bad)+ target = {True: {"pull_request_target": {}}, "jobs": {}}+ assert fork_findings("t.yml", target)++[email protected]("name", UNREAL_WORKFLOWS)+def test_unreal_workflows_follow_the_policy(name):+ workflow = _load(name)+ assert "permissions" in workflow+ assert workflow["permissions"] == {"contents": "read"}+ for job in workflow["jobs"].values():+ assert "timeout-minutes" in job+ for step in job.get("steps", []):+ uses = step.get("uses")+ if uses:+ ref = uses.split("@", 1)[1]+ assert len(ref) == 40 and all(c in "0123456789abcdef" for c in ref), uses+ if "actions/checkout" in (uses or ""):+ assert step["with"]["persist-credentials"] is False+ assert "${{" not in step.get("run", ""), f"{name}: expression inside run (use env)"++[email protected]("name", ["unreal-build.yml", "unreal-gauntlet.yml", "unreal-perf.yml"])+def test_self_hosted_lanes_queue_per_ref_and_never_cancel(name):+ group = _load(name)["concurrency"]+ assert group["cancel-in-progress"] is False+ # A shared group keeps one pending run and cancels the others (merge-queue entries).+ assert "github.ref" in group["group"]++[email protected]("name", ["unreal-build.yml", "unreal-gauntlet.yml"])+def test_merge_queue_entries_without_unreal_paths_skip_the_self_hosted_job(name):+ workflow = _load(name)+ assert "merge_group" in workflow[True]+ changes = workflow["jobs"]["changes"]+ assert changes["runs-on"] == "ubuntu-24.04" and changes["timeout-minutes"] <= 5+ script = changes["steps"][0]["run"]+ for prefix in ("unreal/", "art/verse/", "docs/verse/unreal/", "scripts/unreal/"):+ assert prefix in script+ first = workflow["jobs"]["win64" if name == "unreal-build.yml" else "gauntlet"]+ assert first["needs"] == "changes"+ assert "needs.changes.outputs.unreal == 'true'" in first["if"]+++def test_static_lane_is_hosted_fast_and_lfs_off():+ job = _load("unreal-static.yml")["jobs"]["static"]+ assert job["runs-on"] == "ubuntu-24.04"+ assert job["timeout-minutes"] <= 5+ checkout = job["steps"][0]+ assert checkout["with"]["lfs"] is Falsediff --git a/tests/unit/unreal_scripts/test_tools.py b/tests/unit/unreal_scripts/test_tools.pynew file mode 100644index 0000000000..4a503ec939--- /dev/null+++ b/tests/unit/unreal_scripts/test_tools.py@@ -0,0 +1,393 @@+"""netcode.py, perf.py, capture.py, done_check.py and check_bot_isolation.py (WP10.3, 10.7,+10.8, 10.10, 10.11)."""++from __future__ import annotations++import datetime as dt+import json+from pathlib import Path++import numpy as np+import pytest++from scripts.unreal import capture, check_bot_isolation, done_check, netcode, perf++# --- netcode ---+++def test_netcode_commands_put_lag_on_the_clients_and_iris_on_both():+ cfg = netcode.load_config()+ server = netcode.server_command(Path("E"), Path("P"), cfg, Path("s.log"), 120, iris=False)+ client = netcode.client_command(Path("E"), Path("P"), cfg, Path("c.log"), 120, True, 1000)+ assert "-server" in server and "-UseIrisReplication=0" in server+ assert "-game" in client and "-nullrhi" in client and "-UseIrisReplication=1" in client+ execs = next(c for c in client if c.startswith("-ExecCmds="))+ assert (+ "Net PktLag=60" in execs and "Net PktLagVariance=10" in execs and "Net PktLoss=1" in execs+ )+ assert any(c == f"127.0.0.1:{cfg['port']}" for c in client)+++def test_netcode_log_parsing_and_gates():+ server = netcode.parse_log(+ "LogNet: Join succeeded: A\nLogNet: Join succeeded: B\n"+ "[VerseCounter] reconcileAccepted=40\n*** Server: Error for X at Time=1\n"+ )+ clients = [+ netcode.parse_log(+ "*** Client: Error for P at Time=3\n" * 4 + "[VerseCounter] reconcileFailures=0"+ ),+ netcode.parse_log("*** Client: Error for P at Time=3\n" * 2),+ ]+ result = netcode.evaluate(server, clients, 120, netcode.load_config()["gates"])+ assert result["pass"]+ assert result["correctionsPerClientMinute"] == 1.5+ assert result["reconcile"]["reconcileAccepted"] == 40+ clients.append(netcode.parse_log("Fatal error: boom"))+ assert not netcode.evaluate(server, clients, 120, netcode.load_config()["gates"])["pass"]+ lonely = netcode.parse_log("LogNet: Join succeeded: A\n")+ assert not netcode.evaluate(lonely, [], 120, netcode.load_config()["gates"])["pass"]+++def test_netcode_parse_run_reads_each_variant(tmp_path):+ for variant in ("iris-on", "iris-off"):+ d = tmp_path / variant+ d.mkdir()+ (d / "server.log").write_text("Join succeeded\nJoin succeeded\n", encoding="utf-8")+ (d / "client0.log").write_text("", encoding="utf-8")+ out = netcode.parse_run(tmp_path, netcode.load_config(), 120)+ assert set(out) == {"iris-on", "iris-off"} and all(v["pass"] for v in out.values())+++# --- perf ---+++def _csv(path: Path, frames: list[float], game: float = 3.0) -> Path:+ rows = ["FrameTime,GameThreadTime,RenderThreadTime,GPUTime,Exclusive/GameThread/Physics"]+ rows += [f"{f},{game},4.0,7.0,1.2" for f in frames]+ rows += ["[HasHeaderRowAtEnd],1", "FrameTime,GameThreadTime"]+ path.write_text("\n".join(rows) + "\n", encoding="utf-8")+ return path+++def test_perf_csv_stats(tmp_path):+ frames = [8.0] * 99 + [20.0]+ stats = perf.frame_stats(perf.read_csv(_csv(tmp_path / "a.csv", frames)))+ assert stats["frames"] == 100+ assert stats["frameMsAvg"] == pytest.approx(8.12)+ assert stats["fpsAvg"] == pytest.approx(1000 / 8.12, abs=1e-3)+ assert stats["frameMsP99"] == pytest.approx(8.12, abs=1e-6)+ assert stats["physicsMsAvg"] == 1.2 and stats["gpuMsAvg"] == 7.0+++def test_perf_reads_per_process_vram():+ text = (+ "GPU 00000000:01:00.0\n Processes\n Process ID : 11\n"+ " Used GPU Memory : 900 MiB\n Process ID : 42\n"+ " Type : C+G\n Used GPU Memory : 2048 MiB\n"+ " Process ID : 77\n Used GPU Memory : Not available\n"+ )+ assert perf.parse_process_vram(text, 42) == 2048.0+ assert perf.parse_process_vram(text, 77) is None+ assert perf.parse_process_vram(text, 5) is None+++def test_perf_budgets_and_stability(tmp_path):+ budgets = perf.load_json(perf.BUDGETS_FILE)+ stats = {"fpsAvg": 125.0, "frameMsP99": 10.5, "gameThreadMsAvg": 3.0, "physicsMsAvg": 1.0}+ rows = perf.check_budgets(stats, {"vramMbPeak": 5000.0, "ramMbPeak": None}, budgets, "1440p")+ status = {r["budget"]: r["status"] for r in rows}+ assert status["fpsAvg"] == "pass" and status["vramMbPeak"] == "pass"+ assert status["ramMbPeak"] == "not_measured"+ slow = perf.check_budgets({**stats, "fpsAvg": 100.0}, {}, budgets, "1440p")+ assert {r["budget"]: r["status"] for r in slow}["fpsAvg"] == "fail"+ passed, incomplete = perf.run_verdict(0, stats, rows)+ assert not passed and incomplete == ["ramMbPeak not measured"]+ measured = perf.check_budgets(+ stats, {"vramMbPeak": 5000.0, "ramMbPeak": 3000.0}, budgets, "1440p"+ )+ assert perf.run_verdict(0, stats, measured) == (True, [])+ assert perf.run_verdict(1, {}, measured)[1] == ["replay exited 1", "no CSV profile"]+ assert not perf.run_verdict(0, stats, slow)[0]+ assert any("0.5 ms" in u for u in perf.UNCHECKED_BUDGETS)+ a = {"stats": {"fpsAvg": 120.0, "frameMsP99": 10.0}}+ assert perf.compare(a, {"stats": {"fpsAvg": 117.0, "frameMsP99": 10.2}})["pass"]+ assert not perf.compare(a, {"stats": {"fpsAvg": 110.0, "frameMsP99": 10.0}})["pass"]+++def test_perf_quiet_hours():+ quiet = {"start": "01:00", "end": "06:00", "idleMinutes": 5}+ night = dt.datetime(2026, 11, 3, 2, 0)+ assert perf.quiet_reason(quiet, now=night, idle=600) is None+ assert "used the machine" in perf.quiet_reason(quiet, now=night, idle=30)+ assert "outside" in perf.quiet_reason(quiet, now=dt.datetime(2026, 11, 3, 14, 0), idle=600)+ assert perf.in_window(dt.time(23, 30), "22:00", "02:00")+++def test_perf_command_keeps_the_window_off_screen():+ profile = {"resX": 2560, "resY": 1440}+ cmd = perf.command_for(Path("E"), Path("P"), perf.REPLAY_FILE, profile, Path("o"), Path("l"))+ assert "-WinX=-20000" in cmd and "-VersePerf" in cmd and "-csvGpuStats" in cmd+ assert "-ResX=2560" in cmd and "-d3d12" in cmd+++# --- capture ---+++def _image(rgb_counts: dict[tuple[int, int, int], int]) -> np.ndarray:+ pixels = [c for c, n in rgb_counts.items() for _ in range(n)]+ return np.array(pixels, dtype=np.uint8).reshape(1, -1, 3)+++def test_palette_shares_and_caps():+ img = _image(+ {+ (0x0B, 0x0C, 0x0E): 40,+ (0x16, 0x17, 0x1A): 25,+ (0x2A, 0x2D, 0x31): 15,+ (0x3B, 0x3F, 0x47): 8,+ (0x5E, 0x63, 0x68): 7,+ (0xF2, 0xF4, 0xF5): 5,+ }+ )+ result = capture.measure(img)+ assert result["shares"]["void_black"] == pytest.approx(0.40)+ assert result["shares"]["work_light"] == pytest.approx(0.05)+ assert result["bannedPixels"] == 0+ assert result["pass"]+++def test_palette_caps_fail_on_too_much_amber_and_banned_cyan():+ amber = capture.measure(_image({(0x0B, 0x0C, 0x0E): 98, (0xF2, 0xA3, 0x3A): 2}))+ assert {c["role"]: c["status"] for c in amber["caps"]}["amber"] == "fail"+ cyan = capture.measure(_image({(0x0B, 0x0C, 0x0E): 99, (0x20, 0xC0, 0xE0): 1}))+ assert cyan["bannedPixels"] == 1 and not cyan["pass"]+++def test_banned_pixel_rule_edges():+ px = np.array([[[0, 255, 255], [128, 0, 255], [10, 10, 10], [255, 0, 0], [0, 0, 15]]], np.uint8)+ mask = capture.banned_mask(px)[0]+ assert list(mask) == [True, True, False, False, False]+++def test_capture_measures_a_png_file(tmp_path):+ from PIL import Image++ Image.fromarray(np.full((8, 8, 3), 0x0B, np.uint8)).save(tmp_path / "v.png")+ assert capture.measure_file(tmp_path / "v.png")["pixels"] == 64+++def test_proof_dir_layout(tmp_path):+ path = capture.proof_dir(tmp_path, "WP10", "10.8")+ assert path == tmp_path / "unreal" / "Verse" / "Saved" / "Harness" / "proof" / "WP10" / "10.8"+ with pytest.raises(capture.common.UnrealScriptError):+ capture.proof_dir(tmp_path, "wp10", "10.8")+++def test_views_group_by_map_and_every_view_is_well_formed():+ doc = json.loads(capture.CAMERAS_FILE.read_text(encoding="utf-8"))+ groups = capture.views_by_map(doc)+ assert "/Game/Verse/Decks/Hangar/LV_Hangar" in groups+ assert all(+ len(v["location"]) == 3 and len(v["rotation"]) == 3 for vs in groups.values() for v in vs+ )+ assert list(capture.views_by_map(doc, ["hangar_floor"])) == [+ "/Game/Verse/Decks/Hangar/LV_Hangar"+ ]+++# --- done_check ---+++def test_done_check_lanes_by_path():+ assert done_check.needed_lanes(["dodaios/x.py"]) == []+ assert done_check.needed_lanes(["docs/verse/unreal/README.md"]) == ["static"]+ assert done_check.needed_lanes(["unreal/Verse/Source/VerseBot/A.cpp"]) == ["static", "build"]+ assert done_check.needed_lanes(["scripts/unreal/balance.py"]) == ["static"]+ assert done_check.needed_lanes([".github/workflows/unreal-build.yml"]) == ["static"]+ assert done_check.needed_lanes([".github/workflows/ci.yml"]) == []+ assert done_check.is_visible(["unreal/Verse/Content/Verse/A.uasset"])+++def test_done_check_work_package_sources():+ assert done_check.work_package("wp7") == "WP07"+ assert done_check.work_package(None, "claude/verse-wp10-harness") == "WP10"+ body = "Summary\nWork-Package: WP12 (decks)\n"+ assert done_check.work_package(None, "claude/verse-wp10-harness", body) == "WP12"+ assert done_check.work_package(None, "main", "") is None+++def test_done_check_verdicts(tmp_path):+ runs = {+ "unreal-static.yml": [{"status": "completed", "conclusion": "success", "createdAt": "1"}],+ "unreal-build.yml": [{"status": "completed", "conclusion": "failure", "createdAt": "1"}],+ }++ def fake(cmd):+ return json.dumps(runs[cmd[cmd.index("--workflow") + 1]])++ assert done_check.evaluate(["x.py"], "c", tmp_path, fake)["verdict"] == "n/a"+ assert done_check.evaluate(["docs/verse/unreal/a.md"], "c", tmp_path, fake)["verdict"] == "DONE"+ red = done_check.evaluate(["unreal/Verse/Source/A.cpp"], "c", tmp_path, fake)+ assert red["verdict"] == "NOT DONE"+ runs["unreal-build.yml"][0]["conclusion"] = "success"+ visible = done_check.evaluate(["unreal/Verse/Content/A.uasset"], "c", tmp_path, fake)+ assert visible["verdict"] == "NOT DONE" and "screenshot" in visible["problems"][0]+ proof = tmp_path / "unreal" / "Verse" / "Saved" / "Harness" / "proof"+ (proof / "WP11").mkdir(parents=True)+ (proof / "WP11" / "loose.png").write_bytes(b"png")+ content = ["unreal/Verse/Content/A.uasset"]+ loose = done_check.evaluate(content, "c", tmp_path, fake, wp="WP11")+ assert loose["verdict"] == "NOT DONE", "a PNG outside a sub-task folder does not count"+ shot = proof / "WP11" / "11.1"+ shot.mkdir()+ (shot / "a.png").write_bytes(b"png")+ assert done_check.evaluate(content, "c", tmp_path, fake, wp="WP11")["verdict"] == "DONE"+ other = done_check.evaluate(content, "c", tmp_path, fake, wp="WP12")+ assert other["verdict"] == "NOT DONE", "another package's screenshot does not count"+ stale = done_check.evaluate(content, "c", tmp_path, fake, wp="WP11", since=4e9)+ assert stale["verdict"] == "NOT DONE", "a screenshot older than the commit does not count"+ assert done_check.evaluate(content, "c", tmp_path, fake)["verdict"] == "NOT DONE"+++# --- check_bot_isolation (F1, F6) ---+++def _source(tmp_path: Path, files: dict[str, str]) -> Path:+ for rel, text in files.items():+ path = tmp_path / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text, encoding="utf-8")+ return tmp_path+++ "code",+ [+ "APawn* P = UGameplayStatics::GetPlayerPawn(this, 0);",+ "auto* C = GetWorld()->GetFirstPlayerController();",+ "for (TActorIterator<AVerseCharacter> It(GetWorld()); It; ++It) {}",+ "UGameplayStatics::GetAllActorsOfClass(this, ACharacter::StaticClass(), Out);",+ "APawn* Them = OtherController->GetPawn();",+ "auto* Asc = UAbilitySystemGlobals::GetAbilitySystemComponentFromActor(Target);",+ "GetWorld()->LineTraceSingleByChannel(Hit, A, B, ECC_Visibility);",+ "ACharacter* C = UGameplayStatics::GetPlayerCharacter(this, 0);",+ "AActor* A = UGameplayStatics::GetActorOfClass(this, AVerseCharacter::StaticClass());",+ "for (TActorIterator<AActor> It(W); It; ++It) { if (auto* P = Cast<APawn>(*It)) {} }",+ ],+)+def test_f1_flags_every_truth_read(tmp_path, code):+ root = _source(tmp_path, {"VerseBot/Private/Brain/X.cpp": f"void F() {{ {code} }}\n"})+ assert check_bot_isolation.check_isolation(root)+++def test_f1_allows_own_pawn_sight_channel_comments_and_tests(tmp_path):+ root = _source(+ tmp_path,+ {+ "VerseBot/Private/Brain/X.cpp": (+ "// GetPlayerPawn would be cheating\nvoid F() { APawn* Me = GetPawn(); "+ 'const char* S = "GetPlayerController"; '+ "W->LineTraceSingleByChannel(H, A, B, VerseSight); "+ "auto* Mine = UAbilitySystemGlobals::"+ "GetAbilitySystemComponentFromActor(GetPawn()); }\n"+ ),+ "VerseBot/Private/Tests/Fakes/FakeWorld.cpp": (+ "APawn* P = UGameplayStatics::GetPlayerPawn(this, 0);"+ ),+ "VerseBot/Private/Belief/VersePieceBelief.cpp": "auto S = Query->GetPieceState(Index);",+ },+ )+ assert check_bot_isolation.check_isolation(root) == []+++def test_f1_piece_state_and_eqs_context(tmp_path):+ root = _source(+ tmp_path,+ {+ "VerseBot/Private/Brain/Plan.cpp": "auto S = Query->GetPieceState(Index);",+ "VerseBot/Private/Eqs/Ctx.cpp": (+ "class UCtx : public UEnvQueryContext { AVerseCharacter* T; };"+ ),+ },+ )+ found = check_bot_isolation.check_isolation(root)+ assert any("piece-state" in f for f in found) and any("eqs-context" in f for f in found)+++MODEL = "VerseHarness/Private/Balance/VerseModelController.cpp"+++def test_f6_symmetry(tmp_path):+ root = _source(+ tmp_path,+ {+ MODEL: "void T(const FVersePerceptFrame& F) {} "+ "void A() { Feed->OnPerceptFrame.AddUObject(this, &T); }",+ "VerseBot/Private/Hearing.cpp": "float HearingRangeM = 25.0f;",+ },+ )+ found = check_bot_isolation.check_symmetry(root)+ assert any("hearing-literal" in f for f in found)+ assert any("hearing-source" in f for f in found)+ fixed = _source(+ tmp_path,+ {+ "VerseBot/Private/Hearing.cpp": "float RangeM = Table->HearingRangeFor(Tag); "+ "// UVerseAudibilityTable"+ },+ )+ (fixed / "VerseBot/Private/Hearing.cpp").write_text(+ "float Hearing = UVerseAudibilityTable::RangeFor(Tag, RangeM);", encoding="utf-8"+ )+ assert check_bot_isolation.check_symmetry(fixed) == []+ cheat = _source(+ tmp_path,+ {+ MODEL: "void T(const FVersePerceptFrame& F) { "+ "UGameplayStatics::GetPlayerPawn(this, 0); }"+ },+ )+ assert any("F6.model.player-pawn" in f for f in check_bot_isolation.check_symmetry(cheat))+++def test_the_repo_itself_is_clean():+ assert check_bot_isolation.check_isolation() == []+ assert check_bot_isolation.check_symmetry() == []+++# --- A10.6: two concurrent lock holders serialise ---------------------------------------+++_HOLDER = """+import json, sys, time+sys.path.insert(0, sys.argv[3])+from scripts.unreal import with_lock+with with_lock.MachineLock("build editor (" + sys.argv[2] + ")", "build.py", poll=0.05):+ start = time.time()+ time.sleep(0.6)+ print(json.dumps({"start": start, "end": time.time()}))+"""+++def test_two_concurrent_lock_holders_serialise_and_both_succeed(tmp_path):+ import os+ import subprocess+ import sys++ repo = str(Path(__file__).resolve().parents[3])+ env = dict(os.environ, DODAIOS_LOCK_DIR=str(tmp_path))+ env.pop("DODAIOS_GPU_LOCK_HELD", None)+ procs = [+ subprocess.Popen(+ [sys.executable, "-c", _HOLDER, "x", name, repo],+ env=env,+ stdout=subprocess.PIPE,+ text=True,+ )+ for name in ("a", "b")+ ]+ outs = [p.communicate(timeout=60)[0] for p in procs]+ assert [p.returncode for p in procs] == [0, 0]+ spans = sorted((json.loads(o.strip().splitlines()[-1]) for o in outs), key=lambda s: s["start"])+ assert spans[0]["end"] <= spans[1]["start"] + 0.05diff --git a/unreal/Verse/Data/bot/person_models.json b/unreal/Verse/Data/bot/person_models.jsonnew file mode 100644index 0000000000..1a4269a40c--- /dev/null+++ b/unreal/Verse/Data/bot/person_models.json@@ -0,0 +1,49 @@+{+ "schema": "verse.person_models/1",+ "status": "uncalibrated until the person plays (README Testing); refit from local duel telemetry (bot.md 11.2)",+ "models": {+ "skilled": {+ "description": "A practised person: fast flicks, good recoil control, learns like the hard tier",+ "reactionMeanMs": 225,+ "reactionSdMs": 18,+ "turnRateDegS": 1000,+ "recoilPatternComp": 0.8,+ "headAimChance": 0.3,+ "aimWanderSdDeg": 0.6,+ "aimWanderTheta": 4.0,+ "learning": true,+ "learnWeight": 0.3+ },+ "average": {+ "description": "Slower, looser aim, little learning",+ "reactionMeanMs": 270,+ "reactionSdMs": 40,+ "turnRateDegS": 600,+ "recoilPatternComp": 0.5,+ "headAimChance": 0.12,+ "aimWanderSdDeg": 1.4,+ "aimWanderTheta": 2.5,+ "learning": true,+ "learnWeight": 0.08+ }+ },+ "tricks": {+ "spray": {"behaviour": "Holds the trigger on sight, never bursts, reloads only on empty", "input": {"holdFireOnSight": true, "reloadOnlyOnEmpty": true}},+ "camper": {"behaviour": "Holds cover near its spawn", "intent": {"holdSpawnCoverRadiusM": 8}},+ "rusher": {"behaviour": "Runs straight at the belief", "input": {"sprintForwardWhenUnseen": true}, "intent": {"rushBelief": true}},+ "slider": {"behaviour": "Slides on every approach and every peek", "input": {"slideOnApproach": true, "slideCooldownS": 1.5}},+ "jumppeek": {"behaviour": "Peeks only by jumping", "input": {"leanBecomesJump": true}},+ "leanspam": {"behaviour": "Flips lean every 150-300 ms while exposed", "input": {"leanFlipMinMs": 150, "leanFlipMaxMs": 300}},+ "prone": {"behaviour": "Fights prone from long range", "input": {"proneBeyondM": 20}, "intent": {"preferRangeM": 35}},+ "wallspam": {"behaviour": "Fires through every penetrable piece toward the belief; wall-shot authority off for the trick only", "intent": {"wallShotAuthorityOff": true, "fireThroughPenetrable": true}},+ "turtle": {"behaviour": "Lives behind Bulwarks, redeploys on cooldown", "input": {"deployBulwarkOnCooldown": true}, "intent": {"stayBehindBulwark": true}},+ "breacher": {"behaviour": "Breaches every breachable piece on its route", "intent": {"breachEveryRoutePiece": true}},+ "knife": {"behaviour": "Closes in for knife strikes only", "input": {"meleeOnly": true, "meleeRangeM": 2.0}, "intent": {"rushBelief": true}},+ "finisher": {"behaviour": "Only stalks for finishers", "input": {"neverFire": true}, "intent": {"stalkForFinisher": true}},+ "kiter": {"behaviour": "Keeps 30 m away", "input": {"backOffInsideM": 30}, "intent": {"preferRangeM": 30}},+ "watcher": {"behaviour": "Holds a pre-aimed angle onto the bot's likely spawn", "intent": {"watchOpponentSpawn": true}},+ "silent": {"behaviour": "Crouch-walks everywhere", "input": {"alwaysCrouch": true}},+ "repeek": {"behaviour": "Re-peeks the same angle within 2 s every time", "intent": {"repeekSameAngleWithinS": 2}},+ "hider": {"behaviour": "Avoids every fight", "input": {"fireOnlyWhenHurt": true, "backOffWhenSeen": true}, "intent": {"avoidFights": true}}+ }+}diff --git a/unreal/Verse/Harness/README.md b/unreal/Verse/Harness/README.mdnew file mode 100644index 0000000000..3ea31154bf--- /dev/null+++ b/unreal/Verse/Harness/README.md@@ -0,0 +1,95 @@+# Verse harness (WP10)++Autonomous proof for the Unreal Verse: CI lanes, the netcode test, headless+bot-vs-bot balance runs with their gates, perf capture, screenshots and the+evidence folder. Plan: `docs/verse/unreal/work-packages.md` WP10. Contracts:+`contracts/bot.md` 10 and 11, `contracts/combat-state.md` 12,+`contracts/destruction.md` 10, `architecture.md` 7 and 8,+`contracts/art-pipeline.md` 8.1 and 14.++## Layout++| Path | What |+|---|---|+| `schema/scenario.schema.json` | `verse.scenario/1`: the units one headless process plays (`-VerseHarness=<file>`) |+| `schema/bout.schema.json` | `verse.bout/1`: one line per bout in `bouts.jsonl` |+| `schema/balance.schema.json` | `verse.balance/1`: the report `balance.py` writes |+| `balance/sets.json` | Set definitions, bout cut (15 kills or 600 s), learning, reset and adaptive pairings, the merge-queue subset |+| `balance/scenarios/*.json` | Scripted scenarios `wall_opened_unseen` (F7) and `destruction_storm` (destruction.md 10) |+| `balance/bout_table.json` | Bouts per pairing for 95 % intervals of at most +-0.06, from the measured speed (risk RK1) |+| `netcode/netcode.json` | Dedicated server plus 2 lagged clients: lag, loss, duration, gates |+| `perf/budgets.json`, `perf/replay.json` | Budgets of architecture.md 7; the fixed perf replay path |+| `capture/cameras.json` | Reference views per deck for screenshots and palette shares |+| `fairness/match_memory_fields.json` | Field names the L1 no-persistence scan looks for |+| `clang-format.yml` | Style the static lane applies to changed C++ lines |+| `../Data/bot/person_models.json` | Person models `skilled`, `average` and the 17 tricks (propose-only) |++## Commands++```text+python scripts/unreal/balance.py --set ladder --bouts 200 --seed 7 --jobs 4+python scripts/unreal/balance.py --set ladder --set tricks --tricks spray,camper,rusher,wallspam --gates BG1,BG2,BG4,BG11 --bouts 40+python scripts/unreal/balance.py --set all --nightly+python scripts/unreal/balance.py --from-bouts <run folder> # gates from recorded bouts+python scripts/unreal/balance.py --speed # x real time and the bout table+python scripts/unreal/netcode.py [--iris both]+python scripts/unreal/perf.py run --runs 2 | compare A B | parse <csv>+python scripts/unreal/capture.py shots --wp WP12 --subtask 12.3 | palette <png> | proof-dir --wp WP10 --subtask 10.8+python scripts/unreal/check_bot_isolation.py # F1, F6+python scripts/unreal/check_lfs.py --diff origin/main+python scripts/unreal/check_forbidden_names.py --folders+python scripts/unreal/done_check.py+```++Every run that starts Unreal takes the machine lock (`scripts/unreal/with_lock.py`).++## Lanes++| Workflow | Runner | Trigger | Runs |+|---|---|---|---|+| `unreal-static.yml` | GitHub-hosted, LFS off, 5 min | PR, merge queue, main | DAG, forbidden names (files, diff, commits, PR title), folder names and engine content, F1 and F6, LFS pointers and remote objects and sizes, clang-format, art text and ledger, workflow policy, the script tests (including fork safety, A10.2) |+| `unreal-build.yml` | self-hosted | same-repo PR, merge queue, main | Win64 Editor and Game, automation under `-nullrhi`, netcode smoke; Linux Game cross build |+| `unreal-gauntlet.yml` | self-hosted | merge queue (short), nightly (long) | `balance.py` and gates; nightly netcode with Iris on and off |+| `unreal-perf.yml` | self-hosted | nightly, quiet hours | perf replay twice (budgets, 3 % stability), reference views with palette shares |++The `ci.yml` jobs that make these lanes required (`gate.needs`) belong to the+integration owner (architecture.md 8.2).++## Inside the game process++`UVerseHarnessSubsystem` (a game instance subsystem, created only when the+command line asks for a harness run) starts one driver:++- `UVerseBalanceGauntletController` for `-VerseHarness=`: spawns both slots,+ records bouts from the `UVerseEventHub` events into `FVerseBoutRecorder`, writes+ `bouts.jsonl` and `speed.json`, then exits.+- `UVerseCaptureDirector` for `-VerseCapture=`: reference views or the perf+ flythrough; waits for shader compiles, loading and streaming before each shot.+- The netcode autopilot for `-VerseNetDuration=` and `-VerseNetAutopilot=`.++`AVerseModelController` is a person model: the brain (null until WP08), then+reaction time and turn rate of the person model, then the trick overrides of+`FVerseTrickOverrides`. It reads only `FVersePerceptFrame` (F6).++## Fire audit log format (F4)++VerseBot writes one line per bot shot to the process log, which `balance.py`+merges into the bouts:++```text+[VerseFireAudit] pairing=<id> match=<m> bout=<n> side=<A|B> mode=<Visible|Suppression|Prefire|WallShot> t=<server ms> ids=<percept ids> mass=<belief> age=<s>+```++A bot shot without such a line counts as unclassified and fails F4.++## Waiting on other packages++| Item | Needs | Until then |+|---|---|---|+| Kill-based gates BG1-BG10, BG12 | WP08 brain, WP02 weapons, WP11 ruleset | Report `not_run` with "null brain" when no shot was fired |+| F2, F3, BR1 verdicts | Their automation tests (WP07, WP08) | Fed through `balance.py --checks <json>`, else `not_run` |+| F5 bearing windows | `UVersePerceptionService` (WP07) feeding no-percept windows into the bout | `not_run` below 2,000 windows |+| F7 plan watch, `destruction_storm` budgets | WP06 pieces and WP08 plans | `not_run` |+| `botMsP99`, `navFailures`, adaptive `s` | VerseBot timing, nav and `BotEffectiveSkill` on `AVersePlayerState` | `null`; `s` is read by reflection once the field exists |+| Destruction reset between bouts | WP06 and WP11 reset | Bouts run without it |+| Reconcile counters | WP02 prediction writing `[VerseCounter] reconcile...=<n>` | Netcode gates on corrections and joins only |diff --git a/unreal/Verse/Harness/balance/bout_table.json b/unreal/Verse/Harness/balance/bout_table.jsonnew file mode 100644index 0000000000..0a89753050--- /dev/null+++ b/unreal/Verse/Harness/balance/bout_table.json@@ -0,0 +1,114 @@+{+ "schema": "verse.bout_table/1",+ "halfWidth": 0.06,+ "xRealTimePerProcess": 61.315,+ "killsPerBout": 22.0,+ "boutSimS": 120.0,+ "jobs": 4,+ "provisional": "null brain (no kill in any bout); killsPerBout is the default 22; bouts cut at the 120 s speed-mode limit",+ "gates": {+ "BG1": {+ "p": 0.75,+ "trials": 201,+ "unit": "bouts",+ "boutsPerPairing": 201,+ "pairings": 1,+ "wallHours": null+ },+ "BG2": {+ "p": 0.75,+ "trials": 201,+ "unit": "bouts",+ "boutsPerPairing": 201,+ "pairings": 1,+ "wallHours": null+ },+ "BG3": {+ "p": 0.9,+ "trials": 97,+ "unit": "bouts",+ "boutsPerPairing": 97,+ "pairings": 4,+ "wallHours": null+ },+ "BG4": {+ "p": 0.5,+ "trials": 267,+ "unit": "bouts",+ "boutsPerPairing": 267,+ "pairings": 17,+ "wallHours": null+ },+ "BG5": {+ "p": 0.45,+ "trials": 265,+ "unit": "kills",+ "boutsPerPairing": 13,+ "pairings": 18,+ "wallHours": null+ },+ "BG6": {+ "p": 0.4,+ "trials": 257,+ "unit": "kills",+ "boutsPerPairing": 12,+ "pairings": 2,+ "wallHours": null+ },+ "BG7": {+ "p": 0.55,+ "trials": 265,+ "unit": "kills",+ "boutsPerPairing": 13,+ "pairings": 1,+ "wallHours": null+ },+ "BG8": {+ "p": 0.5,+ "trials": 267,+ "unit": "kills",+ "boutsPerPairing": 13,+ "pairings": 6,+ "wallHours": null+ },+ "BG9": {+ "p": 0.5,+ "trials": 267,+ "unit": "kills",+ "boutsPerPairing": 13,+ "pairings": 1,+ "wallHours": null+ },+ "BG10": {+ "p": 0.5,+ "trials": 267,+ "unit": "kills",+ "boutsPerPairing": 13,+ "pairings": 2,+ "wallHours": null+ }+ },+ "fullWidthQueueBouts": 267,+ "queueBouts": 40,+ "queueHalfWidth": {+ "boutShare": 0.148,+ "killShare": 0.033+ },+ "nightlyBouts": 267,+ "measured": {+ "run": "speed-s11",+ "speed": {+ "processes": 4,+ "xRealTimePerProcess": 61.315,+ "xRealTimeMean": 62.649,+ "simS": 960.0,+ "wallS": 3.914,+ "startupS": 9.278,+ "peakRamMbPerProcess": 1467.8,+ "targetXRealTime": 20.0,+ "meetsTarget": true+ },+ "nullBrain": true+ },+ "note": "Measured 2026-11-02 on the reference box with the null brain on an empty map (4 processes, -nullrhi, -benchmark, fixed 60 Hz). xRealTimePerProcess is the engine floor, an upper bound; the wall-time rows stay null until balance.py --speed is rerun with the real brain on LV_Hangar (WP08, WP02, WP11). Bout counts come from the interval width, not from speed. The merge queue plays queueBouts per pairing; queueHalfWidth is the 95 % interval it gives"+}diff --git a/unreal/Verse/Harness/balance/scenarios/destruction_storm.json b/unreal/Verse/Harness/balance/scenarios/destruction_storm.jsonnew file mode 100644index 0000000000..9c4a0cebf6--- /dev/null+++ b/unreal/Verse/Harness/balance/scenarios/destruction_storm.json@@ -0,0 +1,21 @@+{+ "schema": "verse.scenario_script/1",+ "id": "destruction_storm",+ "contract": "destruction.md 10",+ "description": "Two breach charges plus a full magazine into a container row every 2 s for 60 s; every destruction budget must hold",+ "a": {"kind": "model", "model": "average"},+ "b": {"kind": "model", "model": "average"},+ "steps": [+ {"everyS": 2, "untilS": 60, "do": "breach_charge", "count": 2, "target": "arena.container_row"},+ {"everyS": 2, "untilS": 60, "do": "empty_magazine", "weapon": "rifle", "target": "arena.container_row"}+ ],+ "durationS": 70,+ "budgets": {+ "activeDebrisBodiesMax": 400,+ "fractureEventsPerSMax": 64,+ "physicsMsMax": 2.0,+ "penetrationTraceMsMax": 0.3,+ "geometryCollectionsAliveMax": 32,+ "fullResetBurstBytesMax": 16384+ }+}diff --git a/unreal/Verse/Harness/balance/scenarios/wall_opened_unseen.json b/unreal/Verse/Harness/balance/scenarios/wall_opened_unseen.jsonnew file mode 100644index 0000000000..473e20d27a--- /dev/null+++ b/unreal/Verse/Harness/balance/scenarios/wall_opened_unseen.json@@ -0,0 +1,14 @@+{+ "schema": "verse.scenario_script/1",+ "id": "wall_opened_unseen",+ "contract": "bot.md 10 F7, destruction.md 6.2 DR6",+ "description": "A wall is breached out of sight and earshot of the bot; no bot plan may use the opening until the bot sees it",+ "a": {"kind": "bot", "tier": "hard"},+ "b": {"kind": "model", "model": "average", "trick": "camper"},+ "steps": [+ {"atS": 5, "do": "breach_piece_out_of_perception", "piece": "arena.wall.f7_target", "minDistanceFromBotM": 25},+ {"atS": 5, "do": "watch_plans_through_piece", "piece": "arena.wall.f7_target"}+ ],+ "durationS": 120,+ "pass": {"f7Violations": 0}+}diff --git a/unreal/Verse/Harness/balance/sets.json b/unreal/Verse/Harness/balance/sets.jsonnew file mode 100644index 0000000000..ec0a82cb0f--- /dev/null+++ b/unreal/Verse/Harness/balance/sets.json@@ -0,0 +1,16 @@+{+ "schema": "verse.balance_sets/1",+ "map": "/Game/Verse/Decks/Hangar/LV_Hangar",+ "killsToWin": 15,+ "matchTimeLimitS": 600,+ "boutsPerMatch": 10,+ "tiers": ["normal", "hard", "elite"],+ "learning": {"bot": "hard", "opponents": ["repeek", "watcher", "camper"]},+ "reset": {"bot": "hard", "opponent": "repeek", "windowS": 300},+ "adaptive": {"opponents": ["skilled", "average"], "killWindow": [30, 60]},+ "queue": {"sets": ["ladder", "tricks"], "tricks": ["spray", "camper", "rusher", "wallspam"], "gates": ["BG1", "BG2", "BG4", "BG11"]},+ "scenarios": {+ "wall_opened_unseen": "scenarios/wall_opened_unseen.json",+ "destruction_storm": "scenarios/destruction_storm.json"+ }+}diff --git a/unreal/Verse/Harness/capture/cameras.json b/unreal/Verse/Harness/capture/cameras.jsonnew file mode 100644index 0000000000..87df5b2a47--- /dev/null+++ b/unreal/Verse/Harness/capture/cameras.json@@ -0,0 +1,13 @@+{+ "schema": "verse.capture/1",+ "id": "reference_views",+ "description": "Reference views per deck without combat, for screenshots and the palette share measurement (art-pipeline.md 8.1). Unreal cm and degrees (pitch, yaw, roll)",+ "views": [+ {"id": "hangar_overview", "deck": "Hangar", "map": "/Game/Verse/Decks/Hangar/LV_Hangar", "location": [0, -4200, 1400], "rotation": [-18, 90, 0], "fovDeg": 80},+ {"id": "hangar_floor", "deck": "Hangar", "map": "/Game/Verse/Decks/Hangar/LV_Hangar", "location": [-1500, -800, 170], "rotation": [-2, 30, 0], "fovDeg": 90},+ {"id": "bridge_overview", "deck": "Bridge", "map": "/Game/Verse/Decks/Bridge/LV_Bridge", "location": [0, -1500, 600], "rotation": [-15, 90, 0], "fovDeg": 80},+ {"id": "ops_overview", "deck": "Ops", "map": "/Game/Verse/Decks/Ops/LV_Ops", "location": [0, -1500, 600], "rotation": [-15, 90, 0], "fovDeg": 80},+ {"id": "engineering_overview", "deck": "Engineering", "map": "/Game/Verse/Decks/Engineering/LV_Engineering", "location": [0, -1500, 600], "rotation": [-15, 90, 0], "fovDeg": 80}+ ],+ "settleFrames": 30+}diff --git a/unreal/Verse/Harness/clang-format.yml b/unreal/Verse/Harness/clang-format.ymlnew file mode 100644index 0000000000..b9a66611ca--- /dev/null+++ b/unreal/Verse/Harness/clang-format.yml@@ -0,0 +1,18 @@+# clang-format style of the Unreal Verse C++ (unreal-static, changed lines only).+# Matches the engine's layout: tabs, braces on their own line, no reflow of long lines.+BasedOnStyle: Microsoft+UseTab: ForContinuationAndIndentation+IndentWidth: 4+TabWidth: 4+ColumnLimit: 0+BreakBeforeBraces: Allman+AccessModifierOffset: -4+NamespaceIndentation: All+PointerAlignment: Left+AllowShortFunctionsOnASingleLine: Inline+AllowShortIfStatementsOnASingleLine: Never+AllowShortLambdasOnASingleLine: All+SortIncludes: CaseSensitive+IncludeBlocks: Preserve+SpaceBeforeParens: ControlStatements+IndentCaseLabels: falsediff --git a/unreal/Verse/Harness/fairness/match_memory_fields.json b/unreal/Verse/Harness/fairness/match_memory_fields.jsonnew file mode 100644index 0000000000..72e093fae2--- /dev/null+++ b/unreal/Verse/Harness/fairness/match_memory_fields.json@@ -0,0 +1,14 @@+{+ "schema": "verse.l1_fields/1",+ "contract": "bot.md 7.1, 10 L1 (B8)",+ "description": "Field names of UVerseBotMatchMemory. L1 fails when any file written under Saved/ or the data dir during the match, or any bridge frame, carries one of them",+ "fields": [+ "PositionHeatmap",+ "ShootingSpots",+ "PeekHabits",+ "PreferredRanges",+ "RouteCounts",+ "HabitCounters",+ "UVerseBotMatchMemory"+ ]+}diff --git a/unreal/Verse/Harness/netcode/netcode.json b/unreal/Verse/Harness/netcode/netcode.jsonnew file mode 100644index 0000000000..7caf95940b--- /dev/null+++ b/unreal/Verse/Harness/netcode/netcode.json@@ -0,0 +1,15 @@+{+ "schema": "verse.netcode/1",+ "contract": "architecture.md 3, 8.3, risks RK2-RK4; orchestration.md 5.2",+ "map": "/Game/Verse/Decks/Hangar/LV_Hangar",+ "durationS": 120,+ "clients": 2,+ "netEmulation": {"PktLag": 60, "PktLagVariance": 10, "PktLoss": 1},+ "port": 17777,+ "gates": {+ "correctionsPerClientMinuteMax": 6,+ "reconcileFailuresMax": 0,+ "clientsConnectedMin": 2+ },+ "iris": {"pr": [true], "nightly": [true, false]}+}diff --git a/unreal/Verse/Harness/perf/budgets.json b/unreal/Verse/Harness/perf/budgets.jsonnew file mode 100644index 0000000000..f58d5b1347--- /dev/null+++ b/unreal/Verse/Harness/perf/budgets.json@@ -0,0 +1,14 @@+{+ "schema": "verse.perf_budgets/1",+ "contract": "architecture.md 7",+ "profiles": {+ "1440p": {"resX": 2560, "resY": 1440, "fpsAvgMin": 120, "p99FrameMsMax": 11.0},+ "4k": {"resX": 3840, "resY": 2160, "fpsAvgMin": 90, "p99FrameMsMax": 14.0}+ },+ "gameThreadMsMax": 4.0,+ "physicsMsMax": 2.0,+ "vramVisibleMbMax": 6144,+ "systemRamVisibleMbMax": 4096,+ "stabilityMaxRelDelta": 0.03,+ "quietHours": {"start": "01:00", "end": "06:00", "idleMinutes": 5}+}diff --git a/unreal/Verse/Harness/perf/replay.json b/unreal/Verse/Harness/perf/replay.jsonnew file mode 100644index 0000000000..19d14a9e11--- /dev/null+++ b/unreal/Verse/Harness/perf/replay.json@@ -0,0 +1,18 @@+{+ "schema": "verse.capture/1",+ "id": "perf_hangar_duel",+ "description": "Fixed perf replay: a seeded bot-vs-bot duel in the hangar arena seen along a fixed camera path",+ "map": "/Game/Verse/Decks/Hangar/LV_Hangar",+ "seed": 4242,+ "warmupS": 10,+ "flythrough": {+ "durationS": 60,+ "keys": [+ {"t": 0, "location": [0, -2500, 600], "rotation": [-10, 90, 0], "fovDeg": 90},+ {"t": 20, "location": [2000, 0, 450], "rotation": [-8, 180, 0], "fovDeg": 90},+ {"t": 40, "location": [0, 2500, 600], "rotation": [-10, 270, 0], "fovDeg": 90},+ {"t": 60, "location": [-2000, 0, 450], "rotation": [-8, 0, 0], "fovDeg": 90}+ ]+ },+ "shots": [{"id": "replay_mid", "atS": 30}]+}diff --git a/unreal/Verse/Harness/schema/balance.schema.json b/unreal/Verse/Harness/schema/balance.schema.jsonnew file mode 100644index 0000000000..54abef46b7--- /dev/null+++ b/unreal/Verse/Harness/schema/balance.schema.json@@ -0,0 +1,73 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "verse.balance/1",+ "title": "Balance run report (bot.md 11.1, 11.3, 11.4), written by scripts/unreal/balance.py",+ "type": "object",+ "required": ["schema", "run", "seed", "sets", "pairings", "gates"],+ "properties": {+ "schema": {"const": "verse.balance/1"},+ "run": {"type": "string"},+ "created": {"type": "string"},+ "seed": {"type": "integer"},+ "sets": {"type": "array", "items": {"type": "string"}},+ "bouts": {"type": ["integer", "null"]},+ "jobs": {"type": "integer"},+ "patch": {"type": ["object", "null"]},+ "speed": {"type": ["object", "null"]},+ "pairings": {+ "type": "array",+ "items": {+ "type": "object",+ "required": ["id", "a", "b", "bouts", "boutWinRateA", "killShareA", "killShareA95"],+ "properties": {+ "id": {"type": "string"},+ "set": {"type": "string"},+ "a": {"type": "object"},+ "b": {"type": "object"},+ "bouts": {"type": "integer", "minimum": 0},+ "kills": {"type": "integer", "minimum": 0},+ "boutWinRateA": {"type": ["number", "null"]},+ "boutWinRateA95": {"type": ["array", "null"]},+ "killShareA": {"type": ["number", "null"]},+ "killShareA95": {"type": ["array", "null"]},+ "spawnSide0WinRate": {"type": ["number", "null"]},+ "kd": {"type": "object"},+ "ttkS": {"type": "object"},+ "timeToContactS": {"type": "object"},+ "accuracy": {"type": "object"},+ "headshotShare": {"type": "object"},+ "wallKillShare": {"type": "object"},+ "finisherShare": {"type": "object"},+ "knifeShare": {"type": "object"},+ "bulwarkUses": {"type": "object"},+ "breachUses": {"type": "object"},+ "reloadsInFight": {"type": "object"},+ "engagementRangeHist": {"type": "object"},+ "spawnKills": {"type": "integer"},+ "fireAudit": {"type": "object"},+ "learningDelta": {"type": ["number", "null"]},+ "adaptiveTrace": {"type": "array"},+ "botMsP99": {"type": ["number", "null"]},+ "stuckEvents": {"type": "integer"},+ "navFailures": {"type": ["integer", "null"]},+ "matchTimeS": {"type": "number"}+ }+ }+ },+ "gates": {+ "type": "array",+ "items": {+ "type": "object",+ "required": ["id", "status", "detail"],+ "properties": {+ "id": {"type": "string", "pattern": "^(BG([1-9]|1[0-2])|F[1-7]|L1|BR1)$"},+ "status": {"enum": ["pass", "fail", "not_run"]},+ "detail": {"type": "string"},+ "values": {"type": "object"}+ }+ }+ },+ "fireAuditLog": {"type": ["string", "null"]},+ "incomplete": {"type": "array", "items": {"type": "string"}}+ }+}diff --git a/unreal/Verse/Harness/schema/bout.schema.json b/unreal/Verse/Harness/schema/bout.schema.jsonnew file mode 100644index 0000000000..8245ea3374--- /dev/null+++ b/unreal/Verse/Harness/schema/bout.schema.json@@ -0,0 +1,69 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "verse.bout/1",+ "title": "One bout line in bouts.jsonl, written by UVerseBalanceGauntletController",+ "type": "object",+ "required": ["schema", "pairing", "match", "bout", "seed", "spawnSideA", "winner", "durationS", "kills", "a", "b"],+ "properties": {+ "schema": {"const": "verse.bout/1"},+ "pairing": {"type": "string"},+ "match": {"type": "integer", "minimum": 0},+ "bout": {"type": "integer", "minimum": 0},+ "seed": {"type": "integer", "minimum": 0},+ "spawnSideA": {"enum": [0, 1]},+ "winner": {"enum": ["A", "B", "none"]},+ "durationS": {"type": "number", "minimum": 0},+ "matchTimeStartS": {"type": "number", "minimum": 0},+ "serverStartMs": {"type": "number", "minimum": 0},+ "serverEndMs": {"type": "number", "minimum": 0},+ "fireAudit": {"type": "object", "additionalProperties": {"type": "integer", "minimum": 0}},+ "kills": {+ "type": "array",+ "items": {+ "type": "object",+ "required": ["t", "killer"],+ "properties": {+ "t": {"type": "number", "minimum": 0},+ "killer": {"enum": ["A", "B"]},+ "cause": {"enum": ["bolt", "melee", "finisher", "gadget", "world"]},+ "headshot": {"type": "boolean"},+ "wall": {"type": "boolean"},+ "rangeM": {"type": "number", "minimum": 0},+ "ttkS": {"type": "number", "minimum": 0},+ "spawnKill": {"type": "boolean"}+ }+ }+ },+ "a": {"$ref": "#/$defs/side"},+ "b": {"$ref": "#/$defs/side"},+ "adaptiveTrace": {"type": "array", "items": {"type": "number"}},+ "bearingWindows": {+ "description": "One entry per no-percept window of at least 10 s: [facing deg, true bearing deg, decoy bearing deg] (F5)",+ "type": "array",+ "items": {"type": "array", "items": {"type": "number"}, "minItems": 3, "maxItems": 3}+ },+ "f7Violations": {"type": "integer", "minimum": 0},+ "storm": {"type": "object"}+ },+ "$defs": {+ "side": {+ "type": "object",+ "required": ["kills", "deaths", "shots", "hits"],+ "properties": {+ "kills": {"type": "integer", "minimum": 0},+ "deaths": {"type": "integer", "minimum": 0},+ "shots": {"type": "integer", "minimum": 0},+ "hits": {"type": "integer", "minimum": 0},+ "headshotHits": {"type": "integer", "minimum": 0},+ "timeToContactS": {"type": "array", "items": {"type": "number", "minimum": 0}},+ "bulwarkUses": {"type": "integer", "minimum": 0},+ "breachUses": {"type": "integer", "minimum": 0},+ "reloadsInFight": {"type": "integer", "minimum": 0},+ "fireAudit": {"type": "object", "additionalProperties": {"type": "integer", "minimum": 0}},+ "botMsP99": {"type": ["number", "null"]},+ "stuckEvents": {"type": "integer", "minimum": 0},+ "navFailures": {"type": ["integer", "null"]}+ }+ }+ }+}diff --git a/unreal/Verse/Harness/schema/scenario.schema.json b/unreal/Verse/Harness/schema/scenario.schema.jsonnew file mode 100644index 0000000000..a1ab768e69--- /dev/null+++ b/unreal/Verse/Harness/schema/scenario.schema.json@@ -0,0 +1,58 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "verse.scenario/1",+ "title": "One headless harness process: the units it plays (bot.md 11.1, -VerseHarness=<file>)",+ "type": "object",+ "required": ["schema", "run", "map", "output", "units"],+ "additionalProperties": false,+ "properties": {+ "schema": {"const": "verse.scenario/1"},+ "run": {"type": "string", "minLength": 1},+ "job": {"type": "integer", "minimum": 0},+ "map": {"type": "string", "pattern": "^/(Game|Engine)/"},+ "output": {"type": "string", "minLength": 1},+ "maxWallS": {"type": "number", "exclusiveMinimum": 0},+ "trace": {+ "type": "object",+ "additionalProperties": false,+ "properties": {"bearing": {"type": "boolean"}, "fireAudit": {"type": "boolean"}}+ },+ "units": {"type": "array", "minItems": 1, "items": {"$ref": "#/$defs/unit"}}+ },+ "$defs": {+ "slot": {+ "type": "object",+ "required": ["kind"],+ "additionalProperties": false,+ "properties": {+ "kind": {"enum": ["bot", "model"]},+ "tier": {"enum": ["normal", "hard", "elite", "adaptive"]},+ "learning": {"type": "boolean"},+ "model": {"enum": ["skilled", "average"]},+ "trick": {"type": "string", "pattern": "^[a-z]+$"}+ },+ "allOf": [+ {"if": {"properties": {"kind": {"const": "bot"}}}, "then": {"required": ["tier"]}},+ {"if": {"properties": {"kind": {"const": "model"}}}, "then": {"anyOf": [{"required": ["model"]}, {"required": ["tier"]}]}}+ ]+ },+ "unit": {+ "type": "object",+ "required": ["pairing", "match", "seed", "bouts", "a", "b"],+ "additionalProperties": false,+ "properties": {+ "pairing": {"type": "string", "pattern": "^[a-z0-9_+.-]+$"},+ "set": {"type": "string"},+ "match": {"type": "integer", "minimum": 0},+ "seed": {"type": "integer", "minimum": 0, "maximum": 4294967295},+ "bouts": {"type": "integer", "minimum": 1},+ "a": {"$ref": "#/$defs/slot"},+ "b": {"$ref": "#/$defs/slot"},+ "killsToWin": {"type": "integer", "minimum": 1},+ "matchTimeLimitS": {"type": "number", "exclusiveMinimum": 0},+ "scenario": {"type": "string"},+ "tierPatch": {"type": "object"}+ }+ }+ }+}diff --git a/unreal/Verse/Source/VerseHarness/Private/Balance/VerseBalanceGauntletController.cpp b/unreal/Verse/Source/VerseHarness/Private/Balance/VerseBalanceGauntletController.cppnew file mode 100644index 0000000000..e42398c115--- /dev/null+++ b/unreal/Verse/Source/VerseHarness/Private/Balance/VerseBalanceGauntletController.cpp@@ -0,0 +1,768 @@+#include "Balance/VerseBalanceGauntletController.h"++#include "Balance/VerseHarnessPerceptFeed.h"+#include "Balance/VerseModelController.h"+#include "Bot/VerseBotTier.h"+#include "Engine/World.h"+#include "EngineUtils.h"+#include "Events/VerseEventHub.h"+#include "GameFramework/Character.h"+#include "GameFramework/CharacterMovementComponent.h"+#include "GameFramework/GameModeBase.h"+#include "GameFramework/Pawn.h"+#include "GameFramework/PlayerStart.h"+#include "GameFramework/PlayerState.h"+#include "HAL/PlatformMemory.h"+#include "HAL/PlatformMisc.h"+#include "HAL/PlatformTime.h"+#include "Misc/FileHelper.h"+#include "Misc/Paths.h"+#include "UObject/UObjectGlobals.h"+#include "UObject/UnrealType.h"+#include "VerseHarnessJson.h"+#include "VerseLog.h"++namespace VerseBalancePrivate+{+ /** The bot controller class of VerseBot (WP08), found by name so the harness builds before it. */+ const TCHAR* BotControllerPath = TEXT("/Script/VerseBot.VerseBotController");++ /** Harness spawn pair when the map has fewer than two player starts: 20 m apart, facing each other. */+ constexpr double FallbackSpawnGapCm = 2000.0;++ void AppendLine(const FString& File, const FString& Line)+ {+ FFileHelper::SaveStringToFile(Line + TEXT("\n"), *File, FFileHelper::EEncodingOptions::ForceUTF8WithoutBOM,+ &IFileManager::Get(), FILEWRITE_Append);+ }++ /**+ * Calls a UFUNCTION of the bot controller by name: the frozen AVerseBotController methods,+ * reached by reflection so the harness builds before VerseBot has them. Arg fills the first+ * parameter when bHasArg; OutFloat receives a float return value.+ */+ bool CallBotFunction(UObject& Target, FName Name, TFunctionRef<bool(FProperty&, void*)> Arg, bool bHasArg, float* OutFloat,+ FString& OutError)+ {+ UFunction* Fn = Target.FindFunction(Name);+ if (!Fn)+ {+ OutError = FString::Printf(TEXT("%s has no UFUNCTION %s (bot.md frozen interface)"), *Target.GetClass()->GetName(),+ *Name.ToString());+ return false;+ }+ TArray<uint8, TAlignedHeapAllocator<16>> Buffer;+ Buffer.SetNumZeroed(FMath::Max(1, int32(Fn->ParmsSize)));+ FProperty* First = nullptr;+ FProperty* Return = nullptr;+ for (TFieldIterator<FProperty> It(Fn); It && It->HasAnyPropertyFlags(CPF_Parm); ++It)+ {+ It->InitializeValue_InContainer(Buffer.GetData());+ if (It->HasAnyPropertyFlags(CPF_ReturnParm))+ {+ Return = *It;+ }+ else if (!First)+ {+ First = *It;+ }+ }+ bool bOk = true;+ if (bHasArg)+ {+ bOk = First && Arg(*First, First->ContainerPtrToValuePtr<void>(Buffer.GetData()));+ if (!bOk)+ {+ OutError =+ FString::Printf(TEXT("%s::%s has an unexpected signature"), *Target.GetClass()->GetName(), *Name.ToString());+ }+ }+ if (bOk && OutFloat && !CastField<FFloatProperty>(Return) && !CastField<FDoubleProperty>(Return))+ {+ OutError = FString::Printf(TEXT("%s::%s returns no float"), *Target.GetClass()->GetName(), *Name.ToString());+ bOk = false;+ }+ if (bOk)+ {+ Target.ProcessEvent(Fn, Buffer.GetData());+ if (OutFloat)+ {+ if (const FFloatProperty* F = CastField<FFloatProperty>(Return))+ {+ *OutFloat = F->GetPropertyValue_InContainer(Buffer.GetData());+ }+ else if (const FDoubleProperty* D = CastField<FDoubleProperty>(Return))+ {+ *OutFloat = float(D->GetPropertyValue_InContainer(Buffer.GetData()));+ }+ }+ }+ for (TFieldIterator<FProperty> It(Fn); It && It->HasAnyPropertyFlags(CPF_Parm); ++It)+ {+ It->DestroyValue_InContainer(Buffer.GetData());+ }+ return bOk;+ }++ /** Sets one UVerseBotTier field from a JSON value; false on an unknown field or a wrong type. */+ bool SetTierField(UVerseBotTier& Tier, const FString& Field, const FVerseJson& Value, FString& OutError)+ {+ FProperty* Prop = FindFProperty<FProperty>(UVerseBotTier::StaticClass(), *Field);+ void* Ptr = Prop ? Prop->ContainerPtrToValuePtr<void>(&Tier) : nullptr;+ if (!Prop || !Ptr)+ {+ OutError = FString::Printf(TEXT("tierPatch: UVerseBotTier has no field %s"), *Field);+ return false;+ }+ if (FFloatProperty* F = CastField<FFloatProperty>(Prop); F && Value.Type == FVerseJson::EType::Number)+ {+ F->SetPropertyValue(Ptr, float(Value.Number));+ return true;+ }+ if (FIntProperty* I = CastField<FIntProperty>(Prop); I && Value.Type == FVerseJson::EType::Number)+ {+ I->SetPropertyValue(Ptr, int32(Value.Number));+ return true;+ }+ if (FBoolProperty* B = CastField<FBoolProperty>(Prop); B && Value.Type == FVerseJson::EType::Bool)+ {+ B->SetPropertyValue(Ptr, Value.bBool);+ return true;+ }+ if (FNameProperty* N = CastField<FNameProperty>(Prop); N && Value.Type == FVerseJson::EType::String)+ {+ N->SetPropertyValue(Ptr, FName(*Value.String));+ return true;+ }+ FStructProperty* S = CastField<FStructProperty>(Prop);+ if (S && S->Struct == TVariantStructure<FVector2f>::Get() && Value.Type == FVerseJson::EType::Array && Value.Array.Num() == 2 && Value.Array[0] && Value.Array[1])+ {+ *static_cast<FVector2f*>(Ptr) = FVector2f(float(Value.Array[0]->Number), float(Value.Array[1]->Number));+ return true;+ }+ OutError = FString::Printf(TEXT("tierPatch: %s has the wrong type"), *Field);+ return false;+ }++ bool IsTierId(const FString& Key)+ {+ return Key == TEXT("normal") || Key == TEXT("hard") || Key == TEXT("elite") || Key == TEXT("adaptive");+ }+}++double UVerseBalanceGauntletController::Now() const+{+ const UWorld* W = World.Get();+ return W ? W->GetTimeSeconds() : 0.0;+}++double UVerseBalanceGauntletController::ServerMs() const+{+ return FMath::RoundToDouble(FMath::Max(0.0, Now()) * 1000.0);+}++bool UVerseBalanceGauntletController::Start(UWorld* InWorld, const FVerseHarnessScenario& InScenario, FString& OutError)+{+ World = InWorld;+ Scenario = InScenario;+ if (!InWorld)+ {+ OutError = TEXT("no game world");+ return false;+ }+ if (!FVersePersonModelSet::LoadDefault(PersonModels, OutError))+ {+ return false;+ }+ Feed = NewObject<UVerseHarnessPerceptFeed>(this);+ IFileManager::Get().MakeDirectory(*Scenario.OutputDir, true);+ BoutsFile = FPaths::Combine(Scenario.OutputDir, TEXT("bouts.jsonl"));+ IFileManager::Get().Delete(*BoutsFile, false, true, true);++ if (UVerseEventHub* Hub = UVerseEventHub::Get(InWorld))+ {+ HubHandles.Add(Hub->OnFire.AddUObject(this, &UVerseBalanceGauntletController::HandleFire));+ HubHandles.Add(Hub->OnHit.AddUObject(this, &UVerseBalanceGauntletController::HandleHit));+ HubHandles.Add(Hub->OnDeath.AddUObject(this, &UVerseBalanceGauntletController::HandleDeath));+ HubHandles.Add(Hub->OnReload.AddUObject(this, &UVerseBalanceGauntletController::HandleReload));+ HubHandles.Add(Hub->OnGadget.AddUObject(this, &UVerseBalanceGauntletController::HandleGadget));+ }+ else+ {+ UE_LOG(LogVerseHarness, Warning, TEXT("[VerseHarness] no UVerseEventHub in the world; bouts will hold no combat"));+ }+ BotControllerKind = FindObject<UClass>(nullptr, VerseBalancePrivate::BotControllerPath) ? TEXT("VerseBotController")+ : TEXT("null-brain stand-in");+ WallStartS = FPlatformTime::Seconds();+ StartupS = WallStartS - GStartTime;+ SimStartS = Now();+ UE_LOG(LogVerseHarness, Display, TEXT("[VerseHarness] run %s job %d: %d units, bot slots: %s"), *Scenario.Run, Scenario.Job,+ Scenario.Units.Num(), *BotControllerKind);+ BeginUnit();+ if (bFailed)+ {+ OutError = EndReason;+ return false;+ }+ return true;+}++UVerseBotTier* UVerseBalanceGauntletController::MakeTier(UObject* Outer, FName TierId, bool bLearning, const FString& TierPatchJson,+ FString& OutError)+{+ using namespace VerseBalancePrivate;+ UVerseBotTier* Tier = NewObject<UVerseBotTier>(Outer ? Outer : GetTransientPackage());+ // The adaptive bot interpolates between tiers itself (bot.md 9.2); its base asset is normal.+ const FName Base = TierId == TEXT("adaptive") || TierId.IsNone() ? FName(TEXT("normal")) : TierId;+ if (!UVerseBotTier::ApplyStartValues(Base, *Tier))+ {+ OutError = FString::Printf(TEXT("unknown tier %s"), *Base.ToString());+ return nullptr;+ }+ if (!TierPatchJson.IsEmpty())+ {+ FString ParseError;+ const TSharedPtr<FVerseJson> Patch = FVerseJson::Parse(TierPatchJson, ParseError);+ if (!Patch || !Patch->IsObject())+ {+ OutError = TEXT("tierPatch is not a JSON object: ") + ParseError;+ return nullptr;+ }+ for (const TPair<FString, TSharedPtr<FVerseJson>>& Member : Patch->Object)+ {+ if (!Member.Value)+ {+ continue;+ }+ if (!IsTierId(Member.Key))+ {+ if (!SetTierField(*Tier, Member.Key, *Member.Value, OutError))+ {+ return nullptr;+ }+ continue;+ }+ if (!Member.Value->IsObject())+ {+ OutError = FString::Printf(TEXT("tierPatch.%s is not an object"), *Member.Key);+ return nullptr;+ }+ if (FName(*Member.Key) != TierId)+ {+ continue;+ }+ for (const TPair<FString, TSharedPtr<FVerseJson>>& Field : Member.Value->Object)+ {+ if (!Field.Value || !SetTierField(*Tier, Field.Key, *Field.Value, OutError))+ {+ if (OutError.IsEmpty())+ {+ OutError = FString::Printf(TEXT("tierPatch.%s.%s is null"), *Member.Key, *Field.Key);+ }+ return nullptr;+ }+ }+ }+ }+ if (!bLearning)+ {+ // Learning off (BG8): the frozen tier has no switch, so the learnt weight is capped at 0.+ Tier->LearnWeightMax = 0.f;+ }+ return Tier;+}++FVersePersonModel UVerseBalanceGauntletController::PersonFromTier(const UVerseBotTier& Tier, FName Name)+{+ FVersePersonModel Person;+ Person.Name = Name;+ Person.ReactionMeanMs = Tier.ReactionMs.X;+ Person.ReactionSdMs = Tier.ReactionMs.Y;+ Person.TurnRateDegS = Tier.TurnRateDegS;+ Person.RecoilPatternComp = Tier.RecoilPatternComp;+ Person.HeadAimChance = Tier.HeadAimChance;+ Person.AimWanderSdDeg = Tier.AimNoiseDeg;+ Person.AimWanderTheta = Tier.AimNoiseRate;+ Person.LearnWeight = Tier.LearnWeightMax;+ Person.bLearning = Tier.LearnWeightMax > 0.f;+ return Person;+}++bool UVerseBalanceGauntletController::ConfigureBot(AController& Bot, const FVerseHarnessSlot& Slot, const FString& TierPatchJson,+ FString& OutError)+{+ using namespace VerseBalancePrivate;+ UVerseBotTier* Tier = MakeTier(this, Slot.Tier, Slot.bLearning, TierPatchJson, OutError);+ if (!Tier)+ {+ return false;+ }+ UnitTiers.Add(Tier);+ const bool bTier = CallBotFunction(+ Bot, TEXT("SetTier"),+ [Tier](FProperty& Param, void* Value)+ {+ FObjectPropertyBase* Object = CastField<FObjectPropertyBase>(&Param);+ if (!Object || !Tier->IsA(Object->PropertyClass))+ {+ return false;+ }+ Object->SetObjectPropertyValue(Value, Tier);+ return true;+ },+ true, nullptr, OutError);+ if (!bTier)+ {+ return false;+ }+ const bool bAdaptive = Slot.Tier == TEXT("adaptive");+ return CallBotFunction(+ Bot, TEXT("SetAdaptive"),+ [bAdaptive](FProperty& Param, void* Value)+ {+ FBoolProperty* Flag = CastField<FBoolProperty>(&Param);+ if (!Flag)+ {+ return false;+ }+ Flag->SetPropertyValue(Value, bAdaptive);+ return true;+ },+ true, nullptr, OutError);+}++AController* UVerseBalanceGauntletController::SpawnSlot(const FVerseHarnessSlot& Slot, const FString& TierPatchJson, uint32 SlotSeed,+ FString& OutError)+{+ UWorld* W = World.Get();+ if (!W)+ {+ OutError = TEXT("no game world");+ return nullptr;+ }+ FActorSpawnParameters Params;+ Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;+ if (Slot.IsBot())+ {+ if (UClass* BotClass = FindObject<UClass>(nullptr, VerseBalancePrivate::BotControllerPath))+ {+ AController* Bot = W->SpawnActor<AController>(BotClass, Params);+ if (!Bot)+ {+ OutError = TEXT("cannot spawn ") + BotClass->GetName();+ return nullptr;+ }+ if (!ConfigureBot(*Bot, Slot, TierPatchJson, OutError))+ {+ Bot->Destroy();+ return nullptr;+ }+ return Bot;+ }+ }+ FVersePersonModel Person;+ if (!Slot.Model.IsNone())+ {+ const FVersePersonModel* Found = PersonModels.Models.Find(Slot.Model);+ if (!Found)+ {+ OutError = FString::Printf(TEXT("unknown person model %s"), *Slot.Model.ToString());+ return nullptr;+ }+ Person = *Found;+ }+ else+ {+ // A tier-based model (trick pairings "base hard") or the null-brain stand-in of a bot slot.+ UVerseBotTier* Tier = MakeTier(this, Slot.Tier, Slot.bLearning, TierPatchJson, OutError);+ if (!Tier)+ {+ return nullptr;+ }+ UnitTiers.Add(Tier);+ Person = PersonFromTier(*Tier, Slot.Tier);+ }+ FVerseTrickConfig Trick;+ if (!Slot.Trick.IsNone() && Slot.Trick != TEXT("none"))+ {+ const FVerseTrickConfig* Found = PersonModels.Tricks.Find(Slot.Trick);+ if (!Found)+ {+ OutError = FString::Printf(TEXT("unknown trick %s"), *Slot.Trick.ToString());+ return nullptr;+ }+ Trick = *Found;+ }+ AVerseModelController* Model = W->SpawnActor<AVerseModelController>(Params);+ if (!Model)+ {+ OutError = TEXT("cannot spawn a model controller");+ return nullptr;+ }+ Model->Configure(Person, Trick, SlotSeed);+ FVersePerceptionProfile Profile;+ Profile.Seed = SlotSeed;+ Model->AttachPerception(Feed, Profile);+ return Model;+}++void UVerseBalanceGauntletController::ResolveSpawnPair()+{+ using namespace VerseBalancePrivate;+ UWorld* W = World.Get();+ TArray<APlayerStart*> Starts;+ if (W)+ {+ for (TActorIterator<APlayerStart> It(W); It; ++It)+ {+ Starts.Add(*It);+ }+ }+ Starts.Sort([](const APlayerStart& L, const APlayerStart& R)+ { return L.GetName() < R.GetName(); });+ APlayerStart* Side0 = nullptr;+ APlayerStart* Side1 = nullptr;+ for (APlayerStart* Start : Starts)+ {+ if (!Side0 && Start->PlayerStartTag == TEXT("VerseSide0"))+ {+ Side0 = Start;+ }+ if (!Side1 && Start->PlayerStartTag == TEXT("VerseSide1"))+ {+ Side1 = Start;+ }+ }+ if ((!Side0 || !Side1) && Starts.Num() >= 2)+ {+ Side0 = Starts[0];+ Side1 = nullptr;+ double Best = -1.0;+ for (APlayerStart* Start : Starts)+ {+ const double D = FVector::DistSquared(Start->GetActorLocation(), Side0->GetActorLocation());+ if (Start != Side0 && D > Best)+ {+ Best = D;+ Side1 = Start;+ }+ }+ }+ if (Side0 && Side1)+ {+ SpawnPair[0] = FTransform(Side0->GetActorRotation(), Side0->GetActorLocation());+ SpawnPair[1] = FTransform(Side1->GetActorRotation(), Side1->GetActorLocation());+ return;+ }+ const FVector Base = Starts.Num() ? Starts[0]->GetActorLocation() : FVector(0.0, 0.0, 200.0);+ SpawnPair[0] = FTransform(FRotator::ZeroRotator, Base);+ SpawnPair[1] = FTransform(FRotator(0.0, 180.0, 0.0), Base + FVector(FallbackSpawnGapCm, 0.0, 0.0));+}++void UVerseBalanceGauntletController::RespawnSlot(AController& Controller, const FTransform& Where)+{+ UWorld* W = World.Get();+ if (!W)+ {+ return;+ }+ if (APawn* Old = Controller.GetPawn())+ {+ Controller.UnPossess();+ Old->Destroy();+ }+ Controller.SetControlRotation(Where.Rotator());+ if (AGameModeBase* Mode = W->GetAuthGameMode())+ {+ Mode->RestartPlayerAtTransform(&Controller, Where);+ if (Controller.GetPawn())+ {+ return;+ }+ }+ // No game mode (fixture worlds) or no default pawn: a plain character stands in.+ FActorSpawnParameters Params;+ Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;+ if (ACharacter* Character = W->SpawnActor<ACharacter>(ACharacter::StaticClass(), Where, Params))+ {+ Character->GetCharacterMovement()->GetNavAgentPropertiesRef().bCanCrouch = true;+ Controller.Possess(Character);+ }+}++int32 UVerseBalanceGauntletController::MeasureSpawnSideA() const+{+ const AController* A = GetSlot(0);+ const APawn* Pawn = A ? A->GetPawn() : nullptr;+ if (!Pawn)+ {+ return SpawnSideA;+ }+ const FVector At = Pawn->GetActorLocation();+ return FVector::DistSquared(At, SpawnPair[1].GetLocation()) < FVector::DistSquared(At, SpawnPair[0].GetLocation()) ? 1 : 0;+}++void UVerseBalanceGauntletController::ClearSlots()+{+ for (const TWeakObjectPtr<AController>& Weak : Slots)+ {+ if (AController* Controller = Weak.Get())+ {+ if (AVerseModelController* Model = Cast<AVerseModelController>(Controller))+ {+ Model->DetachPerception();+ }+ if (APawn* Pawn = Controller->GetPawn())+ {+ Pawn->Destroy();+ }+ Controller->Destroy();+ }+ }+ Slots.Reset();+ UnitTiers.Reset();+}++int32 UVerseBalanceGauntletController::PlayerIdOf(const AController* Controller) const+{+ return Controller && Controller->PlayerState ? Controller->PlayerState->GetPlayerId() : INDEX_NONE;+}++void UVerseBalanceGauntletController::BeginUnit()+{+ ++UnitIndex;+ BoutIndex = 0;+ MatchTimeS = 0.0;+ AdaptiveTrace.Reset();+ ClearSlots();+ if (!Scenario.Units.IsValidIndex(UnitIndex))+ {+ Finish(TEXT("all units played"));+ return;+ }+ // A fresh pair of controllers per match: nothing learnt carries over (bot.md 7.3, BG9).+ const FVerseHarnessUnit& Unit = Scenario.Units[UnitIndex];+ FString Error;+ AController* A = SpawnSlot(Unit.A, Unit.TierPatchJson, FVerseRng::Hash(Unit.Seed, 0xA, 0), Error);+ AController* B = A ? SpawnSlot(Unit.B, Unit.TierPatchJson, FVerseRng::Hash(Unit.Seed, 0xB, 0), Error) : nullptr;+ if (A)+ {+ Slots.Add(A);+ }+ if (!A || !B)+ {+ Fail(FString::Printf(TEXT("unit %s#%d: %s"), *Unit.Pairing, Unit.Match, *Error));+ return;+ }+ Slots.Add(B);+ ResolveSpawnPair();+ BeginBout();+}++void UVerseBalanceGauntletController::BeginBout()+{+ const FVerseHarnessUnit& Unit = Scenario.Units[UnitIndex];+ // bot.md 11.1: slots alternate spawn sides per bout. Both pawns are reset every bout.+ SpawnSideA = BoutIndex % 2;+ for (int32 Index = 0; Index < Slots.Num(); ++Index)+ {+ if (AController* Controller = Slots[Index].Get())+ {+ RespawnSlot(*Controller, SpawnPair[(Index + SpawnSideA) % 2]);+ }+ }+ const int32 Measured = MeasureSpawnSideA();+ if (Measured != SpawnSideA)+ {+ UE_LOG(LogVerseHarness, Warning, TEXT("[VerseHarness] bout %d: slot A spawned on side %d, planned %d"), BoutIndex, Measured,+ SpawnSideA);+ SpawnSideA = Measured;+ }+ BoutStartS = Now();+ BoutStartMs = ServerMs();+ const int32 IdA = PlayerIdOf(Slots[0].Get());+ const int32 IdB = PlayerIdOf(Slots[1].Get());+ Recorder = MakeUnique<FVerseBoutRecorder>(IdA, IdB, Unit.KillsToWin, Unit.MatchTimeLimitS);+ Recorder->OnRespawn(IdA, 0.0);+ Recorder->OnRespawn(IdB, 0.0);+ // Destruction resets between bouts through the ruleset's reset (destruction.md 11) once+ // WP06 and WP11 land; the hub carries no reset command the harness could send today.+}++void UVerseBalanceGauntletController::EndBout()+{+ const FVerseHarnessUnit& Unit = Scenario.Units[UnitIndex];+ const double Duration = Now() - BoutStartS;+ const uint32 BoutSeed = FVerseRng::Hash(Unit.Seed, uint32(BoutIndex), 0xB0u);+ FString Line =+ Recorder->ToJsonLine(Unit.Pairing, Unit.Match, BoutIndex, BoutSeed, SpawnSideA, Duration, MatchTimeS, AdaptiveTrace);+ // The server-time window of the bout: balance.py maps fire-audit lines onto bouts with it.+ Line.LeftChopInline(1);+ Line += FString::Printf(TEXT(",\"serverStartMs\":%s,\"serverEndMs\":%s}"), *FVerseJsonWriter::Number(BoutStartMs),+ *FVerseJsonWriter::Number(ServerMs()));+ VerseBalancePrivate::AppendLine(BoutsFile, Line);+ MatchTimeS += Duration;+ AdaptiveTrace.Reset();+ ++BoutIndex;+ if (BoutIndex >= Unit.Bouts)+ {+ BeginUnit();+ }+ else+ {+ BeginBout();+ }+}++bool UVerseBalanceGauntletController::Tick()+{+ if (bFinished)+ {+ return false;+ }+ ++Ticks;+ if (Scenario.MaxWallS > 0.0 && FPlatformTime::Seconds() - WallStartS > Scenario.MaxWallS)+ {+ Finish(TEXT("wall-clock guard reached"));+ return false;+ }+ if (!Recorder)+ {+ return !bFinished;+ }+ // Model slots perceive and act once per server tick (bot slots run their own perception).+ Feed->Tick(World.Get());+ const double T = Now() - BoutStartS;+ for (int32 Index = 0; Index < Slots.Num(); ++Index)+ {+ const AController* Controller = Slots[Index].Get();+ const APawn* Pawn = Controller ? Controller->GetPawn() : nullptr;+ Recorder->SamplePosition(Index == 0 ? EVerseSide::A : EVerseSide::B, Pawn ? Pawn->GetActorLocation() : FVector::ZeroVector,+ Pawn != nullptr, T);+ }+ if (Recorder->IsOver(T))+ {+ EndBout();+ }+ return !bFinished;+}++void UVerseBalanceGauntletController::ReadAdaptive()+{+ // s of the adaptive bot through the frozen AVerseBotController::GetEffectiveSkill() (bot.md 9.2).+ for (const TWeakObjectPtr<AController>& Weak : Slots)+ {+ AController* Controller = Weak.Get();+ if (!Controller || Controller->IsA<AVerseModelController>())+ {+ continue;+ }+ float Skill = 0.f;+ FString Error;+ if (VerseBalancePrivate::CallBotFunction(*Controller, TEXT("GetEffectiveSkill"), [](FProperty&, void*)+ { return true; }, false, &Skill, Error))+ {+ AdaptiveTrace.Add(Skill);+ }+ else if (!bWarnedNoSkill)+ {+ bWarnedNoSkill = true;+ UE_LOG(LogVerseHarness, Warning, TEXT("[VerseHarness] no adaptive trace: %s"), *Error);+ }+ }+}++void UVerseBalanceGauntletController::HandleFire(const FVerseFireEvent& Event)+{+ if (Recorder)+ {+ Recorder->OnFire(Event, Now() - BoutStartS);+ }+}++void UVerseBalanceGauntletController::HandleHit(const FVerseHitEvent& Event)+{+ if (Recorder)+ {+ Recorder->OnHit(Event, Now() - BoutStartS);+ }+}++void UVerseBalanceGauntletController::HandleDeath(const FVerseDeathEvent& Event)+{+ if (!Recorder)+ {+ return;+ }+ Recorder->OnDeath(Event, Now() - BoutStartS);+ ReadAdaptive();+ // The ruleset respawns after 3 s (combat-state.md 9.1); RespawnAt is server time.+ Recorder->OnRespawn(Event.VictimId, FMath::Max(0.0, double(Event.RespawnAt) - BoutStartS));+}++void UVerseBalanceGauntletController::HandleReload(const FVerseReloadEvent& Event)+{+ if (Recorder)+ {+ Recorder->OnReload(Event, Now() - BoutStartS);+ }+}++void UVerseBalanceGauntletController::HandleGadget(const FVerseGadgetEvent& Event)+{+ if (Recorder)+ {+ Recorder->OnGadget(Event, Now() - BoutStartS);+ }+}++void UVerseBalanceGauntletController::Fail(const FString& Why)+{+ UE_LOG(LogVerseHarness, Error, TEXT("[VerseHarness] run failed: %s"), *Why);+ bFailed = true;+ const FString Reason = TEXT("failed: ") + Why;+ Finish(*Reason);+}++void UVerseBalanceGauntletController::Finish(const TCHAR* Why)+{+ if (bFinished)+ {+ return;+ }+ bFinished = true;+ EndReason = Why;+ const int32 UnitsStarted = FMath::Clamp(UnitIndex + (bFailed ? 1 : 0), 0, Scenario.Units.Num());+ ClearSlots();+ Recorder.Reset();+ if (UVerseEventHub* Hub = UVerseEventHub::Get(World.Get()))+ {+ Hub->OnFire.RemoveAll(this);+ Hub->OnHit.RemoveAll(this);+ Hub->OnDeath.RemoveAll(this);+ Hub->OnReload.RemoveAll(this);+ Hub->OnGadget.RemoveAll(this);+ }+ const double WallS = FPlatformTime::Seconds() - WallStartS;+ const double SimS = Now() - SimStartS;+ FVerseJsonWriter Speed;+ Speed.Str(TEXT("schema"), TEXT("verse.speed/1"))+ .Str(TEXT("run"), Scenario.Run)+ .Num(TEXT("job"), Scenario.Job)+ .Num(TEXT("simS"), SimS)+ .Num(TEXT("wallS"), WallS)+ .Num(TEXT("startupS"), StartupS)+ .Num(TEXT("ticks"), double(Ticks))+ .Num(TEXT("xRealTime"), WallS > 0.0 ? SimS / WallS : 0.0)+ .Num(TEXT("peakRamMb"), double(FPlatformMemory::GetStats().PeakUsedPhysical) / (1024.0 * 1024.0))+ .Str(TEXT("botController"), BotControllerKind)+ .Str(TEXT("end"), Why)+ .Bool(TEXT("failed"), bFailed)+ .Num(TEXT("unitsPlanned"), Scenario.Units.Num())+ .Num(TEXT("unitsFinished"), bFailed ? FMath::Max(0, UnitsStarted - 1) : FMath::Min(UnitIndex, Scenario.Units.Num()));+ const FString Text = Speed.Close();+ FFileHelper::SaveStringToFile(Text, *FPaths::Combine(Scenario.OutputDir, TEXT("speed.json")),+ FFileHelper::EEncodingOptions::ForceUTF8WithoutBOM);+ UE_LOG(LogVerseHarness, Display, TEXT("[VerseHarness] done (%s): %.1f s simulated in %.1f s wall, %.1fx real time"), Why, SimS,+ WallS, WallS > 0.0 ? SimS / WallS : 0.0);+}diff --git a/unreal/Verse/Source/VerseHarness/Private/Balance/VerseBoutRecorder.cpp b/unreal/Verse/Source/VerseHarness/Private/Balance/VerseBoutRecorder.cppnew file mode 100644index 0000000000..871d9c6057--- /dev/null+++ b/unreal/Verse/Source/VerseHarness/Private/Balance/VerseBoutRecorder.cpp@@ -0,0 +1,280 @@+#include "Balance/VerseBoutRecorder.h"++#include "VerseHarnessJson.h"++namespace VerseBoutPrivate+{+ const TCHAR* CauseName(EVerseDamageSource Cause)+ {+ switch (Cause)+ {+ case EVerseDamageSource::Melee:+ return TEXT("melee");+ case EVerseDamageSource::Finisher:+ return TEXT("finisher");+ case EVerseDamageSource::Gadget:+ return TEXT("gadget");+ case EVerseDamageSource::World:+ return TEXT("world");+ default:+ return TEXT("bolt");+ }+ }++ int32 Index(EVerseSide Side) { return Side == EVerseSide::A ? 0 : 1; }++ FString SideJson(const FVerseBoutSide& S)+ {+ FVerseJsonWriter O;+ O.Num(TEXT("kills"), S.Kills)+ .Num(TEXT("deaths"), S.Deaths)+ .Num(TEXT("shots"), S.Shots)+ .Num(TEXT("hits"), S.Hits)+ .Num(TEXT("headshotHits"), S.HeadshotHits)+ .Numbers(TEXT("timeToContactS"), S.TimeToContactS)+ .Num(TEXT("bulwarkUses"), S.BulwarkUses)+ .Num(TEXT("breachUses"), S.BreachUses)+ .Num(TEXT("reloadsInFight"), S.ReloadsInFight)+ .Num(TEXT("stuckEvents"), S.StuckEvents)+ .Raw(TEXT("fireAudit"), TEXT("{}"))+ // Bot timing and nav health come from VerseBot once it lands (WP08); unknown until then.+ .Null(TEXT("botMsP99"))+ .Null(TEXT("navFailures"));+ return O.Close();+ }+}++FVerseBoutRecorder::FVerseBoutRecorder(int32 InPlayerIdA, int32 InPlayerIdB, int32 InKillsToWin, double InTimeLimitS)+ : PlayerIdA(InPlayerIdA)+ , PlayerIdB(InPlayerIdB)+ , KillsToWin(InKillsToWin)+ , TimeLimitS(InTimeLimitS)+{+}++EVerseSide FVerseBoutRecorder::SideOf(int32 PlayerId) const+{+ if (PlayerId == PlayerIdA)+ {+ return EVerseSide::A;+ }+ if (PlayerId == PlayerIdB)+ {+ return EVerseSide::B;+ }+ return EVerseSide::None;+}++void FVerseBoutRecorder::Contact(EVerseSide S, double T)+{+ FVerseBoutSide& Side = Mutable(S);+ if (!Side.bContactThisLife)+ {+ Side.bContactThisLife = true;+ Side.TimeToContactS.Add(float(FMath::Max(0.0, T - Side.LifeStartS)));+ }+ Side.LastFightS = T;+}++void FVerseBoutRecorder::OnFire(const FVerseFireEvent& Event, double T)+{+ const EVerseSide S = SideOf(Event.ShooterId);+ if (S != EVerseSide::None)+ {+ Mutable(S).Shots++;+ }+}++void FVerseBoutRecorder::OnHit(const FVerseHitEvent& Event, double T)+{+ const EVerseSide Shooter = SideOf(Event.InstigatorId);+ const EVerseSide Victim = SideOf(Event.VictimId);+ if (Shooter == EVerseSide::None || Victim == EVerseSide::None || Shooter == Victim)+ {+ return;+ }+ FVerseBoutSide& S = Mutable(Shooter);+ S.Hits++;+ S.HeadshotHits += Event.bHeadshot ? 1 : 0;+ FVerseBoutSide& V = Mutable(Victim);+ if (V.FirstHitTakenS < 0.0)+ {+ V.FirstHitTakenS = T;+ }+ Contact(Shooter, T);+ Contact(Victim, T);+ const int32 VI = VerseBoutPrivate::Index(Victim);+ LastHitOn[VI] = Event;+ bHasLastHit[VI] = true;+}++void FVerseBoutRecorder::OnDeath(const FVerseDeathEvent& Event, double T)+{+ const EVerseSide Victim = SideOf(Event.VictimId);+ if (Victim == EVerseSide::None)+ {+ return;+ }+ const EVerseSide Killer = SideOf(Event.KillerId);+ FVerseBoutSide& V = Mutable(Victim);+ V.Deaths++;+ if (Killer != EVerseSide::None && Killer != Victim)+ {+ Mutable(Killer).Kills++;+ FVerseBoutKill Kill;+ Kill.T = T;+ Kill.Killer = Killer;+ Kill.Cause = Event.Cause;+ const int32 VI = VerseBoutPrivate::Index(Victim);+ if (bHasLastHit[VI])+ {+ const FVerseHitEvent& Hit = LastHitOn[VI];+ Kill.bHeadshot = Hit.bHeadshot != 0 || Event.LastZone == EVerseHitZone::Head;+ Kill.bWall = Hit.PenetrationCount > 0;+ Kill.RangeM = Hit.DistanceM;+ }+ else+ {+ Kill.bHeadshot = Event.LastZone == EVerseHitZone::Head;+ }+ if (V.FirstHitTakenS >= 0.0)+ {+ Kill.TtkS = float(T - V.FirstHitTakenS);+ }+ Kill.bSpawnKill = T - V.LifeStartS <= SpawnKillWindowS;+ KillList.Add(Kill);+ }+ const int32 VI = VerseBoutPrivate::Index(Victim);+ bHasLastHit[VI] = false;+ V.FirstHitTakenS = -1.0;+ V.bHasPosition = false;+}++void FVerseBoutRecorder::OnRespawn(int32 PlayerId, double T)+{+ const EVerseSide S = SideOf(PlayerId);+ if (S == EVerseSide::None)+ {+ return;+ }+ FVerseBoutSide& Side = Mutable(S);+ Side.LifeStartS = T;+ Side.bContactThisLife = false;+ Side.FirstHitTakenS = -1.0;+ Side.bHasPosition = false;+}++void FVerseBoutRecorder::OnReload(const FVerseReloadEvent& Event, double T)+{+ const EVerseSide S = SideOf(Event.PlayerId);+ if (S != EVerseSide::None && !Event.bCancelled && T - Side(S).LastFightS <= FightWindowS)+ {+ Mutable(S).ReloadsInFight++;+ }+}++void FVerseBoutRecorder::OnGadget(const FVerseGadgetEvent& Event, double T)+{+ const EVerseSide S = SideOf(Event.OwnerId);+ if (S == EVerseSide::None)+ {+ return;+ }+ const FString Id = Event.GadgetId.ToString();+ if (Event.Kind == EVerseGadgetEventKind::Deploy && Id.Contains(TEXT("Bulwark")))+ {+ Mutable(S).BulwarkUses++;+ }+ else if (Event.Kind == EVerseGadgetEventKind::Plant && Id.Contains(TEXT("Breach")))+ {+ Mutable(S).BreachUses++;+ }+}++void FVerseBoutRecorder::SamplePosition(EVerseSide S, const FVector& Location, bool bAlive, double T)+{+ if (S == EVerseSide::None)+ {+ return;+ }+ FVerseBoutSide& Side = Mutable(S);+ if (!bAlive || !Side.bHasPosition)+ {+ Side.bHasPosition = bAlive;+ Side.LastMovedFrom = Location;+ Side.LastMovedS = T;+ return;+ }+ if (FVector::Dist(Location, Side.LastMovedFrom) > StuckDistanceCm)+ {+ Side.LastMovedFrom = Location;+ Side.LastMovedS = T;+ }+ else if (T - Side.LastMovedS >= StuckAfterS)+ {+ Side.StuckEvents++;+ Side.LastMovedS = T;+ }+}++bool FVerseBoutRecorder::IsOver(double T) const+{+ return SideA.Kills >= KillsToWin || SideB.Kills >= KillsToWin || T >= TimeLimitS;+}++EVerseSide FVerseBoutRecorder::Winner() const+{+ if (SideA.Kills > SideB.Kills)+ {+ return EVerseSide::A;+ }+ if (SideB.Kills > SideA.Kills)+ {+ return EVerseSide::B;+ }+ return EVerseSide::None;+}++FString FVerseBoutRecorder::ToJsonLine(const FString& Pairing, int32 Match, int32 Bout, uint32 Seed,+ int32 SpawnSideA, double DurationS, double MatchTimeStartS, const TArray<float>& AdaptiveTrace) const+{+ using namespace VerseBoutPrivate;++ const auto Ms = [](double V) { return FMath::RoundToDouble(V * 1000.0) / 1000.0; };+ TArray<FString> KillValues;+ for (const FVerseBoutKill& K : KillList)+ {+ FVerseJsonWriter O;+ O.Num(TEXT("t"), Ms(K.T))+ .Str(TEXT("killer"), K.Killer == EVerseSide::A ? TEXT("A") : TEXT("B"))+ .Str(TEXT("cause"), CauseName(K.Cause))+ .Bool(TEXT("headshot"), K.bHeadshot)+ .Bool(TEXT("wall"), K.bWall);+ if (K.RangeM >= 0.f)+ {+ O.Num(TEXT("rangeM"), K.RangeM);+ }+ if (K.TtkS >= 0.f)+ {+ O.Num(TEXT("ttkS"), K.TtkS);+ }+ O.Bool(TEXT("spawnKill"), K.bSpawnKill);+ KillValues.Add(O.Close());+ }+ const EVerseSide W = Winner();+ FVerseJsonWriter Root;+ Root.Str(TEXT("schema"), TEXT("verse.bout/1"))+ .Str(TEXT("pairing"), Pairing)+ .Num(TEXT("match"), Match)+ .Num(TEXT("bout"), Bout)+ .Num(TEXT("seed"), Seed)+ .Num(TEXT("spawnSideA"), SpawnSideA)+ .Str(TEXT("winner"), W == EVerseSide::A ? TEXT("A") : (W == EVerseSide::B ? TEXT("B") : TEXT("none")))+ .Num(TEXT("durationS"), Ms(DurationS))+ .Num(TEXT("matchTimeStartS"), Ms(MatchTimeStartS))+ .Raw(TEXT("kills"), TEXT("[") + FString::Join(KillValues, TEXT(",")) + TEXT("]"))+ .Raw(TEXT("a"), SideJson(SideA))+ .Raw(TEXT("b"), SideJson(SideB))+ .Numbers(TEXT("adaptiveTrace"), AdaptiveTrace);+ return Root.Close();+}diff --git a/unreal/Verse/Source/VerseHarness/Private/Balance/VerseHarnessPerceptFeed.cpp b/unreal/Verse/Source/VerseHarness/Private/Balance/VerseHarnessPerceptFeed.cppnew file mode 100644index 0000000000..e06762f425--- /dev/null+++ b/unreal/Verse/Source/VerseHarness/Private/Balance/VerseHarnessPerceptFeed.cpp@@ -0,0 +1,74 @@+#include "Balance/VerseHarnessPerceptFeed.h"++#include "Engine/World.h"+#include "GameFramework/Character.h"+#include "GameFramework/Controller.h"+#include "GameFramework/Pawn.h"++void UVerseHarnessPerceptFeed::RegisterObserver(AController* Observer, const FVersePerceptionProfile& Profile)+{+ // The null perception has no error model, so the profile (hearing, acquisition, seed) is unused.+ if (Observer && !IsObserving(Observer))+ {+ Observers.Add(Observer);+ }+}++void UVerseHarnessPerceptFeed::UnregisterObserver(AController* Observer)+{+ Observers.RemoveAll([Observer](const TWeakObjectPtr<AController>& Weak)+ { return !Weak.IsValid() || Weak.Get() == Observer; });+}++bool UVerseHarnessPerceptFeed::IsObserving(const AController* Observer) const+{+ return Observers.ContainsByPredicate([Observer](const TWeakObjectPtr<AController>& Weak)+ { return Weak.Get() == Observer; });+}++FVerseSelfPercept UVerseHarnessPerceptFeed::SelfOf(const AController& Observer)+{+ FVerseSelfPercept Self;+ Self.ViewRotation = Observer.GetControlRotation();+ const APawn* Own = Observer.GetPawn();+ if (!Own)+ {+ Self.Phase = EVerseCombatPhase::Dead;+ return Self;+ }+ Self.Phase = EVerseCombatPhase::Alive;+ Self.Location = Own->GetActorLocation();+ Self.Velocity = Own->GetVelocity();+ FRotator EyeRotation;+ Own->GetActorEyesViewPoint(Self.EyeLocation, EyeRotation);+ if (const ACharacter* Character = Cast<ACharacter>(Own))+ {+ Self.Stance = Character->bIsCrouched ? EVerseStance::Crouch : EVerseStance::Stand;+ }+ return Self;+}++void UVerseHarnessPerceptFeed::Tick(UWorld* World)+{+ if (!World)+ {+ return;+ }+ const uint32 ServerTimeMs = uint32(FMath::Max(0.0, World->GetTimeSeconds()) * 1000.0);+ // Copy: a handler may unregister (a slot destroyed mid-bout).+ const TArray<TWeakObjectPtr<AController>> Snapshot = Observers;+ for (const TWeakObjectPtr<AController>& Weak : Snapshot)+ {+ AController* Observer = Weak.Get();+ if (!Observer)+ {+ continue;+ }+ FVersePerceptFrame Frame;+ Frame.ServerTimeMs = ServerTimeMs;+ Frame.Self = SelfOf(*Observer);+ OnPerceptFrame.Broadcast(Observer, Frame);+ }+ Observers.RemoveAll([](const TWeakObjectPtr<AController>& Weak)+ { return !Weak.IsValid(); });+}diff --git a/unreal/Verse/Source/VerseHarness/Private/Balance/VerseHarnessScenario.cpp b/unreal/Verse/Source/VerseHarness/Private/Balance/VerseHarnessScenario.cppnew file mode 100644index 0000000000..3396bfeabb--- /dev/null+++ b/unreal/Verse/Source/VerseHarness/Private/Balance/VerseHarnessScenario.cpp@@ -0,0 +1,145 @@+#include "Balance/VerseHarnessScenario.h"++#include "VerseHarnessJson.h"++namespace VerseHarnessScenarioPrivate+{+ bool ParseSlot(const FVerseJson* Obj, FVerseHarnessSlot& Out, FString& OutError)+ {+ if (!Obj || !Obj->IsObject())+ {+ OutError = TEXT("slot is not an object");+ return false;+ }+ const FString Kind = Obj->StringOr(TEXT("kind"));+ if (Kind == TEXT("bot"))+ {+ Out.Kind = EVerseHarnessSlotKind::Bot;+ }+ else if (Kind == TEXT("model"))+ {+ Out.Kind = EVerseHarnessSlotKind::Model;+ }+ else+ {+ OutError = FString::Printf(TEXT("unknown slot kind '%s'"), *Kind);+ return false;+ }+ FString Text;+ if (Obj->TryString(TEXT("tier"), Text))+ {+ Out.Tier = FName(*Text);+ }+ if (Obj->TryString(TEXT("model"), Text))+ {+ Out.Model = FName(*Text);+ }+ if (Obj->TryString(TEXT("trick"), Text))+ {+ Out.Trick = FName(*Text);+ }+ Obj->TryBool(TEXT("learning"), Out.bLearning);+ if (Out.IsBot() && Out.Tier.IsNone())+ {+ OutError = TEXT("a bot slot needs a tier");+ return false;+ }+ if (!Out.IsBot() && Out.Model.IsNone() && Out.Tier.IsNone())+ {+ OutError = TEXT("a model slot needs a model or a base tier");+ return false;+ }+ return true;+ }+}++FString FVerseHarnessSlot::Label() const+{+ if (IsBot())+ {+ return bLearning ? Tier.ToString() : Tier.ToString() + TEXT("-nolearn");+ }+ if (!Trick.IsNone())+ {+ return Model.IsNone() ? Trick.ToString() : Model.ToString() + TEXT("+") + Trick.ToString();+ }+ return Model.IsNone() ? Tier.ToString() : Model.ToString();+}++bool FVerseHarnessScenario::Parse(const FString& JsonText, FVerseHarnessScenario& Out, FString& OutError)+{+ using namespace VerseHarnessScenarioPrivate;++ const TSharedPtr<FVerseJson> Root = FVerseJson::Parse(JsonText, OutError);+ if (!Root.IsValid() || !Root->IsObject())+ {+ OutError = TEXT("not a JSON object: ") + OutError;+ return false;+ }+ if (Root->StringOr(TEXT("schema")) != TEXT("verse.scenario/1"))+ {+ OutError = TEXT("schema is not verse.scenario/1");+ return false;+ }+ Out = FVerseHarnessScenario();+ Out.Run = Root->StringOr(TEXT("run"));+ Out.Map = Root->StringOr(TEXT("map"));+ Out.OutputDir = Root->StringOr(TEXT("output"));+ Root->TryInt(TEXT("job"), Out.Job);+ Root->TryNumber(TEXT("maxWallS"), Out.MaxWallS);+ if (const FVerseJson* Trace = Root->ObjectField(TEXT("trace")))+ {+ Trace->TryBool(TEXT("bearing"), Out.bTraceBearing);+ Trace->TryBool(TEXT("fireAudit"), Out.bTraceFireAudit);+ }+ if (Out.Run.IsEmpty() || Out.OutputDir.IsEmpty() || Out.Map.IsEmpty())+ {+ OutError = TEXT("run, map and output are required");+ return false;+ }+ const TArray<TSharedPtr<FVerseJson>>* Units = Root->ArrayField(TEXT("units"));+ if (!Units || Units->Num() == 0)+ {+ OutError = TEXT("units must be a non-empty array");+ return false;+ }+ for (const TSharedPtr<FVerseJson>& U : *Units)+ {+ if (!U.IsValid() || !U->IsObject())+ {+ OutError = TEXT("a unit is not an object");+ return false;+ }+ FVerseHarnessUnit Unit;+ Unit.Pairing = U->StringOr(TEXT("pairing"));+ U->TryString(TEXT("set"), Unit.Set);+ U->TryInt(TEXT("match"), Unit.Match);+ double Seed = 0.0;+ U->TryNumber(TEXT("seed"), Seed);+ Unit.Seed = uint32(FMath::Clamp(Seed, 0.0, 4294967295.0));+ U->TryInt(TEXT("bouts"), Unit.Bouts);+ U->TryInt(TEXT("killsToWin"), Unit.KillsToWin);+ U->TryNumber(TEXT("matchTimeLimitS"), Unit.MatchTimeLimitS);+ FString Scenario;+ if (U->TryString(TEXT("scenario"), Scenario))+ {+ Unit.Scenario = FName(*Scenario);+ }+ if (const FVerseJson* Patch = U->ObjectField(TEXT("tierPatch")))+ {+ Unit.TierPatchJson = Patch->ToString();+ }+ if (!ParseSlot(U->Find(TEXT("a")), Unit.A, OutError) || !ParseSlot(U->Find(TEXT("b")), Unit.B, OutError))+ {+ OutError = FString::Printf(TEXT("unit %s: %s"), *Unit.Pairing, *OutError);+ return false;+ }+ if (Unit.Pairing.IsEmpty() || Unit.Bouts < 1 || Unit.KillsToWin < 1 || Unit.MatchTimeLimitS <= 0.0)+ {+ OutError = FString::Printf(TEXT("unit %s has an empty id, no bouts or no limits"), *Unit.Pairing);+ return false;+ }+ Out.Units.Add(MoveTemp(Unit));+ }+ return true;+}diff --git a/unreal/Verse/Source/VerseHarness/Private/Balance/VerseModelController.cpp b/unreal/Verse/Source/VerseHarness/Private/Balance/VerseModelController.cppnew file mode 100644index 0000000000..4ea172affb--- /dev/null+++ b/unreal/Verse/Source/VerseHarness/Private/Balance/VerseModelController.cpp@@ -0,0 +1,171 @@+#include "Balance/VerseModelController.h"++#include "Balance/VerseHarnessPerceptFeed.h"+#include "GameFramework/Character.h"+#include "GameFramework/CharacterMovementComponent.h"+#include "GameFramework/Pawn.h"++AVerseModelController::AVerseModelController()+{+ PrimaryActorTick.bCanEverTick = false;+ Brain = [](const FVersePerceptFrame&) { return FVerseInputFrame(); };+}++void AVerseModelController::PostInitializeComponents()+{+ Super::PostInitializeComponents();+ // A harness slot is a player: it needs a player state for its id and the scoreboard.+ if (HasAuthority())+ {+ InitPlayerState();+ }+}++void AVerseModelController::Destroyed()+{+ DetachPerception();+ Super::Destroyed();+}++void AVerseModelController::AttachPerception(UVerseHarnessPerceptFeed* Feed, const FVersePerceptionProfile& Profile)+{+ DetachPerception();+ if (!Feed)+ {+ return;+ }+ PerceptSource = Feed;+ PerceptHandle = Feed->OnPerceptFrame.AddUObject(this, &AVerseModelController::HandlePerceptFrame);+ Feed->RegisterObserver(this, Profile);+}++void AVerseModelController::DetachPerception()+{+ if (UVerseHarnessPerceptFeed* Feed = PerceptSource.Get())+ {+ Feed->OnPerceptFrame.Remove(PerceptHandle);+ Feed->UnregisterObserver(this);+ }+ PerceptSource.Reset();+ PerceptHandle.Reset();+}++void AVerseModelController::HandlePerceptFrame(AController* Observer, const FVersePerceptFrame& Percepts)+{+ if (Observer != this)+ {+ return;+ }+ const double NowS = double(Percepts.ServerTimeMs) / 1000.0;+ const float DeltaS = LastFrameS >= 0.0 ? float(FMath::Max(0.0, NowS - LastFrameS)) : 0.f;+ LastFrameS = NowS;+ const FVerseInputFrame Input = Think(Percepts, NowS, DeltaS);+ ++FramesThought;+ if (APawn* Own = GetPawn())+ {+ ApplyInputToPawn(*this, *Own, Input);+ }+}++void AVerseModelController::ApplyInputToPawn(AController& Controller, APawn& Pawn, const FVerseInputFrame& Input)+{+ FRotator Control = Controller.GetControlRotation();+ Control.Pitch = FMath::ClampAngle(FRotator::NormalizeAxis(Control.Pitch + Input.LookDeltaDeg.X), -89.f, 89.f);+ Control.Yaw = FRotator::NormalizeAxis(Control.Yaw + Input.LookDeltaDeg.Y);+ Control.Roll = 0.f;+ Controller.SetControlRotation(Control);++ const FRotator Yaw(0.f, Control.Yaw, 0.f);+ const FRotationMatrix Basis(Yaw);+ FVector2f Move = Input.Move;+ if (Move.SizeSquared() > 1.f)+ {+ Move.Normalize();+ }+ if (!Move.IsNearlyZero())+ {+ Pawn.AddMovementInput(Basis.GetUnitAxis(EAxis::X) * Move.X + Basis.GetUnitAxis(EAxis::Y) * Move.Y, 1.f);+ }++ ACharacter* Character = Cast<ACharacter>(&Pawn);+ if (!Character)+ {+ return;+ }+ if (Input.Pressed & uint32(EVerseInputButton::Jump))+ {+ Character->Jump();+ }+ else if (!(Input.Buttons & uint32(EVerseInputButton::Jump)))+ {+ Character->StopJumping();+ }+ const bool bLow = (Input.Buttons & (uint32(EVerseInputButton::Crouch) | uint32(EVerseInputButton::Prone))) != 0;+ const UCharacterMovementComponent* Movement = Character->GetCharacterMovement();+ const bool bWantsLow = Character->bIsCrouched || (Movement && Movement->bWantsToCrouch);+ if (bLow && !bWantsLow)+ {+ Character->Crouch();+ }+ else if (!bLow && bWantsLow)+ {+ Character->UnCrouch();+ }+}++void AVerseModelController::Configure(const FVersePersonModel& InModel, const FVerseTrickConfig& InTrick, uint32 InSeed)+{+ Model = InModel;+ TrickConfig = InTrick;+ Seed = InSeed;+ ResetMatchMemory();+}++void AVerseModelController::SetBrain(FBrain InBrain)+{+ Brain = InBrain ? MoveTemp(InBrain) : FBrain([](const FVersePerceptFrame&) { return FVerseInputFrame(); });+}++void AVerseModelController::ResetMatchMemory()+{+ TrickState = FVerseTrickState();+ Rng = FVerseRng(Seed, 0, EVerseRngSalt::Harness);+ LastInput = FVerseInputFrame();+ bSawLastTick = false;+ ReactUntilS = 0.0;+ LastFrameS = -1.0;+ FramesThought = 0;+}++FVerseInputFrame AVerseModelController::ApplyPersonLimits(const FVersePersonModel& InModel,+ const FVerseInputFrame& InBrain, bool bReacting, float DeltaS)+{+ FVerseInputFrame Out = InBrain;+ if (bReacting)+ {+ // Before the reaction time has passed the person has not processed the sighting yet.+ Out.Buttons &= ~(uint32(EVerseInputButton::Fire) | uint32(EVerseInputButton::Ads));+ Out.LookDeltaDeg = FVector2f::ZeroVector;+ }+ const float MaxTurn = InModel.TurnRateDegS * FMath::Max(DeltaS, 0.f);+ Out.LookDeltaDeg.X = FMath::Clamp(Out.LookDeltaDeg.X, -MaxTurn, MaxTurn);+ Out.LookDeltaDeg.Y = FMath::Clamp(Out.LookDeltaDeg.Y, -MaxTurn, MaxTurn);+ return Out;+}++FVerseInputFrame AVerseModelController::Think(const FVersePerceptFrame& Percepts, double NowS, float DeltaS)+{+ const bool bSees = FVerseTrickOverrides::AnySighting(Percepts);+ if (bSees && !bSawLastTick)+ {+ const double ReactionMs = FMath::Max(80.0, Rng.Gaussian(Model.ReactionMeanMs, Model.ReactionSdMs));+ ReactUntilS = NowS + ReactionMs / 1000.0;+ }+ bSawLastTick = bSees;++ const FVerseInputFrame FromBrain = Brain(Percepts);+ const FVerseInputFrame Limited = ApplyPersonLimits(Model, FromBrain, IsReacting(NowS), DeltaS);+ LastInput = FVerseTrickOverrides::Apply(TrickConfig, Percepts, Limited, TrickState, Rng, NowS);+ LastInput.ServerTimeMs = Percepts.ServerTimeMs;+ return LastInput;+}diff --git a/unreal/Verse/Source/VerseHarness/Private/Balance/VersePersonModels.cpp b/unreal/Verse/Source/VerseHarness/Private/Balance/VersePersonModels.cppnew file mode 100644index 0000000000..13d6a4c99d--- /dev/null+++ b/unreal/Verse/Source/VerseHarness/Private/Balance/VersePersonModels.cpp@@ -0,0 +1,169 @@+#include "Balance/VersePersonModels.h"++#include "Misc/FileHelper.h"+#include "Misc/Paths.h"+#include "VerseHarnessJson.h"++namespace VersePersonModelsPrivate+{+ struct FTrickName+ {+ EVerseTrick Trick;+ const TCHAR* Name;+ };++ // The frozen trick ids of bot.md 11.2.+ const FTrickName TrickNames[] = {+ {EVerseTrick::Spray, TEXT("spray")},+ {EVerseTrick::Camper, TEXT("camper")},+ {EVerseTrick::Rusher, TEXT("rusher")},+ {EVerseTrick::Slider, TEXT("slider")},+ {EVerseTrick::JumpPeek, TEXT("jumppeek")},+ {EVerseTrick::LeanSpam, TEXT("leanspam")},+ {EVerseTrick::Prone, TEXT("prone")},+ {EVerseTrick::WallSpam, TEXT("wallspam")},+ {EVerseTrick::Turtle, TEXT("turtle")},+ {EVerseTrick::Breacher, TEXT("breacher")},+ {EVerseTrick::Knife, TEXT("knife")},+ {EVerseTrick::Finisher, TEXT("finisher")},+ {EVerseTrick::Kiter, TEXT("kiter")},+ {EVerseTrick::Watcher, TEXT("watcher")},+ {EVerseTrick::Silent, TEXT("silent")},+ {EVerseTrick::Repeek, TEXT("repeek")},+ {EVerseTrick::Hider, TEXT("hider")},+ };+ static_assert(UE_ARRAY_COUNT(TrickNames) == VerseTrickCount, "one name per trick");++ float Num(const FVerseJson* Obj, const TCHAR* Field, float Default)+ {+ double Value = Default;+ return Obj && Obj->TryNumber(Field, Value) ? float(Value) : Default;+ }++ bool Flag(const FVerseJson* Obj, const TCHAR* Field)+ {+ bool Value = false;+ return Obj && Obj->TryBool(Field, Value) && Value;+ }+}++bool VerseTrickFromName(FName Name, EVerseTrick& OutTrick)+{+ for (const VersePersonModelsPrivate::FTrickName& Entry : VersePersonModelsPrivate::TrickNames)+ {+ if (Name == FName(Entry.Name))+ {+ OutTrick = Entry.Trick;+ return true;+ }+ }+ OutTrick = EVerseTrick::None;+ return Name.IsNone();+}++FName VerseTrickName(EVerseTrick Trick)+{+ for (const VersePersonModelsPrivate::FTrickName& Entry : VersePersonModelsPrivate::TrickNames)+ {+ if (Entry.Trick == Trick)+ {+ return FName(Entry.Name);+ }+ }+ return NAME_None;+}++FString FVersePersonModelSet::DefaultPath()+{+ return FPaths::Combine(FPaths::ProjectDir(), TEXT("Data"), TEXT("bot"), TEXT("person_models.json"));+}++bool FVersePersonModelSet::LoadDefault(FVersePersonModelSet& Out, FString& OutError)+{+ FString Text;+ if (!FFileHelper::LoadFileToString(Text, *DefaultPath()))+ {+ OutError = FString::Printf(TEXT("cannot read %s"), *DefaultPath());+ return false;+ }+ return Parse(Text, Out, OutError);+}++bool FVersePersonModelSet::Parse(const FString& JsonText, FVersePersonModelSet& Out, FString& OutError)+{+ using namespace VersePersonModelsPrivate;++ const TSharedPtr<FVerseJson> Root = FVerseJson::Parse(JsonText, OutError);+ if (!Root.IsValid() || !Root->IsObject())+ {+ OutError = TEXT("person_models.json is not a JSON object: ") + OutError;+ return false;+ }+ if (Root->StringOr(TEXT("schema")) != TEXT("verse.person_models/1"))+ {+ OutError = TEXT("schema is not verse.person_models/1");+ return false;+ }+ Out = FVersePersonModelSet();+ const FVerseJson* Models = Root->ObjectField(TEXT("models"));+ const FVerseJson* Tricks = Root->ObjectField(TEXT("tricks"));+ if (!Models || !Tricks)+ {+ OutError = TEXT("models and tricks are required");+ return false;+ }+ for (const TPair<FString, TSharedPtr<FVerseJson>>& Pair : Models->Object)+ {+ const FVerseJson* M = Pair.Value.Get();+ FVersePersonModel Model;+ Model.Name = FName(*Pair.Key);+ Model.ReactionMeanMs = Num(M, TEXT("reactionMeanMs"), Model.ReactionMeanMs);+ Model.ReactionSdMs = Num(M, TEXT("reactionSdMs"), Model.ReactionSdMs);+ Model.TurnRateDegS = Num(M, TEXT("turnRateDegS"), Model.TurnRateDegS);+ Model.RecoilPatternComp = Num(M, TEXT("recoilPatternComp"), Model.RecoilPatternComp);+ Model.HeadAimChance = Num(M, TEXT("headAimChance"), Model.HeadAimChance);+ Model.AimWanderSdDeg = Num(M, TEXT("aimWanderSdDeg"), Model.AimWanderSdDeg);+ Model.AimWanderTheta = Num(M, TEXT("aimWanderTheta"), Model.AimWanderTheta);+ Model.LearnWeight = Num(M, TEXT("learnWeight"), Model.LearnWeight);+ Model.bLearning = !M || !M->Find(TEXT("learning")) || Flag(M, TEXT("learning"));+ Out.Models.Add(Model.Name, Model);+ }+ for (const TPair<FString, TSharedPtr<FVerseJson>>& Pair : Tricks->Object)+ {+ FVerseTrickConfig Config;+ if (!VerseTrickFromName(FName(*Pair.Key), Config.Trick) || Config.Trick == EVerseTrick::None)+ {+ OutError = FString::Printf(TEXT("unknown trick id '%s'"), *Pair.Key);+ return false;+ }+ const FVerseJson* T = Pair.Value.Get();+ const FVerseJson* Input = T ? T->ObjectField(TEXT("input")) : nullptr;+ const FVerseJson* Intent = T ? T->ObjectField(TEXT("intent")) : nullptr;+ Config.LeanFlipMinMs = Num(Input, TEXT("leanFlipMinMs"), Config.LeanFlipMinMs);+ Config.LeanFlipMaxMs = Num(Input, TEXT("leanFlipMaxMs"), Config.LeanFlipMaxMs);+ Config.ProneBeyondM = Num(Input, TEXT("proneBeyondM"), Config.ProneBeyondM);+ Config.MeleeRangeM = Num(Input, TEXT("meleeRangeM"), Config.MeleeRangeM);+ Config.BackOffInsideM = Num(Input, TEXT("backOffInsideM"), Config.BackOffInsideM);+ Config.SlideCooldownS = Num(Input, TEXT("slideCooldownS"), Config.SlideCooldownS);+ FVerseTrickIntent& I = Config.Intent;+ I.HoldSpawnCoverRadiusM = Num(Intent, TEXT("holdSpawnCoverRadiusM"), 0.f);+ I.bRushBelief = Flag(Intent, TEXT("rushBelief"));+ I.PreferRangeM = Num(Intent, TEXT("preferRangeM"), 0.f);+ I.bWallShotAuthorityOff = Flag(Intent, TEXT("wallShotAuthorityOff"));+ I.bFireThroughPenetrable = Flag(Intent, TEXT("fireThroughPenetrable"));+ I.bStayBehindBulwark = Flag(Intent, TEXT("stayBehindBulwark"));+ I.bBreachEveryRoutePiece = Flag(Intent, TEXT("breachEveryRoutePiece"));+ I.bStalkForFinisher = Flag(Intent, TEXT("stalkForFinisher"));+ I.bWatchOpponentSpawn = Flag(Intent, TEXT("watchOpponentSpawn"));+ I.RepeekSameAngleWithinS = Num(Intent, TEXT("repeekSameAngleWithinS"), 0.f);+ I.bAvoidFights = Flag(Intent, TEXT("avoidFights"));+ Out.Tricks.Add(FName(*Pair.Key), Config);+ }+ if (Out.Tricks.Num() != VerseTrickCount)+ {+ OutError = FString::Printf(TEXT("person_models.json lists %d tricks, bot.md 11.2 has %d"), Out.Tricks.Num(),+ VerseTrickCount);+ return false;+ }+ return true;+}diff --git a/unreal/Verse/Source/VerseHarness/Private/Balance/VerseTrickOverrides.cpp b/unreal/Verse/Source/VerseHarness/Private/Balance/VerseTrickOverrides.cppnew file mode 100644index 0000000000..4cf3e455da--- /dev/null+++ b/unreal/Verse/Source/VerseHarness/Private/Balance/VerseTrickOverrides.cpp@@ -0,0 +1,152 @@+#include "Balance/VerseTrickOverrides.h"++namespace VerseTrickPrivate+{+ constexpr uint32 Bit(EVerseInputButton Button) { return uint32(Button); }++ void Hold(FVerseInputFrame& Frame, EVerseInputButton Button, bool bOn)+ {+ Frame.Buttons = bOn ? (Frame.Buttons | Bit(Button)) : (Frame.Buttons & ~Bit(Button));+ }++ bool Held(const FVerseInputFrame& Frame, EVerseInputButton Button) { return (Frame.Buttons & Bit(Button)) != 0; }+}++bool FVerseTrickOverrides::AnySighting(const FVersePerceptFrame& Percepts)+{+ for (const FVerseSightPercept& Sight : Percepts.Sightings)+ {+ if (Sight.VisibleMask != 0)+ {+ return true;+ }+ }+ return false;+}++float FVerseTrickOverrides::NearestSightingM(const FVersePerceptFrame& Percepts)+{+ float Best = TNumericLimits<float>::Max();+ for (const FVerseSightPercept& Sight : Percepts.Sightings)+ {+ if (Sight.VisibleMask != 0)+ {+ Best = FMath::Min(Best, float(FVector::Dist(Percepts.Self.EyeLocation, Sight.PelvisLocation) / 100.0));+ }+ }+ return Best;+}++FVerseInputFrame FVerseTrickOverrides::Apply(const FVerseTrickConfig& Config, const FVersePerceptFrame& Percepts,+ const FVerseInputFrame& Brain, FVerseTrickState& State, FVerseRng& Rng, double NowS)+{+ using namespace VerseTrickPrivate;+ using B = EVerseInputButton;++ FVerseInputFrame Out = Brain;+ const bool bSight = AnySighting(Percepts);+ const float Nearest = NearestSightingM(Percepts);+ const FVerseSelfPercept& Self = Percepts.Self;++ switch (Config.Trick)+ {+ case EVerseTrick::Spray:+ {+ // Holds the trigger on sight, never bursts, reloads only on empty.+ if (bSight)+ {+ Hold(Out, B::Fire, true);+ }+ const bool bEmpty = Self.Magazine <= 0 && !Self.bChambered;+ Hold(Out, B::Reload, bEmpty && Self.Reserve > 0);+ break;+ }+ case EVerseTrick::Rusher:+ if (!bSight)+ {+ Out.Move = FVector2f(1.f, 0.f);+ Hold(Out, B::Sprint, true);+ }+ break;+ case EVerseTrick::Slider:+ if (Held(Out, B::Sprint) && Out.Move.X > 0.5f && NowS - State.LastSlideS >= Config.SlideCooldownS)+ {+ Hold(Out, B::Crouch, true);+ State.LastSlideS = NowS;+ }+ break;+ case EVerseTrick::JumpPeek:+ if (Held(Out, B::LeanLeft) || Held(Out, B::LeanRight))+ {+ Hold(Out, B::LeanLeft, false);+ Hold(Out, B::LeanRight, false);+ Hold(Out, B::Jump, true);+ }+ break;+ case EVerseTrick::LeanSpam:+ if (bSight || Percepts.bHasHurt)+ {+ if (NowS >= State.NextLeanFlipS)+ {+ State.bLeanRight = !State.bLeanRight;+ State.NextLeanFlipS = NowS + Rng.Range(Config.LeanFlipMinMs, Config.LeanFlipMaxMs) / 1000.0;+ }+ Hold(Out, B::LeanRight, State.bLeanRight);+ Hold(Out, B::LeanLeft, !State.bLeanRight);+ }+ break;+ case EVerseTrick::Prone:+ if (bSight && Nearest > Config.ProneBeyondM)+ {+ Hold(Out, B::Prone, true);+ Hold(Out, B::Sprint, false);+ Hold(Out, B::Crouch, false);+ }+ break;+ case EVerseTrick::Turtle:+ // GadgetA is the Bulwark (combat-state.md 2.2): redeploy whenever it is ready.+ Hold(Out, B::GadgetA, Self.GadgetCharges[0] > 0 && Self.GadgetCooldownS[0] <= 0.f);+ break;+ case EVerseTrick::Knife:+ Hold(Out, B::Fire, false);+ Hold(Out, B::Ads, false);+ if (Self.ActiveSlot != EVerseLoadoutSlot::Melee)+ {+ Hold(Out, B::SlotMelee, true);+ }+ Hold(Out, B::Melee, bSight && Nearest <= Config.MeleeRangeM);+ break;+ case EVerseTrick::Finisher:+ Hold(Out, B::Fire, false);+ break;+ case EVerseTrick::Kiter:+ if (bSight && Nearest < Config.BackOffInsideM)+ {+ Out.Move.X = -1.f;+ }+ break;+ case EVerseTrick::Silent:+ Hold(Out, B::Crouch, true);+ Hold(Out, B::Sprint, false);+ Hold(Out, B::Jump, false);+ break;+ case EVerseTrick::Hider:+ if (!Percepts.bHasHurt)+ {+ Hold(Out, B::Fire, false);+ }+ if (bSight)+ {+ Out.Move.X = -1.f;+ Hold(Out, B::Sprint, true);+ }+ break;+ default:+ // Camper, WallSpam, Breacher, Watcher, Repeek: decision-level only (FVerseTrickIntent).+ break;+ }++ Out.Pressed = Out.Buttons & ~State.PrevButtons;+ State.PrevButtons = Out.Buttons;+ return Out;+}diff --git a/unreal/Verse/Source/VerseHarness/Private/Capture/VerseCaptureDirector.cpp b/unreal/Verse/Source/VerseHarness/Private/Capture/VerseCaptureDirector.cppnew file mode 100644index 0000000000..5cadabf1a2--- /dev/null+++ b/unreal/Verse/Source/VerseHarness/Private/Capture/VerseCaptureDirector.cpp@@ -0,0 +1,318 @@+#include "Capture/VerseCaptureDirector.h"++#include "Camera/CameraActor.h"+#include "Camera/CameraComponent.h"+#include "Engine/Engine.h"+#include "Engine/World.h"+#include "GameFramework/PlayerController.h"+#include "HAL/FileManager.h"+#include "HAL/PlatformMisc.h"+#include "Misc/FileHelper.h"+#include "Misc/Paths.h"+#include "ShaderCompiler.h"+#include "UnrealClient.h"+#include "UObject/UObjectGlobals.h"+#include "VerseHarnessJson.h"+#include "VerseLog.h"++namespace VerseCapturePrivate+{+ bool ReadVector(const FVerseJson* Obj, const TCHAR* Field, FVector& Out)+ {+ const TArray<TSharedPtr<FVerseJson>>* Values = Obj->ArrayField(Field);+ if (!Values || Values->Num() != 3)+ {+ return false;+ }+ Out = FVector((*Values)[0]->Number, (*Values)[1]->Number, (*Values)[2]->Number);+ return true;+ }++ bool ReadView(const FVerseJson* Obj, FVerseCaptureView& Out, bool bNeedPose)+ {+ if (!Obj || !Obj->IsObject())+ {+ return false;+ }+ Obj->TryString(TEXT("id"), Out.Id);+ double Number = 0.0;+ if (Obj->TryNumber(TEXT("t"), Number) || Obj->TryNumber(TEXT("atS"), Number))+ {+ Out.T = Number;+ }+ if (Obj->TryNumber(TEXT("fovDeg"), Number))+ {+ Out.FovDeg = float(Number);+ }+ FVector Location = FVector::ZeroVector;+ FVector Rotation = FVector::ZeroVector;+ const bool bPose = ReadVector(Obj, TEXT("location"), Location) && ReadVector(Obj, TEXT("rotation"), Rotation);+ if (bPose)+ {+ Out.Location = Location;+ Out.Rotation = FRotator(Rotation.X, Rotation.Y, Rotation.Z);+ }+ return bPose || !bNeedPose;+ }+}++bool FVerseCaptureScript::Parse(const FString& JsonText, FVerseCaptureScript& Out, FString& OutError)+{+ using namespace VerseCapturePrivate;++ const TSharedPtr<FVerseJson> Root = FVerseJson::Parse(JsonText, OutError);+ if (!Root.IsValid() || !Root->IsObject())+ {+ OutError = TEXT("not a JSON object: ") + OutError;+ return false;+ }+ if (Root->StringOr(TEXT("schema")) != TEXT("verse.capture/1"))+ {+ OutError = TEXT("schema is not verse.capture/1");+ return false;+ }+ Out = FVerseCaptureScript();+ Root->TryString(TEXT("id"), Out.Id);+ Root->TryInt(TEXT("settleFrames"), Out.SettleFrames);+ Root->TryNumber(TEXT("warmupS"), Out.WarmupS);+ const TArray<TSharedPtr<FVerseJson>>* Values = Root->ArrayField(TEXT("views"));+ if (Values)+ {+ for (const TSharedPtr<FVerseJson>& Value : *Values)+ {+ FVerseCaptureView View;+ if (!ReadView(Value.Get(), View, true) || View.Id.IsEmpty())+ {+ OutError = TEXT("a view needs id, location and rotation");+ return false;+ }+ Out.Views.Add(View);+ }+ }+ if (const FVerseJson* Fly = Root->ObjectField(TEXT("flythrough")))+ {+ Fly->TryNumber(TEXT("durationS"), Out.FlythroughS);+ if ((Values = Fly->ArrayField(TEXT("keys"))) != nullptr)+ {+ for (const TSharedPtr<FVerseJson>& Value : *Values)+ {+ FVerseCaptureView Key;+ if (!ReadView(Value.Get(), Key, true))+ {+ OutError = TEXT("a flythrough key needs t, location and rotation");+ return false;+ }+ Out.Keys.Add(Key);+ }+ }+ Out.Keys.Sort([](const FVerseCaptureView& L, const FVerseCaptureView& R) { return L.T < R.T; });+ }+ if ((Values = Root->ArrayField(TEXT("shots"))) != nullptr)+ {+ for (const TSharedPtr<FVerseJson>& Value : *Values)+ {+ FVerseCaptureView Shot;+ ReadView(Value.Get(), Shot, false);+ Out.Shots.Add(Shot);+ }+ Out.Shots.Sort([](const FVerseCaptureView& L, const FVerseCaptureView& R) { return L.T < R.T; });+ }+ if (Out.Views.Num() == 0 && Out.Keys.Num() == 0)+ {+ OutError = TEXT("a capture needs views or flythrough keys");+ return false;+ }+ return true;+}++FVerseCaptureView FVerseCaptureScript::Sample(double T) const+{+ if (Keys.Num() == 0)+ {+ return FVerseCaptureView();+ }+ if (T <= Keys[0].T)+ {+ return Keys[0];+ }+ for (int32 Index = 1; Index < Keys.Num(); ++Index)+ {+ const FVerseCaptureView& A = Keys[Index - 1];+ const FVerseCaptureView& B = Keys[Index];+ if (T <= B.T)+ {+ const double Span = FMath::Max(B.T - A.T, 1.0e-6);+ const float Alpha = float((T - A.T) / Span);+ FVerseCaptureView Out;+ Out.T = T;+ Out.Location = FMath::Lerp(A.Location, B.Location, Alpha);+ Out.Rotation = FMath::Lerp(A.Rotation, B.Rotation, Alpha);+ Out.FovDeg = FMath::Lerp(A.FovDeg, B.FovDeg, Alpha);+ return Out;+ }+ }+ return Keys.Last();+}++bool UVerseCaptureDirector::Start(UWorld* InWorld, const FVerseCaptureScript& InScript, const FString& InOutDir,+ bool bInPerf, FString& OutError)+{+ if (!InWorld)+ {+ OutError = TEXT("no game world");+ return false;+ }+ World = InWorld;+ Script = InScript;+ OutDir = InOutDir;+ bPerf = bInPerf;+ SettleLeft = Script.SettleFrames;+ IFileManager::Get().MakeDirectory(*OutDir, true);+ return true;+}++bool UVerseCaptureDirector::EnsureCamera()+{+ if (Camera.IsValid())+ {+ return true;+ }+ UWorld* W = World.Get();+ APlayerController* PC = W ? W->GetFirstPlayerController() : nullptr;+ if (!PC)+ {+ return false;+ }+ FActorSpawnParameters Params;+ Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;+ ACameraActor* Spawned = W->SpawnActor<ACameraActor>(Params);+ if (!Spawned)+ {+ return false;+ }+ Spawned->GetCameraComponent()->bConstrainAspectRatio = false;+ PC->SetViewTarget(Spawned);+ Camera = Spawned;+ return true;+}++bool UVerseCaptureDirector::SceneIsReady() const+{+ const bool bShaders = GShaderCompilingManager && GShaderCompilingManager->IsCompiling();+ return !bShaders && !IsAsyncLoading();+}++void UVerseCaptureDirector::Place(const FVerseCaptureView& View)+{+ if (ACameraActor* Cam = Camera.Get())+ {+ Cam->SetActorLocationAndRotation(View.Location, View.Rotation);+ Cam->GetCameraComponent()->SetFieldOfView(View.FovDeg);+ }+}++void UVerseCaptureDirector::Shoot(const FString& Id)+{+ PendingFile = FPaths::Combine(OutDir, Id + TEXT(".png"));+ IFileManager::Get().Delete(*PendingFile, false, true, true);+ // UI hidden (bShowUI false), exact file name (no suffix): orchestration.md 5.3.+ FScreenshotRequest::RequestScreenshot(PendingFile, false, false);+ PendingFrames = 120;+ UE_LOG(LogVerseHarness, Display, TEXT("[VerseCapture] shot %s"), *PendingFile);+}++bool UVerseCaptureDirector::Tick(float DeltaS)+{+ if (bDone)+ {+ return false;+ }+ if (!EnsureCamera())+ {+ return true;+ }+ if (PendingFrames > 0)+ {+ --PendingFrames;+ if (IFileManager::Get().FileExists(*PendingFile) || PendingFrames == 0)+ {+ Written.Add(PendingFile);+ PendingFrames = 0;+ }+ return true;+ }++ if (Script.Keys.Num() > 0)+ {+ // Perf replay along the fixed path.+ if (FlyStartS < 0.0)+ {+ if (!SceneIsReady())+ {+ return true;+ }+ FlyStartS = 0.0;+ ElapsedS = -Script.WarmupS;+ }+ ElapsedS += DeltaS;+ Place(Script.Sample(FMath::Max(ElapsedS, 0.0)));+ UWorld* W = World.Get();+ if (bPerf && !bProfiling && ElapsedS >= 0.0 && GEngine)+ {+ GEngine->Exec(W, TEXT("CsvProfile Start"));+ bProfiling = true;+ }+ if (Script.Shots.IsValidIndex(NextShot) && ElapsedS >= Script.Shots[NextShot].T)+ {+ Shoot(Script.Shots[NextShot].Id.IsEmpty() ? FString::Printf(TEXT("shot%d"), NextShot) : Script.Shots[NextShot].Id);+ ++NextShot;+ return true;+ }+ if (ElapsedS >= Script.FlythroughS)+ {+ if (bProfiling && StopAtS < 0.0 && GEngine)+ {+ GEngine->Exec(W, TEXT("CsvProfile Stop"));+ StopAtS = ElapsedS + 3.0;+ }+ if (StopAtS < 0.0 || ElapsedS >= StopAtS)+ {+ Finish();+ }+ }+ return !bDone;+ }++ // Reference views.+ if (!Script.Views.IsValidIndex(ViewIndex))+ {+ Finish();+ return false;+ }+ if (SettleLeft == Script.SettleFrames)+ {+ Place(Script.Views[ViewIndex]);+ if (UWorld* W = World.Get())+ {+ W->BlockTillLevelStreamingCompleted();+ }+ }+ if (!SceneIsReady() || --SettleLeft > 0)+ {+ return true;+ }+ Shoot(Script.Views[ViewIndex].Id);+ ++ViewIndex;+ SettleLeft = Script.SettleFrames;+ return true;+}++void UVerseCaptureDirector::Finish()+{+ if (bDone)+ {+ return;+ }+ bDone = true;+ UE_LOG(LogVerseHarness, Display, TEXT("[VerseCapture] done: %d images in %s"), Written.Num(), *OutDir);+}diff --git a/unreal/Verse/Source/VerseHarness/Private/Tests/Harness/VerseHarnessLogicTest.cpp b/unreal/Verse/Source/VerseHarness/Private/Tests/Harness/VerseHarnessLogicTest.cppnew file mode 100644index 0000000000..ff241da032--- /dev/null+++ b/unreal/Verse/Source/VerseHarness/Private/Tests/Harness/VerseHarnessLogicTest.cpp@@ -0,0 +1,340 @@+#include "Balance/VerseBoutRecorder.h"+#include "Balance/VerseHarnessScenario.h"+#include "Balance/VerseModelController.h"+#include "Balance/VersePersonModels.h"+#include "Balance/VerseTrickOverrides.h"+#include "Capture/VerseCaptureDirector.h"+#include "Misc/AutomationTest.h"+#include "VerseHarnessJson.h"++#if WITH_DEV_AUTOMATION_TESTS++namespace VerseHarnessTestPrivate+{+ constexpr EAutomationTestFlags Flags = EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter;++ FVersePerceptFrame Sighting(float DistanceM)+ {+ FVersePerceptFrame Frame;+ Frame.Self.EyeLocation = FVector::ZeroVector;+ Frame.Self.Magazine = 20;+ Frame.Self.bChambered = true;+ Frame.Self.Reserve = 60;+ FVerseSightPercept Sight;+ Sight.PelvisLocation = FVector(DistanceM * 100.0, 0.0, 0.0);+ Sight.VisibleMask = 0xFF;+ Frame.Sightings.Add(Sight);+ return Frame;+ }++ FVerseTrickConfig Trick(EVerseTrick Id)+ {+ FVerseTrickConfig Config;+ Config.Trick = Id;+ return Config;+ }++ bool Held(const FVerseInputFrame& Frame, EVerseInputButton Button) { return Frame.IsHeld(Button); }++ const TCHAR* ScenarioJson = TEXT(R"({+ "schema": "verse.scenario/1", "run": "r1", "job": 2, "map": "/Game/Verse/Decks/Hangar/LV_Hangar",+ "output": "C:/tmp/out", "maxWallS": 100, "trace": {"bearing": true, "fireAudit": true},+ "units": [{"pairing": "skilled+spray_vs_hard", "set": "elite", "match": 1, "seed": 4000000000, "bouts": 3,+ "a": {"kind": "model", "model": "skilled", "trick": "spray"}, "b": {"kind": "bot", "tier": "hard", "learning": false},+ "killsToWin": 15, "matchTimeLimitS": 600, "tierPatch": {"hard": {"ReactionMeanMs": 300}}}]+ })");+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseHarnessScenarioParseTest, "Verse.Harness.Scenario.Parse", VerseHarnessTestPrivate::Flags)+bool FVerseHarnessScenarioParseTest::RunTest(const FString& Parameters)+{+ FVerseHarnessScenario S;+ FString Error;+ TestTrue(TEXT("valid scenario parses"), FVerseHarnessScenario::Parse(VerseHarnessTestPrivate::ScenarioJson, S, Error));+ TestEqual(TEXT("error"), Error, FString());+ TestEqual(TEXT("job"), S.Job, 2);+ TestTrue(TEXT("bearing trace"), S.bTraceBearing);+ if (!TestEqual(TEXT("units"), S.Units.Num(), 1))+ {+ return false;+ }+ const FVerseHarnessUnit& U = S.Units[0];+ TestEqual(TEXT("seed keeps 32 bits"), U.Seed, 4000000000u);+ TestEqual(TEXT("bouts"), U.Bouts, 3);+ TestEqual(TEXT("label A"), U.A.Label(), FString(TEXT("skilled+spray")));+ TestEqual(TEXT("label B"), U.B.Label(), FString(TEXT("hard-nolearn")));+ TestTrue(TEXT("patch carried"), U.TierPatchJson.Contains(TEXT("ReactionMeanMs")));++ FVerseHarnessScenario Bad;+ TestFalse(TEXT("wrong schema fails"), FVerseHarnessScenario::Parse(TEXT(R"({"schema":"x/1"})"), Bad, Error));+ TestFalse(TEXT("bot without tier fails"), FVerseHarnessScenario::Parse(TEXT(R"({"schema":"verse.scenario/1","run":"r",+ "map":"/Game/M","output":"o","units":[{"pairing":"p","match":0,"seed":1,"bouts":1,"a":{"kind":"bot"},+ "b":{"kind":"model","model":"skilled"}}]})"), Bad, Error));+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseHarnessPersonModelsTest, "Verse.Harness.PersonModels.Load", VerseHarnessTestPrivate::Flags)+bool FVerseHarnessPersonModelsTest::RunTest(const FString& Parameters)+{+ FVersePersonModelSet Set;+ FString Error;+ if (!TestTrue(TEXT("person_models.json loads: ") + Error, FVersePersonModelSet::LoadDefault(Set, Error)))+ {+ return false;+ }+ TestEqual(TEXT("17 tricks (bot.md 11.2)"), Set.Tricks.Num(), VerseTrickCount);+ const FVersePersonModel* Skilled = Set.Models.Find(TEXT("skilled"));+ const FVersePersonModel* Average = Set.Models.Find(TEXT("average"));+ if (TestNotNull(TEXT("skilled"), Skilled) && TestNotNull(TEXT("average"), Average))+ {+ TestEqual(TEXT("skilled reaction 225"), Skilled->ReactionMeanMs, 225.f);+ TestEqual(TEXT("skilled turn rate 1000"), Skilled->TurnRateDegS, 1000.f);+ TestEqual(TEXT("skilled recoil comp 0.8"), Skilled->RecoilPatternComp, 0.8f);+ TestEqual(TEXT("skilled head aim 0.3"), Skilled->HeadAimChance, 0.3f);+ TestEqual(TEXT("average reaction 270"), Average->ReactionMeanMs, 270.f);+ TestEqual(TEXT("average recoil comp 0.5"), Average->RecoilPatternComp, 0.5f);+ }+ for (int32 Index = 1; Index <= VerseTrickCount; ++Index)+ {+ const FName Name = VerseTrickName(EVerseTrick(Index));+ EVerseTrick Back = EVerseTrick::None;+ TestTrue(FString::Printf(TEXT("trick %s round-trips"), *Name.ToString()), VerseTrickFromName(Name, Back) && Back == EVerseTrick(Index));+ TestTrue(FString::Printf(TEXT("trick %s in the file"), *Name.ToString()), Set.Tricks.Contains(Name));+ }+ const FVerseTrickConfig* Wallspam = Set.Tricks.Find(TEXT("wallspam"));+ if (TestNotNull(TEXT("wallspam"), Wallspam))+ {+ TestTrue(TEXT("wallspam turns its own authority off"), Wallspam->Intent.bWallShotAuthorityOff);+ }+ EVerseTrick Unknown;+ TestFalse(TEXT("unknown id"), VerseTrickFromName(TEXT("teleport"), Unknown));+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseHarnessTricksTest, "Verse.Harness.Tricks.Overrides", VerseHarnessTestPrivate::Flags)+bool FVerseHarnessTricksTest::RunTest(const FString& Parameters)+{+ using namespace VerseHarnessTestPrivate;+ using B = EVerseInputButton;+ FVerseRng Rng(7);+ const FVerseInputFrame Empty;++ {+ FVerseTrickState State;+ const FVerseInputFrame Out = FVerseTrickOverrides::Apply(Trick(EVerseTrick::Spray), Sighting(10), Empty, State, Rng, 0.0);+ TestTrue(TEXT("spray holds fire on sight"), Held(Out, B::Fire));+ TestTrue(TEXT("fire went down this tick"), Out.WasPressed(B::Fire));+ FVersePerceptFrame Dry = Sighting(10);+ Dry.Self.Magazine = 0;+ Dry.Self.bChambered = false;+ const FVerseInputFrame Again = FVerseTrickOverrides::Apply(Trick(EVerseTrick::Spray), Dry, Empty, State, Rng, 0.1);+ TestTrue(TEXT("spray reloads on empty"), Held(Again, B::Reload));+ TestFalse(TEXT("held fire is not pressed again"), Again.WasPressed(B::Fire));+ FVerseInputFrame Brain;+ Brain.Buttons = uint32(B::Reload);+ const FVerseInputFrame NoTactical = FVerseTrickOverrides::Apply(Trick(EVerseTrick::Spray), Sighting(10), Brain, State, Rng, 0.2);+ TestFalse(TEXT("spray never reloads a loaded magazine"), Held(NoTactical, B::Reload));+ }+ {+ FVerseTrickState State;+ FVerseInputFrame Brain;+ Brain.Buttons = uint32(B::Sprint) | uint32(B::Jump);+ const FVerseInputFrame Out = FVerseTrickOverrides::Apply(Trick(EVerseTrick::Silent), FVersePerceptFrame(), Brain, State, Rng, 0.0);+ TestTrue(TEXT("silent crouches"), Held(Out, B::Crouch));+ TestFalse(TEXT("silent never sprints"), Held(Out, B::Sprint));+ TestFalse(TEXT("silent never jumps"), Held(Out, B::Jump));+ }+ {+ FVerseTrickState State;+ FVerseInputFrame Brain;+ Brain.Buttons = uint32(B::LeanLeft);+ const FVerseInputFrame Out = FVerseTrickOverrides::Apply(Trick(EVerseTrick::JumpPeek), Sighting(8), Brain, State, Rng, 0.0);+ TestTrue(TEXT("jumppeek jumps instead of leaning"), Held(Out, B::Jump) && !Held(Out, B::LeanLeft));+ }+ {+ FVerseTrickState State;+ int32 Flips = 0;+ bool bLast = false;+ for (int32 Tick = 0; Tick < 600; ++Tick)+ {+ const FVerseInputFrame Out = FVerseTrickOverrides::Apply(Trick(EVerseTrick::LeanSpam), Sighting(15), Empty, State, Rng, Tick / 60.0);+ const bool bRight = Held(Out, B::LeanRight);+ TestTrue(TEXT("exactly one lean"), bRight != Held(Out, B::LeanLeft));+ Flips += (Tick > 0 && bRight != bLast) ? 1 : 0;+ bLast = bRight;+ }+ // 10 s with a flip every 150-300 ms: between 33 and 67 flips.+ TestTrue(FString::Printf(TEXT("leanspam flips %d times in 10 s"), Flips), Flips >= 32 && Flips <= 68);+ }+ {+ FVerseTrickState State;+ const FVerseInputFrame Far = FVerseTrickOverrides::Apply(Trick(EVerseTrick::Prone), Sighting(30), Empty, State, Rng, 0.0);+ const FVerseInputFrame Near = FVerseTrickOverrides::Apply(Trick(EVerseTrick::Prone), Sighting(8), Empty, State, Rng, 0.1);+ TestTrue(TEXT("prone at long range"), Held(Far, B::Prone));+ TestFalse(TEXT("not prone up close"), Held(Near, B::Prone));+ }+ {+ FVerseTrickState State;+ FVerseInputFrame Brain;+ Brain.Buttons = uint32(B::Fire);+ const FVerseInputFrame Far = FVerseTrickOverrides::Apply(Trick(EVerseTrick::Knife), Sighting(10), Brain, State, Rng, 0.0);+ const FVerseInputFrame Close = FVerseTrickOverrides::Apply(Trick(EVerseTrick::Knife), Sighting(1.5f), Brain, State, Rng, 0.1);+ TestFalse(TEXT("knife never fires"), Held(Far, B::Fire) || Held(Close, B::Fire));+ TestFalse(TEXT("no strike out of reach"), Held(Far, B::Melee));+ TestTrue(TEXT("strike in reach"), Held(Close, B::Melee));+ }+ {+ FVerseTrickState State;+ FVerseInputFrame Brain;+ Brain.Move = FVector2f(1.f, 0.f);+ const FVerseInputFrame Out = FVerseTrickOverrides::Apply(Trick(EVerseTrick::Kiter), Sighting(12), Brain, State, Rng, 0.0);+ TestEqual(TEXT("kiter backs off inside 30 m"), Out.Move.X, -1.f);+ const FVerseInputFrame Hider = FVerseTrickOverrides::Apply(Trick(EVerseTrick::Hider), Sighting(12), Brain, State, Rng, 0.1);+ TestFalse(TEXT("hider does not shoot unhurt"), Held(Hider, B::Fire));+ TestEqual(TEXT("hider runs away"), Hider.Move.X, -1.f);+ }+ {+ FVerseTrickState State;+ const FVerseInputFrame Out = FVerseTrickOverrides::Apply(Trick(EVerseTrick::Rusher), FVersePerceptFrame(), Empty, State, Rng, 0.0);+ TestTrue(TEXT("rusher sprints forward unseen"), Held(Out, B::Sprint) && Out.Move.X == 1.f);+ FVerseInputFrame Brain;+ Brain.Buttons = uint32(B::Sprint);+ Brain.Move = FVector2f(1.f, 0.f);+ FVerseTrickState SlideState;+ const FVerseInputFrame First = FVerseTrickOverrides::Apply(Trick(EVerseTrick::Slider), FVersePerceptFrame(), Brain, SlideState, Rng, 0.0);+ const FVerseInputFrame Soon = FVerseTrickOverrides::Apply(Trick(EVerseTrick::Slider), FVersePerceptFrame(), Brain, SlideState, Rng, 0.5);+ const FVerseInputFrame Later = FVerseTrickOverrides::Apply(Trick(EVerseTrick::Slider), FVersePerceptFrame(), Brain, SlideState, Rng, 2.0);+ TestTrue(TEXT("slider slides on approach"), Held(First, B::Crouch));+ TestFalse(TEXT("slide cooldown"), Held(Soon, B::Crouch));+ TestTrue(TEXT("slides again after the cooldown"), Held(Later, B::Crouch));+ }+ {+ FVerseTrickState State;+ FVersePerceptFrame Ready;+ Ready.Self.GadgetCharges[0] = 1;+ const FVerseInputFrame Out = FVerseTrickOverrides::Apply(Trick(EVerseTrick::Turtle), Ready, Empty, State, Rng, 0.0);+ TestTrue(TEXT("turtle deploys the Bulwark when ready"), Held(Out, B::GadgetA));+ }+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseHarnessModelLimitsTest, "Verse.Harness.Model.Limits", VerseHarnessTestPrivate::Flags)+bool FVerseHarnessModelLimitsTest::RunTest(const FString& Parameters)+{+ FVersePersonModel Model;+ Model.TurnRateDegS = 600.f;+ FVerseInputFrame Brain;+ Brain.Buttons = uint32(EVerseInputButton::Fire) | uint32(EVerseInputButton::Ads);+ Brain.LookDeltaDeg = FVector2f(-50.f, 50.f);+ const FVerseInputFrame Reacting = AVerseModelController::ApplyPersonLimits(Model, Brain, true, 1.f / 60.f);+ TestFalse(TEXT("no fire before the reaction time"), Reacting.IsHeld(EVerseInputButton::Fire));+ TestEqual(TEXT("no look before the reaction time"), Reacting.LookDeltaDeg.Y, 0.f);+ const FVerseInputFrame Acting = AVerseModelController::ApplyPersonLimits(Model, Brain, false, 1.f / 60.f);+ TestTrue(TEXT("fires after reacting"), Acting.IsHeld(EVerseInputButton::Fire));+ TestEqual(TEXT("turn clamped to 10 deg per tick"), Acting.LookDeltaDeg.Y, 10.f);+ TestEqual(TEXT("both axes clamped"), Acting.LookDeltaDeg.X, -10.f);+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseHarnessBoutRecorderTest, "Verse.Harness.Bout.Recorder", VerseHarnessTestPrivate::Flags)+bool FVerseHarnessBoutRecorderTest::RunTest(const FString& Parameters)+{+ FVerseBoutRecorder R(10, 20, 2, 600.0);+ R.OnRespawn(10, 0.0);+ R.OnRespawn(20, 0.0);+ FVerseFireEvent Fire;+ Fire.ShooterId = 10;+ R.OnFire(Fire, 4.0);+ FVerseHitEvent Hit;+ Hit.InstigatorId = 10;+ Hit.VictimId = 20;+ Hit.DistanceM = 22.f;+ Hit.bHeadshot = 1;+ Hit.PenetrationCount = 1;+ R.OnHit(Hit, 4.0);+ FVerseDeathEvent Death;+ Death.KillerId = 10;+ Death.VictimId = 20;+ R.OnDeath(Death, 5.0);+ R.OnRespawn(20, 8.0);+ TestFalse(TEXT("one kill of two is not over"), R.IsOver(8.0));+ FVerseReloadEvent Reload;+ Reload.PlayerId = 10;+ R.OnReload(Reload, 6.0);+ R.OnDeath(Death, 9.0);+ TestTrue(TEXT("over at KillsToWin"), R.IsOver(9.0));+ TestTrue(TEXT("A wins"), R.Winner() == EVerseSide::A);+ TestEqual(TEXT("kills"), R.Kills().Num(), 2);+ const FVerseBoutKill& First = R.Kills()[0];+ TestTrue(TEXT("headshot wall kill classified"), First.bHeadshot && First.bWall);+ TestEqual(TEXT("range from the killing hit"), First.RangeM, 22.f);+ TestEqual(TEXT("ttk from first hit"), First.TtkS, 1.f);+ TestFalse(TEXT("5 s into a life is no spawn kill"), First.bSpawnKill);+ TestTrue(TEXT("1 s after respawn is a spawn kill"), R.Kills()[1].bSpawnKill);+ TestEqual(TEXT("contact time A"), R.Side(EVerseSide::A).TimeToContactS[0], 4.f);+ TestEqual(TEXT("shots"), R.Side(EVerseSide::A).Shots, 1);+ TestEqual(TEXT("reload in fight"), R.Side(EVerseSide::A).ReloadsInFight, 1);+ TestEqual(TEXT("deaths B"), R.Side(EVerseSide::B).Deaths, 2);++ FVerseBoutRecorder Idle(1, 2, 15, 600.0);+ Idle.SamplePosition(EVerseSide::A, FVector::ZeroVector, true, 0.0);+ Idle.SamplePosition(EVerseSide::A, FVector(10, 0, 0), true, 16.0);+ TestEqual(TEXT("stuck after 15 s without 50 cm"), Idle.Side(EVerseSide::A).StuckEvents, 1);+ TestTrue(TEXT("time limit ends a bout"), Idle.IsOver(600.0));+ TestTrue(TEXT("no kills is a draw"), Idle.Winner() == EVerseSide::None);++ const FString Line = R.ToJsonLine(TEXT("hard_vs_normal"), 0, 3, 99, 1, 9.0, 120.0, {0.5f, 0.52f});+ TestTrue(TEXT("schema"), Line.Contains(TEXT("\"schema\":\"verse.bout/1\"")));+ TestTrue(TEXT("winner"), Line.Contains(TEXT("\"winner\":\"A\"")));+ TestTrue(TEXT("spawn side"), Line.Contains(TEXT("\"spawnSideA\":1")));+ TestFalse(TEXT("one line"), Line.Contains(TEXT("\n")));+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseHarnessCaptureScriptTest, "Verse.Harness.Capture.Script", VerseHarnessTestPrivate::Flags)+bool FVerseHarnessCaptureScriptTest::RunTest(const FString& Parameters)+{+ FVerseCaptureScript S;+ FString Error;+ const bool bOk = FVerseCaptureScript::Parse(TEXT(R"({"schema":"verse.capture/1","id":"p","warmupS":2,+ "flythrough":{"durationS":10,"keys":[{"t":10,"location":[100,0,0],"rotation":[0,90,0],"fovDeg":60},+ {"t":0,"location":[0,0,0],"rotation":[0,0,0],"fovDeg":90}]},"shots":[{"id":"mid","atS":5}]})"), S, Error);+ if (!TestTrue(TEXT("parses: ") + Error, bOk))+ {+ return false;+ }+ TestEqual(TEXT("keys sorted"), S.Keys[0].T, 0.0);+ const FVerseCaptureView Mid = S.Sample(5.0);+ TestEqual(TEXT("halfway location"), Mid.Location.X, 50.0);+ TestEqual(TEXT("halfway yaw"), Mid.Rotation.Yaw, 45.0);+ TestEqual(TEXT("clamped after the end"), S.Sample(99.0).Location.X, 100.0);+ TestEqual(TEXT("shot"), S.Shots[0].Id, FString(TEXT("mid")));+ FVerseCaptureScript Bad;+ TestFalse(TEXT("needs views or keys"), FVerseCaptureScript::Parse(TEXT(R"({"schema":"verse.capture/1"})"), Bad, Error));+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseHarnessJsonTest, "Verse.Harness.Json.RoundTrip", VerseHarnessTestPrivate::Flags)+bool FVerseHarnessJsonTest::RunTest(const FString& Parameters)+{+ FString Error;+ const TSharedPtr<FVerseJson> Doc = FVerseJson::Parse(TEXT("{\"a\": [1, 2.5, -3e2], \"s\": \"x\\\"y\\n\", \"b\": true, \"n\": null, \"o\": {}}"), Error);+ if (!TestTrue(TEXT("parses: ") + Error, Doc.IsValid()))+ {+ return false;+ }+ const TArray<TSharedPtr<FVerseJson>>* A = Doc->ArrayField(TEXT("a"));+ TestTrue(TEXT("array"), A && A->Num() == 3 && (*A)[2]->Number == -300.0);+ TestEqual(TEXT("escapes"), Doc->StringOr(TEXT("s")), FString(TEXT("x\"y\n")));+ bool B = false;+ TestTrue(TEXT("bool"), Doc->TryBool(TEXT("b"), B) && B);+ TestEqual(TEXT("compact round trip"), Doc->ToString(), FString(TEXT("{\"a\":[1,2.5,-300],\"s\":\"x\\\"y\\n\",\"b\":true,\"n\":null,\"o\":{}}")));+ TestFalse(TEXT("trailing garbage fails"), FVerseJson::Parse(TEXT("{} x"), Error).IsValid());+ TestFalse(TEXT("unterminated fails"), FVerseJson::Parse(TEXT("{\"a\": [1, 2"), Error).IsValid());+ FVerseJsonWriter W;+ W.Str(TEXT("k"), TEXT("v")).Num(TEXT("n"), 0.25).Null(TEXT("z"));+ TestEqual(TEXT("writer"), W.Close(), FString(TEXT("{\"k\":\"v\",\"n\":0.25,\"z\":null}")));+ return true;+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseHarness/Private/Tests/Harness/VerseHarnessWorldTest.cpp b/unreal/Verse/Source/VerseHarness/Private/Tests/Harness/VerseHarnessWorldTest.cppnew file mode 100644index 0000000000..f9574bfe76--- /dev/null+++ b/unreal/Verse/Source/VerseHarness/Private/Tests/Harness/VerseHarnessWorldTest.cpp@@ -0,0 +1,233 @@+#include "Balance/VerseBalanceGauntletController.h"+#include "Balance/VerseHarnessPerceptFeed.h"+#include "Balance/VerseHarnessScenario.h"+#include "Balance/VerseModelController.h"+#include "Bot/VerseBotTier.h"+#include "Engine/Engine.h"+#include "Engine/World.h"+#include "GameFramework/Character.h"+#include "GameFramework/CharacterMovementComponent.h"+#include "GameFramework/PlayerStart.h"+#include "HAL/FileManager.h"+#include "Misc/AutomationTest.h"+#include "Misc/FileHelper.h"+#include "Misc/Paths.h"++#if WITH_DEV_AUTOMATION_TESTS++namespace VerseHarnessWorldTestPrivate+{+ constexpr EAutomationTestFlags Flags = EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter;++ /** A bare game world with no game mode: the fixture the harness falls back to plain characters in. */+ struct FFixtureWorld+ {+ UWorld* World = nullptr;++ FFixtureWorld()+ {+ World = UWorld::CreateWorld(EWorldType::Game, false, TEXT("VerseHarnessFixture"));+ FWorldContext& Context = GEngine->CreateNewWorldContext(EWorldType::Game);+ Context.SetCurrentWorld(World);+ World->InitializeActorsForPlay(FURL());+ World->BeginPlay();+ }++ ~FFixtureWorld()+ {+ GEngine->DestroyWorldContext(World);+ World->DestroyWorld(false);+ }++ APlayerStart* Start(const FVector& At, FName Tag) const+ {+ FActorSpawnParameters Params;+ Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;+ APlayerStart* S = World->SpawnActor<APlayerStart>(APlayerStart::StaticClass(), FTransform(At), Params);+ S->PlayerStartTag = Tag;+ return S;+ }+ };++ FVerseHarnessScenario RusherVsSilent(const FString& OutDir)+ {+ FVerseHarnessScenario S;+ S.Run = TEXT("world-test");+ S.OutputDir = OutDir;+ FVerseHarnessUnit Unit;+ Unit.Pairing = TEXT("skilled+rusher_vs_average+silent");+ Unit.Set = TEXT("humans");+ Unit.Seed = 7;+ Unit.Bouts = 3;+ Unit.A.Kind = EVerseHarnessSlotKind::Model;+ Unit.A.Model = TEXT("skilled");+ Unit.A.Trick = TEXT("rusher");+ Unit.B.Kind = EVerseHarnessSlotKind::Model;+ Unit.B.Model = TEXT("average");+ Unit.B.Trick = TEXT("silent");+ S.Units.Add(Unit);+ return S;+ }++ double DistTo(const AController* C, const FVector& At)+ {+ const APawn* P = C ? C->GetPawn() : nullptr;+ return P ? FVector::Dist(P->GetActorLocation(), At) : TNumericLimits<double>::Max();+ }+} // namespace VerseHarnessWorldTestPrivate++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseHarnessModelsActTest, "Verse.Harness.World.ModelsActWithNullBrain",+ VerseHarnessWorldTestPrivate::Flags)+bool FVerseHarnessModelsActTest::RunTest(const FString& Parameters)+{+ using namespace VerseHarnessWorldTestPrivate;+ FFixtureWorld Fixture;+ const FVector Side0(0.0, 0.0, 100.0);+ const FVector Side1(3000.0, 0.0, 100.0);+ Fixture.Start(Side1, TEXT("VerseSide1"));+ Fixture.Start(Side0, TEXT("VerseSide0"));+ const FString OutDir = FPaths::Combine(FPaths::ProjectSavedDir(), TEXT("Harness"), TEXT("test"), TEXT("world"));+ IFileManager::Get().DeleteDirectory(*OutDir, false, true);++ UVerseBalanceGauntletController* Run = NewObject<UVerseBalanceGauntletController>();+ FString Error;+ if (!TestTrue(TEXT("run starts"), Run->Start(Fixture.World, RusherVsSilent(OutDir), Error)))+ {+ AddError(Error);+ return false;+ }+ AController* A = Run->GetSlot(0);+ AController* B = Run->GetSlot(1);+ TestTrue(TEXT("both slots are model controllers"), Cast<AVerseModelController>(A) && Cast<AVerseModelController>(B));+ TestEqual(TEXT("both models observe the percept feed"), Run->GetPerceptFeed()->NumObservers(), 2);++ // Bout 0: slot A on side 0, B on side 1.+ TestEqual(TEXT("bout 0 spawn side of A"), Run->GetSpawnSideA(), 0);+ TestTrue(TEXT("A spawned at side 0"), DistTo(A, Side0) < 1.0);+ TestTrue(TEXT("B spawned at side 1"), DistTo(B, Side1) < 1.0);++ // One server tick: the feed delivers frames, the trick layers act without any brain.+ TestTrue(TEXT("tick runs"), Run->Tick());+ TestEqual(TEXT("A thought once"), Cast<AVerseModelController>(A)->GetFramesThought(), int64(1));+ const APawn* PawnA = A ? A->GetPawn() : nullptr;+ TestTrue(TEXT("the rusher pushes its pawn forward"), PawnA && PawnA->GetPendingMovementInputVector().X > 0.5);+ TestTrue(TEXT("the rusher holds sprint"), Cast<AVerseModelController>(A)->GetLastInput().IsHeld(EVerseInputButton::Sprint));+ const ACharacter* PawnB = B ? Cast<ACharacter>(B->GetPawn()) : nullptr;+ TestTrue(TEXT("the silent model crouches its pawn"), PawnB && PawnB->GetCharacterMovement()->bWantsToCrouch);++ // Bout 1: both pawns reset, sides swapped.+ Run->EndBoutForTest();+ TestEqual(TEXT("bout index"), Run->GetBoutIndex(), 1);+ TestEqual(TEXT("bout 1 spawn side of A"), Run->GetSpawnSideA(), 1);+ TestTrue(TEXT("A respawned at side 1"), DistTo(Run->GetSlot(0), Side1) < 1.0);+ TestTrue(TEXT("B respawned at side 0"), DistTo(Run->GetSlot(1), Side0) < 1.0);+ TestTrue(TEXT("A got a fresh pawn"), Run->GetSlot(0)->GetPawn() != PawnA);++ FString Lines;+ FFileHelper::LoadFileToString(Lines, *FPaths::Combine(OutDir, TEXT("bouts.jsonl")));+ TestTrue(TEXT("bout 0 records side 0"), Lines.Contains(TEXT("\"spawnSideA\":0")));+ TestTrue(TEXT("bout 0 records its server window"), Lines.Contains(TEXT("\"serverStartMs\":")) && Lines.Contains(TEXT("\"serverEndMs\":")));+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseHarnessSpawnFallbackTest, "Verse.Harness.World.SpawnPairWithoutStarts",+ VerseHarnessWorldTestPrivate::Flags)+bool FVerseHarnessSpawnFallbackTest::RunTest(const FString& Parameters)+{+ using namespace VerseHarnessWorldTestPrivate;+ FFixtureWorld Fixture;+ const FString OutDir = FPaths::Combine(FPaths::ProjectSavedDir(), TEXT("Harness"), TEXT("test"), TEXT("fallback"));+ UVerseBalanceGauntletController* Run = NewObject<UVerseBalanceGauntletController>();+ FString Error;+ if (!TestTrue(TEXT("run starts"), Run->Start(Fixture.World, RusherVsSilent(OutDir), Error)))+ {+ AddError(Error);+ return false;+ }+ const double Gap = FVector::Dist(Run->GetSpawnTransform(0).GetLocation(), Run->GetSpawnTransform(1).GetLocation());+ TestTrue(TEXT("the harness pair is 20 m apart"), FMath::IsNearlyEqual(Gap, 2000.0, 1.0));+ TestTrue(TEXT("A at side 0"), DistTo(Run->GetSlot(0), Run->GetSpawnTransform(0).GetLocation()) < 1.0);+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseHarnessTierTest, "Verse.Harness.World.TierAndPatch", VerseHarnessWorldTestPrivate::Flags)+bool FVerseHarnessTierTest::RunTest(const FString& Parameters)+{+ FString Error;+ UVerseBotTier* Hard = UVerseBalanceGauntletController::MakeTier(nullptr, TEXT("hard"), true,+ TEXT(R"({"hard": {"TurnRateDegS": 123, "ReactionMs": [111, 11]}, "elite": {"TurnRateDegS": 999}, "AimNoiseDeg": 0.5})"),+ Error);+ if (!TestNotNull(TEXT("hard tier with a patch"), Hard))+ {+ AddError(Error);+ return false;+ }+ TestEqual(TEXT("per-tier patch"), Hard->TurnRateDegS, 123.f);+ TestEqual(TEXT("vector field patch"), Hard->ReactionMs, FVector2f(111.f, 11.f));+ TestEqual(TEXT("flat patch applies to every tier"), Hard->AimNoiseDeg, 0.5f);+ TestEqual(TEXT("tier id"), Hard->TierId, FName(TEXT("hard")));++ UVerseBotTier* NoLearn = UVerseBalanceGauntletController::MakeTier(nullptr, TEXT("hard"), false, FString(), Error);+ TestEqual(TEXT("learning off caps the learnt weight at 0"), NoLearn ? NoLearn->LearnWeightMax : -1.f, 0.f);++ UVerseBotTier* Adaptive = UVerseBalanceGauntletController::MakeTier(nullptr, TEXT("adaptive"), true, FString(), Error);+ TestEqual(TEXT("adaptive starts from normal"), Adaptive ? Adaptive->TierId : NAME_None, FName(TEXT("normal")));++ Error.Reset();+ TestNull(TEXT("an unknown field fails"),+ UVerseBalanceGauntletController::MakeTier(nullptr, TEXT("hard"), true, TEXT(R"({"NoSuchField": 1})"), Error));+ TestTrue(TEXT("the reason names the field"), Error.Contains(TEXT("NoSuchField")));+ TestNull(TEXT("an unknown tier fails"), UVerseBalanceGauntletController::MakeTier(nullptr, TEXT("legend"), true, FString(), Error));++ UVerseBotTier* Start = NewObject<UVerseBotTier>();+ UVerseBotTier::ApplyStartValues(TEXT("hard"), *Start);+ const FVersePersonModel Person = UVerseBalanceGauntletController::PersonFromTier(*Start, TEXT("hard"));+ TestEqual(TEXT("person reaction mean from the tier"), Person.ReactionMeanMs, Start->ReactionMs.X);+ TestEqual(TEXT("person turn rate from the tier"), Person.TurnRateDegS, Start->TurnRateDegS);+ TestEqual(TEXT("person aim wander from the tier"), Person.AimWanderSdDeg, Start->AimNoiseDeg);+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseHarnessInputApplyTest, "Verse.Harness.World.InputReachesPawn", VerseHarnessWorldTestPrivate::Flags)+bool FVerseHarnessInputApplyTest::RunTest(const FString& Parameters)+{+ using namespace VerseHarnessWorldTestPrivate;+ FFixtureWorld Fixture;+ FActorSpawnParameters Params;+ Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;+ AVerseModelController* Model = Fixture.World->SpawnActor<AVerseModelController>(Params);+ ACharacter* Pawn = Fixture.World->SpawnActor<ACharacter>(ACharacter::StaticClass(), FTransform(FVector(0, 0, 100)), Params);+ Pawn->GetCharacterMovement()->GetNavAgentPropertiesRef().bCanCrouch = true;+ Model->Possess(Pawn);+ Model->SetControlRotation(FRotator::ZeroRotator);++ FVerseInputFrame Input;+ Input.LookDeltaDeg = FVector2f(0.f, 90.f);+ Input.Move = FVector2f(1.f, 0.f);+ AVerseModelController::ApplyInputToPawn(*Model, *Pawn, Input);+ TestTrue(TEXT("yaw added to the control rotation"), FMath::IsNearlyEqual(Model->GetControlRotation().Yaw, 90.f, 0.01f));+ TestTrue(TEXT("move is in pawn space after the turn (+Y)"), Pawn->GetPendingMovementInputVector().Y > 0.99);+ TestFalse(TEXT("no crouch without the button"), Pawn->GetCharacterMovement()->bWantsToCrouch);++ FVerseInputFrame Low;+ Low.Buttons = uint32(EVerseInputButton::Prone);+ AVerseModelController::ApplyInputToPawn(*Model, *Pawn, Low);+ TestTrue(TEXT("prone lowers the character"), Pawn->GetCharacterMovement()->bWantsToCrouch);+ AVerseModelController::ApplyInputToPawn(*Model, *Pawn, FVerseInputFrame());+ TestFalse(TEXT("releasing stands up"), Pawn->GetCharacterMovement()->bWantsToCrouch);++ // Frames of another observer are not this model's.+ UVerseHarnessPerceptFeed* Feed = NewObject<UVerseHarnessPerceptFeed>();+ Model->AttachPerception(Feed, FVersePerceptionProfile());+ Model->HandlePerceptFrame(nullptr, FVersePerceptFrame());+ TestEqual(TEXT("foreign frame ignored"), Model->GetFramesThought(), int64(0));+ Feed->Tick(Fixture.World);+ TestEqual(TEXT("own frame thought"), Model->GetFramesThought(), int64(1));+ const FVerseSelfPercept Self = UVerseHarnessPerceptFeed::SelfOf(*Model);+ TestEqual(TEXT("self percept is the own pawn"), Self.Location, Pawn->GetActorLocation());+ Model->DetachPerception();+ TestEqual(TEXT("detached"), Feed->NumObservers(), 0);+ return true;+}++#endifdiff --git a/unreal/Verse/Source/VerseHarness/Private/VerseHarnessJson.cpp b/unreal/Verse/Source/VerseHarness/Private/VerseHarnessJson.cppnew file mode 100644index 0000000000..5d331bc33f--- /dev/null+++ b/unreal/Verse/Source/VerseHarness/Private/VerseHarnessJson.cpp@@ -0,0 +1,457 @@+#include "VerseHarnessJson.h"++#include "Misc/Parse.h"++namespace VerseHarnessJsonPrivate+{+ constexpr int32 MaxDepth = 64;++ struct FReader+ {+ const TCHAR* At;+ const TCHAR* End;+ FString Error;++ void Skip()+ {+ while (At < End && (*At == ' ' || *At == '\t' || *At == '\n' || *At == '\r'))+ {+ ++At;+ }+ }++ bool Fail(const TCHAR* Why)+ {+ if (Error.IsEmpty())+ {+ Error = Why;+ }+ return false;+ }++ bool Literal(const TCHAR* Word)+ {+ const int32 Len = FCString::Strlen(Word);+ if (End - At >= Len && FCString::Strncmp(At, Word, Len) == 0)+ {+ At += Len;+ return true;+ }+ return false;+ }++ bool ParseString(FString& Out)+ {+ if (At >= End || *At != '"')+ {+ return Fail(TEXT("expected a string"));+ }+ ++At;+ while (At < End && *At != '"')+ {+ TCHAR C = *At++;+ if (C == '\\')+ {+ if (At >= End)+ {+ return Fail(TEXT("unterminated escape"));+ }+ const TCHAR E = *At++;+ switch (E)+ {+ case '"': Out.AppendChar('"'); break;+ case '\\': Out.AppendChar('\\'); break;+ case '/': Out.AppendChar('/'); break;+ case 'b': Out.AppendChar('\b'); break;+ case 'f': Out.AppendChar('\f'); break;+ case 'n': Out.AppendChar('\n'); break;+ case 'r': Out.AppendChar('\r'); break;+ case 't': Out.AppendChar('\t'); break;+ case 'u':+ {+ if (End - At < 4)+ {+ return Fail(TEXT("short unicode escape"));+ }+ const FString Hex(4, At);+ At += 4;+ Out.AppendChar(TCHAR(FParse::HexNumber(*Hex)));+ break;+ }+ default:+ return Fail(TEXT("unknown escape"));+ }+ }+ else+ {+ Out.AppendChar(C);+ }+ }+ if (At >= End)+ {+ return Fail(TEXT("unterminated string"));+ }+ ++At;+ return true;+ }++ bool ParseValue(FVerseJson& Out, int32 Depth)+ {+ if (Depth > MaxDepth)+ {+ return Fail(TEXT("nested too deep"));+ }+ Skip();+ if (At >= End)+ {+ return Fail(TEXT("unexpected end"));+ }+ const TCHAR C = *At;+ if (C == '{')+ {+ Out.Type = FVerseJson::EType::Object;+ ++At;+ Skip();+ if (At < End && *At == '}')+ {+ ++At;+ return true;+ }+ while (true)+ {+ Skip();+ FString Key;+ if (!ParseString(Key))+ {+ return false;+ }+ Skip();+ if (At >= End || *At != ':')+ {+ return Fail(TEXT("expected ':'"));+ }+ ++At;+ TSharedPtr<FVerseJson> Child = MakeShared<FVerseJson>();+ if (!ParseValue(*Child, Depth + 1))+ {+ return false;+ }+ Out.Object.Emplace(MoveTemp(Key), Child);+ Skip();+ if (At < End && *At == ',')+ {+ ++At;+ continue;+ }+ if (At < End && *At == '}')+ {+ ++At;+ return true;+ }+ return Fail(TEXT("expected ',' or '}'"));+ }+ }+ if (C == '[')+ {+ Out.Type = FVerseJson::EType::Array;+ ++At;+ Skip();+ if (At < End && *At == ']')+ {+ ++At;+ return true;+ }+ while (true)+ {+ TSharedPtr<FVerseJson> Child = MakeShared<FVerseJson>();+ if (!ParseValue(*Child, Depth + 1))+ {+ return false;+ }+ Out.Array.Add(Child);+ Skip();+ if (At < End && *At == ',')+ {+ ++At;+ continue;+ }+ if (At < End && *At == ']')+ {+ ++At;+ return true;+ }+ return Fail(TEXT("expected ',' or ']'"));+ }+ }+ if (C == '"')+ {+ Out.Type = FVerseJson::EType::String;+ return ParseString(Out.String);+ }+ if (Literal(TEXT("true")))+ {+ Out.Type = FVerseJson::EType::Bool;+ Out.bBool = true;+ return true;+ }+ if (Literal(TEXT("false")))+ {+ Out.Type = FVerseJson::EType::Bool;+ return true;+ }+ if (Literal(TEXT("null")))+ {+ Out.Type = FVerseJson::EType::Null;+ return true;+ }+ const TCHAR* Start = At;+ while (At < End && (FChar::IsDigit(*At) || *At == '-' || *At == '+' || *At == '.' || *At == 'e' || *At == 'E'))+ {+ ++At;+ }+ if (At == Start)+ {+ return Fail(TEXT("unexpected character"));+ }+ Out.Type = FVerseJson::EType::Number;+ Out.Number = FCString::Atod(*FString(int32(At - Start), Start));+ return true;+ }+ };+}++TSharedPtr<FVerseJson> FVerseJson::Parse(const FString& Text, FString& OutError)+{+ VerseHarnessJsonPrivate::FReader Reader{*Text, *Text + Text.Len(), FString()};+ TSharedPtr<FVerseJson> Root = MakeShared<FVerseJson>();+ if (!Reader.ParseValue(*Root, 0))+ {+ OutError = Reader.Error;+ return nullptr;+ }+ Reader.Skip();+ if (Reader.At != Reader.End)+ {+ OutError = TEXT("trailing characters after the document");+ return nullptr;+ }+ return Root;+}++const FVerseJson* FVerseJson::Find(const TCHAR* Key) const+{+ for (const TPair<FString, TSharedPtr<FVerseJson>>& Member : Object)+ {+ if (Member.Key == Key)+ {+ return Member.Value.Get();+ }+ }+ return nullptr;+}++bool FVerseJson::TryString(const TCHAR* Key, FString& Out) const+{+ const FVerseJson* V = Find(Key);+ if (V && V->Type == EType::String)+ {+ Out = V->String;+ return true;+ }+ return false;+}++bool FVerseJson::TryNumber(const TCHAR* Key, double& Out) const+{+ const FVerseJson* V = Find(Key);+ if (V && V->Type == EType::Number)+ {+ Out = V->Number;+ return true;+ }+ return false;+}++bool FVerseJson::TryInt(const TCHAR* Key, int32& Out) const+{+ double Value = 0.0;+ if (TryNumber(Key, Value))+ {+ Out = int32(Value);+ return true;+ }+ return false;+}++bool FVerseJson::TryFloat(const TCHAR* Key, float& Out) const+{+ double Value = 0.0;+ if (TryNumber(Key, Value))+ {+ Out = float(Value);+ return true;+ }+ return false;+}++bool FVerseJson::TryBool(const TCHAR* Key, bool& Out) const+{+ const FVerseJson* V = Find(Key);+ if (V && V->Type == EType::Bool)+ {+ Out = V->bBool;+ return true;+ }+ return false;+}++const FVerseJson* FVerseJson::ObjectField(const TCHAR* Key) const+{+ const FVerseJson* V = Find(Key);+ return V && V->Type == EType::Object ? V : nullptr;+}++const TArray<TSharedPtr<FVerseJson>>* FVerseJson::ArrayField(const TCHAR* Key) const+{+ const FVerseJson* V = Find(Key);+ return V && V->Type == EType::Array ? &V->Array : nullptr;+}++FString FVerseJson::StringOr(const TCHAR* Key, const FString& Default) const+{+ FString Out;+ return TryString(Key, Out) ? Out : Default;+}++FString FVerseJson::ToString() const+{+ switch (Type)+ {+ case EType::Bool:+ return bBool ? TEXT("true") : TEXT("false");+ case EType::Number:+ return FVerseJsonWriter::Number(Number);+ case EType::String:+ return FVerseJsonWriter::Quote(String);+ case EType::Array:+ {+ TArray<FString> Parts;+ for (const TSharedPtr<FVerseJson>& V : Array)+ {+ Parts.Add(V.IsValid() ? V->ToString() : TEXT("null"));+ }+ return TEXT("[") + FString::Join(Parts, TEXT(",")) + TEXT("]");+ }+ case EType::Object:+ {+ TArray<FString> Parts;+ for (const TPair<FString, TSharedPtr<FVerseJson>>& M : Object)+ {+ Parts.Add(FVerseJsonWriter::Quote(M.Key) + TEXT(":") + (M.Value.IsValid() ? M.Value->ToString() : TEXT("null")));+ }+ return TEXT("{") + FString::Join(Parts, TEXT(",")) + TEXT("}");+ }+ default:+ return TEXT("null");+ }+}++FString FVerseJsonWriter::Quote(const FString& Text)+{+ FString Out(TEXT("\""));+ for (const TCHAR C : Text)+ {+ switch (C)+ {+ case '"': Out += TEXT("\\\""); break;+ case '\\': Out += TEXT("\\\\"); break;+ case '\n': Out += TEXT("\\n"); break;+ case '\r': Out += TEXT("\\r"); break;+ case '\t': Out += TEXT("\\t"); break;+ default:+ if (C < 0x20)+ {+ Out += FString::Printf(TEXT("\\u%04x"), uint32(C));+ }+ else+ {+ Out.AppendChar(C);+ }+ }+ }+ Out.AppendChar('"');+ return Out;+}++FString FVerseJsonWriter::Number(double Value)+{+ if (!FMath::IsFinite(Value))+ {+ return TEXT("null");+ }+ if (FMath::Abs(Value) < 9.0e15 && Value == FMath::RoundToDouble(Value))+ {+ return FString::Printf(TEXT("%lld"), int64(Value));+ }+ FString Text = FString::Printf(TEXT("%.6f"), Value);+ while (Text.EndsWith(TEXT("0")))+ {+ Text.LeftChopInline(1);+ }+ return Text;+}++void FVerseJsonWriter::Key(const TCHAR* Name)+{+ if (!Body.IsEmpty())+ {+ Body.AppendChar(',');+ }+ Body += Quote(Name);+ Body.AppendChar(':');+}++FVerseJsonWriter& FVerseJsonWriter::Str(const TCHAR* K, const FString& Value)+{+ Key(K);+ Body += Quote(Value);+ return *this;+}++FVerseJsonWriter& FVerseJsonWriter::Num(const TCHAR* K, double Value)+{+ Key(K);+ Body += Number(Value);+ return *this;+}++FVerseJsonWriter& FVerseJsonWriter::Bool(const TCHAR* K, bool Value)+{+ Key(K);+ Body += Value ? TEXT("true") : TEXT("false");+ return *this;+}++FVerseJsonWriter& FVerseJsonWriter::Null(const TCHAR* K)+{+ Key(K);+ Body += TEXT("null");+ return *this;+}++FVerseJsonWriter& FVerseJsonWriter::Raw(const TCHAR* K, const FString& Json)+{+ Key(K);+ Body += Json;+ return *this;+}++FVerseJsonWriter& FVerseJsonWriter::Numbers(const TCHAR* K, const TArray<float>& Values)+{+ TArray<FString> Parts;+ for (float V : Values)+ {+ Parts.Add(Number(V));+ }+ return Raw(K, TEXT("[") + FString::Join(Parts, TEXT(",")) + TEXT("]"));+}diff --git a/unreal/Verse/Source/VerseHarness/Private/VerseHarnessSubsystem.cpp b/unreal/Verse/Source/VerseHarness/Private/VerseHarnessSubsystem.cppnew file mode 100644index 0000000000..feedf282f0--- /dev/null+++ b/unreal/Verse/Source/VerseHarness/Private/VerseHarnessSubsystem.cpp@@ -0,0 +1,194 @@+#include "VerseHarnessSubsystem.h"++#include "Balance/VerseBalanceGauntletController.h"+#include "Balance/VerseHarnessScenario.h"+#include "Capture/VerseCaptureDirector.h"+#include "Engine/GameInstance.h"+#include "Engine/World.h"+#include "GameFramework/Character.h"+#include "GameFramework/PlayerController.h"+#include "HAL/PlatformMisc.h"+#include "HAL/PlatformTime.h"+#include "Misc/CommandLine.h"+#include "Misc/FileHelper.h"+#include "Misc/Parse.h"+#include "VerseLog.h"++namespace VerseHarnessSubsystemPrivate+{+ bool Switch(const TCHAR* Name, FString& Out) { return FParse::Value(FCommandLine::Get(), Name, Out); }+}++bool UVerseHarnessSubsystem::IsHarnessRun()+{+ FString Unused;+ using namespace VerseHarnessSubsystemPrivate;+ return Switch(TEXT("VerseHarness="), Unused) || Switch(TEXT("VerseCapture="), Unused)+ || Switch(TEXT("VerseNetDuration="), Unused);+}++bool UVerseHarnessSubsystem::ShouldCreateSubsystem(UObject* Outer) const+{+ return IsHarnessRun() && Super::ShouldCreateSubsystem(Outer);+}++void UVerseHarnessSubsystem::Initialize(FSubsystemCollectionBase& Collection)+{+ Super::Initialize(Collection);+ StartWallS = FPlatformTime::Seconds();+ TickHandle = FTSTicker::GetCoreTicker().AddTicker(+ FTickerDelegate::CreateUObject(this, &UVerseHarnessSubsystem::TickHarness));+}++void UVerseHarnessSubsystem::Deinitialize()+{+ FTSTicker::GetCoreTicker().RemoveTicker(TickHandle);+ Super::Deinitialize();+}++void UVerseHarnessSubsystem::Quit(const TCHAR* Why, uint8 ExitCode)+{+ if (bQuitRequested)+ {+ return;+ }+ bQuitRequested = true;+ UE_LOG(LogVerseHarness, Display, TEXT("[VerseHarness] exit %d: %s"), int32(ExitCode), Why);+ if (ExitCode != 0)+ {+ FPlatformMisc::RequestExitWithStatus(false, ExitCode, TEXT("VerseHarness"));+ return;+ }+ FPlatformMisc::RequestExit(false, TEXT("VerseHarness"));+}++void UVerseHarnessSubsystem::StartDrivers(UWorld* World)+{+ using namespace VerseHarnessSubsystemPrivate;+ bStarted = true;+ FString Path;+ FString Error;+ if (Switch(TEXT("VerseHarness="), Path))+ {+ FString Text;+ FVerseHarnessScenario Scenario;+ if (!FFileHelper::LoadFileToString(Text, *Path) || !FVerseHarnessScenario::Parse(Text, Scenario, Error))+ {+ UE_LOG(LogVerseHarness, Error, TEXT("[VerseHarness] scenario %s: %s"), *Path, *Error);+ Quit(TEXT("bad scenario"), 2);+ return;+ }+ Balance = NewObject<UVerseBalanceGauntletController>(this);+ if (!Balance->Start(World, Scenario, Error))+ {+ UE_LOG(LogVerseHarness, Error, TEXT("[VerseHarness] cannot start: %s"), *Error);+ Quit(TEXT("start failed"), 2);+ }+ return;+ }+ if (Switch(TEXT("VerseCapture="), Path))+ {+ FString Text;+ FVerseCaptureScript Script;+ if (!FFileHelper::LoadFileToString(Text, *Path) || !FVerseCaptureScript::Parse(Text, Script, Error))+ {+ UE_LOG(LogVerseHarness, Error, TEXT("[VerseCapture] script %s: %s"), *Path, *Error);+ Quit(TEXT("bad capture script"));+ return;+ }+ FString Out;+ if (!Switch(TEXT("VerseCaptureOut="), Out))+ {+ Out = FPaths::Combine(FPaths::ProjectSavedDir(), TEXT("Harness"), TEXT("proof"), TEXT("capture"));+ }+ Capture = NewObject<UVerseCaptureDirector>(this);+ if (!Capture->Start(World, Script, Out, FParse::Param(FCommandLine::Get(), TEXT("VersePerf")), Error))+ {+ Quit(TEXT("capture start failed"));+ }+ return;+ }+ FString Duration;+ if (Switch(TEXT("VerseNetDuration="), Duration))+ {+ NetDurationS = FCString::Atod(*Duration);+ NetStartS = World->GetTimeSeconds();+ FString Seed;+ bAutopilot = Switch(TEXT("VerseNetAutopilot="), Seed);+ AutopilotRng = FVerseRng(uint64(FCString::Atoi64(*Seed)), 0, EVerseRngSalt::Harness);+ if (World->GetNetMode() == NM_DedicatedServer || World->GetNetMode() == NM_ListenServer)+ {+ UE_LOG(LogVerseHarness, Display, TEXT("[VerseNet] server ready"));+ }+ }+}++void UVerseHarnessSubsystem::TickNet(UWorld* World, float DeltaS)+{+ const double Now = World->GetTimeSeconds();+ if (bAutopilot && World->GetNetMode() == NM_Client)+ {+ APlayerController* PC = World->GetFirstPlayerController();+ ACharacter* Character = PC ? Cast<ACharacter>(PC->GetPawn()) : nullptr;+ if (Character)+ {+ if (Now >= NextTurnS)+ {+ AutopilotMove = AutopilotRng.UnitDisk().GetSafeNormal();+ NextTurnS = Now + AutopilotRng.Range(0.5, 2.0);+ if (AutopilotRng.Chance(0.25))+ {+ Character->Jump();+ }+ if (AutopilotRng.Chance(0.2))+ {+ Character->bIsCrouched ? Character->UnCrouch() : Character->Crouch();+ }+ }+ Character->AddMovementInput(FVector(AutopilotMove.X, AutopilotMove.Y, 0.0), 1.f);+ ++AutopilotTicks;+ }+ }+ if (NetStartS >= 0.0 && Now - NetStartS >= NetDurationS)+ {+ UE_LOG(LogVerseHarness, Display, TEXT("[VerseCounter] autopilotTicks=%lld"), AutopilotTicks);+ Quit(TEXT("netcode duration reached"));+ }+}++bool UVerseHarnessSubsystem::TickHarness(float DeltaS)+{+ if (bQuitRequested)+ {+ return true;+ }+ UGameInstance* GI = GetGameInstance();+ UWorld* World = GI ? GI->GetWorld() : nullptr;+ if (!World || !World->HasBegunPlay())+ {+ if (FPlatformTime::Seconds() - StartWallS > 600.0)+ {+ Quit(TEXT("no game world after 10 minutes"));+ }+ return true;+ }+ if (!bStarted)+ {+ StartDrivers(World);+ }+ if (Balance && !Balance->Tick())+ {+ // A failed unit or the wall-clock guard leaves the run short: exit non-zero (balance.py).+ const bool bShort = Balance->HasFailed() || Balance->GetEndReason() != TEXT("all units played");+ Quit(*(TEXT("balance run finished: ") + Balance->GetEndReason()), bShort ? 3 : 0);+ }+ if (Capture && !Capture->Tick(DeltaS))+ {+ Quit(TEXT("capture finished"));+ }+ if (NetStartS >= 0.0)+ {+ TickNet(World, DeltaS);+ }+ return true;+}diff --git a/unreal/Verse/Source/VerseHarness/Public/Balance/VerseBalanceGauntletController.h b/unreal/Verse/Source/VerseHarness/Public/Balance/VerseBalanceGauntletController.hnew file mode 100644index 0000000000..fe39d0b343--- /dev/null+++ b/unreal/Verse/Source/VerseHarness/Public/Balance/VerseBalanceGauntletController.h@@ -0,0 +1,135 @@+#pragma once++#include "Balance/VerseBoutRecorder.h"+#include "Balance/VerseHarnessScenario.h"+#include "Balance/VersePersonModels.h"+#include "CoreMinimal.h"+#include "UObject/Object.h"++#include "VerseBalanceGauntletController.generated.h"++class AController;+class UVerseBotTier;+class UVerseHarnessPerceptFeed;+class UWorld;+struct FVerseDeathEvent;+struct FVerseFireEvent;+struct FVerseGadgetEvent;+struct FVerseHitEvent;+struct FVerseReloadEvent;++/**+ * Drives one headless balance process (bot.md 11.1): both slots possessed on the dedicated+ * server, endless deathmatch cut into bouts (first to KillsToWin or MatchTimeLimitS of match+ * time), spawn sides alternating per bout, one verse.bout/1 line per bout in+ * <output>/bouts.jsonl and <output>/speed.json (x real time, RK1) when the scenario is done.+ *+ * Started by UVerseHarnessSubsystem from -VerseHarness=<scenario.json>. It is a plain UObject+ * driven by the subsystem's ticker, so it needs no Gauntlet plugin dependency; the Unreal+ * Gauntlet test node can wrap this process later without changing it.+ *+ * Bot slots spawn /Script/VerseBot.VerseBotController when that class exists (WP08) and get+ * their tier through the frozen SetTier(const UVerseBotTier*) and SetAdaptive(bool) (the tier+ * asset is tiers.json start values plus the unit's tierPatch; learning off sets LearnWeightMax 0).+ * A bot class that cannot be configured fails the run. Until WP08 lands the slot falls back to a+ * null-brain AVerseModelController with the tier's person parameters; speed.json names which ran.+ *+ * Model slots observe through the percept feed (UVerseHarnessPerceptFeed, the stand-in for+ * UVersePerceptionService) and drive their pawns from it every server tick.+ *+ * Spawn sides: the controller picks one spawn pair per unit (two player starts tagged VerseSide0+ * and VerseSide1, else the first start by name and the start farthest from it, else two+ * harness transforms 20 m apart). Every bout respawns both pawns; slot A takes side BoutIndex % 2.+ * The bout line records the side slot A actually spawned on, measured from its pawn.+ */+UCLASS()+class VERSEHARNESS_API UVerseBalanceGauntletController : public UObject+{+ GENERATED_BODY()++public:+ bool Start(UWorld* InWorld, const FVerseHarnessScenario& InScenario, FString& OutError);++ /** One frame; returns false once the run finished and exit was requested. */+ bool Tick();++ bool IsFinished() const { return bFinished; }++ /** True when the run ended on an error (a slot that could not be configured, a bad patch). */+ bool HasFailed() const { return bFailed; }+ const FString& GetEndReason() const { return EndReason; }++ /** Test hooks: the slot controllers, the spawn pair and the side slot A spawned on this bout. */+ AController* GetSlot(int32 Index) const { return Slots.IsValidIndex(Index) ? Slots[Index].Get() : nullptr; }+ const FTransform& GetSpawnTransform(int32 Side) const { return SpawnPair[Side & 1]; }+ int32 GetSpawnSideA() const { return SpawnSideA; }+ int32 GetBoutIndex() const { return BoutIndex; }+ UVerseHarnessPerceptFeed* GetPerceptFeed() const { return Feed; }+ void EndBoutForTest() { EndBout(); }++ /**+ * A tier asset for a slot: start values of TierId (adaptive starts from normal), the patch+ * (either {Field: value} for every tier or {tierId: {Field: value}}; field names are+ * UVerseBotTier's), LearnWeightMax 0 when learning is off. Null with a reason on any error.+ */+ static UVerseBotTier* MakeTier(UObject* Outer, FName TierId, bool bLearning, const FString& TierPatchJson, FString& OutError);++ /** A tier-based person model (trick models "base hard", bot stand-ins) from a tier asset. */+ static FVersePersonModel PersonFromTier(const UVerseBotTier& Tier, FName Name);++private:+ void BeginUnit();+ void BeginBout();+ void EndBout();+ void Finish(const TCHAR* Why);+ void Fail(const FString& Why);+ AController* SpawnSlot(const FVerseHarnessSlot& Slot, const FString& TierPatchJson, uint32 SlotSeed, FString& OutError);+ bool ConfigureBot(AController& Bot, const FVerseHarnessSlot& Slot, const FString& TierPatchJson, FString& OutError);+ void ResolveSpawnPair();+ void RespawnSlot(AController& Controller, const FTransform& Where);+ int32 MeasureSpawnSideA() const;+ double ServerMs() const;+ void ClearSlots();+ int32 PlayerIdOf(const AController* Controller) const;+ double Now() const;+ void ReadAdaptive();++ void HandleFire(const FVerseFireEvent& Event);+ void HandleHit(const FVerseHitEvent& Event);+ void HandleDeath(const FVerseDeathEvent& Event);+ void HandleReload(const FVerseReloadEvent& Event);+ void HandleGadget(const FVerseGadgetEvent& Event);++ TWeakObjectPtr<UWorld> World;+ FVerseHarnessScenario Scenario;+ FVersePersonModelSet PersonModels;+ int32 UnitIndex = -1;+ int32 BoutIndex = 0;+ double BoutStartS = 0.0;+ double BoutStartMs = 0.0;+ int32 SpawnSideA = 0;+ FTransform SpawnPair[2];+ double MatchTimeS = 0.0;+ TUniquePtr<FVerseBoutRecorder> Recorder;+ TArray<TWeakObjectPtr<AController>> Slots;+ TArray<float> AdaptiveTrace;+ FString BoutsFile;+ FString BotControllerKind;+ double WallStartS = 0.0;+ double SimStartS = 0.0;+ double StartupS = 0.0;+ double SimTotalS = 0.0;+ int64 Ticks = 0;+ bool bFinished = false;+ bool bFailed = false;+ bool bWarnedNoSkill = false;+ FString EndReason;+ TArray<FDelegateHandle> HubHandles;++ UPROPERTY()+ TObjectPtr<UVerseHarnessPerceptFeed> Feed;++ /** Tier assets handed to bots and models of the current unit (kept alive for SetTier). */+ UPROPERTY()+ TArray<TObjectPtr<UVerseBotTier>> UnitTiers;+};diff --git a/unreal/Verse/Source/VerseHarness/Public/Balance/VerseBoutRecorder.h b/unreal/Verse/Source/VerseHarness/Public/Balance/VerseBoutRecorder.hnew file mode 100644index 0000000000..6f3739612f--- /dev/null+++ b/unreal/Verse/Source/VerseHarness/Public/Balance/VerseBoutRecorder.h@@ -0,0 +1,109 @@+#pragma once++#include "Combat/VerseCombatTypes.h"+#include "CoreMinimal.h"++/** Side of a pairing: A is the side under test. */+enum class EVerseSide : uint8+{+ A,+ B,+ None+};++/** One kill on the bout timeline (verse.bout/1 "kills"). */+struct VERSEHARNESS_API FVerseBoutKill+{+ double T = 0.0;+ EVerseSide Killer = EVerseSide::None;+ EVerseDamageSource Cause = EVerseDamageSource::Bolt;+ bool bHeadshot = false;+ bool bWall = false;+ float RangeM = -1.f;+ float TtkS = -1.f;+ bool bSpawnKill = false;+};++/** Per-side counters of one bout (verse.bout/1 "a" and "b"). */+struct VERSEHARNESS_API FVerseBoutSide+{+ int32 Kills = 0;+ int32 Deaths = 0;+ int32 Shots = 0;+ int32 Hits = 0;+ int32 HeadshotHits = 0;+ TArray<float> TimeToContactS;+ int32 BulwarkUses = 0;+ int32 BreachUses = 0;+ int32 ReloadsInFight = 0;+ int32 StuckEvents = 0;++ // Per-life state.+ double LifeStartS = 0.0;+ double FirstHitTakenS = -1.0;+ bool bContactThisLife = false;+ double LastFightS = -1.0e9;+ FVector LastMovedFrom = FVector::ZeroVector;+ double LastMovedS = 0.0;+ bool bHasPosition = false;+};++/**+ * Turns hub events of one bout into the verse.bout/1 record (bot.md 11.3). Pure logic: the+ * gauntlet controller feeds it events and clock values, the tests feed it synthetic ones.+ * Times are seconds of match time since the bout began.+ */+class VERSEHARNESS_API FVerseBoutRecorder+{+public:+ /** Kills within this long of the victim's (re)spawn are spawn kills (bot.md 11.3). */+ static constexpr double SpawnKillWindowS = 3.0;+ /** A reload this soon after a hit involving the reloader counts as in-fight. */+ static constexpr double FightWindowS = 3.0;+ /** Alive and not moved 50 cm for this long is a stuck event. */+ static constexpr double StuckAfterS = 15.0;+ static constexpr double StuckDistanceCm = 50.0;++ FVerseBoutRecorder(int32 InPlayerIdA, int32 InPlayerIdB, int32 InKillsToWin, double InTimeLimitS);++ EVerseSide SideOf(int32 PlayerId) const;++ void OnFire(const FVerseFireEvent& Event, double T);+ void OnHit(const FVerseHitEvent& Event, double T);+ void OnDeath(const FVerseDeathEvent& Event, double T);+ void OnReload(const FVerseReloadEvent& Event, double T);+ void OnGadget(const FVerseGadgetEvent& Event, double T);++ /** A respawn of PlayerId at time T (starts a life). */+ void OnRespawn(int32 PlayerId, double T);++ /** Pawn position sample for the stuck counter; bAlive false pauses it. */+ void SamplePosition(EVerseSide Side, const FVector& Location, bool bAlive, double T);++ /** True once a side reached KillsToWin or the time limit passed. */+ bool IsOver(double T) const;++ EVerseSide Winner() const;++ const FVerseBoutSide& Side(EVerseSide S) const { return S == EVerseSide::A ? SideA : SideB; }+ const TArray<FVerseBoutKill>& Kills() const { return KillList; }++ /** The verse.bout/1 line (no trailing newline). */+ FString ToJsonLine(const FString& Pairing, int32 Match, int32 Bout, uint32 Seed, int32 SpawnSideA,+ double DurationS, double MatchTimeStartS, const TArray<float>& AdaptiveTrace) const;++private:+ FVerseBoutSide& Mutable(EVerseSide S) { return S == EVerseSide::A ? SideA : SideB; }+ void Contact(EVerseSide S, double T);++ int32 PlayerIdA;+ int32 PlayerIdB;+ int32 KillsToWin;+ double TimeLimitS;+ FVerseBoutSide SideA;+ FVerseBoutSide SideB;+ TArray<FVerseBoutKill> KillList;+ /** The killing hit seen last per victim side, to classify the death that follows. */+ FVerseHitEvent LastHitOn[2];+ bool bHasLastHit[2] = {false, false};+};diff --git a/unreal/Verse/Source/VerseHarness/Public/Balance/VerseHarnessPerceptFeed.h b/unreal/Verse/Source/VerseHarness/Public/Balance/VerseHarnessPerceptFeed.hnew file mode 100644index 0000000000..e1ba61f00b--- /dev/null+++ b/unreal/Verse/Source/VerseHarness/Public/Balance/VerseHarnessPerceptFeed.h@@ -0,0 +1,46 @@+#pragma once++#include "Bot/VersePerceptTypes.h"+#include "CoreMinimal.h"+#include "UObject/Object.h"++#include "VerseHarnessPerceptFeed.generated.h"++class AController;+class UWorld;++DECLARE_MULTICAST_DELEGATE_TwoParams(FVerseHarnessPerceptFrameEvent, AController*, const FVersePerceptFrame&);++/**+ * The percept source of the harness person models until UVersePerceptionService lands (WP07,+ * VerseCombat). It has the frozen shape of that service (bot.md frozen interface):+ * RegisterObserver(AController*, const FVersePerceptionProfile&), UnregisterObserver and the+ * delegate OnPerceptFrame(AController*, const FVersePerceptFrame&), so the model controller+ * binds the real service without changing.+ *+ * It is a null perception: every server tick each observer gets a frame with the server time and+ * its own state (FVerseSelfPercept: what its own HUD shows) and no sighting, sound, bolt or hurt.+ * It never reports anything about another actor, so fairness F1 and F6 hold by construction.+ */+UCLASS()+class VERSEHARNESS_API UVerseHarnessPerceptFeed : public UObject+{+ GENERATED_BODY()++public:+ void RegisterObserver(AController* Observer, const FVersePerceptionProfile& Profile);+ void UnregisterObserver(AController* Observer);+ bool IsObserving(const AController* Observer) const;+ int32 NumObservers() const { return Observers.Num(); }++ /** One server tick: one frame per registered observer, in registration order. */+ void Tick(UWorld* World);++ /** The observer's own part of a frame (bot.md 3.3), exposed for tests. */+ static FVerseSelfPercept SelfOf(const AController& Observer);++ FVerseHarnessPerceptFrameEvent OnPerceptFrame;++private:+ TArray<TWeakObjectPtr<AController>> Observers;+};diff --git a/unreal/Verse/Source/VerseHarness/Public/Balance/VerseHarnessScenario.h b/unreal/Verse/Source/VerseHarness/Public/Balance/VerseHarnessScenario.hnew file mode 100644index 0000000000..7bb00bad3c--- /dev/null+++ b/unreal/Verse/Source/VerseHarness/Public/Balance/VerseHarnessScenario.h@@ -0,0 +1,76 @@+#pragma once++#include "CoreMinimal.h"++// The scenario file one headless harness process plays (schema verse.scenario/1,+// unreal/Verse/Harness/schema/scenario.schema.json; contracts/bot.md 11.1). balance.py writes+// it, UVerseBalanceGauntletController reads it from -VerseHarness=<file>.++enum class EVerseHarnessSlotKind : uint8+{+ Bot,+ Model+};++/** One side of a pairing. */+struct VERSEHARNESS_API FVerseHarnessSlot+{+ EVerseHarnessSlotKind Kind = EVerseHarnessSlotKind::Bot;++ /** normal, hard, elite, adaptive for a bot; the base tier of a trick model ("base hard"). */+ FName Tier;++ /** Per-match learning on (bot.md 7); BG8 runs the same pairing with it off. */+ bool bLearning = true;++ /** skilled or average (person_models.json); empty for a tier-based trick model. */+ FName Model;++ /** One of the 17 trick ids of bot.md 11.2, or none. */+ FName Trick;++ bool IsBot() const { return Kind == EVerseHarnessSlotKind::Bot; }++ /** The label balance.py uses in pairing ids: "hard", "hard-nolearn", "skilled+spray", "spray". */+ FString Label() const;+};++/** One match of one pairing: the smallest unit of work, seeded independently of --jobs. */+struct VERSEHARNESS_API FVerseHarnessUnit+{+ FString Pairing;+ FString Set;+ int32 Match = 0;+ uint32 Seed = 0;+ int32 Bouts = 1;+ FVerseHarnessSlot A;+ FVerseHarnessSlot B;+ int32 KillsToWin = 15;++ /** A bout ends at KillsToWin or after this much match time (bot.md 11.1: 10 minutes). */+ double MatchTimeLimitS = 600.0;++ /** Scripted scenario id (wall_opened_unseen, destruction_storm) or none. */+ FName Scenario;++ /** The --patch tier overrides as JSON text, applied by the bot when it lands (WP09). */+ FString TierPatchJson;+};++struct VERSEHARNESS_API FVerseHarnessScenario+{+ FString Run;+ int32 Job = 0;+ FString Map;+ FString OutputDir;++ /** Wall-clock guard; the process ends its run cleanly when it passes. 0 = none. */+ double MaxWallS = 0.0;++ bool bTraceBearing = false;+ bool bTraceFireAudit = true;+ TArray<FVerseHarnessUnit> Units;++ /** Parses a verse.scenario/1 document. False with a reason on any schema error. */+ static bool Parse(const FString& JsonText, FVerseHarnessScenario& Out, FString& OutError);+};diff --git a/unreal/Verse/Source/VerseHarness/Public/Balance/VerseModelController.h b/unreal/Verse/Source/VerseHarness/Public/Balance/VerseModelController.hnew file mode 100644index 0000000000..df603610cc--- /dev/null+++ b/unreal/Verse/Source/VerseHarness/Public/Balance/VerseModelController.h@@ -0,0 +1,93 @@+#pragma once++#include "Balance/VersePersonModels.h"+#include "Balance/VerseTrickOverrides.h"+#include "Bot/VersePerceptTypes.h"+#include "Combat/VerseCombatTypes.h"+#include "CoreMinimal.h"+#include "GameFramework/Controller.h"+#include "VerseRng.h"++#include "VerseModelController.generated.h"++class APawn;+class UVerseHarnessPerceptFeed;++/**+ * A person model in the balance harness (bot.md 11.1, 11.2; frozen interface): the same brain+ * as the bot with person parameters and optional trick overrides. It perceives only through+ * FVersePerceptFrame (fairness F6) and acts only through FVerseInputFrame (bot.md B1).+ *+ * Until VerseBot's FVerseBotBrainCore lands (WP08) the brain is the null brain: an empty input+ * frame every tick. SetBrain plugs the real one in without touching the model or trick layers.+ *+ * The loop: AttachPerception subscribes to OnPerceptFrame of the percept source (the harness+ * feed until UVersePerceptionService lands, WP07). Every frame runs Think and applies the result+ * to the possessed pawn through ApplyInputToPawn, so the trick layer acts even with the null+ * brain (a rusher runs, a silent model crouches).+ */+UCLASS()+class VERSEHARNESS_API AVerseModelController : public AController+{+ GENERATED_BODY()++public:+ using FBrain = TFunction<FVerseInputFrame(const FVersePerceptFrame&)>;++ AVerseModelController();++ virtual void PostInitializeComponents() override;++ virtual void Destroyed() override;++ void Configure(const FVersePersonModel& InModel, const FVerseTrickConfig& InTrick, uint32 InSeed);+ void SetBrain(FBrain InBrain);++ /** Subscribes to the feed's OnPerceptFrame and registers as an observer (one source at a time). */+ void AttachPerception(UVerseHarnessPerceptFeed* Feed, const FVersePerceptionProfile& Profile);+ void DetachPerception();++ /** OnPerceptFrame handler: Think on this controller's frames, then drive the pawn. */+ void HandlePerceptFrame(AController* Observer, const FVersePerceptFrame& Percepts);++ /** Frames this controller has thought about since Configure. */+ int64 GetFramesThought() const { return FramesThought; }++ /**+ * Applies one input frame to a pawn: look to the control rotation, Move in pawn space to+ * movement input, Jump, Crouch and Prone to an ACharacter. The VerseMovement and VerseCombat+ * input path of AVerseCharacter (combat-state.md 11.1, bot.md B1) takes the whole frame once it+ * lands; until then fire, ADS, reload, lean, sprint, gadgets and slots have no consumer.+ */+ static void ApplyInputToPawn(AController& Controller, APawn& Pawn, const FVerseInputFrame& Input);++ /** One server tick: brain, then reaction delay and turn-rate limit, then trick overrides. */+ FVerseInputFrame Think(const FVersePerceptFrame& Percepts, double NowS, float DeltaS);++ /** Forget everything learnt in the match (BG9: nothing carries over). */+ void ResetMatchMemory();++ const FVerseInputFrame& GetLastInput() const { return LastInput; }+ const FVersePersonModel& GetModel() const { return Model; }+ const FVerseTrickConfig& GetTrickConfig() const { return TrickConfig; }+ bool IsReacting(double NowS) const { return NowS < ReactUntilS; }++ /** Pure model layer, exposed for tests: delay and turn limit applied to a brain frame. */+ static FVerseInputFrame ApplyPersonLimits(const FVersePersonModel& Model, const FVerseInputFrame& Brain,+ bool bReacting, float DeltaS);++private:+ FVersePersonModel Model;+ FVerseTrickConfig TrickConfig;+ FVerseTrickState TrickState;+ FVerseRng Rng;+ uint32 Seed = 0;+ FBrain Brain;+ FVerseInputFrame LastInput;+ bool bSawLastTick = false;+ double ReactUntilS = 0.0;+ double LastFrameS = -1.0;+ int64 FramesThought = 0;+ TWeakObjectPtr<UVerseHarnessPerceptFeed> PerceptSource;+ FDelegateHandle PerceptHandle;+};diff --git a/unreal/Verse/Source/VerseHarness/Public/Balance/VersePersonModels.h b/unreal/Verse/Source/VerseHarness/Public/Balance/VersePersonModels.hnew file mode 100644index 0000000000..04b4b3e63b--- /dev/null+++ b/unreal/Verse/Source/VerseHarness/Public/Balance/VersePersonModels.h@@ -0,0 +1,94 @@+#pragma once++#include "CoreMinimal.h"++// Person models and tricks of contracts/bot.md 11.2, loaded from+// unreal/Verse/Data/bot/person_models.json. A person model is the bot brain with person+// parameters; a trick is a set of input overrides plus intent hints the brain reads.++/** The 17 trick ids of bot.md 11.2 (frozen ids; the order here is not frozen). */+enum class EVerseTrick : uint8+{+ None,+ Spray,+ Camper,+ Rusher,+ Slider,+ JumpPeek,+ LeanSpam,+ Prone,+ WallSpam,+ Turtle,+ Breacher,+ Knife,+ Finisher,+ Kiter,+ Watcher,+ Silent,+ Repeek,+ Hider,+ Count+};++VERSEHARNESS_API bool VerseTrickFromName(FName Name, EVerseTrick& OutTrick);+VERSEHARNESS_API FName VerseTrickName(EVerseTrick Trick);++/** Number of real tricks (bot.md 11.2: 17). */+constexpr int32 VerseTrickCount = int32(EVerseTrick::Count) - 1;++/** Person parameters the model controller applies on top of the shared brain. */+struct VERSEHARNESS_API FVersePersonModel+{+ FName Name;+ float ReactionMeanMs = 250.f;+ float ReactionSdMs = 30.f;+ float TurnRateDegS = 800.f;+ float RecoilPatternComp = 0.6f;+ float HeadAimChance = 0.2f;+ float AimWanderSdDeg = 1.f;+ float AimWanderTheta = 3.f;+ bool bLearning = true;+ float LearnWeight = 0.1f;+};++/** What a trick asks of the brain's decisions (read by the brain once WP08 lands). */+struct VERSEHARNESS_API FVerseTrickIntent+{+ float HoldSpawnCoverRadiusM = 0.f;+ bool bRushBelief = false;+ float PreferRangeM = 0.f;+ bool bWallShotAuthorityOff = false;+ bool bFireThroughPenetrable = false;+ bool bStayBehindBulwark = false;+ bool bBreachEveryRoutePiece = false;+ bool bStalkForFinisher = false;+ bool bWatchOpponentSpawn = false;+ float RepeekSameAngleWithinS = 0.f;+ bool bAvoidFights = false;+};++/** Input-level parameters of a trick (person_models.json "input"). */+struct VERSEHARNESS_API FVerseTrickConfig+{+ EVerseTrick Trick = EVerseTrick::None;+ FVerseTrickIntent Intent;+ float LeanFlipMinMs = 150.f;+ float LeanFlipMaxMs = 300.f;+ float ProneBeyondM = 20.f;+ float MeleeRangeM = 2.f;+ float BackOffInsideM = 30.f;+ float SlideCooldownS = 1.5f;+};++struct VERSEHARNESS_API FVersePersonModelSet+{+ TMap<FName, FVersePersonModel> Models;+ TMap<FName, FVerseTrickConfig> Tricks;++ static bool Parse(const FString& JsonText, FVersePersonModelSet& Out, FString& OutError);++ /** Reads <ProjectDir>/Data/bot/person_models.json. */+ static bool LoadDefault(FVersePersonModelSet& Out, FString& OutError);++ static FString DefaultPath();+};diff --git a/unreal/Verse/Source/VerseHarness/Public/Balance/VerseTrickOverrides.h b/unreal/Verse/Source/VerseHarness/Public/Balance/VerseTrickOverrides.hnew file mode 100644index 0000000000..1a4dfadc57--- /dev/null+++ b/unreal/Verse/Source/VerseHarness/Public/Balance/VerseTrickOverrides.h@@ -0,0 +1,31 @@+#pragma once++#include "Balance/VersePersonModels.h"+#include "Bot/VersePerceptTypes.h"+#include "Combat/VerseCombatTypes.h"+#include "CoreMinimal.h"+#include "VerseRng.h"++/** Per-controller memory of the trick overrides (one per life is fine; reset per match). */+struct VERSEHARNESS_API FVerseTrickState+{+ double NextLeanFlipS = 0.0;+ bool bLeanRight = false;+ double LastSlideS = -1.0e9;+ uint32 PrevButtons = 0;+};++/**+ * Trick overrides as a pure function of the percept frame and the brain's input frame+ * (bot.md 11.2). Reads only FVersePerceptFrame (fairness F6): never a true location.+ */+struct VERSEHARNESS_API FVerseTrickOverrides+{+ static FVerseInputFrame Apply(const FVerseTrickConfig& Config, const FVersePerceptFrame& Percepts,+ const FVerseInputFrame& Brain, FVerseTrickState& State, FVerseRng& Rng, double NowS);++ static bool AnySighting(const FVersePerceptFrame& Percepts);++ /** Distance in metres from the own eye to the nearest sighting's pelvis; huge when none. */+ static float NearestSightingM(const FVersePerceptFrame& Percepts);+};diff --git a/unreal/Verse/Source/VerseHarness/Public/Capture/VerseCaptureDirector.h b/unreal/Verse/Source/VerseHarness/Public/Capture/VerseCaptureDirector.hnew file mode 100644index 0000000000..161dad4097--- /dev/null+++ b/unreal/Verse/Source/VerseHarness/Public/Capture/VerseCaptureDirector.h@@ -0,0 +1,79 @@+#pragma once++#include "CoreMinimal.h"+#include "UObject/Object.h"++#include "VerseCaptureDirector.generated.h"++class ACameraActor;+class UWorld;++/** One reference view or keyframe of a verse.capture/1 file (Unreal cm and degrees). */+struct VERSEHARNESS_API FVerseCaptureView+{+ FString Id;+ FVector Location = FVector::ZeroVector;+ FRotator Rotation = FRotator::ZeroRotator;+ float FovDeg = 90.f;+ /** Keyframe time (flythrough) or shot time (shots), seconds. */+ double T = 0.0;+};++struct VERSEHARNESS_API FVerseCaptureScript+{+ FString Id;+ TArray<FVerseCaptureView> Views;+ int32 SettleFrames = 30;+ double WarmupS = 0.0;+ double FlythroughS = 0.0;+ TArray<FVerseCaptureView> Keys;+ TArray<FVerseCaptureView> Shots;++ static bool Parse(const FString& JsonText, FVerseCaptureScript& Out, FString& OutError);++ /** Camera pose along the flythrough at time T (linear, clamped at both ends). */+ FVerseCaptureView Sample(double T) const;+};++/**+ * Scripted camera for capture.py and perf.py (work-packages.md WP10.7, 10.8): places a camera+ * at each reference view, waits for shader compiles, async loading and streaming plus settle+ * frames, and writes <out>/<view>.png without UI; or flies the perf replay path, starting the+ * CSV profiler after the warm-up (-VersePerf) and stopping it before exit.+ */+UCLASS()+class VERSEHARNESS_API UVerseCaptureDirector : public UObject+{+ GENERATED_BODY()++public:+ bool Start(UWorld* InWorld, const FVerseCaptureScript& InScript, const FString& InOutDir, bool bInPerf,+ FString& OutError);++ /** One frame; false once done and exit was requested. */+ bool Tick(float DeltaS);++private:+ bool EnsureCamera();+ bool SceneIsReady() const;+ void Place(const FVerseCaptureView& View);+ void Shoot(const FString& Id);+ void Finish();++ TWeakObjectPtr<UWorld> World;+ TWeakObjectPtr<ACameraActor> Camera;+ FVerseCaptureScript Script;+ FString OutDir;+ bool bPerf = false;+ int32 ViewIndex = 0;+ int32 SettleLeft = 0;+ int32 PendingFrames = 0;+ FString PendingFile;+ double FlyStartS = -1.0;+ double ElapsedS = 0.0;+ int32 NextShot = 0;+ bool bProfiling = false;+ double StopAtS = -1.0;+ bool bDone = false;+ TArray<FString> Written;+};diff --git a/unreal/Verse/Source/VerseHarness/Public/VerseHarnessJson.h b/unreal/Verse/Source/VerseHarness/Public/VerseHarnessJson.hnew file mode 100644index 0000000000..57c1b3df27--- /dev/null+++ b/unreal/Verse/Source/VerseHarness/Public/VerseHarnessJson.h@@ -0,0 +1,69 @@+#pragma once++#include "CoreMinimal.h"++/**+ * A small JSON reader and writer for the harness files (verse.scenario/1, verse.capture/1,+ * person_models.json, verse.bout/1, speed.json). VerseHarness links only Core, CoreUObject,+ * Engine and the Verse modules (VerseHarness.Build.cs belongs to the integration owner), so it+ * cannot link the engine's Json module; these documents are small and plain, so this is enough.+ */+struct VERSEHARNESS_API FVerseJson+{+ enum class EType : uint8+ {+ Null,+ Bool,+ Number,+ String,+ Array,+ Object+ };++ EType Type = EType::Null;+ bool bBool = false;+ double Number = 0.0;+ FString String;+ TArray<TSharedPtr<FVerseJson>> Array;+ /** Members in document order. */+ TArray<TPair<FString, TSharedPtr<FVerseJson>>> Object;++ static TSharedPtr<FVerseJson> Parse(const FString& Text, FString& OutError);++ bool IsObject() const { return Type == EType::Object; }+ const FVerseJson* Find(const TCHAR* Key) const;++ bool TryString(const TCHAR* Key, FString& Out) const;+ bool TryNumber(const TCHAR* Key, double& Out) const;+ bool TryInt(const TCHAR* Key, int32& Out) const;+ bool TryFloat(const TCHAR* Key, float& Out) const;+ bool TryBool(const TCHAR* Key, bool& Out) const;+ const FVerseJson* ObjectField(const TCHAR* Key) const;+ const TArray<TSharedPtr<FVerseJson>>* ArrayField(const TCHAR* Key) const;+ FString StringOr(const TCHAR* Key, const FString& Default = FString()) const;++ /** Compact serialisation of this value. */+ FString ToString() const;+};++/** Builds one compact JSON object; values are appended in call order. */+class VERSEHARNESS_API FVerseJsonWriter+{+public:+ FVerseJsonWriter& Str(const TCHAR* Key, const FString& Value);+ FVerseJsonWriter& Num(const TCHAR* Key, double Value);+ FVerseJsonWriter& Bool(const TCHAR* Key, bool Value);+ FVerseJsonWriter& Null(const TCHAR* Key);+ /** Raw, already-serialised JSON (an object, array or number). */+ FVerseJsonWriter& Raw(const TCHAR* Key, const FString& Json);+ FVerseJsonWriter& Numbers(const TCHAR* Key, const TArray<float>& Values);++ FString Close() const { return TEXT("{") + Body + TEXT("}"); }++ static FString Quote(const FString& Text);+ static FString Number(double Value);++private:+ void Key(const TCHAR* Name);+ FString Body;+};diff --git a/unreal/Verse/Source/VerseHarness/Public/VerseHarnessSubsystem.h b/unreal/Verse/Source/VerseHarness/Public/VerseHarnessSubsystem.hnew file mode 100644index 0000000000..fab5d2d24c--- /dev/null+++ b/unreal/Verse/Source/VerseHarness/Public/VerseHarnessSubsystem.h@@ -0,0 +1,61 @@+#pragma once++#include "Containers/Ticker.h"+#include "CoreMinimal.h"+#include "Subsystems/GameInstanceSubsystem.h"+#include "VerseRng.h"++#include "VerseHarnessSubsystem.generated.h"++class UVerseBalanceGauntletController;+class UVerseCaptureDirector;++/**+ * Entry point of every harness run inside a game process. Reads the command line once the+ * game world is up and starts the matching driver:+ *+ * - -VerseHarness=<scenario.json>: balance bouts (UVerseBalanceGauntletController).+ * - -VerseCapture=<capture.json> -VerseCaptureOut=<dir> [-VersePerf]: screenshots or perf replay.+ * - -VerseNetDuration=<s> [-VerseNetAutopilot=<seed>]: netcode test; the server logs+ * "[VerseNet] server ready", clients walk with seeded input; both exit after the duration.+ *+ * Without any of these switches it does nothing, so loading the module in the editor is free.+ */+UCLASS()+class VERSEHARNESS_API UVerseHarnessSubsystem : public UGameInstanceSubsystem+{+ GENERATED_BODY()++public:+ virtual bool ShouldCreateSubsystem(UObject* Outer) const override;+ virtual void Initialize(FSubsystemCollectionBase& Collection) override;+ virtual void Deinitialize() override;++ /** True when the command line asks for any harness run. */+ static bool IsHarnessRun();++private:+ bool TickHarness(float DeltaS);+ void StartDrivers(UWorld* World);+ void TickNet(UWorld* World, float DeltaS);+ void Quit(const TCHAR* Why, uint8 ExitCode = 0);++ FTSTicker::FDelegateHandle TickHandle;++ UPROPERTY()+ TObjectPtr<UVerseBalanceGauntletController> Balance;++ UPROPERTY()+ TObjectPtr<UVerseCaptureDirector> Capture;++ bool bStarted = false;+ bool bQuitRequested = false;+ double NetDurationS = 0.0;+ double NetStartS = -1.0;+ bool bAutopilot = false;+ FVerseRng AutopilotRng;+ FVector2D AutopilotMove = FVector2D::ZeroVector;+ double NextTurnS = 0.0;+ int64 AutopilotTicks = 0;+ double StartWallS = 0.0;+};