try {
    Banner "Rocket-R ${Version}: local static recompilation builder"
    Write-Host "Repository: $Root"
    Write-Host "Build log:  $LogPath"
    Write-Host "Builder revision: $BuilderRevision"
    Write-Host 'This builder never uploads this repository or your ROM.' -ForegroundColor Green
    if ($Root.Length -gt 120) {
        Write-Host 'WARNING: This repository is in a long path. If a dependency hits Windows path-length limits, move the folder somewhere short such as C:\Rocket-R and rerun.' -ForegroundColor Yellow
    }

    $SelectedPlatforms = Select-BuildPlatforms $Platforms
    $BuildWindows = $SelectedPlatforms -contains 'Windows-x64'
    $BuildLinuxX64 = $SelectedPlatforms -contains 'Linux-x86_64'
    $BuildLinuxArm64 = $SelectedPlatforms -contains 'Linux-aarch64'
    $BuildAndroidArm64 = $SelectedPlatforms -contains 'Android-arm64'
    $NeedLinuxPackages = $BuildLinuxX64 -or $BuildLinuxArm64
    Write-Host ("Selected platforms: " + ($SelectedPlatforms -join ', ')) -ForegroundColor Green
    Write-Host 'FIXED34 gameplay timing retained; stable v5/v6 interpolation + retail Rocket renderer restored.' -ForegroundColor Green

    Banner '1/9 - Windows prerequisites + source integrity'
    Remove-StaleInterpolationExperimentFiles
    $DecompHelperPath = Ensure-RocketDecompHelper
    Write-Host "Stage-5 helper verified/recreated: $DecompHelperPath" -ForegroundColor DarkGreen
    if (-not [Environment]::Is64BitOperatingSystem) { throw 'Rocket-R requires 64-bit Windows.' }

    if (-not (Get-Command git.exe -ErrorAction SilentlyContinue)) {
        Install-Winget 'Git.Git' 'Git for Windows'
    }
    if (-not (Find-Python)) {
        Install-Winget 'Python.Python.3.12' 'Python 3.12'
    }
    Invoke-Python @((Join-Path $Root 'scripts\self_check.py'),'--root',$Root)
    Invoke-Python @((Join-Path $Root 'scripts\verify_recomp_policy_v42.py'),'--root',$Root)
    Invoke-Python @((Join-Path $Root 'scripts\verify_interpolation_v35.py'),'--root',$Root)
    Invoke-Python @((Join-Path $Root 'scripts\verify_global_interpolation_ui_v36.py'),'--root',$Root)
    Invoke-Python @((Join-Path $Root 'scripts\verify_shared_mode0_v43_3.py'),'--root',$Root)
    Invoke-Python @((Join-Path $Root 'scripts\verify_presentation_policy.py'),'--root',$Root)
    Invoke-Python @('-m','unittest','discover','-s',(Join-Path $Root 'tests'),'-p','test_*.py')
    Write-Host 'Interpolation v36 global ownership + UI source: VERIFIED.' -ForegroundColor DarkGreen
    Write-Host 'Interpolation v35 source coverage: VERIFIED (v5/v6 baseline preserved).' -ForegroundColor DarkGreen

    if (-not (Import-VsEnvironment)) {
        Install-Winget 'Microsoft.VisualStudio.2022.BuildTools' 'Visual Studio 2022 Build Tools' '--wait --passive --norestart --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended --add Microsoft.VisualStudio.Component.VC.Llvm.Clang --add Microsoft.VisualStudio.Component.VC.CMake.Project'
        if (-not (Import-VsEnvironment)) {
            Write-Host 'ACTION REQUIRED: Visual Studio Build Tools was installed, but its C++ environment is not active yet.' -ForegroundColor Yellow
            Write-Host 'Restart Windows, then double-click ONE-CLICK-BUILD.cmd again.' -ForegroundColor Yellow
            Stop-Transcript | Out-Null
            exit 20
        }
    }
    $NativeCMake = Get-NativeCMake
    if (-not $NativeCMake) {
        Write-Host 'No suitable native Windows CMake 3.24+ was found. Installing Kitware CMake...' -ForegroundColor Yellow
        Require-Winget
        if (-not (Ask-YesNo 'Native Kitware CMake is required. Install/repair it automatically now?' $true)) {
            throw 'Native Kitware CMake 3.24+ is required.'
        }
        $oldPreference = $ErrorActionPreference
        try {
            $ErrorActionPreference = 'Continue'
            & winget.exe install --id Kitware.CMake --exact --accept-package-agreements --accept-source-agreements --silent
            $cmakeInstallExit = $LASTEXITCODE
        } finally { $ErrorActionPreference = $oldPreference }
        Refresh-Path
        # winget returns a non-zero status when the requested package is already
        # installed and has no upgrade. That is not a build failure if a valid
        # native cmake.exe exists after discovery.
        for ($cmakeProbeAttempt = 1; $cmakeProbeAttempt -le 5 -and -not $NativeCMake; $cmakeProbeAttempt++) {
            $NativeCMake = Get-NativeCMake
            if (-not $NativeCMake) { Start-Sleep -Milliseconds 500 }
        }
        if (-not $NativeCMake) {
            throw "Native Kitware CMake installation/discovery failed (winget exit $cmakeInstallExit)."
        }
    }
    Write-Host "Native Windows CMake: $NativeCMake" -ForegroundColor DarkGreen

    $NativeNinja = Get-NativeNinja
    if (-not $NativeNinja) {
        Install-Winget 'Ninja-build.Ninja' 'native Ninja'
        Refresh-Path
        $NativeNinja = Get-NativeNinja
    }
    if (-not $NativeNinja) { throw 'A native Windows Ninja executable could not be found after prerequisite setup.' }
    Write-Host "Native Ninja: $NativeNinja" -ForegroundColor DarkGreen

    $MsvcCl = Get-Command cl.exe -ErrorAction SilentlyContinue
    if (-not $MsvcCl) { throw 'MSVC cl.exe was not found after importing the Visual Studio 2022 x64 developer environment.' }
    $MsvcCl = $MsvcCl.Source
    Write-Host "MSVC compiler: $MsvcCl" -ForegroundColor DarkGreen

    $ClangCl = Get-ClangCl
    if (-not $ClangCl) {
        throw 'clang-cl.exe was not found. In Visual Studio Installer, add the C++ Clang/LLVM support component, then rerun ONE-CLICK-BUILD.cmd.'
    }
    Write-Host "ClangCL compiler: $ClangCl" -ForegroundColor DarkGreen

    Banner '2/9 - WSL / Ubuntu decompilation toolchain'
    if (-not (Get-Command wsl.exe -ErrorAction SilentlyContinue)) {
        throw 'WSL is not available. Enable Windows Subsystem for Linux from Windows Features (and Virtual Machine Platform if requested), restart, then rerun ONE-CLICK-BUILD.cmd.'
    }

    $script:WslDistro = Select-UbuntuDistro
    if (-not $script:WslDistro) {
        if (Ask-YesNo 'No Ubuntu WSL distribution is configured. Install Ubuntu now?' $true) {
            & wsl.exe --install -d Ubuntu
            if ($LASTEXITCODE -ne 0) {
                throw "Windows could not start the Ubuntu WSL installation (exit $LASTEXITCODE)."
            }
            Write-Host ''
            Write-Host 'ACTION REQUIRED: Ubuntu/WSL installation was started.' -ForegroundColor Yellow
            Write-Host 'If Windows requests a restart, restart. Then launch Ubuntu once, create its Linux username/password, and run ONE-CLICK-BUILD.cmd again.' -ForegroundColor Yellow
            Stop-Transcript | Out-Null
            exit 20
        }
        throw "An Ubuntu WSL distribution is required to build RocketRet's matching NSUE ELF."
    }
    Write-Host "Using WSL distribution: $script:WslDistro"
    & wsl.exe -d $script:WslDistro -- bash -lc 'printf WSL_READY'
    if ($LASTEXITCODE -ne 0) {
        Write-Host "ACTION REQUIRED: $script:WslDistro exists but its first-run Linux account setup is incomplete." -ForegroundColor Yellow
        Write-Host "Launch $script:WslDistro once, create its username/password, close it, then rerun ONE-CLICK-BUILD.cmd." -ForegroundColor Yellow
        Stop-Transcript | Out-Null
        exit 20
    }
    # Prove Windows -> WSL path translation before dependency work or ROM selection.
    # This catches WSL interop/path configuration problems at the earliest safe point.
    $WslRoot = Resolve-WslPath $Root
    Write-Host "WSL repository path: $WslRoot" -ForegroundColor DarkGreen

    Write-Host 'The next command may ask for your Linux sudo password. That is expected.' -ForegroundColor Yellow
    $WslPackages = 'build-essential git python3 python3-venv python3-pip python3-dev libyaml-dev pkg-config make wget curl tar file libc6-i386 gcc-mips-linux-gnu binutils-mips-linux-gnu'
    if ($NeedLinuxPackages) {
        $WslPackages += ' rsync docker.io qemu-user-static binfmt-support'
    }
    # BUILDER v21.2: direct WSL package bootstrap helper
    # Keep multi-line Bash out of PowerShell/native-process command strings.
    # The helper owns the package list, sudo and all apt quoting.
    $WslBootstrapWindows = Join-Path $Root 'scripts\bootstrap_wsl_packages.sh'
    if (-not (Test-Path $WslBootstrapWindows)) {
        throw "Missing WSL package bootstrap helper: $WslBootstrapWindows"
    }
    $WslBootstrapScript = "$WslRoot/scripts/bootstrap_wsl_packages.sh"
    if ($NeedLinuxPackages) {
        & wsl.exe -d $script:WslDistro -- bash $WslBootstrapScript --need-linux-packages
    } else {
        & wsl.exe -d $script:WslDistro -- bash $WslBootstrapScript
    }
    if ($LASTEXITCODE -ne 0) {
        throw "WSL package bootstrap helper failed with exit $LASTEXITCODE in $script:WslDistro."
    }

    Banner '3/9 - Pinned source dependencies'
    $DependencyLog = Join-Path $LogRoot "dependency-bootstrap-$Stamp.log"
    Write-Host "Dependency bootstrap detail log: $DependencyLog" -ForegroundColor DarkGreen
    Write-Host 'FIXED34 keeps pinned dependencies; stable v5/v6 interpolation retained and retail Rocket renderer restored for render recovery.' -ForegroundColor DarkGreen
    $bootstrapArgs = @((Join-Path $Root 'scripts\bootstrap_dependencies.py'),'--root',$Root)
    if ($RepairDependencies) { $bootstrapArgs += '--repair' }
    Invoke-Python $bootstrapArgs $DependencyLog

    Banner '4/9 - Your Rocket US ROM'
    $PrivateDir = Join-Path $BuildRoot 'private'
    New-Item -ItemType Directory -Force -Path $PrivateDir | Out-Null
    $CanonicalRom = Join-Path $PrivateDir 'rocket.us.z64'
    $RomMetadata = Join-Path $PrivateDir 'rocket.us.json'
    $SourceRom = $null
    if ($env:ROCKET_ROM -and (Test-Path $env:ROCKET_ROM)) {
        $SourceRom = (Resolve-Path $env:ROCKET_ROM).Path
    } elseif (Test-Path $CanonicalRom) {
        $SourceRom = $CanonicalRom
        Write-Host 'Reusing the already validated private ROM copy.'
    } else {
        try {
            Add-Type -AssemblyName System.Windows.Forms
            $dialog = New-Object System.Windows.Forms.OpenFileDialog
            $dialog.Title = 'Select your unmodified Rocket: Robot on Wheels (USA) ROM'
            $dialog.Filter = 'Nintendo 64 ROM (*.z64;*.v64;*.n64)|*.z64;*.v64;*.n64|All files (*.*)|*.*'
            if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {
                $SourceRom = $dialog.FileName
            }
        } catch {
            Write-Host 'Graphical file picker was unavailable; falling back to a path prompt.' -ForegroundColor Yellow
        }
        if (-not $SourceRom) { $SourceRom = Read-Host 'Enter the full path to your Rocket USA ROM' }
    }
    if (-not $SourceRom -or -not (Test-Path $SourceRom)) { throw 'No readable ROM was selected.' }
    Invoke-Python @((Join-Path $Root 'scripts\validate_rom.py'),$SourceRom,$CanonicalRom,'--metadata',$RomMetadata)

    Banner '5/9 - Matching Rocket NSUE ELF'
    $DecompLogName = "rocket-decomp-$Stamp.log"
    $DecompLog = Join-Path $LogRoot $DecompLogName
    $WslDecompLog = "$WslRoot/build/logs/$DecompLogName"
    # Recreate once more immediately before use. This makes stage 5 independent
    # of whatever happened to the source helper earlier in the run.
    $DecompHelperPath = Ensure-RocketDecompHelper
    $WslDecompScript = Resolve-WslPath $DecompHelperPath
    Write-Host "Rocket decomp detail log: $DecompLog" -ForegroundColor DarkGreen

    # Stage 5 does not need shell operators, so avoid bash -lc entirely here.
    # Windows PowerShell 5.1 can mangle a composed native command line even when
    # its embedded single-quoted paths are valid Bash. Pass every argument to
    # wsl.exe separately and let WSL exec /bin/bash directly instead.
    Write-Host "WSL helper path: $WslDecompScript" -ForegroundColor DarkGray
    $wslStage5Args = @('-d', $script:WslDistro, '--exec', '/bin/bash', $WslDecompScript, $WslRoot, $WslDecompLog)
    try {
        & wsl.exe @wslStage5Args
        if ($LASTEXITCODE -ne 0) {
            throw "Rocket decomp helper exited with $LASTEXITCODE in $script:WslDistro."
        }
    }
    catch {
        Write-Host ''
        Write-Host 'Rocket decompilation failed inside WSL.' -ForegroundColor Red
        if (Test-Path $DecompLog) {
            Write-Host 'Last 80 lines from the dedicated decomp log:' -ForegroundColor Yellow
            Get-Content $DecompLog -Tail 80 | ForEach-Object { Write-Host $_ }
        } else {
            Write-Host 'The dedicated decomp log was not created; the failure occurred before the Linux helper started.' -ForegroundColor Yellow
        }
        throw "Rocket NSUE ELF build failed. See $DecompLog for the exact Linux command and error."
    }

    $ElfPath = Join-Path $Root 'extern\rocket-decomp\build\us\NSUE.elf'
    if (-not (Test-Path $ElfPath)) { throw 'Rocket decomp finished without producing build/us/NSUE.elf.' }

    Banner '6/9 - N64Recomp and RSPRecomp tools'
    $N64Source = Join-Path $Root 'extern\n64-modern-runtime\N64Recomp'
    $N64Build = Join-Path $BuildRoot 'tools\n64recomp'
    $N64Log = Join-Path $LogRoot "n64recomp-tools-$Stamp.log"

    # N64RecompCLI is the executable target; N64Recomp itself is only the
    # core library target. FIXED12 uses native Windows CMake + Ninja inside the
    # imported VS2022 x64 environment, explicitly binding MSVC cl.exe. This
    # avoids all Visual Studio-generator discovery and MSYS/devkitPro shadowing.
    Remove-Item $N64Build -Recurse -Force -ErrorAction SilentlyContinue
    Write-Host "N64Recomp tool log: $N64Log"
    Write-Host "Using native CMake: $NativeCMake"
    Write-Host 'Configuring N64Recomp with native Ninja + MSVC (x64)...'
    $n64ConfigureExit = Invoke-NativeLogged $NativeCMake @('-S',$N64Source,'-B',$N64Build,'-G','Ninja',"-DCMAKE_MAKE_PROGRAM=$NativeNinja",'-DCMAKE_BUILD_TYPE=Release',"-DCMAKE_C_COMPILER=$MsvcCl","-DCMAKE_CXX_COMPILER=$MsvcCl") $N64Log
    if ($n64ConfigureExit -ne 0) { throw "N64Recomp CMake configuration failed (exit $n64ConfigureExit). See $N64Log" }

    Write-Host 'Building N64RecompCLI + RSPRecomp (Release)...'
    $n64BuildExit = Invoke-NativeLogged $NativeCMake @('--build',$N64Build,'--target','N64RecompCLI','RSPRecomp','RecompModTool','--parallel') $N64Log
    if ($n64BuildExit -ne 0) { throw "N64Recomp/RSPRecomp build failed (exit $n64BuildExit). See $N64Log" }
    $N64Exe = Find-BuiltFile $N64Build 'N64Recomp.exe'
    $RspExe = Find-BuiltFile $N64Build 'RSPRecomp.exe'
    Write-Host "N64Recomp executable: $N64Exe" -ForegroundColor Green
    Write-Host "RSPRecomp executable: $RspExe" -ForegroundColor Green

    # librecomp checks ROMs with XXH3_64. Calculate the exact value from the
    # user's verified canonical ROM instead of hard-coding an unverified hash.
    $HashBuild = Join-Path $BuildRoot 'tools\rom-hash'
    $HashLog = Join-Path $LogRoot "rom-hash-tool-$Stamp.log"
    Remove-Item $HashBuild -Recurse -Force -ErrorAction SilentlyContinue
    $hashConfigureExit = Invoke-NativeLogged $NativeCMake @('-S',(Join-Path $Root 'tools\rom_hash'),'-B',$HashBuild,'-G','Ninja',"-DCMAKE_MAKE_PROGRAM=$NativeNinja",'-DCMAKE_BUILD_TYPE=Release',"-DCMAKE_C_COMPILER=$MsvcCl","-DCMAKE_CXX_COMPILER=$MsvcCl","-DRUNTIME_DIR=$(Join-Path $Root 'extern\n64-modern-runtime')") $HashLog
    if ($hashConfigureExit -ne 0) { throw "ROM hash tool configuration failed (exit $hashConfigureExit). See $HashLog" }
    $hashBuildExit = Invoke-NativeLogged $NativeCMake @('--build',$HashBuild,'--parallel') $HashLog
    if ($hashBuildExit -ne 0) { throw "ROM hash tool build failed (exit $hashBuildExit). See $HashLog" }
    $HashExe = Find-BuiltFile $HashBuild 'RocketRomHash.exe'
    $RomHash = (& $HashExe $CanonicalRom).Trim()
    if ($LASTEXITCODE -ne 0 -or $RomHash -notmatch '^0x[0-9A-F]{16}ULL$') { throw "Unexpected XXH3 ROM hash output: $RomHash" }
    $GeneratedDir = Join-Path $Root 'generated'
    New-Item -ItemType Directory -Force -Path $GeneratedDir | Out-Null
    @"
#pragma once
#include <cstdint>
namespace rocket::generated {
inline constexpr std::uint64_t kRomXxh3 = $RomHash;
}
"@ | Set-Content -Encoding UTF8 (Join-Path $GeneratedDir 'rom_identity.generated.hpp')
    Write-Host "ROM XXH3: $RomHash"

    Banner '7/9 - Static CPU and RSP recompilation'
    $CpuOut = Join-Path $Root 'runtime-recomp\RecompiledFuncs'
    $RspOut = Join-Path $Root 'runtime-recomp\RecompiledRSP'
    Get-ChildItem $CpuOut -Force | Where-Object { $_.Name -ne '.gitkeep' } | Remove-Item -Recurse -Force
    Get-ChildItem $RspOut -Force | Where-Object { $_.Name -ne '.gitkeep' } | Remove-Item -Recurse -Force

    # Keep the cartridge's retail 0x80000400 address for N64ModernRuntime's
    # initial ROM placement, but compile/call game_init as the host entrypoint.
    # The raw retail stub deliberately BREAKs at 0x80000438 if game_init ever
    # returns; under the static runtime it does return after starting the idle
    # thread. This split mirrors DKR-R's proven bootstrap-wrapper architecture.
    $RocketBootstrap = Resolve-RocketBootstrap $ElfPath
    $RocketEntrypoint = $RocketBootstrap.GameInit
    $BootstrapHeader = Join-Path $GeneratedDir 'bootstrap.generated.hpp'
    @"
#pragma once
#include <cstdint>
namespace rocket::generated {
inline constexpr std::uint32_t kRetailLoadAddress = $($RocketBootstrap.Retail)U;
inline constexpr std::uint32_t kCallableEntrypoint = $($RocketBootstrap.GameInit)U;
inline constexpr std::uint32_t kInitialStackPointer = $($RocketBootstrap.InitialStack)U;
inline constexpr std::uint32_t kBootstrapBssStart = $($RocketBootstrap.BssStart)U;
inline constexpr std::uint32_t kBootstrapBssEnd = $($RocketBootstrap.BssEnd)U;
}
"@ | Set-Content -Encoding UTF8 $BootstrapHeader

    $RecompToml = Join-Path $BuildRoot 'generated\rocket.us.toml'
    $RecompLog = Join-Path $LogRoot "static-recomp-$Stamp.log"
    Write-Host "Static recompilation log: $RecompLog" -ForegroundColor DarkGreen
    Write-Host 'Rocket static-recomp policy: game_init callable entry + 24 verified zero-size assembly routines; retail 0x80000400 retained for ROM placement' -ForegroundColor DarkGreen
    Invoke-Python @((Join-Path $Root 'scripts\generate_recomp_config.py'),
        '--policy',(Join-Path $Root 'runtime-recomp\rocket.us.recomp-policy.json'),
        '--elf',$ElfPath,'--rom',$CanonicalRom,'--output-functions',$CpuOut,
        '--entrypoint',$RocketEntrypoint,'--output',$RecompToml,'--functions-per-output-file','50')

    # First ask N64Recomp to parse the ELF and dump its resolved context. This
    # proves the config and selected entrypoint are valid before code generation.
    $GeneratedWork = Join-Path $BuildRoot 'generated'
    Remove-Item (Join-Path $GeneratedWork 'dump.toml') -Force -ErrorAction SilentlyContinue
    Remove-Item (Join-Path $GeneratedWork 'data_dump.toml') -Force -ErrorAction SilentlyContinue
    Push-Location $GeneratedWork
    try {
        Write-Host 'Validating Rocket ELF context with N64Recomp --dump-context...'
        $contextExit = Invoke-NativeLogged $N64Exe @($RecompToml,'--dump-context') $RecompLog
        if ($contextExit -ne 0) {
            throw "N64Recomp ELF/context validation failed (exit $contextExit). See $RecompLog"
        }
        if (Test-Path 'dump.toml') { Move-Item 'dump.toml' 'rocket.functions.dump.toml' -Force }
        if (Test-Path 'data_dump.toml') { Move-Item 'data_dump.toml' 'rocket.data.dump.toml' -Force }
    }
    finally { Pop-Location }

    # ROCKET-R V42 GOLDEN RULE: RecompiledFuncs is disposable N64Recomp output.
    # Clean the output directory before generation; never edit generated C afterwards.
    if (Test-Path $CpuOut) { Remove-Item $CpuOut -Recurse -Force }
    New-Item -ItemType Directory -Force -Path $CpuOut | Out-Null
    Write-Host 'Generating Rocket CPU recompilation...'
    $recompExit = Invoke-NativeLogged $N64Exe @($RecompToml) $RecompLog
    if ($recompExit -ne 0) {
        throw "N64Recomp CPU generation failed (exit $recompExit). See $RecompLog for the exact function/instruction."
    }

    # ROCKET-R V42 GOLDEN RULE: generated CPU C is read-only after N64Recomp.
    # v32/v35/v36/Tinker hooks come only from rocket.us.recomp-policy.json.
    Invoke-Python @((Join-Path $Root 'scripts\verify_recomp_policy_v42.py'),'--root',$Root,'--with-generated')
    Invoke-Python @((Join-Path $Root 'scripts\verify_presentation_policy.py'),'--root',$Root,'--with-generated')
    Write-Host 'RecompiledFuncs policy verification: PASS (read-only; no post-generation patching).' -ForegroundColor DarkGreen
    Write-Host 'Graphics v32 single live RenderEntry queue: ENABLED via N64Recomp policy (32768 entries).' -ForegroundColor DarkGreen

    Push-Location (Join-Path $Root 'runtime-recomp\rsp')
    try {
        Write-Host 'Generating Rocket n_aspMain RSP recompilation...'
        $rspExit = Invoke-NativeLogged $RspExe @((Join-Path $Root 'runtime-recomp\rsp\n_aspMain.us.toml')) $RecompLog
        if ($rspExit -ne 0) {
            throw "RSPRecomp failed for Rocket n_aspMain (exit $rspExit). See $RecompLog for the exact indirect target/instruction."
        }
    } finally { Pop-Location }
    if (-not (Test-Path (Join-Path $CpuOut 'recomp_overlays.inl'))) { throw 'N64Recomp did not emit recomp_overlays.inl.' }
    if (-not (Get-ChildItem $RspOut -Filter '*.cpp' -File -ErrorAction SilentlyContinue)) { throw 'RSPRecomp did not emit a C++ microcode file.' }

    $ModTool = Find-BuiltFile $N64Build 'RecompModTool.exe'
    Invoke-Python @((Join-Path $Root 'scripts\build_mod.py'),
        (Join-Path $Root 'modding\examples\modern-camera'), '--wsl', '--wsl-distro', $script:WslDistro,
        '--tool', $ModTool, '--symbols', (Join-Path $GeneratedWork 'rocket.functions.dump.toml'),
        '--output', (Join-Path $BuildRoot 'mods'))

    Banner '8/9 - Selected native platform builds'
    $Dist = Join-Path $Root 'dist'
    New-Item -ItemType Directory -Force -Path $Dist | Out-Null
    $BuiltArtifacts = New-Object System.Collections.Generic.List[string]
    $RocketExe = $null
    $RocketDir = $null

    Write-Host 'Rocket runtime policy: retail 30 Hz simulation + stable v5/v6 RT64 semantic interpolation + original Rocket RenderEntry/sort/draw path + safe-area crop + widescreen CPU frustum.' -ForegroundColor DarkGreen
    Write-Host 'Attachment/skybox interpolation v6: ENABLED (shared-parent + dynamic GFX identities).' -ForegroundColor Green
    Write-Host 'Interpolation v35: ENABLED (exact Submodel wheels/parts + range-stable V33 sky identity; fail-closed fallback retained).' -ForegroundColor Green
    Write-Host 'N64 colour dithering v7: LAUNCHER TOGGLE (retail Bayer / disabled).' -ForegroundColor Green
    Write-Host 'Interpolation + presentation fix v3.1: ENABLED (centroid-stable small geometry + double-buffered RT64 presentation targets).' -ForegroundColor Green

    if ($BuildWindows) {
        Write-Host ''
        Write-Host '[Windows x64]' -ForegroundColor Cyan
        $WindowsBuild = Join-Path $BuildRoot 'windows'
        $RuntimeLog = Join-Path $LogRoot "rocket-runtime-windows-$Stamp.log"
        Remove-Item $WindowsBuild -Recurse -Force -ErrorAction SilentlyContinue
        Write-Host "Rocket runtime build log: $RuntimeLog"
        $runtimeConfigureExit = Invoke-NativeLogged $NativeCMake @('-S',$Root,'-B',$WindowsBuild,'-G','Ninja',"-DCMAKE_MAKE_PROGRAM=$NativeNinja",'-DCMAKE_BUILD_TYPE=Release',"-DCMAKE_C_COMPILER=$ClangCl","-DCMAKE_CXX_COMPILER=$ClangCl") $RuntimeLog
        if ($runtimeConfigureExit -ne 0) { throw "Rocket-R Windows CMake configuration failed (exit $runtimeConfigureExit). See $RuntimeLog" }
        $runtimeBuildExit = Invoke-NativeLogged $NativeCMake @('--build',$WindowsBuild,'--target','RocketR','RocketPresentationTests','RocketRuntimeLogTests','RocketControlsTests','RocketControlsUiTests','RocketModsTests','RocketCameraModTests','RocketGraphicsCameraTests','--parallel') $RuntimeLog
        if ($runtimeBuildExit -ne 0) { throw "Rocket-R Windows build failed (exit $runtimeBuildExit). See $RuntimeLog" }
        $NativeCTest = Join-Path (Split-Path -Parent $NativeCMake) 'ctest.exe'
        $runtimeTestExit = Invoke-NativeLogged $NativeCTest @('--test-dir',$WindowsBuild,'--output-on-failure') $RuntimeLog
        if ($runtimeTestExit -ne 0) { throw "Rocket-R regression tests failed. See $RuntimeLog" }
        $RocketExe = Find-BuiltFile $WindowsBuild 'Rocket-R.exe'
        $RocketDir = Split-Path $RocketExe -Parent
        Write-Host "Built: $RocketExe" -ForegroundColor Green
    }

    if ($BuildLinuxX64) {
        Write-Host ''
        Write-Host '[Linux x86_64 AppImage]' -ForegroundColor Cyan
        $LinuxX64Log = Join-Path $LogRoot "rocket-runtime-linux-x86_64-$Stamp.log"
        $wslLinuxArgs = @('-d',$script:WslDistro,'--exec','/bin/bash',"$WslRoot/Build-Linux.sh",'--arch','x86_64','--output-dir',"$WslRoot/dist")
        $linuxExit = Invoke-NativeLogged 'wsl.exe' $wslLinuxArgs $LinuxX64Log
        if ($linuxExit -ne 0) { throw "Rocket-R Linux x86_64/AppImage build failed (exit $linuxExit). See $LinuxX64Log" }
        $LinuxX64Artifact = Join-Path $Dist "Rocket-R-$Version-Linux-x86_64.AppImage"
        if (-not (Test-Path $LinuxX64Artifact)) { throw "Linux x86_64 build completed but $LinuxX64Artifact was not produced." }
        $BuiltArtifacts.Add($LinuxX64Artifact)
        $LinuxX64Portable = Join-Path $Dist "Rocket-R-$Version-Linux-x86_64-Portable.tar.gz"
        if (Test-Path $LinuxX64Portable) { $BuiltArtifacts.Add($LinuxX64Portable) }
        $LinuxX64SteamDeck = Join-Path $Dist "Rocket-R-$Version-Linux-x86_64-SteamDeck.tar.gz"
        if (Test-Path $LinuxX64SteamDeck) { $BuiltArtifacts.Add($LinuxX64SteamDeck) }
    }

    if ($BuildLinuxArm64) {
        Write-Host ''
        Write-Host '[Linux ARM64 / aarch64 AppImage]' -ForegroundColor Cyan
        $LinuxArmLog = Join-Path $LogRoot "rocket-runtime-linux-aarch64-$Stamp.log"
        $wslArmArgs = @('-d',$script:WslDistro,'--exec','/bin/bash',"$WslRoot/Build-Linux.sh",'--arch','aarch64','--output-dir',"$WslRoot/dist")
        $linuxArmExit = Invoke-NativeLogged 'wsl.exe' $wslArmArgs $LinuxArmLog
        if ($linuxArmExit -ne 0) { throw "Rocket-R Linux ARM64/AppImage build failed (exit $linuxArmExit). See $LinuxArmLog" }
        $LinuxArmArtifact = Join-Path $Dist "Rocket-R-$Version-Linux-aarch64.AppImage"
        if (-not (Test-Path $LinuxArmArtifact)) { throw "Linux ARM64 build completed but $LinuxArmArtifact was not produced." }
        $BuiltArtifacts.Add($LinuxArmArtifact)
        $LinuxArmPortable = Join-Path $Dist "Rocket-R-$Version-Linux-aarch64-Portable.tar.gz"
        if (Test-Path $LinuxArmPortable) { $BuiltArtifacts.Add($LinuxArmPortable) }
    }

    if ($BuildAndroidArm64) {
        Write-Host ''
        Write-Host '[Android ARM64 / arm64-v8a APK]' -ForegroundColor Cyan
        $AndroidLog = Join-Path $LogRoot "rocket-runtime-android-arm64-$Stamp.log"
        $PowerShellExe = (Get-Command powershell.exe -ErrorAction Stop).Source
        $androidExit = Invoke-NativeLogged $PowerShellExe @('-NoProfile','-ExecutionPolicy','Bypass','-File',(Join-Path $Root 'scripts\Build-Android.ps1'),'-ProjectRoot',$Root,'-OutputDirectory',$Dist) $AndroidLog
        if ($androidExit -ne 0) { throw "Rocket-R Android ARM64/APK build failed (exit $androidExit). See $AndroidLog" }
        $AndroidArtifact = Join-Path $Dist "Rocket-R-$Version-Android-arm64-v8a.apk"
        if (-not (Test-Path $AndroidArtifact)) { throw "Android ARM64 build completed but $AndroidArtifact was not produced." }
        $BuiltArtifacts.Add($AndroidArtifact)
    }

    Banner '9/9 - ROM-free release outputs'
    if ($BuildWindows) {
        if (-not $NoPackage) {
            $PackageName = "Rocket-R-$Version-Windows-x64"
            $Stage = Join-Path $BuildRoot "package\$PackageName"
            Remove-Item $Stage -Recurse -Force -ErrorAction SilentlyContinue
            New-Item -ItemType Directory -Force -Path $Stage | Out-Null
            Copy-Item (Join-Path $RocketDir '*') $Stage -Recurse -Force
            Invoke-Python @((Join-Path $Root 'scripts\stage_release_docs.py'),'--root',$Root,'--output',$Stage)
            Invoke-Python @((Join-Path $Root 'scripts\scan_release.py'),$Stage)
            $ZipPath = Join-Path $Dist "$PackageName.zip"
            Remove-Item $ZipPath -Force -ErrorAction SilentlyContinue
            Compress-Archive -Path (Join-Path $Stage '*') -DestinationPath $ZipPath -CompressionLevel Optimal
            $BuiltArtifacts.Add($ZipPath)
            Write-Host "Package: $ZipPath" -ForegroundColor Green
        } else {
            $BuiltArtifacts.Add($RocketExe)
            Write-Host "NoPackage selected; Windows executable retained at: $RocketExe" -ForegroundColor Yellow
        }
    }

    Write-Host 'ROM-free release scan/package policy is applied per selected platform. Linux AppImages and the Android APK are the native distributable formats, so those selections are always packaged.' -ForegroundColor DarkGreen
    Write-Host ''
    Write-Host 'Selected build outputs:' -ForegroundColor Cyan
    foreach ($artifact in $BuiltArtifacts) { Write-Host "  $artifact" -ForegroundColor Green }
    Write-Host ''
    Write-Host 'BUILD COMPLETE.' -ForegroundColor Green
    Write-Host 'The runtime uses your private ROM only; packaged builds are scanned to reject ROMs.'
    if ($BuildWindows -and -not $NoLaunch -and (Ask-YesNo 'Launch the freshly built Windows runtime with your verified ROM now?' $false)) {
        & $RocketExe --rom $CanonicalRom
    }
    Stop-Transcript | Out-Null
    exit 0
}
catch {
    Write-Host ''
    Write-Host 'BUILD STOPPED SAFELY' -ForegroundColor Red
    Write-Host $_.Exception.Message -ForegroundColor Red
    Write-Host 'Nothing was uploaded and your original ROM was not modified.' -ForegroundColor Yellow
    Write-Host "Full log: $LogPath" -ForegroundColor Yellow
    try { Stop-Transcript | Out-Null } catch {}
    exit 1
}
