A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Steam: --steam content folders, the nightly's Steam stage, a draft-release hand-over and the CI upload job (Refs #2155) (#2164)
Eyal Golane5673d04a7c3
diff --git a/.github/workflows/steam-upload.yml b/.github/workflows/steam-upload.ymlnew file mode 100644index 000000000..baaa6c64b--- /dev/null+++ b/.github/workflows/steam-upload.yml@@ -0,0 +1,195 @@+name: Steam upload++# Uploads one release's or one nightly's Steam players to a Steam branch (plan+# docs/superpowers/plans/2026-11-01-steamworks-integration.md Task 8, #2155; spec+# docs/superpowers/specs/2026-11-01-steamworks-integration-design.md; owner answers Q7 "Also nightlies" and Q8 "GitHub+# Actions", 1 Nov 2026). The players are built on the owner's Mac (Unity never runs here, decision O7) by+# `tools/release_build.py --steam`; `tools/steam_upload.py stage` attaches them to a DRAFT release `steam-<tag>` that is+# never published, with steam-record.json (tag, commit, branch, each zip's SHA-256), and dispatches this workflow.+#+# Trust: this is the only workflow that holds secrets (scripts/oss/tests/test_github_config.py names it as the one+# exception). It runs on workflow_dispatch only: never on a pull request, a fork, a push or a release event, and only+# someone with write access can dispatch it. Its one job uses the environment `steam`, whose deployment branches the+# owner limits to `main`, so a run from any other ref never receives the secrets. The two secrets, the builder+# account's name and steamcmd's cached login (base64 of config/config.vdf, made once by the owner on their own+# machine; no password exists anywhere in CI), are created by the owner only (#2151), reach only the two login steps,+# and only through env:. The cached login file is always deleted at the end. Nothing here prints a secret; GitHub masks+# them in the log as well. Every input is checked before use, and every action is pinned to a commit SHA.+#+# The draft can be edited by anyone with push access after `stage` made it, so the job trusts steam-record.json only+# when its SHA-256 equals the `record_sha256` input, which `stage` computed on the owner's Mac and put in the dispatch;+# the record then pins every zip's SHA-256 (review of #2155). steamcmd itself is trusted as Valve serves it over TLS: its+# bootstrap tarball's SHA-256 is printed for the record, not compared, because Valve republishes it and steamcmd updates+# itself from Valve on its first run anyway.+#+# What it never does: build or run the game, publish a release, set the `default` branch live (Valve does not allow+# it from a build script; the owner does it in App Admin), or upload a draft whose files differ from its record or+# whose commit is not on main.+#+# The one GitHub fact this relies on, read 1 Nov 2026: "List releases" says "Only users with push access will receive+# listings for draft releases" (https://docs.github.com/en/rest/releases/releases), and the workflow syntax's+# permissions table says `contents: write` lets a job publish a new release, which needs push access to the repository;+# the release and release-asset endpoints are under the Contents permission+# (https://docs.github.com/en/rest/authentication/permissions-required-for-github-apps). So this job's token, with+# `contents: write`, can list and download the draft's assets and delete the draft. The first real upload (plan+# Task 10 step 3) confirms it in practice.+#+# Valve facts, read 1 Nov 2026 from https://partner.steamgames.com/doc/sdk/uploading: a build machine keeps steamcmd's+# config/config.vdf between runs and logs in without a password; SetLive names a beta branch and "the 'default' branch+# can not be set live automatically". steamcmd's Linux download URL and its success line ("Successfully finished AppID+# ... build") are not on that page: the URL is the one Valve's SteamCMD wiki gives+# (https://developer.valvesoftware.com/wiki/SteamCMD, which refused an automated read on 1 Nov 2026), so a maintainer+# confirms both, and where steamcmd keeps config.vdf on Linux ($HOME/Steam/config), on the first run (Task 10 step 3).++on:+ workflow_dispatch:+ inputs:+ tag:+ description: "The release or nightly tag (vX.Y.Z) whose draft steam-<tag> to upload"+ required: true+ type: string+ branch:+ description: "The Steam branch to set live (never default)"+ required: true+ type: choice+ options:+ - beta+ - nightly+ record_sha256:+ description: "SHA-256 of the draft's steam-record.json, from tools/steam_upload.py stage"+ required: true+ type: string++permissions: {}++env:+ UV_PYTHON: "3.12"++concurrency:+ group: steam-upload+ cancel-in-progress: false++jobs:+ upload:+ name: Steam upload+ runs-on: ubuntu-24.04+ timeout-minutes: 90+ # Only the owner's own dispatch on main (tools/steam_upload.py stage, by hand or from the nightly, runs as the owner);+ # the environment's branch policy is a repository setting this file cannot check (review of #2155).+ if: github.ref == 'refs/heads/main' && github.triggering_actor == github.repository_owner+ environment: steam+ permissions:+ contents: write+ defaults:+ run:+ shell: bash+ steps:+ - name: The inputs, checked before anything uses them+ env:+ TAG: ${{ inputs.tag }}+ BRANCH: ${{ inputs.branch }}+ RECORD_SHA256: ${{ inputs.record_sha256 }}+ run: |+ if [[ ! $TAG =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then echo "::error::not a vX.Y.Z tag"; exit 1; fi+ if [[ ! $BRANCH =~ ^(beta|nightly)$ ]]; then echo "::error::the branch is beta or nightly"; exit 1; fi+ if [[ ! $RECORD_SHA256 =~ ^[0-9a-f]{64}$ ]]; then echo "::error::record_sha256 is not a SHA-256"; exit 1; fi+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ ref: main+ fetch-depth: 0+ persist-credentials: false+ - uses: astral-sh/setup-uv@1c37ad07a6a961277cf70c0d37d6f313000f5884 # v10.3.0+ with:+ version: "0.12.5"+ enable-cache: false+ - name: Download the draft and check it against its record+ id: draft+ env:+ GH_TOKEN: ${{ github.token }}+ TAG: ${{ inputs.tag }}+ BRANCH: ${{ inputs.branch }}+ RECORD_SHA256: ${{ inputs.record_sha256 }}+ run: |+ gh release view "steam-$TAG" --repo "$GITHUB_REPOSITORY" --json isDraft --jq .isDraft | grep -qx true \+ || { echo "::error::steam-$TAG is not a draft release"; exit 1; }+ gh release download "steam-$TAG" --repo "$GITHUB_REPOSITORY" --dir "$RUNNER_TEMP/draft"+ commit=$(uv run --no-project tools/steam_upload.py verify --dir "$RUNNER_TEMP/draft" --tag "$TAG" --branch "$BRANCH" --record-sha256 "$RECORD_SHA256")+ echo "commit=$commit" >> "$GITHUB_OUTPUT"+ - name: The record's commit is on main+ env:+ COMMIT: ${{ steps.draft.outputs.commit }}+ run: |+ git merge-base --is-ancestor "$COMMIT" refs/remotes/origin/main \+ || { echo "::error::$COMMIT is not on main"; exit 1; }+ - name: Unpack the content and render the SteamPipe scripts+ id: render+ env:+ TAG: ${{ inputs.tag }}+ BRANCH: ${{ inputs.branch }}+ COMMIT: ${{ steps.draft.outputs.commit }}+ run: |+ for platform in windows mac linux; do+ unzip -q "$RUNNER_TEMP/draft/steam-$TAG-$platform.zip" -d "$RUNNER_TEMP/steam/content/$platform"+ done+ app=$(uv run --no-project tools/steam_upload.py render --root "$RUNNER_TEMP/steam/content" --tag "$TAG" --commit "$COMMIT" --branch "$BRANCH")+ echo "app_vdf=$app" >> "$GITHUB_OUTPUT"+ - name: Fetch steamcmd from Valve+ run: |+ sudo apt-get update -q && sudo apt-get install -y -q --no-install-recommends lib32gcc-s1+ mkdir -p "$RUNNER_TEMP/steamcmd"+ curl -fsSL -o "$RUNNER_TEMP/steamcmd_linux.tar.gz" https://steamcdn-a.akamaihd.net/client/installer/steamcmd_linux.tar.gz+ sha256sum "$RUNNER_TEMP/steamcmd_linux.tar.gz"+ tar -xzf "$RUNNER_TEMP/steamcmd_linux.tar.gz" -C "$RUNNER_TEMP/steamcmd"+ - name: Restore the builder login (owner's secret)+ env:+ STEAM_CONFIG_VDF: ${{ secrets.STEAM_CONFIG_VDF }}+ run: |+ umask 077+ # Where the tarball's steamcmd keeps config/ is confirmed on the first run; both candidates get the cache and+ # the cleanup step removes both.+ for dir in "$HOME/Steam/config" "$RUNNER_TEMP/steamcmd/config"; do+ mkdir -p "$dir"+ done+ printf '%s' "$STEAM_CONFIG_VDF" | base64 -d > "$HOME/Steam/config/config.vdf"+ cp "$HOME/Steam/config/config.vdf" "$RUNNER_TEMP/steamcmd/config/config.vdf"+ chmod 600 "$HOME/Steam/config/config.vdf" "$RUNNER_TEMP/steamcmd/config/config.vdf"+ - name: Upload with steamcmd (owner's builder account)+ env:+ STEAM_BUILDER_USERNAME: ${{ secrets.STEAM_BUILDER_USERNAME }}+ APP_VDF: ${{ steps.render.outputs.app_vdf }}+ run: |+ set -o pipefail+ "$RUNNER_TEMP/steamcmd/steamcmd.sh" +@NoPromptForPassword 1 +login "$STEAM_BUILDER_USERNAME" \+ +run_app_build "$APP_VDF" +quit | tee "$RUNNER_TEMP/steamcmd.log"+ grep -q "Successfully finished AppID" "$RUNNER_TEMP/steamcmd.log" \+ || { echo "::error::SteamPipe did not report a finished build; a login failure means the owner re-provisions the secret"; exit 1; }+ - name: Delete the cached login and steamcmd+ if: always()+ run: |+ rm -f "$HOME/Steam/config/config.vdf" "$RUNNER_TEMP/steamcmd/config/config.vdf"+ rm -rf "$HOME/Steam" "$HOME/.steam" "$RUNNER_TEMP/steamcmd" "$RUNNER_TEMP/steam"+ - name: Delete the draft after a successful upload+ if: success()+ env:+ GH_TOKEN: ${{ github.token }}+ TAG: ${{ inputs.tag }}+ run: |+ if [ "$(gh release view "steam-$TAG" --repo "$GITHUB_REPOSITORY" --json isDraft --jq .isDraft)" = true ]; then+ gh release delete "steam-$TAG" --repo "$GITHUB_REPOSITORY" --yes+ else+ echo "::warning::steam-$TAG is no longer a draft; left alone"+ fi++ refused:+ # A dispatch the owner-on-main guard turns away fails here, visibly, instead of showing a green skipped job. It has+ # no environment, no permissions and no secret.+ name: Steam upload (refused)+ if: "!(github.ref == 'refs/heads/main' && github.triggering_actor == github.repository_owner)"+ runs-on: ubuntu-24.04+ timeout-minutes: 5+ permissions: {}+ steps:+ - name: Refuse+ run: |+ echo "::error::the Steam upload runs only for the repository owner's own dispatch on main"+ exit 1diff --git a/docs/RELEASING.md b/docs/RELEASING.mdindex 57f55cc65..959531481 100644--- a/docs/RELEASING.md+++ b/docs/RELEASING.md@@ -267,6 +267,16 @@ The no-change skip compares `state.json`'s last published SHA with `origin/main`A night that starts after 03:30 is MISSED unless it was started by hand with `--manual`.+**Steam (the `steam` stage, #2155).** Only after the web nightly is published (`publish_night` returned), the nightly+fetches tonight's tag into its clone, runs `uv run tools/release_build.py --platform all --steam --tag <tag>+--nightly-version <X.Y.Z> --out <run folder>/steam-release` (each Unity build stamped with tonight's version, as the web+builds are) and then `uv run tools/steam_upload.py stage --out <run folder>/steam-release --tag <tag>`, which attaches+the Steam content to a never-published draft release `steam-<tag>` and starts `steam-upload.yml` for the `nightly`+branch. A failure there never refuses, unpublishes or rolls back the web nightly: the night stays `PUBLISHED`, its+line ends with `steam=failed` (the `steam-build.log` and `steam-stage.log` are in the run folder) and a notification+is shown. The stage is skipped while `steam/steam.json` still has a `null` ID (until the owner has created the app,+#2151), and with `uv run tools/nightly.py run --no-steam`.+**itch.io.** Pushes stay off until the owner runs `uv run tools/nightly.py savetest --tag <a published nightly>` onceand it prints `PASS` (the two-upload save test of `docs/m3-release.md`, "Upload to itch.io"); the nightly then logsthat itch was skipped. The save test pushes only to a separate test page, named in the job's `config.json` asdiff --git a/scripts/oss/tests/test_github_config.py b/scripts/oss/tests/test_github_config.pyindex 62e166401..c716720ca 100644--- a/scripts/oss/tests/test_github_config.py+++ b/scripts/oss/tests/test_github_config.py@@ -54,6 +54,16 @@ def test_ci_uses_no_secret_but_the_read_only_token():assert set(re.findall(r"\$\{\{\s*github\.token\s*\}\}", text)) <= {"${{ github.token }}"}+# The one named exception to "no secrets in workflows": the Steam upload (plan 2026-11-01-steamworks-integration Task 8,+# owner answer Q8 "GitHub Actions"). Its two secrets live in the `steam` environment, which only `main` may deploy.+SECRET_WORKFLOWS = {"steam-upload.yml"}+++def test_the_secret_exception_names_only_steam_upload():+ users = {wf.name for wf in (ROOT / ".github/workflows").glob("*.yml") if "secrets." in wf.read_text(encoding="utf-8")}+ assert users <= SECRET_WORKFLOWS, users++def test_every_action_is_pinned_to_a_full_sha():for wf in (ROOT / ".github/workflows").glob("*.yml"):for ref in re.findall(r"uses:\s*[\w.-]+/[\w./-]+@(\S+)", wf.read_text(encoding="utf-8")):@@ -192,3 +202,119 @@ def test_the_reviewed_by_guard_runs_on_the_pr_head_with_full_history():assert '--base "$BASE_SHA"' in step["run"] and '--head "$HEAD_SHA"' in step["run"]assert step["env"]["HEAD_SHA"] == "${{ github.event.pull_request.head.sha }}"assert step["env"]["BASE_SHA"] == "${{ github.event.pull_request.base.sha }}"+++STEAM = ROOT / ".github/workflows/steam-upload.yml"+STEAM_SECRETS = {"STEAM_BUILDER_USERNAME", "STEAM_CONFIG_VDF"}+STEAM_LOGIN_STEPS = {"Restore the builder login (owner's secret)", "Upload with steamcmd (owner's builder account)"}+++def steam():+ return yaml.safe_load(STEAM.read_text(encoding="utf-8"))+++def test_steam_upload_runs_only_on_dispatch():+ # Plan Task 8: a pull request, a fork, a release event or a push never starts an upload; only someone with write+ # access dispatches it (tools/steam_upload.py stage does, on the owner's Mac).+ t = triggers(steam())+ assert set(t) == {"workflow_dispatch"}+ for name in ("push", "pull_request", "pull_request_target", "release", "schedule", "workflow_run"):+ assert name not in t+++def test_steam_upload_uses_the_steam_environment_and_minimal_permissions():+ wf = steam()+ assert wf["permissions"] == {}+ assert set(wf["jobs"]) == {"upload", "refused"}+ job = wf["jobs"]["upload"]+ assert job["environment"] == "steam" and job["permissions"] == {"contents": "write"}+ assert job["runs-on"] == "ubuntu-24.04" and job["timeout-minutes"] <= 120+ for s in job["steps"]:+ if s.get("uses", "").startswith("actions/checkout@"):+ assert s["with"]["persist-credentials"] is False and s["with"]["ref"] == "main", s+ assert "${{" not in s.get("run", ""), s # inputs, outputs and secrets reach the shell only through env:+ assert "set -x" not in s.get("run", ""), s+ for ref_line in re.findall(r"uses:\s*[\w.-]+/[\w./-]+@[0-9a-f]{40}.*", STEAM.read_text(encoding="utf-8")):+ assert re.search(r"# v\d+\.\d+\.\d+$", ref_line), ref_line+++def test_steam_upload_branch_input_is_beta_or_nightly():+ inputs = triggers(steam())["workflow_dispatch"]["inputs"]+ assert set(inputs) == {"tag", "branch", "record_sha256"}+ assert inputs["branch"]["type"] == "choice" and inputs["branch"]["options"] == ["beta", "nightly"]+ assert inputs["tag"]["required"] is True and inputs["branch"]["required"] is True+ first = steam()["jobs"]["upload"]["steps"][0]+ assert "^v[0-9]+\\.[0-9]+\\.[0-9]+$" in first["run"] and "^(beta|nightly)$" in first["run"]+++def test_steam_secrets_appear_only_in_the_login_steps():+ job = steam()["jobs"]["upload"]+ using = {}+ for s in job["steps"]:+ text = yaml.safe_dump(s)+ found = set(re.findall(r"secrets\.(\w+)", text))+ if found:+ using[s.get("name")] = found+ assert all(f"${{{{ secrets.{n} }}}}" in s.get("env", {}).values() for n in found), s # only through env:+ assert set(using) == STEAM_LOGIN_STEPS and set().union(*using.values()) == STEAM_SECRETS+ text = STEAM.read_text(encoding="utf-8")+ assert "secrets: inherit" not in text and "toJSON(secrets)" not in text+ # The login config is always deleted, the upload fails without SteamPipe's success line, and the draft goes only+ # after a successful upload.+ names = [s.get("name", s.get("uses")) for s in job["steps"]]+ cleanup = next(s for s in job["steps"] if "config.vdf" in s.get("run", "") and s.get("if") == "always()")+ assert names.index(cleanup["name"]) > names.index("Upload with steamcmd (owner's builder account)")+ upload = next(s for s in job["steps"] if s.get("name") == "Upload with steamcmd (owner's builder account)")+ assert "+@NoPromptForPassword 1" in upload["run"] and '+login "$STEAM_BUILDER_USERNAME"' in upload["run"]+ assert "Successfully finished AppID" in upload["run"]+ delete = next(s for s in job["steps"] if "gh release delete" in s.get("run", ""))+ assert delete.get("if", "success()") == "success()" and names.index(delete["name"]) > names.index(cleanup["name"])+++def test_steam_upload_checks_the_draft_and_the_commit_before_any_login():+ job = steam()["jobs"]["upload"]+ names = [s.get("name", s.get("uses")) for s in job["steps"]]+ verify = next(s for s in job["steps"] if "steam_upload.py verify" in s.get("run", ""))+ on_main = next(s for s in job["steps"] if "merge-base --is-ancestor" in s.get("run", ""))+ render = next(s for s in job["steps"] if "steam_upload.py render" in s.get("run", ""))+ login = names.index("Restore the builder login (owner's secret)")+ assert names.index(verify["name"]) < names.index(on_main["name"]) < names.index(render["name"]) < login+ assert "refs/remotes/origin/main" in on_main["run"]+++def test_steam_upload_runs_only_for_the_owner_on_main():+ # Review I1 (#2155): the environment's branch policy is a repository setting the workflow cannot see; the job also+ # refuses itself any run not started by the repository owner (stage and the nightly dispatch as the owner) on main.+ guard = steam()["jobs"]["upload"]["if"]+ assert "github.ref == 'refs/heads/main'" in guard+ assert "github.triggering_actor == github.repository_owner" in guard and "&&" in guard+++def test_steam_upload_record_hash_comes_from_the_dispatch():+ # Review (a review agent, k2 C1): the draft can be edited after stage; the dispatch input cannot.+ inputs = triggers(steam())["workflow_dispatch"]["inputs"]+ assert inputs["record_sha256"]["required"] is True+ first = steam()["jobs"]["upload"]["steps"][0]+ assert "^[0-9a-f]{64}$" in first["run"] and first["env"]["RECORD_SHA256"] == "${{ inputs.record_sha256 }}"+ verify = next(s for s in steam()["jobs"]["upload"]["steps"] if "steam_upload.py verify" in s.get("run", ""))+ assert '--record-sha256 "$RECORD_SHA256"' in verify["run"]+++def test_a_refused_steam_upload_fails_loudly():+ # Review (k2 C4): a run the guard refuses must fail, not show a green skipped job.+ jobs = steam()["jobs"]+ refused = jobs["refused"]+ assert refused["if"] == "!(" + jobs["upload"]["if"] + ")"+ assert "environment" not in refused and refused["permissions"] == {}+ assert any("exit 1" in s.get("run", "") for s in refused["steps"])+ assert "secrets." not in yaml.safe_dump(refused)+++def test_the_login_cache_is_written_where_either_steamcmd_layout_reads_it():+ # Review (k2 H1): where the tarball's steamcmd keeps config/ is unconfirmed; both candidates get it and both go.+ job = steam()["jobs"]["upload"]+ restore = next(s for s in job["steps"] if s.get("name") == "Restore the builder login (owner's secret)")+ for path in ('"$HOME/Steam/config/config.vdf"', '"$RUNNER_TEMP/steamcmd/config/config.vdf"'):+ assert path in restore["run"]+ cleanup = next(s for s in job["steps"] if s.get("if") == "always()")+ assert '"$HOME/Steam"' in cleanup["run"] and '"$RUNNER_TEMP/steamcmd"' in cleanup["run"]diff --git a/steam/app_build.vdf.in b/steam/app_build.vdf.innew file mode 100644index 000000000..702b837f2--- /dev/null+++ b/steam/app_build.vdf.in@@ -0,0 +1,13 @@+"AppBuild"+{+ "AppID" "${app_id}"+ "Desc" "${desc}"+ "ContentRoot" "${content_root}"+ "BuildOutput" "${build_output}"+ "SetLive" "${branch}"+ "Preview" "0"+ "Depots"+ {+${depots}+ }+}diff --git a/steam/depot_build.vdf.in b/steam/depot_build.vdf.innew file mode 100644index 000000000..9404330db--- /dev/null+++ b/steam/depot_build.vdf.in@@ -0,0 +1,10 @@+"DepotBuild"+{+ "DepotID" "${depot_id}"+ "FileMapping"+ {+ "LocalPath" "${platform}/*"+ "DepotPath" "."+ "Recursive" "1"+ }+}diff --git a/steam/steam.json b/steam/steam.jsonnew file mode 100644index 000000000..858ad2cf4--- /dev/null+++ b/steam/steam.json@@ -0,0 +1 @@+{"app_id": null, "depots": {"windows": null, "mac": null, "linux": null}, "branches": ["beta", "nightly"]}diff --git a/tools/nightly.py b/tools/nightly.pyindex 6c9216962..202b9b350 100644--- a/tools/nightly.py+++ b/tools/nightly.py@@ -774,6 +774,64 @@ def publish_night(night: Night, state: State, gh: GitHub, itch, zips: tuple[Pathraise+# --- the Steam stage (plan 2026-11-01-steamworks-integration Task 7, #2155; owner answer Q7 "Also nightlies") ------++STEAM_BUILD_MINUTES = 240 # three Unity players and the macOS golden check+STEAM_STAGE_MINUTES = 60 # zips, the draft release upload and the workflow dispatch+++def steam_ids_missing(clone: Path) -> str | None:+ """Why the Steam stage cannot run yet, or None: steam/steam.json must name the app and every depot."""+ path = clone / "steam/steam.json"+ try:+ config = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, ValueError) as e:+ return f"cannot read {path}: {type(e).__name__}"+ if not isinstance(config, dict) or not isinstance(config.get("depots"), dict):+ raise ValueError(f"{path} is not an object with a depots object")+ depots = config["depots"]+ missing = [name for name, value in [("app_id", config.get("app_id")),+ *((f"depots.{p}", depots.get(p)) for p in ("windows", "mac", "linux"))]+ if value is None]+ return f"steam/steam.json has no {', '.join(missing)} yet" if missing else None+++def run_steam(night: Night, runner: Runner) -> None:+ """After the web nightly is published: build the Steam players, stage them in a draft release and dispatch the+ upload to the `nightly` branch. It never refuses, unpublishes or rolls back the web nightly: any failure only adds+ steam=failed to the night's line (the logs are in the run folder) and notifies."""+ out = night.run_dir / "steam-release"+ try:+ if (why := steam_ids_missing(night.cfg.clone)) is not None:+ print(f"steam: skipped ({why})")+ return+ check_window(night)+ # tonight's tag was made on GitHub by the publish; release_build.py checks it points at HEAD and never fetches+ _git(runner, night.cfg.clone, "fetch", "--no-tags", "origin", f"refs/tags/{night.tag}:refs/tags/{night.tag}")+ code, _ = _step(night, runner, "steam-build",+ ["uv", "run", "tools/release_build.py", "--platform", "all", "--steam", "--tag", night.tag,+ "--nightly-version", night.version, "--out", str(out)], STEAM_BUILD_MINUTES,+ unity_env(night), stop_on_interrupt=True)+ if code != 0:+ raise Refused("steam", "release_build.py timed out" if code == 124 else f"release_build.py exited {code}")+ code, _ = _step(night, runner, "steam-stage",+ ["uv", "run", "tools/steam_upload.py", "stage", "--out", str(out), "--tag", night.tag],+ STEAM_STAGE_MINUTES, stop_on_interrupt=True)+ if code != 0:+ raise Refused("steam", "steam_upload.py timed out" if code == 124 else f"steam_upload.py exited {code}")+ except Exception as e:+ detail = _detail(e)+ print(f"steam: failed: {detail}", file=sys.stderr)+ night.notes.append("steam=failed")+ notify("Nightly Steam stage failed", f"{night.tag} is published; Steam: {detail}; logs in {night.run_dir}"[:200])+ finally:+ # Nothing prunes the run folders, and three players and their zips a night would eat the free space the next+ # web nightly's disk gate needs (review of #2155). The draft holds the zips; the record and the logs stay.+ shutil.rmtree(out / "steam", ignore_errors=True)+ for z in out.glob("steam-*.zip"):+ z.unlink(missing_ok=True)++# --- the night --------------------------------------------------------------------------------------------------def _build_both(night: Night, runner: Runner, free_gb: Callable[[Path], float]) -> tuple[Path, Path]:@@ -800,8 +858,9 @@ def _build_both(night: Night, runner: Runner, free_gb: Callable[[Path], float])def run_stages(night: Night, state: State, runner: Runner, gh: GitHub, itch, *, no_publish: bool,free_gb: Callable[[Path], float] = lambda p: shutil.disk_usage(p).free / 1e9,- save: Callable[[], bool | None] = lambda: None) -> bool:- """Every gate, then (unless no_publish) the publish. True when published, False when stopped before any store."""+ save: Callable[[], bool | None] = lambda: None, no_steam: bool = False) -> bool:+ """Every gate, then (unless no_publish) the publish, then (unless no_steam) the Steam stage. True when published,+ False when stopped before any store."""run_gates(night, runner)run_editmode(night, runner)gz, pages = _build_both(night, runner, free_gb)@@ -821,6 +880,10 @@ def run_stages(night: Night, state: State, runner: Runner, gh: GitHub, itch, *,print(f"NO-PUBLISH: all gates passed for {night.tag}")return Falsepublish_night(night, state, gh, itch, zips, sizes, boot, previous=previous, save=save, runner=runner)+ if no_steam:+ print("steam: skipped (--no-steam)")+ else:+ run_steam(night, runner)return True@@ -836,7 +899,8 @@ def _try_save(state_path: Path, state: State) -> bool:def run_night(cfg: Config, state_path: Path, job: Path, runner: Runner, gh: GitHub | None, itch, *, now: datetime,manual: bool, no_publish: bool, client_error: Refused | None = None,- free_gb: Callable[[Path], float] = lambda p: shutil.disk_usage(p).free / 1e9) -> str:+ free_gb: Callable[[Path], float] = lambda p: shutil.disk_usage(p).free / 1e9,+ no_steam: bool = False) -> str:outcome, gate, detail = "REFUSED", "internal", ""state: State | None = Nonenight: Night | None = None@@ -863,7 +927,7 @@ def run_night(cfg: Config, state_path: Path, job: Path, runner: Runner, gh: GitHnight = preflight(cfg, state, runner, gh, job=job, now=now, manual=manual, free_gb=free_gb,no_publish=no_publish)published = run_stages(night, state, runner, gh, itch, no_publish=no_publish, free_gb=free_gb,- save=lambda: _try_save(state_path, state))+ save=lambda: _try_save(state_path, state), no_steam=no_steam)outcome, gate = ("PUBLISHED" if published else "NO-PUBLISH"), "-"except Stop as e:outcome, gate, detail = e.outcome, e.gate, e.detail@@ -1121,6 +1185,7 @@ def main(argv: list[str] | None = None) -> int:run = sub.add_parser("run")run.add_argument("--manual", action="store_true")run.add_argument("--no-publish", action="store_true")+ run.add_argument("--no-steam", action="store_true", help="skip the Steam stage after the web publish")test = sub.add_parser("savetest", help="the two-upload itch.io save test: pushes twice to the separate test page, never the public one")test.add_argument("--tag", required=True, help="a published nightly release tag")args = parser.parse_args(argv)@@ -1148,7 +1213,7 @@ def main(argv: list[str] | None = None) -> int:gh = itch = Noneclient_error = eoutcome = run_night(cfg, job / "state.json", job, ProcRunner(), gh, itch, now=now, manual=args.manual,- no_publish=args.no_publish, client_error=client_error)+ no_publish=args.no_publish, client_error=client_error, no_steam=args.no_steam)print(outcome)return 1 if outcome == "REFUSED" else 0diff --git a/tools/release_build.py b/tools/release_build.pyindex ff6d812ad..f844fe710 100644--- a/tools/release_build.py+++ b/tools/release_build.py@@ -7,7 +7,7 @@ plan in PR #482, specdocs/superpowers/specs/2026-10-14-desktop-builds-and-release-pipeline.md, sections 6.4 and 6.5).Usage: uv run tools/release_build.py [--platform mac|linux|windows|all] [--out DIR] [--tag vX.Y.Z] [--dev] [--dry-run]- [--unity PATH]+ [--unity PATH] [--steam [--nightly-version X.Y.Z]]- Refuses, before anything is built (spec 6.4 step 1):- a dirty working tree (tracked changes or untracked files);@@ -46,6 +46,20 @@ by accident. Build records live in the owner'sseparate records repository (decision O12): this script never commits, pushes or uploads anything; it prints where therecord is, and the owner copies it.+Steam (plan docs/superpowers/plans/2026-11-01-steamworks-integration.md Task 7, #2155; spec+docs/superpowers/specs/2026-11-01-steamworks-integration-design.md):+- --steam passes -steam to every Unity build (only those players carry Valve's library) and writes+ <out>/steam/<platform>/ (the player folder plus the notices, no archive): the ContentBuilder content that+ tools/steam_upload.py stage zips for the CI upload. The record says "steam": true, "channel": "beta" (or "nightly")+ and "dev"; tools/steam_upload.py refuses a dev record. A Steam folder holding steam_appid.txt is refused.+- --nightly-version X.Y.Z (with --steam only) is the nightly's Steam stage (tools/nightly.py): the tag must be vX.Y.Z,+ the tree may differ from HEAD only by the nightly's bundleVersion stamp to X.Y.Z (tools/nightly.py+ stamp_bundle_version), every build is stamped again before it starts (the settings are restored after each one),+ and the record says "channel": "nightly".+- A GitHub/itch archive (no --steam) is refused when it lists any Valve file (VALVE_FILES), the macOS steam_api.bundle+ directory included. This is a backstop: the -steam build switch already leaves the plugins out of other players, so+ nothing is deleted after a build and a macOS signature is never broken.+Exit 0 when every build succeeded and every check that ran passed; 1 on a refusal, a failed build or a failed golden(the record is still written for a failed golden); 2 when the editor or a module is missing."""@@ -84,6 +98,14 @@ PHOTOS = "event-photos.json" # Build.PhotoManifestName: written beside every p# cannot drift (issue #546). {tag} carries the v. The CI check names the Mac "macos".ARCHIVES = {"mac": pgc.ASSETS["macos"], "linux": pgc.ASSETS["linux"], "windows": pgc.ASSETS["windows"]}TAG = pgc.TAG+# Valve's redistributables. The macOS plugin is a bundle directory, so a zip lists .../steam_api.bundle/ and files in it.+VALVE_FILES = re.compile(r"(^|/)(lib)?steam_api(64)?\.(dll|so|dylib)$|(^|/)steam_api\.bundle(/|$)|(^|/)steam_appid\.txt$")+APPID_FILE = re.compile(r"(^|/)steam_appid\.txt$")+# The library each platform's Steam player must carry (only -steam builds include it; #2154).+STEAM_LIBRARY = {"windows": re.compile(r"(^|/)steam_api64\.dll$"), "linux": re.compile(r"(^|/)libsteam_api\.so$"),+ "mac": re.compile(r"(^|/)steam_api\.bundle(/|$)")}+NIGHTLY_VERSION = re.compile(r"[0-9]+\.[0-9]+\.[0-9]+", re.ASCII)+SETTINGS_ASSET = "unity/ProjectSettings/ProjectSettings.asset"@dataclass(frozen=True)@@ -136,6 +158,9 @@ def parse(argv: list[str]) -> argparse.Namespace:"v<bundleVersion>)")ap.add_argument("--unity", type=Path, default=None, help="the Unity executable (default: the Hub path of the ""version in ProjectVersion.txt)")+ ap.add_argument("--steam", action="store_true", help="Steam players (-steam) in <out>/steam/<platform>/, no archive")+ ap.add_argument("--nightly-version", default=None, metavar="X.Y.Z",+ help="with --steam: the nightly's Steam build, stamped with this bundleVersion")return ap.parse_args(argv)@@ -237,12 +262,14 @@ def locked(cmd: list, wait_unity: bool) -> list[str]:return [*head, "--timeout", str(LOCK_TIMEOUT), "--", *[str(c) for c in cmd]]-def build_command(unity: Path, p: Platform, target: Path, log: Path, shareable: bool) -> list[str]:+def build_command(unity: Path, p: Platform, target: Path, log: Path, shareable: bool, steam: bool = False) -> list[str]:cmd = [str(unity), "-batchmode", "-CI", "false", "-GITHUB_ACTIONS", "false", "-TF_BUILD", "false", "-quit","-projectPath", str(REPO / "unity"), "-buildTarget", p.build_target, "-executeMethod", METHOD + p.method,"-out", str(target), "-logFile", str(log)]if shareable:cmd.append("-shareable")+ if steam:+ cmd.append("-steam")return locked(cmd, wait_unity=True)@@ -299,12 +326,52 @@ def add_notices(folder: Path) -> None:(folder / name).write_bytes(src.read_bytes())-def archive_names(archive: Path) -> list[str]:+def archive_names(archive: Path, dirs: bool = False) -> list[str]:if archive.name.endswith(".tar.gz"):with tarfile.open(archive) as t:- return [m.name for m in t.getmembers() if not m.isdir()]+ return [m.name + ("/" if m.isdir() else "") for m in t.getmembers() if dirs or not m.isdir()]with zipfile.ZipFile(archive) as z:- return [n for n in z.namelist() if not n.endswith("/")]+ return [n for n in z.namelist() if dirs or not n.endswith("/")]+++def refuse_valve_files(names: list[str]) -> str | None:+ """Why a non-Steam archive with this listing (directories included) must not ship, or None."""+ found = [n for n in names if VALVE_FILES.search(n)]+ return ("it carries Valve files, which only Steam builds may ship: " + ", ".join(found)) if found else None+++def steam_folder_problem(folder: Path, platform: str) -> str | None:+ """Why a Steam content folder must not be uploaded, or None: steam_appid.txt is for local runs only (with it,+ the player never relaunches through Steam), and a player without Valve's library was not built with -steam."""+ names = [p.relative_to(folder).as_posix() for p in sorted(folder.rglob("*"))]+ found = [n for n in names if APPID_FILE.search(n)]+ if found:+ return f"{folder} holds {', '.join(found)}, which must never be uploaded to Steam"+ if not any(STEAM_LIBRARY[platform].search(n) for n in names):+ return (f"{folder} has no Steam library ({STEAM_LIBRARY[platform].pattern}); the player was not built with "+ "Steam (the -steam build switch, #2154)")+ return None+++def stamp_problem(lines: list[str], version: str) -> str | None:+ """None when the tree differs from HEAD only by the nightly's bundleVersion stamp to `version` (or not at all)."""+ if not lines:+ return None+ if lines != [f" M {SETTINGS_ASSET}"]:+ return "the tree has changes besides the nightly's bundleVersion stamp:\n" + "\n".join(" " + l for l in lines)+ head = git("show", f"HEAD:{SETTINGS_ASSET}")+ if head.returncode != 0:+ return f"cannot read {SETTINGS_ASSET} at HEAD"+ expected, n = re.subn(r"^( bundleVersion: )\S+$", lambda m: m.group(1) + version, head.stdout, flags=re.M)+ if n != 1 or (REPO / SETTINGS_ASSET).read_text() != expected:+ return f"{SETTINGS_ASSET} differs from HEAD by more than the bundleVersion stamp to {version}"+ return None+++def stamp(version: str) -> None:+ """The nightly's own stamp (tools/nightly.py), so the Steam players carry tonight's version; never committed."""+ from nightly import stamp_bundle_version # tools/: one stamp rule with the nightly's web builds+ stamp_bundle_version(REPO / SETTINGS_ASSET, version)def missing_notices(archive: Path) -> list[str]:@@ -394,13 +461,15 @@ def markdown(r: dict) -> str:f"- Date (UTC): {r['date_utc']}",f"- Unity: {r['unity']['version']} ({r['unity']['revision']})",f"- Version: bundleVersion {r['version']['bundle_version']}, SimInfo.Version {r['version']['sim_version']}",+ (f"- Steam content folders for the `{r['channel']}` branch (no archives)"+ + (f", nightly {r['nightly_version']}" if r["nightly_version"] else "") if r["steam"] else "- GitHub archives"),f"- Shareable build: {r['shareable']}" + ("" if r["shareable"] else " (a --dev build: not for sharing)"),f"- Signing: {r['signing']}", "","| Platform | Backend | Architecture | Archive | Archive bytes | Archive SHA-256 | Player files | Player bytes ""| File list SHA-256 | Golden |","| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |"]for a in r["artifacts"]:- ar = a["archive"]+ ar = a["archive"] or {"name": a["steam_folder"] + "/", "bytes": "-", "sha256": "-"} # a Steam folderout.append(f"| {a['platform']} | {a['backend']} | {a['architecture'] or '-'} | `{ar['name']}` | {ar['bytes']} | "f"`{ar['sha256']}` | {a['files']} | {a['bytes']} | `{a['file_list_sha256']}` | {a['golden']['status']} |")out.append("")@@ -423,6 +492,16 @@ def markdown(r: dict) -> str:def main(argv: list[str] | None = None) -> int:a = parse(sys.argv[1:] if argv is None else argv)names = selected(a)+ nightly = a.nightly_version+ if nightly is not None:+ if not a.steam or a.dev:+ print("REFUSED: --nightly-version is the nightly's Steam build: it needs --steam and takes no --dev.",+ file=sys.stderr)+ return 1+ if not NIGHTLY_VERSION.fullmatch(nightly) or a.tag != f"v{nightly}":+ print(f"REFUSED: --nightly-version takes X.Y.Z and --tag v<that version> (got {nightly!r} and {a.tag!r}).",+ file=sys.stderr)+ return 1version, revision = unity_version()unity = a.unity or Path(f"/Applications/Unity/Hub/Editor/{version}/Unity.app/Contents/MacOS/Unity")if not unity.is_file():@@ -441,7 +520,10 @@ def main(argv: list[str] | None = None) -> int:print(modules_message(missing, version), file=sys.stderr)return 2dirty = dirty_lines()- if dirty:+ if nightly is not None and (problem := stamp_problem(dirty, nightly)):+ print(f"REFUSED: {problem}", file=sys.stderr)+ return 1+ if dirty and nightly is None:print("REFUSED: the working tree is not clean. A build record names a commit, so build only a committed tree.\n"+ "\n".join(" " + l for l in dirty)+ "\nAfter a Unity run, `git checkout -- unity/Assets/Settings unity/ProjectSettings/ProjectSettings.asset` "@@ -456,6 +538,8 @@ def main(argv: list[str] | None = None) -> int:branch = git("rev-parse", "--abbrev-ref", "HEAD").stdout.strip()describe = git("describe", "--tags", "--always", "--dirty").stdout.strip()vers = versions()+ if nightly is not None:+ vers["bundle_version"] = nightly # every build is stamped with it belowstarted = utc_now()release = not a.devif release:@@ -497,14 +581,18 @@ def main(argv: list[str] | None = None) -> int:print(f"REFUSED: {out} exists and is not empty; a release folder starts empty.", file=sys.stderr)return 1shareable = release- plan = [(PLATFORMS[n], out / "players" / n / PLATFORMS[n].output, out / "logs" / f"unity-build-{n}.log") for n in names]+ players = out / ("steam" if a.steam else "players")+ plan = [(PLATFORMS[n], players / n / PLATFORMS[n].output, out / "logs" / f"unity-build-{n}.log") for n in names]sim = [sys.executable, str(REPO / "tools/build_sim_for_unity.py")]if a.dry_run:print("DRY RUN: nothing is built or written.\n" + " ".join(sim))for p, target, log in plan:- print(" ".join(f'"{c}"' if " " in c else c for c in build_command(unity, p, target, log, shareable)))+ if nightly is not None:+ print(f"stamp bundleVersion {nightly}")+ print(" ".join(f'"{c}"' if " " in c else c+ for c in build_command(unity, p, target, log, shareable, a.steam)))print("git checkout -- unity/ProjectSettings unity/Assets/Settings")- print(f"archive: {out / archive_name(tag, p.name)}")+ print(f"steam folder: {target.parent}" if a.steam else f"archive: {out / archive_name(tag, p.name)}")if p.runs_here:print(" ".join(golden_command(target / "Contents/MacOS/<CFBundleExecutable>", out / "logs/golden-mac.log")))print(f"record: {out / 'build-record.json'}")@@ -520,7 +608,9 @@ def main(argv: list[str] | None = None) -> int:print(f"release_build: building {p.name} ({p.backend}) -> {target}", flush=True)t0 = time.monotonic()try:- code = run(build_command(unity, p, target, log, shareable), cwd=REPO).returncode+ if nightly is not None:+ stamp(nightly) # restored by the checkout below, so each build stamps again+ code = run(build_command(unity, p, target, log, shareable, a.steam), cwd=REPO).returncodefinally:run(["git", "checkout", "--", "unity/ProjectSettings", "unity/Assets/Settings"], cwd=REPO)wall = round(time.monotonic() - t0)@@ -528,7 +618,10 @@ def main(argv: list[str] | None = None) -> int:if code != 0 or not target.exists():print(f"FAILED: the {p.name} build (exit {code}); see {log}", file=sys.stderr)return 1- folder = out / "players" / p.name+ folder = target.parent+ if a.steam and (problem := steam_folder_problem(folder, p.name)):+ print(f"FAILED: {problem}", file=sys.stderr)+ return 1add_notices(folder)text, files, size = tree_manifest(folder, mac=p.name == "mac")listing = out / f"files-{p.name}.sha256"@@ -541,11 +634,16 @@ def main(argv: list[str] | None = None) -> int:if problem := player_problem(p, folder):print(f"FAILED: {problem}", file=sys.stderr)return 1- archive = out / archive_name(tag, p.name)- make_archive(p, folder, target, archive)- if lacking := missing_notices(archive):- print(f"FAILED: {archive.name} lacks the notices {', '.join(lacking)}", file=sys.stderr)- return 1+ archive = None+ if not a.steam:+ archive = out / archive_name(tag, p.name)+ make_archive(p, folder, target, archive)+ if lacking := missing_notices(archive):+ print(f"FAILED: {archive.name} lacks the notices {', '.join(lacking)}", file=sys.stderr)+ return 1+ if problem := refuse_valve_files(archive_names(archive, dirs=True)):+ print(f"FAILED: {archive.name}: {problem}", file=sys.stderr)+ return 1arch = Noneif p.name == "mac":arch = run(["lipo", "-archs", str(mac_executable(target))], capture=True).stdout.strip() or None@@ -561,8 +659,10 @@ def main(argv: list[str] | None = None) -> int:artifacts.append({"platform": p.name, "build_target": p.build_target, "backend": p.backend,"architecture": arch, "build_method": METHOD + p.method,"path": str(target.relative_to(out)), "files": files, "bytes": size,- "archive": {"name": archive.name, "bytes": archive.stat().st_size,- "sha256": file_sha256(archive)},+ "archive": None if archive is None else {"name": archive.name,+ "bytes": archive.stat().st_size,+ "sha256": file_sha256(archive)},+ "steam_folder": folder.relative_to(out).as_posix() if a.steam else None,"file_list_sha256": file_sha256(listing), "file_list": listing.name,"photo_manifest": photos,"unity_build_seconds": unity_seconds(log_text), "wall_seconds_with_lock_wait": wall,@@ -571,17 +671,23 @@ def main(argv: list[str] | None = None) -> int:dirty_after = [l.strip() for l in dirty_lines()]record = {"schema": 1, "tool": "tools/release_build.py", "commit": commit,"describe": describe, "branch": branch, "release": release,- "tree_clean": True, # checked before the builds: a dirty tree is refused+ # checked before the builds: a dirty tree is refused (a nightly may carry only its own bundleVersion stamp)+ "tree_clean": True,"tree_clean_after_builds": not dirty_after, "dirty_after_builds": dirty_after,"date_utc": started.strftime("%Y-%m-%dT%H:%M:%SZ"), "unity": {"version": version, "revision": revision},"version": vers, "tag": tag, "shareable": shareable, "signing": "none", "golden_expected": expected,- "artifacts": artifacts, "steam_build_id": None}+ "artifacts": artifacts, "steam_build_id": None,+ "steam": a.steam, "channel": ("nightly" if nightly else "beta") if a.steam else None, "dev": a.dev,+ "nightly_version": nightly}(out / "build-record.json").write_text(json.dumps(record, indent=2) + "\n")(out / "build-record.md").write_text(markdown(record))print(f"RECORD {out / 'build-record.json'}\nRECORD {out / 'build-record.md'}")for a_ in artifacts:- print(f"{a_['archive']['name']}: sha256 {a_['archive']['sha256']}, {a_['archive']['bytes']} bytes, "- f"golden {a_['golden']['status']}")+ if a_["archive"] is None:+ print(f"{a_['steam_folder']}: {a_['files']} files, golden {a_['golden']['status']}")+ else:+ print(f"{a_['archive']['name']}: sha256 {a_['archive']['sha256']}, {a_['archive']['bytes']} bytes, "+ f"golden {a_['golden']['status']}")print("Nothing was pushed or uploaded. Copy the record files to the build records repository.")return 0 if all_ok else 1diff --git a/tools/steam_upload.py b/tools/steam_upload.pynew file mode 100644index 000000000..823cea9b3--- /dev/null+++ b/tools/steam_upload.py@@ -0,0 +1,285 @@+# /// script+# requires-python = ">=3.11"+# dependencies = []+# ///+"""The Steam hand-over: SteamPipe scripts and a never-published draft release for .github/workflows/steam-upload.yml+(plan docs/superpowers/plans/2026-11-01-steamworks-integration.md Task 8, #2155; spec+docs/superpowers/specs/2026-11-01-steamworks-integration-design.md; owner answers Q7 "Also nightlies", Q8 "GitHub+Actions").++Usage:+ uv run tools/steam_upload.py stage --out <release folder> --tag vX.Y.Z (the owner's Mac, or the nightly)+ uv run tools/steam_upload.py render --root <content> --tag vX.Y.Z --commit <sha> --branch beta|nightly (CI)+ uv run tools/steam_upload.py verify --dir <draft> --tag vX.Y.Z --branch beta|nightly --record-sha256 <sha> (CI)++- stage reads the folder tools/release_build.py --steam wrote (build-record.json and steam/<platform>/), refuses a+ record that is not a clean, non-dev Steam build of that tag for `beta` or `nightly`, steam/steam.json while any+ ID is null, and a folder that no longer matches the file list the build recorded. It zips the files of that list to steam-<tag>-<platform>.zip (keeping the executable bits and symlinks:+ steamcmd uploads from a Linux machine), writes steam-record.json (tag, commit, branch, each zip's SHA-256 and size),+ attaches them to a DRAFT release steam-<tag> (never published; an existing release of that name is replaced only if+ it is a draft) and runs `gh workflow run steam-upload.yml --ref main -f tag=<tag> -f branch=<branch>`.+- render writes app_build_<appid>.vdf and one depot_build_<depotid>.vdf per platform from steam/app_build.vdf.in and+ steam/depot_build.vdf.in (written for this project from the keys of Valve's SteamPipe documentation,+ https://partner.steamgames.com/doc/sdk/uploading, read 1 Nov 2026), into <root>/../steam-scripts. SetLive is the+ branch; `default` is never accepted (Valve: "the 'default' branch can not be set live automatically"; the owner sets+ it live in App Admin).+- verify is the upload job's check of the downloaded draft against steam-record.json; it prints the record's commit.++None of these takes, reads or prints a credential, and none runs steamcmd: only steam-upload.yml does, on GitHub's+machines, with the two secrets the owner created in the `steam` environment.+"""+import argparse+import hashlib+import json+import os+import re+import stat+import subprocess+import sys+import zipfile+from dataclasses import dataclass+from pathlib import Path+from string import Template+from typing import Callable++import release_build as rb # tools/: the build's own folder checks and file list, so stage ships what was built++REPO = Path(__file__).resolve().parents[1]+CONFIG = REPO / "steam/steam.json"+PLATFORMS = ("windows", "mac", "linux")+TAG = re.compile(r"v[0-9]+\.[0-9]+\.[0-9]+", re.ASCII) # the upload job's own input check+COMMIT = re.compile(r"[0-9a-f]{40}")+WORKFLOW = "steam-upload.yml"+NEVER = "default" # the branch players get; only the owner sets it live, in App Admin+++@dataclass+class Result:+ returncode: int+ stdout: str = ""+ stderr: str = ""+++def gh_cli(args: list[str]) -> Result:+ """The one place a process starts: GitHub's own CLI, as the person running this (tests replace it)."""+ p = subprocess.run(["gh", *map(str, args)], cwd=REPO, text=True, capture_output=True)+ return Result(p.returncode, p.stdout, p.stderr)+++def load_config(path: Path = CONFIG) -> dict:+ return json.loads(path.read_text(encoding="utf-8"))+++def refuse(config: dict, record: dict | None = None) -> str | None:+ """Why nothing may be uploaded, or None: every null ID by name; with a record, a build that is not a clean,+ non-dev Steam build for one of the configured branches."""+ problems = []+ depots = config.get("depots") or {}+ nulls = [n for n, v in [("app_id", config.get("app_id")), *((f"depots.{p}", depots.get(p)) for p in PLATFORMS)]+ if v is None]+ if nulls:+ problems.append("steam/steam.json has no " + ", ".join(nulls) + " yet (the owner's step, #2151)")+ if record is not None:+ if record.get("steam") is not True:+ problems.append("the record is not a Steam build (tools/release_build.py --steam)")+ if record.get("dev") is not False:+ problems.append("the record is a --dev build, which never goes to Steam")+ if not (record.get("tree_clean") is True and record.get("tree_clean_after_builds") is True):+ problems.append("the record was built from a dirty tree")+ channel = record.get("channel")+ if channel == NEVER or channel not in config.get("branches", []):+ problems.append(f"the record's channel {channel!r} is not one of {config.get('branches')}")+ return "; ".join(problems) or None+++def _quoted(value: str) -> str:+ if '"' in value or "\\" in value or "\n" in value:+ raise ValueError(f"{value!r} cannot be written into a VDF string")+ return value+++def render(config: dict, root: Path, tag: str, commit: str, branch: str) -> list[Path]:+ """The SteamPipe scripts for one upload; returns their paths (the app script first)."""+ if problem := refuse(config):+ raise ValueError(problem)+ if branch.lower() == NEVER or branch not in config["branches"]:+ raise ValueError(f"{branch!r} is not a branch this job may set live ({config['branches']}; never {NEVER!r})")+ if not TAG.fullmatch(tag) or not COMMIT.fullmatch(commit):+ raise ValueError(f"expected a vX.Y.Z tag and a full commit SHA, not {tag!r} and {commit!r}")+ root = root.resolve()+ scripts = root.parent / "steam-scripts" # beside the content, never inside it+ scripts.mkdir(parents=True, exist_ok=True)+ app_id, depots = config["app_id"], config["depots"]+ depot_template = Template((REPO / "steam/depot_build.vdf.in").read_text(encoding="utf-8"))+ written = []+ for platform in PLATFORMS:+ path = scripts / f"depot_build_{depots[platform]}.vdf"+ path.write_text(depot_template.substitute(depot_id=int(depots[platform]), platform=platform), encoding="utf-8")+ written.append(path)+ lines = "\n".join(f'\t\t"{int(depots[p])}" "depot_build_{int(depots[p])}.vdf"' for p in PLATFORMS)+ app = scripts / f"app_build_{int(app_id)}.vdf"+ app.write_text(Template((REPO / "steam/app_build.vdf.in").read_text(encoding="utf-8")).substitute(+ app_id=int(app_id), desc=f"{tag} {commit[:8]}", content_root=_quoted(str(root)),+ build_output=_quoted(f"{root}/../steam-output"), branch=branch, depots=lines), encoding="utf-8")+ return [app, *written]+++def sha256(path: Path) -> str:+ h = hashlib.sha256()+ with open(path, "rb") as f:+ for chunk in iter(lambda: f.read(1 << 20), b""):+ h.update(chunk)+ return h.hexdigest()+++def zip_folder(folder: Path, dest: Path, paths: list[Path] | None = None) -> None:+ """A zip of folder's contents (or of `paths`, all under folder) with each entry's Unix mode (the executable bits)+ and symlinks kept as links, so `unzip` on the Linux upload machine restores the players as they were built."""+ with zipfile.ZipFile(dest, "w", zipfile.ZIP_DEFLATED) as z:+ for path in sorted(folder.rglob("*") if paths is None else paths):+ rel = path.relative_to(folder).as_posix()+ mode = os.lstat(path).st_mode+ if path.is_symlink():+ info = zipfile.ZipInfo(rel)+ info.create_system = 3+ info.external_attr = (stat.S_IFLNK | 0o777) << 16+ z.writestr(info, os.readlink(path))+ elif path.is_file():+ info = zipfile.ZipInfo.from_file(path, rel)+ info.create_system = 3+ info.external_attr = (stat.S_IFREG | stat.S_IMODE(mode)) << 16+ info.compress_type = zipfile.ZIP_DEFLATED+ with open(path, "rb") as f:+ z.writestr(info, f.read())+++def stage(out: Path, tag: str, gh: Callable[[list[str]], Result] = gh_cli, config_path: Path = CONFIG) -> None:+ """Zip the Steam folders, write steam-record.json, attach them to the draft steam-<tag> and start the upload."""+ record_path = out / "build-record.json"+ try:+ record = json.loads(record_path.read_text(encoding="utf-8"))+ except (OSError, ValueError) as e:+ raise SystemExit(f"REFUSED: cannot read {record_path}: {e}")+ if problem := refuse(load_config(config_path), record):+ raise SystemExit(f"REFUSED: {problem}")+ if not TAG.fullmatch(tag) or record.get("tag") != tag:+ raise SystemExit(f"REFUSED: the upload takes a vX.Y.Z tag that is the record's ({record.get('tag')!r}), "+ f"not {tag!r}")+ commit = record.get("commit", "")+ if not COMMIT.fullmatch(commit):+ raise SystemExit(f"REFUSED: the record's commit {commit!r} is not a full SHA")+ folders = {a.get("platform"): a.get("steam_folder") for a in record.get("artifacts", [])}+ if set(folders) != set(PLATFORMS) or any(folders[p] != f"steam/{p}" or not (out / folders[p]).is_dir()+ for p in PLATFORMS):+ raise SystemExit(f"REFUSED: a Steam upload needs all three platform folders (steam/{{{','.join(PLATFORMS)}}}); "+ f"the record has {sorted(folders)}")+ branch = record["channel"]+ # The folders must still be what the build checked and listed: no steam_appid.txt dropped in for a local test, no+ # log a run left behind (review of #2155). Only the files the build's list names are zipped, so Unity's+ # *_DoNotShip folders and the photo manifest never ship, as with the GitHub archives.+ listed = {a["platform"]: a.get("file_list_sha256") for a in record["artifacts"]}+ shipped = {}+ for platform in PLATFORMS:+ folder, mac = out / "steam" / platform, platform == "mac"+ if problem := rb.steam_folder_problem(folder, platform):+ raise SystemExit(f"REFUSED: {problem}")+ text, _, _ = rb.tree_manifest(folder, mac=mac)+ if hashlib.sha256(text.encode()).hexdigest() != listed[platform]:+ raise SystemExit(f"REFUSED: {folder} no longer matches the file list the build recorded; rebuild it")+ shipped[platform] = rb.shipped(folder, mac=mac)+ assets = {}+ for platform in PLATFORMS:+ dest = out / f"steam-{tag}-{platform}.zip"+ zip_folder(out / "steam" / platform, dest, shipped[platform])+ assets[dest.name] = {"sha256": sha256(dest), "size": dest.stat().st_size}+ steam_record = out / "steam-record.json"+ steam_record.write_text(json.dumps({"tag": tag, "commit": commit, "branch": branch, "assets": assets}, indent=2)+ + "\n", encoding="utf-8")+ name = f"steam-{tag}"+ seen = gh(["release", "view", name, "--json", "isDraft"])+ if seen.returncode == 0:+ if json.loads(seen.stdout).get("isDraft") is not True:+ raise SystemExit(f"REFUSED: {name} is a published release; it is never replaced (check by hand)")+ if (r := gh(["release", "delete", name, "--yes"])).returncode != 0:+ raise SystemExit(f"FAILED: could not delete the old draft {name}: {r.stderr.strip()}")+ elif "release not found" not in seen.stderr:+ raise SystemExit(f"FAILED: gh release view {name}: {seen.stderr.strip()}")+ files = [str(out / n) for n in assets] + [str(steam_record)]+ notes = (f"Steam content for {tag} ({commit[:8]}), branch {branch}. A draft that is never published: "+ "steam-upload.yml downloads it, uploads to Steam and deletes it.")+ if (r := gh(["release", "create", name, "--draft", "--target", commit, "--title", name, "--notes", notes,+ *files])).returncode != 0:+ raise SystemExit(f"FAILED: gh release create {name}: {r.stderr.strip()}")+ # The record's hash travels in the dispatch, which nobody can edit afterwards; the draft itself stays editable by+ # anyone with push access, so the job trusts the record only if it hashes to this (review of #2155).+ if (r := gh(["workflow", "run", WORKFLOW, "--ref", "main", "-f", f"tag={tag}", "-f", f"branch={branch}",+ "-f", f"record_sha256={sha256(steam_record)}"])).returncode != 0:+ raise SystemExit(f"FAILED: gh workflow run {WORKFLOW}: {r.stderr.strip()} (the draft {name} is ready; "+ "dispatch it again by hand)")+ print(f"STAGED {name} (draft) and started {WORKFLOW} for {tag} on {branch}")+++def verify(folder: Path, tag: str, branch: str, record_sha256: str) -> str:+ """The upload job's check of the downloaded draft: the record is the one the owner's machine dispatched (its+ SHA-256 is the dispatch input), it names this tag and branch and a full commit, and every zip has its exact SHA-256+ and size. Returns the commit."""+ path = folder / "steam-record.json"+ if not re.fullmatch(r"[0-9a-f]{64}", record_sha256) or not path.is_file() or sha256(path) != record_sha256:+ raise SystemExit("REFUSED: steam-record.json is not the record whose record_sha256 was dispatched")+ try:+ rec = json.loads((folder / "steam-record.json").read_text(encoding="utf-8"))+ except (OSError, ValueError) as e:+ raise SystemExit(f"REFUSED: no readable steam-record.json: {e}")+ if rec.get("tag") != tag:+ raise SystemExit(f"REFUSED: the record's tag {rec.get('tag')!r} is not {tag!r}")+ if rec.get("branch") != branch or branch == NEVER:+ raise SystemExit(f"REFUSED: the record's branch {rec.get('branch')!r} is not the input {branch!r}")+ if not COMMIT.fullmatch(str(rec.get("commit", ""))):+ raise SystemExit("REFUSED: the record's commit is not a full SHA")+ wanted = {f"steam-{tag}-{p}.zip" for p in PLATFORMS}+ if set(rec.get("assets", {})) != wanted:+ raise SystemExit(f"REFUSED: the record lists {sorted(rec.get('assets', {}))}, not {sorted(wanted)}")+ for name, meta in rec["assets"].items():+ path = folder / name+ if not path.is_file() or sha256(path) != meta.get("sha256") or path.stat().st_size != meta.get("size"):+ raise SystemExit(f"REFUSED: {name} does not match its sha256 and size in steam-record.json")+ return rec["commit"]+++def parser() -> argparse.ArgumentParser:+ ap = argparse.ArgumentParser(description="Steam hand-over: never takes a credential, never runs steamcmd.")+ sub = ap.add_subparsers(dest="command", required=True)+ s = sub.add_parser("stage", help="draft release steam-<tag> and the upload dispatch (the owner's Mac)")+ s.add_argument("--out", type=Path, required=True, help="the folder tools/release_build.py --steam wrote")+ s.add_argument("--tag", required=True)+ r = sub.add_parser("render", help="the SteamPipe scripts (the upload job)")+ r.add_argument("--root", type=Path, required=True, help="the content root holding windows/, mac/ and linux/")+ r.add_argument("--tag", required=True)+ r.add_argument("--commit", required=True)+ r.add_argument("--branch", required=True, choices=["beta", "nightly"])+ v = sub.add_parser("verify", help="check a downloaded draft against steam-record.json (the upload job)")+ v.add_argument("--dir", type=Path, required=True)+ v.add_argument("--tag", required=True)+ v.add_argument("--branch", required=True, choices=["beta", "nightly"])+ v.add_argument("--record-sha256", required=True, help="the dispatch input: steam-record.json's SHA-256")+ return ap+++def main(argv: list[str] | None = None) -> int:+ a = parser().parse_args(argv)+ if a.command == "stage":+ stage(a.out, a.tag)+ elif a.command == "render":+ try:+ paths = render(load_config(), a.root, a.tag, a.commit, a.branch)+ except ValueError as e:+ print(f"REFUSED: {e}", file=sys.stderr)+ return 1+ print(paths[0])+ else:+ print(verify(a.dir, a.tag, a.branch, a.record_sha256))+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/tests/data/steam/app_build_1000.vdf b/tools/tests/data/steam/app_build_1000.vdfnew file mode 100644index 000000000..233dffca6--- /dev/null+++ b/tools/tests/data/steam/app_build_1000.vdf@@ -0,0 +1,15 @@+"AppBuild"+{+ "AppID" "1000"+ "Desc" "v0.3.2 1b7a36cb"+ "ContentRoot" "<root>"+ "BuildOutput" "<root>/../steam-output"+ "SetLive" "nightly"+ "Preview" "0"+ "Depots"+ {+ "1001" "depot_build_1001.vdf"+ "1002" "depot_build_1002.vdf"+ "1003" "depot_build_1003.vdf"+ }+}diff --git a/tools/tests/data/steam/depot_build_1002.vdf b/tools/tests/data/steam/depot_build_1002.vdfnew file mode 100644index 000000000..ec9c6a38c--- /dev/null+++ b/tools/tests/data/steam/depot_build_1002.vdf@@ -0,0 +1,10 @@+"DepotBuild"+{+ "DepotID" "1002"+ "FileMapping"+ {+ "LocalPath" "mac/*"+ "DepotPath" "."+ "Recursive" "1"+ }+}diff --git a/tools/tests/test_nightly.py b/tools/tests/test_nightly.pyindex 4260f1c31..abda51faf 100644--- a/tools/tests/test_nightly.py+++ b/tools/tests/test_nightly.py@@ -1473,7 +1473,7 @@ def test_state_is_saved_right_after_create_draft_and_right_after_publish(night,def test_a_failing_checkpoint_save_does_not_stop_the_night(env, monkeypatch, capsys):monkeypatch.setattr(nightly, "save_state", lambda p, st: (_ for _ in ()).throw(OSError("full")))seen = {}- def stages(night, state, runner, gh, itch, *, no_publish, free_gb, save):+ def stages(night, state, runner, gh, itch, *, no_publish, free_gb, save, no_steam=False):save()seen["ok"] = Truereturn True@@ -1483,7 +1483,7 @@ def test_a_failing_checkpoint_save_does_not_stop_the_night(env, monkeypatch, capdef test_a_failed_checkpoint_save_notifies_so_it_is_never_silent(env, monkeypatch):monkeypatch.setattr(nightly, "save_state", lambda p, st: (_ for _ in ()).throw(OSError("full")))- monkeypatch.setattr(nightly, "run_stages", lambda night, state, runner, gh, itch, *, no_publish, free_gb, save:+ monkeypatch.setattr(nightly, "run_stages", lambda night, state, runner, gh, itch, *, no_publish, free_gb, save, no_steam=False:save() or True)assert env.night() == "PUBLISHED"assert any("not saved" in a[0].lower() and "full" in a[1] for a in env_notes)@@ -1678,7 +1678,7 @@ def test_the_itch_skip_reason_is_noted_on_the_night(night, env, pub, served):def test_the_night_notes_reach_the_log_line(env, monkeypatch):- def stages(night, state, runner, gh, itch, *, no_publish, free_gb, save):+ def stages(night, state, runner, gh, itch, *, no_publish, free_gb, save, no_steam=False):night.notes.append("itch: skipped (save test not passed)")return Truemonkeypatch.setattr(nightly, "run_stages", stages)@@ -2842,3 +2842,162 @@ def test_pending_demo_without_verified_latest_preserves_hold_and_never_dispatcheassert env.night(ns.State(last_published=ns.Published(TAG, SHA, "0.3.2", {}, None), site_pending="0.3.2"), gh) == "SKIPPED"assert gh.names() == ["latest_tag"]assert ns.load_state(env.state_path).site_pending == "0.3.2"+++# --- the Steam stage (plan 2026-11-01-steamworks-integration Task 7, #2155) --------------------------------------------++STEAM_IDS = {"app_id": 1000, "depots": {"windows": 1001, "mac": 1002, "linux": 1003}, "branches": ["beta", "nightly"]}+++def steam_ready(env, ids=STEAM_IDS, *, build=0, stage=0):+ """steam/steam.json in the clone, and runner answers for the tag fetch and the two Steam commands."""+ (env.cfg.clone / "steam").mkdir(exist_ok=True)+ (env.cfg.clone / "steam/steam.json").write_text(json.dumps(ids))+ clone = str(env.cfg.clone)+ env.runner.add(["git", "-C", clone, "fetch", "--no-tags", "origin"], out="")+ env.runner.add(["uv", "run", "tools/release_build.py"], code=build)+ env.runner.add(["uv", "run", "tools/steam_upload.py"], code=stage)+++def steam_calls(env):+ return [c for c in env.runner.calls if c[:3] in (["uv", "run", "tools/release_build.py"],+ ["uv", "run", "tools/steam_upload.py"])+ or c[:4] == ["git", "-C", str(env.cfg.clone), "fetch"]]+++def staged(night, env, stages, st, **kw):+ """One run_stages call; a repeat in the same test first drops the previous call's copy of the first player."""+ shutil.rmtree(stages.gz, ignore_errors=True)+ return nightly.run_stages(night, st, env.runner, stages.gh, None, free_gb=lambda p: 100.0, **kw)+++def published_marker(env, monkeypatch):+ monkeypatch.setattr(nightly, "publish_night", lambda *a, **k: env.runner.calls.append(["PUBLISHED"]))+++def test_the_steam_stage_runs_only_after_publish(night, env, stages, monkeypatch):+ steam_ready(env)+ published_marker(env, monkeypatch)+ st = ns.State(last_published=last_published())+ assert staged(night, env, stages, st, no_publish=False)+ calls = env.runner.calls+ first = next(i for i, c in enumerate(calls) if c in steam_calls(env))+ assert calls.index(["PUBLISHED"]) < first+ out = night.run_dir / "steam-release"+ assert ["git", "-C", str(env.cfg.clone), "fetch", "--no-tags", "origin", f"refs/tags/{TAG}:refs/tags/{TAG}"] in calls+ assert ["uv", "run", "tools/release_build.py", "--platform", "all", "--steam", "--tag", TAG,+ "--nightly-version", night.version, "--out", str(out)] in calls+ assert ["uv", "run", "tools/steam_upload.py", "stage", "--out", str(out), "--tag", TAG] in calls+ assert not night.notes+++def test_no_steam_stage_without_a_publish(night, env, stages, monkeypatch):+ steam_ready(env)+ st = ns.State(last_published=last_published())+ staged(night, env, stages, st, no_publish=True)+ assert steam_calls(env) == []+ monkeypatch.setattr(nightly, "publish_night",+ lambda *a, **k: (_ for _ in ()).throw(ns.Refused("github-publish", "no")))+ with pytest.raises(ns.Refused):+ staged(night, env, stages, st, no_publish=False)+ assert steam_calls(env) == []++[email protected]("failure", ["build", "stage", "fetch", "raises"])+def test_a_steam_failure_leaves_the_web_nightly_published(env, stages, monkeypatch, failure):+ if failure == "fetch":+ clone = str(env.cfg.clone)+ env.runner.add(["git", "-C", clone, "fetch", "--no-tags", "origin"], code=128)+ if failure == "raises":+ env.runner.add(["uv", "run", "tools/release_build.py"],+ effect=lambda cmd: (_ for _ in ()).throw(OSError("uv is missing")))+ steam_ready(env, build=1 if failure == "build" else 0, stage=1 if failure == "stage" else 0)+ published_marker(env, monkeypatch)+ ns.save_state(env.state_path, ns.State(last_published=last_published()))+ outcome = nightly.run_night(env.cfg, env.state_path, env.job, env.runner, stages.gh, None, now=NOW, manual=False,+ no_publish=False, free_gb=lambda p: 100.0)+ assert outcome == "PUBLISHED"+ line = env.log().strip().splitlines()[-1]+ assert "PUBLISHED" in line and line.endswith("steam=failed")+ assert not {"delete_draft", "restore_latest"} & set(stages.gh.names()), "the web nightly is never rolled back"+ assert any("Steam" in note[0] for note in env_notes)+++def test_the_steam_stage_is_skipped_while_ids_are_null(night, env, stages, monkeypatch, capsys):+ published_marker(env, monkeypatch)+ st = ns.State(last_published=last_published())+ for ids in ({**STEAM_IDS, "app_id": None}, {**STEAM_IDS, "depots": {**STEAM_IDS["depots"], "mac": None}}):+ steam_ready(env, ids)+ assert staged(night, env, stages, st, no_publish=False)+ assert steam_calls(env) == [] and not night.notes+ assert "steam: skipped" in capsys.readouterr().out+ # --no-steam skips it even with every ID known.+ steam_ready(env)+ assert staged(night, env, stages, st, no_publish=False, no_steam=True)+ assert steam_calls(env) == []+++def test_no_steam_reaches_the_stage_from_the_command_line(env, monkeypatch):+ seen = {}+ monkeypatch.setattr(nightly, "load_config", lambda path: env.cfg)+ monkeypatch.setattr(nightly, "_clients", lambda cfg: (FakeGH(), None))+ monkeypatch.setattr(nightly, "JOB", env.job)+ monkeypatch.setattr(nightly, "run_night", lambda *a, **k: seen.update(k) or "PUBLISHED")+ assert nightly.main(["run", "--no-steam"]) == 0 and seen["no_steam"] is True+ assert nightly.main(["run"]) == 0 and seen["no_steam"] is False+++class SteamEnvRunner(EnvRunner):+ """Also records stop_on_interrupt per command."""++ def __init__(self):+ super().__init__()+ self.stops = []++ def run(self, cmd, *, cwd, log, deadline, env=None, holder=None, stop_on_interrupt=False):+ self.stops.append((list(cmd), stop_on_interrupt))+ return super().run(cmd, cwd=cwd, log=log, deadline=deadline, env=env, holder=holder)+++def test_the_steam_build_runs_like_the_nightlys_other_unity_steps(night, env):+ # Review I2 (#2155): the MCP-free Unity env, the exclusive-window check, and children stopped on an interrupt.+ env.runner = SteamEnvRunner()+ env._rules()+ steam_ready(env)+ nightly.run_steam(night, env.runner)+ build = next(e for e in env.runner.envs if e[0][:3] == ["uv", "run", "tools/release_build.py"])+ assert build[1]["UNITY_MCP_SERVER_PATH"] == str(night.job / "no-mcp-server")+ runs = [stop for cmd, stop in env.runner.stops if cmd[:2] == ["uv", "run"]]+ assert runs == [True, True], runs # release_build.py and steam_upload.py, each stopped on an interrupt+ assert not night.notes+ env.marker.write_text("x")+ nightly.run_steam(night, env.runner)+ assert night.notes == ["steam=failed"]+ assert len([e for e in env.runner.envs if e[0][:3] == ["uv", "run", "tools/release_build.py"]]) == 1++[email protected]("text, notes", [('{"app_id": 1, "depots": [1, 2, 3], "branches": []}', ["steam=failed"]),+ ('[1]', ["steam=failed"]), ("not json", [])])+def test_a_malformed_steam_json_is_a_steam_failure_not_a_refused_night(night, env, text, notes):+ # Review I3 (#2155): the web nightly is public by now, so even a broken steam.json only marks Steam.+ (env.cfg.clone / "steam").mkdir(exist_ok=True)+ (env.cfg.clone / "steam/steam.json").write_text(text)+ nightly.run_steam(night, env.runner) # never raises+ assert night.notes == notes # unreadable JSON is "not configured yet" (skipped); a wrong shape is a failure+ assert not [c for c in env.runner.calls if c[:2] == ["uv", "run"]]+++def test_the_steam_content_is_removed_after_the_stage(night, env):+ # Review (k2 H6): nothing prunes the run folders, and three players plus their zips each night would fill the disk+ # the next web nightly's free-space gate reads. The record and the logs stay.+ out = night.run_dir / "steam-release"+ def built(cmd):+ (out / "steam/linux").mkdir(parents=True)+ (out / "steam/linux/Statecraft.x86_64").write_bytes(b"x" * 10)+ (out / "steam-v0.3.2-linux.zip").write_bytes(b"z")+ (out / "build-record.json").write_text("{}")+ steam_ready(env)+ env.runner.rules.insert(0, (("uv", "run", "tools/release_build.py"), 0, "", built))+ nightly.run_steam(night, env.runner)+ assert not (out / "steam").exists() and not list(out.glob("*.zip"))+ assert (out / "build-record.json").is_file()diff --git a/tools/tests/test_release_build.py b/tools/tests/test_release_build.pyindex de73bb6a3..9394c79e3 100644--- a/tools/tests/test_release_build.py+++ b/tools/tests/test_release_build.py@@ -63,6 +63,8 @@ def write_editor_version(exe, version):class Fake:"""Records every command and plays git, Unity and the player."""+ steam_library = True+def __init__(self, dirty="", golden_ok=True, build_ok=True, branch="main", tags=("v0.1.0",), worktrees=None,build_raises=None, dirty_after="", on_origin_main=True):self.calls: list[list[str]] = []@@ -105,6 +107,13 @@ class Fake:target.parent.mkdir(parents=True, exist_ok=True)target.write_bytes(b"player " + target.name.encode())(target.parent / "event-photos.json").write_text("{}\n")+ if "-steam" in cmd and self.steam_library: # #2154's Build.cs ships Valve's plugin only in -steam builds+ lib = {".app": "Contents/PlugIns/steam_api.bundle/Contents/MacOS/libsteam_api.dylib",+ ".exe": "../Statecraft_Data/Plugins/x86_64/steam_api64.dll",+ ".x86_64": "../Statecraft_Data/Plugins/libsteam_api.so"}[target.suffix]+ path = (target / lib) if target.suffix == ".app" else (target.parent / lib[3:])+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(b"valve")log.write_text("BUILD Succeeded StandaloneOSX -> x: 1.0 MB on disk, 0 errors, 321s\n")if not self.build_ok: # Unity failed, but a (partial or older) player is still therelog.write_text("BUILD Failed StandaloneOSX -> x: 0.0 MB on disk, 3 errors, 12s\n")@@ -800,3 +809,196 @@ def test_the_golden_rule_wants_the_exact_bare_lines_the_player_prints():assert rb.golden_status(f"12:00:01 GOLDEN OK 1950 {H1950}\n12:00:02 GOLDEN OK 1952 {H1952}\n", 0, expected) == "fail"assert rb.golden_status(f"GOLDEN OK 1950 {H1950}a\nGOLDEN OK 1952 {H1952}\n", 0, expected) == "fail"assert rb.golden_lines(f"GOLDEN OK 1950 {H1950}a\n") == [f"GOLDEN OK 1950 {H1950}a"], "the record shows what was printed"+++# --- Steam (plan 2026-11-01-steamworks-integration Task 7, #2155) -------------------------------------------------------++VALVE_NAMES = ["Statecraft_Data/Plugins/x86_64/steam_api64.dll", "Statecraft_Data/Plugins/steam_api.dll",+ "Statecraft.app/Contents/PlugIns/steam_api.bundle/",+ "Statecraft.app/Contents/PlugIns/steam_api.bundle/Contents/MacOS/libsteam_api.dylib",+ "Statecraft_Data/Plugins/libsteam_api.so", "steam_appid.txt"]++[email protected]("name", VALVE_NAMES)+def test_a_non_steam_archive_never_carries_valve_files(name):+ clean = ["Statecraft.exe", "Statecraft_Data/Plugins/x86_64/lib_burst_generated.dll",+ "Statecraft_Data/StreamingAssets/vehicle-steam-locomotive-1948-v2.bundle", "LICENSE"]+ assert rb.refuse_valve_files(clean) is None+ problem = rb.refuse_valve_files([*clean, name])+ assert problem is not None and name in problem+++class ValveFake(Fake):+ """A player build that leaves `extra` (a path relative to the player's folder) beside the player."""++ def __init__(self, extra, **kw):+ super().__init__(**kw)+ self.extra = extra++ def __call__(self, cmd, **kw):+ result = super().__call__(cmd, **kw)+ cmd = [str(c) for c in cmd]+ if "-executeMethod" in cmd:+ folder = Path(cmd[cmd.index("-out") + 1]).parent+ (folder / self.extra).parent.mkdir(parents=True, exist_ok=True)+ (folder / self.extra).write_text("valve")+ return result+++def test_a_valve_file_in_a_github_archive_fails_the_build(repo, editor, monkeypatch, tmp_path, capsys):+ out = tmp_path / "out"+ fake = ValveFake("Statecraft_Data/Plugins/x86_64/steam_api64.dll")+ assert run_main(["--platform", "windows", "--out", str(out)], repo, editor, fake, monkeypatch) == 1+ assert "steam_api64.dll" in capsys.readouterr().err+ assert not (out / "build-record.json").exists()+++def test_steam_folders_are_written_not_archived(repo, editor, monkeypatch, tmp_path, capsys):+ out = tmp_path / "out"+ assert run_main(["--platform", "all", "--steam", "--dry-run", "--out", str(out)], repo, editor, Fake(),+ monkeypatch) == 0+ text = capsys.readouterr().out+ builds = [line for line in text.splitlines() if "-executeMethod" in line]+ assert len(builds) == 3 and all("-steam" in line.split() for line in builds)+ for platform in ("windows", "mac", "linux"):+ assert f"steam folder: {out / 'steam' / platform}" in text+ assert "archive:" not in text+ # A GitHub build never asks for the Steam define.+ assert run_main(["--platform", "all", "--dry-run", "--out", str(out)], repo, editor, Fake(), monkeypatch) == 0+ assert "-steam" not in capsys.readouterr().out+ # The real run: one folder per platform with the player and the notices, and no archive anywhere.+ assert run_main(["--platform", "all", "--steam", "--out", str(out)], repo, editor, Fake(), monkeypatch) == 0+ for platform, player in (("windows", "Statecraft.exe"), ("linux", "Statecraft.x86_64"), ("mac", "Statecraft.app")):+ folder = out / "steam" / platform+ assert (folder / player).exists() and all((folder / n).is_file() for n in NOTICES)+ assert not list(out.glob("*.zip")) and not list(out.glob("*.tar.gz"))+ record = json.loads((out / "build-record.json").read_text())+ assert record["steam"] is True and record["channel"] == "beta" and record["dev"] is False+ for a in record["artifacts"]:+ assert a["archive"] is None and a["steam_folder"] == f"steam/{a['platform']}"+++def test_every_steam_build_passes_the_steam_flag(repo, editor, monkeypatch, tmp_path):+ fake = Fake()+ assert run_main(["--platform", "all", "--steam", "--out", str(tmp_path / "out")], repo, editor, fake,+ monkeypatch) == 0+ assert len(unity_calls(fake)) == 3 and all("-steam" in c for c in unity_calls(fake))+++def test_a_steam_folder_with_steam_appid_txt_is_refused(repo, editor, monkeypatch, tmp_path, capsys):+ out = tmp_path / "out"+ assert run_main(["--platform", "linux", "--steam", "--out", str(out)], repo, editor, ValveFake("steam_appid.txt"),+ monkeypatch) == 1+ assert "steam_appid.txt" in capsys.readouterr().err+ assert not (out / "build-record.json").exists()+++def test_a_steam_folder_may_carry_the_steam_library(repo, editor, monkeypatch, tmp_path):+ out = tmp_path / "out"+ fake = ValveFake("Statecraft_Data/Plugins/libsteam_api.so")+ assert run_main(["--platform", "linux", "--steam", "--out", str(out)], repo, editor, fake, monkeypatch) == 0+ assert (out / "steam/linux/Statecraft_Data/Plugins/libsteam_api.so").is_file()+++def test_a_dev_steam_build_is_recorded_as_dev(repo, editor, monkeypatch, tmp_path):+ out = tmp_path / "out"+ assert run_main(["--platform", "linux", "--steam", "--dev", "--out", str(out)], repo, editor, Fake(),+ monkeypatch) == 0+ record = json.loads((out / "build-record.json").read_text())+ assert record["steam"] is True and record["dev"] is True and record["shareable"] is False+ # A GitHub release is not a Steam build and not dev.+ out2 = tmp_path / "out2"+ assert run_main(["--platform", "linux", "--out", str(out2)], repo, editor, Fake(), monkeypatch) == 0+ plain = json.loads((out2 / "build-record.json").read_text())+ assert plain["steam"] is False and plain["dev"] is False and plain["channel"] is None+++SETTINGS = "unity/ProjectSettings/ProjectSettings.asset"+++class StampFake(Fake):+ """The nightly's clone: ProjectSettings.asset differs from HEAD only by tonight's bundleVersion stamp. `git show`+ gives HEAD's text and `git checkout` restores it, as git would; each build records the bundleVersion it saw."""++ def __init__(self, repo, head_text, **kw):+ super().__init__(**kw)+ self.repo, self.head_text, self.seen = repo, head_text, []++ def __call__(self, cmd, **kw):+ cmd = [str(c) for c in cmd]+ if cmd[:2] == ["git", "show"]:+ self.calls.append(cmd)+ return rb.Result(0, self.head_text) if cmd[2] == f"HEAD:{SETTINGS}" else rb.Result(128, "")+ if cmd[:2] == ["git", "checkout"]:+ (self.repo / SETTINGS).write_text(self.head_text)+ if "-executeMethod" in cmd:+ self.seen.append(rb.versions()["bundle_version"])+ return super().__call__(cmd, **kw)+++def stamped(repo, version="0.1.5", extra=""):+ """The nightly's own stamp (tools/nightly.py), so the accepted shape is the one the nightly really writes."""+ from nightly import stamp_bundle_version+ head = (repo / SETTINGS).read_text()+ stamp_bundle_version(repo / SETTINGS, version)+ if extra:+ (repo / SETTINGS).write_text((repo / SETTINGS).read_text() + extra)+ return head+++def test_nightly_version_accepts_only_the_bundle_version_stamp(repo, editor, monkeypatch, tmp_path, capsys):+ argv = ["--platform", "all", "--steam", "--tag", "v0.1.5", "--nightly-version", "0.1.5"]+ head = stamped(repo)+ fake = StampFake(repo, head, dirty=f" M {SETTINGS}\n", tags=("v0.1.5",))+ out = tmp_path / "out"+ assert run_main([*argv, "--out", str(out)], repo, editor, fake, monkeypatch) == 0+ assert fake.seen == ["0.1.5"] * 3, "every Unity build carries tonight's version, not only the first"+ record = json.loads((out / "build-record.json").read_text())+ assert record["channel"] == "nightly" and record["tag"] == "v0.1.5" and record["nightly_version"] == "0.1.5"+ assert record["version"]["bundle_version"] == "0.1.5" and record["tree_clean"] is True+ # A clean tree (the nightly restores its stamp after the web builds) is accepted too.+ (repo / SETTINGS).write_text(head)+ fake = StampFake(repo, head, tags=("v0.1.5",))+ assert run_main([*argv, "--out", str(tmp_path / "clean")], repo, editor, fake, monkeypatch) == 0+ assert fake.seen == ["0.1.5"] * 3+ capsys.readouterr()++[email protected]("case", ["other-file", "other-version", "other-line"])+def test_nightly_version_refuses_any_other_change(repo, editor, monkeypatch, tmp_path, capsys, case):+ argv = ["--platform", "linux", "--steam", "--tag", "v0.1.5", "--nightly-version", "0.1.5",+ "--out", str(tmp_path / "out")]+ dirty = f" M {SETTINGS}\n"+ if case == "other-file":+ head, dirty = stamped(repo), dirty + " M content/events/x.yaml\n"+ elif case == "other-version":+ head = stamped(repo, "0.1.6")+ else:+ head = stamped(repo, extra=" companyName: Someone\n")+ fake = StampFake(repo, head, dirty=dirty, tags=("v0.1.5",))+ assert run_main(argv, repo, editor, fake, monkeypatch) == 1+ assert unity_calls(fake) == [] and "REFUSED" in capsys.readouterr().err++[email protected]("argv", [+ ["--tag", "v0.1.5", "--nightly-version", "0.1.5"], # not a Steam build+ ["--steam", "--dev", "--nightly-version", "0.1.5"], # a nightly is not a dev build+ ["--steam", "--tag", "v0.1.6", "--nightly-version", "0.1.5"], # the tag is the nightly's own+ ["--steam", "--tag", "v0.1.5-x", "--nightly-version", "0.1.5-x"], # X.Y.Z only+])+def test_nightly_version_needs_steam_and_its_own_tag(repo, editor, monkeypatch, tmp_path, argv):+ fake = Fake(tags=("v0.1.5", "v0.1.6", "v0.1.5-x"))+ assert run_main(["--platform", "linux", *argv, "--out", str(tmp_path / "out")], repo, editor, fake,+ monkeypatch) == 1+ assert unity_calls(fake) == []++[email protected]("platform", ["windows", "linux", "mac"])+def test_a_steam_folder_without_valves_library_is_refused(repo, editor, monkeypatch, tmp_path, capsys, platform):+ # Review I4 (#2155): a --steam run whose players lack Steam (an editor without #2154's -steam handling) must not+ # produce folders that look uploadable.+ class NoLibrary(Fake):+ steam_library = False+ out = tmp_path / "out"+ assert run_main(["--platform", platform, "--steam", "--out", str(out)], repo, editor, NoLibrary(), monkeypatch) == 1+ assert "Steam library" in capsys.readouterr().err and not (out / "build-record.json").exists()diff --git a/tools/tests/test_steam_upload.py b/tools/tests/test_steam_upload.pynew file mode 100644index 000000000..abd94cc29--- /dev/null+++ b/tools/tests/test_steam_upload.py@@ -0,0 +1,353 @@+"""tools/steam_upload.py: the VDF scripts and the draft-release hand-over to steam-upload.yml (plan+docs/superpowers/plans/2026-11-01-steamworks-integration.md Task 8, #2155). `gh` is faked and no process starts:+nothing here logs in to Steam, runs steamcmd or touches the network."""+import hashlib+import json+import re+import stat+import subprocess+import zipfile+from pathlib import Path++import pytest++import release_build as rb+import steam_upload as su++REPO = Path(__file__).resolve().parents[2]+DATA = Path(__file__).resolve().parent / "data/steam"+SHA = "1b7a36cb" + "0" * 32+IDS = {"app_id": 1000, "depots": {"windows": 1001, "mac": 1002, "linux": 1003}, "branches": ["beta", "nightly"]}++[email protected](autouse=True)+def no_steamcmd(monkeypatch):+ """Any process naming steamcmd fails the test; every other process start does too, since nothing here needs one."""+ def boom(*a, **k):+ cmd = a[0] if a else k.get("args")+ if "steamcmd" in " ".join(map(str, cmd if isinstance(cmd, (list, tuple)) else [cmd])):+ pytest.fail("steamcmd was run")+ pytest.fail(f"a test started a process: {cmd}")+ for name in ("run", "Popen", "call", "check_call", "check_output"):+ monkeypatch.setattr(subprocess, name, boom)+++def record(**over):+ r = {"schema": 1, "commit": SHA, "tag": "v0.3.2", "release": True, "tree_clean": True,+ "tree_clean_after_builds": True, "steam": True, "channel": "nightly", "dev": False,+ "artifacts": [{"platform": p, "steam_folder": f"steam/{p}", "archive": None} for p in su.PLATFORMS]}+ r.update(over)+ return r+++PLAYERS = {"windows": {"Statecraft.exe": 0o644, "Statecraft_Data/data.unity3d": 0o644,+ "Statecraft_Data/Plugins/x86_64/steam_api64.dll": 0o644},+ "linux": {"Statecraft.x86_64": 0o755, "Statecraft_Data/data.unity3d": 0o644,+ "Statecraft_Data/Plugins/libsteam_api.so": 0o644},+ "mac": {"Statecraft.app/Contents/MacOS/Statecraft Israel": 0o755, "Statecraft.app/Contents/Info.plist": 0o644,+ "Statecraft.app/Contents/PlugIns/steam_api.bundle/Contents/MacOS/libsteam_api.dylib": 0o644}}+++def file_list_hashes(out, rec):+ for a in rec["artifacts"]:+ if (out / "steam" / a["platform"]).is_dir():+ text, _, _ = rb.tree_manifest(out / "steam" / a["platform"], mac=a["platform"] == "mac")+ a["file_list_sha256"] = hashlib.sha256(text.encode()).hexdigest()+ (out / "build-record.json").write_text(json.dumps(rec))+++def release_folder(tmp_path, **over):+ """A folder as release_build.py --steam leaves it: each player with Valve's library and the notices, plus what+ Unity leaves beside a player that never ships (a *_DoNotShip folder, the photo manifest); the record carries each+ folder's file-list hash exactly as release_build computes it."""+ out = tmp_path / "release"+ for p, files in PLAYERS.items():+ for rel, mode in files.items():+ f = out / "steam" / p / rel+ f.parent.mkdir(parents=True, exist_ok=True)+ f.write_bytes(f"{p} {rel}".encode())+ f.chmod(mode)+ (out / "steam" / p / "LICENSE").write_text("licence\n")+ (out / "steam" / p / rb.PHOTOS).write_text("{}\n")+ (out / "steam" / p / "Statecraft_BurstDebugInformation_DoNotShip").mkdir()+ (out / "steam" / p / "Statecraft_BurstDebugInformation_DoNotShip/x.pdb").write_text("debug")+ file_list_hashes(out, record(**over))+ return out+++class FakeGh:+ """Plays `gh`: no release of that name exists unless `existing` says it is a draft (True) or published (False)."""++ def __init__(self, existing=None):+ self.calls, self.existing = [], existing++ def __call__(self, args):+ args = [str(a) for a in args]+ self.calls.append(args)+ if args[:2] == ["release", "view"]:+ if self.existing is None:+ return su.Result(1, "", "release not found")+ return su.Result(0, json.dumps({"isDraft": self.existing}), "")+ return su.Result(0, "", "")+++def config_file(tmp_path, ids=IDS):+ path = tmp_path / "steam.json"+ path.write_text(json.dumps(ids))+ return path+++# --- the IDs and the record --------------------------------------------------------------------------------------------++def test_the_committed_config_has_every_id_null_until_the_owner_has_them():+ config = json.loads((REPO / "steam/steam.json").read_text())+ assert set(config) == {"app_id", "depots", "branches"} and set(config["depots"]) == set(su.PLATFORMS)+ assert config["branches"] == ["beta", "nightly"]+ for value in [config["app_id"], *config["depots"].values()]:+ assert value is None or (isinstance(value, int) and value > 0)+++def test_null_ids_refuse_by_name():+ nulls = {"app_id": None, "depots": {"windows": 1001, "mac": None, "linux": None}, "branches": ["beta", "nightly"]}+ problem = su.refuse(nulls)+ assert problem is not None+ for name in ("app_id", "depots.mac", "depots.linux"):+ assert name in problem+ assert "depots.windows" not in problem+ assert su.refuse(IDS) is None+++def test_the_game_app_id_matches_steam_json():+ config = json.loads((REPO / "steam/steam.json").read_text())+ source = REPO / "unity/Assets/Steam/SteamAppId.cs"+ if not source.exists():+ # The Steam assembly lands with #2154 (plan Task 6); until then nothing may give the app an ID only here.+ assert config["app_id"] is None, "steam/steam.json has an app ID but unity/Assets/Steam/SteamAppId.cs is missing"+ return+ m = re.search(r"\bValue\s*=\s*(\d+)u?\s*;", source.read_text())+ assert m, f"no `Value = <number>;` in {source}"+ assert int(m.group(1)) == (config["app_id"] or 0)++[email protected]("over, word", [({"dev": True}, "dev"), ({"tree_clean_after_builds": False}, "dirty"),+ ({"tree_clean": False}, "dirty"), ({"channel": "default"}, "channel"),+ ({"channel": None}, "channel"), ({"steam": False}, "Steam")])+def test_a_dev_or_dirty_record_is_refused(over, word):+ assert su.refuse(IDS, record()) is None+ problem = su.refuse(IDS, record(**over))+ assert problem is not None and word in problem+++# --- render ------------------------------------------------------------------------------------------------------------++def test_render_matches_a_golden_vdf(tmp_path):+ root = tmp_path / "content"+ root.mkdir()+ paths = su.render(IDS, root, "v0.3.2", SHA, "nightly")+ names = sorted(p.name for p in paths)+ assert names == ["app_build_1000.vdf", "depot_build_1001.vdf", "depot_build_1002.vdf", "depot_build_1003.vdf"]+ by_name = {p.name: p for p in paths}+ app = by_name["app_build_1000.vdf"].read_text().replace(str(root.resolve()), "<root>")+ assert app == (DATA / "app_build_1000.vdf").read_text()+ assert by_name["depot_build_1002.vdf"].read_text() == (DATA / "depot_build_1002.vdf").read_text()+ for p in paths:+ assert p.parent == by_name["app_build_1000.vdf"].parent, "the depot scripts sit beside the app script"+ assert by_name["app_build_1000.vdf"].parent != root.resolve(), "the scripts are never uploaded as content"++[email protected]("branch", ["default", "Default", "", "public", "beta2"])+def test_default_branch_is_never_rendered(tmp_path, branch):+ with pytest.raises(ValueError):+ su.render(IDS, tmp_path, "v0.3.2", SHA, branch)+ with pytest.raises(ValueError): # not even when someone adds it to steam.json+ su.render({**IDS, "branches": ["beta", "nightly", "default"]}, tmp_path, "v0.3.2", SHA, "default")+ assert not list(tmp_path.glob("**/*.vdf"))+++def test_render_refuses_null_ids_and_a_bad_tag_or_commit(tmp_path):+ with pytest.raises(ValueError, match="app_id"):+ su.render({**IDS, "app_id": None}, tmp_path, "v0.3.2", SHA, "beta")+ with pytest.raises(ValueError):+ su.render(IDS, tmp_path, 'v0.3.2" "SetLive" "default', SHA, "beta")+ with pytest.raises(ValueError):+ su.render(IDS, tmp_path, "v0.3.2", "HEAD", "beta")+++# --- stage -------------------------------------------------------------------------------------------------------------++def stage(tmp_path, gh, config=IDS, upload_tag="v0.3.2", **over):+ out = release_folder(tmp_path, **over)+ su.stage(out, upload_tag, gh, config_path=config_file(tmp_path, config))+ return out+++def test_stage_writes_hashes_and_only_a_draft(tmp_path):+ gh = FakeGh()+ out = stage(tmp_path, gh)+ rec = json.loads((out / "steam-record.json").read_text())+ assert rec["tag"] == "v0.3.2" and rec["commit"] == SHA and rec["branch"] == "nightly"+ assert set(rec["assets"]) == {f"steam-v0.3.2-{p}.zip" for p in su.PLATFORMS}+ for name, meta in rec["assets"].items():+ data = (out / name).read_bytes()+ assert meta == {"sha256": hashlib.sha256(data).hexdigest(), "size": len(data)}+ releases = [c for c in gh.calls if c[0] == "release"]+ create = [c for c in releases if c[1] == "create"]+ assert len(create) == 1 and "--draft" in create[0] and create[0][2] == "steam-v0.3.2"+ assert create[0][create[0].index("--target") + 1] == SHA+ uploaded = {Path(a).name for a in create[0] if a.endswith((".zip", ".json"))}+ assert uploaded == {*rec["assets"], "steam-record.json"}+ for c in releases:+ assert c[1] in ("view", "create"), c+ assert not any(x.startswith("--draft=") or x in ("--latest", "--prerelease") for x in c), c+ assert not [c for c in gh.calls if c[:2] == ["release", "edit"]], "a draft is never published"+++def test_stage_replaces_only_a_draft_of_that_name(tmp_path):+ gh = FakeGh(existing=True)+ stage(tmp_path, gh)+ assert ["release", "delete", "steam-v0.3.2", "--yes"] in gh.calls+ gh = FakeGh(existing=False)+ with pytest.raises(SystemExit, match="published"):+ stage(tmp_path / "again", gh)+ assert not [c for c in gh.calls if c[:2] in (["release", "delete"], ["release", "create"], ["workflow", "run"])]+++def test_stage_dispatches_with_the_records_branch(tmp_path):+ for channel in ("beta", "nightly"):+ gh = FakeGh()+ stage(tmp_path / channel, gh, channel=channel)+ digest = hashlib.sha256((tmp_path / channel / "release/steam-record.json").read_bytes()).hexdigest()+ assert gh.calls[-1] == ["workflow", "run", "steam-upload.yml", "--ref", "main", "-f", "tag=v0.3.2",+ "-f", f"branch={channel}", "-f", f"record_sha256={digest}"]++[email protected]("over, tag", [({"dev": True}, "v0.3.2"), ({"channel": "default"}, "v0.3.2"),+ ({}, "v0.3.3"), ({"tag": "v0.3.2-rc1"}, "v0.3.2-rc1"),+ ({"artifacts": [{"platform": "linux", "steam_folder": "steam/linux"}]}, "v0.3.2")])+def test_stage_refuses_before_any_gh_call(tmp_path, over, tag):+ gh = FakeGh()+ with pytest.raises(SystemExit):+ stage(tmp_path, gh, upload_tag=tag, **over)+ assert gh.calls == []+++def test_stage_refuses_null_ids_before_any_gh_call(tmp_path):+ gh = FakeGh()+ with pytest.raises(SystemExit, match="app_id"):+ stage(tmp_path, gh, config={**IDS, "app_id": None})+ assert gh.calls == []+++def test_stage_keeps_the_executable_bits(tmp_path):+ out = stage(tmp_path, FakeGh())+ with zipfile.ZipFile(out / "steam-v0.3.2-linux.zip") as z:+ modes = {i.filename: i.external_attr >> 16 for i in z.infolist()}+ assert z.getinfo("Statecraft.x86_64").create_system == 3 # Unix, so unzip honours the mode+ assert stat.S_IMODE(modes["Statecraft.x86_64"]) == 0o755 and stat.S_IMODE(modes["LICENSE"]) == 0o644+ with zipfile.ZipFile(out / "steam-v0.3.2-mac.zip") as z:+ modes = {i.filename: i.external_attr >> 16 for i in z.infolist()}+ assert stat.S_IMODE(modes["Statecraft.app/Contents/MacOS/Statecraft Israel"]) == 0o755+++def test_stage_keeps_symlinks_as_links(tmp_path):+ out = release_folder(tmp_path)+ fw = out / "steam/mac/Statecraft.app/Contents/Frameworks/X.framework"+ (fw / "Versions/A").mkdir(parents=True)+ (fw / "Versions/A/X").write_bytes(b"lib")+ (fw / "Versions/Current").symlink_to("A")+ file_list_hashes(out, json.loads((out / "build-record.json").read_text())) # the build saw the framework too+ su.stage(out, "v0.3.2", FakeGh(), config_path=config_file(tmp_path))+ with zipfile.ZipFile(out / "steam-v0.3.2-mac.zip") as z:+ info = z.getinfo("Statecraft.app/Contents/Frameworks/X.framework/Versions/Current")+ assert stat.S_ISLNK(info.external_attr >> 16) and z.read(info) == b"A"+++# --- the upload job's own check ----------------------------------------------------------------------------------------++def downloaded(tmp_path):+ out = stage(tmp_path, FakeGh())+ d = tmp_path / "download"+ d.mkdir()+ for f in [*out.glob("steam-*.zip"), out / "steam-record.json"]:+ (d / f.name).write_bytes(f.read_bytes())+ return d+++def record_digest(d):+ return hashlib.sha256((d / "steam-record.json").read_bytes()).hexdigest()+++def test_verify_checks_hashes_tag_and_branch(tmp_path, capsys):+ d = downloaded(tmp_path)+ digest = record_digest(d)+ assert su.verify(d, "v0.3.2", "nightly", digest) == SHA+ with pytest.raises(SystemExit, match="branch"):+ su.verify(d, "v0.3.2", "beta", digest)+ with pytest.raises(SystemExit, match="tag"):+ su.verify(d, "v0.3.3", "nightly", digest)+ (d / "steam-v0.3.2-linux.zip").write_bytes(b"replaced")+ with pytest.raises(SystemExit, match="sha256"):+ su.verify(d, "v0.3.2", "nightly", digest)+++# --- no credential, ever -----------------------------------------------------------------------------------------------++def test_no_option_takes_a_credential():+ parser = su.parser()+ options = [o for action in parser._actions for o in action.option_strings]+ for sub in parser._subparsers._group_actions[0].choices.values():+ options += [o for action in sub._actions for o in action.option_strings]+ assert options+ for o in options:+ assert not re.search(r"password|token|secret|vdf|user|login|key", o, re.I), o+ source = (REPO / "tools/steam_upload.py").read_text()+ assert "STEAM_CONFIG_VDF" not in source and "STEAM_BUILDER_USERNAME" not in source and "getpass" not in source+++def test_steamcmd_is_never_run_here(tmp_path):+ # The autouse fixture fails any process start; the whole hand-over runs with gh faked and starts none.+ stage(tmp_path, FakeGh())+ source = (REPO / "tools/steam_upload.py").read_text()+ assert not re.search(r"""["']steamcmd""", source), "steam_upload.py never names steamcmd as a command"+++def test_verify_refuses_a_record_whose_hash_is_not_the_dispatched_one(tmp_path):+ # Review (a review agent, k2 C1): the draft is mutable, so a swapped zip with a matching rewritten record must fail+ # against the record hash the owner's machine put in the dispatch.+ d = downloaded(tmp_path)+ digest = record_digest(d)+ (d / "steam-v0.3.2-linux.zip").write_bytes(b"trojan")+ rec = json.loads((d / "steam-record.json").read_text())+ rec["assets"]["steam-v0.3.2-linux.zip"] = {"sha256": hashlib.sha256(b"trojan").hexdigest(), "size": 6}+ (d / "steam-record.json").write_text(json.dumps(rec))+ with pytest.raises(SystemExit, match="record_sha256"):+ su.verify(d, "v0.3.2", "nightly", digest)+ with pytest.raises(SystemExit, match="record_sha256"):+ su.verify(d, "v0.3.2", "nightly", "not-a-hash")+++def test_stage_ships_only_what_the_file_list_names(tmp_path):+ # Review (k2 C3): Unity's *_DoNotShip folders and the photo manifest never reach Steam, as with the GitHub archives.+ out = stage(tmp_path, FakeGh())+ for p in su.PLATFORMS:+ with zipfile.ZipFile(out / f"steam-v0.3.2-{p}.zip") as z:+ names = z.namelist()+ assert not [n for n in names if "_DoNotShip" in n or n == rb.PHOTOS], names+ assert "LICENSE" in names++[email protected]("change", ["appid", "edited", "added"])+def test_stage_refuses_a_folder_changed_after_the_build(tmp_path, change):+ # Review (k2 C3): stage re-checks the folder it zips against the build's own record before any gh call.+ out = release_folder(tmp_path)+ linux = out / "steam/linux"+ if change == "appid":+ (linux / "steam_appid.txt").write_text("480")+ elif change == "edited":+ (linux / "Statecraft.x86_64").write_bytes(b"other")+ else:+ (linux / "Player.log").write_text("ran here")+ gh = FakeGh()+ with pytest.raises(SystemExit):+ su.stage(out, "v0.3.2", gh, config_path=config_file(tmp_path))+ assert gh.calls == []