Skip to content

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.

feat(verse): package the Unreal Verse as an optional on-demand download (#1136)

Ruben Lütke5030572f1b95
diff --git a/.github/workflows/unreal-package.yml b/.github/workflows/unreal-package.yml
new file mode 100644
index 0000000000..9b5d0fa9a7
--- /dev/null
+++ b/.github/workflows/unreal-package.yml
@@ -0,0 +1,469 @@
+# Unreal Verse packaging lane (docs/verse/unreal/architecture.md 8.3,
+# docs/verse/unreal/work-packages.md WP22).
+#
+# package self-hosted (the dev box): BuildCookRun Win64 and Linux
+# Shipping with IoStore chunks per deck, the harness check
+# and the size report. Builds go through
+# scripts/unreal/package.py, which takes the machine lock.
+# This job holds no secret and never signs: the runner is a
+# person's own machine (RK12).
+# sign-windows GitHub-hosted: hands the unsigned Verse binaries to the
+# existing SignPath signing path (docs/code-signing-policy.md)
+# and verifies the Authenticode signature before the signed
+# files replace the unsigned ones.
+# assemble GitHub-hosted: full package tar per platform, the delta
+# from the previous release and the per-platform release
+# manifest (package.py full / delta / manifest).
+# sign-manifest GitHub-hosted, release-signing environment: the release
+# key's Ed25519 signature over each verse-<Platform>-manifest.json
+# (version, sizes, SHA-256 of every package), the same key
+# the in-app updater pins, plus verse-SHA256SUMS.txt for
+# checking by hand.
+# release attaches the Verse assets to the tag's release, never
+# replacing an existing asset.
+#
+# The Verse is an optional download (docs/verse/unreal/README.md, Delivery):
+# these assets sit on the release beside the installers but no installer,
+# app update or source archive carries them. The app fetches them only when
+# the user presses "Download the Verse" (dodaios/verse_host/install).
+# linux-smoke nightly, self-hosted: Linux Development package and the
+# 60 s container smoke (package.py linux-smoke).
+#
+# Self-hosted jobs never run for pull requests: this workflow has no
+# pull_request trigger at all (architecture.md 8.2).
+#
+# Each platform ships on its own: a failed Linux leg (or a failed Windows
+# signature) does not stop the other platform's payload. The jobs after
+# package run unless the run was cancelled, and a leg whose artifact is
+# missing fails on its own download step.
+
+name: unreal-package
+
+on:
+ push:
+ tags:
+ - "v*.*.*"
+ schedule:
+ # Nightly Linux smoke (A22.6); the quiet-hours rule of architecture.md 8.2.
+ - cron: "17 2 * * *"
+ workflow_dispatch:
+ inputs:
+ previous:
+ description: "Release tag the delta starts from (empty: the latest release)"
+ required: false
+ default: ""
+ smoke_only:
+ description: "Only run the Linux smoke"
+ type: boolean
+ required: false
+ default: false
+
+permissions:
+ contents: read
+
+concurrency:
+ group: unreal-build
+ cancel-in-progress: false
+
+env:
+ PYTHON_VERSION: "3.11"
+
+jobs:
+ package:
+ if: github.event_name != 'schedule' && !inputs.smoke_only
+ name: Package ${{ matrix.platform }} Shipping
+ runs-on: [self-hosted, windows, unreal]
+ timeout-minutes: 360
+ permissions:
+ contents: read
+ strategy:
+ # One build at a time on the box; the machine lock queues them anyway.
+ max-parallel: 1
+ fail-fast: false
+ matrix:
+ platform: [win64, linux]
+ steps:
+ - name: Checkout
+ uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
+ with:
+ persist-credentials: false
+ lfs: false
+
+ # .lfsconfig keeps installs from fetching unreal/**; the runner needs it.
+ - name: Fetch the Unreal LFS objects
+ shell: pwsh
+ run: |
+ git config lfs.fetchexclude ""
+ git lfs pull
+
+ - name: Check the toolchain
+ run: python scripts/unreal/package.py verify --target ${{ matrix.platform }}
+
+ - name: BuildCookRun
+ run: python scripts/unreal/package.py build --platform ${{ matrix.platform }} --config Shipping
+
+ - name: Upload the unsigned payload
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ with:
+ name: verse-unsigned-${{ matrix.platform }}
+ path: unreal/Verse/Saved/Package/Shipping/${{ matrix.platform == 'win64' && 'Windows' || 'Linux' }}
+ if-no-files-found: error
+ retention-days: 7
+
+ - name: Upload the size report
+ if: always()
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ with:
+ name: verse-size-${{ matrix.platform }}
+ path: unreal/Verse/Saved/Harness/proof/WP22/
+ if-no-files-found: warn
+ retention-days: 30
+
+ sign-windows:
+ needs: package
+ if: ${{ !cancelled() && github.event_name != 'schedule' && !inputs.smoke_only }}
+ name: Sign the Verse binaries (Windows)
+ runs-on: windows-latest
+ timeout-minutes: 90
+ permissions:
+ contents: read
+ # SignPath reads this job's metadata and downloads the unsigned artifact
+ # with the job token.
+ actions: read
+ env:
+ HAS_SIGNPATH_SIGNING: ${{ github.ref_type == 'tag' && secrets.SIGNPATH_API_TOKEN != '' && vars.SIGNPATH_ORGANIZATION_ID != '' && vars.SIGNPATH_PROJECT_SLUG != '' && vars.SIGNPATH_SIGNING_POLICY_SLUG != '' }}
+ steps:
+ - name: Download the unsigned payload
+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
+ with:
+ name: verse-unsigned-win64
+ path: payload
+
+ - name: Collect the executables to sign
+ if: env.HAS_SIGNPATH_SIGNING == 'true'
+ shell: pwsh
+ run: |
+ $ErrorActionPreference = 'Stop'
+ $out = Join-Path $env:RUNNER_TEMP 'verse-exe'
+ Get-ChildItem -Path payload -Recurse -Include *.exe, *.dll | ForEach-Object {
+ $rel = $_.FullName.Substring((Resolve-Path payload).Path.Length + 1)
+ $dest = Join-Path $out $rel
+ New-Item -ItemType Directory -Force -Path (Split-Path $dest) | Out-Null
+ Copy-Item -LiteralPath $_.FullName -Destination $dest
+ }
+
+ - name: Stage the unsigned binaries for SignPath
+ id: signpath-unsigned
+ if: env.HAS_SIGNPATH_SIGNING == 'true'
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ with:
+ name: signpath-unsigned-verse-win64
+ path: ${{ runner.temp }}/verse-exe
+ if-no-files-found: error
+ retention-days: 1
+
+ - name: Sign the binaries (SignPath Foundation)
+ if: env.HAS_SIGNPATH_SIGNING == 'true'
+ # pin: signpath/[email protected] - pinned by commit SHA.
+ uses: signpath/github-action-submit-signing-request@f6d04783b4569d051e0c80105fe66e82819d0092
+ with:
+ api-token: ${{ secrets.SIGNPATH_API_TOKEN }}
+ organization-id: ${{ vars.SIGNPATH_ORGANIZATION_ID }}
+ project-slug: ${{ vars.SIGNPATH_PROJECT_SLUG }}
+ signing-policy-slug: ${{ vars.SIGNPATH_SIGNING_POLICY_SLUG }}
+ artifact-configuration-slug: ${{ vars.SIGNPATH_VERSE_ARTIFACT_CONFIGURATION_SLUG }}
+ github-artifact-id: ${{ steps.signpath-unsigned.outputs.artifact-id }}
+ wait-for-completion: true
+ wait-for-completion-timeout-in-seconds: 3600
+ output-artifact-directory: ${{ runner.temp }}/verse-signed
+
+ - name: Verify every signature, then replace the unsigned files
+ if: env.HAS_SIGNPATH_SIGNING == 'true'
+ shell: pwsh
+ run: |
+ $ErrorActionPreference = 'Stop'
+ $signedRoot = Join-Path $env:RUNNER_TEMP 'verse-signed'
+ $files = Get-ChildItem -Path $signedRoot -Recurse -Include *.exe, *.dll
+ if (-not $files) { Write-Host '::error::SignPath returned no binaries'; exit 1 }
+ foreach ($file in $files) {
+ $signature = Get-AuthenticodeSignature -LiteralPath $file.FullName
+ if ($signature.Status -ne 'Valid') {
+ Write-Host "::error::$($file.Name): $($signature.StatusMessage)"
+ exit 1
+ }
+ $rel = $file.FullName.Substring($signedRoot.Length + 1)
+ Copy-Item -LiteralPath $file.FullName -Destination (Join-Path payload $rel) -Force
+ }
+ Write-Host "Signed and verified $($files.Count) binaries."
+
+ - name: Without signing secrets the payload ships unsigned
+ if: env.HAS_SIGNPATH_SIGNING != 'true'
+ run: echo "::warning::No SignPath configuration on this run; the Verse binaries stay unsigned."
+
+ - name: Upload the payload for assembly
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ with:
+ name: verse-ready-win64
+ path: payload
+ if-no-files-found: error
+ retention-days: 7
+
+ assemble:
+ needs: [package, sign-windows]
+ if: ${{ !cancelled() && github.event_name != 'schedule' && !inputs.smoke_only }}
+ name: Payload and delta ${{ matrix.platform }}
+ runs-on: ubuntu-latest
+ timeout-minutes: 90
+ permissions:
+ contents: read
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - platform: Win64
+ artifact: verse-ready-win64
+ - platform: Linux
+ artifact: verse-unsigned-linux
+ steps:
+ - name: Checkout
+ uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
+ with:
+ persist-credentials: false
+ lfs: false
+
+ - name: Set up Python
+ uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: ${{ env.PYTHON_VERSION }}
+
+ - name: Download the payload
+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
+ with:
+ name: ${{ matrix.artifact }}
+ path: stage
+
+ - name: Full payload
+ id: full
+ shell: bash
+ run: |
+ set -euo pipefail
+ version="$(python -c 'import re,pathlib; print(re.search(r"__version__ = \"([^\"]+)\"", pathlib.Path("dodaios/__init__.py").read_text()).group(1))')"
+ echo "version=${version}" >> "$GITHUB_OUTPUT"
+ python -m pip install --quiet filelock
+ python scripts/unreal/package.py full --stage stage --version "${version}" \
+ --platform "${{ matrix.platform }}" --out "verse/Verse-${{ matrix.platform }}-${version}.tar"
+
+ - name: Delta from the previous release
+ shell: bash
+ env:
+ GH_TOKEN: ${{ github.token }}
+ PREVIOUS: ${{ inputs.previous }}
+ run: |
+ set -euo pipefail
+ previous="${PREVIOUS:-}"
+ if [ -z "${previous}" ]; then
+ previous="$(gh release list --repo "$GITHUB_REPOSITORY" --exclude-drafts --limit 20 \
+ --json tagName --jq '.[].tagName' | grep -vx "${GITHUB_REF_NAME}" | head -n 1 || true)"
+ fi
+ old_version="${previous#v}"
+ name="Verse-${{ matrix.platform }}-${old_version}.tar"
+ if [ -z "${previous}" ] || ! gh release download "${previous}" --repo "$GITHUB_REPOSITORY" \
+ --pattern "${name}" --dir old; then
+ echo "::notice::No ${name} on ${previous:-any release}; this release ships the full payload only."
+ exit 0
+ fi
+ python scripts/unreal/package.py delta --old "old/${name}" --stage stage \
+ --version "${{ steps.full.outputs.version }}" \
+ --out "verse/Verse-${{ matrix.platform }}-${old_version}-to-${{ steps.full.outputs.version }}.delta.tar"
+
+ - name: Release manifest
+ shell: bash
+ run: |
+ set -euo pipefail
+ version="${{ steps.full.outputs.version }}"
+ args=()
+ for delta in verse/Verse-${{ matrix.platform }}-*-to-"${version}".delta.tar; do
+ if [ -f "${delta}" ]; then args+=(--delta "${delta}"); fi
+ done
+ python scripts/unreal/package.py manifest \
+ --full "verse/Verse-${{ matrix.platform }}-${version}.tar" "${args[@]}" \
+ --tag "v${version}" --out "verse/verse-${{ matrix.platform }}-manifest.json"
+
+ - name: Upload the Verse assets
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ with:
+ name: verse-assets-${{ matrix.platform }}
+ path: verse/
+ if-no-files-found: error
+ retention-days: 7
+
+ sign-manifest:
+ needs: assemble
+ # Signs whatever platforms assembled; none at all fails the digest step.
+ if: ${{ !cancelled() && github.ref_type == 'tag' }}
+ name: Sign the Verse checksum manifest
+ environment: release-signing
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ permissions:
+ contents: read
+ steps:
+ - name: Checkout
+ uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
+ with:
+ persist-credentials: false
+
+ - name: Set up Python
+ uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: ${{ env.PYTHON_VERSION }}
+
+ - name: Download the Verse assets
+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
+ with:
+ pattern: verse-assets-*
+ path: verse
+ merge-multiple: true
+
+ - name: Check every manifest names this tag, write verse-SHA256SUMS.txt
+ shell: bash
+ run: |
+ set -euo pipefail
+ for manifest in verse/verse-*-manifest.json; do
+ tag="$(python -c 'import json,sys; print(json.load(open(sys.argv[1]))["tag"])' "${manifest}")"
+ if [ "${tag}" != "${GITHUB_REF_NAME}" ]; then
+ echo "::error::${manifest} names ${tag}, not ${GITHUB_REF_NAME}"
+ exit 1
+ fi
+ done
+ cd verse
+ sha256sum Verse-*.tar verse-*-manifest.json > verse-SHA256SUMS.txt
+ cat verse-SHA256SUMS.txt
+
+ - name: Sign every manifest with the release key
+ env:
+ WAVE2_OFFLINE_KEY_B64: ${{ secrets.WAVE2_OFFLINE_KEY_B64 }}
+ shell: bash
+ run: |
+ set -euo pipefail
+ if [ -z "${WAVE2_OFFLINE_KEY_B64:-}" ]; then
+ echo "::error::WAVE2_OFFLINE_KEY_B64 is not available to the release-signing environment; refusing to publish an unsigned Verse manifest."
+ exit 1
+ fi
+ key="${RUNNER_TEMP}/verse-manifest.key"
+ trap 'rm -f "$key" "${RUNNER_TEMP}/verse-manifest.sig.raw"' EXIT
+ umask 077
+ printf '%s' "${WAVE2_OFFLINE_KEY_B64}" | base64 -d > "$key"
+ if ! grep -q "BEGIN PRIVATE KEY" "$key"; then
+ echo "::error::WAVE2_OFFLINE_KEY_B64 does not decode to a PEM private key"
+ exit 1
+ fi
+ for manifest in verse/verse-*-manifest.json; do
+ openssl pkeyutl -sign -inkey "$key" -rawin -in "${manifest}" \
+ -out "${RUNNER_TEMP}/verse-manifest.sig.raw"
+ base64 -w0 "${RUNNER_TEMP}/verse-manifest.sig.raw" > "${manifest}.sig"
+ echo "Signed ${manifest} (key contents not logged)."
+ done
+
+ - name: Verify every signature against the pinned public key
+ shell: bash
+ run: |
+ set -euo pipefail
+ python -m pip install --quiet cryptography
+ for manifest in verse/verse-*-manifest.json; do
+ base64 -d "${manifest}.sig" > "${RUNNER_TEMP}/check.sig.raw"
+ openssl pkeyutl -verify -pubin -inkey install/keys/offline-ceremony.pub -rawin \
+ -in "${manifest}" -sigfile "${RUNNER_TEMP}/check.sig.raw"
+ platform="$(basename "${manifest}" | sed -E 's/^verse-(.*)-manifest\.json$/\1/')"
+ python -c 'import pathlib,sys; from dodaios.verse_host.install.manifest import verify_release_manifest as v; m=pathlib.Path(sys.argv[1]); v(m.read_bytes(), pathlib.Path(sys.argv[1]+".sig").read_text(), platform=sys.argv[2], tag=sys.argv[3]); print("verified", m.name)' \
+ "${manifest}" "${platform}" "${GITHUB_REF_NAME}"
+ done
+
+ - name: Upload the signed manifest
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ with:
+ name: verse-manifest
+ path: |
+ verse/verse-SHA256SUMS.txt
+ verse/verse-*-manifest.json.sig
+ if-no-files-found: error
+ retention-days: 14
+
+ release:
+ needs: sign-manifest
+ if: ${{ !cancelled() && github.ref_type == 'tag' && needs.sign-manifest.result == 'success' }}
+ name: Attach the Verse to the release
+ runs-on: ubuntu-latest
+ timeout-minutes: 60
+ permissions:
+ # The only job that writes, and only to attach the assets it verified.
+ contents: write
+ steps:
+ - name: Download the Verse assets
+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
+ with:
+ pattern: verse-assets-*
+ path: verse
+ merge-multiple: true
+
+ - name: Download the signed manifest
+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
+ with:
+ name: verse-manifest
+ path: verse
+
+ - name: Check the digests, then upload without replacing anything
+ shell: bash
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ set -euo pipefail
+ cd verse
+ sha256sum -c verse-SHA256SUMS.txt
+ existing="$(gh release view "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" --json assets --jq '.assets[].name')"
+ for file in Verse-*.tar verse-*-manifest.json verse-*-manifest.json.sig verse-SHA256SUMS.txt; do
+ if printf '%s\n' "${existing}" | grep -qx "${file}"; then
+ echo "::error::${file} is already on the release; refusing to replace it"
+ exit 1
+ fi
+ done
+ gh release upload "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" \
+ Verse-*.tar verse-*-manifest.json verse-*-manifest.json.sig verse-SHA256SUMS.txt
+
+ linux-smoke:
+ if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.smoke_only)
+ name: Linux smoke (nightly)
+ runs-on: [self-hosted, windows, unreal]
+ timeout-minutes: 240
+ permissions:
+ contents: read
+ steps:
+ - name: Checkout
+ uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
+ with:
+ persist-credentials: false
+ lfs: false
+
+ - name: Fetch the Unreal LFS objects
+ shell: pwsh
+ run: |
+ git config lfs.fetchexclude ""
+ git lfs pull
+
+ - name: Check the toolchain
+ run: python scripts/unreal/package.py verify --target linux
+
+ - name: Package Linux Development
+ run: python scripts/unreal/package.py build --platform linux --config Development
+
+ - name: 60 s container smoke
+ run: python scripts/unreal/package.py linux-smoke --config Development --seconds 60
+
+ - name: Upload the smoke results
+ if: always()
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ with:
+ name: verse-linux-smoke
+ path: unreal/Verse/Saved/Harness/proof/WP22/
+ if-no-files-found: warn
+ retention-days: 30
diff --git a/dodaios/core/main_follow.py b/dodaios/core/main_follow.py
index 1de10bb82c..7527009e9e 100644
--- a/dodaios/core/main_follow.py
+++ b/dodaios/core/main_follow.py
@@ -114,6 +114,9 @@ def _run(
env = dict(os.environ)
env["GIT_TERMINAL_PROMPT"] = "0"
env["GCM_INTERACTIVE"] = "never"
+ # Following main never downloads the Unreal Verse's LFS binaries (``unreal/**``,
+ # docs/verse/unreal/architecture.md 8.4); the Verse arrives as its own package.
+ env["GIT_LFS_SKIP_SMUDGE"] = "1"
if read_only:
# A read never takes the index lock (``git status`` would refresh the index
# under it), so a read that is given up on can never leave one behind.
diff --git a/dodaios/ui/web/update_routes.py b/dodaios/ui/web/update_routes.py
index 05fb05dd4a..ae92884c44 100644
--- a/dodaios/ui/web/update_routes.py
+++ b/dodaios/ui/web/update_routes.py
@@ -321,6 +321,7 @@ async def _run(
cwd: Path,
timeout_s: float,
on_stderr_line: Callable[[str], None] | None = None,
+ env: dict[str, str] | None = None,
) -> tuple[int, str, str]:
"""Run ``cmd`` in ``cwd``. Returns ``(returncode, stdout, stderr)``.
@@ -340,6 +341,7 @@ async def _run(
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
creationflags=NO_WINDOW_CREATIONFLAGS,
+ env=env,
)
except (FileNotFoundError, OSError, NotImplementedError) as exc:
# Not swallowed: the reason travels back to the caller in stderr and
@@ -384,7 +386,12 @@ async def _git(
timeout_s: float = 60.0,
on_stderr_line: Callable[[str], None] | None = None,
) -> tuple[int, str, str]:
- return await _run(["git", *args], cwd=cwd, timeout_s=timeout_s, on_stderr_line=on_stderr_line)
+ # An update never downloads the Unreal Verse's LFS binaries (``unreal/**``,
+ # docs/verse/unreal/architecture.md 8.4); the Verse arrives as its own package.
+ env = {**os.environ, "GIT_LFS_SKIP_SMUDGE": "1"}
+ return await _run(
+ ["git", *args], cwd=cwd, timeout_s=timeout_s, on_stderr_line=on_stderr_line, env=env
+ )
async def _git_output(args: list[str], *, cwd: Path, timeout_s: float = 15.0) -> str | None:
diff --git a/dodaios/verse_host/install/__init__.py b/dodaios/verse_host/install/__init__.py
new file mode 100644
index 0000000000..45d2343cb2
--- /dev/null
+++ b/dodaios/verse_host/install/__init__.py
@@ -0,0 +1,47 @@
+"""The optional, on-demand Verse install (docs/verse/unreal/work-packages.md WP22).
+
+The installer, a plain ``git clone`` and app updates never carry the Unreal
+Verse. It is its own signed package per platform on the release, downloaded
+only when the user asks for it, resumably, checked against the signed
+manifest, and unpacked into the user data folder. Settings can remove it
+again. Only an installed Verse receives (delta) updates.
+
+ installer = VerseInstaller(gpu_supported=probe.supported)
+ installer.install_state() # {"status": "not_installed", ...}
+ await installer.offer() # {"version", "download_bytes", "install_bytes"}
+ installer.start_install() # background task; installer.progress() for the bar
+ installer.cancel() # the .part stays, the next start resumes
+ installer.uninstall() # back to not_installed
+"""
+
+from __future__ import annotations
+
+from dodaios.verse_host.install.layout import (
+ VERSE_ROOT_ENV,
+ VerseInstallError,
+ default_root,
+ read_current,
+ verse_platform,
+)
+from dodaios.verse_host.install.manifest import (
+ ReleaseManifest,
+ build_release_manifest,
+ parse_release_manifest,
+ verify_release_manifest,
+)
+from dodaios.verse_host.install.service import VerseInstaller, VerseRelease, find_release
+
+__all__ = [
+ "VERSE_ROOT_ENV",
+ "ReleaseManifest",
+ "VerseInstallError",
+ "VerseInstaller",
+ "VerseRelease",
+ "build_release_manifest",
+ "default_root",
+ "find_release",
+ "parse_release_manifest",
+ "read_current",
+ "verify_release_manifest",
+ "verse_platform",
+]
diff --git a/dodaios/verse_host/install/download.py b/dodaios/verse_host/install/download.py
new file mode 100644
index 0000000000..9008419b96
--- /dev/null
+++ b/dodaios/verse_host/install/download.py
@@ -0,0 +1,240 @@
+"""Resumable, verified download of one Verse package (WP22.5).
+
+A package streams into ``<downloads>/<name>.part``. After a dropped
+connection, an app restart or a cancel, the next attempt asks for
+``Range: bytes=<size of .part>-`` and appends; a server that ignores ranges
+(``200``) starts the file over. The file is renamed to its final name only
+after its size and SHA-256 match the signed manifest, so nothing unverified
+is ever unpacked. A cancelled download keeps its ``.part`` so it resumes.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import os
+from collections.abc import Awaitable, Callable
+from pathlib import Path
+from typing import Any, Protocol
+
+from dodaios.verse_host.install.layout import VerseInstallError
+from dodaios.verse_host.install.manifest import PackageRef
+from dodaios.verse_host.install.payload import sha256_file
+
+log = logging.getLogger(__name__)
+
+__all__ = [
+ "MAX_TEXT_BYTES",
+ "HttpFetcher",
+ "Progress",
+ "RangeFetcher",
+ "download_package",
+]
+
+#: ``(bytes on disk, total bytes)`` as a download advances.
+Progress = Callable[[int, int], None]
+#: Transport failures one download survives by resuming where it stopped.
+RESUME_ATTEMPTS = 8
+RESUME_BACKOFF_S = 3.0
+#: Release listings and manifests; anything larger is not what was published.
+MAX_TEXT_BYTES = 4_000_000
+CONNECT_TIMEOUT_S = 15.0
+READ_TIMEOUT_S = 120.0
+USER_AGENT = "Dodaios-Verse-Installer"
+
+
+class RangeFetcher(Protocol):
+ """The only network the Verse installer performs. Faked in tests."""
+
+ async def get_text(self, url: str, *, max_bytes: int) -> str: ...
+
+ async def download_range(
+ self,
+ url: str,
+ dest: Path,
+ *,
+ offset: int,
+ max_bytes: int,
+ on_chunk: Callable[[int], None] | None = None,
+ ) -> int:
+ """Append ``url`` from byte ``offset`` to ``dest`` (or rewrite it); return its size."""
+ ...
+
+
+class HttpFetcher:
+ """:class:`RangeFetcher` on httpx. Every hop, redirects included, must be ``https``.
+
+ ``allow_loopback_http`` exists for tests against a local server only.
+ """
+
+ def __init__(self, *, transport: Any | None = None, allow_loopback_http: bool = False) -> None:
+ self._transport = transport
+ self._allow_loopback_http = allow_loopback_http
+
+ async def _check_hop(self, request: Any) -> None:
+ if request.url.scheme == "https":
+ return
+ if self._allow_loopback_http and request.url.host in {"127.0.0.1", "localhost"}:
+ return
+ raise VerseInstallError(
+ f"refusing a non-https download hop to {request.url.host or 'an unknown host'}"
+ )
+
+ def _client(self) -> Any:
+ import httpx # lazy: the app boots without ever loading it here
+
+ return httpx.AsyncClient(
+ timeout=httpx.Timeout(READ_TIMEOUT_S, connect=CONNECT_TIMEOUT_S),
+ follow_redirects=True,
+ transport=self._transport,
+ event_hooks={"request": [self._check_hop]},
+ headers={"User-Agent": USER_AGENT},
+ )
+
+ async def get_text(self, url: str, *, max_bytes: int) -> str:
+ body = bytearray()
+ async with self._client() as client:
+ async with client.stream("GET", url) as response:
+ response.raise_for_status()
+ async for chunk in response.aiter_bytes():
+ body.extend(chunk)
+ if len(body) > max_bytes:
+ raise VerseInstallError(f"{url} is larger than {max_bytes} bytes")
+ return body.decode("utf-8")
+
+ async def download_range(
+ self,
+ url: str,
+ dest: Path,
+ *,
+ offset: int,
+ max_bytes: int,
+ on_chunk: Callable[[int], None] | None = None,
+ ) -> int:
+ headers = {"Accept": "application/octet-stream"}
+ if offset:
+ headers["Range"] = f"bytes={offset}-"
+ async with self._client() as client:
+ async with client.stream("GET", url, headers=headers) as response:
+ if offset and response.status_code == 416:
+ return offset # already complete; the hash check decides
+ response.raise_for_status()
+ resumed = bool(offset) and response.status_code == 206
+ written = offset if resumed else 0
+ with dest.open("ab" if resumed else "wb") as handle:
+ async for chunk in response.aiter_bytes():
+ written += len(chunk)
+ if written > max_bytes:
+ raise VerseInstallError(
+ f"the download exceeded {max_bytes} bytes — refusing it"
+ )
+ handle.write(chunk)
+ if on_chunk is not None:
+ on_chunk(written)
+ return written
+
+
+def _report(on_progress: Progress | None, done: int, total: int) -> None:
+ if on_progress is None:
+ return
+ try:
+ on_progress(done, total)
+ except Exception: # noqa: BLE001 - a progress consumer never breaks a download
+ log.debug("[verse] progress callback failed", exc_info=True)
+
+
+def _discard(path: Path) -> None:
+ try:
+ path.unlink(missing_ok=True)
+ except OSError:
+ log.warning("[verse] could not remove %s", path)
+
+
+async def download_package(
+ ref: PackageRef,
+ url: str,
+ *,
+ dest_dir: Path,
+ fetcher: RangeFetcher,
+ on_progress: Progress | None = None,
+ timeout_s: float = 6 * 3600.0,
+ sleep: Callable[[float], Awaitable[Any]] = asyncio.sleep,
+) -> Path:
+ """Download ``ref`` from ``url`` into ``dest_dir``, resuming after drops. Fail closed."""
+ _make_dir(dest_dir)
+ final = dest_dir / ref.name
+ part = dest_dir / f"{ref.name}.part"
+ if final.is_file():
+ if final.stat().st_size == ref.size and await asyncio.to_thread(sha256_file, final) == (
+ ref.sha256
+ ):
+ _report(on_progress, ref.size, ref.size)
+ return final
+ _discard(final)
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + timeout_s
+ attempt = 0
+ while True:
+ offset = part.stat().st_size if part.is_file() else 0
+ if offset > ref.size:
+ _discard(part)
+ offset = 0
+ _report(on_progress, offset, ref.size)
+ remaining = deadline - loop.time()
+ if remaining <= 0:
+ raise VerseInstallError(
+ f"{ref.name} did not finish in time; the next attempt resumes where it stopped"
+ )
+ try:
+ await asyncio.wait_for(
+ fetcher.download_range(
+ url,
+ part,
+ offset=offset,
+ max_bytes=ref.size,
+ on_chunk=lambda done: _report(on_progress, done, ref.size),
+ ),
+ timeout=remaining,
+ )
+ break
+ except VerseInstallError:
+ _discard(part)
+ raise
+ except TimeoutError as exc:
+ raise VerseInstallError(
+ f"{ref.name} did not finish in time; the next attempt resumes where it stopped"
+ ) from exc
+ except asyncio.CancelledError:
+ log.info("[verse] %s paused at %d bytes", ref.name, _size(part))
+ raise
+ except Exception as exc: # noqa: BLE001 - every transport error resumes
+ attempt += 1
+ if attempt >= RESUME_ATTEMPTS:
+ raise VerseInstallError(
+ f"{ref.name}: {attempt} attempts failed ({exc}); "
+ "the next attempt resumes where this one stopped"
+ ) from exc
+ log.info("[verse] %s dropped at %d bytes (%s); resuming", ref.name, _size(part), exc)
+ await sleep(RESUME_BACKOFF_S)
+ size = _size(part)
+ actual = await asyncio.to_thread(sha256_file, part) if size == ref.size else None
+ if actual != ref.sha256:
+ _discard(part)
+ raise VerseInstallError(
+ f"{ref.name} failed its check (size {size} of {ref.size}, sha256 {actual}) — "
+ "the download was NOT installed"
+ )
+ os.replace(part, final)
+ log.info("[verse] verified %s (sha256 %s)", ref.name, actual)
+ return final
+
+
+def _make_dir(folder: Path) -> None:
+ folder.mkdir(parents=True, exist_ok=True)
+
+
+def _size(path: Path) -> int:
+ try:
+ return path.stat().st_size
+ except OSError: # no partial file yet: the download starts at byte 0
+ return 0
diff --git a/dodaios/verse_host/install/layout.py b/dodaios/verse_host/install/layout.py
new file mode 100644
index 0000000000..651686758c
--- /dev/null
+++ b/dodaios/verse_host/install/layout.py
@@ -0,0 +1,131 @@
+"""Where an installed Verse lives and which version runs (WP22.5).
+
+The Verse is an optional download (docs/verse/unreal/README.md, Delivery):
+the installer, a plain ``git clone`` and app updates never carry it. Once the
+user asks for it, it lives in the per-user data folder, outside the app:
+
+ <root>/current.json which version runs, and the one before
+ <root>/versions/<version>/ one complete, verified payload each
+ <root>/versions/<v>/verse-tree.json size + SHA-256 of every file of it
+ <root>/downloads/ resumable ``.part`` downloads
+
+``<root>`` is ``DODAIOS_VERSE_ROOT`` when set, else ``<user data>/verse``
+(``%LOCALAPPDATA%\\Dodaios\\verse`` on Windows). No ``current.json`` means
+the Verse is not installed.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import platform as platform_module
+import re
+import sys
+from pathlib import Path
+from typing import Any
+
+__all__ = [
+ "VERSE_CURRENT_FILE",
+ "VERSE_CURRENT_SCHEMA",
+ "VERSE_PLATFORMS",
+ "VERSE_ROOT_ENV",
+ "VerseInstallError",
+ "check_version",
+ "default_root",
+ "read_current",
+ "verse_platform",
+ "version_dir",
+ "version_key",
+ "write_current",
+]
+
+VERSE_CURRENT_SCHEMA = "verse.current/1"
+VERSE_CURRENT_FILE = "current.json"
+VERSE_ROOT_ENV = "DODAIOS_VERSE_ROOT"
+
+#: ``(os, cpu)`` -> the Unreal platform name of the package.
+VERSE_PLATFORMS: dict[tuple[str, str], str] = {
+ ("windows", "x64"): "Win64",
+ ("linux", "x64"): "Linux",
+}
+_VERSION = re.compile(r"^\d+\.\d+\.\d+$")
+
+
+class VerseInstallError(RuntimeError):
+ """A Verse download, install, delta, rollback or removal failed.
+
+ The message is user-facing: the launcher card shows it.
+ """
+
+
+def check_version(value: Any) -> str:
+ """``MAJOR.MINOR.PATCH`` (a leading ``v`` is dropped), else :class:`VerseInstallError`."""
+ version = str(value or "").strip().removeprefix("v")
+ if not _VERSION.match(version):
+ raise VerseInstallError(f"{value!r} is not a Verse version (want MAJOR.MINOR.PATCH)")
+ return version
+
+
+def version_key(version: str) -> tuple[int, ...]:
+ return tuple(int(part) for part in check_version(version).split("."))
+
+
+def verse_platform(platform_name: str | None = None, machine: str | None = None) -> str | None:
+ """``Win64`` / ``Linux`` for this machine, ``None`` where no Verse ships (macOS, ARM)."""
+ active = (sys.platform if platform_name is None else platform_name).lower()
+ cpu = (platform_module.machine() if machine is None else machine).strip().lower()
+ if active.startswith("win"):
+ os_name = "windows"
+ elif active.startswith("linux"):
+ os_name = "linux"
+ else:
+ os_name = ""
+ arch = "x64" if cpu in {"amd64", "x86_64", "x64"} else ""
+ return VERSE_PLATFORMS.get((os_name, arch))
+
+
+def default_root(env: dict[str, str] | None = None) -> Path:
+ """``DODAIOS_VERSE_ROOT``, else ``<user data folder>/verse``."""
+ environ = os.environ if env is None else env
+ override = environ.get(VERSE_ROOT_ENV, "").strip()
+ if override:
+ return Path(override)
+ # Imported late: the app's path rules read the environment once per process.
+ from dodaios.core.paths import user_data_dir
+
+ return user_data_dir() / "verse"
+
+
+def version_dir(root: Path, version: str) -> Path:
+ return root / "versions" / check_version(version)
+
+
+def read_current(root: Path) -> dict[str, Any] | None:
+ """``current.json`` of ``root``: the running version and the previous one."""
+ try:
+ data = json.loads((root / VERSE_CURRENT_FILE).read_text(encoding="utf-8"))
+ except (OSError, ValueError): # no or unreadable pointer means nothing installed
+ return None
+ if not isinstance(data, dict) or data.get("schema") != VERSE_CURRENT_SCHEMA:
+ return None
+ try:
+ check_version(data.get("version"))
+ except VerseInstallError: # a pointer naming no version means nothing installed
+ return None
+ return data
+
+
+def write_current(
+ root: Path, version: str, previous: str | None, platform: str, *, entry: str | None
+) -> None:
+ """Move ``current.json`` atomically (write a sibling, then replace)."""
+ data = {
+ "schema": VERSE_CURRENT_SCHEMA,
+ "version": version,
+ "previous": previous,
+ "platform": platform,
+ "entry": entry,
+ }
+ tmp = root / f".{VERSE_CURRENT_FILE}.{os.getpid()}.tmp"
+ tmp.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
+ os.replace(tmp, root / VERSE_CURRENT_FILE)
diff --git a/dodaios/verse_host/install/manifest.py b/dodaios/verse_host/install/manifest.py
new file mode 100644
index 0000000000..8b1b77ed45
--- /dev/null
+++ b/dodaios/verse_host/install/manifest.py
@@ -0,0 +1,245 @@
+"""The signed per-platform Verse release manifest (WP22.5, WP22.8).
+
+Every release that carries the Verse publishes, per platform, next to the
+installers but never inside them:
+
+ Verse-<Platform>-<version>.tar the full package
+ Verse-<Platform>-<old>-to-<new>.delta.tar changed chunks since <old>
+ verse-<Platform>-manifest.json this document
+ verse-<Platform>-manifest.json.sig Ed25519 signature over it
+
+The manifest names the version, the platform, the full package's size and
+SHA-256, the unpacked size, the digest of the package's file list and every
+delta. It is canonical JSON (sorted keys, no whitespace, ASCII), signed by
+the same release key and with the same ``openssl pkeyutl -sign -rawin`` step
+as the installers' update manifest, and checked against the keys pinned in
+:mod:`dodaios.core.update_manifest`. Nothing is downloaded before the
+signature verifies, and nothing is installed whose SHA-256 differs from the
+signed one.
+"""
+
+from __future__ import annotations
+
+import json
+from collections.abc import Sequence
+from dataclasses import dataclass, field
+from typing import Any
+
+from dodaios.verse_host.install.layout import VerseInstallError, check_version
+
+__all__ = [
+ "MAX_RELEASE_MANIFEST_BYTES",
+ "RELEASE_SCHEMA",
+ "PackageRef",
+ "ReleaseManifest",
+ "build_release_manifest",
+ "delta_asset_name",
+ "full_asset_name",
+ "manifest_asset_name",
+ "parse_release_manifest",
+ "signature_asset_name",
+ "verify_release_manifest",
+]
+
+RELEASE_SCHEMA = "verse.release/1"
+MAX_RELEASE_MANIFEST_BYTES = 64_000
+_HEX = frozenset("0123456789abcdef")
+
+
+def full_asset_name(platform: str, version: str) -> str:
+ return f"Verse-{platform}-{check_version(version)}.tar"
+
+
+def delta_asset_name(platform: str, old: str, new: str) -> str:
+ return f"Verse-{platform}-{check_version(old)}-to-{check_version(new)}.delta.tar"
+
+
+def manifest_asset_name(platform: str) -> str:
+ return f"verse-{platform}-manifest.json"
+
+
+def signature_asset_name(platform: str) -> str:
+ return f"{manifest_asset_name(platform)}.sig"
+
+
+@dataclass(frozen=True)
+class PackageRef:
+ """One downloadable package the manifest vouches for."""
+
+ name: str
+ size: int
+ sha256: str
+ from_version: str | None = None # deltas only
+ from_tree_sha256: str | None = None # deltas only
+
+ def as_dict(self) -> dict[str, Any]:
+ data: dict[str, Any] = {"name": self.name, "size": self.size, "sha256": self.sha256}
+ if self.from_version is not None:
+ data["from"] = self.from_version
+ data["from_tree_sha256"] = self.from_tree_sha256
+ return data
+
+
+@dataclass(frozen=True)
+class ReleaseManifest:
+ version: str
+ tag: str
+ platform: str
+ entry: str | None
+ install_bytes: int
+ tree_sha256: str
+ full: PackageRef
+ deltas: tuple[PackageRef, ...] = field(default=())
+
+ def delta_from(self, version: str | None) -> PackageRef | None:
+ for delta in self.deltas:
+ if version is not None and delta.from_version == version:
+ return delta
+ return None
+
+ def expected(self) -> dict[str, Any]:
+ """What an installed package must match (``payload.install_full(expected=)``)."""
+ return {"version": self.version, "platform": self.platform, "tree_sha256": self.tree_sha256}
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "version": self.version,
+ "tag": self.tag,
+ "platform": self.platform,
+ "entry": self.entry,
+ "install_bytes": self.install_bytes,
+ "download_bytes": self.full.size,
+ "full": self.full.as_dict(),
+ "deltas": [d.as_dict() for d in self.deltas],
+ }
+
+
+def _digest(value: Any, what: str) -> str:
+ text = str(value or "")
+ if len(text) != 64 or any(c not in _HEX for c in text):
+ raise VerseInstallError(f"the Verse manifest has no valid SHA-256 for {what}")
+ return text
+
+
+def _size(value: Any, what: str) -> int:
+ if not isinstance(value, int) or isinstance(value, bool) or value <= 0:
+ raise VerseInstallError(f"the Verse manifest has no valid size for {what}")
+ return value
+
+
+def build_release_manifest(
+ *,
+ version: str,
+ tag: str,
+ platform: str,
+ entry: str | None,
+ install_bytes: int,
+ tree_sha256: str,
+ full: dict[str, Any],
+ deltas: Sequence[dict[str, Any]] = (),
+) -> bytes:
+ """The exact bytes the release workflow signs (canonical JSON, ASCII)."""
+ bare = check_version(version)
+ if check_version(tag) != bare:
+ raise VerseInstallError(f"tag {tag!r} does not match version {version!r}")
+ document = {
+ "schema": RELEASE_SCHEMA,
+ "version": bare,
+ "tag": tag,
+ "platform": platform,
+ "entry": entry,
+ "install_bytes": install_bytes,
+ "tree_sha256": tree_sha256,
+ "full": full,
+ "deltas": sorted(deltas, key=lambda d: str(d.get("from"))),
+ }
+ data = json.dumps(document, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
+ parse_release_manifest(data.encode("ascii")) # never sign what the app would refuse
+ return data.encode("ascii")
+
+
+def _ref(raw: Any, what: str, *, delta: bool) -> PackageRef:
+ if not isinstance(raw, dict) or not isinstance(raw.get("name"), str) or not raw["name"]:
+ raise VerseInstallError(f"the Verse manifest has a bad {what} entry")
+ name = raw["name"]
+ if "/" in name or "\\" in name or name.startswith("."):
+ raise VerseInstallError(f"the Verse manifest names an unsafe file {name!r}")
+ return PackageRef(
+ name=name,
+ size=_size(raw.get("size"), name),
+ sha256=_digest(raw.get("sha256"), name),
+ from_version=check_version(raw.get("from")) if delta else None,
+ from_tree_sha256=_digest(raw.get("from_tree_sha256"), name) if delta else None,
+ )
+
+
+def parse_release_manifest(data: bytes) -> ReleaseManifest:
+ """Parse manifest bytes; raise :class:`VerseInstallError` on any defect."""
+ if len(data) > MAX_RELEASE_MANIFEST_BYTES:
+ raise VerseInstallError("the Verse manifest is too large to be genuine")
+ try:
+ document: Any = json.loads(data.decode("utf-8"))
+ except (UnicodeDecodeError, ValueError) as exc:
+ raise VerseInstallError(f"the Verse manifest is not valid JSON: {exc}") from exc
+ if not isinstance(document, dict) or document.get("schema") != RELEASE_SCHEMA:
+ raise VerseInstallError("the Verse manifest has an unknown schema")
+ version = check_version(document.get("version"))
+ tag = document.get("tag")
+ if not isinstance(tag, str) or check_version(tag) != version:
+ raise VerseInstallError("the Verse manifest's tag does not match its version")
+ platform = document.get("platform")
+ if not isinstance(platform, str) or not platform:
+ raise VerseInstallError("the Verse manifest names no platform")
+ entry = document.get("entry")
+ if entry is not None and (not isinstance(entry, str) or not entry):
+ raise VerseInstallError("the Verse manifest has a bad entry")
+ full = _ref(document.get("full"), "full package", delta=False)
+ if full.name != full_asset_name(platform, version):
+ raise VerseInstallError(f"the Verse manifest's full package is misnamed: {full.name}")
+ raw_deltas = document.get("deltas", [])
+ if not isinstance(raw_deltas, list):
+ raise VerseInstallError("the Verse manifest's delta list is not a list")
+ deltas = tuple(_ref(item, "delta", delta=True) for item in raw_deltas)
+ for delta in deltas:
+ assert delta.from_version is not None
+ if delta.name != delta_asset_name(platform, delta.from_version, version):
+ raise VerseInstallError(f"the Verse manifest's delta is misnamed: {delta.name}")
+ return ReleaseManifest(
+ version=version,
+ tag=tag,
+ platform=platform,
+ entry=entry,
+ install_bytes=_size(document.get("install_bytes"), "the unpacked Verse"),
+ tree_sha256=_digest(document.get("tree_sha256"), "the file list"),
+ full=full,
+ deltas=deltas,
+ )
+
+
+def verify_release_manifest(
+ data: bytes,
+ signature_text: str,
+ *,
+ platform: str,
+ tag: str | None = None,
+ public_keys: Sequence[str] | None = None,
+) -> ReleaseManifest:
+ """Signature first, then shape, platform and the release it was found on. Fail closed."""
+ from dodaios.core.update_manifest import UpdateManifestError, verify_signature
+
+ try:
+ verify_signature(data, signature_text, public_keys=public_keys)
+ except UpdateManifestError as exc:
+ raise VerseInstallError(
+ f"the Verse package is not signed by the Dodaios release key — refusing it ({exc})"
+ ) from exc
+ manifest = parse_release_manifest(data)
+ if manifest.platform != platform:
+ raise VerseInstallError(
+ f"the signed Verse manifest is for {manifest.platform}, this machine needs {platform}"
+ )
+ if tag is not None and check_version(tag) != manifest.version:
+ raise VerseInstallError(
+ f"the signed Verse manifest is for {manifest.tag}, found on {tag} — refusing a replay"
+ )
+ return manifest
diff --git a/dodaios/verse_host/install/payload.py b/dodaios/verse_host/install/payload.py
new file mode 100644
index 0000000000..edb7afdea5
--- /dev/null
+++ b/dodaios/verse_host/install/payload.py
@@ -0,0 +1,547 @@
+"""Verse packages on disk: tree, full install, delta apply, rollback, removal (WP22.4/22.5).
+
+A full package (``Verse-<Platform>-<version>.tar``) holds ``verse-tree.json``
+and ``files/<path>``. A delta (``Verse-<Platform>-<old>-to-<new>.delta.tar``)
+also holds ``verse-delta.json`` and only the changed or added files. A new
+version is assembled beside the running one in a staging folder, every file is
+checked against the target tree (100 % hash match), and only then does
+``current.json`` move. Any failure discards the staging folder, so the
+previous version stays the running one: that is the rollback.
+
+Extraction copies file data only: no links, modes, devices or paths that could
+leave the folder are ever taken from an archive.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import logging
+import os
+import shutil
+import tarfile
+import time
+from pathlib import Path
+from typing import Any
+
+from dodaios.verse_host.install.layout import (
+ VERSE_CURRENT_FILE,
+ VerseInstallError,
+ check_version,
+ read_current,
+ version_dir,
+ write_current,
+)
+
+log = logging.getLogger(__name__)
+
+__all__ = [
+ "DEFAULT_ENTRIES",
+ "VERSE_DELTA_FILE",
+ "VERSE_DELTA_SCHEMA",
+ "VERSE_TREE_FILE",
+ "VERSE_TREE_SCHEMA",
+ "apply_delta",
+ "build_tree",
+ "check_tree",
+ "ensure_healthy",
+ "entry_path",
+ "folder_bytes",
+ "install_full",
+ "read_package_tree",
+ "rollback",
+ "sha256_file",
+ "tree_digest",
+ "uninstall",
+ "verify_tree",
+]
+
+VERSE_TREE_SCHEMA = "verse.tree/1"
+VERSE_DELTA_SCHEMA = "verse.delta/1"
+VERSE_TREE_FILE = "verse-tree.json"
+VERSE_DELTA_FILE = "verse-delta.json"
+#: A tree or delta header lists a few thousand files at most.
+MAX_HEADER_BYTES = 16_000_000
+#: The launcher of a staged Unreal build, per platform. A tree may name another.
+DEFAULT_ENTRIES = {"Win64": "Verse.exe", "Linux": "Verse.sh"}
+_PAYLOAD_PREFIX = "files/"
+_SHA256_LENGTH = 64
+
+
+def sha256_file(path: Path) -> str:
+ digest = hashlib.sha256()
+ with path.open("rb") as handle:
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def folder_bytes(folder: Path) -> int:
+ if not folder.exists():
+ return 0
+ return sum(p.stat().st_size for p in folder.rglob("*") if p.is_file())
+
+
+# ------------------------------------------------------------------ the tree
+def _safe_relpath(name: Any) -> str:
+ """A package path as POSIX text; anything that could leave the folder is refused."""
+ text = str(name)
+ if not text or "\\" in text or text.startswith("/") or ":" in text or "\0" in text:
+ raise VerseInstallError(f"unsafe path in the Verse package: {name!r}")
+ if any(part in {"", ".", ".."} for part in text.split("/")):
+ raise VerseInstallError(f"unsafe path in the Verse package: {name!r}")
+ return text
+
+
+def build_tree(
+ folder: Path, *, version: str, platform: str, entry: str | None = None
+) -> dict[str, Any]:
+ """Size and SHA-256 of every file below ``folder`` (``verse-tree.json`` excluded).
+
+ ``entry`` is the file the launcher starts; by default the platform's
+ Unreal launcher when the build has one.
+ """
+ files: dict[str, dict[str, Any]] = {}
+ for path in sorted(p for p in folder.rglob("*") if p.is_file()):
+ rel = path.relative_to(folder).as_posix()
+ if rel == VERSE_TREE_FILE:
+ continue
+ files[_safe_relpath(rel)] = {"size": path.stat().st_size, "sha256": sha256_file(path)}
+ chosen = entry if entry is not None else DEFAULT_ENTRIES.get(platform)
+ if chosen is not None and chosen not in files:
+ if entry is not None:
+ raise VerseInstallError(f"the entry {entry!r} is not part of the build")
+ chosen = None
+ return {
+ "schema": VERSE_TREE_SCHEMA,
+ "version": check_version(version),
+ "platform": platform,
+ "entry": chosen,
+ "files": files,
+ }
+
+
+def tree_digest(tree: dict[str, Any]) -> str:
+ """SHA-256 of a tree's canonical JSON: what a delta names as its base."""
+ canonical = json.dumps(tree, sort_keys=True, separators=(",", ":")).encode("utf-8")
+ return hashlib.sha256(canonical).hexdigest()
+
+
+def check_tree(tree: Any) -> dict[str, Any]:
+ if not isinstance(tree, dict) or tree.get("schema") != VERSE_TREE_SCHEMA:
+ raise VerseInstallError(f"{VERSE_TREE_FILE} is not a {VERSE_TREE_SCHEMA} document")
+ check_version(tree.get("version"))
+ if not isinstance(tree.get("platform"), str) or not tree["platform"]:
+ raise VerseInstallError(f"{VERSE_TREE_FILE} names no platform")
+ files = tree.get("files")
+ if not isinstance(files, dict) or not files:
+ raise VerseInstallError(f"{VERSE_TREE_FILE} lists no files")
+ for rel, entry in files.items():
+ _safe_relpath(rel)
+ if not isinstance(entry, dict):
+ raise VerseInstallError(f"{VERSE_TREE_FILE} has a bad entry for {rel}")
+ digest = str(entry.get("sha256", ""))
+ if len(digest) != _SHA256_LENGTH or not isinstance(entry.get("size"), int):
+ raise VerseInstallError(f"{VERSE_TREE_FILE} has a bad entry for {rel}")
+ launcher = tree.get("entry")
+ if launcher is not None and launcher not in files:
+ raise VerseInstallError(f"{VERSE_TREE_FILE} names an entry that is not in the package")
+ return tree
+
+
+def _read_tree(folder: Path) -> dict[str, Any]:
+ try:
+ return check_tree(json.loads((folder / VERSE_TREE_FILE).read_text(encoding="utf-8")))
+ except (OSError, ValueError) as exc:
+ raise VerseInstallError(f"{folder / VERSE_TREE_FILE} cannot be read: {exc}") from exc
+
+
+def verify_tree(
+ folder: Path, tree: dict[str, Any] | None = None, *, hashes: bool = True
+) -> list[str]:
+ """Every way ``folder`` differs from its tree; empty means a 100 % match.
+
+ ``hashes=False`` compares sizes only, a cheap check for every launch.
+ """
+ try:
+ expected = check_tree(tree) if tree is not None else _read_tree(folder)
+ except VerseInstallError as exc: # the reason becomes the reported problem
+ return [str(exc)]
+ problems: list[str] = []
+ for rel, entry in expected["files"].items():
+ path = folder / rel
+ if not path.is_file():
+ problems.append(f"missing {rel}")
+ elif path.stat().st_size != entry["size"]:
+ problems.append(f"size mismatch {rel}")
+ elif hashes and sha256_file(path) != entry["sha256"]:
+ problems.append(f"hash mismatch {rel}")
+ listed = set(expected["files"])
+ for path in folder.rglob("*"):
+ if path.is_file():
+ rel = path.relative_to(folder).as_posix()
+ if rel != VERSE_TREE_FILE and rel not in listed:
+ problems.append(f"unexpected {rel}")
+ return problems
+
+
+def entry_path(root: Path) -> Path | None:
+ """The launcher file of the running version, or ``None`` when nothing is installed."""
+ current = read_current(root)
+ if current is None or not current.get("entry"):
+ return None
+ return version_dir(root, current["version"]) / str(current["entry"])
+
+
+# --------------------------------------------------------------- switching
+def _prune_versions(root: Path, keep: set[str]) -> None:
+ versions = root / "versions"
+ if not versions.is_dir():
+ return
+ for item in versions.iterdir():
+ if item.is_dir() and item.name not in keep:
+ shutil.rmtree(item, ignore_errors=True)
+
+
+def _staging_dir(root: Path, version: str) -> Path:
+ staging = root / "versions" / f".staging-{version}-{os.getpid()}"
+ shutil.rmtree(staging, ignore_errors=True)
+ staging.mkdir(parents=True)
+ return staging
+
+
+def _mark_executable(folder: Path, tree: dict[str, Any]) -> None:
+ """The launcher and Linux binaries need the execute bit; tar modes are never trusted."""
+ if os.name == "nt":
+ return
+ for rel in tree["files"]:
+ if rel == tree.get("entry") or rel.endswith(".sh") or "/Binaries/Linux/" in f"/{rel}":
+ path = folder / rel
+ path.chmod(path.stat().st_mode | 0o755)
+
+
+def _replace(source: Path, target: Path, *, attempts: int = 6) -> None:
+ """``os.replace`` that rides out a short Windows sharing violation.
+
+ A virus scanner or the search indexer holds a freshly written folder for a
+ moment; a rename in that moment fails with access denied and succeeds a
+ few hundred milliseconds later.
+ """
+ for attempt in range(attempts):
+ try:
+ os.replace(source, target)
+ return
+ except PermissionError:
+ if os.name != "nt" or attempt == attempts - 1:
+ raise
+ time.sleep(0.05 * (attempt + 1))
+
+
+def _switch(root: Path, staging: Path, tree: dict[str, Any]) -> dict[str, Any]:
+ """Make the verified ``staging`` folder the running version; keep one previous."""
+ version = tree["version"]
+ current = read_current(root)
+ previous = current["version"] if current else None
+ if previous == version:
+ previous = current.get("previous") if current else None
+ target = version_dir(root, version)
+ aside: Path | None = None
+ if target.exists():
+ # Reinstalling the running version (a repair): move the old folder
+ # aside first, so current.json never points at a missing folder and a
+ # failed swap puts it back.
+ aside = target.with_name(f".replaced-{version}-{os.getpid()}")
+ shutil.rmtree(aside, ignore_errors=True)
+ _replace(target, aside)
+ try:
+ _replace(staging, target)
+ except OSError:
+ if aside is not None:
+ _replace(aside, target, attempts=20)
+ raise
+ if aside is not None:
+ shutil.rmtree(aside, ignore_errors=True)
+ write_current(root, version, previous, tree["platform"], entry=tree.get("entry"))
+ _prune_versions(root, {version, *([previous] if previous else [])})
+ return {"version": version, "previous": previous}
+
+
+# ----------------------------------------------------------- tar extraction
+def _tar_members(archive: tarfile.TarFile) -> dict[str, tarfile.TarInfo]:
+ members: dict[str, tarfile.TarInfo] = {}
+ for member in archive.getmembers():
+ if member.isdir():
+ continue
+ if not member.isfile():
+ raise VerseInstallError(f"the Verse package holds a non-file entry: {member.name!r}")
+ members[_safe_relpath(member.name)] = member
+ return members
+
+
+def _tar_json(archive: tarfile.TarFile, members: dict[str, tarfile.TarInfo], name: str) -> Any:
+ member = members.get(name)
+ handle = archive.extractfile(member) if member is not None else None
+ if member is None or handle is None or member.size > MAX_HEADER_BYTES:
+ raise VerseInstallError(f"the Verse package has no usable {name}")
+ try:
+ return json.loads(handle.read().decode("utf-8"))
+ except ValueError as exc:
+ raise VerseInstallError(f"{name} in the Verse package is not JSON: {exc}") from exc
+
+
+def read_package_tree(source: Path) -> dict[str, Any]:
+ """The tree of a full package tar or of an installed version folder."""
+ if source.is_dir():
+ return _read_tree(source)
+ try:
+ with tarfile.open(source, "r:") as archive:
+ return check_tree(_tar_json(archive, _tar_members(archive), VERSE_TREE_FILE))
+ except (OSError, tarfile.TarError) as exc:
+ raise VerseInstallError(f"{source.name} is not a Verse package: {exc}") from exc
+
+
+def _extract(
+ archive: tarfile.TarFile, members: dict[str, tarfile.TarInfo], rel: str, dest: Path
+) -> None:
+ member = members.get(_PAYLOAD_PREFIX + rel)
+ source = archive.extractfile(member) if member is not None else None
+ if source is None:
+ raise VerseInstallError(f"the Verse package lacks {rel}")
+ target = dest / rel
+ target.parent.mkdir(parents=True, exist_ok=True)
+ with source, target.open("wb") as handle:
+ shutil.copyfileobj(source, handle, 1024 * 1024)
+
+
+def _link_or_copy(source: Path, target: Path) -> None:
+ """Reuse an unchanged file of the running version: a hard link, else a copy.
+
+ Nothing ever writes into a package file after it is verified, so a file
+ shared by two versions through a hard link stays correct for both.
+ """
+ target.parent.mkdir(parents=True, exist_ok=True)
+ try:
+ os.link(source, target)
+ except OSError: # no hard links here (FAT, other volume): copy instead
+ shutil.copy2(source, target)
+
+
+def _write_tree(folder: Path, tree: dict[str, Any]) -> None:
+ (folder / VERSE_TREE_FILE).write_text(
+ json.dumps(tree, indent=2, sort_keys=True) + "\n", encoding="utf-8"
+ )
+
+
+def _fail_and_discard(staging: Path, message: str, *, previous: str | None) -> VerseInstallError:
+ shutil.rmtree(staging, ignore_errors=True)
+ kept = f"; rolled back, version {previous} stays installed" if previous else ""
+ log.warning("[verse] %s%s", message, kept)
+ return VerseInstallError(f"{message}{kept}")
+
+
+def _verified_switch(
+ root: Path, staging: Path, tree: dict[str, Any], *, what: str, previous: str | None
+) -> dict[str, Any]:
+ _write_tree(staging, tree)
+ problems = verify_tree(staging, tree)
+ if problems:
+ raise _fail_and_discard(
+ staging,
+ f"{what} failed verification ({len(problems)} files: {', '.join(problems[:3])})",
+ previous=previous,
+ )
+ _mark_executable(staging, tree)
+ try:
+ return _switch(root, staging, tree)
+ except OSError as exc:
+ raise _fail_and_discard(
+ staging, f"{what} could not be switched in: {exc}", previous=previous
+ ) from exc
+
+
+def _check_expected(tree: dict[str, Any], expected: dict[str, Any] | None) -> None:
+ """The package must be the one the signed manifest describes."""
+ if not expected:
+ return
+ if expected.get("version") and tree["version"] != expected["version"]:
+ raise VerseInstallError(
+ f"the package is Verse {tree['version']}, the manifest names {expected['version']}"
+ )
+ if expected.get("platform") and tree["platform"] != expected["platform"]:
+ raise VerseInstallError("the package is for another platform than the manifest names")
+ if expected.get("tree_sha256") and tree_digest(tree) != expected["tree_sha256"]:
+ raise VerseInstallError("the package's file list is not the one the manifest signed")
+
+
+# ---------------------------------------------------------- install, delta
+def install_full(
+ root: Path, package: Path, *, expected: dict[str, Any] | None = None
+) -> dict[str, Any]:
+ """Install a full package tar as the running version. Verified before it switches."""
+ root.mkdir(parents=True, exist_ok=True)
+ current = read_current(root)
+ previous = current["version"] if current else None
+ try:
+ archive = tarfile.open(package, "r:")
+ except (OSError, tarfile.TarError) as exc:
+ raise VerseInstallError(f"{package.name} is not a Verse package: {exc}") from exc
+ with archive:
+ members = _tar_members(archive)
+ tree = check_tree(_tar_json(archive, members, VERSE_TREE_FILE))
+ _check_expected(tree, expected)
+ staging = _staging_dir(root, tree["version"])
+ try:
+ for rel in tree["files"]:
+ _extract(archive, members, rel, staging)
+ except (OSError, tarfile.TarError, VerseInstallError) as exc:
+ raise _fail_and_discard(
+ staging, f"Verse install failed: {exc}", previous=previous
+ ) from exc
+ switched = _verified_switch(
+ root, staging, tree, what=f"Verse {tree['version']}", previous=previous
+ )
+ log.info("[verse] installed %s (full, %d files)", tree["version"], len(tree["files"]))
+ return {"kind": "full", "files": len(tree["files"]), **switched}
+
+
+def _check_delta_header(
+ header: Any, tree: dict[str, Any], current: dict[str, Any], base_tree: dict[str, Any]
+) -> tuple[list[str], list[str]]:
+ previous = current["version"]
+ if not isinstance(header, dict) or header.get("schema") != VERSE_DELTA_SCHEMA:
+ raise VerseInstallError(f"{VERSE_DELTA_FILE} is not a {VERSE_DELTA_SCHEMA} document")
+ if header.get("from") != previous:
+ raise VerseInstallError(
+ f"this delta updates Verse {header.get('from')}, but {previous} is installed"
+ )
+ platform = header.get("platform")
+ if platform != current.get("platform") or platform != tree["platform"]:
+ raise VerseInstallError("this delta is for another platform")
+ if header.get("to") != tree["version"]:
+ raise VerseInstallError(f"{VERSE_DELTA_FILE} and {VERSE_TREE_FILE} name other versions")
+ if header.get("from_tree_sha256") != tree_digest(base_tree):
+ raise VerseInstallError(
+ f"the installed Verse {previous} is not the build this delta was made from"
+ )
+ changed = [_safe_relpath(p) for p in header.get("files", [])]
+ reused = [_safe_relpath(p) for p in header.get("reuse", [])]
+ if set(changed) | set(reused) != set(tree["files"]) or set(changed) & set(reused):
+ raise VerseInstallError(f"{VERSE_DELTA_FILE} does not cover the target tree exactly")
+ missing = [rel for rel in reused if rel not in base_tree["files"]]
+ if missing:
+ raise VerseInstallError(f"{missing[0]} is not part of the installed Verse {previous}")
+ return changed, reused
+
+
+def apply_delta(
+ root: Path, delta: Path, *, expected: dict[str, Any] | None = None
+) -> dict[str, Any]:
+ """Apply a delta tar on top of the running version. Fail closed, roll back.
+
+ The new version is assembled from the delta's files plus hard links to the
+ running version's unchanged files, then checked against the target tree.
+ A corrupted chunk, a wrong base version or a missing file leaves the
+ running version untouched and raises :class:`VerseInstallError`.
+ """
+ current = read_current(root)
+ if current is None:
+ raise VerseInstallError("no Verse is installed; a delta needs the version it was made from")
+ previous = current["version"]
+ base_dir = version_dir(root, previous)
+ try:
+ archive = tarfile.open(delta, "r:")
+ except (OSError, tarfile.TarError) as exc:
+ raise VerseInstallError(f"{delta.name} is not a Verse delta: {exc}") from exc
+ with archive:
+ members = _tar_members(archive)
+ header = _tar_json(archive, members, VERSE_DELTA_FILE)
+ tree = check_tree(_tar_json(archive, members, VERSE_TREE_FILE))
+ _check_expected(tree, expected)
+ changed, reused = _check_delta_header(header, tree, current, _read_tree(base_dir))
+ staging = _staging_dir(root, tree["version"])
+ try:
+ for rel in changed:
+ _extract(archive, members, rel, staging)
+ for rel in reused:
+ _link_or_copy(base_dir / rel, staging / rel)
+ except (OSError, tarfile.TarError, VerseInstallError) as exc:
+ raise _fail_and_discard(
+ staging, f"Verse delta to {tree['version']} failed: {exc}", previous=previous
+ ) from exc
+ switched = _verified_switch(
+ root, staging, tree, what=f"Verse delta to {tree['version']}", previous=previous
+ )
+ log.info(
+ "[verse] applied delta %s -> %s (%d changed, %d reused, 100%% hash match)",
+ previous,
+ tree["version"],
+ len(changed),
+ len(reused),
+ )
+ return {"kind": "delta", "changed": len(changed), "reused": len(reused), **switched}
+
+
+def rollback(root: Path) -> dict[str, Any]:
+ """Make the previous version the running one again, after verifying it."""
+ current = read_current(root)
+ if current is None or not current.get("previous"):
+ raise VerseInstallError("there is no previous Verse version to roll back to")
+ previous = current["previous"]
+ folder = version_dir(root, previous)
+ problems = verify_tree(folder)
+ if problems:
+ raise VerseInstallError(
+ f"the previous Verse {previous} is damaged too ({', '.join(problems[:3])})"
+ )
+ tree = _read_tree(folder)
+ write_current(root, previous, None, str(current.get("platform", "")), entry=tree.get("entry"))
+ log.warning("[verse] rolled back from %s to %s", current["version"], previous)
+ return {"version": previous, "rolled_back_from": current["version"]}
+
+
+def ensure_healthy(root: Path, *, hashes: bool = False) -> dict[str, Any]:
+ """Check the running version; roll back to the previous one when it is damaged."""
+ current = read_current(root)
+ if current is None:
+ return {"status": "not_installed"}
+ problems = verify_tree(version_dir(root, current["version"]), hashes=hashes)
+ if not problems:
+ return {"status": "ok", "version": current["version"]}
+ try:
+ rolled = rollback(root)
+ except VerseInstallError as exc: # reported to the caller as status broken
+ return {
+ "status": "broken",
+ "version": current["version"],
+ "problems": problems[:10],
+ "detail": str(exc),
+ }
+ return {"status": "rolled_back", "problems": problems[:10], **rolled}
+
+
+def uninstall(root: Path) -> dict[str, Any]:
+ """Remove every installed version and download; the Verse is ``not_installed`` again.
+
+ The pointer goes first, so a removal stopped half-way (a file a running
+ game still holds on Windows) already reads as not installed, and the next
+ removal or install clears what is left.
+ """
+ before = folder_bytes(root)
+ (root / VERSE_CURRENT_FILE).unlink(missing_ok=True)
+ leftovers: list[str] = []
+ for name in ("versions", "downloads"):
+ folder = root / name
+ if folder.exists():
+ shutil.rmtree(folder, ignore_errors=True)
+ if folder.exists():
+ leftovers.append(str(folder))
+ freed = before - folder_bytes(root)
+ if leftovers:
+ log.warning("[verse] removal left %s behind (files in use?)", ", ".join(leftovers))
+ else:
+ try:
+ root.rmdir() # only when nothing else (crash reports, settings) lives there
+ except OSError:
+ log.debug("[verse] %s keeps other files; left in place", root)
+ log.info("[verse] removed the Verse (%d bytes freed)", freed)
+ return {"status": "not_installed", "freed_bytes": freed, "leftovers": leftovers}
diff --git a/dodaios/verse_host/install/service.py b/dodaios/verse_host/install/service.py
new file mode 100644
index 0000000000..f8bfdc0ec0
--- /dev/null
+++ b/dodaios/verse_host/install/service.py
@@ -0,0 +1,480 @@
+"""The on-demand Verse installer the launcher card drives (WP22.5, WP22.6, A22.7).
+
+The installer and app updates never carry the Verse. The first time someone
+opens it, the card (WP17.13) shows the size from :meth:`VerseInstaller.offer`
+and a "Download the Verse" button that calls :meth:`VerseInstaller.start_install`;
+``GET /api/verse/install/progress`` reads :meth:`VerseInstaller.progress`,
+``DELETE /api/verse/install`` cancels a running download (it resumes on the
+next start) or, when none runs, :meth:`VerseInstaller.uninstall` removes the
+Verse again. Only an installed Verse is offered updates
+(:meth:`VerseInstaller.update`, a delta when one fits).
+
+:meth:`VerseInstaller.install_state` answers ``unsupported`` (no package for
+this OS, or the capability probe says no GPU: nothing is ever downloaded),
+``not_installed``, ``installing``, ``installed`` or ``broken``. WP17's
+``GET /api/verse/status`` reports ``installed`` as ``stopped`` / ``running``.
+
+Where packages come from: the newest published release of the official repo,
+no newer than the running app, that carries a signed
+``verse-<Platform>-manifest.json`` (:mod:`.manifest`).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import shutil
+import time
+from collections.abc import Callable, Sequence
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+from dodaios.verse_host.install import payload
+from dodaios.verse_host.install.download import (
+ MAX_TEXT_BYTES,
+ HttpFetcher,
+ RangeFetcher,
+ download_package,
+)
+from dodaios.verse_host.install.layout import (
+ VerseInstallError,
+ check_version,
+ default_root,
+ read_current,
+ verse_platform,
+ version_key,
+)
+from dodaios.verse_host.install.manifest import (
+ PackageRef,
+ ReleaseManifest,
+ manifest_asset_name,
+ signature_asset_name,
+ verify_release_manifest,
+)
+
+log = logging.getLogger(__name__)
+
+__all__ = ["InstallProgress", "VerseInstaller", "VerseRelease", "find_release", "releases_url"]
+
+#: Releases looked at, newest first; a Verse ships with most releases, not all.
+RELEASE_LOOKBACK = 30
+#: Free space kept beyond the download and the unpacked folder.
+DISK_MARGIN_BYTES = 1_000_000_000
+_MAX_SIGNATURE_BYTES = 1_000
+#: "Not given": the app's own version / this machine's platform.
+_UNSET: Any = object()
+
+
+def _remove(path: Path) -> None:
+ path.unlink(missing_ok=True)
+
+
+def releases_url(slug: str | None = None) -> str:
+ if slug is None:
+ from dodaios.core.branding import OFFICIAL_REPO_SLUG
+
+ slug = OFFICIAL_REPO_SLUG
+ return f"https://api.github.com/repos/{slug}/releases?per_page={RELEASE_LOOKBACK}"
+
+
+def _app_version() -> str | None:
+ try:
+ from dodaios import __version__
+
+ return check_version(__version__)
+ except (ImportError, VerseInstallError): # a dev build: no ceiling on the Verse version
+ return None
+
+
+def _optional_str(value: object) -> str | None:
+ return None if value is None else str(value)
+
+
+@dataclass(frozen=True)
+class VerseRelease:
+ """A verified manifest and where its packages download from."""
+
+ manifest: ReleaseManifest
+ urls: dict[str, str]
+
+ def url(self, ref: PackageRef) -> str:
+ try:
+ return self.urls[ref.name]
+ except KeyError as exc:
+ raise VerseInstallError(f"the release does not carry {ref.name}") from exc
+
+
+def _asset_urls(release: dict[str, Any]) -> dict[str, tuple[str, int | None]]:
+ urls: dict[str, tuple[str, int | None]] = {}
+ for asset in release.get("assets") or []:
+ if not isinstance(asset, dict):
+ continue
+ name, url = asset.get("name"), asset.get("browser_download_url")
+ if isinstance(name, str) and isinstance(url, str):
+ size = asset.get("size")
+ urls[name] = (url, size if isinstance(size, int) else None)
+ return urls
+
+
+async def find_release(
+ fetcher: RangeFetcher,
+ *,
+ platform: str,
+ listing_url: str,
+ app_version: str | None,
+ public_keys: Sequence[str] | None = None,
+) -> VerseRelease:
+ """The newest release, not newer than the app, with a verified Verse for ``platform``."""
+ try:
+ listed = json.loads(await fetcher.get_text(listing_url, max_bytes=MAX_TEXT_BYTES))
+ except VerseInstallError:
+ raise
+ except Exception as exc: # noqa: BLE001 - every network failure reads the same
+ raise VerseInstallError(f"the release list could not be read ({exc})") from exc
+ if not isinstance(listed, list):
+ raise VerseInstallError("the release list is not a list")
+ ceiling = version_key(app_version) if app_version else None
+ for release in listed:
+ if not isinstance(release, dict) or release.get("draft") or release.get("prerelease"):
+ continue
+ tag = str(release.get("tag_name") or "")
+ try:
+ key = version_key(tag)
+ except VerseInstallError: # not a release tag (a draft name): never a Verse source
+ continue
+ if ceiling is not None and key > ceiling:
+ continue # a Verse newer than the app may speak a newer bridge protocol
+ assets = _asset_urls(release)
+ manifest_asset = assets.get(manifest_asset_name(platform))
+ signature_asset = assets.get(signature_asset_name(platform))
+ if manifest_asset is None or signature_asset is None:
+ continue
+ try:
+ text = await fetcher.get_text(manifest_asset[0], max_bytes=MAX_TEXT_BYTES)
+ signature = await fetcher.get_text(signature_asset[0], max_bytes=_MAX_SIGNATURE_BYTES)
+ except VerseInstallError:
+ raise
+ except Exception as exc: # noqa: BLE001
+ raise VerseInstallError(
+ f"the Verse manifest of {tag} could not be read ({exc})"
+ ) from exc
+ manifest = verify_release_manifest(
+ text.encode("utf-8"), signature, platform=platform, tag=tag, public_keys=public_keys
+ )
+ urls: dict[str, str] = {}
+ for ref in (manifest.full, *manifest.deltas):
+ found = assets.get(ref.name)
+ if found is None:
+ continue
+ if found[1] is not None and found[1] != ref.size:
+ raise VerseInstallError(
+ f"{ref.name} on {tag} is {found[1]} bytes, the signed manifest says {ref.size}"
+ )
+ urls[ref.name] = found[0]
+ if manifest.full.name not in urls:
+ continue
+ return VerseRelease(manifest=manifest, urls=urls)
+ raise VerseInstallError(f"no published release carries the Verse for {platform} yet")
+
+
+@dataclass
+class InstallProgress:
+ phase: str = "idle" # idle|checking|downloading|installing|done|failed|cancelled
+ version: str | None = None
+ kind: str | None = None # full|delta
+ done_bytes: int = 0
+ total_bytes: int = 0
+ error: str | None = None
+ started_at: float | None = None
+ history: list[str] = field(default_factory=list)
+
+ def as_dict(self) -> dict[str, Any]:
+ percent = round(100.0 * self.done_bytes / self.total_bytes, 1) if self.total_bytes else None
+ return {
+ "phase": self.phase,
+ "version": self.version,
+ "kind": self.kind,
+ "done_bytes": self.done_bytes,
+ "total_bytes": self.total_bytes,
+ "percent": percent,
+ "error": self.error,
+ }
+
+
+class VerseInstaller:
+ """Download, install, update and remove the Verse for one user data folder."""
+
+ def __init__(
+ self,
+ *,
+ root: Path | None = None,
+ fetcher: RangeFetcher | None = None,
+ listing_url: str | None = None,
+ app_version: str | None | object = _UNSET,
+ gpu_supported: Callable[[], bool] | bool = True,
+ platform: str | None | object = _UNSET,
+ public_keys: Sequence[str] | None = None,
+ disk_usage: Callable[[Path], Any] = shutil.disk_usage,
+ ) -> None:
+ self.root = default_root() if root is None else root
+ self._fetcher: RangeFetcher = HttpFetcher() if fetcher is None else fetcher
+ self._listing_url = listing_url or releases_url()
+ self._app_version: str | None = (
+ _app_version() if app_version is _UNSET else _optional_str(app_version)
+ )
+ self._gpu_supported = gpu_supported
+ self.platform: str | None = (
+ verse_platform() if platform is _UNSET else _optional_str(platform)
+ )
+ self._public_keys = public_keys
+ self._disk_usage = disk_usage
+ self._progress = InstallProgress()
+ self._task: asyncio.Task[dict[str, Any]] | None = None
+
+ # ------------------------------------------------------------ status
+ def supported(self) -> bool:
+ if self.platform is None:
+ return False
+ probe = self._gpu_supported
+ try:
+ return bool(probe() if callable(probe) else probe)
+ except Exception: # noqa: BLE001 - a failing probe means "cannot run it"
+ log.warning("[verse] the capability probe failed", exc_info=True)
+ return False
+
+ def busy(self) -> bool:
+ return self._task is not None and not self._task.done()
+
+ def install_state(self) -> dict[str, Any]:
+ """``unsupported`` / ``not_installed`` / ``installing`` / ``installed`` / ``broken``."""
+ current = read_current(self.root)
+ base: dict[str, Any] = {"version": current["version"] if current else None}
+ if self.busy():
+ return {"status": "installing", **base, "progress": self.progress()}
+ if not self.supported():
+ return {"status": "unsupported", **base}
+ if current is None:
+ return {"status": "not_installed", "version": None}
+ health = payload.ensure_healthy(self.root)
+ if health["status"] == "broken":
+ return {"status": "broken", **base, "problems": health.get("problems", [])}
+ entry = payload.entry_path(self.root)
+ return {
+ "status": "installed",
+ "version": health.get("version", base["version"]),
+ "entry": str(entry) if entry else None,
+ "install_bytes": payload.folder_bytes(self.root / "versions"),
+ }
+
+ def launch_command(self) -> list[str]:
+ """The command WP17's supervisor starts; raises when nothing is installed."""
+ entry = payload.entry_path(self.root)
+ if entry is None or not entry.is_file():
+ raise VerseInstallError("the Verse is not installed")
+ return [str(entry)]
+
+ def progress(self) -> dict[str, Any]:
+ return self._progress.as_dict()
+
+ # ------------------------------------------------------------- offer
+ async def release(self) -> VerseRelease:
+ if not self.supported() or self.platform is None:
+ raise VerseInstallError("this machine cannot run the Verse")
+ return await find_release(
+ self._fetcher,
+ platform=self.platform,
+ listing_url=self._listing_url,
+ app_version=self._app_version,
+ public_keys=self._public_keys,
+ )
+
+ async def offer(self) -> dict[str, Any]:
+ """What the card shows before the download: version and sizes."""
+ manifest = (await self.release()).manifest
+ return {
+ "version": manifest.version,
+ "download_bytes": manifest.full.size,
+ "install_bytes": manifest.install_bytes,
+ }
+
+ # ----------------------------------------------------------- install
+ def start_install(self) -> dict[str, Any]:
+ """Start (or join) the download in the background; returns the progress."""
+ if not self.busy():
+ self._task = asyncio.get_running_loop().create_task(self._run(self.install))
+ return self.progress()
+
+ def start_update(self) -> dict[str, Any]:
+ if not self.busy():
+ self._task = asyncio.get_running_loop().create_task(self._run(self.update))
+ return self.progress()
+
+ async def wait(self) -> dict[str, Any] | None:
+ task = self._task
+ if task is None:
+ return None
+ try:
+ return await task
+ except (asyncio.CancelledError, VerseInstallError): # the reason is in progress()
+ return None
+
+ def cancel(self) -> dict[str, Any]:
+ """Stop a running download; its ``.part`` stays, so the next start resumes.
+
+ Only the download can be stopped. Once the verified package is being
+ unpacked (phase ``installing``) the worker thread cannot be interrupted
+ safely, so the cancel is refused and the install finishes.
+ """
+ if self.busy() and self._task is not None:
+ if self._progress.phase == "installing":
+ log.info("[verse] cancel refused: the verified package is being unpacked")
+ else:
+ self._task.cancel()
+ return self.progress()
+
+ async def _run(self, job: Callable[[], Any]) -> dict[str, Any]:
+ self._progress = InstallProgress(phase="checking", started_at=time.time())
+ try:
+ result: dict[str, Any] = await job()
+ except asyncio.CancelledError:
+ self._progress.phase = "cancelled"
+ raise
+ except VerseInstallError as exc:
+ self._progress.phase = "failed"
+ self._progress.error = str(exc)
+ raise
+ except Exception as exc: # noqa: BLE001 - reported on the card, never swallowed
+ log.exception("[verse] install failed")
+ self._progress.phase = "failed"
+ self._progress.error = f"the Verse install failed: {exc}"
+ raise VerseInstallError(self._progress.error) from exc
+ self._progress.phase = "done"
+ return result
+
+ def _on_bytes(self, done: int, total: int) -> None:
+ self._progress.phase = "downloading"
+ self._progress.done_bytes = done
+ self._progress.total_bytes = total
+
+ def _prune_downloads(self, ref: PackageRef) -> None:
+ """Drop packages and ``.part`` files of every other (superseded) release."""
+ downloads = self.root / "downloads"
+ if not downloads.is_dir():
+ return
+ keep = {ref.name, f"{ref.name}.part"}
+ for entry in downloads.iterdir():
+ if entry.name in keep or not entry.is_file():
+ continue
+ try:
+ entry.unlink()
+ log.info("[verse] removed stale download %s", entry.name)
+ except OSError:
+ log.warning("[verse] could not remove stale download %s", entry)
+
+ def _check_disk(self, ref: PackageRef, install_bytes: int) -> None:
+ self.root.mkdir(parents=True, exist_ok=True)
+ self._prune_downloads(ref)
+ part = self.root / "downloads" / f"{ref.name}.part"
+ have = part.stat().st_size if part.is_file() else 0
+ need = (ref.size - have) + install_bytes + DISK_MARGIN_BYTES
+ free = int(self._disk_usage(self.root).free)
+ if free < need:
+ raise VerseInstallError(
+ f"the Verse needs {need / 1e9:.1f} GB free in {self.root}, "
+ f"only {free / 1e9:.1f} GB are free"
+ )
+
+ async def _fetch(self, release: VerseRelease, ref: PackageRef, kind: str) -> Path:
+ self._progress.kind = kind
+ self._progress.version = release.manifest.version
+ self._progress.total_bytes = ref.size
+ await asyncio.to_thread(self._check_disk, ref, release.manifest.install_bytes)
+ return await download_package(
+ ref,
+ release.url(ref),
+ dest_dir=self.root / "downloads",
+ fetcher=self._fetcher,
+ on_progress=self._on_bytes,
+ )
+
+ async def _apply(
+ self, step: Callable[..., dict[str, Any]], path: Path, manifest: ReleaseManifest
+ ) -> dict[str, Any]:
+ """Run an unpack step in a worker thread and always wait for that thread.
+
+ Cancelling the awaiting task does not stop a thread, so the task keeps
+ waiting until the worker returns: ``busy()`` stays True, uninstall and a
+ second install stay refused, and the package is removed only after the
+ worker has closed it. A cancel that arrived meanwhile is re-raised then.
+ """
+ self._progress.phase = "installing"
+ worker = asyncio.ensure_future(
+ asyncio.to_thread(step, self.root, path, expected=manifest.expected())
+ )
+ cancelled = False
+ try:
+ while True:
+ try:
+ result = await asyncio.shield(worker)
+ break
+ except asyncio.CancelledError:
+ if worker.done():
+ raise
+ cancelled = True
+ log.info("[verse] unpack still running; waiting for it before stopping")
+ finally:
+ if worker.done():
+ _remove(path)
+ if cancelled:
+ raise asyncio.CancelledError
+ return result
+
+ async def install(self) -> dict[str, Any]:
+ """Download the full package, verify it, unpack it into the user data folder."""
+ release = await self.release()
+ manifest = release.manifest
+ path = await self._fetch(release, manifest.full, "full")
+ result = await self._apply(payload.install_full, path, manifest)
+ return {"status": "installed", **result}
+
+ async def update(self) -> dict[str, Any]:
+ """Bring an installed Verse to the newest release; a delta when one fits.
+
+ A damaged install rolls back first; one with nothing healthy left gets
+ the full package again. A delta that fails leaves the running version
+ in place and falls back to the full package.
+ """
+ health = await asyncio.to_thread(payload.ensure_healthy, self.root)
+ if health["status"] == "not_installed":
+ raise VerseInstallError("the Verse is not installed; only an installed Verse updates")
+ broken = health["status"] == "broken"
+ current = read_current(self.root)
+ installed = current["version"] if current else None
+ release = await self.release()
+ manifest = release.manifest
+ if not broken and installed and version_key(installed) >= version_key(manifest.version):
+ return {"status": "current", "version": installed}
+ delta = None if broken else manifest.delta_from(installed)
+ if delta is not None and delta.name in release.urls:
+ base = payload.read_package_tree(payload.version_dir(self.root, str(installed)))
+ if payload.tree_digest(base) == delta.from_tree_sha256:
+ try:
+ path = await self._fetch(release, delta, "delta")
+ result = await self._apply(payload.apply_delta, path, manifest)
+ return {"status": "updated", **result}
+ except VerseInstallError as exc:
+ log.warning("[verse] delta update failed (%s); using the full package", exc)
+ path = await self._fetch(release, manifest.full, "full")
+ result = await self._apply(payload.install_full, path, manifest)
+ return {"status": "repaired" if broken else "updated", **result}
+
+ # ---------------------------------------------------------- uninstall
+ def uninstall(self) -> dict[str, Any]:
+ """Remove the Verse; refused while a download or install runs."""
+ if self.busy():
+ raise VerseInstallError("a Verse download is running; cancel it first")
+ result = payload.uninstall(self.root)
+ self._progress = InstallProgress()
+ return result
diff --git a/install/install.ps1 b/install/install.ps1
index 2b98762d16..e449b1ac65 100644
--- a/install/install.ps1
+++ b/install/install.ps1
@@ -755,6 +755,9 @@ $GitVerbosity = if ([Console]::IsErrorRedirected) { '--quiet' } else { '--progre
# 2. a mid-transfer disconnect aborts the install -> retry a clean clone
# up to 3 times before giving up with an honest message.
$GitNetOpts = @('-c', 'http.lowSpeedLimit=1024', '-c', 'http.lowSpeedTime=30')
+# An install never downloads the Unreal Verse's LFS binaries (unreal/**); the
+# Verse arrives as its own package (docs/verse/unreal/architecture.md 8.4).
+$env:GIT_LFS_SKIP_SMUDGE = '1'
# --- install-ref begin (extracted by tests/unit/install/test_install_ref.py)
# Without JARVIS_INSTALL_REF an install follows the newest published release,
@@ -1243,6 +1246,11 @@ if (-not (Test-Path $InstallerPy)) {
Write-Note 'handing over to the Python installer (phases 4-6)'
+# The LFS skip is for this script's own git calls only. Drop it before the
+# hand-off so the app installer.py launches (and every git it runs in the
+# user's own repos) never inherits it.
+Remove-Item Env:GIT_LFS_SKIP_SMUDGE -ErrorAction SilentlyContinue
+
Push-Location $InstallDir
try {
& $VenvPython $InstallerPy @ExtraArgs
diff --git a/install/install.sh b/install/install.sh
index cadfd2cf92..c7b29f816a 100755
--- a/install/install.sh
+++ b/install/install.sh
@@ -958,6 +958,10 @@ GIT_VERBOSITY='--quiet'
# 2. a mid-transfer disconnect aborts the install -> retry a clean clone
# up to 3 times before giving up with an honest message.
GIT_NET_OPTS='-c http.lowSpeedLimit=1024 -c http.lowSpeedTime=30'
+# An install never downloads the Unreal Verse's LFS binaries (unreal/**); the
+# Verse arrives as its own package (docs/verse/unreal/architecture.md 8.4).
+GIT_LFS_SKIP_SMUDGE=1
+export GIT_LFS_SKIP_SMUDGE
# Restyle git's raw transfer chatter into the installer's visual grammar
# (maintainer request 2026-07-18: phases 1-2 look polished, then raw
@@ -1496,6 +1500,11 @@ fi
note 'handing over to the Python installer (phases 4-6)'
+# The LFS skip is for this script's own git calls only. Drop it before the
+# hand-off so the app installer.py launches (and every git it runs in the
+# user's own repos) never inherits it.
+unset GIT_LFS_SKIP_SMUDGE
+
cd "$INSTALL_DIR"
exec "$VENV_PYTHON" "$INSTALLER_PY" "$@"
diff --git a/install/installer.py b/install/installer.py
index 0965caa04e..a003322f2a 100644
--- a/install/installer.py
+++ b/install/installer.py
@@ -1129,7 +1129,7 @@ def step_launch(*, headless: bool, dry_run: bool) -> None:
# We deliberately do not wait for the App — the installer returns control
# to the user's shell as soon as the App is spawned.
try:
- subprocess.Popen(cmd, cwd=repo_root(), close_fds=True)
+ subprocess.Popen(cmd, cwd=repo_root(), close_fds=True, env=app_launch_env())
except OSError as exc:
console.print(f"[bad]│ Could not launch: {exc}[/]")
console.print(f"[muted] Open it by hand:[/] [brand]{hint}[/]")
@@ -1142,6 +1142,19 @@ def step_launch(*, headless: bool, dry_run: bool) -> None:
console.print(f"[muted] If it doesn't open, run:[/] [brand]{hint}[/]")
+def app_launch_env(base: dict[str, str] | None = None) -> dict[str, str]:
+ """Environment for the launched app: the installer's own, minus its git-only knobs.
+
+ The shell stage sets ``GIT_LFS_SKIP_SMUDGE`` for its clone so an install
+ never pulls the Verse's LFS binaries. The app (coding-agent panes, git in
+ the user's own repos) must not inherit it, or LFS files there would come
+ out as pointer files.
+ """
+ env = dict(os.environ if base is None else base)
+ env.pop("GIT_LFS_SKIP_SMUDGE", None)
+ return env
+
+
def step_cli_links(*, dry_run: bool) -> None:
"""Make `dodaios` and its earlier names plain terminal commands on every OS.
diff --git a/packaging/linux/verse/README.md b/packaging/linux/verse/README.md
new file mode 100644
index 0000000000..76ca0a0687
--- /dev/null
+++ b/packaging/linux/verse/README.md
@@ -0,0 +1,21 @@
+# Verse on Linux: optional download and nightly smoke
+
+The AppImage, the Debian package, `install.sh` and every app update carry no
+Verse (docs/verse/unreal/README.md, Delivery; work-packages.md WP22.5,
+WP22.6). The release carries `Verse-Linux-<version>.tar`, deltas and the
+signed `verse-Linux-manifest.json` (`scripts/unreal/package.py full`, `delta`,
+`manifest`). When the user presses "Download the Verse" on the launcher card,
+the app (`dodaios/verse_host/install`) downloads it resumably, verifies it and
+unpacks it into the user data folder (`<user data>/verse`); a read-only
+AppImage stays untouched. Machines without a Vulkan 1.3 GPU are never offered
+the download.
+
+Nightly smoke (WP22.7, `scripts/unreal/package.py linux-smoke`):
+
+| File | Role |
+|---|---|
+| `smoke.Dockerfile` | Ubuntu 24.04 with the Vulkan loader, Xvfb, a window manager and a headless Wayland compositor; runs as a normal user |
+| `linux_smoke.sh` | Inside the container: the `-nullrhi` server run through the smoke stages, a Vulkan first frame when a device exists, then the activation check; writes `result.json` |
+| `activation_check.py` | X11 `_NET_ACTIVE_WINDOW` and Wayland `xdg_activation_v1` availability (architecture.md RK7) |
+
+The container has no network; the packaged build is mounted read-only.
diff --git a/packaging/linux/verse/activation_check.py b/packaging/linux/verse/activation_check.py
new file mode 100644
index 0000000000..e8c0db256f
--- /dev/null
+++ b/packaging/linux/verse/activation_check.py
@@ -0,0 +1,90 @@
+#!/usr/bin/env python3
+"""Can a Linux session bring the Verse window to the front? (architecture.md 1.3, RK7)
+
+The backend hands focus to ``Verse`` and back. On X11 that needs a window
+manager that supports ``_NET_ACTIVE_WINDOW``; on Wayland it needs the
+compositor's ``xdg_activation_v1`` global, whose token travels over the
+bridge. This check asks the running display servers and prints JSON:
+
+ python3 activation_check.py --x11 :98 --wayland wl-verse-smoke
+ {"x11": "ok", "wayland": "ok", "detail": {...}}
+
+Each entry is ``ok``, ``fail`` (the server answered without the feature) or
+``skip`` (no such server was given or it did not answer). Exit code 1 when
+any entry is ``fail``. Standard library only: it runs in the smoke container.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import subprocess
+import sys
+from collections.abc import Callable, Sequence
+
+Runner = Callable[[Sequence[str], dict], "tuple[int, str]"]
+
+
+def _run(command: Sequence[str], env: dict) -> tuple[int, str]:
+ try:
+ done = subprocess.run(list(command), env=env, capture_output=True, text=True,
+ timeout=20, check=False)
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ return 127, str(exc)
+ return done.returncode, done.stdout
+
+
+def x11_supports_activation(xprop_output: str) -> bool:
+ """``xprop -root _NET_SUPPORTED`` lists ``_NET_ACTIVE_WINDOW``."""
+ for line in xprop_output.splitlines():
+ if line.startswith("_NET_SUPPORTED"):
+ atoms = {atom.strip() for atom in line.split("=", 1)[-1].split(",")}
+ return "_NET_ACTIVE_WINDOW" in atoms
+ return False
+
+
+def wayland_supports_activation(info_output: str) -> bool:
+ """``wayland-info`` lists the ``xdg_activation_v1`` global."""
+ return any("xdg_activation_v1" in line for line in info_output.splitlines())
+
+
+def check_x11(display: str | None, run: Runner = _run) -> tuple[str, str]:
+ if not display:
+ return "skip", "no X11 display given"
+ env = dict(os.environ, DISPLAY=display)
+ code, output = run(["xprop", "-root", "_NET_SUPPORTED"], env)
+ if code != 0:
+ return "skip", f"xprop on {display} exited {code}"
+ if x11_supports_activation(output):
+ return "ok", "_NET_ACTIVE_WINDOW supported"
+ return "fail", "the window manager does not list _NET_ACTIVE_WINDOW"
+
+
+def check_wayland(socket: str | None, run: Runner = _run) -> tuple[str, str]:
+ if not socket:
+ return "skip", "no Wayland socket given"
+ env = dict(os.environ, WAYLAND_DISPLAY=socket)
+ code, output = run(["wayland-info"], env)
+ if code != 0:
+ return "skip", f"wayland-info on {socket} exited {code}"
+ if wayland_supports_activation(output):
+ return "ok", "xdg_activation_v1 available"
+ return "fail", "the compositor has no xdg_activation_v1 global"
+
+
+def main(argv: Sequence[str] | None = None, run: Runner = _run) -> int:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument("--x11", help="X11 display, for example :98")
+ parser.add_argument("--wayland", help="Wayland socket name")
+ options = parser.parse_args(argv)
+ x11, x11_detail = check_x11(options.x11, run)
+ wayland, wayland_detail = check_wayland(options.wayland, run)
+ result = {"x11": x11, "wayland": wayland,
+ "detail": {"x11": x11_detail, "wayland": wayland_detail}}
+ print(json.dumps(result, indent=2))
+ return 1 if "fail" in (x11, wayland) else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/packaging/linux/verse/linux_smoke.sh b/packaging/linux/verse/linux_smoke.sh
new file mode 100644
index 0000000000..375be57170
--- /dev/null
+++ b/packaging/linux/verse/linux_smoke.sh
@@ -0,0 +1,136 @@
+#!/usr/bin/env bash
+# Nightly Linux smoke of the packaged Unreal Verse, run inside smoke.Dockerfile.
+#
+# bash /smoke/linux_smoke.sh <seconds> <gpu|nogpu>
+#
+# 1. Server run: Verse.sh under -nullrhi (the game is its own listen server;
+# there is no Server target, decision C7) through the smoke stages
+# boot, hangar and a bot-vs-bot arena, for at most <seconds> plus start-up.
+# 2. Vulkan first frame, only when a Vulkan device exists in the container.
+# 3. Window activation: X11 (_NET_ACTIVE_WINDOW under a window manager) and
+# Wayland (the xdg_activation_v1 global of a headless wlroots compositor).
+# Runs 1 and 2 talk to scripts/unreal/fake_bridge.py (mounted at /repo) over
+# loopback: URL in DODAIOS_VERSE_BRIDGE, token in DODAIOS_VERSE_TOKEN. The
+# scenarios /out/bridge-{server,vulkan}.json come from package.py; the
+# reports land in /out/bridge-{server,vulkan}-report.json.
+# Writes /out/result.json; scripts/unreal/package.py reads it.
+set -u
+
+seconds="${1:-60}"
+mode="${2:-nogpu}"
+out=/out
+stages='boot,hangar,arena30s'
+export XDG_RUNTIME_DIR=/tmp/xdg-verse
+mkdir -p "${XDG_RUNTIME_DIR}"
+chmod 700 "${XDG_RUNTIME_DIR}"
+
+# Start the fake bridge for run <name>; sets bridge_pid and exports the
+# bridge URL and token for the game.
+start_bridge() {
+ name="$1"
+ DODAIOS_VERSE_TOKEN="$(python3 -c 'import secrets; print(secrets.token_hex(16))')"
+ export DODAIOS_VERSE_TOKEN
+ rm -f "/tmp/bridge-${name}.json"
+ python3 /repo/scripts/unreal/fake_bridge.py --scenario "${out}/bridge-${name}.json" --once \
+ --report "${out}/bridge-${name}-report.json" --discovery "/tmp/bridge-${name}.json" \
+ >"${out}/bridge-${name}.log" 2>&1 &
+ bridge_pid=$!
+ DODAIOS_VERSE_BRIDGE=''
+ for _ in $(seq 1 150); do
+ if [ -s "/tmp/bridge-${name}.json" ]; then
+ DODAIOS_VERSE_BRIDGE="$(python3 -c 'import json, sys; print(json.load(open(sys.argv[1]))["url"])' "/tmp/bridge-${name}.json" 2>/dev/null)"
+ [ -n "${DODAIOS_VERSE_BRIDGE}" ] && break
+ fi
+ sleep 0.1
+ done
+ export DODAIOS_VERSE_BRIDGE
+}
+
+# Stop the fake bridge: it exits by itself once the game disconnected (--once);
+# SIGINT makes it write its report on the way out.
+stop_bridge() {
+ for _ in $(seq 1 50); do
+ kill -0 "${bridge_pid}" 2>/dev/null || break
+ sleep 0.2
+ done
+ if kill -0 "${bridge_pid}" 2>/dev/null; then
+ kill -INT "${bridge_pid}" 2>/dev/null
+ sleep 3
+ kill -KILL "${bridge_pid}" 2>/dev/null
+ fi
+ wait "${bridge_pid}" 2>/dev/null
+ unset DODAIOS_VERSE_BRIDGE DODAIOS_VERSE_TOKEN
+}
+
+stages_ok() {
+ log="$1"
+ for stage in boot hangar arena30s; do
+ grep -q "VerseSmoke: stage ${stage} OK" "${log}" 2>/dev/null || return 1
+ done
+ return 0
+}
+
+# --- 1. server run ----------------------------------------------------------
+start_bridge server
+start=$(date +%s)
+timeout --signal=TERM "$((seconds + 60))" /verse/Verse.sh -nullrhi -nosound -unattended \
+ -VerseSmoke="${stages}" -log -abslog="${out}/nullrhi.log" >"${out}/nullrhi.stdout" 2>&1
+server_rc=$?
+server_seconds=$(( $(date +%s) - start ))
+stop_bridge
+server_ok=false
+if [ "${server_rc}" -eq 0 ] && stages_ok "${out}/nullrhi.log"; then server_ok=true; fi
+
+# --- 2. Vulkan first frame --------------------------------------------------
+vulkan='skip'
+if [ "${mode}" = 'gpu' ] && vulkaninfo --summary >"${out}/vulkaninfo.txt" 2>&1; then
+ Xvfb :99 -screen 0 1280x720x24 >/dev/null 2>&1 &
+ xvfb_pid=$!
+ sleep 2
+ start_bridge vulkan
+ DISPLAY=:99 timeout --signal=TERM 120 /verse/Verse.sh -vulkan -windowed -ResX=1280 -ResY=720 \
+ -nosound -unattended -VerseSmoke=boot -log -abslog="${out}/vulkan.log" >"${out}/vulkan.stdout" 2>&1
+ stop_bridge
+ if grep -q 'VerseSmoke: first frame' "${out}/vulkan.log" 2>/dev/null; then
+ vulkan='ok'
+ else
+ vulkan='fail'
+ fi
+ kill "${xvfb_pid}" 2>/dev/null
+fi
+
+# --- 3. activation ----------------------------------------------------------
+Xvfb :98 -screen 0 1024x768x24 >/dev/null 2>&1 &
+x_pid=$!
+sleep 1
+DISPLAY=:98 openbox >/dev/null 2>&1 &
+wm_pid=$!
+# A headless wlroots compositor: it implements xdg_activation_v1.
+WLR_BACKENDS=headless WLR_LIBINPUT_NO_DEVICES=1 sway -c /dev/null >"${out}/sway.log" 2>&1 &
+sway_pid=$!
+sleep 3
+wl_socket="$(cd "${XDG_RUNTIME_DIR}" && ls wayland-* 2>/dev/null | grep -v lock | head -n 1)"
+python3 /smoke/activation_check.py --x11 :98 ${wl_socket:+--wayland "${wl_socket}"} >"${out}/activation.json" 2>"${out}/activation.err"
+kill "${sway_pid}" "${wm_pid}" "${x_pid}" 2>/dev/null
+
+python3 - "${out}" "${server_ok}" "${server_rc}" "${server_seconds}" "${vulkan}" <<'PY'
+import json, sys
+out, server_ok, rc, secs, vulkan = sys.argv[1:6]
+try:
+ activation = json.load(open(f"{out}/activation.json", encoding="utf-8"))
+except (OSError, ValueError):
+ activation = {"x11": "fail", "wayland": "fail", "detail": "activation check wrote nothing"}
+problems = []
+if server_ok != "true":
+ problems.append(f"server run exit {rc} or a smoke stage was not reported OK")
+if vulkan == "fail":
+ problems.append("no Vulkan first frame although a device exists")
+for name in ("x11", "wayland"):
+ # The container provides both servers, so a skip is a failure here too.
+ if activation.get(name) != "ok":
+ problems.append(f"{name} activation is not available ({activation.get(name)})")
+json.dump({"schema": "verse.linux-smoke/1", "server_ok": server_ok == "true",
+ "server_exit": int(rc), "server_seconds": int(secs), "vulkan": vulkan,
+ "activation": activation, "problems": problems},
+ open(f"{out}/result.json", "w", encoding="utf-8"), indent=2)
+PY
diff --git a/packaging/linux/verse/smoke.Dockerfile b/packaging/linux/verse/smoke.Dockerfile
new file mode 100644
index 0000000000..b71d631902
--- /dev/null
+++ b/packaging/linux/verse/smoke.Dockerfile
@@ -0,0 +1,16 @@
+# Container of the nightly Linux smoke of the Unreal Verse
+# (docs/verse/unreal/work-packages.md WP22.7, scripts/unreal/package.py linux-smoke).
+# The packaged build is mounted read-only at /verse, this folder at /smoke and
+# the result folder at /out, and scripts/ plus the bridge golden data under
+# /repo for the fake bridge; the run itself has no network (loopback only).
+FROM ubuntu:24.04
+RUN apt-get update \
+ && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
+ ca-certificates libvulkan1 mesa-vulkan-drivers vulkan-tools \
+ xvfb x11-utils openbox sway wayland-utils python3 python3-pip procps coreutils \
+ && rm -rf /var/lib/apt/lists/* \
+ && pip3 install --no-cache-dir --break-system-packages "websockets==16.0" "jsonschema==4.26.0"
+# The engine refuses to run as root.
+RUN useradd --create-home --uid 1001 verse
+USER verse
+WORKDIR /home/verse
diff --git a/packaging/windows/verse/README.md b/packaging/windows/verse/README.md
new file mode 100644
index 0000000000..aef85a1ee1
--- /dev/null
+++ b/packaging/windows/verse/README.md
@@ -0,0 +1,22 @@
+# Verse on Windows: an optional download, never in the installer
+
+`Dodaios-Setup-x64.exe` and every app update carry no Verse
+(docs/verse/unreal/README.md, Delivery; work-packages.md WP22.5, WP22.6).
+The Verse is its own signed package on the release:
+
+1. `scripts/unreal/package.py build --platform win64` packages the Win64
+ Shipping build (IoStore chunk per deck). The `sign-windows` job of
+ `.github/workflows/unreal-package.yml` signs its executables.
+2. `package.py full` turns it into `Verse-Win64-<version>.tar`, `package.py
+ delta` adds `Verse-Win64-<old>-to-<new>.delta.tar`, and `package.py
+ manifest` writes `verse-Win64-manifest.json` (version, sizes, SHA-256 of
+ every package). The release key signs it as `verse-Win64-manifest.json.sig`.
+3. The first time someone opens the Verse, the launcher card shows the
+ download size and a "Download the Verse" button. The app
+ (`dodaios/verse_host/install`) verifies the signature, downloads the
+ package resumably, checks its SHA-256 and every file of it, and unpacks it
+ into `%LOCALAPPDATA%\Dodaios\verse`. Settings can remove it again.
+
+Only an installed Verse gets updates, as delta packages when one fits. A
+machine without a GPU is never offered the download; the Verse reports
+`unsupported` and the rest of the app is unaffected.
diff --git a/scripts/unreal/package.py b/scripts/unreal/package.py
new file mode 100644
index 0000000000..279858e76e
--- /dev/null
+++ b/scripts/unreal/package.py
@@ -0,0 +1,1360 @@
+#!/usr/bin/env python3
+"""Package, chunk, delta, smoke-test and keep the disk clean for the Unreal Verse.
+
+Work package WP22 (docs/verse/unreal/work-packages.md). Every Unreal run goes
+through the machine lock (``with_lock.py``); nothing here calls UBT or UAT
+outside it.
+
+ python scripts/unreal/package.py verify [--target all|win64|linux]
+ python scripts/unreal/package.py build --platform win64 [--config Shipping]
+ python scripts/unreal/package.py report --platform win64 [--archive DIR]
+ python scripts/unreal/package.py chunks # the ini block of the deck chunks
+ python scripts/unreal/package.py pso --platform win64 --collected DIR
+ python scripts/unreal/package.py full --stage DIR --version 4.2.0 --platform Win64 --out F
+ python scripts/unreal/package.py delta --old OLD.tar --stage DIR --version 4.2.1 --out F
+ python scripts/unreal/package.py manifest --full F [--delta D ...] --tag v4.2.1 [--out F]
+ python scripts/unreal/package.py apply --root DIR (--full F | --delta F) [--log F]
+ python scripts/unreal/package.py cold-start --platform win64
+ python scripts/unreal/package.py linux-smoke [--seconds 60]
+ python scripts/unreal/package.py hygiene [--apply] [--worktrees C:/demo]
+
+Outputs that are evidence (size report, cold-start JSON, delta apply log) go
+to ``unreal/Verse/Saved/Harness/proof/WP22/<sub-task>/`` (work-packages 0.4).
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import re
+import secrets
+import shutil
+import subprocess
+import sys
+import tarfile
+import time
+from collections.abc import Callable, Mapping, Sequence
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+if __package__ in (None, ""):
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+
+from dodaios.verse_host.install import layout as verse_layout
+from dodaios.verse_host.install import manifest as verse_manifest
+from dodaios.verse_host.install import payload as verse_payload
+from scripts.unreal import _common as common
+from scripts.unreal import with_lock
+
+TOOLCHAIN_DIR = common.UNREAL_ROOT / "Toolchain"
+CHUNKS_FILE = TOOLCHAIN_DIR / "chunks.json"
+DDC_FILE = TOOLCHAIN_DIR / "ddc.json"
+LINUX_SMOKE_DIR = common.REPO_ROOT / "packaging" / "linux" / "verse"
+SMOKE_IMAGE = "dodaios-verse-smoke:1"
+#: The scripted backend side of verse.bridge/1 (G0.11) and its golden data.
+FAKE_BRIDGE = common.REPO_ROOT / "scripts" / "unreal" / "fake_bridge.py"
+BRIDGE_DATA_DIR = common.UNREAL_ROOT / "Verse" / "Tests" / "Data" / "bridge"
+BRIDGE_ENV = "DODAIOS_VERSE_BRIDGE"
+TOKEN_ENV = "DODAIOS_VERSE_TOKEN" # noqa: S105 - the variable name, not a secret
+
+GB = 1_000_000_000
+MB = 1_000_000
+
+
+@dataclass(frozen=True)
+class PlatformSpec:
+ key: str # command-line name
+ ue: str # UAT -platform
+ staged: str # folder BuildCookRun archives into
+ launcher: str # file the person starts
+ cook: str # cooked platform name
+
+
+PLATFORMS: dict[str, PlatformSpec] = {
+ "win64": PlatformSpec("win64", "Win64", "Windows", "Verse.exe", "Windows"),
+ "linux": PlatformSpec("linux", "Linux", "Linux", "Verse.sh", "Linux"),
+}
+CONFIGS = ("Shipping", "Development")
+
+
+def proof_dir(worktree: Path, sub_task: str) -> Path:
+ return worktree / "unreal" / "Verse" / "Saved" / "Harness" / "proof" / "WP22" / sub_task
+
+
+def archive_root(worktree: Path, config: str) -> Path:
+ return worktree / "unreal" / "Verse" / "Saved" / "Package" / config
+
+
+def staged_dir(worktree: Path, spec: PlatformSpec, config: str) -> Path:
+ return archive_root(worktree, config) / spec.staged
+
+
+def write_json(path: Path, data: Any) -> Path:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(data, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+ return path
+
+
+# --------------------------------------------------------------------------- #
+# 22.1 Toolchain pins and verify
+# --------------------------------------------------------------------------- #
+def load_chunks(path: Path = CHUNKS_FILE) -> dict:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ problems = chunk_rule_problems(data)
+ if problems:
+ raise common.UnrealScriptError(f"{path}: {'; '.join(problems)}")
+ return data
+
+
+def chunk_rule_problems(data: Mapping[str, Any]) -> list[str]:
+ problems: list[str] = []
+ if data.get("schema") != "verse.chunks/1":
+ problems.append("schema must be verse.chunks/1")
+ chunks = list(data.get("chunks") or [])
+ ids = [c.get("id") for c in chunks]
+ if 0 not in ids:
+ problems.append("chunk 0 (core) is required")
+ if len(set(ids)) != len(ids):
+ problems.append("chunk ids must be unique")
+ names = [c.get("name") for c in chunks]
+ if len(set(names)) != len(names):
+ problems.append("chunk names must be unique")
+ maps = [m for c in chunks for m in c.get("maps", [])]
+ if len(set(maps)) != len(maps):
+ problems.append("a map belongs to exactly one chunk")
+ for path in maps:
+ if not re.fullmatch(r"/Game/Verse/Decks/[A-Za-z]+/LV_[A-Za-z]+", path):
+ problems.append(f"{path} is not a deck level (/Game/Verse/Decks/<Deck>/LV_<Deck>)")
+ gate = data.get("size_gate") or {}
+ for key in ("payload_max_bytes", "delta_typical_max_bytes"):
+ if not isinstance(gate.get(key), int) or gate[key] <= 0:
+ problems.append(f"size_gate.{key} must be a positive integer")
+ return problems
+
+
+def load_ddc(path: Path = DDC_FILE) -> dict:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ if data.get("schema") != "verse.ddc/1" or data.get("shared") is not False:
+ raise common.UnrealScriptError(f"{path}: want schema verse.ddc/1 and shared false")
+ if not 0 < int(data.get("cap_gb", 0)) <= 100:
+ raise common.UnrealScriptError(f"{path}: cap_gb must be between 1 and 100")
+ return data
+
+
+def ddc_args(ddc: Mapping[str, Any]) -> list[str]:
+ return [f"-ddc={ddc['graph']}"]
+
+
+def ddc_env(ddc: Mapping[str, Any], base: Mapping[str, str] | None = None) -> dict[str, str]:
+ env = dict(os.environ if base is None else base)
+ env[ddc["local_path_env"]] = ddc["local_path"]
+ return env
+
+
+@dataclass
+class VerifyProbe:
+ run: Callable[..., common.Completed] = common.run
+ exists: Callable[[Path], bool] = Path.exists
+ which: Callable[[str], str | None] = shutil.which
+
+
+def verify_packaging(
+ targets: Sequence[str], *, engine: Path, probe: VerifyProbe | None = None
+) -> list[dict]:
+ """Packaging checks on top of ``doctor.py``: pins, Linux engine part, Docker."""
+ probe = probe or VerifyProbe()
+ checks: list[dict] = []
+
+ def add(name: str, ok: bool, detail: str, fix: str = "") -> None:
+ checks.append(
+ {
+ "name": name,
+ "status": "ok" if ok else "fail",
+ "detail": detail,
+ "fix": "" if ok else fix,
+ }
+ )
+
+ try:
+ chunks = load_chunks()
+ add("chunks", True, f"{len(chunks['chunks'])} chunks in {CHUNKS_FILE.name}")
+ except (OSError, ValueError, common.UnrealScriptError) as exc:
+ add("chunks", False, str(exc), "fix unreal/Toolchain/chunks.json")
+ try:
+ ddc = load_ddc()
+ add("ddc", True, f"{ddc['graph']}, cap {ddc['cap_gb']} GB, {ddc['local_path']}")
+ except (OSError, ValueError, KeyError, common.UnrealScriptError) as exc:
+ add("ddc", False, str(exc), "fix unreal/Toolchain/ddc.json")
+ if "linux" in targets:
+ marker = engine / "Engine" / "Binaries" / "Linux" / "UnrealGame.target"
+ add(
+ "linux-engine",
+ probe.exists(marker),
+ f"{marker}",
+ "add the Linux target platform to the engine install once (launcher: UE 5.7, "
+ "Options, Target Platforms, Linux)",
+ )
+ docker = probe.which("docker")
+ ok = (
+ bool(docker)
+ and probe.run(
+ [docker or "docker", "info", "--format", "{{.OSType}}"], capture=True
+ ).returncode
+ == 0
+ )
+ add(
+ "docker",
+ ok,
+ docker or "docker not on PATH",
+ "start Docker Desktop with Linux containers (the Linux smoke runs in one)",
+ )
+ return checks
+
+
+def cmd_verify(options: argparse.Namespace) -> int:
+ from scripts.unreal import doctor
+
+ targets = ("win64", "linux") if options.target == "all" else (options.target,)
+ checks = [
+ {"name": c.name, "status": c.status, "detail": c.detail, "fix": c.fix}
+ for c in doctor.diagnose(targets)
+ ]
+ checks += verify_packaging(targets, engine=common.engine_root())
+ for check in checks:
+ common.log(f"{check['status'].upper():5} {check['name']:16} {check['detail']}")
+ if check["status"] == "fail" and check["fix"]:
+ common.log(f"{'':22}fix: {check['fix']}")
+ failed = [c for c in checks if c["status"] == "fail"]
+ common.log("verify: GREEN" if not failed else f"verify: RED ({len(failed)} failing)")
+ return 0 if not failed else 1
+
+
+# --------------------------------------------------------------------------- #
+# 22.2 BuildCookRun, 22.3 chunks and PSO cache
+# --------------------------------------------------------------------------- #
+def chunk_ini_block(chunks: Mapping[str, Any]) -> str:
+ """The config lines that put every deck level in its own IoStore chunk.
+
+ ``Config/DefaultGame.ini`` belongs to the integration owner, so this block
+ is what WP22's contract change request asks to merge.
+ """
+ lines = [
+ "[/Script/UnrealEd.ProjectPackagingSettings]",
+ "bGenerateChunks=True",
+ "bShareMaterialShaderCode=True",
+ "bSharedMaterialNativeLibraries=True",
+ "",
+ "[/Script/Engine.AssetManagerSettings]",
+ '+PrimaryAssetTypesToScan=(PrimaryAssetType="Map",AssetBaseClass=/Script/Engine.World,'
+ 'bHasBlueprintClasses=False,bIsEditorOnly=True,Directories=((Path="/Game/Verse/Decks")),'
+ "Rules=(Priority=-1,ChunkId=-1,bApplyRecursively=True,CookRule=Unknown))",
+ ]
+ for chunk in sorted(chunks["chunks"], key=lambda c: c["id"]):
+ for path in chunk.get("maps", []):
+ name = path.rsplit("/", 1)[-1]
+ priority = 10 + chunk["id"]
+ lines.append(
+ f'+PrimaryAssetRules=(PrimaryAssetId="Map:{name}",Rules=(Priority={priority},'
+ f"ChunkId={chunk['id']},bApplyRecursively=True,CookRule=AlwaysCook))"
+ )
+ return "\n".join(lines) + "\n"
+
+
+def missing_chunk_config(project_dir: Path, chunks: Mapping[str, Any]) -> list[str]:
+ """Lines of :func:`chunk_ini_block` that ``DefaultGame.ini`` does not have yet."""
+ try:
+ text = (project_dir / "Config" / "DefaultGame.ini").read_text(encoding="utf-8")
+ except OSError:
+ text = ""
+ have = {line.strip() for line in text.splitlines()}
+ wanted = [line for line in chunk_ini_block(chunks).splitlines() if line and "=" in line]
+ return [line for line in wanted if line not in have]
+
+
+def buildcookrun_command(
+ spec: PlatformSpec,
+ config: str,
+ *,
+ engine: Path,
+ project: Path,
+ archive: Path,
+ ddc: Mapping[str, Any] | None = None,
+) -> list[str]:
+ command = [
+ str(common.run_uat_bat(engine)),
+ "BuildCookRun",
+ f"-project={project}",
+ "-target=Verse",
+ f"-platform={spec.ue}",
+ f"-clientconfig={config}",
+ "-build",
+ "-cook",
+ "-stage",
+ "-pak",
+ "-iostore",
+ "-compressed",
+ "-manifests",
+ "-archive",
+ f"-archivedirectory={archive}",
+ "-nodebuginfo",
+ "-unattended",
+ "-utf8output",
+ "-nocompileeditor",
+ "-NoP4",
+ f"-ubtargs=-MaxParallelActions={common.MAX_PARALLEL_ACTIONS}",
+ ]
+ if spec.key == "win64":
+ command.append("-prereqs")
+ if ddc:
+ command += ddc_args(ddc)
+ return command
+
+
+def editor_build_command(engine: Path, project: Path) -> list[str]:
+ return [
+ str(common.build_bat(engine)),
+ "VerseEditor",
+ "Win64",
+ "Development",
+ f"-Project={project}",
+ "-WaitMutex",
+ "-NoHotReloadFromIDE",
+ f"-MaxParallelActions={common.MAX_PARALLEL_ACTIONS}",
+ ]
+
+
+_HARNESS_MARKERS = (b"VerseHarness", "VerseHarness".encode("utf-16-le"))
+
+
+def harness_problems(worktree: Path, spec: PlatformSpec, staged: Path | None) -> list[str]:
+ """Where the harness shows up in a Shipping build; empty means it is absent."""
+ problems: list[str] = []
+ source = worktree / "unreal" / "Verse" / "Source"
+ try:
+ target_cs = (source / "Verse.Target.cs").read_text(encoding="utf-8")
+ except OSError:
+ target_cs = ""
+ code = "\n".join(line.split("//", 1)[0] for line in target_cs.splitlines())
+ if "VerseHarness" in code:
+ problems.append("Verse.Target.cs lists VerseHarness")
+ intermediate = worktree / "unreal" / "Verse" / "Intermediate" / "Build" / spec.ue
+ if intermediate.is_dir():
+ for folder in intermediate.rglob("VerseHarness"):
+ parts = {p.lower() for p in folder.parts}
+ if folder.is_dir() and "shipping" in parts and "verseeditor" not in parts:
+ problems.append(f"Shipping objects of VerseHarness at {folder}")
+ if staged is not None and staged.is_dir():
+ for binary in staged.rglob("*"):
+ if not binary.is_file() or binary.suffix.lower() in {".pak", ".utoc", ".ucas"}:
+ continue
+ if binary.suffix.lower() not in {".exe", ".dll", ".so", ""}:
+ continue
+ data = binary.read_bytes()
+ if any(marker in data for marker in _HARNESS_MARKERS):
+ problems.append(f"{binary.relative_to(staged).as_posix()} carries VerseHarness")
+ return problems
+
+
+_PAK_NAME = re.compile(
+ r"^(?:pakchunk(?P<id>\d+)(?:optional)?(?:s\d+)?-[A-Za-z0-9]+|(?P<global>global))"
+ r"\.(?:pak|utoc|ucas|sig)$",
+ re.IGNORECASE,
+)
+
+
+def size_report(staged: Path, chunks: Mapping[str, Any], *, platform: str) -> dict[str, Any]:
+ """Bytes per deck chunk plus binaries; the size gate of A22.1 for the full payload."""
+ names = {c["id"]: c["name"] for c in chunks["chunks"]}
+ groups: dict[str, dict[str, Any]] = {}
+
+ def add(group: str, path: Path) -> None:
+ entry = groups.setdefault(group, {"bytes": 0, "files": 0})
+ entry["bytes"] += path.stat().st_size
+ entry["files"] += 1
+
+ unknown: list[str] = []
+ pso = False
+ for path in sorted(p for p in staged.rglob("*") if p.is_file()):
+ match = _PAK_NAME.match(path.name)
+ if match and match.group("global"):
+ add("global", path)
+ elif match:
+ chunk_id = int(match.group("id"))
+ if chunk_id not in names:
+ unknown.append(path.name)
+ add(names.get(chunk_id, f"chunk{chunk_id}"), path)
+ else:
+ if path.suffix.lower() == ".spc" or "PipelineCaches" in path.parts:
+ pso = True
+ add("binaries", path)
+ total = sum(g["bytes"] for g in groups.values())
+ cap = chunks["size_gate"]["payload_max_bytes"]
+ decks = [c["name"] for c in chunks["chunks"] if c.get("maps")]
+ return {
+ "schema": "verse.size-report/1",
+ "platform": platform,
+ "chunks": groups,
+ "total_bytes": total,
+ "payload_max_bytes": cap,
+ "within_payload_cap": total <= cap,
+ "deck_chunks_present": sorted(d for d in decks if d in groups),
+ "deck_chunks_missing": sorted(d for d in decks if d not in groups),
+ "unknown_chunk_files": unknown,
+ "pso_cache_shipped": pso,
+ }
+
+
+def pso_expand_command(
+ engine: Path, project: Path, collected: Sequence[Path], shk: Sequence[Path], out: Path
+) -> list[str]:
+ """``ShaderPipelineCacheTools expand``: recorded PSOs + cook shader keys -> ``.spc``."""
+ return [
+ str(common.editor_cmd(engine)),
+ str(project),
+ "-run=ShaderPipelineCacheTools",
+ "expand",
+ *(str(p) for p in collected),
+ *(str(p) for p in shk),
+ str(out),
+ "-unattended",
+ "-nullrhi",
+ "-nosplash",
+ "-NoP4",
+ "-stdout",
+ ]
+
+
+def pso_paths(worktree: Path, spec: PlatformSpec) -> tuple[Path, Path]:
+ """(cooked shader key folder, the engine-required shipped cache folder)."""
+ project_dir = worktree / "unreal" / "Verse"
+ shk = project_dir / "Saved" / "Cooked" / spec.cook / "Verse" / "Metadata" / "PipelineCaches"
+ shipped = project_dir / "Build" / spec.staged / "PipelineCaches"
+ return shk, shipped
+
+
+def cmd_build(options: argparse.Namespace) -> int:
+ spec = PLATFORMS[options.platform]
+ worktree = options.worktree.resolve()
+ engine = common.engine_root()
+ project = common.project_file(worktree)
+ archive = archive_root(worktree, options.config)
+ chunks = load_chunks()
+ missing = missing_chunk_config(project.parent, chunks)
+ if missing:
+ common.log(
+ f"chunks: DefaultGame.ini lacks {len(missing)} chunk lines; every deck lands "
+ "in chunk 0 until the integration owner merges `package.py chunks`"
+ )
+ if options.require_chunks:
+ return 1
+ if spec.key == "linux" and not os.environ.get("LINUX_MULTIARCH_ROOT", "").strip():
+ return common.exit_with(
+ common.UnrealScriptError(
+ "LINUX_MULTIARCH_ROOT is not set (package.py verify --target linux)"
+ )
+ )
+ common.require_free_disk(worktree)
+ try:
+ ddc = load_ddc()
+ except (OSError, ValueError, common.UnrealScriptError) as exc:
+ return common.exit_with(exc)
+ env = ddc_env(ddc)
+ steps = []
+ if not options.skip_editor:
+ steps.append(("build editor", editor_build_command(engine, project)))
+ steps.append(
+ (
+ f"package {spec.key} {options.config}",
+ buildcookrun_command(
+ spec, options.config, engine=engine, project=project, archive=archive, ddc=ddc
+ ),
+ )
+ )
+ for label, command in steps:
+ common.log(f"{label}: {' '.join(command)}")
+ started = time.monotonic()
+ code = with_lock.run_locked(
+ command, label=f"{label} ({worktree.name})", cwd=worktree, env=env
+ )
+ common.log(f"{label}: exit {code} in {(time.monotonic() - started) / 60:.1f} min")
+ if code != 0:
+ return code
+ staged = staged_dir(worktree, spec, options.config)
+ out = proof_dir(worktree, "22.2")
+ problems = harness_problems(worktree, spec, staged) if options.config == "Shipping" else []
+ report = size_report(staged, chunks, platform=spec.ue)
+ report["harness_problems"] = problems
+ path = write_json(out / f"size-{spec.key}-{options.config}.json", report)
+ common.log(f"size report: {path} total {report['total_bytes'] / MB:.1f} MB")
+ for problem in problems:
+ common.log(f"PROBLEM {problem}")
+ return 0 if not problems and report["within_payload_cap"] else 1
+
+
+def cmd_report(options: argparse.Namespace) -> int:
+ spec = PLATFORMS[options.platform]
+ worktree = options.worktree.resolve()
+ staged = options.archive or staged_dir(worktree, spec, options.config)
+ report = size_report(staged, load_chunks(), platform=spec.ue)
+ report["harness_problems"] = harness_problems(worktree, spec, staged)
+ print(json.dumps(report, indent=2, sort_keys=True))
+ return 0 if report["within_payload_cap"] and not report["harness_problems"] else 1
+
+
+def cmd_chunks(_options: argparse.Namespace) -> int:
+ print(chunk_ini_block(load_chunks()), end="")
+ return 0
+
+
+def cmd_pso(options: argparse.Namespace) -> int:
+ spec = PLATFORMS[options.platform]
+ worktree = options.worktree.resolve()
+ shk_dir, shipped = pso_paths(worktree, spec)
+ collected = sorted(Path(options.collected).glob("*.upipelinecache"))
+ shk = sorted(shk_dir.glob("*.shk"))
+ if not collected or not shk:
+ return common.exit_with(
+ common.UnrealScriptError(
+ f"need recorded *.upipelinecache in {options.collected} "
+ f"(play a build with -logPSO) and cooked *.shk in {shk_dir}"
+ )
+ )
+ out = shipped / f"Verse_{spec.ue}.spc"
+ out.parent.mkdir(parents=True, exist_ok=True)
+ command = pso_expand_command(
+ common.engine_root(), common.project_file(worktree), collected, shk, out
+ )
+ return with_lock.run_locked(command, label=f"pso {spec.key}", cwd=worktree)
+
+
+# --------------------------------------------------------------------------- #
+# 22.4 Full payloads and deltas
+# --------------------------------------------------------------------------- #
+def _add_bytes(archive: tarfile.TarFile, name: str, data: bytes) -> None:
+ import io
+
+ info = tarfile.TarInfo(name)
+ info.size = len(data)
+ info.mtime = 0
+ info.mode = 0o644
+ archive.addfile(info, io.BytesIO(data))
+
+
+def _add_file(archive: tarfile.TarFile, name: str, path: Path) -> None:
+ info = tarfile.TarInfo(name)
+ info.size = path.stat().st_size
+ info.mtime = 0
+ info.mode = 0o755 if os.access(path, os.X_OK) and path.suffix in {"", ".sh"} else 0o644
+ with path.open("rb") as handle:
+ archive.addfile(info, handle)
+
+
+def _json_bytes(data: Any) -> bytes:
+ return (json.dumps(data, indent=2, sort_keys=True) + "\n").encode("utf-8")
+
+
+def make_full(
+ stage: Path, *, version: str, platform: str, out: Path, entry: str | None = None
+) -> dict[str, Any]:
+ """A full package tar of a staged build (uncompressed: IoStore is compressed already).
+
+ ``entry`` is the file the app launches; by default the platform's Unreal
+ launcher (``Verse.exe`` / ``Verse.sh``).
+ """
+ tree = verse_payload.build_tree(stage, version=version, platform=platform, entry=entry)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ with tarfile.open(out, "w", format=tarfile.PAX_FORMAT) as archive:
+ _add_bytes(archive, verse_payload.VERSE_TREE_FILE, _json_bytes(tree))
+ for rel in tree["files"]:
+ _add_file(archive, f"files/{rel}", stage / rel)
+ return {
+ "kind": "full",
+ "version": tree["version"],
+ "platform": platform,
+ "files": len(tree["files"]),
+ "bytes": out.stat().st_size,
+ "tree": tree,
+ }
+
+
+def read_payload_tree(source: Path) -> dict[str, Any]:
+ """The tree of a previous version: a full package tar or an installed version folder."""
+ return verse_payload.read_package_tree(source)
+
+
+def make_delta(
+ old_tree: Mapping[str, Any],
+ stage: Path,
+ *,
+ version: str,
+ out: Path,
+ typical_max_bytes: int = 300 * MB,
+ entry: str | None = None,
+) -> dict[str, Any]:
+ """A delta tar from ``old_tree`` to the staged build: only changed or new files."""
+ platform = str(old_tree["platform"])
+ tree = verse_payload.build_tree(stage, version=version, platform=platform, entry=entry)
+ old_files = old_tree["files"]
+ changed = [
+ rel
+ for rel, entry in tree["files"].items()
+ if old_files.get(rel, {}).get("sha256") != entry["sha256"]
+ ]
+ reuse = [rel for rel in tree["files"] if rel not in set(changed)]
+ removed = sorted(set(old_files) - set(tree["files"]))
+ header = {
+ "schema": verse_payload.VERSE_DELTA_SCHEMA,
+ "platform": platform,
+ "from": old_tree["version"],
+ "to": tree["version"],
+ "from_tree_sha256": verse_payload.tree_digest(dict(old_tree)),
+ "files": changed,
+ "reuse": reuse,
+ "removed": removed,
+ }
+ out.parent.mkdir(parents=True, exist_ok=True)
+ with tarfile.open(out, "w", format=tarfile.PAX_FORMAT) as archive:
+ _add_bytes(archive, verse_payload.VERSE_DELTA_FILE, _json_bytes(header))
+ _add_bytes(archive, verse_payload.VERSE_TREE_FILE, _json_bytes(tree))
+ for rel in changed:
+ _add_file(archive, f"files/{rel}", stage / rel)
+ size = out.stat().st_size
+ return {
+ "kind": "delta",
+ "from": header["from"],
+ "to": header["to"],
+ "platform": platform,
+ "changed": len(changed),
+ "reused": len(reuse),
+ "removed": len(removed),
+ "bytes": size,
+ "typical_max_bytes": typical_max_bytes,
+ "within_typical": size <= typical_max_bytes,
+ "changed_files": changed,
+ }
+
+
+def cmd_full(options: argparse.Namespace) -> int:
+ result = make_full(
+ options.stage, version=options.version, platform=options.platform, out=options.out
+ )
+ result.pop("tree")
+ print(json.dumps(result, indent=2))
+ return 0
+
+
+def cmd_delta(options: argparse.Namespace) -> int:
+ gate = load_chunks()["size_gate"]["delta_typical_max_bytes"]
+ result = make_delta(
+ read_payload_tree(options.old),
+ options.stage,
+ version=options.version,
+ out=options.out,
+ typical_max_bytes=gate,
+ )
+ print(json.dumps(result, indent=2))
+ if not result["within_typical"]:
+ common.log(
+ f"delta is {result['bytes'] / MB:.0f} MB, over the typical "
+ f"{gate / MB:.0f} MB budget (A22.1)"
+ )
+ return 0
+
+
+def cmd_apply(options: argparse.Namespace) -> int:
+ root = options.root
+ started = time.monotonic()
+ entry: dict[str, Any] = {"root": str(root), "before": verse_layout.read_current(root)}
+ try:
+ if options.full:
+ entry["result"] = verse_payload.install_full(root, options.full)
+ else:
+ entry["result"] = verse_payload.apply_delta(root, options.delta)
+ entry["status"] = "applied"
+ except verse_layout.VerseInstallError as exc:
+ entry["status"] = "rolled_back"
+ entry["error"] = str(exc)
+ entry["after"] = verse_layout.read_current(root)
+ after = entry["after"]
+ entry["verify_problems"] = (
+ verse_payload.verify_tree(verse_layout.version_dir(root, after["version"]))
+ if after
+ else ["nothing installed"]
+ )
+ entry["seconds"] = round(time.monotonic() - started, 3)
+ if options.log:
+ with Path(options.log).open("a", encoding="utf-8") as handle:
+ handle.write(json.dumps(entry, sort_keys=True) + "\n")
+ print(json.dumps(entry, indent=2, sort_keys=True))
+ return 0 if entry["status"] == "applied" and not entry["verify_problems"] else 1
+
+
+def _delta_header(delta: Path) -> dict[str, Any]:
+ with tarfile.open(delta, "r:") as archive:
+ handle = archive.extractfile(archive.getmember(verse_payload.VERSE_DELTA_FILE))
+ if handle is None:
+ raise common.UnrealScriptError(f"{delta} has no {verse_payload.VERSE_DELTA_FILE}")
+ return json.loads(handle.read().decode("utf-8"))
+
+
+def make_release_manifest(full: Path, deltas: Sequence[Path], *, tag: str) -> bytes:
+ """The per-platform release manifest (22.5) the release key signs (22.8).
+
+ Names the version, the full package's size and SHA-256, the unpacked size,
+ the digest of the package's file list and every delta with the build it
+ starts from, so the app can show the size and check everything it fetches.
+ """
+ tree = verse_payload.read_package_tree(full)
+ platform = str(tree["platform"])
+ version = str(tree["version"])
+ expected_full = verse_manifest.full_asset_name(platform, version)
+ if full.name != expected_full:
+ raise common.UnrealScriptError(f"{full.name} should be named {expected_full}")
+ delta_refs = []
+ for delta in deltas:
+ header = _delta_header(delta)
+ if header.get("to") != version or header.get("platform") != platform:
+ raise common.UnrealScriptError(f"{delta.name} does not lead to {platform} {version}")
+ delta_refs.append(
+ {
+ "name": delta.name,
+ "from": header["from"],
+ "from_tree_sha256": header["from_tree_sha256"],
+ "size": delta.stat().st_size,
+ "sha256": verse_payload.sha256_file(delta),
+ }
+ )
+ return verse_manifest.build_release_manifest(
+ version=version,
+ tag=tag,
+ platform=platform,
+ entry=tree.get("entry"),
+ install_bytes=sum(int(f["size"]) for f in tree["files"].values()),
+ tree_sha256=verse_payload.tree_digest(tree),
+ full={
+ "name": full.name,
+ "size": full.stat().st_size,
+ "sha256": verse_payload.sha256_file(full),
+ },
+ deltas=delta_refs,
+ )
+
+
+def cmd_manifest(options: argparse.Namespace) -> int:
+ data = make_release_manifest(options.full, options.delta or [], tag=options.tag)
+ platform = verse_manifest.parse_release_manifest(data).platform
+ out = options.out or options.full.with_name(verse_manifest.manifest_asset_name(platform))
+ out.write_bytes(data)
+ print(json.dumps({"manifest": str(out), **json.loads(data)}, indent=2))
+ return 0
+
+
+# --------------------------------------------------------------------------- #
+# A22.2 Cold start
+# --------------------------------------------------------------------------- #
+#: The harness line the game logs on its first rendered frame. ``stage boot
+#: OK`` is not it: that stage ends after the handshake and the deck load.
+FIRST_FRAME = re.compile(r"VerseSmoke: first frame")
+#: How long the game keeps running after its first frame, so that
+#: ``lifecycle.ready`` reaches the bridge before the game is stopped.
+READY_GRACE_S = 5.0
+COLD_START_BUDGET_S = 8.0
+
+
+def bridge_scenario(*, ready_timeout_s: float, ready_optional: bool = False) -> dict[str, Any]:
+ """A fake-bridge scenario that waits for ``lifecycle.ready`` after the handshake."""
+ return {
+ "name": "verse-package-smoke",
+ "description": "Handshake, then lifecycle.ready {first_frame_ms} after the first frame.",
+ "topics": [],
+ "watch_screens": [],
+ "watch_chat_tails": [],
+ "state": {},
+ "replies": {},
+ "steps": [
+ {
+ "at_ms": 0,
+ "expect": {"type": "lifecycle.ready"},
+ "timeout_ms": int(ready_timeout_s * 1000),
+ "optional": ready_optional,
+ }
+ ],
+ }
+
+
+def bridge_problems(report: Mapping[str, Any] | None, *, require_ready: bool) -> list[str]:
+ """What a fake-bridge run report says is wrong with the Verse's side of the bridge."""
+ if not report:
+ return ["the Verse never finished the bridge handshake (the fake bridge wrote no report)"]
+ problems = []
+ # The bridge answers only a valid hello (protocol, token) with welcome, and
+ # counts the hello itself outside the session, so welcome is the proof.
+ if not report.get("sent", {}).get("welcome"):
+ problems.append("no hello/welcome handshake (the bridge sent no welcome)")
+ if require_ready:
+ ready = [e for e in report.get("expectations", []) if e.get("type") == "lifecycle.ready"]
+ if not (ready and ready[0].get("ok")):
+ problems.append("no lifecycle.ready after the first frame")
+ invalid = report.get("invalid_from_verse") or []
+ if invalid:
+ problems.append(f"{len(invalid)} invalid frames from the Verse: {invalid[0]}")
+ return problems
+
+
+class FakeBridgeRun:
+ """``fake_bridge.py`` around one game run: URL and token for the game's environment.
+
+ The bridge plays :func:`bridge_scenario` once and writes its report when
+ the game disconnects; :attr:`report` holds it after the ``with`` block
+ (``None`` when the game never connected).
+ """
+
+ def __init__(
+ self,
+ out: Path,
+ *,
+ token: str,
+ ready_timeout_s: float,
+ fake_bridge: Path = FAKE_BRIDGE,
+ start_timeout_s: float = 15.0,
+ stop_timeout_s: float = 15.0,
+ ) -> None:
+ self.out = out
+ self.token = token
+ self.ready_timeout_s = ready_timeout_s
+ self.fake_bridge = fake_bridge
+ self.start_timeout_s = start_timeout_s
+ self.stop_timeout_s = stop_timeout_s
+ self.url = ""
+ self.report: dict[str, Any] | None = None
+ self.process: subprocess.Popen | None = None
+ self.report_path = out / "bridge-report.json"
+
+ def env(self, base: Mapping[str, str] | None = None) -> dict[str, str]:
+ return {
+ **(os.environ if base is None else base),
+ BRIDGE_ENV: self.url,
+ TOKEN_ENV: self.token,
+ }
+
+ def __enter__(self) -> FakeBridgeRun:
+ if not self.fake_bridge.is_file():
+ raise common.UnrealScriptError(
+ f"{self.fake_bridge} is missing; the fake bridge lands with G0.11"
+ )
+ self.out.mkdir(parents=True, exist_ok=True)
+ scenario = write_json(
+ self.out / "bridge-scenario.json", bridge_scenario(ready_timeout_s=self.ready_timeout_s)
+ )
+ discovery = self.out / "bridge-discovery.json"
+ for stale in (discovery, self.report_path):
+ stale.unlink(missing_ok=True)
+ command = [
+ sys.executable,
+ str(self.fake_bridge),
+ "--scenario",
+ str(scenario),
+ "--once",
+ "--report",
+ str(self.report_path),
+ "--discovery",
+ str(discovery),
+ ]
+ with (self.out / "bridge.log").open("w", encoding="utf-8") as log_handle:
+ self.process = subprocess.Popen( # noqa: S603 - fixed argv
+ command,
+ cwd=str(common.REPO_ROOT),
+ env={**os.environ, TOKEN_ENV: self.token},
+ stdout=log_handle,
+ stderr=subprocess.STDOUT,
+ )
+ deadline = time.monotonic() + self.start_timeout_s
+ while time.monotonic() < deadline and self.process.poll() is None:
+ try:
+ self.url = str(json.loads(discovery.read_text(encoding="utf-8"))["url"])
+ return self
+ except (OSError, ValueError, KeyError):
+ time.sleep(0.05)
+ self._stop()
+ raise common.UnrealScriptError(f"the fake bridge did not start ({self.out / 'bridge.log'})")
+
+ def _stop(self) -> None:
+ process = self.process
+ if process is None:
+ return
+ try:
+ # With --once the bridge exits by itself once the game disconnected.
+ process.wait(timeout=self.stop_timeout_s)
+ except subprocess.TimeoutExpired:
+ process.terminate()
+ try:
+ process.wait(timeout=10)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait()
+
+ def __exit__(self, *exc: object) -> None:
+ self._stop()
+ try:
+ self.report = json.loads(self.report_path.read_text(encoding="utf-8"))
+ except (OSError, ValueError): # no report: the game never connected
+ self.report = None
+
+
+def wait_for_marker(
+ log_path: Path,
+ pattern: re.Pattern[str],
+ *,
+ timeout_s: float,
+ alive: Callable[[], bool],
+ clock: Callable[[], float] = time.monotonic,
+ sleep: Callable[[float], None] = time.sleep,
+) -> float | None:
+ """Seconds until ``pattern`` appears in ``log_path``; ``None`` on timeout or exit."""
+ started = clock()
+ while clock() - started < timeout_s:
+ try:
+ if pattern.search(log_path.read_text(encoding="utf-8", errors="replace")):
+ return clock() - started
+ except OSError:
+ pass
+ if not alive():
+ return None
+ sleep(0.05)
+ return None
+
+
+def cmd_cold_start(options: argparse.Namespace) -> int:
+ spec = PLATFORMS[options.platform]
+ worktree = options.worktree.resolve()
+ staged = options.archive or staged_dir(worktree, spec, options.config)
+ exe = staged / spec.launcher
+ if not exe.is_file():
+ return common.exit_with(common.UnrealScriptError(f"no packaged game at {exe}"))
+ out = proof_dir(worktree, "22.3")
+ log_path = out / f"cold-start-{common.run_stamp()}.log"
+ log_path.parent.mkdir(parents=True, exist_ok=True)
+ command = [
+ str(exe),
+ "-windowed",
+ "-ResX=1280",
+ "-ResY=720",
+ "-WinX=-32000",
+ "-WinY=-32000",
+ "-VerseSmoke=boot",
+ "-unattended",
+ "-log",
+ f"-abslog={log_path}",
+ ]
+ token = secrets.token_hex(16)
+ bridge = FakeBridgeRun(
+ out / "bridge", token=token, ready_timeout_s=options.timeout + READY_GRACE_S
+ )
+ try:
+ with with_lock.MachineLock(f"cold start ({worktree.name})", command), bridge:
+ process = subprocess.Popen(command, cwd=str(staged), env=bridge.env())
+ try:
+ seconds = wait_for_marker(
+ log_path,
+ FIRST_FRAME,
+ timeout_s=options.timeout,
+ alive=lambda: process.poll() is None,
+ )
+ if seconds is not None and process.poll() is None:
+ time.sleep(READY_GRACE_S) # let lifecycle.ready reach the bridge
+ finally:
+ if process.poll() is None:
+ process.terminate()
+ try:
+ process.wait(timeout=15)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait()
+ except common.UnrealScriptError as error:
+ return common.exit_with(error)
+ report = size_report(staged, load_chunks(), platform=spec.ue)
+ problems = bridge_problems(bridge.report, require_ready=True)
+ if seconds is None:
+ problems.append("no first-frame marker in the game log")
+ elif seconds > COLD_START_BUDGET_S:
+ problems.append(f"first frame after {seconds:.1f} s (budget {COLD_START_BUDGET_S} s)")
+ if not report["pso_cache_shipped"]:
+ problems.append("no shipped PSO cache in the build (A22.2 measures with it)")
+ result = {
+ "schema": "verse.cold-start/1",
+ "platform": spec.ue,
+ "config": options.config,
+ "seconds_to_first_frame": None if seconds is None else round(seconds, 3),
+ "budget_s": COLD_START_BUDGET_S,
+ "pass": not problems,
+ "problems": problems,
+ "pso_cache_shipped": report["pso_cache_shipped"],
+ "bridge": bridge.report,
+ "log": str(log_path),
+ }
+ path = write_json(out / f"cold-start-{spec.key}.json", result)
+ common.log(f"cold start: {result['seconds_to_first_frame']} s ({path}) {problems}")
+ return 0 if result["pass"] else 1
+
+
+# --------------------------------------------------------------------------- #
+# 22.7 Linux smoke in a container
+# --------------------------------------------------------------------------- #
+def docker_smoke_command(
+ staged: Path,
+ out: Path,
+ *,
+ seconds: int,
+ gpu: bool,
+ image: str = SMOKE_IMAGE,
+ name: str | None = None,
+) -> list[str]:
+ command = [
+ "docker",
+ "run",
+ "--rm",
+ "--name",
+ name or f"verse-smoke-{secrets.token_hex(4)}",
+ "--network",
+ "none",
+ "-v",
+ f"{staged}:/verse:ro",
+ "-v",
+ f"{LINUX_SMOKE_DIR}:/smoke:ro",
+ # The fake bridge runs inside the container (loopback only).
+ "-v",
+ f"{common.REPO_ROOT / 'scripts'}:/repo/scripts:ro",
+ "-v",
+ f"{BRIDGE_DATA_DIR}:/repo/unreal/Verse/Tests/Data/bridge:ro",
+ "-v",
+ f"{out}:/out",
+ ]
+ if gpu:
+ command += ["--gpus", "all", "-e", "NVIDIA_DRIVER_CAPABILITIES=all"]
+ command += [image, "bash", "/smoke/linux_smoke.sh", str(seconds), "gpu" if gpu else "nogpu"]
+ return command
+
+
+def docker_gpu_available(run: Callable[..., common.Completed] = common.run) -> bool:
+ result = run(["docker", "info", "--format", "{{json .Runtimes}}"], capture=True)
+ return result.returncode == 0 and "nvidia" in result.stdout
+
+
+def evaluate_linux_smoke(out: Path) -> dict[str, Any]:
+ """Read the container's ``result.json`` and the logs it wrote."""
+ from scripts.unreal import test as automation
+
+ try:
+ result = json.loads((out / "result.json").read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return {"pass": False, "problems": ["the container wrote no result.json"]}
+ problems = list(result.get("problems") or [])
+ for log_name in ("nullrhi.log", "vulkan.log"):
+ problems += [f"{log_name}: {line}" for line in automation.scan_log(out / log_name)]
+ runs = [("server", False)] + ([("vulkan", True)] if result.get("vulkan") == "ok" else [])
+ for run, require_ready in runs:
+ try:
+ report = json.loads((out / f"bridge-{run}-report.json").read_text(encoding="utf-8"))
+ except (OSError, ValueError): # no report: the game never connected
+ report = None
+ problems += [
+ f"{run} run: {p}" for p in bridge_problems(report, require_ready=require_ready)
+ ]
+ result["problems"] = problems
+ result["pass"] = bool(result.get("server_ok")) and not problems
+ return result
+
+
+def cmd_linux_smoke(options: argparse.Namespace) -> int:
+ worktree = options.worktree.resolve()
+ staged = options.archive or staged_dir(worktree, PLATFORMS["linux"], options.config)
+ if not (staged / "Verse.sh").is_file():
+ return common.exit_with(common.UnrealScriptError(f"no packaged Linux game at {staged}"))
+ out = proof_dir(worktree, "22.7") / common.run_stamp()
+ out.mkdir(parents=True, exist_ok=True)
+ if not FAKE_BRIDGE.is_file():
+ return common.exit_with(
+ common.UnrealScriptError(f"{FAKE_BRIDGE} is missing; the fake bridge lands with G0.11")
+ )
+ # The server run only has to finish the handshake; the Vulkan run must
+ # also report lifecycle.ready.
+ write_json(
+ out / "bridge-server.json",
+ bridge_scenario(ready_timeout_s=30, ready_optional=True),
+ )
+ write_json(out / "bridge-vulkan.json", bridge_scenario(ready_timeout_s=120))
+ build = [
+ "docker",
+ "build",
+ "-t",
+ SMOKE_IMAGE,
+ "-f",
+ str(LINUX_SMOKE_DIR / "smoke.Dockerfile"),
+ str(LINUX_SMOKE_DIR),
+ ]
+ if common.run(build).returncode != 0:
+ return common.exit_with(common.UnrealScriptError("docker build of the smoke image failed"))
+ command = docker_smoke_command(staged, out, seconds=options.seconds, gpu=docker_gpu_available())
+ code = with_lock.run_locked(command, label="linux smoke", cwd=worktree)
+ result = evaluate_linux_smoke(out)
+ result["exit_code"] = code
+ write_json(out / "summary.json", result)
+ common.log("linux smoke: PASS" if result["pass"] else f"linux smoke: FAIL {result['problems']}")
+ return 0 if result["pass"] and code == 0 else 1
+
+
+# --------------------------------------------------------------------------- #
+# 22.9 Disk hygiene
+# --------------------------------------------------------------------------- #
+def folder_bytes(folder: Path) -> int:
+ total = 0
+ for path in folder.rglob("*"):
+ try:
+ if path.is_file() and not path.is_symlink():
+ total += path.stat().st_size
+ except OSError:
+ continue
+ return total
+
+
+def newest_mtime(folder: Path) -> float:
+ """Newest file write below ``folder`` (folders themselves do not count)."""
+ newest = 0.0
+ for path in folder.rglob("*"):
+ try:
+ if path.is_file():
+ newest = max(newest, path.stat().st_mtime)
+ except OSError:
+ continue
+ return newest
+
+
+@dataclass
+class HygienePlan:
+ ddc_bytes: int = 0
+ ddc_cap_bytes: int = 0
+ ddc_prune: list[Path] = field(default_factory=list)
+ intermediate_prune: list[Path] = field(default_factory=list)
+ free_gb: float = 0.0
+ alert: bool = False
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "ddc_bytes": self.ddc_bytes,
+ "ddc_cap_bytes": self.ddc_cap_bytes,
+ "ddc_prune_files": len(self.ddc_prune),
+ "intermediate_prune": [str(p) for p in self.intermediate_prune],
+ "free_gb": round(self.free_gb, 1),
+ "alert": self.alert,
+ }
+
+
+def plan_ddc_prune(ddc_dir: Path, cap_bytes: int) -> tuple[int, list[Path]]:
+ """Oldest-first files of a file-system DDC to delete until it fits ``cap_bytes``."""
+ if not ddc_dir.is_dir():
+ return 0, []
+ files = []
+ for path in ddc_dir.rglob("*"):
+ try:
+ if path.is_file() and not path.is_symlink():
+ stat = path.stat()
+ files.append((max(stat.st_atime, stat.st_mtime), stat.st_size, path))
+ except OSError:
+ continue
+ total = sum(size for _, size, _ in files)
+ prune: list[Path] = []
+ excess = total - cap_bytes
+ for _, size, path in sorted(files):
+ if excess <= 0:
+ break
+ prune.append(path)
+ excess -= size
+ return total, prune
+
+
+def plan_intermediate_prune(worktrees_root: Path, *, max_age_days: float, now: float) -> list[Path]:
+ """``unreal/Verse/Intermediate`` folders of worktrees untouched for ``max_age_days``."""
+ found: list[Path] = []
+ if not worktrees_root.is_dir():
+ return found
+ for worktree in sorted(p for p in worktrees_root.iterdir() if p.is_dir()):
+ for intermediate in (worktree / "unreal" / "Verse" / "Intermediate",):
+ if intermediate.is_dir() and not intermediate.is_symlink():
+ if now - newest_mtime(intermediate) > max_age_days * 86400:
+ found.append(intermediate)
+ return found
+
+
+def plan_hygiene(
+ ddc: Mapping[str, Any],
+ *,
+ worktrees_root: Path,
+ now: float | None = None,
+ free_gb: Callable[[Path], float] = common.free_gb,
+) -> HygienePlan:
+ current = time.time() if now is None else now
+ cap = int(ddc["cap_gb"]) * GB
+ total, prune = plan_ddc_prune(Path(ddc["local_path"]), cap)
+ zen = Path(ddc.get("zen_data_path", ""))
+ if ddc.get("zen_data_path") and zen.is_dir():
+ total += folder_bytes(zen)
+ free = free_gb(worktrees_root)
+ return HygienePlan(
+ ddc_bytes=total,
+ ddc_cap_bytes=cap,
+ ddc_prune=prune,
+ intermediate_prune=plan_intermediate_prune(
+ worktrees_root, max_age_days=float(ddc["intermediate_max_age_days"]), now=current
+ ),
+ free_gb=free,
+ alert=free < float(ddc["alert_free_gb"]),
+ )
+
+
+def apply_hygiene(
+ plan: HygienePlan,
+ *,
+ remove_file: Callable[[Path], None] = Path.unlink,
+ remove_tree: Callable[[Path], None] = shutil.rmtree,
+) -> int:
+ removed = 0
+ for path in plan.ddc_prune:
+ try:
+ remove_file(path)
+ removed += 1
+ except OSError:
+ continue
+ for folder in plan.intermediate_prune:
+ try:
+ remove_tree(folder)
+ removed += 1
+ except OSError as error: # a locked file: the rest still gets pruned
+ common.log(f"could not prune {folder}: {error}")
+ return removed
+
+
+def zen_over_cap(plan: HygienePlan) -> bool:
+ """The cache is over its cap and no file-system prune can fix it (the Zen store)."""
+ return plan.ddc_bytes > plan.ddc_cap_bytes and not plan.ddc_prune
+
+
+def cmd_hygiene(options: argparse.Namespace) -> int:
+ ddc = load_ddc()
+ plan = plan_hygiene(ddc, worktrees_root=options.worktrees)
+ if options.apply:
+ # The lock guarantees no build, cook or editor is writing while we
+ # prune. The queue can take hours, so plan again once it is granted:
+ # a worktree that became active in the meantime keeps its folder.
+ with with_lock.MachineLock("disk hygiene", "package.py hygiene --apply"):
+ plan = plan_hygiene(ddc, worktrees_root=options.worktrees)
+ summary = plan.as_dict()
+ summary["removed"] = apply_hygiene(plan)
+ else:
+ summary = plan.as_dict()
+ print(json.dumps(summary, indent=2))
+ if zen_over_cap(plan):
+ common.log(
+ f"FAIL the DDC holds {plan.ddc_bytes / GB:.1f} GB, over its {ddc['cap_gb']} GB cap, "
+ "in the Zen store, which this command cannot prune: run the Zen server's gc"
+ )
+ return 4
+ if plan.alert:
+ common.log(
+ f"ALERT only {plan.free_gb:.0f} GB free (want {ddc['alert_free_gb']}); "
+ "remove merged worktrees (worktree.py remove)"
+ )
+ return 3
+ return 0
+
+
+# --------------------------------------------------------------------------- #
+def parser() -> argparse.ArgumentParser:
+ top = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ sub = top.add_subparsers(dest="command", required=True)
+
+ def with_worktree(p: argparse.ArgumentParser) -> argparse.ArgumentParser:
+ p.add_argument("--worktree", type=Path, default=common.REPO_ROOT)
+ return p
+
+ p = with_worktree(sub.add_parser("verify", help="toolchain and packaging prerequisites"))
+ p.add_argument("--target", choices=["all", "win64", "linux"], default="all")
+ p.set_defaults(func=cmd_verify)
+
+ for name, func in (
+ ("build", cmd_build),
+ ("report", cmd_report),
+ ("cold-start", cmd_cold_start),
+ ):
+ p = with_worktree(sub.add_parser(name))
+ p.add_argument("--platform", choices=sorted(PLATFORMS), required=True)
+ p.add_argument("--config", choices=CONFIGS, default="Shipping")
+ if name == "build":
+ p.add_argument("--skip-editor", action="store_true")
+ p.add_argument("--require-chunks", action="store_true")
+ else:
+ p.add_argument("--archive", type=Path)
+ if name == "cold-start":
+ p.add_argument("--timeout", type=float, default=60.0)
+ p.set_defaults(func=func)
+
+ sub.add_parser("chunks", help="config block of the deck chunks").set_defaults(func=cmd_chunks)
+
+ p = with_worktree(sub.add_parser("pso", help="expand the shipped PSO cache"))
+ p.add_argument("--platform", choices=sorted(PLATFORMS), required=True)
+ p.add_argument("--collected", type=Path, required=True)
+ p.set_defaults(func=cmd_pso)
+
+ p = sub.add_parser("full", help="full payload tar of a staged build")
+ p.add_argument("--stage", type=Path, required=True)
+ p.add_argument("--version", required=True)
+ p.add_argument("--platform", choices=["Win64", "Linux"], required=True)
+ p.add_argument("--out", type=Path, required=True)
+ p.set_defaults(func=cmd_full)
+
+ p = sub.add_parser("delta", help="delta tar from a previous payload to a staged build")
+ p.add_argument("--old", type=Path, required=True)
+ p.add_argument("--stage", type=Path, required=True)
+ p.add_argument("--version", required=True)
+ p.add_argument("--out", type=Path, required=True)
+ p.set_defaults(func=cmd_delta)
+
+ p = sub.add_parser("manifest", help="per-platform release manifest the release key signs")
+ p.add_argument("--full", type=Path, required=True)
+ p.add_argument("--delta", type=Path, action="append")
+ p.add_argument("--tag", required=True)
+ p.add_argument("--out", type=Path)
+ p.set_defaults(func=cmd_manifest)
+
+ p = sub.add_parser("apply", help="install a full payload or apply a delta")
+ p.add_argument("--root", type=Path, required=True)
+ group = p.add_mutually_exclusive_group(required=True)
+ group.add_argument("--full", type=Path)
+ group.add_argument("--delta", type=Path)
+ p.add_argument("--log", type=Path)
+ p.set_defaults(func=cmd_apply)
+
+ p = with_worktree(sub.add_parser("linux-smoke", help="container smoke of the Linux build"))
+ p.add_argument("--config", choices=CONFIGS, default="Development")
+ p.add_argument("--archive", type=Path)
+ p.add_argument("--seconds", type=int, default=60)
+ p.set_defaults(func=cmd_linux_smoke)
+
+ p = sub.add_parser("hygiene", help="DDC cap, Intermediate pruning, free-space alert")
+ p.add_argument("--apply", action="store_true")
+ p.add_argument("--worktrees", type=Path, default=Path("C:/demo"))
+ p.set_defaults(func=cmd_hygiene)
+ return top
+
+
+def main(argv: Sequence[str] | None = None) -> int:
+ options = parser().parse_args(argv)
+ try:
+ return int(options.func(options))
+ except (common.UnrealScriptError, verse_layout.VerseInstallError) as error:
+ return common.exit_with(error)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/unit/installer/test_verse_lfs.py b/tests/unit/installer/test_verse_lfs.py
new file mode 100644
index 0000000000..6e879cd237
--- /dev/null
+++ b/tests/unit/installer/test_verse_lfs.py
@@ -0,0 +1,213 @@
+"""Installs and updates never download the Unreal LFS objects (WP22.6, A22.4)."""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import shutil
+import subprocess
+import tarfile
+from pathlib import Path
+
+import pytest
+
+REPO = Path(__file__).resolve().parents[3]
+POINTER = (
+ "version https://git-lfs.github.com/spec/v1\noid sha256:" + "ab" * 32 + "\nsize 123456789\n"
+)
+
+
+def test_lfsconfig_excludes_the_unreal_tree() -> None:
+ text = (REPO / ".lfsconfig").read_text(encoding="utf-8")
+ assert "fetchexclude = unreal/**" in text
+
+
+def test_the_release_source_archive_carries_no_unreal_path(tmp_path: Path) -> None:
+ attr = subprocess.run(
+ [
+ "git",
+ "-C",
+ str(REPO),
+ "check-attr",
+ "export-ignore",
+ "--",
+ "unreal/Verse/Verse.uproject",
+ ],
+ capture_output=True,
+ text=True,
+ check=True,
+ )
+ assert attr.stdout.strip().endswith("export-ignore: set")
+ archive = tmp_path / "src.tar"
+ subprocess.run(
+ [
+ "git",
+ "-C",
+ str(REPO),
+ "archive",
+ "--format=tar",
+ "-o",
+ str(archive),
+ "HEAD",
+ "--",
+ "unreal",
+ "install",
+ ],
+ check=True,
+ )
+ with tarfile.open(archive) as handle:
+ names = handle.getnames()
+ assert names and not [n for n in names if n.startswith("unreal")]
+
+
+def test_install_scripts_set_git_lfs_skip_smudge_before_any_clone() -> None:
+ ps1 = (REPO / "install/install.ps1").read_text(encoding="utf-8")
+ sh = (REPO / "install/install.sh").read_text(encoding="utf-8")
+ first_ps1_git = min(ps1.index("& git @GitNetOpts"), ps1.index("& git -C"))
+ assert ps1.index("$env:GIT_LFS_SKIP_SMUDGE = '1'") < first_ps1_git
+ assert sh.index("export GIT_LFS_SKIP_SMUDGE") < sh.index("pretty_git git $GIT_NET_OPTS")
+
+
+def test_install_scripts_drop_git_lfs_skip_smudge_before_the_hand_off() -> None:
+ ps1 = (REPO / "install/install.ps1").read_text(encoding="utf-8")
+ sh = (REPO / "install/install.sh").read_text(encoding="utf-8")
+ ps1_drop = ps1.index("Remove-Item Env:GIT_LFS_SKIP_SMUDGE")
+ sh_drop = sh.index("unset GIT_LFS_SKIP_SMUDGE")
+ # After the last git call of the shell stage, before installer.py runs.
+ assert ps1.rindex("& git ") < ps1_drop < ps1.index("& $VenvPython $InstallerPy")
+ assert (
+ sh.rindex('git -C "$INSTALL_DIR"')
+ < sh_drop
+ < sh.index('exec "$VENV_PYTHON" "$INSTALLER_PY"')
+ )
+
+
+def test_app_launch_env_has_no_git_lfs_skip_smudge() -> None:
+ import importlib.util
+
+ spec = importlib.util.spec_from_file_location(
+ "_installer_under_test", REPO / "install/installer.py"
+ )
+ assert spec and spec.loader
+ installer = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(installer)
+ env = installer.app_launch_env({"GIT_LFS_SKIP_SMUDGE": "1", "PATH": "x"})
+ assert "GIT_LFS_SKIP_SMUDGE" not in env
+ assert env["PATH"] == "x"
+
+
+def test_follow_main_git_calls_skip_lfs_smudge(monkeypatch, tmp_path: Path) -> None:
+ from dodaios.core import main_follow
+
+ seen: list[dict] = []
+
+ def fake_run(args, **kwargs):
+ seen.append(kwargs["env"])
+ return subprocess.CompletedProcess(args, 0, "", "")
+
+ monkeypatch.setattr(main_follow.subprocess, "run", fake_run)
+ main_follow._git(["fetch", "--quiet", "origin", "main"], tmp_path)
+ main_follow._git_write(["merge", "--ff-only", "origin/main"], tmp_path)
+ assert [env.get("GIT_LFS_SKIP_SMUDGE") for env in seen] == ["1", "1"]
+
+
+def test_update_route_git_calls_skip_lfs_smudge(monkeypatch, tmp_path: Path) -> None:
+ from dodaios.ui.web import update_routes
+
+ seen: list[dict | None] = []
+
+ async def fake_run(cmd, *, cwd, timeout_s, on_stderr_line=None, env=None):
+ seen.append(env)
+ return 0, "", ""
+
+ monkeypatch.setattr(update_routes, "_run", fake_run)
+ asyncio.run(update_routes._git(["fetch", "origin"], cwd=tmp_path))
+ assert seen and seen[0]["GIT_LFS_SKIP_SMUDGE"] == "1"
+
+
[email protected](shutil.which("git-lfs") is None, reason="git-lfs is not installed")
+def test_a_clone_with_the_installer_setting_downloads_no_lfs_object(tmp_path: Path) -> None:
+ """A repo whose ``unreal/**`` holds an LFS pointer to an object no server has.
+
+ With ``GIT_LFS_SKIP_SMUDGE=1`` the clone succeeds and keeps the pointer:
+ zero bytes of the object were asked for. Without it, smudging tries to
+ fetch the object and the checkout fails.
+ """
+ origin = tmp_path / "origin"
+ (origin / "unreal/Verse/Content").mkdir(parents=True)
+ env = dict(
+ os.environ,
+ GIT_CONFIG_NOSYSTEM="1",
+ HOME=str(tmp_path),
+ GIT_AUTHOR_NAME="t",
+ GIT_AUTHOR_EMAIL="[email protected]",
+ GIT_COMMITTER_NAME="t",
+ GIT_COMMITTER_EMAIL="[email protected]",
+ )
+ lfs = [
+ "-c",
+ "filter.lfs.smudge=git-lfs smudge -- %f",
+ "-c",
+ "filter.lfs.process=git-lfs filter-process",
+ "-c",
+ "filter.lfs.required=true",
+ "-c",
+ "core.hooksPath=" + str(tmp_path / "nohooks"),
+ ]
+
+ def git(*args: str, cwd: Path, extra: dict | None = None, check: bool = True):
+ return subprocess.run(
+ ["git", *lfs, *args],
+ cwd=cwd,
+ env={**env, **(extra or {})},
+ capture_output=True,
+ text=True,
+ check=check,
+ )
+
+ git("init", "-q", "-b", "main", cwd=origin)
+ (origin / ".gitattributes").write_text(
+ "*.uasset filter=lfs diff=lfs merge=lfs -text\n", encoding="utf-8"
+ )
+ (origin / "readme.txt").write_text("app\n", encoding="utf-8")
+ git("add", ".gitattributes", "readme.txt", cwd=origin)
+ # Store the pointer itself as the blob (no clean filter), as LFS would.
+ blob = subprocess.run(
+ ["git", "hash-object", "-w", "--stdin"],
+ cwd=origin,
+ env=env,
+ input=POINTER,
+ capture_output=True,
+ text=True,
+ check=True,
+ ).stdout.strip()
+ git(
+ "update-index",
+ "--add",
+ "--cacheinfo",
+ f"100644,{blob},unreal/Verse/Content/Big.uasset",
+ cwd=origin,
+ )
+ git("commit", "-q", "-m", "init", cwd=origin)
+
+ skipped = tmp_path / "skipped"
+ done = git(
+ "clone",
+ "-q",
+ "--depth",
+ "1",
+ origin.as_uri(),
+ str(skipped),
+ cwd=tmp_path,
+ extra={"GIT_LFS_SKIP_SMUDGE": "1"},
+ check=False,
+ )
+ assert done.returncode == 0, done.stderr
+ content = (skipped / "unreal/Verse/Content/Big.uasset").read_text(encoding="utf-8")
+ assert content.replace("\r\n", "\n") == POINTER
+
+ smudged = tmp_path / "smudged"
+ done = git(
+ "clone", "-q", "--depth", "1", origin.as_uri(), str(smudged), cwd=tmp_path, check=False
+ )
+ assert done.returncode != 0 # it tried to download the object
diff --git a/tests/unit/installer/test_verse_on_demand.py b/tests/unit/installer/test_verse_on_demand.py
new file mode 100644
index 0000000000..0a0e3f28b2
--- /dev/null
+++ b/tests/unit/installer/test_verse_on_demand.py
@@ -0,0 +1,584 @@
+"""The Verse as an optional on-demand download (WP22.5, WP22.6, acceptance A22.7).
+
+Runs the real installer against a local HTTP server that speaks like a GitHub
+release (listing, assets, byte ranges) and can drop a connection mid-file:
+
+- a fresh install reads ``not_installed`` and no installer carries the Verse;
+- the download from the card installs and the installed Verse launches;
+- an interrupted download resumes with a byte range instead of starting over;
+- a tampered package or manifest is rejected and nothing is installed;
+- uninstall frees the folder and returns to ``not_installed``;
+- only an installed Verse updates, by delta when one fits.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import json
+import re
+import subprocess
+import sys
+import threading
+from collections.abc import Iterator
+from dataclasses import dataclass, field
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+
+import pytest
+from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
+from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
+
+from dodaios.core import installer_update
+from dodaios.verse_host.install import VerseInstaller, VerseInstallError, layout
+from dodaios.verse_host.install import manifest as vm
+from dodaios.verse_host.install.download import HttpFetcher
+from scripts.unreal import package
+
+REPO = Path(__file__).resolve().parents[3]
+LAUNCH_SCRIPT = b"print('verse up')\n"
+
+
+# --------------------------------------------------------------- signing
+@dataclass
+class Signer:
+ key: Ed25519PrivateKey = field(default_factory=Ed25519PrivateKey.generate)
+
+ @property
+ def public_keys(self) -> list[str]:
+ der = self.key.public_key().public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo)
+ return [base64.b64encode(der).decode("ascii")]
+
+ def sign(self, data: bytes) -> bytes:
+ return base64.b64encode(self.key.sign(data))
+
+
+# ------------------------------------------------------------ the server
+@dataclass
+class Release:
+ tag: str
+ assets: dict[str, bytes]
+
+
+@dataclass
+class FakeGitHub:
+ releases: list[Release] = field(default_factory=list)
+ #: asset name -> bytes after which the next GET of it drops the connection
+ drop_once: dict[str, int] = field(default_factory=dict)
+ #: asset name -> replacement bytes served instead of the published ones
+ tamper: dict[str, bytes] = field(default_factory=dict)
+ requests: list[tuple[str, str | None]] = field(default_factory=list)
+ base: str = ""
+
+ def listing(self) -> bytes:
+ rows = []
+ for release in self.releases:
+ rows.append(
+ {
+ "tag_name": release.tag,
+ "draft": False,
+ "prerelease": False,
+ "assets": [
+ {
+ "name": name,
+ "size": len(data),
+ "browser_download_url": f"{self.base}/dl/{release.tag}/{name}",
+ }
+ for name, data in release.assets.items()
+ ],
+ }
+ )
+ return json.dumps(rows).encode()
+
+ def asset(self, tag: str, name: str) -> bytes | None:
+ for release in self.releases:
+ if release.tag == tag and name in release.assets:
+ return self.tamper.get(name, release.assets[name])
+ return None
+
+ def downloaded(self, name: str) -> list[str | None]:
+ return [rng for path, rng in self.requests if path.endswith("/" + name)]
+
+
+def _handler(hub: FakeGitHub) -> type[BaseHTTPRequestHandler]:
+ class Handler(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def log_message(self, *_args: object) -> None:
+ return
+
+ def do_GET(self) -> None: # noqa: N802 - http.server naming
+ rng = self.headers.get("Range")
+ hub.requests.append((self.path, rng))
+ if self.path == "/releases":
+ return self._send(200, hub.listing())
+ match = re.fullmatch(r"/dl/([^/]+)/([^/]+)", self.path)
+ data = hub.asset(*match.groups()) if match else None
+ if data is None:
+ return self._send(404, b"not found")
+ name = match.group(2)
+ start = 0
+ if rng:
+ start = int(re.fullmatch(r"bytes=(\d+)-", rng).group(1))
+ if start >= len(data):
+ return self._send(416, b"")
+ body = data[start:]
+ self.send_response(206 if rng else 200)
+ self.send_header("Content-Length", str(len(body)))
+ if rng:
+ self.send_header("Content-Range", f"bytes {start}-{len(data) - 1}/{len(data)}")
+ self.end_headers()
+ cut = hub.drop_once.pop(name, None)
+ if cut is not None:
+ self.wfile.write(body[:cut])
+ self.wfile.flush()
+ # A clean close (FIN) with the body short of Content-Length:
+ # the client sees a connection that dropped mid-file.
+ self.close_connection = True
+ return
+ self.wfile.write(body)
+
+ def _send(self, code: int, body: bytes) -> None:
+ self.send_response(code)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ return Handler
+
+
+def hub() -> Iterator[FakeGitHub]:
+ state = FakeGitHub()
+ server = ThreadingHTTPServer(("127.0.0.1", 0), _handler(state))
+ state.base = f"http://127.0.0.1:{server.server_address[1]}"
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ yield state
+ finally:
+ server.shutdown()
+ server.server_close()
+
+
+# ------------------------------------------------------------ the release
+def _stage(folder: Path, version: str, *, hangar: bytes) -> Path:
+ files = {
+ "launch.py": LAUNCH_SCRIPT,
+ "Verse.exe": b"launcher",
+ "Verse/Content/Paks/pakchunk0-Windows.ucas": b"core" * 4000,
+ "Verse/Content/Paks/pakchunk4-Windows.ucas": hangar,
+ "Verse/version.txt": version.encode(),
+ }
+ for rel, data in files.items():
+ path = folder / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(data)
+ return folder
+
+
+def _publish(
+ tmp: Path,
+ signer: Signer,
+ version: str,
+ *,
+ hangar: bytes,
+ previous: Path | None = None,
+) -> tuple[Release, Path]:
+ out = tmp / f"release-{version}"
+ out.mkdir()
+ stage = _stage(tmp / f"stage-{version}", version, hangar=hangar)
+ full = out / vm.full_asset_name("Win64", version)
+ package.make_full(stage, version=version, platform="Win64", out=full, entry="launch.py")
+ deltas = []
+ if previous is not None:
+ old_tree = package.read_payload_tree(previous)
+ delta = out / vm.delta_asset_name("Win64", old_tree["version"], version)
+ package.make_delta(old_tree, stage, version=version, out=delta, entry="launch.py")
+ deltas.append(delta)
+ manifest = package.make_release_manifest(full, deltas, tag=f"v{version}")
+ assets = {p.name: p.read_bytes() for p in (full, *deltas)}
+ assets[vm.manifest_asset_name("Win64")] = manifest
+ assets[vm.signature_asset_name("Win64")] = signer.sign(manifest)
+ return Release(tag=f"v{version}", assets=assets), full
+
+
+def signer() -> Signer:
+ return Signer()
+
+
+def _installer(hub: FakeGitHub, signer: Signer, root: Path, **kwargs) -> VerseInstaller:
+ options = {
+ "root": root,
+ "fetcher": HttpFetcher(allow_loopback_http=True),
+ "listing_url": f"{hub.base}/releases",
+ "app_version": "9.9.9",
+ "platform": "Win64",
+ "public_keys": signer.public_keys,
+ "gpu_supported": True,
+ }
+ options.update(kwargs)
+ return VerseInstaller(**options)
+
+
+def _run(coro):
+ return asyncio.run(coro)
+
+
+# ------------------------------------------------------------------ A22.7
+def test_a_fresh_install_reads_not_installed(tmp_path: Path) -> None:
+ installer = VerseInstaller(root=tmp_path / "verse", platform="Win64", app_version="4.2.0")
+ assert installer.install_state() == {"status": "not_installed", "version": None}
+ assert not (tmp_path / "verse").exists() # asking never creates anything
+
+
+def test_no_installer_or_app_update_carries_the_verse() -> None:
+ # The update size cap is the one from before the Verse (A22.7: installer
+ # size unchanged); the Verse never rides in an installer download.
+ assert installer_update.MAX_INSTALLER_BYTES == 1_500_000_000
+ source = (REPO / "dodaios/core/installer_update.py").read_text(encoding="utf-8")
+ assert "verse" not in source.lower()
+ word = re.compile(r"\bverse\b|unreal", re.IGNORECASE)
+ for rel in (
+ "dodaios.spec",
+ "packaging/windows/Dodaios.iss",
+ "packaging/windows/build.ps1",
+ "packaging/linux/build.sh",
+ ):
+ text = (REPO / rel).read_text(encoding="utf-8", errors="replace")
+ assert not word.search(text), f"{rel} mentions the Verse; installers must not carry it"
+ assert not list((REPO / "packaging").rglob("stage_verse*"))
+
+
+def test_a_machine_without_gpu_is_never_offered_the_download(
+ hub: FakeGitHub, signer: Signer, tmp_path: Path
+) -> None:
+ release, _ = _publish(tmp_path, signer, "4.2.0", hangar=b"h1" * 5000)
+ hub.releases = [release]
+ installer = _installer(hub, signer, tmp_path / "verse", gpu_supported=lambda: False)
+ assert installer.install_state()["status"] == "unsupported"
+ with pytest.raises(VerseInstallError, match="cannot run the Verse"):
+ _run(installer.offer())
+ assert hub.requests == []
+ mac = _installer(hub, signer, tmp_path / "verse", platform=None)
+ assert mac.install_state()["status"] == "unsupported"
+
+
+def test_the_card_shows_the_size_before_the_download(
+ hub: FakeGitHub, signer: Signer, tmp_path: Path
+) -> None:
+ release, full = _publish(tmp_path, signer, "4.2.0", hangar=b"h1" * 5000)
+ hub.releases = [release]
+ offer = _run(_installer(hub, signer, tmp_path / "verse").offer())
+ assert offer["version"] == "4.2.0"
+ assert offer["download_bytes"] == full.stat().st_size
+ assert offer["install_bytes"] > 0
+ # Only the listing, the manifest and its signature: no package bytes yet.
+ assert all("/dl/" not in path or "manifest" in path for path, _ in hub.requests)
+
+
+def test_download_installs_and_the_installed_verse_launches(
+ hub: FakeGitHub, signer: Signer, tmp_path: Path
+) -> None:
+ release, full = _publish(tmp_path, signer, "4.2.0", hangar=b"h1" * 5000)
+ hub.releases = [release]
+ root = tmp_path / "verse"
+ installer = _installer(hub, signer, root)
+ seen: list[dict] = []
+
+ async def go() -> dict:
+ installer.start_install()
+ assert installer.install_state()["status"] == "installing"
+ while installer.busy():
+ seen.append(installer.progress())
+ await asyncio.sleep(0.01)
+ return await installer.wait()
+
+ result = _run(go())
+ assert result["status"] == "installed" and result["version"] == "4.2.0"
+ done = installer.progress()
+ assert done["phase"] == "done" and done["percent"] == 100.0
+ assert done["total_bytes"] == full.stat().st_size
+ state = installer.install_state()
+ assert state["status"] == "installed" and state["version"] == "4.2.0"
+ assert not list((root / "downloads").iterdir()) # the package is not kept twice
+ launched = subprocess.run(
+ [sys.executable, *installer.launch_command()],
+ capture_output=True,
+ text=True,
+ timeout=30,
+ check=False,
+ )
+ assert launched.returncode == 0 and launched.stdout.strip() == "verse up"
+
+
+def test_an_interrupted_download_resumes_where_it_stopped(
+ hub: FakeGitHub, signer: Signer, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr("dodaios.verse_host.install.download.RESUME_BACKOFF_S", 0.0)
+ release, full = _publish(tmp_path, signer, "4.2.0", hangar=b"h1" * 5000)
+ hub.releases = [release]
+ size = full.stat().st_size
+ hub.drop_once[full.name] = size // 3
+ installer = _installer(hub, signer, tmp_path / "verse")
+ assert _run(installer.install())["version"] == "4.2.0"
+ ranges = hub.downloaded(full.name)
+ assert ranges[0] is None and ranges[1] == f"bytes={size // 3}-"
+ assert installer.install_state()["status"] == "installed"
+
+
+def test_a_download_stopped_by_an_app_restart_resumes_on_the_next_start(
+ hub: FakeGitHub, signer: Signer, tmp_path: Path
+) -> None:
+ release, full = _publish(tmp_path, signer, "4.2.0", hangar=b"h1" * 5000)
+ hub.releases = [release]
+ root = tmp_path / "verse"
+ half = full.stat().st_size // 2
+ (root / "downloads").mkdir(parents=True)
+ (root / "downloads" / f"{full.name}.part").write_bytes(full.read_bytes()[:half])
+ installer = _installer(hub, signer, root)
+ assert _run(installer.install())["status"] == "installed"
+ assert hub.downloaded(full.name) == [f"bytes={half}-"]
+
+
+def test_cancel_keeps_the_partial_download_for_the_next_start(
+ hub: FakeGitHub, signer: Signer, tmp_path: Path
+) -> None:
+ release, full = _publish(tmp_path, signer, "4.2.0", hangar=b"h1" * 5000)
+ hub.releases = [release]
+ root = tmp_path / "verse"
+ installer = _installer(hub, signer, root)
+ gate = asyncio.Event
+
+ async def go() -> None:
+ stalled = gate()
+ real = installer._fetcher.download_range
+
+ async def stall(url, dest, *, offset, max_bytes, on_chunk=None):
+ dest.write_bytes(full.read_bytes()[:1000])
+ stalled.set()
+ await asyncio.sleep(3600)
+ return await real(url, dest, offset=offset, max_bytes=max_bytes, on_chunk=on_chunk)
+
+ installer._fetcher.download_range = stall # type: ignore[method-assign]
+ installer.start_install()
+ await stalled.wait()
+ installer.cancel()
+ await installer.wait()
+
+ _run(go())
+ assert installer.progress()["phase"] == "cancelled"
+ assert (root / "downloads" / f"{full.name}.part").stat().st_size == 1000
+ assert installer.install_state()["status"] == "not_installed"
+ fresh = _installer(hub, signer, root)
+ assert _run(fresh.install())["status"] == "installed"
+ assert hub.downloaded(full.name) == ["bytes=1000-"]
+
+
+def test_cancel_while_unpacking_waits_for_the_install_to_finish(
+ hub: FakeGitHub, signer: Signer, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from dodaios.verse_host.install import payload
+
+ release, _ = _publish(tmp_path, signer, "4.2.0", hangar=b"h1" * 5000)
+ hub.releases = [release]
+ root = tmp_path / "verse"
+ installer = _installer(hub, signer, root)
+ entered = threading.Event()
+ release_worker = threading.Event()
+ real_install = payload.install_full
+ calls: list[int] = []
+
+ def slow_install(*args, **kwargs):
+ calls.append(1)
+ entered.set()
+ assert release_worker.wait(30)
+ return real_install(*args, **kwargs)
+
+ monkeypatch.setattr(payload, "install_full", slow_install)
+
+ async def go() -> dict | None:
+ installer.start_install()
+ assert await asyncio.to_thread(entered.wait, 30)
+ assert installer.progress()["phase"] == "installing"
+ # The card's cancel is refused while unpacking.
+ assert installer.cancel()["phase"] == "installing"
+ await asyncio.sleep(0.05)
+ assert installer.busy()
+ # Even a hard cancel of the task (app shutdown) waits for the worker.
+ installer._task.cancel()
+ await asyncio.sleep(0.05)
+ assert installer.busy()
+ with pytest.raises(VerseInstallError, match="cancel it first"):
+ installer.uninstall()
+ installer.start_install() # joins the running job, never a second unpack
+ release_worker.set()
+ return await installer.wait()
+
+ _run(go())
+ assert calls == [1]
+ assert not installer.busy()
+ state = installer.install_state()
+ assert state["status"] == "installed" and state["version"] == "4.2.0"
+ assert not list((root / "downloads").iterdir())
+ assert installer.uninstall()["status"] == "not_installed"
+ assert installer.install_state() == {"status": "not_installed", "version": None}
+
+
+def test_a_superseded_partial_download_is_removed(
+ hub: FakeGitHub, signer: Signer, tmp_path: Path
+) -> None:
+ old, old_full = _publish(tmp_path, signer, "4.2.0", hangar=b"h1" * 5000)
+ new, _ = _publish(tmp_path, signer, "4.2.1", hangar=b"h2" * 5000)
+ root = tmp_path / "verse"
+ downloads = root / "downloads"
+ downloads.mkdir(parents=True)
+ # 4.2.0 was interrupted half way (and an old finished package lies around).
+ (downloads / f"{old_full.name}.part").write_bytes(old_full.read_bytes()[:500])
+ (downloads / old_full.name).write_bytes(b"stale")
+ hub.releases = [new, old]
+ installer = _installer(hub, signer, root)
+ assert _run(installer.install())["version"] == "4.2.1"
+ assert not list(downloads.iterdir())
+
+
+def test_a_tampered_package_is_rejected_and_nothing_is_installed(
+ hub: FakeGitHub, signer: Signer, tmp_path: Path
+) -> None:
+ release, full = _publish(tmp_path, signer, "4.2.0", hangar=b"h1" * 5000)
+ hub.releases = [release]
+ data = bytearray(full.read_bytes())
+ data[len(data) // 2] ^= 0xFF # one flipped byte, same size
+ hub.tamper[full.name] = bytes(data)
+ root = tmp_path / "verse"
+ installer = _installer(hub, signer, root)
+
+ async def go() -> None:
+ installer.start_install()
+ await installer.wait()
+
+ _run(go())
+ progress = installer.progress()
+ assert progress["phase"] == "failed" and "NOT installed" in progress["error"]
+ assert installer.install_state()["status"] == "not_installed"
+ assert not (root / "versions").exists()
+ assert not list((root / "downloads").iterdir()) # the bad bytes are gone
+
+
+def test_a_tampered_or_foreign_manifest_is_rejected(
+ hub: FakeGitHub, signer: Signer, tmp_path: Path
+) -> None:
+ release, full = _publish(tmp_path, signer, "4.2.0", hangar=b"h1" * 5000)
+ hub.releases = [release]
+ name = vm.manifest_asset_name("Win64")
+ honest = release.assets[name]
+ # Someone swaps in their own package and edits its digest into the manifest.
+ hub.tamper[name] = honest.replace(json.loads(honest)["full"]["sha256"].encode(), b"0" * 64, 1)
+ installer = _installer(hub, signer, tmp_path / "verse")
+ with pytest.raises(VerseInstallError, match="not signed by the Dodaios release key"):
+ _run(installer.install())
+ # A manifest signed by any other key is refused the same way.
+ hub.tamper.clear()
+ other = Signer()
+ release.assets[vm.signature_asset_name("Win64")] = other.sign(honest)
+ with pytest.raises(VerseInstallError, match="not signed by the Dodaios release key"):
+ _run(installer.install())
+ assert hub.downloaded(full.name) == [] # no package byte before the signature holds
+ assert installer.install_state()["status"] == "not_installed"
+
+
+def test_a_signed_manifest_replayed_on_another_release_is_refused(
+ hub: FakeGitHub, signer: Signer, tmp_path: Path
+) -> None:
+ release, _ = _publish(tmp_path, signer, "4.2.0", hangar=b"h1" * 5000)
+ release.tag = "v4.3.0"
+ hub.releases = [release]
+ with pytest.raises(VerseInstallError, match="refusing a replay"):
+ _run(_installer(hub, signer, tmp_path / "verse").install())
+
+
+def test_uninstall_returns_to_not_installed(
+ hub: FakeGitHub, signer: Signer, tmp_path: Path
+) -> None:
+ release, _ = _publish(tmp_path, signer, "4.2.0", hangar=b"h1" * 5000)
+ hub.releases = [release]
+ root = tmp_path / "verse"
+ installer = _installer(hub, signer, root)
+ _run(installer.install())
+ assert installer.install_state()["status"] == "installed"
+ result = installer.uninstall()
+ assert result["status"] == "not_installed" and result["freed_bytes"] > 0
+ assert installer.install_state() == {"status": "not_installed", "version": None}
+ assert not root.exists()
+ with pytest.raises(VerseInstallError, match="not installed"):
+ installer.launch_command()
+
+
+def test_a_release_newer_than_the_app_is_skipped(
+ hub: FakeGitHub, signer: Signer, tmp_path: Path
+) -> None:
+ old, _ = _publish(tmp_path, signer, "4.2.0", hangar=b"h1" * 5000)
+ new, _ = _publish(tmp_path, signer, "4.3.0", hangar=b"h2" * 5000)
+ hub.releases = [new, old]
+ installer = _installer(hub, signer, tmp_path / "verse", app_version="4.2.5")
+ assert _run(installer.offer())["version"] == "4.2.0"
+
+
+def test_only_an_installed_verse_updates_and_it_takes_the_delta(
+ hub: FakeGitHub, signer: Signer, tmp_path: Path
+) -> None:
+ old, old_full = _publish(tmp_path, signer, "4.2.0", hangar=b"h1" * 5000)
+ hub.releases = [old]
+ root = tmp_path / "verse"
+ installer = _installer(hub, signer, root)
+ with pytest.raises(VerseInstallError, match="only an installed Verse updates"):
+ _run(installer.update())
+ _run(installer.install())
+ assert _run(installer.update()) == {"status": "current", "version": "4.2.0"}
+
+ new, new_full = _publish(tmp_path, signer, "4.3.0", hangar=b"h2" * 5000, previous=old_full)
+ hub.releases = [new, old]
+ result = _run(installer.update())
+ assert result["status"] == "updated" and result["kind"] == "delta"
+ assert result["version"] == "4.3.0" and result["previous"] == "4.2.0"
+ assert hub.downloaded(new_full.name) == [] # the full package was never fetched
+ state = installer.install_state()
+ assert state["status"] == "installed" and state["version"] == "4.3.0"
+
+
+def test_a_corrupted_delta_falls_back_to_the_full_package(
+ hub: FakeGitHub, signer: Signer, tmp_path: Path
+) -> None:
+ old, old_full = _publish(tmp_path, signer, "4.2.0", hangar=b"h1" * 5000)
+ hub.releases = [old]
+ root = tmp_path / "verse"
+ installer = _installer(hub, signer, root)
+ _run(installer.install())
+ new, new_full = _publish(tmp_path, signer, "4.3.0", hangar=b"h2" * 5000, previous=old_full)
+ hub.releases = [new, old]
+ delta_name = vm.delta_asset_name("Win64", "4.2.0", "4.3.0")
+ hub.tamper[delta_name] = b"x" * len(new.assets[delta_name])
+ result = _run(installer.update())
+ assert result["status"] == "updated" and result["kind"] == "full"
+ assert layout.read_current(root)["version"] == "4.3.0"
+
+
+def test_too_little_disk_space_is_said_before_any_download(
+ hub: FakeGitHub, signer: Signer, tmp_path: Path
+) -> None:
+ release, full = _publish(tmp_path, signer, "4.2.0", hangar=b"h1" * 5000)
+ hub.releases = [release]
+
+ class Tiny:
+ free = 10
+
+ installer = _installer(hub, signer, tmp_path / "verse", disk_usage=lambda _p: Tiny())
+ with pytest.raises(VerseInstallError, match="GB free"):
+ _run(installer.install())
+ assert hub.downloaded(full.name) == []
+
+
+def test_the_fetcher_refuses_plain_http_outside_tests(hub: FakeGitHub, tmp_path: Path) -> None:
+ with pytest.raises(VerseInstallError, match="non-https"):
+ _run(HttpFetcher().get_text(f"{hub.base}/releases", max_bytes=1000))
diff --git a/tests/unit/installer/test_verse_packaging.py b/tests/unit/installer/test_verse_packaging.py
new file mode 100644
index 0000000000..9fa29645f1
--- /dev/null
+++ b/tests/unit/installer/test_verse_packaging.py
@@ -0,0 +1,588 @@
+"""Packaging, chunks, toolchain pins, Linux smoke and disk hygiene (WP22.1-22.3, 22.7-22.9)."""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+import os
+import re
+import secrets
+import shutil
+import subprocess
+import time
+from pathlib import Path
+
+import pytest
+import yaml
+
+from scripts.unreal import _common as common
+from scripts.unreal import package
+
+REPO = Path(__file__).resolve().parents[3]
+
+
+def _load_activation():
+ # packaging/ is not a Python package (and its name is taken by a library).
+ path = REPO / "packaging/linux/verse/activation_check.py"
+ spec = importlib.util.spec_from_file_location("verse_activation_check", path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+activation = _load_activation()
+
+
+# ------------------------------------------------------------------ 22.1 pins
+def test_toolchain_pins_name_every_installable_part() -> None:
+ pins = common.load_toolchains()
+ assert pins["engine"]["version"] == "5.7.1"
+ assert pins["visual_studio"]["components"]
+ linux = pins["linux"]
+ assert linux["sdk"] in linux["installer_url"]
+ assert re.fullmatch(r"[0-9a-f]{64}", linux["installer_sha256"])
+ assert linux["installer_bytes"] > 0
+ assert linux["engine_component"].endswith("UnrealGame.target")
+
+
+def test_ddc_policy_is_local_and_capped() -> None:
+ ddc = package.load_ddc()
+ assert ddc["shared"] is False
+ assert ddc["cap_gb"] == 40
+ assert ddc["alert_free_gb"] == 40
+ assert package.ddc_args(ddc) == [f"-ddc={ddc['graph']}"]
+ assert package.ddc_env(ddc, {})[ddc["local_path_env"]] == ddc["local_path"]
+
+
+def test_verify_reports_the_missing_linux_engine_part(tmp_path: Path) -> None:
+ probe = package.VerifyProbe(
+ run=lambda *a, **k: common.Completed(0, "linux"),
+ exists=lambda p: False,
+ which=lambda name: "docker",
+ )
+ checks = {
+ c["name"]: c for c in package.verify_packaging(["linux"], engine=tmp_path, probe=probe)
+ }
+ assert checks["chunks"]["status"] == "ok"
+ assert checks["ddc"]["status"] == "ok"
+ assert checks["linux-engine"]["status"] == "fail"
+ assert "Target Platforms, Linux" in checks["linux-engine"]["fix"]
+ assert checks["docker"]["status"] == "ok"
+ win_only = package.verify_packaging(["win64"], engine=tmp_path, probe=probe)
+ assert {c["name"] for c in win_only} == {"chunks", "ddc"}
+
+
+# ------------------------------------------------------ 22.2 BuildCookRun
+def test_buildcookrun_is_shipping_iostore_chunked_and_compressed(tmp_path: Path) -> None:
+ command = package.buildcookrun_command(
+ package.PLATFORMS["win64"],
+ "Shipping",
+ engine=tmp_path,
+ project=tmp_path / "Verse.uproject",
+ archive=tmp_path / "out",
+ ddc=package.load_ddc(),
+ )
+ for flag in (
+ "-target=Verse",
+ "-platform=Win64",
+ "-clientconfig=Shipping",
+ "-iostore",
+ "-pak",
+ "-compressed",
+ "-manifests",
+ "-nodebuginfo",
+ "-nocompileeditor",
+ "-prereqs",
+ "-ddc=InstalledDerivedDataBackendGraph",
+ ):
+ assert flag in command
+ assert command[0].endswith("RunUAT.bat") and command[1] == "BuildCookRun"
+ linux = package.buildcookrun_command(
+ package.PLATFORMS["linux"],
+ "Shipping",
+ engine=tmp_path,
+ project=tmp_path / "p",
+ archive=tmp_path / "o",
+ )
+ assert "-platform=Linux" in linux and "-prereqs" not in linux
+ assert not any("Harness" in part for part in command + linux)
+
+
+def test_the_game_target_on_disk_has_no_harness() -> None:
+ assert package.harness_problems(REPO, package.PLATFORMS["win64"], None) == []
+
+
+def test_harness_detection_in_target_objects_and_binaries(tmp_path: Path) -> None:
+ source = tmp_path / "unreal/Verse/Source"
+ source.mkdir(parents=True)
+ (source / "Verse.Target.cs").write_text(
+ '// VerseHarness lives in the editor target only\nExtraModuleNames.Add("Verse");\n',
+ encoding="utf-8",
+ )
+ spec = package.PLATFORMS["win64"]
+ staged = tmp_path / "staged"
+ (staged / "Verse/Binaries/Win64").mkdir(parents=True)
+ exe = staged / "Verse/Binaries/Win64/Verse-Win64-Shipping.exe"
+ exe.write_bytes(b"MZ" + b"\0" * 100)
+ (staged / "Verse/Content/Paks").mkdir(parents=True)
+ (staged / "Verse/Content/Paks/pakchunk0-Windows.ucas").write_bytes(b"VerseHarness")
+ assert package.harness_problems(tmp_path, spec, staged) == []
+
+ exe.write_bytes(b"MZ" + "VerseHarness".encode("utf-16-le"))
+ (tmp_path / "unreal/Verse/Intermediate/Build/Win64/x64/Verse/Shipping/VerseHarness").mkdir(
+ parents=True
+ )
+ (source / "Verse.Target.cs").write_text(
+ 'ExtraModuleNames.Add("VerseHarness");\n', encoding="utf-8"
+ )
+ problems = package.harness_problems(tmp_path, spec, staged)
+ assert len(problems) == 3
+ assert any("Verse.Target.cs" in p for p in problems)
+ assert any("Shipping objects" in p for p in problems)
+ assert any("Verse-Win64-Shipping.exe carries VerseHarness" in p for p in problems)
+
+
+# ---------------------------------------------------- 22.3 chunks, size, PSO
+def test_every_deck_level_gets_its_own_chunk() -> None:
+ chunks = package.load_chunks()
+ by_name = {c["name"]: c for c in chunks["chunks"]}
+ assert by_name["core"]["id"] == 0 and by_name["core"]["maps"] == []
+ for deck in ("Bridge", "Ops", "Engineering", "Hangar"):
+ assert by_name[deck.lower()]["maps"] == [f"/Game/Verse/Decks/{deck}/LV_{deck}"]
+ block = package.chunk_ini_block(chunks)
+ assert "bGenerateChunks=True" in block
+ assert 'PrimaryAssetId="Map:LV_Hangar",Rules=(Priority=14,ChunkId=4' in block
+ assert block.count("+PrimaryAssetRules=") == 4
+
+
+def test_chunk_rule_problems_catch_broken_rules() -> None:
+ broken = {
+ "schema": "verse.chunks/1",
+ "size_gate": {"payload_max_bytes": 1, "delta_typical_max_bytes": 0},
+ "chunks": [
+ {"id": 1, "name": "a", "maps": ["/Game/Verse/Decks/Ops/LV_Ops"]},
+ {"id": 1, "name": "a", "maps": ["/Game/Verse/Decks/Ops/LV_Ops", "/Game/Other"]},
+ ],
+ }
+ problems = package.chunk_rule_problems(broken)
+ assert "chunk 0 (core) is required" in problems
+ assert "chunk ids must be unique" in problems
+ assert "chunk names must be unique" in problems
+ assert "a map belongs to exactly one chunk" in problems
+ assert any("/Game/Other" in p for p in problems)
+ assert any("delta_typical_max_bytes" in p for p in problems)
+
+
+def test_missing_chunk_config_lists_what_the_ini_lacks(tmp_path: Path) -> None:
+ chunks = package.load_chunks()
+ (tmp_path / "Config").mkdir()
+ assert len(package.missing_chunk_config(tmp_path, chunks)) == 8
+ (tmp_path / "Config/DefaultGame.ini").write_text(
+ package.chunk_ini_block(chunks), encoding="utf-8"
+ )
+ assert package.missing_chunk_config(tmp_path, chunks) == []
+
+
+def test_size_report_groups_bytes_by_deck_chunk(tmp_path: Path) -> None:
+ paks = tmp_path / "Verse/Content/Paks"
+ paks.mkdir(parents=True)
+ files = {
+ "global.utoc": 10,
+ "global.ucas": 20,
+ "pakchunk0-Windows.utoc": 5,
+ "pakchunk0-Windows.ucas": 100,
+ "pakchunk0-Windows.pak": 1,
+ "pakchunk4-Windows.ucas": 300,
+ "pakchunk4optional-Windows.ucas": 7,
+ "pakchunk9-Windows.ucas": 2,
+ }
+ for name, size in files.items():
+ (paks / name).write_bytes(b"x" * size)
+ (tmp_path / "Verse.exe").write_bytes(b"x" * 50)
+ report = package.size_report(tmp_path, package.load_chunks(), platform="Win64")
+ assert report["chunks"]["global"] == {"bytes": 30, "files": 2}
+ assert report["chunks"]["core"] == {"bytes": 106, "files": 3}
+ assert report["chunks"]["hangar"] == {"bytes": 307, "files": 2}
+ assert report["chunks"]["binaries"] == {"bytes": 50, "files": 1}
+ assert report["unknown_chunk_files"] == ["pakchunk9-Windows.ucas"]
+ assert report["total_bytes"] == sum(files.values()) + 50
+ assert report["within_payload_cap"] is True
+ assert report["deck_chunks_present"] == ["hangar"]
+ assert report["deck_chunks_missing"] == ["bridge", "engineering", "ops"]
+ assert report["pso_cache_shipped"] is False
+ (tmp_path / "Verse/Content/PipelineCaches").mkdir()
+ (tmp_path / "Verse/Content/PipelineCaches/Verse_Win64.spc").write_bytes(b"p")
+ assert package.size_report(tmp_path, package.load_chunks(), platform="Win64")[
+ "pso_cache_shipped"
+ ]
+
+
+def test_pso_expand_writes_into_the_engine_required_build_folder(tmp_path: Path) -> None:
+ shk, shipped = package.pso_paths(tmp_path, package.PLATFORMS["win64"])
+ assert shipped == tmp_path / "unreal/Verse/Build/Windows/PipelineCaches"
+ assert shk.parts[-4:] == ("Windows", "Verse", "Metadata", "PipelineCaches")
+ command = package.pso_expand_command(
+ tmp_path,
+ tmp_path / "p",
+ [tmp_path / "a.upipelinecache"],
+ [tmp_path / "b.shk"],
+ shipped / "Verse_Win64.spc",
+ )
+ assert command[2:4] == ["-run=ShaderPipelineCacheTools", "expand"]
+ assert command[-6].endswith("Verse_Win64.spc")
+
+
+def test_cold_start_marker_wait(tmp_path: Path) -> None:
+ log = tmp_path / "game.log"
+ log.write_text("LogInit: start\nVerseSmoke: stage boot OK\n", encoding="utf-8")
+ # The boot stage is not the first frame.
+ assert not package.FIRST_FRAME.search(log.read_text(encoding="utf-8"))
+ log.write_text("LogInit: start\nVerseSmoke: first frame\n", encoding="utf-8")
+ ticks = iter([0.0, 0.0, 0.4])
+ seconds = package.wait_for_marker(
+ log,
+ package.FIRST_FRAME,
+ timeout_s=8,
+ alive=lambda: True,
+ clock=lambda: next(ticks),
+ sleep=lambda s: None,
+ )
+ assert seconds == 0.4
+ log.write_text("LogInit: start\n", encoding="utf-8")
+ assert (
+ package.wait_for_marker(
+ log, package.FIRST_FRAME, timeout_s=8, alive=lambda: False, sleep=lambda s: None
+ )
+ is None
+ )
+
+
+def _bridge_report(**overrides) -> dict:
+ report = {
+ "received": {"hello": 1, "lifecycle.ready": 1},
+ "sent": {"welcome": 1},
+ "expectations": [{"type": "lifecycle.ready", "ok": True, "optional": False}],
+ "invalid_from_verse": [],
+ }
+ report.update(overrides)
+ return report
+
+
+def test_bridge_problems_need_the_handshake_and_lifecycle_ready() -> None:
+ assert package.bridge_problems(_bridge_report(), require_ready=True) == []
+ assert package.bridge_problems(None, require_ready=False)
+ no_hello = package.bridge_problems(_bridge_report(sent={}), require_ready=False)
+ assert no_hello == ["no hello/welcome handshake (the bridge sent no welcome)"]
+ not_ready = _bridge_report(
+ expectations=[{"type": "lifecycle.ready", "ok": False, "optional": True}]
+ )
+ assert package.bridge_problems(not_ready, require_ready=False) == []
+ assert package.bridge_problems(not_ready, require_ready=True) == [
+ "no lifecycle.ready after the first frame"
+ ]
+ scenario = package.bridge_scenario(ready_timeout_s=12)
+ assert scenario["steps"] == [
+ {"at_ms": 0, "expect": {"type": "lifecycle.ready"}, "timeout_ms": 12000, "optional": False}
+ ]
+
+
+TEST_TOKEN = secrets.token_hex(8)
+FAKE_BRIDGE_STANDIN = """
+import argparse, json, os, sys, time
+p = argparse.ArgumentParser()
+for name in ("--scenario", "--report", "--discovery"):
+ p.add_argument(name)
+p.add_argument("--once", action="store_true")
+a = p.parse_args()
+scenario = json.load(open(a.scenario, encoding="utf-8"))
+json.dump({"url": "ws://127.0.0.1:1/api/verse/bridge", "token": os.environ["DODAIOS_VERSE_TOKEN"]},
+ open(a.discovery, "w", encoding="utf-8"))
+time.sleep(0.3)
+json.dump({"received": {"hello": 1}, "sent": {"welcome": 1}, "invalid_from_verse": [],
+ "expectations": [{"type": scenario["steps"][0]["expect"]["type"], "ok": True}]},
+ open(a.report, "w", encoding="utf-8"))
+"""
+
+
+def test_fake_bridge_run_hands_url_and_token_to_the_game(tmp_path: Path) -> None:
+ script = tmp_path / "fake_bridge.py"
+ script.write_text(FAKE_BRIDGE_STANDIN, encoding="utf-8")
+ run = package.FakeBridgeRun(
+ tmp_path / "out", token=TEST_TOKEN, ready_timeout_s=5, fake_bridge=script
+ )
+ with run:
+ env = run.env({})
+ assert env == {
+ package.BRIDGE_ENV: "ws://127.0.0.1:1/api/verse/bridge",
+ package.TOKEN_ENV: TEST_TOKEN,
+ }
+ assert package.bridge_problems(run.report, require_ready=True) == []
+ with pytest.raises(common.UnrealScriptError, match="fake bridge"):
+ with package.FakeBridgeRun(
+ tmp_path / "o2",
+ token=TEST_TOKEN,
+ ready_timeout_s=1,
+ fake_bridge=tmp_path / "missing.py",
+ ):
+ pass
+
+
+# ------------------------------------------------------------ 22.7 Linux
+def test_docker_smoke_command_is_offline_and_read_only(tmp_path: Path) -> None:
+ command = package.docker_smoke_command(
+ tmp_path / "Linux", tmp_path / "out", seconds=60, gpu=False, name="verse-smoke-test"
+ )
+ assert command[:3] == ["docker", "run", "--rm"]
+ assert command[command.index("--network") + 1] == "none"
+ assert f"{tmp_path / 'Linux'}:/verse:ro" in command
+ assert command[-3:] == ["/smoke/linux_smoke.sh", "60", "nogpu"]
+ assert "--gpus" not in command
+ # The fake bridge and its golden data reach the container read-only.
+ assert f"{REPO / 'scripts'}:/repo/scripts:ro" in command
+ assert f"{package.BRIDGE_DATA_DIR}:/repo/unreal/Verse/Tests/Data/bridge:ro" in command
+ gpu = package.docker_smoke_command(tmp_path, tmp_path, seconds=60, gpu=True)
+ assert gpu[gpu.index("--gpus") + 1] == "all" and gpu[-1] == "gpu"
+
+
+def test_linux_smoke_evaluation(tmp_path: Path) -> None:
+ assert package.evaluate_linux_smoke(tmp_path)["pass"] is False
+ (tmp_path / "result.json").write_text(
+ json.dumps(
+ {
+ "server_ok": True,
+ "vulkan": "skip",
+ "problems": [],
+ "activation": {"x11": "ok", "wayland": "ok"},
+ }
+ ),
+ encoding="utf-8",
+ )
+ (tmp_path / "nullrhi.log").write_text("VerseSmoke: stage boot OK\n", encoding="utf-8")
+ # No bridge report: the handshake never happened.
+ assert package.evaluate_linux_smoke(tmp_path)["pass"] is False
+ (tmp_path / "bridge-server-report.json").write_text(
+ json.dumps(_bridge_report()), encoding="utf-8"
+ )
+ assert package.evaluate_linux_smoke(tmp_path)["pass"] is True
+ (tmp_path / "nullrhi.log").write_text("LogWindows: Error: Fatal error!\n", encoding="utf-8")
+ result = package.evaluate_linux_smoke(tmp_path)
+ assert result["pass"] is False and result["problems"]
+
+
+def test_linux_smoke_scripts_parse_under_bash() -> None:
+ bash = shutil.which("bash")
+ if bash is None:
+ pytest.skip("no bash")
+ for script in ("linux_smoke.sh",):
+ path = REPO / "packaging/linux/verse" / script
+ assert subprocess.run([bash, "-n", str(path)], check=False).returncode == 0
+
+
+def test_activation_parsers_and_statuses() -> None:
+ xprop = "_NET_SUPPORTED(ATOM) = _NET_WM_NAME, _NET_ACTIVE_WINDOW, _NET_CLIENT_LIST\n"
+ assert activation.x11_supports_activation(xprop)
+ assert not activation.x11_supports_activation("_NET_SUPPORTED(ATOM) = _NET_WM_NAME\n")
+ assert not activation.x11_supports_activation("_NET_SUPPORTED: not found.\n")
+ info = "interface: 'wl_compositor', version: 6\ninterface: 'xdg_activation_v1', version: 1\n"
+ assert activation.wayland_supports_activation(info)
+
+ def run(command, env):
+ if command[0] == "xprop":
+ return 0, xprop
+ return 0, "interface: 'wl_shm', version: 1\n"
+
+ assert activation.check_x11(":98", run)[0] == "ok"
+ assert activation.check_wayland("wl-0", run)[0] == "fail"
+ assert activation.check_x11(None, run)[0] == "skip"
+ assert activation.check_wayland("wl-0", lambda c, e: (1, ""))[0] == "skip"
+ assert activation.main(["--x11", ":98"], run) == 0
+ assert activation.main(["--x11", ":98", "--wayland", "wl-0"], run) == 1
+
+
+# ------------------------------------------------------------ 22.9 hygiene
+def _file(path: Path, size: int, age_s: float, now: float) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(b"x" * size)
+ os.utime(path, (now - age_s, now - age_s))
+
+
+def test_ddc_prune_removes_oldest_first_down_to_the_cap(tmp_path: Path) -> None:
+ now = time.time()
+ _file(tmp_path / "a", 400, 300, now)
+ _file(tmp_path / "b/c", 300, 200, now)
+ _file(tmp_path / "d", 300, 100, now)
+ total, prune = package.plan_ddc_prune(tmp_path, cap_bytes=500)
+ assert total == 1000
+ assert prune == [tmp_path / "a", tmp_path / "b/c"]
+ assert package.plan_ddc_prune(tmp_path / "missing", 1) == (0, [])
+
+
+def test_hygiene_plans_intermediate_pruning_and_alerts(tmp_path: Path) -> None:
+ now = time.time()
+ _file(tmp_path / "wt-old/unreal/Verse/Intermediate/Build/x.obj", 10, 10 * 86400, now)
+ _file(tmp_path / "wt-new/unreal/Verse/Intermediate/Build/x.obj", 10, 60, now)
+ (tmp_path / "wt-none").mkdir()
+ ddc = dict(package.load_ddc(), local_path=str(tmp_path / "ddc"), zen_data_path="")
+ _file(tmp_path / "ddc/old", 10, 100, now)
+ plan = package.plan_hygiene(ddc, worktrees_root=tmp_path, now=now, free_gb=lambda p: 12.0)
+ assert plan.intermediate_prune == [tmp_path / "wt-old/unreal/Verse/Intermediate"]
+ assert plan.ddc_prune == []
+ assert plan.alert is True
+ removed = package.apply_hygiene(plan)
+ assert removed == 1
+ assert not (tmp_path / "wt-old/unreal/Verse/Intermediate").exists()
+ assert (tmp_path / "wt-new/unreal/Verse/Intermediate").exists()
+ healthy = package.plan_hygiene(ddc, worktrees_root=tmp_path, now=now, free_gb=lambda p: 500)
+ assert healthy.alert is False
+
+
+def test_a_locked_intermediate_folder_does_not_stop_the_prune(tmp_path: Path) -> None:
+ plan = package.HygienePlan(intermediate_prune=[tmp_path / "a", tmp_path / "b"])
+ removed: list[Path] = []
+
+ def remove_tree(folder: Path) -> None:
+ if folder.name == "a":
+ raise PermissionError("in use")
+ removed.append(folder)
+
+ assert package.apply_hygiene(plan, remove_tree=remove_tree) == 1
+ assert removed == [tmp_path / "b"]
+
+
+def test_hygiene_plans_again_inside_the_lock_and_fails_over_a_zen_cap(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ import argparse
+
+ now = time.time()
+ stale = tmp_path / "wt/unreal/Verse/Intermediate"
+ _file(stale / "x.obj", 10, 10 * 86400, now)
+ zen = tmp_path / "zen"
+ _file(zen / "cas.ucas", 50, 10, now)
+ ddc = dict(
+ package.load_ddc(),
+ local_path=str(tmp_path / "ddc"),
+ zen_data_path=str(zen),
+ cap_gb=0,
+ alert_free_gb=0,
+ )
+ monkeypatch.setattr(package, "load_ddc", lambda: ddc)
+
+ class Lock:
+ def __init__(self, *args) -> None:
+ pass
+
+ def __enter__(self):
+ # The worktree became active while the job waited in the queue.
+ _file(stale / "fresh.obj", 10, 0, time.time())
+ return self
+
+ def __exit__(self, *exc) -> None:
+ return None
+
+ monkeypatch.setattr(package.with_lock, "MachineLock", Lock)
+ options = argparse.Namespace(worktrees=tmp_path, apply=True)
+ assert package.cmd_hygiene(options) == 4 # the Zen store is over its cap
+ assert stale.is_dir()
+
+
+# ---------------------------------------------------- 22.8 workflow policy
+def _workflow() -> dict:
+ return yaml.safe_load((REPO / ".github/workflows/unreal-package.yml").read_text("utf-8"))
+
+
+def test_package_workflow_never_runs_self_hosted_for_pull_requests() -> None:
+ workflow = _workflow()
+ triggers = workflow.get("on") or workflow.get(True)
+ assert "pull_request" not in triggers and "pull_request_target" not in triggers
+ assert workflow["permissions"] == {"contents": "read"}
+ assert workflow["concurrency"]["group"] == "unreal-build"
+
+
+def test_no_secret_reaches_the_self_hosted_runner() -> None:
+ for name, job in _workflow()["jobs"].items():
+ runs_on = job["runs-on"]
+ if isinstance(runs_on, list) and "self-hosted" in runs_on:
+ dumped = yaml.safe_dump(job)
+ assert "secrets." not in dumped, name
+ assert job["permissions"] == {"contents": "read"}, name
+ assert "environment" not in job, name
+
+
+def test_signing_and_release_jobs_follow_the_existing_paths() -> None:
+ jobs = _workflow()["jobs"]
+ assert jobs["sign-windows"]["runs-on"] == "windows-latest"
+ signpath = [
+ s for s in jobs["sign-windows"]["steps"] if s.get("uses", "").startswith("signpath/")
+ ]
+ assert signpath and re.fullmatch(r"signpath/[\w-]+@[0-9a-f]{40}", signpath[0]["uses"])
+ assert jobs["sign-manifest"]["environment"] == "release-signing"
+ assert "offline-ceremony.pub" in yaml.safe_dump(jobs["sign-manifest"])
+ writers = [n for n, j in jobs.items() if j.get("permissions", {}).get("contents") == "write"]
+ # A failed Linux leg must not hold back the Windows payload.
+ for name in ("sign-windows", "assemble", "sign-manifest", "release"):
+ assert "!cancelled()" in jobs[name]["if"], name
+ assert writers == ["release"]
+ assert "--clobber" not in yaml.safe_dump(jobs["release"])
+
+
+def test_workflow_policy_check_stays_green() -> None:
+ from scripts.ci import check_workflow_policy as policy
+
+ workflows = {
+ path.name: yaml.safe_load(path.read_text(encoding="utf-8"))
+ for path in (REPO / ".github/workflows").glob("*.yml")
+ }
+ findings = [f for f in policy.audit(workflows) if "unreal-package" in f]
+ assert findings == []
+
+
+# ------------------------------------------- 22.5 the signed release manifest
+def test_manifest_command_names_sizes_hashes_and_deltas(tmp_path: Path) -> None:
+ from dodaios.verse_host.install import manifest as vm
+ from dodaios.verse_host.install import payload as vp
+
+ old = tmp_path / "old"
+ old.mkdir()
+ (old / "Verse.sh").write_bytes(b"#!/bin/sh\n")
+ (old / "deck.ucas").write_bytes(b"a" * 500)
+ old_full = tmp_path / "Verse-Linux-4.2.0.tar"
+ package.make_full(old, version="4.2.0", platform="Linux", out=old_full)
+ new = tmp_path / "new"
+ new.mkdir()
+ (new / "Verse.sh").write_bytes(b"#!/bin/sh\n")
+ (new / "deck.ucas").write_bytes(b"b" * 600)
+ full = tmp_path / "Verse-Linux-4.2.1.tar"
+ package.make_full(new, version="4.2.1", platform="Linux", out=full)
+ delta = tmp_path / "Verse-Linux-4.2.0-to-4.2.1.delta.tar"
+ package.make_delta(package.read_payload_tree(old_full), new, version="4.2.1", out=delta)
+
+ out = tmp_path / "verse-Linux-manifest.json"
+ code = package.main(["manifest", "--full", str(full), "--delta", str(delta), "--tag", "v4.2.1"])
+ assert code == 0
+ parsed = vm.parse_release_manifest(out.read_bytes())
+ assert parsed.version == "4.2.1" and parsed.platform == "Linux"
+ assert parsed.entry == "Verse.sh"
+ assert parsed.full.size == full.stat().st_size
+ assert parsed.full.sha256 == vp.sha256_file(full)
+ assert parsed.install_bytes == 600 + len(b"#!/bin/sh\n")
+ assert parsed.tree_sha256 == vp.tree_digest(vp.read_package_tree(full))
+ (ref,) = parsed.deltas
+ assert ref.from_version == "4.2.0" and ref.sha256 == vp.sha256_file(delta)
+ assert ref.from_tree_sha256 == vp.tree_digest(package.read_payload_tree(old_full))
+ # Canonical bytes: what the release key signs is stable.
+ assert out.read_bytes() == package.make_release_manifest(full, [delta], tag="v4.2.1")
+
+
+def test_manifest_command_refuses_a_misnamed_package_or_tag(tmp_path: Path) -> None:
+ stage = tmp_path / "stage"
+ stage.mkdir()
+ (stage / "Verse.exe").write_bytes(b"x")
+ wrong = tmp_path / "verse.tar"
+ package.make_full(stage, version="4.2.0", platform="Win64", out=wrong)
+ with pytest.raises(common.UnrealScriptError, match="should be named"):
+ package.make_release_manifest(wrong, [], tag="v4.2.0")
+ right = tmp_path / "Verse-Win64-4.2.0.tar"
+ package.make_full(stage, version="4.2.0", platform="Win64", out=right)
+ with pytest.raises(Exception, match="does not match version"):
+ package.make_release_manifest(right, [], tag="v4.3.0")
diff --git a/tests/unit/installer/test_verse_payload.py b/tests/unit/installer/test_verse_payload.py
new file mode 100644
index 0000000000..c0bd2c1e28
--- /dev/null
+++ b/tests/unit/installer/test_verse_payload.py
@@ -0,0 +1,282 @@
+"""Verse packages and deltas: make, install, apply, verify, roll back, remove (WP22.4, A22.5)."""
+
+from __future__ import annotations
+
+import io
+import json
+import tarfile
+from pathlib import Path
+
+import pytest
+
+from dodaios.verse_host.install import layout as lay
+from dodaios.verse_host.install import payload as pl
+from scripts.unreal import package
+
+
+def _stage(folder: Path, files: dict[str, bytes]) -> Path:
+ for rel, data in files.items():
+ path = folder / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(data)
+ return folder
+
+
+BASE = {
+ "Verse.exe": b"launcher-1",
+ "Verse/Binaries/Win64/Verse-Win64-Shipping.exe": b"game-1" * 100,
+ "Verse/Content/Paks/global.utoc": b"global" * 50,
+ "Verse/Content/Paks/pakchunk0-Windows.utoc": b"core-1" * 80,
+ "Verse/Content/Paks/pakchunk1-Windows.ucas": b"bridge-1" * 300,
+ "Verse/Content/Paks/pakchunk4-Windows.ucas": b"hangar-1" * 400,
+}
+
+
+def released(tmp_path: Path) -> dict[str, Path]:
+ """Version 4.2.0 installed from its full payload, and a 4.2.1 build staged."""
+ old_stage = _stage(tmp_path / "old", BASE)
+ full = tmp_path / "Verse-Win64-4.2.0.tar"
+ package.make_full(old_stage, version="4.2.0", platform="Win64", out=full)
+ root = tmp_path / "root"
+ pl.install_full(root, full)
+ new_files = dict(BASE)
+ new_files["Verse/Content/Paks/pakchunk4-Windows.ucas"] = b"hangar-2" * 450
+ new_files["Verse/Content/Paks/pakchunk5-Windows.ucas"] = b"new-deck" * 10
+ new_stage = _stage(tmp_path / "new", new_files)
+ return {"root": root, "full": full, "new": new_stage, "tmp": tmp_path}
+
+
+def test_full_install_verifies_and_points_current(released: dict[str, Path]) -> None:
+ root = released["root"]
+ current = lay.read_current(root)
+ assert current == {
+ "schema": lay.VERSE_CURRENT_SCHEMA,
+ "version": "4.2.0",
+ "previous": None,
+ "platform": "Win64",
+ "entry": "Verse.exe",
+ }
+ assert pl.verify_tree(lay.version_dir(root, "4.2.0")) == []
+
+
+def test_delta_carries_only_changed_chunks_and_applies_with_full_hash_match(
+ released: dict[str, Path],
+) -> None:
+ delta = released["tmp"] / "d.delta.tar"
+ made = package.make_delta(
+ package.read_payload_tree(released["full"]), released["new"], version="4.2.1", out=delta
+ )
+ assert sorted(made["changed_files"]) == [
+ "Verse/Content/Paks/pakchunk4-Windows.ucas",
+ "Verse/Content/Paks/pakchunk5-Windows.ucas",
+ ]
+ assert made["reused"] == len(BASE) - 1
+ assert made["within_typical"] is True
+
+ result = pl.apply_delta(released["root"], delta)
+ assert result["version"] == "4.2.1" and result["previous"] == "4.2.0"
+ assert result["changed"] == 2
+ new_dir = lay.version_dir(released["root"], "4.2.1")
+ assert pl.verify_tree(new_dir) == [] # 100 % hash match
+ assert (new_dir / "Verse/Content/Paks/pakchunk4-Windows.ucas").read_bytes() == b"hangar-2" * 450
+ # The previous version stays for a rollback.
+ assert pl.verify_tree(lay.version_dir(released["root"], "4.2.0")) == []
+
+
+def _rewrite_member(source: Path, out: Path, name: str, data: bytes) -> None:
+ with tarfile.open(source, "r:") as old, tarfile.open(out, "w") as new:
+ for member in old.getmembers():
+ payload = old.extractfile(member).read() if member.isfile() else b""
+ if member.name == name:
+ payload = data
+ info = tarfile.TarInfo(member.name)
+ info.size = len(payload)
+ new.addfile(info, io.BytesIO(payload))
+
+
+def test_a_corrupted_chunk_rolls_back_to_the_previous_version(released: dict[str, Path]) -> None:
+ delta = released["tmp"] / "d.delta.tar"
+ package.make_delta(
+ package.read_payload_tree(released["full"]), released["new"], version="4.2.1", out=delta
+ )
+ corrupted = released["tmp"] / "corrupt.delta.tar"
+ _rewrite_member(
+ delta, corrupted, "files/Verse/Content/Paks/pakchunk4-Windows.ucas", b"X" * (8 * 450)
+ )
+ with pytest.raises(lay.VerseInstallError, match="rolled back, version 4.2.0 stays installed"):
+ pl.apply_delta(released["root"], corrupted)
+ assert lay.read_current(released["root"])["version"] == "4.2.0"
+ assert pl.verify_tree(lay.version_dir(released["root"], "4.2.0")) == []
+ leftovers = [p.name for p in (released["root"] / "versions").iterdir()]
+ assert leftovers == ["4.2.0"] # the staging folder is gone
+
+
+def test_a_delta_for_another_base_build_is_refused(released: dict[str, Path]) -> None:
+ other = _stage(released["tmp"] / "other", {**BASE, "Verse.exe": b"launcher-other"})
+ other_full = released["tmp"] / "Verse-Win64-4.2.0-other.tar"
+ package.make_full(other, version="4.2.0", platform="Win64", out=other_full)
+ delta = released["tmp"] / "d.delta.tar"
+ package.make_delta(
+ package.read_payload_tree(other_full), released["new"], version="4.2.1", out=delta
+ )
+ with pytest.raises(lay.VerseInstallError, match="not the build this delta was made from"):
+ pl.apply_delta(released["root"], delta)
+ assert lay.read_current(released["root"])["version"] == "4.2.0"
+
+
+def test_a_delta_from_another_version_is_refused(released: dict[str, Path]) -> None:
+ tree = package.read_payload_tree(released["full"])
+ tree["version"] = "4.1.0"
+ delta = released["tmp"] / "d.delta.tar"
+ package.make_delta(tree, released["new"], version="4.2.1", out=delta)
+ with pytest.raises(lay.VerseInstallError, match="updates Verse 4.1.0, but 4.2.0 is installed"):
+ pl.apply_delta(released["root"], delta)
+
+
+def test_a_delta_needs_an_installed_verse(tmp_path: Path) -> None:
+ with pytest.raises(lay.VerseInstallError, match="no Verse is installed"):
+ pl.apply_delta(tmp_path / "empty", tmp_path / "x.tar")
+
+
+ "name", ["files/../escape.txt", "/abs/path", "files/C:/x", "files\\win\\path", "files//x"]
+)
+def test_unsafe_tar_paths_are_refused(tmp_path: Path, name: str) -> None:
+ bad = tmp_path / "bad.tar"
+ tree = {
+ "schema": pl.VERSE_TREE_SCHEMA,
+ "version": "1.0.0",
+ "platform": "Win64",
+ "files": {"a": {"size": 1, "sha256": "0" * 64}},
+ }
+ with tarfile.open(bad, "w") as archive:
+ for member_name, data in (
+ (pl.VERSE_TREE_FILE, json.dumps(tree).encode()),
+ (name, b"x"),
+ ):
+ info = tarfile.TarInfo(member_name)
+ info.size = len(data)
+ archive.addfile(info, io.BytesIO(data))
+ with pytest.raises(lay.VerseInstallError, match="unsafe path"):
+ pl.install_full(tmp_path / "root", bad)
+ assert not (tmp_path / "escape.txt").exists()
+
+
+def test_a_symlink_member_is_refused(tmp_path: Path) -> None:
+ bad = tmp_path / "bad.tar"
+ with tarfile.open(bad, "w") as archive:
+ info = tarfile.TarInfo("files/link")
+ info.type = tarfile.SYMTYPE
+ info.linkname = "/etc/passwd"
+ archive.addfile(info)
+ with pytest.raises(lay.VerseInstallError, match="non-file entry"):
+ pl.install_full(tmp_path / "root", bad)
+
+
+def test_rollback_and_health_check(released: dict[str, Path]) -> None:
+ root = released["root"]
+ delta = released["tmp"] / "d.delta.tar"
+ package.make_delta(
+ package.read_payload_tree(released["full"]), released["new"], version="4.2.1", out=delta
+ )
+ pl.apply_delta(root, delta)
+ assert pl.ensure_healthy(root, hashes=True) == {"status": "ok", "version": "4.2.1"}
+ # A damaged chunk of the running version rolls back to the verified previous one.
+ (lay.version_dir(root, "4.2.1") / "Verse/Content/Paks/pakchunk4-Windows.ucas").write_bytes(
+ b"truncated"
+ )
+ health = pl.ensure_healthy(root)
+ assert health["status"] == "rolled_back"
+ assert health["version"] == "4.2.0"
+ assert lay.read_current(root)["version"] == "4.2.0"
+ with pytest.raises(lay.VerseInstallError, match="no previous Verse version"):
+ pl.rollback(root)
+
+
+def test_damage_to_a_file_both_versions_share_reports_broken(released: dict[str, Path]) -> None:
+ """Unchanged files are hard links; damage to one is damage to both versions.
+
+ The health check then says ``broken`` (the updater reinstalls the full
+ payload) instead of switching to a previous version that is damaged too.
+ """
+ root = released["root"]
+ delta = released["tmp"] / "d.delta.tar"
+ package.make_delta(
+ package.read_payload_tree(released["full"]), released["new"], version="4.2.1", out=delta
+ )
+ pl.apply_delta(root, delta)
+ (lay.version_dir(root, "4.2.1") / "Verse.exe").write_bytes(b"truncated")
+ health = pl.ensure_healthy(root)
+ assert health["status"] == "broken"
+ assert lay.read_current(root)["version"] == "4.2.1"
+
+
+def test_verify_reports_every_kind_of_difference(released: dict[str, Path]) -> None:
+ folder = lay.version_dir(released["root"], "4.2.0")
+ (folder / "Verse.exe").write_bytes(b"launcher-X") # same size, other bytes
+ (folder / "Verse/Content/Paks/global.utoc").unlink()
+ (folder / "stray.txt").write_bytes(b"x")
+ problems = pl.verify_tree(folder)
+ assert "hash mismatch Verse.exe" in problems
+ assert "missing Verse/Content/Paks/global.utoc" in problems
+ assert "unexpected stray.txt" in problems
+ assert "hash mismatch Verse.exe" not in pl.verify_tree(folder, hashes=False)
+
+
+def test_reinstalling_the_running_version_keeps_it_when_the_swap_fails(
+ released: dict[str, Path], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ root = released["root"]
+ real_replace = pl.os.replace
+
+ def failing_replace(src, dst):
+ if Path(src).name.startswith(".staging-"):
+ raise PermissionError("in use")
+ return real_replace(src, dst)
+
+ monkeypatch.setattr(pl.os, "replace", failing_replace)
+ with pytest.raises(lay.VerseInstallError, match="could not be switched in"):
+ pl.install_full(root, released["full"])
+ monkeypatch.setattr(pl.os, "replace", real_replace)
+ assert pl.ensure_healthy(root, hashes=True) == {"status": "ok", "version": "4.2.0"}
+ assert not [p for p in (root / "versions").iterdir() if p.name.startswith(".")]
+
+
+def test_apply_command_writes_the_delta_apply_log(released: dict[str, Path]) -> None:
+ delta = released["tmp"] / "d.delta.tar"
+ package.make_delta(
+ package.read_payload_tree(released["full"]), released["new"], version="4.2.1", out=delta
+ )
+ log = released["tmp"] / "apply.log"
+ code = package.main(
+ ["apply", "--root", str(released["root"]), "--delta", str(delta), "--log", str(log)]
+ )
+ assert code == 0
+ entry = json.loads(log.read_text(encoding="utf-8").splitlines()[-1])
+ assert entry["status"] == "applied"
+ assert entry["after"]["version"] == "4.2.1"
+ assert entry["verify_problems"] == []
+
+
+def test_uninstall_frees_the_folder_and_reads_not_installed(released: dict[str, Path]) -> None:
+ root = released["root"]
+ (root / "downloads").mkdir()
+ (root / "downloads" / "Verse-Win64-4.2.1.tar.part").write_bytes(b"x" * 100)
+ result = pl.uninstall(root)
+ assert result["status"] == "not_installed"
+ assert result["freed_bytes"] > 0 and result["leftovers"] == []
+ assert lay.read_current(root) is None
+ assert pl.ensure_healthy(root) == {"status": "not_installed"}
+ assert not root.exists()
+ # Removing twice is harmless.
+ assert pl.uninstall(root)["status"] == "not_installed"
+
+
+def test_the_entry_points_at_the_launcher_of_the_running_version(
+ released: dict[str, Path],
+) -> None:
+ root = released["root"]
+ assert lay.read_current(root)["entry"] == "Verse.exe"
+ assert pl.entry_path(root) == lay.version_dir(root, "4.2.0") / "Verse.exe"
+ assert pl.entry_path(released["tmp"] / "nothing") is None
diff --git a/unreal/Toolchain/chunks.json b/unreal/Toolchain/chunks.json
new file mode 100644
index 0000000000..84b87db62a
--- /dev/null
+++ b/unreal/Toolchain/chunks.json
@@ -0,0 +1,15 @@
+{
+ "schema": "verse.chunks/1",
+ "about": "IoStore chunk per deck (docs/verse/unreal/work-packages.md WP22.3). Chunk 0 carries the startup map, code-referenced content and everything two decks share; each deck level and the actors World Partition streams for it land in its own chunk, so a change to one deck ships as one chunk in the delta. scripts/unreal/package.py chunks prints the config lines that apply these rules.",
+ "size_gate": {
+ "payload_max_bytes": 2000000000,
+ "delta_typical_max_bytes": 300000000
+ },
+ "chunks": [
+ {"id": 0, "name": "core", "maps": []},
+ {"id": 1, "name": "bridge", "maps": ["/Game/Verse/Decks/Bridge/LV_Bridge"]},
+ {"id": 2, "name": "ops", "maps": ["/Game/Verse/Decks/Ops/LV_Ops"]},
+ {"id": 3, "name": "engineering", "maps": ["/Game/Verse/Decks/Engineering/LV_Engineering"]},
+ {"id": 4, "name": "hangar", "maps": ["/Game/Verse/Decks/Hangar/LV_Hangar"]}
+ ]
+}
diff --git a/unreal/Toolchain/ddc.json b/unreal/Toolchain/ddc.json
new file mode 100644
index 0000000000..050ffdebfd
--- /dev/null
+++ b/unreal/Toolchain/ddc.json
@@ -0,0 +1,12 @@
+{
+ "schema": "verse.ddc/1",
+ "about": "Derived data cache policy of the Unreal Verse (docs/verse/unreal/architecture.md 8.1). Local only, never a shared cloud cache. package.py passes -ddc=<graph> and sets <local_path_env>; package.py hygiene keeps the cache under cap_gb, prunes Intermediate folders of worktrees untouched for intermediate_max_age_days and alerts below alert_free_gb free.",
+ "graph": "InstalledDerivedDataBackendGraph",
+ "local_path_env": "UE-LocalDataCachePath",
+ "local_path": "C:/demo/.ddc/local",
+ "zen_data_path": "C:/demo/.ddc/zen",
+ "cap_gb": 40,
+ "intermediate_max_age_days": 7,
+ "alert_free_gb": 40,
+ "shared": false
+}
diff --git a/unreal/Toolchain/setup_toolchain.ps1 b/unreal/Toolchain/setup_toolchain.ps1
new file mode 100644
index 0000000000..599a1a0f23
--- /dev/null
+++ b/unreal/Toolchain/setup_toolchain.ps1
@@ -0,0 +1,95 @@
+<#
+.SYNOPSIS
+ Install the toolchain the Unreal Verse builds with, from the pins in toolchains.json.
+
+.DESCRIPTION
+ docs/verse/unreal/work-packages.md WP22.1. Reads unreal/Toolchain/toolchains.json
+ and brings this box to it:
+
+ 1. Visual Studio 2022 Build Tools with the pinned MSVC, Windows SDK and .NET
+ targeting packs (the Visual Studio installer asks for elevation once).
+ 2. The engine's Linux cross toolchain: the vendor installer is downloaded,
+ checked against the pinned size and SHA-256, and unpacked with 7-Zip into
+ install_root, so no elevation is needed for it.
+ 3. The user variable LINUX_MULTIARCH_ROOT pointing at it.
+
+ Without -Apply it only prints what it would do. The Linux target platform of
+ the engine install itself is added once through the launcher (UE 5.7, Options,
+ Target Platforms, Linux); the script says when it is missing. Afterwards run:
+
+ python scripts/unreal/package.py verify
+
+.PARAMETER Apply
+ Install for real. Without it the script changes nothing.
+#>
+[CmdletBinding()]
+param([switch]$Apply)
+
+$ErrorActionPreference = 'Stop'
+$Pins = Get-Content -Raw -LiteralPath (Join-Path $PSScriptRoot 'toolchains.json') | ConvertFrom-Json
+
+function Write-Step([string]$Text) { Write-Host "[toolchain] $Text" }
+
+# ---------------------------------------------------------------- Visual Studio
+$Vswhere = 'C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe'
+$Components = @($Pins.visual_studio.components)
+$Installed = $null
+if (Test-Path -LiteralPath $Vswhere) {
+ $Installed = & $Vswhere -products '*' -version "[$($Pins.visual_studio.min_version),18.0)" `
+ -requires $Components -property installationPath | Select-Object -First 1
+}
+if ($Installed) {
+ Write-Step "Build Tools with every pinned component: $Installed"
+} else {
+ $InstallArgs = @('--quiet', '--wait', '--norestart', '--nocache') + ($Components | ForEach-Object { @('--add', $_) })
+ Write-Step "Build Tools missing components: vs_buildtools.exe $($InstallArgs -join ' ')"
+ if ($Apply) {
+ $Boot = Join-Path $env:TEMP 'vs_buildtools.exe'
+ Invoke-WebRequest -Uri $Pins.visual_studio.bootstrapper -OutFile $Boot -UseBasicParsing
+ $Signature = Get-AuthenticodeSignature -LiteralPath $Boot
+ if ($Signature.Status -ne 'Valid') { throw "vs_buildtools.exe signature is $($Signature.Status)" }
+ $Process = Start-Process -FilePath $Boot -ArgumentList $InstallArgs -Verb RunAs -Wait -PassThru
+ if ($Process.ExitCode -notin 0, 3010) { throw "vs_buildtools.exe exited with $($Process.ExitCode)" }
+ }
+}
+
+# ------------------------------------------------------- Linux cross toolchain
+$Linux = $Pins.linux
+$Root = Join-Path $Linux.install_root $Linux.sdk
+$Clang = Join-Path $Root 'x86_64-unknown-linux-gnu\bin\clang++.exe'
+if (Test-Path -LiteralPath $Clang) {
+ Write-Step "Linux toolchain $($Linux.sdk) at $Root"
+} else {
+ Write-Step "Linux toolchain missing: download $($Linux.installer_url), unpack to $Root"
+ if ($Apply) {
+ $SevenZip = @('C:\Program Files\7-Zip\7z.exe', (Get-Command 7z.exe -ErrorAction SilentlyContinue).Source) |
+ Where-Object { $_ -and (Test-Path -LiteralPath $_) } | Select-Object -First 1
+ if (-not $SevenZip) { throw '7-Zip is needed to unpack the toolchain without elevation' }
+ $Download = Join-Path $env:TEMP "$($Linux.sdk).exe"
+ & curl.exe -fL -C - -o $Download $Linux.installer_url
+ if ($LASTEXITCODE -ne 0) { throw "download failed (curl exit $LASTEXITCODE)" }
+ $Size = (Get-Item -LiteralPath $Download).Length
+ $Hash = (Get-FileHash -LiteralPath $Download -Algorithm SHA256).Hash.ToLowerInvariant()
+ if ($Size -ne [int64]$Linux.installer_bytes -or $Hash -ne $Linux.installer_sha256) {
+ throw "toolchain installer does not match its pin ($Size bytes, sha256 $Hash)"
+ }
+ New-Item -ItemType Directory -Force -Path $Root | Out-Null
+ & $SevenZip x -tNsis -y "-o$Root" $Download | Out-Null
+ if ($LASTEXITCODE -ne 0) { throw "7-Zip exited with $LASTEXITCODE" }
+ if (-not (Test-Path -LiteralPath $Clang)) { throw "no $Clang after unpacking" }
+ }
+}
+$Current = [Environment]::GetEnvironmentVariable($Linux.env, 'User')
+if ($Current -ne "$Root\") {
+ Write-Step "set user variable $($Linux.env)=$Root\"
+ if ($Apply) { [Environment]::SetEnvironmentVariable($Linux.env, "$Root\", 'User') }
+}
+
+# ------------------------------------------------- engine Linux target platform
+$EngineMarker = Join-Path $Pins.engine.windows_root $Linux.engine_component
+if (-not (Test-Path -LiteralPath $EngineMarker)) {
+ Write-Step "the engine has no Linux target platform ($EngineMarker): add it once in the launcher (UE 5.7, Options, Target Platforms, Linux)"
+}
+
+if (-not $Apply) { Write-Step 'dry run: nothing changed (pass -Apply to install)' }
+Write-Step 'next: python scripts/unreal/package.py verify'
diff --git a/unreal/Toolchain/toolchains.json b/unreal/Toolchain/toolchains.json
index 1901c3b827..9a1c8acc5c 100644
--- a/unreal/Toolchain/toolchains.json
+++ b/unreal/Toolchain/toolchains.json
@@ -8,7 +8,14 @@
},
"visual_studio": {
"min_version": "17.14",
- "workloads_note": "VS 2022 Build Tools with the C++ x64 tools of the MSVC family below and the Windows SDK below"
+ "workloads_note": "VS 2022 Build Tools with the C++ x64 tools of the MSVC family below and the Windows SDK below",
+ "components": [
+ "Microsoft.VisualStudio.Workload.VCTools",
+ "Microsoft.VisualStudio.Component.VC.Tools.x86.x64",
+ "Microsoft.VisualStudio.Component.Windows11SDK.22621",
+ "Microsoft.Net.Component.4.6.2.TargetingPack"
+ ],
+ "bootstrapper": "https://aka.ms/vs/17/release/vs_buildtools.exe"
},
"msvc": {
"family": "14.44",
@@ -21,7 +28,10 @@
"netfx": {
"runtime": "4.8.1",
"min_release": 533320,
- "targeting_packs": ["v4.6.2", "v4.8.1"],
+ "targeting_packs": [
+ "v4.6.2",
+ "v4.8.1"
+ ],
"reference_root": "C:/Program Files (x86)/Reference Assemblies/Microsoft/Framework/.NETFramework"
},
"git_lfs": {
@@ -29,9 +39,19 @@
},
"linux": {
"sdk": "v26_clang-20.1.8-rockylinux8",
- "env": "LINUX_MULTIARCH_ROOT"
+ "env": "LINUX_MULTIARCH_ROOT",
+ "installer_url": "https://cdn.unrealengine.com/CrossToolchain_Linux/v26_clang-20.1.8-rockylinux8.exe",
+ "installer_bytes": 1014385664,
+ "installer_sha256": "02dee9f48cc65c5abbc9cc429271115f1cce68ebcef632db42ba4b5c9dbe2088",
+ "install_root": "C:/UnrealToolchains",
+ "clang_version": "20.1.8",
+ "engine_component": "Engine/Binaries/Linux/UnrealGame.target"
},
"disk": {
"min_free_gb": 40
+ },
+ "docker": {
+ "min_version": "27.0",
+ "smoke_base_image": "ubuntu:24.04"
}
}