Files
rust-discovery/deploy/windows/Install-NativeBuildTools.ps1
2026-11-14 03:53:48 +01:00

282 lines
22 KiB
PowerShell

#requires -Version 5.1
<#!
Explicit development-tool bootstrap; no RMM jobs, daemon changes, OS update
command, trust import, persistent execution-policy/PATH modification or reboot.
The already authorized development bootstrap uses process RemoteSigned only;
Machine/User/GPO scopes are never changed and GPOs retain precedence.
Prepare downloads pinned public inputs only. InstallVs/InstallRust each start
one fixed demand-only task; Read never retries. Worker result is durable before
the task exits. A lost reply, timeout, 3010 or failure never restarts installation.
!#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)][ValidateSet('Prepare','InstallVs','InstallRust','Read','WorkerVs','WorkerRust')][string]$Phase,
[string]$RootDirectory=(Join-Path $env:USERPROFILE 'RmmNativeTools'),
[string]$CaseDirectory,
[Guid]$CaseId=([Guid]::NewGuid()),
[string]$ScriptFile=$PSCommandPath
)
Set-StrictMode -Version Latest
$ErrorActionPreference='Stop'
$VsVersion='18.11.12405.450'
$VsDirectory='C:\RmmBuildTools'
$Toolchain='1.99.1-x86_64-pc-windows-msvc'
$RustupSha256='38027d51d69a5d05493627a0634dbea52d6cd793c8f072d2373d3f4163eec7db'
$downloads=@(
@{name='vs_BuildTools.exe';sha256='386b5d9a3d6576eab3772c1ecaa7c107ded38146a9c483f41679c194ae1e63b4';max=16MB;
url='https://download.visualstudio.microsoft.com/download/pr/2d4073f5-2775-4a70-8c1d-b50ae62795a7/386b5d9a3d6576eab3772c1ecaa7c107ded38146a9c483f41679c194ae1e63b4/vs_BuildTools.exe'},
@{name='rustup-init.exe';sha256=$RustupSha256;max=32MB;
url='https://static.rust-lang.org/rustup/archive/1.29.3/x86_64-pc-windows-msvc/rustup-init.exe'},
@{name='rustup-init.exe.sha256';sha256=$null;max=4096;
url='https://static.rust-lang.org/rustup/archive/1.29.3/x86_64-pc-windows-msvc/rustup-init.exe.sha256'},
@{name='rust-toolchain.toml.sha256';sha256=$null;max=4096;
url='https://static.rust-lang.org/dist/channel-rust-1.99.1.toml.sha256'}
)
$case=$null
function Require([bool]$Value,[string]$Code) {if (-not $Value) {throw $Code}}
function Hash([string]$Path) {return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant()}
function Hash-Text([string]$Value) {
$sha=[Security.Cryptography.SHA256]::Create()
try {return ([BitConverter]::ToString($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($Value)))).Replace('-','').ToLowerInvariant()}
finally {$sha.Dispose()}
}
function No-Reparse([string]$Path) {
$item=Get-Item -LiteralPath $Path -Force
while ($null -ne $item) {
Require (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -eq 0) 'SETUP_REPARSE_PATH'
if ($item -is [IO.FileInfo]) {$item=$item.Directory} else {$item=$item.Parent}
}
}
function Protected-Directory([string]$Path) {
No-Reparse $Path;$acl=Get-Acl -LiteralPath $Path
$trusted=@([Security.Principal.WindowsIdentity]::GetCurrent().User.Value,'S-1-5-18','S-1-5-32-544')
Require ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -in $trusted) 'SETUP_DIRECTORY_OWNER'
$write=[Security.AccessControl.FileSystemRights]::Write -bor [Security.AccessControl.FileSystemRights]::Delete -bor
[Security.AccessControl.FileSystemRights]::ChangePermissions -bor [Security.AccessControl.FileSystemRights]::TakeOwnership -bor
[Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles
foreach ($ace in $acl.Access) {
if ($ace.AccessControlType -eq 'Allow' -and ($ace.FileSystemRights -band $write) -ne 0) {
Require ($ace.IdentityReference.Translate([Security.Principal.SecurityIdentifier]).Value -in $trusted) 'UNTRUSTED_SETUP_DIRECTORY_WRITER'
}
}
}
function New-Private([string]$Path) {
Require (-not (Test-Path -LiteralPath $Path)) 'SETUP_CASE_ALREADY_EXISTS'
[void][IO.Directory]::CreateDirectory($Path)
$acl=New-Object Security.AccessControl.DirectorySecurity;$acl.SetAccessRuleProtection($true,$false)
$acl.SetOwner((New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544')))
foreach ($sid in @('S-1-5-18','S-1-5-32-544')) {
$acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule(
(New-Object Security.Principal.SecurityIdentifier($sid)),[Security.AccessControl.FileSystemRights]::FullControl,
([Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [Security.AccessControl.InheritanceFlags]::ObjectInherit),
[Security.AccessControl.PropagationFlags]::None,[Security.AccessControl.AccessControlType]::Allow)))
}
Set-Acl -LiteralPath $Path -AclObject $acl;Protected-Directory $Path
}
function Write-New([string]$Path,$Value) {
$raw=(New-Object Text.UTF8Encoding($false)).GetBytes(($Value | ConvertTo-Json -Depth 30))
$stream=[IO.File]::Open($Path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::None)
try {$stream.Write($raw,0,$raw.Length);$stream.Flush($true)} finally {$stream.Dispose()}
}
function Read-Json([string]$Name) {No-Reparse (Join-Path $case $Name);return Get-Content -LiteralPath (Join-Path $case $Name) -Raw | ConvertFrom-Json}
function Microsoft-Signature([string]$Path) {
No-Reparse $Path;$sig=Get-AuthenticodeSignature -LiteralPath $Path
Require ($sig.Status -eq 'Valid' -and $null -ne $sig.SignerCertificate -and $sig.SignerCertificate.Subject -match 'Microsoft Corporation') 'SETUP_MICROSOFT_SIGNATURE'
return @{status=[string]$sig.Status;thumbprint=$sig.SignerCertificate.Thumbprint;sha256=(Hash $Path)}
}
function Download($Item) {
$uri=[Uri]$Item.url;$redirects=0
while ($true) {
Require ($uri.Scheme -eq 'https' -and $uri.Host -in @('download.visualstudio.microsoft.com','static.rust-lang.org')) 'SETUP_DOWNLOAD_ORIGIN'
$request=[Net.HttpWebRequest]::Create($uri);$request.AllowAutoRedirect=$false;$request.UseDefaultCredentials=$false
$request.Timeout=30000;$request.ReadWriteTimeout=30000
$response=$request.GetResponse()
try {
if ([int]$response.StatusCode -in @(301,302,303,307,308)) {
Require ($redirects -lt 3) 'SETUP_DOWNLOAD_REDIRECT_LIMIT';$redirects++
$uri=New-Object Uri($uri,$response.Headers['Location']);continue
}
Require ([int]$response.StatusCode -eq 200) 'SETUP_DOWNLOAD_HTTP_STATUS'
$stream=[IO.File]::Open((Join-Path $case $Item.name),[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::None)
$inputStream=$response.GetResponseStream()
try {
$buffer=New-Object byte[] 65536;$size=0
while (($count=$inputStream.Read($buffer,0,$buffer.Length)) -gt 0) {$size+=$count;Require ($size -le $Item.max) 'SETUP_DOWNLOAD_SIZE';$stream.Write($buffer,0,$count)}
$stream.Flush($true)
} finally {$inputStream.Dispose();$stream.Dispose()}
Require ($null -eq $Item.sha256 -or (Hash (Join-Path $case $Item.name)) -eq $Item.sha256) 'SETUP_DOWNLOAD_HASH'
return @{name=$Item.name;url=$Item.url;final_url=$uri.AbsoluteUri;sha256=(Hash (Join-Path $case $Item.name));bytes=$size}
} finally {$response.Dispose()}
}
}
function Facts {
$os=Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion'
$policies=@(Get-ExecutionPolicy -List | Sort-Object Scope | ForEach-Object {$_.Scope.ToString()+':'+$_.ExecutionPolicy.ToString()})
$services=@{}
foreach ($name in @('W32Time','RmmDiscoveryWindows','RmmDiscoverySystemHelper')) {
$s=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'")
$services[$name]=if ($null -eq $s) {$null} else {@{state=$s.State;start_mode=$s.StartMode;pid=$s.ProcessId}}
}
$roots=@(Get-ChildItem Cert:\LocalMachine\Root | ForEach-Object {$_.Thumbprint} | Sort-Object)
$publishers=@(Get-ChildItem Cert:\LocalMachine\TrustedPublisher | ForEach-Object {$_.Thumbprint} | Sort-Object)
return @{boot_ticks=(Get-CimInstance Win32_OperatingSystem).LastBootUpTime.ToUniversalTime().Ticks;
os_build=[string]$os.CurrentBuildNumber;os_ubr=[int]$os.UBR;policies=$policies;services=$services;
root_trust_sha256=(Hash-Text ($roots -join ','));publisher_trust_sha256=(Hash-Text ($publishers -join ','));
machine_path_sha256=(Hash-Text ([Environment]::GetEnvironmentVariable('Path','Machine')));
reboot_pending=((Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending') -or
(Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired'))}
}
function Stable-Facts($Before,$After) {
foreach ($key in @('boot_ticks','os_build','os_ubr','root_trust_sha256','publisher_trust_sha256','machine_path_sha256')) {Require ($Before.$key -eq $After.$key) ('SETUP_BOUNDARY_CHANGED_'+$key.ToUpperInvariant())}
Require (($Before.policies -join '|') -eq ($After.policies -join '|')) 'SETUP_EXECUTION_POLICY_CHANGED'
foreach ($name in @('W32Time','RmmDiscoveryWindows','RmmDiscoverySystemHelper')) {
$old=$Before.services.$name;$new=$After.services.$name
Require (($null -eq $old) -eq ($null -eq $new)) 'SETUP_SERVICE_PRESENCE_CHANGED'
if ($null -ne $old) {Require ($old.state -eq $new.state -and $old.start_mode -eq $new.start_mode -and $old.pid -eq $new.pid) 'SETUP_SERVICE_CHANGED'}
}
}
function Validate-Inputs($Prepared) {
Require ((Hash $ScriptFile) -eq $Prepared.script_sha256 -and $Prepared.vs_version -eq $VsVersion -and $Prepared.toolchain -eq $Toolchain) 'SETUP_SOURCE_PLAN_CHANGED'
foreach ($item in $Prepared.downloads) {Require ((Hash (Join-Path $case $item.name)) -eq $item.sha256) 'PREPARED_INSTALLER_CHANGED'}
$sig=Microsoft-Signature (Join-Path $case 'vs_BuildTools.exe')
Require ($sig.thumbprint -eq $Prepared.vs_signer.thumbprint) 'PREPARED_SIGNER_CHANGED'
}
function Verify-Vs {
$where=Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio/Installer/vswhere.exe'
[void](Microsoft-Signature $where)
$instances=@(& $where -products Microsoft.VisualStudio.Product.BuildTools -version '[18.11,18.12)' -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -format json | ConvertFrom-Json)
Require ($LASTEXITCODE -eq 0 -and $instances.Count -eq 1 -and $instances[0].installationVersion -eq $VsVersion -and $instances[0].installationPath -eq $VsDirectory) 'INSTALLED_VS_VERSION_OR_TARGET'
$sdk=Join-Path ${env:ProgramFiles(x86)} 'Windows Kits/10/bin/10.0.26100.0/x64/midl.exe'
return @{version=$instances[0].installationVersion;path=$VsDirectory;sdk_midl=(Microsoft-Signature $sdk)}
}
function Worker([string]$Kind,$Prepared) {
Require ([Security.Principal.WindowsIdentity]::GetCurrent().User.Value -eq 'S-1-5-18') 'SETUP_FIXED_WORKER_SYSTEM_ACCOUNT'
$intent=Read-Json ($Kind+'-start-intent.json')
Require ($intent.prepared_sha256 -eq (Hash (Join-Path $case 'prepared.json'))) 'SETUP_FIXED_ONCE_INTENT'
Write-New (Join-Path $case ($Kind+'-worker-once.json')) @{kind=$Kind;pid=$PID;prepared_sha256=$intent.prepared_sha256}
$result=[ordered]@{kind=$Kind;completed=$false;reboot_required=$false;stage='worker_entered';rmm_jobs_created=$false;reboot_requested=$false}
$saved=@{}
try {
Validate-Inputs $Prepared;$before=Facts;Stable-Facts $Prepared.before $before
Require (-not $before.reboot_pending) 'SETUP_PREEXISTING_REBOOT_PENDING'
if ($Kind -eq 'vs') {
Require (-not (Test-Path -LiteralPath $VsDirectory)) 'EXISTING_VS_TARGET_NO_RETRY'
$exe=Join-Path $case 'vs_BuildTools.exe'
# Standard Microsoft acquisition/verification only. No custom
# catalog, channel, checksum override or signature-bypass option.
$args=@('--wait','--quiet','--norestart','--noUpdateInstaller','--installPath',$VsDirectory,
'--add','Microsoft.VisualStudio.Workload.VCTools','--add','Microsoft.VisualStudio.Component.VC.Tools.x86.x64',
'--add','Microsoft.VisualStudio.Component.Windows11SDK.26100')
} else {
$vs=Read-Json 'vs-result.json';Require ($vs.completed -eq $true -and $vs.reboot_required -eq $false) 'VS_MUST_COMPLETE_WITHOUT_REBOOT_FIRST'
[void](Verify-Vs)
foreach ($name in @('RUSTUP_HOME','CARGO_HOME')) {
$saved[$name]=[Environment]::GetEnvironmentVariable($name,'Process')
$path=Join-Path $case $name.ToLowerInvariant();Require (-not (Test-Path -LiteralPath $path)) 'EXISTING_RUST_HOME_NO_RETRY'
[Environment]::SetEnvironmentVariable($name,$path,'Process')
}
foreach ($pair in @(@('RUSTUP_DIST_SERVER','https://static.rust-lang.org'),@('RUSTUP_UPDATE_ROOT','https://static.rust-lang.org/rustup'))) {
$saved[$pair[0]]=[Environment]::GetEnvironmentVariable($pair[0],'Process')
[Environment]::SetEnvironmentVariable($pair[0],$pair[1],'Process')
}
$exe=Join-Path $case 'rustup-init.exe'
$args=@('-y','--no-modify-path','--no-update-default-toolchain','--profile','minimal',
'--default-host','x86_64-pc-windows-msvc','--default-toolchain','1.99.1','--component','clippy,rustfmt')
}
$arguments=@($args | ForEach-Object {Require ($_ -notmatch '["\r\n\x00]') 'SETUP_ARGUMENT_ENCODING';'"'+($_ -replace '(\\+)$','$1$1')+'"'}) -join ' '
$process=Start-Process -FilePath $exe -ArgumentList $arguments -PassThru -WindowStyle Hidden -RedirectStandardOutput (Join-Path $case ($Kind+'.stdout')) -RedirectStandardError (Join-Path $case ($Kind+'.stderr'))
Write-New (Join-Path $case ($Kind+'-installer-process.json')) @{pid=$process.Id;start_ticks=$process.StartTime.ToUniversalTime().Ticks;exe_sha256=(Hash $exe)}
Require ($process.WaitForExit(3600000)) 'SETUP_TIMEOUT_EFFECT_UNKNOWN_NO_RETRY';$process.Refresh();$result.exit_code=$process.ExitCode
$result.reboot_required=($process.ExitCode -in @(3010,1641))
$after=Facts;$result.after=$after;$result.reboot_required=($result.reboot_required -or $after.reboot_pending);Stable-Facts $Prepared.before $after
if ($process.ExitCode -eq 3010 -or $after.reboot_pending) {$result.stage='blocked_reboot_required';$result.reboot_required=$true}
elseif ($process.ExitCode -eq 1641) {$result.stage='unexpected_reboot_initiated';$result.reboot_required=$true}
else {
Require ($process.ExitCode -eq 0) 'SETUP_INSTALLER_FAILED_NO_RETRY'
if ($Kind -eq 'vs') {$result.installed=Verify-Vs}
else {
$rustup=Join-Path $env:CARGO_HOME 'bin/rustup.exe';$rustc=@(& $rustup which --toolchain $Toolchain rustc)
Require ($LASTEXITCODE -eq 0 -and $rustc.Count -eq 1) 'PINNED_RUSTC_MISSING'
$version=@(& $rustc[0] -vV)
Require ($LASTEXITCODE -eq 0 -and 'release: 1.99.1' -in $version -and 'host: x86_64-pc-windows-msvc' -in $version) 'INSTALLED_RUST_VERSION_OR_HOST'
$result.installed=@{rustup_exe=$rustup;rustup_sha256=(Hash $rustup);rustc_sha256=(Hash $rustc[0]);rustup_home=$env:RUSTUP_HOME;cargo_home=$env:CARGO_HOME;version=$version}
}
$result.stage='installed_verified';$result.completed=$true
}
} catch {
$result.error_class=$_.Exception.GetType().Name;$result.error_code=if ($_.Exception.Message -match '^[A-Z0-9_]{1,96}$') {$_.Exception.Message} else {'SETUP_WORKER_FAILED'}
} finally {
foreach ($name in $saved.Keys) {[Environment]::SetEnvironmentVariable($name,$saved[$name],'Process')}
Write-New (Join-Path $case ($Kind+'-result.json')) $result
Disable-ScheduledTask -TaskName ('RmmNativeTools-'+$Kind+'-'+$Prepared.case_id) -ErrorAction SilentlyContinue | Out-Null
}
}
try {
Require ($env:OS -eq 'Windows_NT' -and [Environment]::Is64BitProcess) 'SETUP_NATIVE_WINDOWS_X64'
Require ((Get-ExecutionPolicy -Scope Process) -eq 'RemoteSigned') 'AUTHORIZED_BOOTSTRAP_PROCESS_REMOTESIGNED_REQUIRED'
$principal=New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
Require ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) 'SETUP_ADMIN_REQUIRED'
Require (-not [string]::IsNullOrEmpty($ScriptFile)) 'EXPLICIT_PINNED_SCRIPT_FILE_REQUIRED'
$ScriptFile=(Get-Item -LiteralPath $ScriptFile).FullName;No-Reparse $ScriptFile
if ($Phase -eq 'Prepare') {
Require ($RootDirectory -match '^[A-Za-z]:\\') 'LOCAL_TOOL_ROOT_REQUIRED'
if (-not (Test-Path -LiteralPath $RootDirectory)) {[void][IO.Directory]::CreateDirectory($RootDirectory)}
Protected-Directory $RootDirectory;$case=Join-Path $RootDirectory $CaseId.ToString();New-Private $case
Require (-not (Test-Path -LiteralPath $VsDirectory)) 'EXISTING_VS_TARGET'
$before=Facts;Require (-not $before.reboot_pending) 'SETUP_PREEXISTING_REBOOT_PENDING'
$drive=New-Object IO.DriveInfo([IO.Path]::GetPathRoot($case));Require ($drive.AvailableFreeSpace -ge 30GB) 'SETUP_DISK_BELOW_30GIB'
$savedTls=[Net.ServicePointManager]::SecurityProtocol
try {[Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12;$downloaded=@($downloads | ForEach-Object {Download $_})}
finally {[Net.ServicePointManager]::SecurityProtocol=$savedTls}
$signer=Microsoft-Signature (Join-Path $case 'vs_BuildTools.exe')
$version=(Get-Item -LiteralPath (Join-Path $case 'vs_BuildTools.exe')).VersionInfo
Require ($version.ProductVersion -eq '18.11.4 LTSC' -and $version.FileVersion -eq $VsVersion) 'PINNED_VS_BOOTSTRAPPER_VERSION'
Require ((Get-Content -LiteralPath (Join-Path $case 'rustup-init.exe.sha256') -Raw).Trim().Split(' ')[0] -eq $RustupSha256) 'RUSTUP_OFFICIAL_CHECKSUM'
Require ((Get-Content -LiteralPath (Join-Path $case 'rust-toolchain.toml.sha256') -Raw).Trim().Split(' ')[0] -eq 'fb152be80975c194aa5fc684b2aec3a6e14e2b855efe2faa4e5f8ae6e590f463') 'RUST_TOOLCHAIN_DISTRIBUTION_PIN'
[IO.File]::Copy($ScriptFile,(Join-Path $case 'Install-NativeBuildTools.ps1'),$false)
$prepared=@{schema_version=1;case_id=$CaseId.ToString();script_sha256=(Hash $ScriptFile);before=$before;downloads=$downloaded;
vs_signer=$signer;vs_version=$VsVersion;toolchain=$Toolchain;free_bytes=$drive.AvailableFreeSpace;installers_executed=$false}
Write-New (Join-Path $case 'prepared.json') $prepared
Write-Output ('PREPARED '+$case+'; downloads verified, no installation');exit 0
}
Require (-not [string]::IsNullOrEmpty($CaseDirectory)) 'EXPLICIT_RETAINED_CASE_REQUIRED'
$case=(Get-Item -LiteralPath $CaseDirectory).FullName;Protected-Directory $case;$prepared=Read-Json 'prepared.json'
Require (([Guid]$prepared.case_id).ToString() -eq (Split-Path $case -Leaf)) 'SAME_PREPARED_CASE'
Validate-Inputs $prepared
if ($Phase -in @('WorkerVs','WorkerRust')) {Worker $(if ($Phase -eq 'WorkerVs') {'vs'} else {'rust'}) $prepared;exit 0}
if ($Phase -eq 'Read') {
$results=@{}
foreach ($kind in @('vs','rust')) {
$name=$kind+'-result.json';$task=Get-ScheduledTask -TaskName ('RmmNativeTools-'+$kind+'-'+$prepared.case_id) -ErrorAction SilentlyContinue
$results[$kind]=@{result=$(if (Test-Path -LiteralPath (Join-Path $case $name)) {Read-Json $name} else {$null});task_state=$(if ($null -eq $task) {'absent'} else {[string]$task.State})}
}
$facts=Facts;$stable=$true;$boundaryError=$null
try {Stable-Facts $prepared.before $facts} catch {$stable=$false;$boundaryError='BOOTSTRAP_BOUNDARY_CHANGED'}
Write-Output (@{case_id=$prepared.case_id;results=$results;facts=$facts;read_only=$true;boundary_verified=$stable;boundary_error=$boundaryError} | ConvertTo-Json -Depth 30);exit 0
}
$kind=if ($Phase -eq 'InstallVs') {'vs'} else {'rust'}
$before=Facts;Stable-Facts $prepared.before $before;Require (-not $before.reboot_pending) 'SETUP_REBOOT_PENDING'
if ($kind -eq 'rust') {$vs=Read-Json 'vs-result.json';Require ($vs.completed -eq $true -and $vs.reboot_required -eq $false) 'VS_FIRST_NO_REBOOT'}
$intentPath=Join-Path $case ($kind+'-start-intent.json')
Write-New $intentPath @{kind=$kind;prepared_sha256=(Hash (Join-Path $case 'prepared.json'));script_sha256=$prepared.script_sha256}
$taskName='RmmNativeTools-'+$kind+'-'+$prepared.case_id
Require ($null -eq (Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue)) 'EXISTING_TOOL_TASK_NO_RETRY'
$workerFile=Join-Path $case 'Install-NativeBuildTools.ps1';$quotedFile=$workerFile.Replace("'","''");$quotedCase=$case.Replace("'","''")
$workerPhase=if ($kind -eq 'vs') {'WorkerVs'} else {'WorkerRust'}
$command="`$p='$quotedFile';if((Get-FileHash -LiteralPath `$p -Algorithm SHA256).Hash.ToLowerInvariant() -ne '$($prepared.script_sha256)'){throw 'WORKER_HASH'};& `$p -Phase $workerPhase -CaseDirectory '$quotedCase'"
$encoded=[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command))
$powershell=Join-Path ([Environment]::SystemDirectory) 'WindowsPowerShell/v1.0/powershell.exe';[void](Microsoft-Signature $powershell)
$action=New-ScheduledTaskAction -Execute $powershell -Argument ('-NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -EncodedCommand '+$encoded)
$settings=New-ScheduledTaskSettingsSet -MultipleInstances IgnoreNew -RestartCount 0 -ExecutionTimeLimit (New-TimeSpan -Minutes 90) -DisallowHardTerminate -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
$user=New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest
Register-ScheduledTask -TaskName $taskName -Action $action -Principal $user -Settings $settings | Out-Null
# Deliberately no trigger or automatic restart: exactly this one demand call.
Start-ScheduledTask -TaskName $taskName
Write-New (Join-Path $case ($kind+'-task-started.json')) @{task_name=$taskName;source_sha256=$prepared.script_sha256;demand_only=$true;automatic_retry=$false}
Write-Output ('STARTED '+$kind+'; read retained case, never repeat install')
} catch {
$errorCode=if ($_.Exception.Message -match '^[A-Z0-9_]{1,96}$') {$_.Exception.Message} else {'NATIVE_TOOL_BOOTSTRAP_FAILED'}
if ($null -ne $case) {try {Write-New (Join-Path $case ('bootstrap-error-'+[Guid]::NewGuid().ToString()+'.json')) @{phase=$Phase;error_class=$_.Exception.GetType().Name;error_code=$errorCode}} catch {}}
Write-Output ('NATIVE_TOOL_SETUP_INCOMPLETE '+$errorCode+'; retain case and readback, no automatic retry');exit 2
}