diff --git a/.github/actions/export-web/action.yml b/.github/actions/export-web/action.yml index afbb0bc..621d879 100644 --- a/.github/actions/export-web/action.yml +++ b/.github/actions/export-web/action.yml @@ -2,7 +2,6 @@ name: "Export Godot C# project to Web (WASM)" description: > Builds an experimental C#/.NET WebAssembly export using ComplexRobot's patched Windows editor build. Must run on a windows-latest runner. Produces build/web. - Step logic lives in ./scripts/*.ps1. inputs: # These three intentionally default to EMPTY. When empty they are resolved from @@ -26,6 +25,30 @@ inputs: description: "Token for downloading the fork release via gh" required: true + # Build stamp. Compiled into the binary so the About screen and the test bridge can report + # which commit produced the running build. Blank is legitimate — it produces a build that + # honestly reports itself as untraceable rather than one carrying a misleading hash. + build_commit: + description: "Full commit SHA this build is made from (blank = unstamped)" + required: false + default: "" + build_branch: + description: "Branch or tag name, without any refs/heads/ prefix" + required: false + default: "" + build_repository: + description: "owner/repo, used to build commit and run links" + required: false + default: "" + build_run_id: + description: "GitHub Actions run id that produced this build" + required: false + default: "" + build_run_attempt: + description: "Run attempt — a re-run of the same commit is a different artefact" + required: false + default: "" + outputs: web_dir: description: "Path to the exported web output" @@ -36,6 +59,12 @@ outputs: template_version: description: "The export-template version actually used for this export" value: ${{ steps.toolchain.outputs.template_version }} + build_commit: + description: > + The commit this export was actually stamped with. Prefer this over github.sha when + asserting what a deploy serves: for issue_comment-triggered runs github.sha is the + default branch, not the PR head that was built. + value: ${{ steps.stamp.outputs.commit }} runs: using: composite @@ -47,7 +76,21 @@ runs: IN_FORK_REPO: ${{ inputs.fork_repo }} IN_FORK_TAG: ${{ inputs.godot_fork_tag }} IN_TEMPLATE_VERSION: ${{ inputs.template_version }} - run: '& "${{ github.action_path }}/scripts/resolve-toolchain.ps1"' + run: '& "$env:GITHUB_ACTION_PATH/scripts/resolve-toolchain.ps1"' + + - name: Resolve build stamp + id: stamp + shell: pwsh + env: + IN_COMMIT: ${{ inputs.build_commit }} + IN_BRANCH: ${{ inputs.build_branch }} + IN_REPOSITORY: ${{ inputs.build_repository }} + IN_RUN_ID: ${{ inputs.build_run_id }} + IN_RUN_ATTEMPT: ${{ inputs.build_run_attempt }} + CTX_REPOSITORY: ${{ github.repository }} + CTX_RUN_ID: ${{ github.run_id }} + CTX_RUN_ATTEMPT: ${{ github.run_attempt }} + run: '& "$env:GITHUB_ACTION_PATH/scripts/resolve-build-stamp.ps1"' - name: Guard against version drift shell: pwsh @@ -55,7 +98,7 @@ runs: TEMPLATE_VERSION: ${{ steps.toolchain.outputs.template_version }} FORK_TAG: ${{ steps.toolchain.outputs.fork_tag }} ASSET: ${{ steps.toolchain.outputs.asset }} - run: '& "${{ github.action_path }}/scripts/check-version-drift.ps1"' + run: '& "$env:GITHUB_ACTION_PATH/scripts/check-version-drift.ps1"' - name: Set up .NET 9 SDK uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 @@ -81,13 +124,16 @@ runs: FORK_REPO: ${{ steps.toolchain.outputs.fork_repo }} FORK_TAG: ${{ steps.toolchain.outputs.fork_tag }} ASSET: ${{ steps.toolchain.outputs.asset }} - run: '& "${{ github.action_path }}/scripts/download-editor.ps1"' + run: | + New-Item -ItemType Directory -Force -Path "${env:RUNNER_TEMP}/godot-zip" | Out-Null + Write-Host "Downloading $env:ASSET from $env:FORK_REPO@$env:FORK_TAG" + gh release download "$env:FORK_TAG" --repo "$env:FORK_REPO" --pattern "$env:ASSET" --dir "${env:RUNNER_TEMP}/godot-zip" - name: Verify editor checksum (supply-chain guard) shell: pwsh env: ASSET: ${{ steps.toolchain.outputs.asset }} - run: '& "${{ github.action_path }}/scripts/verify-editor-checksum.ps1"' + run: '& "$env:GITHUB_ACTION_PATH/scripts/verify-editor-checksum.ps1"' - name: Extract editor shell: pwsh @@ -98,34 +144,67 @@ runs: - name: Locate editor executable and bundle contents id: locate shell: pwsh - run: '& "${{ github.action_path }}/scripts/locate-editor.ps1"' + run: '& "$env:GITHUB_ACTION_PATH/scripts/locate-editor.ps1"' - name: Install web export templates (self-contained mode) shell: pwsh env: - BUNDLE_DIR: ${{ steps.locate.outputs.bundle_dir }} TEMPLATE_VERSION: ${{ steps.toolchain.outputs.template_version }} - run: '& "${{ github.action_path }}/scripts/install-templates.ps1"' + BUNDLE_DIR: ${{ steps.locate.outputs.bundle_dir }} + run: '& "$env:GITHUB_ACTION_PATH/scripts/install-templates.ps1"' - name: Register bundled NuGet source (if present) shell: pwsh - run: '& "${{ github.action_path }}/scripts/register-nuget-source.ps1"' - + run: '& "$env:GITHUB_ACTION_PATH/scripts/register-nuget-source.ps1"' + # Build-stamp variables are set as ENVIRONMENT variables on the build and export steps + # rather than passed with -p:. The export step re-enters MSBuild through the Godot editor, + # whose command line we do not control; MSBuild reads environment variables as properties, + # so this is the one channel that reaches both. Consumed by the GenerateBuildStamp target + # in ProceduralGeneration3DMazes.csproj. See docs/BUILD_VERIFICATION.md. - name: Restore / build (net9.0) shell: pwsh + env: + BuildCommit: ${{ steps.stamp.outputs.commit }} + BuildBranch: ${{ steps.stamp.outputs.branch }} + BuildRepository: ${{ steps.stamp.outputs.repository }} + BuildRunId: ${{ steps.stamp.outputs.run_id }} + BuildRunAttempt: ${{ steps.stamp.outputs.run_attempt }} + BuildTimestampUtc: ${{ steps.stamp.outputs.timestamp }} run: dotnet build ProceduralGeneration3DMazes.csproj -c ExportRelease /p:GodotTargetPlatform=web - name: Import resources (headless) shell: pwsh continue-on-error: true - run: | - & "${{ steps.locate.outputs.godot_exe }}" --headless --path . --import 2>&1 | Tee-Object -FilePath import.log + env: + GODOT_EXE: ${{ steps.locate.outputs.godot_exe }} + run: '& "$env:GITHUB_ACTION_PATH/scripts/import-project.ps1"' - name: Export Web (headless CLI) shell: pwsh env: GODOT_EXE: ${{ steps.locate.outputs.godot_exe }} - run: '& "${{ github.action_path }}/scripts/export-web.ps1"' + BuildCommit: ${{ steps.stamp.outputs.commit }} + BuildBranch: ${{ steps.stamp.outputs.branch }} + BuildRepository: ${{ steps.stamp.outputs.repository }} + BuildRunId: ${{ steps.stamp.outputs.run_id }} + BuildRunAttempt: ${{ steps.stamp.outputs.run_attempt }} + BuildTimestampUtc: ${{ steps.stamp.outputs.timestamp }} + run: '& "$env:GITHUB_ACTION_PATH/scripts/export-web.ps1"' + # A sibling of index.html, so the served build can be identified with a plain curl without + # booting a 96 MB WASM payload in a browser. The About screen reads its values from the + # compiled-in stamp, not from this file — they come from the same inputs, so a mismatch + # between the two would itself be a signal that something repackaged the deploy. + - name: Write build-info.json + shell: pwsh + env: + BUILD_COMMIT: ${{ steps.stamp.outputs.commit }} + BUILD_BRANCH: ${{ steps.stamp.outputs.branch }} + BUILD_REPOSITORY: ${{ steps.stamp.outputs.repository }} + BUILD_RUN_ID: ${{ steps.stamp.outputs.run_id }} + BUILD_RUN_ATTEMPT: ${{ steps.stamp.outputs.run_attempt }} + BUILD_TIMESTAMP: ${{ steps.stamp.outputs.timestamp }} + FORK_TAG: ${{ steps.toolchain.outputs.fork_tag }} + run: '& "$env:GITHUB_ACTION_PATH/scripts/write-build-info.ps1"' - name: Upload web export artifact if: always() diff --git a/.github/actions/export-web/scripts/check-version-drift.ps1 b/.github/actions/export-web/scripts/check-version-drift.ps1 index 08b35c5..8d90fdc 100644 --- a/.github/actions/export-web/scripts/check-version-drift.ps1 +++ b/.github/actions/export-web/scripts/check-version-drift.ps1 @@ -1,18 +1,33 @@ -# Fail fast (before the 165 MB editor download) if the Godot.NET.Sdk version (csproj), -# the patched-editor tag, and the export-template folder disagree at PATCH level, or if -# the target editor asset has no pinned checksum. +# Fail fast if the Godot SDK, export templates and editor tag disagree. # -# The three values spell the same version differently; normalise to bare x.y[.z]: -# csproj "4.7.1" -> 4.7.1 -# template "4.7.1.stable.mono" -> 4.7.1 -# fork tag "4.7.1-stable" -> 4.7.1 -# Godot names x.y releases without a patch component (template "4.7.stable.mono"), -# so a csproj SDK of "4.7.0" normalises to "4.7". +# Compares at PATCH level -- major.minor alone lets a 4.7.0-vs-4.7.1 mismatch through, which is the most common kind of bump. +# +# Extracted from action.yml rather than inlined there: a 40-line script inside a YAML block +# scalar cannot be linted, cannot be run outside CI, and silently breaks on constructs the +# block scalar swallows -- a PowerShell here-string (@"..."@) needs its terminator at column 0, +# which ends the YAML block. See docs/WEB_EXPORT.md. # -# Env in: TEMPLATE_VERSION, FORK_TAG, ASSET +# Inputs (environment): +# TEMPLATE_VERSION, FORK_TAG, ASSET +Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' +# Actions' pwsh wrapper sets these; set them here too so the script behaves identically when +# run by hand, and so a failing native command (git/gh/dotnet/godot) is not silently ignored. +$PSNativeCommandUseErrorActionPreference = $true +# The Godot.NET.Sdk version (csproj), the patched-editor tag, and the +# export-template folder must agree at PATCH level — comparing only +# major.minor lets a 4.7.0-vs-4.7.1 mismatch through, which is exactly the +# class of bump that happens most often. Catch it in seconds, before we +# download a 165 MB editor. +# +# Normalise the three spellings of the same version to a bare x.y[.z]: +# csproj "4.7.1" -> 4.7.1 ("4.7.0" -> 4.7, see below) +# template "4.7.1.stable.mono" -> 4.7.1 +# fork tag "4.7.1-stable" -> 4.7.1 +# Godot names x.y releases without a patch component, so an SDK version of +# "4.7.0" corresponds to template "4.7.stable.mono": strip a trailing ".0". function Get-BareVersion([string]$s) { return ($s -replace '[-.](stable|beta|rc|dev)[-.0-9]*.*$', '') } @@ -23,17 +38,22 @@ $sdkVersion = $Matches[1] -replace '\.0$', '' $tplVersion = Get-BareVersion $env:TEMPLATE_VERSION $tagVersion = Get-BareVersion $env:FORK_TAG -if (($sdkVersion -ne $tplVersion) -or ($sdkVersion -ne $tagVersion)) { - throw @" -Version drift - these must all describe the same Godot version: - Godot.NET.Sdk (csproj) -> $sdkVersion - template_version -> $tplVersion (raw: $env:TEMPLATE_VERSION) - godot_fork_tag -> $tagVersion (raw: $env:FORK_TAG) -Align them in ProceduralGeneration3DMazes.csproj and .github/web-toolchain.env. -See docs/WEB_EXPORT.md -> 'Updating the pinned editor'. -"@ +$mismatch = ($sdkVersion -ne $tplVersion) -or ($sdkVersion -ne $tagVersion) +if ($mismatch) { + # Built as an array rather than a here-string: a PowerShell here-string needs + # its closing "@ at column 0, which would terminate this YAML block scalar. + throw (@( + "Version drift - these must all describe the same Godot version:", + " Godot.NET.Sdk (csproj) -> $sdkVersion", + " template_version -> $tplVersion (raw: $env:TEMPLATE_VERSION)", + " godot_fork_tag -> $tagVersion (raw: $env:FORK_TAG)", + "Align them in ProceduralGeneration3DMazes.csproj and .github/web-toolchain.env.", + "See docs/WEB_EXPORT.md -> 'Updating the pinned editor'." + ) -join "`n") } +# Fail fast if the editor we're about to fetch has no pinned checksum, rather +# than after spending a runner-minute downloading it. $pinned = Get-Content .github/editor-checksums.txt | Where-Object { $_ -notmatch '^\s*#' -and $_ -match [regex]::Escape($env:ASSET) } if (-not $pinned) { diff --git a/.github/actions/export-web/scripts/download-editor.ps1 b/.github/actions/export-web/scripts/download-editor.ps1 deleted file mode 100644 index 009d92c..0000000 --- a/.github/actions/export-web/scripts/download-editor.ps1 +++ /dev/null @@ -1,9 +0,0 @@ -# Download the patched Godot editor zip from the fork release. -# Env in: GH_TOKEN, FORK_REPO, FORK_TAG, ASSET - -$ErrorActionPreference = 'Stop' - -New-Item -ItemType Directory -Force -Path "${env:RUNNER_TEMP}/godot-zip" | Out-Null -Write-Host "Downloading $env:ASSET from $env:FORK_REPO@$env:FORK_TAG" -gh release download "$env:FORK_TAG" --repo "$env:FORK_REPO" --pattern "$env:ASSET" --dir "${env:RUNNER_TEMP}/godot-zip" -if ($LASTEXITCODE -ne 0) { throw "gh release download failed (exit $LASTEXITCODE)." } diff --git a/.github/actions/export-web/scripts/export-web.ps1 b/.github/actions/export-web/scripts/export-web.ps1 index 8111a5f..c14aabf 100644 --- a/.github/actions/export-web/scripts/export-web.ps1 +++ b/.github/actions/export-web/scripts/export-web.ps1 @@ -1,7 +1,20 @@ -# Run the headless web export and fail loudly if no output was produced. -# Env in: GODOT_EXE +# Run the headless web export and confirm it produced output. +# +# The export can exit 0 while producing nothing, so index.html is checked explicitly. +# +# Extracted from action.yml rather than inlined there: a 40-line script inside a YAML block +# scalar cannot be linted, cannot be run outside CI, and silently breaks on constructs the +# block scalar swallows -- a PowerShell here-string (@"..."@) needs its terminator at column 0, +# which ends the YAML block. See docs/WEB_EXPORT.md. +# +# Inputs (environment): +# GODOT_EXE +Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' +# Actions' pwsh wrapper sets these; set them here too so the script behaves identically when +# run by hand, and so a failing native command (git/gh/dotnet/godot) is not silently ignored. +$PSNativeCommandUseErrorActionPreference = $true New-Item -ItemType Directory -Force -Path "build/web" | Out-Null & "$env:GODOT_EXE" --headless --path . --export-release "Web" "build/web/index.html" 2>&1 | Tee-Object -FilePath export.log diff --git a/.github/actions/export-web/scripts/import-project.ps1 b/.github/actions/export-web/scripts/import-project.ps1 new file mode 100644 index 0000000..36d4df3 --- /dev/null +++ b/.github/actions/export-web/scripts/import-project.ps1 @@ -0,0 +1,19 @@ +# Import the project's resources headlessly before exporting. +# +# Godot must import once or the export produces an incomplete PCK. +# +# Extracted from action.yml rather than inlined there: a 40-line script inside a YAML block +# scalar cannot be linted, cannot be run outside CI, and silently breaks on constructs the +# block scalar swallows -- a PowerShell here-string (@"..."@) needs its terminator at column 0, +# which ends the YAML block. See docs/WEB_EXPORT.md. +# +# Inputs (environment): +# GODOT_EXE + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +# Actions' pwsh wrapper sets these; set them here too so the script behaves identically when +# run by hand, and so a failing native command (git/gh/dotnet/godot) is not silently ignored. +$PSNativeCommandUseErrorActionPreference = $true + +& "$env:GODOT_EXE" --headless --path . --import 2>&1 | Tee-Object -FilePath import.log diff --git a/.github/actions/export-web/scripts/install-templates.ps1 b/.github/actions/export-web/scripts/install-templates.ps1 index 6923193..c0afbbc 100644 --- a/.github/actions/export-web/scripts/install-templates.ps1 +++ b/.github/actions/export-web/scripts/install-templates.ps1 @@ -1,14 +1,25 @@ -# Install the bundled web export templates in self-contained mode (next to the -# editor, via a "._sc_" marker — no AppData). -# Env in: BUNDLE_DIR, TEMPLATE_VERSION +# Install the web export templates into the editor bundle (self-contained mode). +# +# A `._sc_` marker makes the editor look for templates beside itself instead of in the user profile. +# +# Extracted from action.yml rather than inlined there: a 40-line script inside a YAML block +# scalar cannot be linted, cannot be run outside CI, and silently breaks on constructs the +# block scalar swallows -- a PowerShell here-string (@"..."@) needs its terminator at column 0, +# which ends the YAML block. See docs/WEB_EXPORT.md. +# +# Inputs (environment): +# TEMPLATE_VERSION, BUNDLE_DIR +Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' +# Actions' pwsh wrapper sets these; set them here too so the script behaves identically when +# run by hand, and so a failing native command (git/gh/dotnet/godot) is not silently ignored. +$PSNativeCommandUseErrorActionPreference = $true -$bundle = $env:BUNDLE_DIR +$bundle = "$env:BUNDLE_DIR" New-Item -ItemType File -Force -Path (Join-Path $bundle "._sc_") | Out-Null $tplDir = Join-Path $bundle "editor_data/export_templates/${env:TEMPLATE_VERSION}" New-Item -ItemType Directory -Force -Path $tplDir | Out-Null - $templates = Get-ChildItem -Path "$env:RUNNER_TEMP/godot" -Recurse -Include "web_release.zip","web_debug.zip" if (-not $templates) { Get-ChildItem -Path "$env:RUNNER_TEMP/godot" -Recurse -File | Select-Object -ExpandProperty FullName diff --git a/.github/actions/export-web/scripts/locate-editor.ps1 b/.github/actions/export-web/scripts/locate-editor.ps1 index 2ba7798..6c2ba7c 100644 --- a/.github/actions/export-web/scripts/locate-editor.ps1 +++ b/.github/actions/export-web/scripts/locate-editor.ps1 @@ -1,8 +1,17 @@ -# Find the Godot editor executable inside the extracted fork bundle (prefer the -# console build) and report it plus its directory for later steps. -# Outputs: godot_exe, bundle_dir +# Locate the editor executable inside the extracted fork bundle. +# +# The fork's zip layout is not guaranteed stable, so the exe is discovered rather than assumed. +# +# Extracted from action.yml rather than inlined there: a 40-line script inside a YAML block +# scalar cannot be linted, cannot be run outside CI, and silently breaks on constructs the +# block scalar swallows -- a PowerShell here-string (@"..."@) needs its terminator at column 0, +# which ends the YAML block. See docs/WEB_EXPORT.md. +Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' +# Actions' pwsh wrapper sets these; set them here too so the script behaves identically when +# run by hand, and so a failing native command (git/gh/dotnet/godot) is not silently ignored. +$PSNativeCommandUseErrorActionPreference = $true $root = "$env:RUNNER_TEMP/godot" $exe = Get-ChildItem -Path $root -Recurse -Filter "*.exe" | diff --git a/.github/actions/export-web/scripts/register-nuget-source.ps1 b/.github/actions/export-web/scripts/register-nuget-source.ps1 index e424c53..041104d 100644 --- a/.github/actions/export-web/scripts/register-nuget-source.ps1 +++ b/.github/actions/export-web/scripts/register-nuget-source.ps1 @@ -1,6 +1,17 @@ -# Register the fork's bundled local NuGet source, if the bundle ships one. +# Register the fork's bundled NuGet source, when it ships one. +# +# The patched editor may carry Godot NuGet packages that are not on nuget.org. +# +# Extracted from action.yml rather than inlined there: a 40-line script inside a YAML block +# scalar cannot be linted, cannot be run outside CI, and silently breaks on constructs the +# block scalar swallows -- a PowerShell here-string (@"..."@) needs its terminator at column 0, +# which ends the YAML block. See docs/WEB_EXPORT.md. +Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' +# Actions' pwsh wrapper sets these; set them here too so the script behaves identically when +# run by hand, and so a failing native command (git/gh/dotnet/godot) is not silently ignored. +$PSNativeCommandUseErrorActionPreference = $true $nuget = Get-ChildItem -Path "$env:RUNNER_TEMP/godot" -Recurse -Directory -Filter "nuget" | Select-Object -First 1 if ($nuget) { diff --git a/.github/actions/export-web/scripts/resolve-build-stamp.ps1 b/.github/actions/export-web/scripts/resolve-build-stamp.ps1 new file mode 100644 index 0000000..d2e4344 --- /dev/null +++ b/.github/actions/export-web/scripts/resolve-build-stamp.ps1 @@ -0,0 +1,77 @@ +# Resolve the build stamp compiled into the binary. +# +# Derived here rather than trusted from the caller: an issue_comment run takes the workflow file from the default branch, so a caller's inputs can be silently absent. +# +# Extracted from action.yml rather than inlined there: a 40-line script inside a YAML block +# scalar cannot be linted, cannot be run outside CI, and silently breaks on constructs the +# block scalar swallows -- a PowerShell here-string (@"..."@) needs its terminator at column 0, +# which ends the YAML block. See docs/WEB_EXPORT.md. +# +# Inputs (environment): +# IN_COMMIT, IN_BRANCH, IN_REPOSITORY, IN_RUN_ID, IN_RUN_ATTEMPT (overrides; blank = derive) +# CTX_REPOSITORY, CTX_RUN_ID, CTX_RUN_ATTEMPT (from the github context) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +# Actions' pwsh wrapper sets these; set them here too so the script behaves identically when +# run by hand, and so a failing native command (git/gh/dotnet/godot) is not silently ignored. +$PSNativeCommandUseErrorActionPreference = $true + +# Derived HERE, with the caller's inputs as optional overrides, because the caller +# cannot always be trusted to supply them. +# +# A `/preview` run proved why: for issue_comment events GitHub loads the WORKFLOW FILE +# from the default branch, while the composite action comes from the checked-out PR +# head. A PR that adds `with: build_commit:` therefore has its own caller ignored, and +# every caller-supplied field arrived empty — the artefact built fine and reported +# itself as untraceable. Reading the commit from the checkout instead makes the stamp +# correct no matter which caller invoked us, or whether it passed anything at all. +function Resolve-Stamp($override, $fallback, $name) { + if (-not [string]::IsNullOrWhiteSpace($override)) { return $override.Trim() } + return $fallback +} + +# The commit that is actually checked out — the thing being built, by definition. +$gitCommit = "" +try { + $gitCommit = (git rev-parse HEAD 2>$null | Out-String).Trim() +} catch { + Write-Host "::warning::git rev-parse HEAD failed; build will be unstamped." +} +if ($gitCommit -notmatch '^[0-9a-fA-F]{40}$') { $gitCommit = "" } + +# A checkout by SHA is detached, so this is usually "HEAD" — not a branch name. Only +# report it when it is a real one; a wrong branch is worse than a missing one. +$gitBranch = "" +try { + $b = (git rev-parse --abbrev-ref HEAD 2>$null | Out-String).Trim() + if ($b -and $b -ne "HEAD") { $gitBranch = $b } +} catch { } + +$commit = Resolve-Stamp $env:IN_COMMIT $gitCommit 'commit' +$branch = Resolve-Stamp $env:IN_BRANCH $gitBranch 'branch' +$repository = Resolve-Stamp $env:IN_REPOSITORY $env:CTX_REPOSITORY 'repository' +$runId = Resolve-Stamp $env:IN_RUN_ID $env:CTX_RUN_ID 'runId' +$runAttempt = Resolve-Stamp $env:IN_RUN_ATTEMPT $env:CTX_RUN_ATTEMPT 'runAttempt' + +# Recorded here so it reflects when the artefact was actually produced. The same +# string reaches the About screen and build-info.json — they are meant to be +# compared literally. +$timestamp = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ") + +"commit=$commit" >> $env:GITHUB_OUTPUT +"branch=$branch" >> $env:GITHUB_OUTPUT +"repository=$repository" >> $env:GITHUB_OUTPUT +"run_id=$runId" >> $env:GITHUB_OUTPUT +"run_attempt=$runAttempt" >> $env:GITHUB_OUTPUT +"timestamp=$timestamp" >> $env:GITHUB_OUTPUT + +Write-Host "Build stamp:" +Write-Host " commit = $(if ($commit) { $commit } else { '(none — build will report itself untraceable)' })" +Write-Host " branch = $branch" +Write-Host " repository = $repository" +Write-Host " run = $runId (attempt $runAttempt)" +Write-Host " timestamp = $timestamp" +if (-not $commit) { + Write-Host "::warning::No commit resolved — the About screen will report this as a local, untraceable build." +} diff --git a/.github/actions/export-web/scripts/resolve-toolchain.ps1 b/.github/actions/export-web/scripts/resolve-toolchain.ps1 index f1d068a..e662f64 100644 --- a/.github/actions/export-web/scripts/resolve-toolchain.ps1 +++ b/.github/actions/export-web/scripts/resolve-toolchain.ps1 @@ -1,11 +1,22 @@ -# Resolve the web-export toolchain versions: read .github/web-toolchain.env (the -# single source of truth), then let non-empty action inputs override individual values. +# Resolve the Godot toolchain versions for this export. # -# Env in: IN_FORK_REPO, IN_FORK_TAG, IN_TEMPLATE_VERSION (action inputs, may be blank) -# Outputs: fork_repo, fork_tag, template_version, asset +# Single source of truth is .github/web-toolchain.env; non-empty action inputs override it. +# +# Extracted from action.yml rather than inlined there: a 40-line script inside a YAML block +# scalar cannot be linted, cannot be run outside CI, and silently breaks on constructs the +# block scalar swallows -- a PowerShell here-string (@"..."@) needs its terminator at column 0, +# which ends the YAML block. See docs/WEB_EXPORT.md. +# +# Inputs (environment): +# IN_FORK_REPO, IN_FORK_TAG, IN_TEMPLATE_VERSION (blank = read from the toolchain file) +Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' +# Actions' pwsh wrapper sets these; set them here too so the script behaves identically when +# run by hand, and so a failing native command (git/gh/dotnet/godot) is not silently ignored. +$PSNativeCommandUseErrorActionPreference = $true +# Read the shared toolchain file, then let non-empty inputs override it. $path = ".github/web-toolchain.env" if (-not (Test-Path $path)) { throw "Missing $path — the web export toolchain versions live there. See docs/WEB_EXPORT.md." } $cfg = @{} @@ -27,11 +38,11 @@ function Resolve-Value($inputValue, $key) { return $cfg[$key] } -$forkRepo = Resolve-Value $env:IN_FORK_REPO 'GODOT_FORK_REPO' -$forkTag = Resolve-Value $env:IN_FORK_TAG 'GODOT_FORK_TAG' +$forkRepo = Resolve-Value $env:IN_FORK_REPO 'GODOT_FORK_REPO' +$forkTag = Resolve-Value $env:IN_FORK_TAG 'GODOT_FORK_TAG' $template = Resolve-Value $env:IN_TEMPLATE_VERSION 'GODOT_TEMPLATE_VERSION' -"fork_repo=$forkRepo" >> $env:GITHUB_OUTPUT -"fork_tag=$forkTag" >> $env:GITHUB_OUTPUT -"template_version=$template" >> $env:GITHUB_OUTPUT +"fork_repo=$forkRepo" >> $env:GITHUB_OUTPUT +"fork_tag=$forkTag" >> $env:GITHUB_OUTPUT +"template_version=$template" >> $env:GITHUB_OUTPUT "asset=Godot_v${forkTag}_mono_web_export_win64.zip" >> $env:GITHUB_OUTPUT diff --git a/.github/actions/export-web/scripts/verify-editor-checksum.ps1 b/.github/actions/export-web/scripts/verify-editor-checksum.ps1 index ae74e32..13b11c1 100644 --- a/.github/actions/export-web/scripts/verify-editor-checksum.ps1 +++ b/.github/actions/export-web/scripts/verify-editor-checksum.ps1 @@ -1,11 +1,24 @@ -# Verify the editor zip against its pinned SHA-256 — a supply-chain guard for the -# third-party binary we run. Runs on both fresh downloads and cache hits, and matches -# the expected filename exactly so a restored cache can't substitute a different zip. +# Verify the downloaded editor against its pinned SHA-256. # -# Env in: ASSET +# Runs on cache hits as well as fresh downloads, and matches the expected filename exactly so a restored cache cannot substitute a different editor. +# +# Extracted from action.yml rather than inlined there: a 40-line script inside a YAML block +# scalar cannot be linted, cannot be run outside CI, and silently breaks on constructs the +# block scalar swallows -- a PowerShell here-string (@"..."@) needs its terminator at column 0, +# which ends the YAML block. See docs/WEB_EXPORT.md. +# +# Inputs (environment): +# ASSET (expected zip filename) +Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' +# Actions' pwsh wrapper sets these; set them here too so the script behaves identically when +# run by hand, and so a failing native command (git/gh/dotnet/godot) is not silently ignored. +$PSNativeCommandUseErrorActionPreference = $true +# Runs on both fresh downloads and cache hits — verifies the exact bytes we execute. +# Match the expected filename explicitly: a restored cache must not be able to +# substitute a differently-named editor zip for the one we pinned. $zip = Get-ChildItem "${env:RUNNER_TEMP}/godot-zip" -Filter *.zip | Where-Object { $_.Name -eq $env:ASSET } | Select-Object -First 1 if (-not $zip) { @@ -13,11 +26,9 @@ if (-not $zip) { Get-ChildItem "${env:RUNNER_TEMP}/godot-zip" -ErrorAction SilentlyContinue | ForEach-Object { Write-Host " $($_.Name)" } throw "Expected editor zip '$env:ASSET' not found (cache or download failed)." } - $line = Get-Content .github/editor-checksums.txt | Where-Object { $_ -notmatch '^\s*#' -and $_ -match [regex]::Escape($zip.Name) } | Select-Object -First 1 if (-not $line) { throw "No pinned checksum for '$($zip.Name)' in .github/editor-checksums.txt — refusing to run an unverified binary. See docs/WEB_EXPORT.md." } - $expected = (($line -split '\s+') | Where-Object { $_ })[0].ToLower() $actual = (Get-FileHash $zip.FullName -Algorithm SHA256).Hash.ToLower() if ($actual -ne $expected) { diff --git a/.github/actions/export-web/scripts/write-build-info.ps1 b/.github/actions/export-web/scripts/write-build-info.ps1 new file mode 100644 index 0000000..f77ee83 --- /dev/null +++ b/.github/actions/export-web/scripts/write-build-info.ps1 @@ -0,0 +1,30 @@ +# Write build-info.json beside index.html. +# +# Lets the served build be identified with a plain curl, without downloading ~96 MB of WASM. +# +# Extracted from action.yml rather than inlined there: a 40-line script inside a YAML block +# scalar cannot be linted, cannot be run outside CI, and silently breaks on constructs the +# block scalar swallows -- a PowerShell here-string (@"..."@) needs its terminator at column 0, +# which ends the YAML block. See docs/WEB_EXPORT.md. +# +# Inputs (environment): +# BUILD_COMMIT, BUILD_BRANCH, BUILD_REPOSITORY, BUILD_RUN_ID, BUILD_RUN_ATTEMPT, +# BUILD_TIMESTAMP, FORK_TAG + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +# Actions' pwsh wrapper sets these; set them here too so the script behaves identically when +# run by hand, and so a failing native command (git/gh/dotnet/godot) is not silently ignored. +$PSNativeCommandUseErrorActionPreference = $true + +$info = [ordered]@{ + commit = $env:BUILD_COMMIT + branch = $env:BUILD_BRANCH + repository = $env:BUILD_REPOSITORY + runId = $env:BUILD_RUN_ID + runAttempt = $env:BUILD_RUN_ATTEMPT + builtUtc = $env:BUILD_TIMESTAMP + godotEditor = $env:FORK_TAG +} +$info | ConvertTo-Json | Set-Content -Path "build/web/build-info.json" -Encoding utf8 +Write-Host "build-info.json:"; Get-Content "build/web/build-info.json" diff --git a/.github/scripts/check-workflow-scripts.py b/.github/scripts/check-workflow-scripts.py new file mode 100644 index 0000000..ed62303 --- /dev/null +++ b/.github/scripts/check-workflow-scripts.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""Verify every workflow/action step that calls a script file can actually run it. + +Moving step bodies out of YAML into .ps1/.sh files trades one failure mode for another: the +script no longer sees `${{ ... }}` interpolation, so every value it needs must be handed over +through `env:`. Miss one and the step does not fail loudly — it reads an empty string and does +something subtly wrong. That happened three times while doing the extraction (BUNDLE_DIR, +GODOT_EXE, IN_TARGET), which is why this is a committed check rather than a one-off. + +Checks, for each step whose `run:` invokes a file under .github/: + 1. the script exists at the path the step names + 2. every environment variable the script reads is provided by the step, the job, the + workflow, or the runner itself + +Run from the repository root: python3 .github/scripts/check-workflow-scripts.py +Exits non-zero if anything is unsatisfied, so it works as a CI gate. +""" + +import glob +import os +import re +import sys + +import yaml + +# Supplied by the runner or by Actions itself, so a step need not declare them. +RUNNER_PROVIDED = { + "GITHUB_OUTPUT", + "GITHUB_STEP_SUMMARY", + "GITHUB_ENV", + "GITHUB_PATH", + "GITHUB_WORKSPACE", + "GITHUB_ACTION_PATH", + "GITHUB_REPOSITORY", + "GITHUB_SHA", + "GITHUB_REF", + "GITHUB_RUN_ID", + "GITHUB_RUN_ATTEMPT", + "GITHUB_EVENT_NAME", + "RUNNER_TEMP", + "RUNNER_OS", + "HOME", + "PATH", +} + + +def steps_with_env(path): + """Yield (step, env visible to it from workflow/job level) for one YAML file.""" + doc = yaml.safe_load(open(path)) + workflow_env = doc.get("env") or {} + + if "runs" in doc: # composite action + for step in doc["runs"].get("steps") or []: + yield step, dict(workflow_env) + return + + for job in (doc.get("jobs") or {}).values(): + inherited = dict(workflow_env) + inherited.update(job.get("env") or {}) + for step in job.get("steps") or []: + yield step, inherited + + +def invoked_script(run, containing_yaml): + """The script path a `run:` body calls, or None if it is an ordinary inline command.""" + m = re.search(r"\$env:GITHUB_ACTION_PATH/(\S+?)\"", run) + if m: # relative to the composite action's own directory + return os.path.join(os.path.dirname(containing_yaml), m.group(1)) + m = re.search(r"\$env:GITHUB_WORKSPACE/(\S+?)\"", run) + if m: + return m.group(1) + m = re.search(r"\bbash (\.github/\S+)", run) + if m: + return m.group(1) + return None + + +def env_vars_read(path): + """Environment variables a script depends on, excluding ones it defines itself.""" + text = open(path).read() + + if path.endswith(".ps1"): + return set(re.findall(r"\$env:([A-Za-z_][A-Za-z0-9_]*)", text)) + + assigned = set(re.findall(r"^\s*([A-Za-z_][A-Za-z0-9_]*)=", text, re.M)) + assigned |= set(re.findall(r"\bfor\s+([A-Za-z_][A-Za-z0-9_]*)\s+in\b", text)) + used = set(re.findall(r"\$\{?([A-Z_][A-Z0-9_]*)\}?", text)) + return used - assigned + + +def main(): + targets = [".github/actions/export-web/action.yml"] + sorted(glob.glob(".github/workflows/*.yml")) + problems = 0 + checked = 0 + + for yml in targets: + for step, inherited in steps_with_env(yml): + run = step.get("run") or "" + script = invoked_script(run, yml) + if not script: + continue + + name = step.get("name", "(unnamed)") + if not os.path.exists(script): + print(f" MISSING {script} (step: {name} in {yml})") + problems += 1 + continue + + provided = set(inherited) | set(step.get("env") or {}) | RUNNER_PROVIDED + needed = env_vars_read(script) + unsatisfied = sorted(needed - provided) + checked += 1 + + if unsatisfied: + print(f" FAIL {script} (step: {name} in {yml})") + print(f" not provided by the step: {', '.join(unsatisfied)}") + problems += 1 + else: + print(f" ok {script} ({len(needed)} env refs satisfied)") + + print(f"\n{checked} script invocation(s) checked, {problems} problem(s)") + return 1 if problems else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/scripts/deploy-vercel.ps1 b/.github/scripts/deploy-vercel.ps1 new file mode 100644 index 0000000..da33985 --- /dev/null +++ b/.github/scripts/deploy-vercel.ps1 @@ -0,0 +1,53 @@ +# Deploy build/web to Vercel, to preview or production. +# +# Shared by the production and preview jobs so the two cannot drift: both get the same target guard, the same DEPLOY_URL marker line and the same step summary. +# +# Lives in a file rather than a YAML block scalar so it can be linted and read; see +# docs/WEB_EXPORT.md. +# +# Inputs (environment): +# EVENT_NAME, GIT_REF, IN_TARGET (blank = preview), BUILD_COMMIT, VERCEL_TOKEN + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +$PSNativeCommandUseErrorActionPreference = $true + +Copy-Item infra/vercel/vercel.json build/web/vercel.json -Force +npm i -g vercel@latest + +# Target is STATED, not inferred from the ref. It used to be "main means --prod", +# which made a dispatch the wrong branch away from silently publishing to +# maze.ryankelly.dev -- an unacceptable footgun now that agents dispatch this +# workflow to get preview URLs (see docs/BUILD_VERIFICATION.md). +$target = if ($env:EVENT_NAME -eq 'push') { 'production' } + elseif ([string]::IsNullOrWhiteSpace($env:IN_TARGET)) { 'preview' } + else { $env:IN_TARGET } + +if ($target -eq 'production' -and $env:GIT_REF -ne 'refs/heads/main') { + throw "deploy_target=production is only allowed on refs/heads/main (got $env:GIT_REF). Use 'preview'." +} + +if ($target -eq 'production') { + $url = (vercel deploy build/web --prod --yes --token=$env:VERCEL_TOKEN) | Select-Object -Last 1 +} else { + $url = (vercel deploy build/web --yes --token=$env:VERCEL_TOKEN) | Select-Object -Last 1 +} + +"url=$url" >> $env:GITHUB_OUTPUT +"target=$target" >> $env:GITHUB_OUTPUT + +# A single machine-readable line so a caller reading the job log (an agent via the +# GitHub API, for instance) does not have to parse vercel's own chatter. +Write-Host "DEPLOY_URL=$url" +Write-Host "DEPLOY_TARGET=$target" + +# Also in the step summary, which is one short API call rather than a whole log. +@( + "### $target deploy", + "", + "| | |", + "|---|---|", + "| URL | <$url> |", + "| Commit | ``$env:BUILD_COMMIT`` |", + "| Build info | <$url/build-info.json> |" +) -join "`n" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8 diff --git a/.github/scripts/publish-mirror-release.sh b/.github/scripts/publish-mirror-release.sh new file mode 100644 index 0000000..2093621 --- /dev/null +++ b/.github/scripts/publish-mirror-release.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Publish (or refresh) the mirrored editor release on this repository. +# +# Idempotent: re-running replaces the asset rather than failing on an existing tag. +# +# Inputs (environment): +# TAG, ASSET, SOURCE_REPO, TARGET_REPO, GH_TOKEN +set -euo pipefail + +notes="Mirror of \`$SOURCE_REPO@$TAG\` for the C#/WASM web export. + +Byte-identical to upstream and verified against the SHA-256 pinned in +\`.github/editor-checksums.txt\` before upload. Exists so the export pipeline does not +depend on a third-party release staying published — see docs/WEB_EXPORT_ROADMAP.md. + +Not a fork and not modified. To use it, set \`GODOT_FORK_REPO\` in +\`.github/web-toolchain.env\` to this repository." + +# Idempotent: re-running replaces the asset rather than failing on an existing tag. +if gh release view "$TAG" --repo "$TARGET_REPO" >/dev/null 2>&1; then + gh release upload "$TAG" "$ASSET" --repo "$TARGET_REPO" --clobber +else + gh release create "$TAG" "$ASSET" --repo "$TARGET_REPO" \ + --title "Mirrored editor $TAG" --notes "$notes" +fi + +echo "### Mirrored \`$ASSET\`" >> "$GITHUB_STEP_SUMMARY" +echo "" >> "$GITHUB_STEP_SUMMARY" +echo "Point \`GODOT_FORK_REPO\` in \`.github/web-toolchain.env\` at \`$TARGET_REPO\` to use it." >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/scripts/report-smoke-result.sh b/.github/scripts/report-smoke-result.sh new file mode 100644 index 0000000..ae93f33 --- /dev/null +++ b/.github/scripts/report-smoke-result.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# Post the preview smoke-test verdict back to the pull request. +# +# Runs with if: always() so a failure is reported rather than only showing in the run. +# +# Inputs (environment): +# SMOKE_OUTCOME, ISSUE_NUMBER, REPOSITORY, GH_TOKEN +set -euo pipefail + +if [ "$SMOKE_OUTCOME" = "success" ]; then + gh pr comment "$ISSUE_NUMBER" --repo "$REPOSITORY" --body "✅ Smoke test passed on the preview (boots, cross-origin isolated, canvas rendered)." +else + gh pr comment "$ISSUE_NUMBER" --repo "$REPOSITORY" --body "❌ Smoke test FAILED on the preview — the build served but did not boot correctly. Check the workflow logs." +fi diff --git a/.github/scripts/resolve-mirror-target.sh b/.github/scripts/resolve-mirror-target.sh new file mode 100644 index 0000000..2b18764 --- /dev/null +++ b/.github/scripts/resolve-mirror-target.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Decide which editor asset to mirror. +# +# Reads the same toolchain file the export action uses, so a mirror cannot drift from the version actually being built with. +# +# Inputs (environment): +# IN_TAG, IN_REPO (blank = read from .github/web-toolchain.env) +set -euo pipefail + +# Same single source of truth the export action uses, so a mirror cannot drift from +# the version actually being built with. +cfg=.github/web-toolchain.env +tag="${IN_TAG:-$(grep -E '^GODOT_FORK_TAG=' $cfg | cut -d= -f2)}" +repo="${IN_REPO:-$(grep -E '^GODOT_FORK_REPO=' $cfg | cut -d= -f2)}" +asset="Godot_v${tag}_mono_web_export_win64.zip" +echo "tag=$tag" >> "$GITHUB_OUTPUT" +echo "repo=$repo" >> "$GITHUB_OUTPUT" +echo "asset=$asset" >> "$GITHUB_OUTPUT" +echo "Mirroring $asset from $repo@$tag" diff --git a/.github/scripts/resolve-pr-head.ps1 b/.github/scripts/resolve-pr-head.ps1 new file mode 100644 index 0000000..1bb4a27 --- /dev/null +++ b/.github/scripts/resolve-pr-head.ps1 @@ -0,0 +1,20 @@ +# Resolve the PR head SHA and branch for a /preview run. +# +# A preview builds the PR head; github.sha on an issue_comment event is the default branch, so it cannot be used. +# +# Lives in a file rather than a YAML block scalar so it can be linted and read; see +# docs/WEB_EXPORT.md. +# +# Inputs (environment): +# ISSUE_NUMBER, REPOSITORY, GH_TOKEN + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +$PSNativeCommandUseErrorActionPreference = $true + +$sha = gh pr view $env:ISSUE_NUMBER --repo $env:REPOSITORY --json headRefOid -q ".headRefOid" +"sha=$sha" >> $env:GITHUB_OUTPUT +# Needed for the build stamp: a preview builds the PR head, so github.sha (the +# default branch, for an issue_comment event) would stamp the wrong commit entirely. +$ref = gh pr view $env:ISSUE_NUMBER --repo $env:REPOSITORY --json headRefName -q ".headRefName" +"ref=$ref" >> $env:GITHUB_OUTPUT diff --git a/.github/scripts/verify-godot-checksum.sh b/.github/scripts/verify-godot-checksum.sh new file mode 100644 index 0000000..d130b04 --- /dev/null +++ b/.github/scripts/verify-godot-checksum.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Verify the upstream Godot editor against its pinned SHA-256. +# +# Same supply-chain guard as the patched Windows editor; the scene-test job runs this binary. +# +# Inputs (environment): +# GODOT_ASSET +set -euo pipefail + +# Same supply-chain guard as the patched web editor: never run an unverified binary. +expected=$(grep -v '^\s*#' .github/editor-checksums.txt | grep "$GODOT_ASSET.zip" | awk '{print $1}') +if [ -z "$expected" ]; then + echo "::error::No pinned checksum for $GODOT_ASSET.zip in .github/editor-checksums.txt" + exit 1 +fi +actual=$(sha256sum "$RUNNER_TEMP/godot/$GODOT_ASSET.zip" | awk '{print $1}') +if [ "$expected" != "$actual" ]; then + echo "::error::Checksum mismatch for $GODOT_ASSET.zip (expected $expected, got $actual)" + exit 1 +fi +echo "Checksum OK: $actual" diff --git a/.github/scripts/verify-mirror-checksum.sh b/.github/scripts/verify-mirror-checksum.sh new file mode 100644 index 0000000..5409776 --- /dev/null +++ b/.github/scripts/verify-mirror-checksum.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +# Verify the downloaded asset against its pinned SHA-256 before it is republished. +# +# Mirroring unverified bytes would launder a compromised upstream into a trusted location, which is worse than having no mirror. +# +# Inputs (environment): +# ASSET +set -euo pipefail + +# Mirroring unverified bytes would launder a compromised upstream into a trusted +# location, which is worse than having no mirror at all. +expected=$(grep -v '^\s*#' .github/editor-checksums.txt | grep "$ASSET" | awk '{print $1}') +if [ -z "$expected" ]; then + echo "::error::No pinned checksum for $ASSET in .github/editor-checksums.txt." + echo "::error::Add it first (see docs/WEB_EXPORT.md) — refusing to mirror unverified bytes." + exit 1 +fi +actual=$(sha256sum "$ASSET" | awk '{print $1}') +if [ "$expected" != "$actual" ]; then + echo "::error::Checksum mismatch for $ASSET (expected $expected, got $actual)." + exit 1 +fi +echo "Checksum OK: $actual" diff --git a/.github/smoke/smoke.mjs b/.github/smoke/smoke.mjs index 292d6f8..d7abf6c 100644 --- a/.github/smoke/smoke.mjs +++ b/.github/smoke/smoke.mjs @@ -41,14 +41,33 @@ try { if (!env.hasCanvas) throw new Error("No element present."); // Boot signal: Godot resizes the canvas to the viewport once the engine starts. - console.log(" waiting for engine to boot (canvas sized)…"); - await page.waitForFunction( - () => { + // + // This must NOT be `width > 0 && height > 0`. An untouched defaults to 300x150, so + // that predicate is already true before the engine does anything — it made this check pass in + // 0.02s on a build that had not booted, which is how it went unnoticed. Assert the canvas is + // no longer the default size, which only the engine can cause. + const DEFAULT_CANVAS = { w: 300, h: 150 }; + console.log(" waiting for engine to boot (canvas resized off the 300x150 default)…"); + try { + await page.waitForFunction( + (def) => { + const c = document.querySelector("canvas"); + return !!c && (c.width !== def.w || c.height !== def.h); + }, + DEFAULT_CANVAS, + { timeout: BOOT_TIMEOUT_MS }, + ); + } catch { + const stuck = await page.evaluate(() => { const c = document.querySelector("canvas"); - return c && c.width > 0 && c.height > 0; - }, - { timeout: BOOT_TIMEOUT_MS }, - ); + return c ? { w: c.width, h: c.height } : null; + }); + throw new Error( + `Engine did not boot: canvas still ${JSON.stringify(stuck)} after ${BOOT_TIMEOUT_MS}ms. ` + + `A canvas at the 300x150 default means Godot never started — check the browser console ` + + `output above for a WASM or .NET runtime failure.`, + ); + } const size = await page.evaluate(() => { const c = document.querySelector("canvas"); return { w: c.width, h: c.height }; @@ -58,6 +77,136 @@ try { if (fatalErrors.length) { throw new Error("Fatal runtime error(s):\n" + fatalErrors.join("\n")); } + + // Confirm the deploy is serving the build this run produced, not a stale or partially + // replaced one. Vercel promotes an alias after upload, so "deploy succeeded" and "the new + // build is what visitors get" are two different claims — this checks the second. + // + // Asserted, not merely reported: unlike the bridge probe below, a wrong build being served + // is a real user-facing defect, and it is exactly what a deploy check exists to catch. + const expectedCommit = process.env.EXPECT_COMMIT || ""; + console.log("→ Checking served build identity (build-info.json)"); + const infoUrl = url.replace(/\/+$/, "") + "/build-info.json"; + const infoResp = await page.request.get(infoUrl); + // Parsed defensively rather than with .json(): a host with an SPA-style catch-all answers an + // unknown path with index.html and HTTP 200, which would throw a bare SyntaxError here and + // fail the deploy for the wrong reason. Observed while testing this check. + let info = null; + if (!infoResp.ok()) { + // Predates this file, or the export step changed — worth flagging but not worth failing a + // deploy over, since nothing user-facing depends on it. + console.log(`⚠️ build-info.json not served (HTTP ${infoResp.status()}) — cannot verify build identity.`); + } else { + const body = await infoResp.text(); + try { + info = JSON.parse(body); + } catch { + console.log( + `⚠️ build-info.json was not JSON (first 80 chars: ${JSON.stringify(body.slice(0, 80))}) — ` + + `cannot verify build identity from the sidecar.`, + ); + } + } + + if (info) { + console.log(" build-info.json:", JSON.stringify(info)); + if (!expectedCommit) { + console.log(" EXPECT_COMMIT not set — reporting the served commit without asserting it."); + } else if (info.commit !== expectedCommit) { + throw new Error( + `Served build is not the one just built.\n` + + ` expected commit: ${expectedCommit}\n` + + ` served commit: ${info.commit || "(empty)"}\n` + + `The deploy may not have promoted, or an older artefact is still being served.`, + ); + } else { + console.log(`✅ Served build matches commit ${expectedCommit}`); + } + } + + // Put the identity in the step summary too. A caller inspecting this run (an agent via the + // GitHub API) can then read one short summary instead of pulling the whole job log. + if (process.env.GITHUB_STEP_SUMMARY) { + const rows = info + ? [ + `| Served commit | \`${info.commit || "(unstamped)"}\` |`, + `| Built (UTC) | ${info.builtUtc || "—"} |`, + `| Branch | ${info.branch || "—"} |`, + `| Editor | ${info.godotEditor || "—"} |`, + ].join("\n") + : "| Served commit | _build-info.json unavailable_ |"; + await import("node:fs").then((fs) => + fs.appendFileSync( + process.env.GITHUB_STEP_SUMMARY, + `### Served build\n\n| | |\n|---|---|\n${rows}\n| Expected | \`${expectedCommit || "(not asserted)"}\` |\n`, + ), + ); + } + + // Report whether the in-app test bridge came up under this (patched-template) build. + // Reported, not asserted: the bridge is an automation aid, and a build without it is still + // a working build — failing the smoke test over it would block deploys for no user-visible + // reason. But it is the one thing unit and scene tests cannot answer (see + // docs/TEST_BRIDGE.md -> "Verification status"), so every deploy answers it for free + // instead of waiting for someone to check by hand. + const bridgeUrl = url + (url.includes("?") ? "&" : "?") + "test=1"; + console.log(`→ Checking test bridge at ${bridgeUrl}`); + const probe = await browser.newPage(); + try { + await probe.goto(bridgeUrl, { waitUntil: "domcontentloaded", timeout: 60_000 }); + await probe.waitForFunction(() => self.crossOriginIsolated === true, { timeout: 60_000 }); + const ready = await probe + .waitForFunction(() => window.__mazeTestApi === "1", { timeout: BOOT_TIMEOUT_MS }) + .then(() => true) + .catch(() => false); + + if (ready) { + const state = await probe.evaluate(() => window.__mazeState ?? null); + console.log("✅ TEST BRIDGE PRESENT — set MAZE_TEST_BRIDGE=1 to enable the browser suites"); + console.log(" window.__mazeState:", String(state).slice(0, 300)); + + // Cross-check the commit compiled INTO the WASM against the one in the sidecar JSON. + // They come from the same inputs, so a disagreement means the two halves of the deploy + // are from different builds — which a check of either one alone would miss. + try { + const inApp = JSON.parse(state || "{}").buildCommit || ""; + if (expectedCommit && inApp && inApp !== expectedCommit) { + throw new Error( + `The running WASM reports commit ${inApp}, but this run built ${expectedCommit}.`, + ); + } + console.log(` in-app buildCommit: ${inApp || "(unstamped)"}`); + } catch (e) { + if (e instanceof SyntaxError) console.log(" (could not parse __mazeState)"); + else throw e; + } + if (process.env.GITHUB_STEP_SUMMARY) { + await import("node:fs").then((fs) => + fs.appendFileSync( + process.env.GITHUB_STEP_SUMMARY, + "### Test bridge: **present** ✅\n\nSet `MAZE_TEST_BRIDGE=1` in `web-export.yml` " + + "to un-skip the Playwright functional and visual suites.\n", + ), + ); + } + } else { + console.log("⚠️ TEST BRIDGE ABSENT — window.__mazeTestApi never became \"1\"."); + console.log(" The deploy is fine; the browser suites stay skipped. See docs/TEST_BRIDGE.md."); + if (process.env.GITHUB_STEP_SUMMARY) { + await import("node:fs").then((fs) => + fs.appendFileSync( + process.env.GITHUB_STEP_SUMMARY, + "### Test bridge: **absent** ⚠️\n\n`window.__mazeTestApi` never became `\"1\"`. " + + "Keep `MAZE_TEST_BRIDGE=0`. Check the Godot console for a `TestBridge: enabled` " + + "line — see docs/TEST_BRIDGE.md.\n", + ), + ); + } + } + } finally { + await probe.close(); + } + console.log("✅ SMOKE PASS"); } finally { await browser.close(); diff --git a/.github/workflows/mirror-editor.yml b/.github/workflows/mirror-editor.yml new file mode 100644 index 0000000..63dbfc8 --- /dev/null +++ b/.github/workflows/mirror-editor.yml @@ -0,0 +1,71 @@ +name: Mirror Patched Editor + +# Mirrors the patched Godot web-export editor to a release on THIS repository, so the web +# pipeline no longer depends on a third-party release staying published. +# +# WHY: the export needs a Windows editor build from ComplexRobot/godot-dotnet-web-export (see +# docs/WEB_EXPORT.md). That fork is actively maintained -- it matched upstream 4.7.1 within two +# days -- but "maintained today" is not "available forever". A deleted or re-published release +# breaks the export outright, and the checksum pin turns a silent substitution into a hard +# failure but cannot conjure the bytes back. +# +# Run this once per pinned editor version, then point GODOT_FORK_REPO in +# .github/web-toolchain.env at this repository. The export action already treats the repo as +# config, so that is a one-line change. +# +# Deliberately manual: it uploads ~165 MB to a release, which is not something to do on a +# schedule or a push. + +on: + workflow_dispatch: + inputs: + tag: + description: "Editor release tag to mirror (blank = value from .github/web-toolchain.env)" + required: false + default: "" + source_repo: + description: "Upstream repo to mirror from (blank = GODOT_FORK_REPO from the toolchain file)" + required: false + default: "" + +permissions: + contents: write # needed to create the mirror release + +jobs: + mirror: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Resolve what to mirror + id: resolve + env: + IN_TAG: ${{ github.event.inputs.tag }} + IN_REPO: ${{ github.event.inputs.source_repo }} + run: bash .github/scripts/resolve-mirror-target.sh + + - name: Download from upstream + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ steps.resolve.outputs.repo }} + TAG: ${{ steps.resolve.outputs.tag }} + ASSET: ${{ steps.resolve.outputs.asset }} + run: | + set -euo pipefail + gh release download "$TAG" --repo "$REPO" --pattern "$ASSET" --dir . + + - name: Verify against the pinned checksum + env: + ASSET: ${{ steps.resolve.outputs.asset }} + run: bash .github/scripts/verify-mirror-checksum.sh + + - name: Publish mirror release + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ steps.resolve.outputs.tag }} + ASSET: ${{ steps.resolve.outputs.asset }} + SOURCE_REPO: ${{ steps.resolve.outputs.repo }} + TARGET_REPO: ${{ github.repository }} + run: bash .github/scripts/publish-mirror-release.sh \ No newline at end of file diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 299d412..9b50cac 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -34,6 +34,12 @@ jobs: - name: Test run: dotnet test tests/ProceduralMaze.Tests.csproj -c Debug --nologo + # The CI step bodies live in .github/scripts and .github/actions/*/scripts rather than in + # YAML block scalars. A script cannot see `${{ ... }}`, so every value it needs must arrive + # via `env:` — and a missing one reads as empty rather than failing. This catches that. + - name: Check workflow scripts are wired up + run: python3 .github/scripts/check-workflow-scripts.py + # In-engine tests for the Godot scene/UI layer, which the NUnit suite cannot reach (it # deliberately builds without the Godot SDK). Runs the official upstream Linux editor # headless -- the patched Windows fork is only needed for the *web export*, not for this. @@ -49,16 +55,16 @@ jobs: GODOT_ASSET: "Godot_v4.7.1-stable_mono_linux_x86_64" steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Set up .NET 9 SDK - uses: actions/setup-dotnet@v4 + uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 with: dotnet-version: "9.0.x" - name: Cache Godot editor id: godotcache - uses: actions/cache@v4 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ runner.temp }}/godot key: godot-linux-${{ env.GODOT_VERSION }} @@ -71,19 +77,7 @@ jobs: "https://github.com/godotengine/godot-builds/releases/download/$GODOT_VERSION/$GODOT_ASSET.zip" - name: Verify Godot checksum - run: | - # Same supply-chain guard as the patched web editor: never run an unverified binary. - expected=$(grep -v '^\s*#' .github/editor-checksums.txt | grep "$GODOT_ASSET.zip" | awk '{print $1}') - if [ -z "$expected" ]; then - echo "::error::No pinned checksum for $GODOT_ASSET.zip in .github/editor-checksums.txt" - exit 1 - fi - actual=$(sha256sum "$RUNNER_TEMP/godot/$GODOT_ASSET.zip" | awk '{print $1}') - if [ "$expected" != "$actual" ]; then - echo "::error::Checksum mismatch for $GODOT_ASSET.zip (expected $expected, got $actual)" - exit 1 - fi - echo "Checksum OK: $actual" + run: bash .github/scripts/verify-godot-checksum.sh - name: Extract Godot run: | @@ -114,10 +108,10 @@ jobs: timeout-minutes: 15 steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Set up Node - uses: actions/setup-node@v4 + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 with: node-version: "20" @@ -133,7 +127,7 @@ jobs: - name: Upload report on failure if: failure() - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: visual-harness-report path: | diff --git a/.github/workflows/web-export.yml b/.github/workflows/web-export.yml index d4b1867..40114fc 100644 --- a/.github/workflows/web-export.yml +++ b/.github/workflows/web-export.yml @@ -3,8 +3,17 @@ name: Web Export & Deploy # Builds the experimental C#/.NET WebAssembly export (Windows runner), deploys it to # the `maze` Vercel project, then smoke-tests that the deployed build actually boots. # -# * push to main / manual dispatch → PRODUCTION deploy (aliases maze.ryankelly.dev) +# * push to main → PRODUCTION deploy (aliases maze.ryankelly.dev) # * comment "/preview" on a PR → on-demand PREVIEW deploy (unique URL, posted back) +# * workflow_dispatch → PREVIEW by default; production requires +# deploy_target=production AND ref main +# +# workflow_dispatch is the path an automated caller (an agent with GitHub API access, with no +# ability to comment as an OWNER) should use: it needs no comment, and unlike issue_comment it +# runs the workflow file AND the checkout from the ref you dispatch, so a branch's own changes +# to this workflow and to .github/smoke/ are actually exercised. An issue_comment run always +# takes the workflow from the default branch, which is how a build stamp added on a branch +# silently arrived empty (see docs/BUILD_VERIFICATION.md). # # The fast test gate lives in test.yml and runs on every PR. The expensive Windows # export here only runs on merge to main or an explicit /preview, to keep runner @@ -27,11 +36,17 @@ on: - ".github/editor-checksums.txt" - ".github/web-toolchain.env" workflow_dispatch: - # Both blank by default: the versions come from .github/web-toolchain.env so that - # dispatch, push-to-main and /preview always agree. Fill one in only to test an - # unpinned editor build ad hoc — note the checksum guard still requires an entry - # in .github/editor-checksums.txt for whatever tag you name. + # Both version inputs are blank by default: the versions come from + # .github/web-toolchain.env so that dispatch, push-to-main and /preview always agree. + # Fill one in only to test an unpinned editor build ad hoc — note the checksum guard + # still requires an entry in .github/editor-checksums.txt for whatever tag you name. inputs: + deploy_target: + description: "preview (default, throwaway URL) or production (main only, aliases maze.ryankelly.dev)" + required: false + default: "preview" + type: choice + options: ["preview", "production"] godot_fork_tag: description: "Override patched-editor release tag (blank = .github/web-toolchain.env)" required: false @@ -57,6 +72,7 @@ jobs: runs-on: windows-latest outputs: url: ${{ steps.deploy.outputs.url }} + build_commit: ${{ steps.export.outputs.build_commit }} env: VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }} VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} @@ -66,6 +82,7 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Export web (WASM) + id: export uses: ./.github/actions/export-web with: # Pass dispatch overrides straight through; blank resolves from @@ -73,25 +90,24 @@ jobs: godot_fork_tag: ${{ github.event.inputs.godot_fork_tag }} template_version: ${{ github.event.inputs.template_version }} github_token: ${{ github.token }} + # Stamps the artefact with the commit it came from, so the About screen and + # build-info.json identify exactly what is being served. + build_commit: ${{ github.sha }} + build_branch: ${{ github.ref_name }} + build_repository: ${{ github.repository }} + build_run_id: ${{ github.run_id }} + build_run_attempt: ${{ github.run_attempt }} - name: Deploy to Vercel id: deploy if: env.VERCEL_TOKEN != '' shell: pwsh - run: | - Copy-Item infra/vercel/vercel.json build/web/vercel.json -Force - npm i -g vercel@latest - # Only a run on main ships to production (aliases maze.ryankelly.dev). - # Any other ref (e.g. a manual dispatch on a feature branch to test the - # pipeline) deploys a throwaway preview instead of touching prod. - if ("${{ github.ref }}" -eq "refs/heads/main") { - $url = (vercel deploy build/web --prod --yes --token=$env:VERCEL_TOKEN) | Select-Object -Last 1 - Write-Host "Production: $url" - } else { - $url = (vercel deploy build/web --yes --token=$env:VERCEL_TOKEN) | Select-Object -Last 1 - Write-Host "Preview (non-main run): $url" - } - "url=$url" >> $env:GITHUB_OUTPUT + env: + EVENT_NAME: ${{ github.event_name }} + GIT_REF: ${{ github.ref }} + IN_TARGET: ${{ github.event.inputs.deploy_target }} + BUILD_COMMIT: ${{ steps.export.outputs.build_commit }} + run: '& "$env:GITHUB_WORKSPACE/.github/scripts/deploy-vercel.ps1"' - name: Skip notice (no secrets) if: env.VERCEL_TOKEN == '' @@ -115,28 +131,35 @@ jobs: - name: Smoke test the deployed build env: SMOKE_URL: ${{ needs.production.outputs.url }} + # Asserts the alias actually serves the artefact this run built, rather than a + # previous one that a failed promotion left in place. Taken from the export itself + # rather than github.sha, which is the wrong commit for issue_comment-triggered runs. + EXPECT_COMMIT: ${{ needs.production.outputs.build_commit }} run: node .github/smoke/smoke.mjs # Visual regression against the DEPLOYED build, after the smoke test proves it boots. # Screenshotting a build that didn't start just yields a blank baseline. # - # MAZE_TEST_BRIDGE gates both browser suites. The in-app bridge - # (scripts/testing/TestBridge.cs) provides URL seeding and the state channel they need. It - # is unit- and scene-tested, but whether it survives the *patched* web export template is - # unproven until a deploy exists to check against -- so both suites skip rather than risk a - # false red. Flip to "1" after confirming window.__mazeTestApi === "1" on a deploy. - # See docs/TEST_BRIDGE.md -> "Enabling in CI". + # MAZE_TEST_BRIDGE is now "1": the in-app bridge (scripts/testing/TestBridge.cs) is CONFIRMED + # working inside the patched web export -- verified on a real deploy, where + # window.__mazeTestApi became "1" and __mazeState reported ready with the build stamp. That was + # the last unknown blocking these suites. See docs/TEST_BRIDGE.md -> "Verification status". + # + # MAZE_VISUAL_BASELINES stays "0" for a different reason: no baseline PNGs are committed, and + # Playwright fails a missing snapshot on CI rather than creating one, so enabling the visual + # project would redden every deploy for a reason unrelated to the build. The functional suite + # needs no baselines and runs. See docs/VISUAL_REGRESSION.md for generating them. visual-production: needs: [production, smoke-production] if: needs.production.outputs.url != '' runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Set up Node - uses: actions/setup-node@v4 + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 with: node-version: "20" @@ -150,19 +173,21 @@ jobs: working-directory: tests/visual env: MAZE_URL: ${{ needs.production.outputs.url }} - MAZE_TEST_BRIDGE: "0" + MAZE_TEST_BRIDGE: "1" run: npx playwright test --project=functional - name: Visual regression working-directory: tests/visual env: MAZE_URL: ${{ needs.production.outputs.url }} - MAZE_TEST_BRIDGE: "0" + MAZE_TEST_BRIDGE: "1" + # Flip to "1" in the same commit that adds tests/visual/maze.spec.ts-snapshots/. + MAZE_VISUAL_BASELINES: "0" run: npx playwright test --project=maze - name: Upload visual diff on failure if: failure() - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: visual-production-report path: | @@ -183,6 +208,7 @@ jobs: pull-requests: write outputs: url: ${{ steps.deploy.outputs.url }} + build_commit: ${{ steps.export.outputs.build_commit }} env: VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }} VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} @@ -196,9 +222,10 @@ jobs: - name: Resolve PR head SHA id: pr shell: pwsh - run: | - $sha = gh pr view ${{ github.event.issue.number }} --repo ${{ github.repository }} --json headRefOid -q ".headRefOid" - "sha=$sha" >> $env:GITHUB_OUTPUT + env: + ISSUE_NUMBER: ${{ github.event.issue.number }} + REPOSITORY: ${{ github.repository }} + run: '& "$env:GITHUB_WORKSPACE/.github/scripts/resolve-pr-head.ps1"' - name: Checkout PR head uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -206,20 +233,30 @@ jobs: ref: ${{ steps.pr.outputs.sha }} - name: Export web (WASM) + id: export uses: ./.github/actions/export-web with: github_token: ${{ github.token }} + # The PR head, not github.sha — see the note in the step above. + build_commit: ${{ steps.pr.outputs.sha }} + build_branch: ${{ steps.pr.outputs.ref }} + build_repository: ${{ github.repository }} + build_run_id: ${{ github.run_id }} + build_run_attempt: ${{ github.run_attempt }} - name: Deploy to Vercel (preview) id: deploy if: env.VERCEL_TOKEN != '' shell: pwsh - run: | - Copy-Item infra/vercel/vercel.json build/web/vercel.json -Force - npm i -g vercel@latest - $url = (vercel deploy build/web --yes --token=$env:VERCEL_TOKEN) | Select-Object -Last 1 - "url=$url" >> $env:GITHUB_OUTPUT - Write-Host "Preview: $url" + env: + # Same script as the production job. IN_TARGET is pinned to preview rather than left + # unset: a /preview must never be able to reach production, and stating it means the + # script's behaviour does not depend on how PowerShell reads an absent env var. + IN_TARGET: "preview" + EVENT_NAME: ${{ github.event_name }} + GIT_REF: ${{ github.ref }} + BUILD_COMMIT: ${{ steps.export.outputs.build_commit }} + run: '& "$env:GITHUB_WORKSPACE/.github/scripts/deploy-vercel.ps1"' - name: Comment preview URL if: env.VERCEL_TOKEN != '' @@ -257,35 +294,38 @@ jobs: id: smoke env: SMOKE_URL: ${{ needs.preview.outputs.url }} + EXPECT_COMMIT: ${{ needs.preview.outputs.build_commit }} run: node .github/smoke/smoke.mjs + - name: Report smoke result on PR if: always() - run: | - if [ "${{ steps.smoke.outcome }}" = "success" ]; then - gh pr comment ${{ github.event.issue.number }} --repo ${{ github.repository }} --body "✅ Smoke test passed on the preview (boots, cross-origin isolated, canvas rendered)." - else - gh pr comment ${{ github.event.issue.number }} --repo ${{ github.repository }} --body "❌ Smoke test FAILED on the preview — the build served but did not boot correctly. Check the workflow logs." - fi - + env: + SMOKE_OUTCOME: ${{ steps.smoke.outcome }} + ISSUE_NUMBER: ${{ github.event.issue.number }} + REPOSITORY: ${{ github.repository }} + run: bash .github/scripts/report-smoke-result.sh # Visual regression against the DEPLOYED build, after the smoke test proves it boots. # Screenshotting a build that didn't start just yields a blank baseline. # - # MAZE_TEST_BRIDGE gates both browser suites. The in-app bridge - # (scripts/testing/TestBridge.cs) provides URL seeding and the state channel they need. It - # is unit- and scene-tested, but whether it survives the *patched* web export template is - # unproven until a deploy exists to check against -- so both suites skip rather than risk a - # false red. Flip to "1" after confirming window.__mazeTestApi === "1" on a deploy. - # See docs/TEST_BRIDGE.md -> "Enabling in CI". + # MAZE_TEST_BRIDGE is now "1": the in-app bridge (scripts/testing/TestBridge.cs) is CONFIRMED + # working inside the patched web export -- verified on a real deploy, where + # window.__mazeTestApi became "1" and __mazeState reported ready with the build stamp. That was + # the last unknown blocking these suites. See docs/TEST_BRIDGE.md -> "Verification status". + # + # MAZE_VISUAL_BASELINES stays "0" for a different reason: no baseline PNGs are committed, and + # Playwright fails a missing snapshot on CI rather than creating one, so enabling the visual + # project would redden every deploy for a reason unrelated to the build. The functional suite + # needs no baselines and runs. See docs/VISUAL_REGRESSION.md for generating them. visual-preview: needs: [preview, smoke-preview] if: needs.preview.outputs.url != '' runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Set up Node - uses: actions/setup-node@v4 + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 with: node-version: "20" @@ -299,19 +339,21 @@ jobs: working-directory: tests/visual env: MAZE_URL: ${{ needs.preview.outputs.url }} - MAZE_TEST_BRIDGE: "0" + MAZE_TEST_BRIDGE: "1" run: npx playwright test --project=functional - name: Visual regression working-directory: tests/visual env: MAZE_URL: ${{ needs.preview.outputs.url }} - MAZE_TEST_BRIDGE: "0" + MAZE_TEST_BRIDGE: "1" + # Flip to "1" in the same commit that adds tests/visual/maze.spec.ts-snapshots/. + MAZE_VISUAL_BASELINES: "0" run: npx playwright test --project=maze - name: Upload visual diff on failure if: failure() - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: visual-preview-report path: | diff --git a/.gitignore b/.gitignore index 0af5f34..89320fe 100644 --- a/.gitignore +++ b/.gitignore @@ -6,8 +6,10 @@ bin/ obj/ -# Web export output -build/ +# Web export output. +# Anchored with a leading slash: an unanchored `build/` matches a directory of that name +# at ANY depth, which silently excluded scripts/build/ (the build-stamp source) from git. +/build/ # Test coverage output tests/coverage/ @@ -47,6 +49,9 @@ blob-report/ playwright/.cache/ .last-run.json +# Web export output +build/ + # Local scratch / planning notes todo.md diff --git a/AGENTS.md b/AGENTS.md index 678ecd8..987c24c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -111,6 +111,7 @@ In Godot 2D rendering: - Session state/behaviour (Godot-free): `scripts/session/` - UI code: `scripts/ui/` - Web test bridge: `scripts/testing/` +- Build identity (About screen): `scripts/build/` ## Adding New Features @@ -126,7 +127,7 @@ Four layers, each with a different cost. **Push tests down** — see | Layer | Command | Needs | |---|---|---| -| Unit + integration (551 tests, ~10s) | `cd tests && dotnet test` | .NET only | +| Unit + integration (584 tests, ~1s) | `cd tests && dotnet test` | .NET only | | Scene / UI (in-engine) | `dotnet build -p:IncludeSceneTests=true` then `godot --headless --path . res://tests/scene/scene_tests.tscn` | Godot binary | | Functional (browser) | `cd tests/visual && npx playwright test --project=functional` | deployed build | | Visual | `cd tests/visual && npx playwright test --project=maze` | deployed build | @@ -192,13 +193,46 @@ desktop build and the whole test suite stay green:** Prefer `CultureInfo.InvariantCulture` explicitly, and keep `scripts/maze/` free of platform-specific BCL calls. If you add anything in the table above, **test it on web -explicitly**: comment `/preview` on the PR and check the smoke test result — a green -desktop CI proves nothing about the browser build. +explicitly** — a green desktop CI proves nothing about the browser build. + +**CI step bodies live in script files, not YAML.** Anything beyond a one-line command belongs in +`.github/scripts/` (workflows) or `.github/actions/export-web/scripts/` (the composite action), +invoked from a one-line `run:`. Two rules follow from that: + +- **Pass values through `env:`, never `${{ }}` inside the script.** A script file cannot see + `${{ ... }}`, and interpolating into a command line is also the injection-prone pattern. + `python3 .github/scripts/check-workflow-scripts.py` (run on every PR) fails if a script reads + an environment variable its step does not provide — the failure mode is otherwise an empty + string and silently wrong behaviour, not an error. +- **A bare `&` cannot start a YAML scalar** — it is the anchor indicator. Quote the invocation: + `run: '& "$env:GITHUB_ACTION_PATH/scripts/x.ps1"'`. + +The reason for all of this: a long script inside a block scalar cannot be linted or run outside +CI, and some constructs simply do not survive it — a PowerShell here-string needs its terminator +at column 0, which ends the YAML block. + +**To deploy and check a branch on the web, dispatch `web-export.yml` on that ref** +(`deploy_target` defaults to `preview`); an agent can do this through the GitHub API with no +comment and no owner privileges. Prefer it over commenting `/preview`, which is an +`issue_comment` trigger and therefore always runs the workflow and smoke script from the +**default branch** — so it cannot exercise a branch's own changes to either. Read the outcome +from the run's step summaries (deploy URL, served commit, bridge verdict). If the deploy host is +unreachable from the agent's sandbox, that is expected — the checks run in CI for exactly that +reason; do not try to route around the network policy. See +[docs/BUILD_VERIFICATION.md](./docs/BUILD_VERIFICATION.md). **Version locking:** the patched editor tag and export templates live in `.github/web-toolchain.env`, and `Godot.NET.Sdk` in the `.csproj` must match them at patch level. CI fails fast on drift. Never hardcode these versions into workflow files. +**Build identity:** every CI build is stamped with the commit it came from, surfaced on the +**About** screen, in `build-info.json` beside `index.html`, and in the test bridge state. The +values come from MSBuild properties CI passes as *environment variables* (the export re-enters +MSBuild through the Godot editor, so a `-p:` argument would not reach it) and are compiled into +the assembly by the `GenerateBuildStamp` target — a data file would not survive the export's +`all_resources` filter. Unstamped local builds say so rather than showing a stale hash. See +[docs/BUILD_VERIFICATION.md](./docs/BUILD_VERIFICATION.md). + ## Running the Game ```bash diff --git a/ProceduralGeneration3DMazes.csproj b/ProceduralGeneration3DMazes.csproj index 33166b1..c33c1c5 100644 --- a/ProceduralGeneration3DMazes.csproj +++ b/ProceduralGeneration3DMazes.csproj @@ -55,4 +55,49 @@ + + + + + $(IntermediateOutputPath)BuildStamp.g.cs + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/BUILD_VERIFICATION.md b/docs/BUILD_VERIFICATION.md new file mode 100644 index 0000000..aeb3d40 --- /dev/null +++ b/docs/BUILD_VERIFICATION.md @@ -0,0 +1,206 @@ +# Build verification + +How to tell **which build is being served** at [maze.ryankelly.dev](https://maze.ryankelly.dev), +and how that identity gets there. + +Deploying is not the same as serving. Vercel uploads an artefact and then promotes an alias to +it; a failed or partial promotion leaves the previous build live while the job still reports +success. Everything here exists to close that gap. + +## Three ways to check, cheapest first + +| | How | Answers | +|---|---|---| +| **`build-info.json`** | `curl -s https://maze.ryankelly.dev/build-info.json` | What the deploy *claims*, without downloading ~96 MB of WASM | +| **About screen** | Menu → **About** | What the running application *believes it is* | +| **Smoke test** | Runs itself on every production deploy | Asserts both agree with the commit CI just built | + +The first two can disagree, and that is the point. `build-info.json` is written next to +`index.html` by the deploy; the About screen reads constants **compiled into the WASM**. If a +deploy were partially replaced, or an old artefact re-promoted under a new sidecar, the two +would diverge — which neither one alone would reveal. + +```console +$ curl -s https://maze.ryankelly.dev/build-info.json +{ + "commit": "12f29bd…", + "branch": "main", + "repository": "rtkelly13/ProceduralGeneration3DMazes", + "runId": "30194540175", + "runAttempt": "1", + "builtUtc": "2026-07-26T09:15:03Z", + "godotEditor": "4.7.1-stable" +} +``` + +Compare `commit` against the repository. `runId` links to the exact job: +`https://github.com//actions/runs/`. + +## Issuing a preview deploy without commenting `/preview` + +`/preview` is an `issue_comment` trigger gated on `author_association == 'OWNER'`, so an +automated caller — an agent with GitHub API access but no ability to comment as the owner — +cannot use it. **Use `workflow_dispatch` instead.** It is not a workaround; for verifying a +branch it is strictly better: + +| | `/preview` comment | `workflow_dispatch` | +|---|---|---| +| Needs an OWNER comment | yes | no | +| Workflow file used | **always the default branch** | **the ref you dispatch** | +| `.github/smoke/` used | default branch | the ref you dispatch | +| Deploy target | preview | `preview` (default), `production` only on `main` | + +That second row is the one that matters. An `issue_comment` run cannot exercise a branch's own +changes to this workflow or to the smoke script — which is exactly how a build stamp added on a +branch arrived empty and a broken boot check went unnoticed. + +```jsonc +// POST /repos/{owner}/{repo}/actions/workflows/web-export.yml/dispatches +{ "ref": "my-branch" } // deploy_target defaults to "preview" +``` + +Then read the result from the run, cheapest call first: + +1. **Step summaries** — the deploy step writes a `### preview deploy` table with the URL, + commit, and a link to `build-info.json`; the smoke step writes a `### Served build` table and + the bridge verdict. One short call, no log parsing. +2. **Job log markers** — `DEPLOY_URL=…` and `DEPLOY_TARGET=…` are printed on their own lines so + a caller does not have to parse vercel's own output. + +**Production is opt-in and `main`-only.** It used to be inferred — `refs/heads/main` meant +`--prod` — which put a dispatch on the wrong branch one step away from silently publishing to +`maze.ryankelly.dev`. The target is now stated explicitly, and `deploy_target=production` on any +other ref fails the job with a message rather than doing something surprising. + +### If the deploy host is unreachable from where the agent runs + +A sandboxed agent may be unable to reach `*.vercel.app` at all — this project's own environment +denies it at the proxy (`403` on `CONNECT`). **Do not try to route around that.** Dispatch the +workflow and read the verdict from the run instead: the smoke job runs inside CI, where the +deploy *is* reachable, and reports the served commit and the bridge state into the step summary. +That is the whole reason those checks are asserted in CI rather than left to a human to eyeball. + +## The About screen + +Menu → **About**, or `?test=1` and `window.__mazeCommand('{"cmd":"goto","scene":"about"}')`. + +It shows the **full** 40-character commit rather than a short prefix — the screen exists so the +value can be compared against a workflow run, and an abbreviation weakens that for no benefit on +a screen with room. **Copy build details** puts the commit, branch, build time, run URL and +engine version on the clipboard in a form that can be pasted straight into an issue. + +A build that CI did not stamp says so explicitly: + +> **Provenance** — local build — not produced by CI, so it cannot be traced to a commit + +That row is deliberate. The failure mode worth designing against is not a missing hash, it is a +**misleading** one: a locally built binary that looks official, or a stale value left over from +whenever a file was last written. `BuildInfo.IsOfficial` requires *both* a full 40-character hex +SHA *and* a CI run id, because only CI can supply the latter. + +## How the stamp gets in + +``` +GitHub Actions + └─ export-web action + ├─ env: BuildCommit / BuildBranch / BuildRepository / BuildRunId / … + │ └─ MSBuild reads env vars as properties + │ └─ GenerateBuildStamp target → obj/BuildStamp.g.cs (constants) + │ └─ compiled into the WASM → CurrentBuild.Info → About screen + │ → test bridge state + └─ writes build/web/build-info.json (sidecar, same inputs) +``` + +Three decisions are load-bearing. + +**The action derives the stamp itself; caller inputs are only overrides.** A `/preview` run +proved why. For `issue_comment` events GitHub loads the **workflow file from the default +branch**, while a composite action is read from the *checked-out* PR head. So a PR that adds +`with: build_commit: …` has its own caller ignored: the action ran, `build-info.json` was +written, and every caller-supplied field arrived **empty**: + +```json +{ "commit": "", "branch": "", "repository": "", "runId": "", + "builtUtc": "2026-07-26T12:12:49Z", "godotEditor": "4.7.1-stable" } +``` + +Only the fields computed *inside* the action survived. The action now reads the commit from the +checkout (`git rev-parse HEAD`) and the repository and run from the `github` context, so the +stamp is correct regardless of which caller invoked it or whether it passed anything. The branch +is left blank when the checkout is detached — a wrong branch is worse than a missing one. + +It also exposes a `build_commit` **output**. Assert against that rather than `github.sha`, which +is the default branch — not the PR head — on an `issue_comment`-triggered run. + +**Compile-time constants, not a data file.** The obvious design — ship a `build-info.json` inside +the app and read it at startup — does not survive this project's web export. +`export_presets.cfg` uses `export_filter="all_resources"` with an empty `include_filter`, so a +plain `.json`/`.txt` file is **not packed into the PCK**. It would work on desktop and silently +report "unknown" in the browser, which is the one place the information is needed. Constants have +no packaging step to get wrong, no file I/O, and nothing for the trimmer to remove. + +**Environment variables, not `-p:` arguments.** The export re-enters MSBuild *through the Godot +editor*, whose command line the workflow does not control. MSBuild reads environment variables as +properties, so that is the only channel reaching both the explicit `dotnet build` step and the +editor's own build. Both steps therefore set the same env block. + +Unset locally by design: a developer build reports itself as a developer build. + +## Verified + +Each of these was executed, not reasoned about: + +| Claim | Evidence | +|---|---| +| Env-var injection reaches the generated constants | `BuildCommit=… dotnet build` → the value appears in `BuildStamp.g.cs` | +| Unset properties produce a valid, compiling file | Local build with no env → empty constants, compiles | +| Repeat builds do not churn | `WriteOnlyWhenDifferent` — file mtime unchanged across two identical builds, so no forced recompile | +| The stamp reaches the running app | Building **stamped** made the scene test's "unstamped ⇒ Provenance row" assertion fail, and only that assertion — end to end through engine, autoload and UI | +| The About screen wires up | Headless Godot 4.7.1 scene test adds it to the tree so `_Ready` runs, then asserts the rows; **9/9 pass**, in both stamped and unstamped builds | +| `BuildInfo` logic | 22 NUnit tests, including that a short hash or a missing run id is *not* treated as official | + +Not verified here: behaviour inside the **patched web export template**, which needs a real +deploy — the same standing gap as the test bridge (see +[TEST_BRIDGE.md](./TEST_BRIDGE.md#verification-status)). + +## The smoke test's boot check was vacuous + +Worth recording, because it invalidated a claim this project had been relying on. The check read: + +```js +// waiting for engine to boot (canvas sized)… +() => { const c = document.querySelector("canvas"); return c && c.width > 0 && c.height > 0; } +``` + +An untouched `` defaults to **300×150**, so `width > 0 && height > 0` is true before the +engine does anything. On a real preview it returned in **0.02 s** and reported +`canvas: {"w":300,"h":150}` followed by `✅ SMOKE PASS` — the default size, meaning Godot had not +resized it. Every "the deploy boots" result from this check was therefore unproven. + +It now waits for the canvas to stop being the default size, which only the engine can cause, and +fails with the stuck dimensions and a pointer to the console output. Verified against a local +server serving both cases: a canvas that never resizes now fails, one that resizes passes, and a +`build-info.json` mismatch fails with both commits named. A sidecar that answers with HTML and +HTTP 200 — what an SPA catch-all does — warns instead of throwing a bare `SyntaxError`, which is +how it behaved when first written. + +The lesson generalises: **a boot check must assert something only a booted app can produce.** +Presence of an element, or a dimension that is non-zero by default, is satisfied by the empty +page you are trying to rule out. + +## For automation + +The test bridge publishes the same identity, so a browser test can assert it: + +```js +const state = JSON.parse(await page.evaluate(() => window.__mazeState)); +expect(state.buildCommit).toBe(process.env.EXPECT_COMMIT); +``` + +Fields: `buildCommit`, `buildBranch`, `buildTime`, `buildRunId`. See +[TEST_BRIDGE.md](./TEST_BRIDGE.md). + +The post-deploy smoke test asserts this automatically when `EXPECT_COMMIT` is set, which +`web-export.yml` supplies as `github.sha`. It fails the deploy on a mismatch — unlike the bridge +*presence* probe, which is only reported, because a wrong build being served is a genuine +user-facing defect rather than a missing convenience. diff --git a/docs/REGRESSION_TESTING.md b/docs/REGRESSION_TESTING.md index c26be63..666844d 100644 --- a/docs/REGRESSION_TESTING.md +++ b/docs/REGRESSION_TESTING.md @@ -158,14 +158,15 @@ should wait. - **`BinaryTreeAlgorithm` is a placeholder** that delegates to `BacktrackerAlgorithm` (see its own comment). Golden files would lock in that duplicate behaviour — worth resolving before, not after, goldens are committed. -- **`PerfectAgent`'s search is worst-case exponential** and should use a shared visited set - instead of scanning the current path (`previousPoints.Any(...)`) — it also copies the whole - path per branch. Measured on the 1200/1600-cell samples, 8 runs of two tests: 1.8s to - >120s (two runs unfinished), while RandomAgent stayed flat at 1.6-1.8s. This is what made - CI wall-time range from 29s to a 40-minute hang on identical code, including a 1002s run on - `main` before any of this work. - - Mitigated for now by narrowing the PerfectAgent sample to <= 200 cells and capping those - tests at 60s (`SampleMazeTests`), plus `timeout-minutes: 15` on the CI job. **That bounds - the symptom; the algorithm is still exponential** and will resurface on any larger maze — - including in the app, where it would hang the UI rather than a test. +- ~~**`PerfectAgent`'s search is worst-case exponential**~~ — **fixed.** It now uses a shared + visited set and an explicit stack instead of scanning the current path + (`previousPoints.Any(...)`) and copying the whole path per branch. + + Before: 8 runs of the two sample-maze tests gave 1.8s, 1.9s, 2.0s, 3.2s, 14.6s, 25.9s and + **two runs unfinished at 120s**. After: 1.8–2.8s, zero timeouts. Full suite dropped from 8s + to 1s. The iterative form also removes a stack-overflow ceiling that scaled with path + length — the app allows 50 cells per axis, i.e. tens of thousands of cells. + + The temporary workaround (narrowing the PerfectAgent sample to 200 cells) has been removed, + restoring the 4 dropped test cases. The 60s per-test cap and `timeout-minutes: 15` on the + CI job stay as tripwires: cheap, and a regression previously cost a 40-minute job. diff --git a/docs/TESTING.md b/docs/TESTING.md index 6c9890f..132cc64 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -16,7 +16,7 @@ layer needs a Windows-built web export and a Vercel deploy. Only test in the bro ## Unit tests — `dotnet test tests/` -551 tests. The project deliberately compiles **without the Godot SDK**, which is what keeps it +584 tests. The project deliberately compiles **without the Godot SDK**, which is what keeps it fast and portable. Any code needing `using Godot;` cannot live here — that is the boundary, and it is why the scene layer exists. @@ -98,6 +98,30 @@ building; none did both, which is how it survived. Fixed, with regression covera That is the argument for this refactor in one incident: the bug was always reachable from the UI, and became visible the moment the flow was testable without the engine. +### Finding bugs by combination sweeping + +Both bugs found so far came from **combining operations no single test combined**. That is now +cheap to search deliberately: `MazeSession` makes a full generate → wrap → graph → serialise → +import → stats cycle a few lines of plain C#, so the option space can be swept in seconds. + +Doing that found a second defect: **generating a 1×1×1 maze hung forever.** +`MazeModelFactory.BuildMaze` picked the end point with +`while (start.Equals(end)) end = RandomPoint(...)`, and a single-cell maze has exactly one +point, so no distinct end point could ever be drawn. A hang, not a crash — no stack trace, no +error, just a frozen app. Reachable by importing a `SIZE 1 1 1` file, which the format permits. +Every neighbouring size (1×2×1, 2×1×1, 1×1×2, 2×2×1) worked, which is why nothing caught it. +Fixed with a cell-count guard plus bounded retries and a deterministic fallback; covered by +[`tests/DegenerateMazeSizeTests.cs`](../tests/DegenerateMazeSizeTests.cs). + +After the fix the sweep runs clean: **418 combinations, 0 failures** — 4 algorithms × 3 maze +types × 7 sizes (including degenerate axes) × wall-removal × door placement, plus every agent +and solver/heuristic pairing. Worth re-running after any change to generation, import or +solving; it is a throwaway exploratory test, not something to commit. + +Technique note: an exploratory sweep must log progress **to a file before each case**, not via +`TestContext.Out`. A hang never flushes the test output, so the console shows nothing and the +culprit is invisible — writing the label to disk first makes the last line name it. + See [REGRESSION_TESTING.md](./REGRESSION_TESTING.md) for the determinism guarantees the suite relies on and the golden-file plan. @@ -113,7 +137,9 @@ nearest thing to coverage was a test that read `menu.tscn` as **text** and asser contained the string `"ComparisonButton"` — proving a node name appears in a file, not that it is a `Button` or that the scene even instantiates. The scene runner checks the real thing. -Current checks: every scene instantiates, `ComparisonButton` is genuinely a `Button`, the +Current checks: every scene instantiates, `ComparisonButton` and `AboutButton` are genuinely +`Button`s, the About screen wires up and reports the running build's identity (see +[BUILD_VERIFICATION.md](./BUILD_VERIFICATION.md)), the `GameState` autoload initialises its `ServiceContainer`, the test bridge is inert off the web platform, seeded generation is deterministic *through the autoload path the app actually uses*, and `SetLevel` clamps to maze bounds. @@ -180,10 +206,14 @@ deterministic seeding, plus committed baseline PNGs. | `test.yml` | `visual-harness` | every PR | | `web-export.yml` | `smoke-*` → `visual-*` (functional + visual) | merge to `main`, or `/preview` | -Both browser suites are **gated on `MAZE_TEST_BRIDGE=1`** and currently skip. The bridge is -unit- and scene-tested, but whether it behaves under the *patched* web export template is -unproven until a deploy exists to check. Skipping beats a false red — see -[TEST_BRIDGE.md → Enabling in CI](./TEST_BRIDGE.md#enabling-in-ci). +The **functional** suite now runs on every deploy: the bridge is confirmed working inside the +patched web export template, verified on a real deploy — see +[TEST_BRIDGE.md → Verification status](./TEST_BRIDGE.md#verification-status). + +The **visual** suite still skips, on `MAZE_VISUAL_BASELINES` rather than on the bridge. Its +blocker is now narrower and concrete: no baseline PNGs are committed, and Playwright fails a +missing snapshot on CI rather than creating one, so enabling it would redden every deploy for a +reason unrelated to the build. See [VISUAL_REGRESSION.md](./VISUAL_REGRESSION.md). The scene-test job downloads the **official upstream** Linux editor, checksum-pinned in [`.github/editor-checksums.txt`](../.github/editor-checksums.txt) exactly like the patched @@ -198,6 +228,7 @@ tests fine. (1473 lines) is largely untested. Next: abstract `FileAccess`/`OS` in `MazeImportExport` so import/export round-trips become testable, then pull orchestration out of `MazeMain` incrementally as it is touched — not as a big-bang rewrite. -- **`PerfectAgent` is worst-case exponential** — see - [REGRESSION_TESTING.md](./REGRESSION_TESTING.md). Bounded in tests, unfixed in the app. +- ~~**`PerfectAgent` is worst-case exponential**~~ — fixed (shared visited set + explicit + stack); 8-run spread went from 1.8s–>120s to 1.8–2.8s. See + [REGRESSION_TESTING.md](./REGRESSION_TESTING.md). - **No golden files yet.** Designed in REGRESSION_TESTING.md, not built. diff --git a/docs/TEST_BRIDGE.md b/docs/TEST_BRIDGE.md index 98e8805..f36b7de 100644 --- a/docs/TEST_BRIDGE.md +++ b/docs/TEST_BRIDGE.md @@ -54,6 +54,10 @@ Normal visitors never receive the API surface. "junctions": 9, "start": { "x": 0, "y": 0, "z": 0 }, "end": { "x": 9, "y": 9, "z": 0 }, + "buildCommit": "12f29bd…", // which build this is — see BUILD_VERIFICATION.md + "buildBranch": "main", + "buildTime": "2026-07-26T09:15:03Z", + "buildRunId": "30194540175", "lastCommand": "{\"cmd\":\"generate\"}", "lastError": "" // non-empty when a command failed } @@ -62,6 +66,10 @@ Normal visitors never receive the API surface. `seed`, `shortestPath`, `totalCells`, `deadEnds`, `junctions`, `start` and `end` appear only once a maze exists (`hasMaze: true`). +The `build*` fields are always present — they do not depend on any app state, and a check that +wants to know *which build it is talking to* needs them before the app has done anything. They +are empty on an unstamped local build. See [BUILD_VERIFICATION.md](./BUILD_VERIFICATION.md). + ### Commands | Command | Fields | Effect | @@ -70,7 +78,7 @@ once a maze exists (`hasMaze: true`). | `setLevel` | `level` | Changes the displayed Z level (clamped to the maze). | | `showPath` | `value` | Toggles solution-path display. | | `nextPath` / `previousPath` | — | Cycles alternative paths. | -| `goto` | `scene`: `maze`\|`menu`\|`comparison`\|`loader` | Changes screen. | +| `goto` | `scene`: `maze`\|`menu`\|`comparison`\|`loader`\|`about` | Changes screen. | `algorithm` accepts `backtracker` (or `recursivebacktracker`), `growingtree`, `binarytree`, `prims` — case-insensitive. @@ -137,23 +145,50 @@ kind of mistake nothing else would notice. | Wire format (parsers, JSON escaping, round-trip) | ✅ 54 NUnit tests, run on every PR | | Compiles against the real GodotSharp 4.7.1 API | ✅ `dotnet build` of the Godot project | | Autoload registered; inert off web | ✅ headless scene test in Godot 4.7.1 | -| Behaviour inside the **patched web export** | ❌ **unproven** — needs a deploy | +| Behaviour inside the **patched web export** | ✅ **confirmed on a real deploy** | + +That last row was the project's longest-standing unknown, and it is now closed. On a preview +deploy of the patched export (`workflow_dispatch`, run `30216793098`): + +``` +✅ TEST BRIDGE PRESENT + window.__mazeState: {"ready":true,"scene":"res://scenes/menu.tscn","hasMaze":false, + "buildCommit":"b3995abd…","buildBranch":"claude/godot-wasm-hosting-eval-3a6h5m", + "buildTime":"2026-07-26T19:25:05Z","buildRunId":"30216793098", + "algorithm":"GrowingTreeAlgorithm","sizeX":20,"sizeY":20,…} +``` + +So `JavaScriptBridge.GetInterface("window")` plus property assignment works normally under the +patched template, `CreateCallback` is installed, and state publishes. `MAZE_TEST_BRIDGE=1` is +now set in CI and the functional suite runs on every deploy. -That last row is why both browser suites are gated (below) rather than switched on. The bridge -depends on `JavaScriptBridge` behaving normally under a *patched* export template, and the one -thing that cannot be checked without a real web build is exactly that. +The visual suite still skips, but on `MAZE_VISUAL_BASELINES` and for an unrelated reason: no +baseline PNGs are committed yet. See [VISUAL_REGRESSION.md](./VISUAL_REGRESSION.md). ## Enabling in CI -Both Playwright projects skip unless `MAZE_TEST_BRIDGE=1`: +**Already enabled.** `MAZE_TEST_BRIDGE: "1"` is set on the functional step of both the +`visual-production` and `visual-preview` jobs, on the strength of the deploy evidence above. -```yaml -env: - MAZE_URL: ${{ needs.production.outputs.url }} - MAZE_TEST_BRIDGE: "1" +The smoke test still reports bridge presence on every deploy, which is how a regression would be +noticed — if a future editor or template bump broke `JavaScriptBridge`, the functional suite would +go red and this line would say why: + +``` +✅ TEST BRIDGE PRESENT — set MAZE_TEST_BRIDGE=1 to enable the browser suites +⚠️ TEST BRIDGE ABSENT — window.__mazeTestApi never became "1". ``` -Before flipping it, confirm on a `/preview` deploy that: +Reported, not asserted: the bridge is an automation aid, and a build without it is still a +working build, so failing a deploy over it would block releases for no user-visible reason. But +it is the one thing unit and scene tests cannot answer, so it is checked automatically instead +of waiting on someone to look. + +If `__mazeTestApi` ever goes absent again, check the Godot console output for the +`TestBridge: enabled` line — its absence means either the URL flag was missing or +`GetInterface("window")` returned null under the patched template. + +To reproduce the check by hand against any deploy: ```js window.__mazeTestApi === "1" // with ?test=1 in the URL @@ -161,10 +196,6 @@ typeof window.__mazeCommand === "function" JSON.parse(window.__mazeState).ready === true ``` -If `__mazeTestApi` is absent, check the Godot console output for the -`TestBridge: enabled` line — its absence means either the URL flag was missing or -`GetInterface("window")` returned null under the patched template. - ## Security notes - **Off by default.** No `test=1`/`seed` parameter, no API surface. diff --git a/docs/VISUAL_REGRESSION.md b/docs/VISUAL_REGRESSION.md index a0899df..d045adc 100644 --- a/docs/VISUAL_REGRESSION.md +++ b/docs/VISUAL_REGRESSION.md @@ -8,11 +8,40 @@ nothing. `toHaveScreenshot()` snapshot comparison — the standard for web visual regression. The repo already uses Playwright for the post-deploy smoke test, so this adds no new tool. -**Status:** harness built and self-verified. URL-parameter seeding is now **implemented** by -the in-app test bridge ([TEST_BRIDGE.md](./TEST_BRIDGE.md)). The maze suite remains **skipped** -until a deploy confirms the bridge works under the patched export template — deliberately -skipped rather than failing, so it can't report a false red. Flip `MAZE_TEST_BRIDGE=1` once -confirmed. +**Status:** harness built and self-verified. URL-parameter seeding is **implemented** by the +in-app test bridge ([TEST_BRIDGE.md](./TEST_BRIDGE.md)), and the bridge is now **confirmed +working in the patched web export** on a real deploy — so `MAZE_TEST_BRIDGE=1` is set in CI and +that blocker is gone. + +**One thing still blocks this suite: no baseline PNGs are committed.** Playwright fails a +missing-snapshot test on CI rather than silently writing one, so switching it on now would +redden every deploy for a reason that has nothing to do with the build. It is therefore gated +separately on `MAZE_VISUAL_BASELINES`, and the procedure below is the remaining work. + +## Generating the baselines (the remaining step) + +The web build cannot be produced on Linux or macOS (see [WEB_EXPORT.md](./WEB_EXPORT.md)), so +baselines have to come from a deployed build rather than a local run: + +1. Deploy the commit you want to baseline — dispatch `web-export.yml` on its ref + (`deploy_target` defaults to `preview`); see + [BUILD_VERIFICATION.md](./BUILD_VERIFICATION.md). +2. Against that URL, run the suite with `--update-snapshots`: + + ```sh + cd tests/visual + MAZE_URL= MAZE_TEST_BRIDGE=1 MAZE_VISUAL_BASELINES=1 \ + npx playwright test --project=maze --update-snapshots + ``` + +3. **Inspect every generated PNG before committing.** A baseline captured from a broken build + silently makes the breakage the expected result, which is worse than having no baseline — + the suite would then go red only when the bug is *fixed*. +4. Commit `tests/visual/maze.spec.ts-snapshots/` and set `MAZE_VISUAL_BASELINES: "1"` in + `web-export.yml` **in the same commit**, so the flag and the files can never disagree. + +Baselines are platform-specific — Playwright suffixes them with the platform, and the committed +ones must come from a Linux run to match the `ubuntu-latest` CI runner. ## How this depends on the seeding work diff --git a/docs/WEB_EXPORT_ROADMAP.md b/docs/WEB_EXPORT_ROADMAP.md index ef66bc2..ab16bbb 100644 --- a/docs/WEB_EXPORT_ROADMAP.md +++ b/docs/WEB_EXPORT_ROADMAP.md @@ -92,12 +92,17 @@ Make the current setup cheap to maintain and cheap to leave. (`4.7.1` / `4.7.1.stable.mono` / `4.7.1-stable`) and requires exact agreement, and fails *before* the 165 MB editor download if the target tag has no pinned checksum. -- [ ] **Mirror the editor binary.** The single highest-value remaining item. Copy the - exact editor zip we depend on to storage we control (a release asset on this - repo, or S3), then point `GODOT_FORK_REPO` at it. Today a deleted upstream - release breaks CI outright. The checksum pin means a mirror is trivially - verifiable — it must hash to the value already in - [`editor-checksums.txt`](../.github/editor-checksums.txt). +- [x] **Mirror the editor binary.** [`mirror-editor.yml`](../.github/workflows/mirror-editor.yml) + downloads the pinned editor, **verifies it against the SHA-256 in + [`editor-checksums.txt`](../.github/editor-checksums.txt) before uploading** — mirroring + unverified bytes would launder a compromised upstream into a trusted location — and + publishes it as a release on this repository. Idempotent, so re-running replaces the + asset. + + **Still needs one manual run** (`workflow_dispatch`, ~165 MB upload), then set + `GODOT_FORK_REPO` in [`web-toolchain.env`](../.github/web-toolchain.env) to this repo. + Deliberately manual rather than scheduled: it is a large upload done once per pinned + version. - [ ] **Guard the feature gaps in code, not prose.** Invariant globalization and the missing crypto APIs fail *only on web* — desktop builds and the test suite stay green. Add an analyzer/test that rejects culture-sensitive formatting and diff --git a/scenes/about.tscn b/scenes/about.tscn new file mode 100644 index 0000000..494a62f --- /dev/null +++ b/scenes/about.tscn @@ -0,0 +1,97 @@ +[gd_scene load_steps=2 format=3 uid="uid://c8ab0ut5c3n1"] + +[ext_resource type="Script" path="res://scripts/ui/AboutUI.cs" id="1"] + +[node name="About" type="Control"] +layout_mode = 3 +anchors_preset = 15 +anchor_right = 1.0 +anchor_bottom = 1.0 +grow_horizontal = 2 +grow_vertical = 2 +script = ExtResource("1") + +[node name="Background" type="ColorRect" parent="."] +layout_mode = 1 +anchors_preset = 15 +anchor_right = 1.0 +anchor_bottom = 1.0 +grow_horizontal = 2 +grow_vertical = 2 +color = Color(0.15, 0.15, 0.2, 1) + +[node name="MarginContainer" type="MarginContainer" parent="."] +layout_mode = 1 +anchors_preset = 15 +anchor_right = 1.0 +anchor_bottom = 1.0 +grow_horizontal = 2 +grow_vertical = 2 +theme_override_constants/margin_left = 40 +theme_override_constants/margin_top = 30 +theme_override_constants/margin_right = 40 +theme_override_constants/margin_bottom = 30 + +[node name="VBoxContainer" type="VBoxContainer" parent="MarginContainer"] +layout_mode = 2 +theme_override_constants/separation = 14 + +[node name="Title" type="Label" parent="MarginContainer/VBoxContainer"] +layout_mode = 2 +theme_override_font_sizes/font_size = 32 +text = "About" +horizontal_alignment = 1 + +[node name="SummaryLabel" type="Label" parent="MarginContainer/VBoxContainer"] +unique_name_in_owner = true +layout_mode = 2 +theme_override_font_sizes/font_size = 16 +text = "build" +horizontal_alignment = 1 + +[node name="HSeparator" type="HSeparator" parent="MarginContainer/VBoxContainer"] +layout_mode = 2 + +[node name="AppDescription" type="Label" parent="MarginContainer/VBoxContainer"] +layout_mode = 2 +autowrap_mode = 3 +text = "3D Maze Generator — procedural maze generation, visualisation and solving, built with Godot 4 and C#. The browser version runs the same C# through an experimental WebAssembly export." + +[node name="BuildHeading" type="Label" parent="MarginContainer/VBoxContainer"] +layout_mode = 2 +theme_override_font_sizes/font_size = 18 +text = "Build" + +[node name="BuildHelp" type="Label" parent="MarginContainer/VBoxContainer"] +layout_mode = 2 +autowrap_mode = 3 +theme_override_font_sizes/font_size = 12 +text = "The commit below identifies exactly which source produced this build. Compare it against the repository to confirm which version is being served." + +[node name="Rows" type="VBoxContainer" parent="MarginContainer/VBoxContainer"] +unique_name_in_owner = true +layout_mode = 2 +size_flags_vertical = 3 +theme_override_constants/separation = 6 + +[node name="ButtonRow" type="HBoxContainer" parent="MarginContainer/VBoxContainer"] +layout_mode = 2 +alignment = 1 +theme_override_constants/separation = 10 + +[node name="BackButton" type="Button" parent="MarginContainer/VBoxContainer/ButtonRow"] +unique_name_in_owner = true +layout_mode = 2 +custom_minimum_size = Vector2(150, 40) +text = "Back" + +[node name="CopyButton" type="Button" parent="MarginContainer/VBoxContainer/ButtonRow"] +unique_name_in_owner = true +layout_mode = 2 +custom_minimum_size = Vector2(190, 40) +text = "Copy build details" + +[node name="CopyFeedback" type="Label" parent="MarginContainer/VBoxContainer/ButtonRow"] +unique_name_in_owner = true +layout_mode = 2 +vertical_alignment = 1 diff --git a/scenes/menu.tscn b/scenes/menu.tscn index f8f4cd0..73bd64c 100644 --- a/scenes/menu.tscn +++ b/scenes/menu.tscn @@ -357,6 +357,12 @@ layout_mode = 2 custom_minimum_size = Vector2(150, 40) text = "Compare Algos" +[node name="AboutButton" type="Button" parent="MarginContainer/VBoxContainer/BottomContainer"] +unique_name_in_owner = true +layout_mode = 2 +custom_minimum_size = Vector2(110, 40) +text = "About" + [node name="ImportButton" type="Button" parent="MarginContainer/VBoxContainer/BottomContainer"] unique_name_in_owner = true layout_mode = 2 diff --git a/scripts/build/BuildInfo.cs b/scripts/build/BuildInfo.cs new file mode 100644 index 0000000..f212ec6 --- /dev/null +++ b/scripts/build/BuildInfo.cs @@ -0,0 +1,226 @@ +using System.Collections.Generic; +using System.Globalization; + +namespace ProceduralMaze.Build +{ + /// + /// Identifies the build that produced this binary, so a deployed artefact can be traced + /// back to the exact commit it was built from. + /// + /// + /// The values come from BuildStamp, generated at compile time from MSBuild + /// properties that CI supplies (see the GenerateBuildStamp target in + /// ProceduralGeneration3DMazes.csproj). + /// + /// WHY COMPILE-TIME CONSTANTS RATHER THAN A DATA FILE + /// + /// The obvious design is a build-info.json read at startup. It does not survive this + /// project's web export: export_presets.cfg uses export_filter="all_resources" + /// with an empty include_filter, so a plain .json/.txt file is not + /// packed into the PCK at all. It would work on desktop and silently report "unknown" in the + /// browser — the one place this information is actually needed. Constants are compiled into + /// the assembly, so there is no packaging step to get wrong, no file I/O, and nothing for the + /// trimmer to remove. + /// + /// This type is deliberately Godot-free so the ordinary NUnit suite covers it; the engine and + /// platform rows are added by the About screen, which is the part that legitimately needs + /// Godot. + /// + public sealed class BuildInfo + { + /// Shown wherever a field was never supplied. + public const string Unknown = "unknown"; + + /// Length of a full git SHA-1, the only form GitHub Actions supplies. + public const int FullCommitLength = 40; + + /// Characters of the commit shown in the short form. + public const int ShortCommitLength = 7; + + public BuildInfo( + string? commit = null, + string? branch = null, + string? repository = null, + string? runId = null, + string? runAttempt = null, + string? timestampUtc = null) + { + Commit = Normalise(commit); + Branch = Normalise(branch); + Repository = Normalise(repository); + RunId = Normalise(runId); + RunAttempt = Normalise(runAttempt); + TimestampUtc = Normalise(timestampUtc); + } + + /// Full commit SHA the build came from; empty for a local build. + public string Commit { get; } + + /// Branch or tag, with any refs/heads/ prefix already stripped by CI. + public string Branch { get; } + + /// owner/repo, used to build links. + public string Repository { get; } + + /// GitHub Actions run id that produced the build. + public string RunId { get; } + + /// Run attempt — a re-run produces the same commit but a different artefact. + public string RunAttempt { get; } + + /// ISO-8601 UTC build time, kept verbatim as a string. + /// + /// Deliberately not parsed into a DateTime. The web build forces + /// InvariantGlobalization, and a timestamp that renders differently in the browser + /// than in the job log is worse than useless for verification — the whole point is that + /// the two can be compared character by character. + /// + public string TimestampUtc { get; } + + /// + /// True when this came from CI: a full-length commit SHA and a run id. A local build has + /// neither, and must not be able to masquerade as a traceable one. + /// + public bool IsOfficial => IsFullCommitSha(Commit) && RunId.Length > 0; + + /// Abbreviated commit for display, or when there is none. + public string ShortCommit => + Commit.Length == 0 ? Unknown + : Commit.Length <= ShortCommitLength ? Commit + : Commit.Substring(0, ShortCommitLength); + + /// One-line identity, e.g. a1b2c3d (main) built 2026-07-26T08:15:03Z. + public string Summary + { + get + { + if (Commit.Length == 0) + { + return "local development build"; + } + + var text = ShortCommit; + if (Branch.Length > 0) + { + text += " (" + Branch + ")"; + } + + if (TimestampUtc.Length > 0) + { + text += " built " + TimestampUtc; + } + + return text; + } + } + + /// Link to the commit, or empty when it cannot be formed. + public string CommitUrl => + Repository.Length > 0 && Commit.Length > 0 + ? string.Format(CultureInfo.InvariantCulture, "https://github.com/{0}/commit/{1}", Repository, Commit) + : string.Empty; + + /// Link to the workflow run that built this, or empty when it cannot be formed. + public string RunUrl => + Repository.Length > 0 && RunId.Length > 0 + ? string.Format(CultureInfo.InvariantCulture, "https://github.com/{0}/actions/runs/{1}", Repository, RunId) + : string.Empty; + + /// + /// Label/value pairs for display, in order. Fields that were never supplied are omitted + /// rather than shown as "unknown" — except the commit, whose absence is itself the point. + /// + public IReadOnlyList> DisplayRows() + { + var rows = new List> + { + new("Commit", Commit.Length > 0 ? Commit : Unknown), + }; + + AddIfPresent(rows, "Branch", Branch); + AddIfPresent(rows, "Built (UTC)", TimestampUtc); + AddIfPresent(rows, "Repository", Repository); + + if (RunId.Length > 0) + { + var run = RunId; + // A re-run of the same commit produces a different artefact, so attempt > 1 is + // worth surfacing; showing "attempt 1" on every build would just be noise. + if (RunAttempt.Length > 0 && RunAttempt != "1") + { + run += " (attempt " + RunAttempt + ")"; + } + + rows.Add(new KeyValuePair("CI run", run)); + } + + if (!IsOfficial) + { + rows.Add(new KeyValuePair( + "Provenance", + "local build — not produced by CI, so it cannot be traced to a commit")); + } + + return rows; + } + + /// + /// Multi-line text identifying this build, for pasting into an issue. Callers with + /// engine-specific detail (the About screen) append their own lines. + /// + public string ToClipboardText() + { + var sb = new System.Text.StringBuilder(); + sb.Append("commit: ").Append(Commit.Length > 0 ? Commit : Unknown).Append('\n'); + AppendLineIfPresent(sb, "branch: ", Branch); + AppendLineIfPresent(sb, "built: ", TimestampUtc); + AppendLineIfPresent(sb, "run: ", RunUrl); + return sb.ToString(); + } + + /// + /// True when is a full 40-character hex SHA-1. Used to reject a + /// truncated or placeholder value being presented as a verifiable identity. + /// + public static bool IsFullCommitSha(string? value) + { + if (value is null || value.Length != FullCommitLength) + { + return false; + } + + foreach (var c in value) + { + var isHex = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); + if (!isHex) + { + return false; + } + } + + return true; + } + + private static void AppendLineIfPresent(System.Text.StringBuilder sb, string prefix, string value) + { + if (value.Length > 0) + { + sb.Append(prefix).Append(value).Append('\n'); + } + } + + private static void AddIfPresent(List> rows, string label, string value) + { + if (value.Length > 0) + { + rows.Add(new KeyValuePair(label, value)); + } + } + + /// + /// MSBuild substitutes an empty string for an unset property, and a stray newline or + /// space would corrupt a hash comparison, so every field is trimmed on the way in. + /// + private static string Normalise(string? value) => value is null ? string.Empty : value.Trim(); + } +} diff --git a/scripts/build/CurrentBuild.cs b/scripts/build/CurrentBuild.cs new file mode 100644 index 0000000..9ac73f9 --- /dev/null +++ b/scripts/build/CurrentBuild.cs @@ -0,0 +1,23 @@ +namespace ProceduralMaze.Build +{ + /// + /// The build stamp of the running binary, resolved once. + /// + /// + /// Separate from so that type stays free of the generated + /// BuildStamp constants and can be compiled — and therefore tested — by the NUnit + /// suite, which does not run the code generator. Anything needing "which build am I?" + /// should come here rather than touching BuildStamp directly. + /// + public static class CurrentBuild + { + /// Identity of this build. Never null; reports a local build when unstamped. + public static BuildInfo Info { get; } = new BuildInfo( + BuildStamp.Commit, + BuildStamp.Branch, + BuildStamp.Repository, + BuildStamp.RunId, + BuildStamp.RunAttempt, + BuildStamp.TimestampUtc); + } +} diff --git a/scripts/maze/agents/PerfectAgent.cs b/scripts/maze/agents/PerfectAgent.cs index 7656fb8..cd58418 100644 --- a/scripts/maze/agents/PerfectAgent.cs +++ b/scripts/maze/agents/PerfectAgent.cs @@ -1,11 +1,43 @@ -using System; using System.Collections.Generic; -using System.Linq; using ProceduralMaze.Maze.Helper; using ProceduralMaze.Maze.Model; namespace ProceduralMaze.Maze.Agents { + /// + /// Walks the maze to the end point, reporting the route it took. + /// + /// + /// Implemented as an **iterative depth-first search with a shared visited set**. Both + /// details are load-bearing; the previous version had neither and was pathologically slow. + /// + /// WHAT WAS WRONG + /// + /// The old search tracked visited cells *per path* — previousPoints.Any(x => …), a + /// linear scan of the current route — rather than once for the whole search. A cell reachable + /// by several routes was therefore re-explored once per route, making the search exponential + /// in the worst case. It also rebuilt the entire path per branch + /// (previousPoints.Concat(…).ToList()), adding an O(path) allocation per step. + /// + /// Measured on the 1200- and 1600-cell sample mazes, 8 runs of two tests: 1.8s, 1.9s, 2.0s, + /// 3.2s, 14.6s, 25.9s, and two runs still unfinished at 120s. The same runs with RandomAgent + /// were flat at 1.6–1.8s. That tail is what made CI wall-time range from 29s to a 40-minute + /// hang on identical code. + /// + /// WHY ITERATIVE + /// + /// Recursion depth tracked path length, so a large maze risked a stack overflow independently + /// of the exponential blowup — the app allows up to 50 cells per axis, i.e. tens of thousands + /// of cells. An explicit stack removes that ceiling. + /// + /// WHAT IS UNCHANGED + /// + /// Still "the first route DFS finds", not a guaranteed shortest path. In a perfect maze + /// (a spanning tree) exactly one simple route exists between any two cells, so that route is + /// the shortest — which is what the existing tests assert. With wall removal the maze gains + /// loops and DFS may return a longer route; that was equally true before. Direction order is + /// still shuffled through the injected generator, so a seed still reproduces the walk. + /// public class PerfectAgent : AgentBase { private readonly IDirectionsFlagParser _directionsFlagParser; @@ -18,55 +50,80 @@ public PerfectAgent(IDirectionsFlagParser directionsFlagParser, _randomValueGenerator = randomValueGenerator; } - public override AgentResults RunAgentBase(IMaze maze) + /// One search frame: the cell's directions and how many have been tried. + private sealed class Frame { - return new AgentResults - { - Movements = GetPathToLastPoint(new List(), maze) - .Where(x => x.Direction != Direction.None).ToList() - }; + public Direction[] Directions = []; + public int Next; } - private List GetPathToLastPoint(List previousPoints, - IMaze maze) + public override AgentResults RunAgentBase(IMaze maze) { - // If we are at the end return a list with the final Point added with No direction + var movements = new List(); + + // Start == end happens on a single-cell maze; there is nothing to walk. if (maze.CurrentPoint.Equals(maze.EndPoint)) { - previousPoints.Add(new DirectionAndPoint { Direction = Direction.None, MazePoint = maze.CurrentPoint }); - return previousPoints; + return new AgentResults { Movements = movements }; } - // If the cell has been visited immediately return the current List of previous points - if (previousPoints.Any(x => x.MazePoint.Equals(maze.CurrentPoint))) - { - return previousPoints; - } - var directions = maze.GetDirectionsFromPoint(); - _randomValueGenerator.Shuffle(directions); - var currentPoint = maze.CurrentPoint; - // Check each direction for path to end - foreach (var direction in directions) + + // Shared across the whole search, not per path. This is the fix: a cell is + // explored at most once, making the walk linear in the number of cells. + var visited = new HashSet { maze.CurrentPoint }; + var stack = new Stack(); + stack.Push(NewFrame(maze)); + + while (stack.Count > 0) { - maze.MoveInDirection(direction); - var newPreviousPoints = previousPoints.Concat( - [ - new DirectionAndPoint + var frame = stack.Peek(); + + if (frame.Next >= frame.Directions.Length) + { + // Every direction from this cell is exhausted: back out of it. + stack.Pop(); + if (stack.Count > 0) { - Direction = direction, - MazePoint = currentPoint + // Undo the move that led here. The root frame has no such move, which is + // why this is guarded — reaching it means the end is unreachable. + var retreat = movements[^1]; + movements.RemoveAt(movements.Count - 1); + maze.MoveInDirection(_directionsFlagParser.OppositeDirection(retreat.Direction)); } - ]).ToList(); - var path = GetPathToLastPoint(newPreviousPoints, maze); - var last = path.Last(); - if (last.MazePoint.Equals(maze.EndPoint)) + + continue; + } + + var direction = frame.Directions[frame.Next++]; + var from = maze.CurrentPoint; + maze.MoveInDirection(direction); + + if (!visited.Add(maze.CurrentPoint)) + { + // Already explored from another route; step back and try the next direction. + maze.MoveInDirection(_directionsFlagParser.OppositeDirection(direction)); + continue; + } + + movements.Add(new DirectionAndPoint { Direction = direction, MazePoint = from }); + + if (maze.CurrentPoint.Equals(maze.EndPoint)) { - return path; + return new AgentResults { Movements = movements }; } - // Move back to start point if no path is found. - maze.MoveInDirection(_directionsFlagParser.OppositeDirection(direction)); + + stack.Push(NewFrame(maze)); } - // If no path in any direction reaches end then return previous points. - return previousPoints; + + // No route exists. Returns an empty walk rather than a partial one, so a caller + // cannot mistake a dead search for a real route. + return new AgentResults { Movements = [] }; + } + + private Frame NewFrame(IMaze maze) + { + var directions = maze.GetDirectionsFromPoint(); + _randomValueGenerator.Shuffle(directions); + return new Frame { Directions = directions }; } } } diff --git a/scripts/maze/factory/MazeModelFactory.cs b/scripts/maze/factory/MazeModelFactory.cs index 81894fd..4f877ca 100644 --- a/scripts/maze/factory/MazeModelFactory.cs +++ b/scripts/maze/factory/MazeModelFactory.cs @@ -22,6 +22,59 @@ public MazeModelFactory(IMovementHelper movementHelper, IDirectionsFlagParser pa _randomPointGenerator = randomPointGenerator; } + /// + /// Maximum random draws before falling back to a deterministic choice. Generous enough + /// that normal mazes always succeed on the first or second try. + /// + private const int MaxEndPointAttempts = 100; + + /// + /// Picks an end point different from where one exists. + /// + /// + /// Replaces an unbounded `while (start.Equals(end)) end = RandomPoint(...)` retry loop + /// that **hung forever on a 1x1x1 maze**: a single-cell maze has exactly one point, so + /// no distinct end point can ever be drawn. Reachable by importing a `.maze` file with + /// `SIZE 1 1 1`, which the format permits. + /// + /// Two guards, because "retry until different" is unsafe in general: + /// * A single-cell maze returns the start point — degenerate but finite, and callers + /// already tolerate start == end (agents check for it before moving). + /// * Retries are bounded, then fall back to a deterministic neighbour. Random draws can + /// be arbitrarily unlucky, and with PickType.RandomEdge the candidate set is a small + /// subset of cells, so an unbounded loop is a latent stall even on larger mazes. + /// + private MazePoint PickDistinctEndPoint(MazeSize size, PickType pickType, MazePoint startPoint) + { + if (size.X * size.Y * size.Z <= 1) + { + return startPoint; + } + + for (var attempt = 0; attempt < MaxEndPointAttempts; attempt++) + { + var candidate = _randomPointGenerator.RandomPoint(size, pickType); + if (!candidate.Equals(startPoint)) + { + return candidate; + } + } + + // Deterministic fallback: step one cell along whichever axis has room. The maze has + // at least two cells, so exactly one of these must differ from the start. + if (size.X > 1) + { + return _pointFactory.MakePoint(startPoint.X == 0 ? 1 : startPoint.X - 1, startPoint.Y, startPoint.Z); + } + + if (size.Y > 1) + { + return _pointFactory.MakePoint(startPoint.X, startPoint.Y == 0 ? 1 : startPoint.Y - 1, startPoint.Z); + } + + return _pointFactory.MakePoint(startPoint.X, startPoint.Y, startPoint.Z == 0 ? 1 : startPoint.Z - 1); + } + public IModelBuilder BuildMaze(MazeGenerationSettings settings) { var pickType = PickType.Random; @@ -30,11 +83,7 @@ public IModelBuilder BuildMaze(MazeGenerationSettings settings) pickType = PickType.RandomEdge; } var startPoint = _randomPointGenerator.RandomPoint(settings.Size, pickType); - var endPoint = _randomPointGenerator.RandomPoint(settings.Size, pickType); - while (startPoint.Equals(endPoint)) - { - endPoint = _randomPointGenerator.RandomPoint(settings.Size, pickType); - } + var endPoint = PickDistinctEndPoint(settings.Size, pickType, startPoint); var options = new ModelInitialisationOptions { Size = settings.Size, diff --git a/scripts/testing/TestBridge.cs b/scripts/testing/TestBridge.cs index 34684c5..b04e8a9 100644 --- a/scripts/testing/TestBridge.cs +++ b/scripts/testing/TestBridge.cs @@ -2,6 +2,7 @@ using System.Globalization; using System.Text; using Godot; +using ProceduralMaze.Build; using ProceduralMaze.Autoload; using ProceduralMaze.Maze; using ProceduralMaze.Maze.Agents; @@ -310,6 +311,17 @@ private string BuildStateJson() TestBridgeProtocol.AppendString(sb, "scene", GetTree()?.CurrentScene?.SceneFilePath ?? ""); sb.Append(','); TestBridgeProtocol.AppendBool(sb, "hasMaze", maze is not null); + sb.Append(','); + // Build identity, so an automated check can confirm WHICH build it is talking to. + // Published unconditionally: unlike the maze fields it does not depend on any state + // existing, and a smoke test needs it before the app has done anything. + TestBridgeProtocol.AppendString(sb, "buildCommit", CurrentBuild.Info.Commit); + sb.Append(','); + TestBridgeProtocol.AppendString(sb, "buildBranch", CurrentBuild.Info.Branch); + sb.Append(','); + TestBridgeProtocol.AppendString(sb, "buildTime", CurrentBuild.Info.TimestampUtc); + sb.Append(','); + TestBridgeProtocol.AppendString(sb, "buildRunId", CurrentBuild.Info.RunId); if (state is not null) { diff --git a/scripts/testing/TestBridgeProtocol.cs b/scripts/testing/TestBridgeProtocol.cs index b7374cd..acfdb05 100644 --- a/scripts/testing/TestBridgeProtocol.cs +++ b/scripts/testing/TestBridgeProtocol.cs @@ -178,6 +178,7 @@ private static int FieldValueStart(string? json, string name) "maze" => "res://scenes/maze.tscn", "menu" => "res://scenes/menu.tscn", "comparison" => "res://scenes/comparison_dashboard.tscn", + "about" => "res://scenes/about.tscn", "loader" => "res://scenes/maze_loader.tscn", _ => null, }; diff --git a/scripts/ui/AboutUI.cs b/scripts/ui/AboutUI.cs new file mode 100644 index 0000000..c4c4f75 --- /dev/null +++ b/scripts/ui/AboutUI.cs @@ -0,0 +1,114 @@ +using System.Collections.Generic; +using Godot; +using ProceduralMaze.Build; + +namespace ProceduralMaze.UI +{ + /// + /// About screen. Its job is to answer one question precisely: which build is this? + /// + /// + /// The commit is shown in full rather than abbreviated. The point of the screen is to compare + /// what is being served against a workflow run or a git rev-parse HEAD, and a + /// seven-character prefix makes that comparison weaker for no gain on a screen with room. + /// + /// A thin adapter, as this codebase requires of Godot types: what the build *is*, and how it + /// renders as text, lives in where the NUnit suite covers it. What is + /// left here is node wiring plus the two rows that genuinely need the engine. + /// + public partial class AboutUI : Control + { + private Label _summaryLabel = null!; + private VBoxContainer _rows = null!; + private Button _backButton = null!; + private Button _copyButton = null!; + private Label _copyFeedback = null!; + + public override void _Ready() + { + _summaryLabel = GetNode