@@ -76,12 +76,120 @@ if (-not $BinaryDir) {
7676 $BinaryDir = Join-Path $targetRoot " $target /release"
7777}
7878$savedEnv = @ {}
79- foreach ($name in @ (" OPENSHELL_GATEWAY_CONFIG" , " OPENSHELL_GATEWAY" , " OPENSHELL_MXC_MOCK_WXC" , " OPENSHELL_WXC_EXEC_PATH" , " OPENSHELL_COMPUTE_DRIVER" , " OPENSHELL_MXC_SHARE_DIR" , " XDG_CONFIG_HOME" )) {
80- $savedEnv [$name ] = [Environment ]::GetEnvironmentVariable($name , " Process" )
79+ $processEnvironment = [Environment ]::GetEnvironmentVariables(" Process" )
80+ foreach ($name in @ (" OPENSHELL_MXC_MOCK_WXC" , " OPENSHELL_WXC_EXEC_PATH" , " OPENSHELL_COMPUTE_DRIVER" , " OPENSHELL_MXC_SHARE_DIR" )) {
81+ $exists = $processEnvironment.Contains ($name )
82+ $savedEnv [$name ] = [pscustomobject ]@ {
83+ Exists = $exists
84+ Value = if ($exists ) { [string ] $processEnvironment [$name ] } else { $null }
85+ }
8186}
8287$secretDir = Join-Path $resultsRoot " keys-$stamp -$ ( [guid ]::NewGuid().ToString(' N' )) "
8388$transcriptStarted = $false
8489
90+ $cliStateRoot = $null
91+ $cliEnvironmentSnapshot = @ {}
92+ $cliEnvironmentNames = @ (
93+ " APPDATA" , " LOCALAPPDATA" , " XDG_CONFIG_HOME" , " XDG_STATE_HOME" , " XDG_DATA_HOME" ,
94+ " OPENSHELL_GATEWAY" , " OPENSHELL_GATEWAY_ENDPOINT" , " OPENSHELL_GATEWAY_INSECURE" ,
95+ " OPENSHELL_GATEWAY_CONFIG" , " OPENSHELL_GATEWAY_NAME"
96+ )
97+
98+ function Set-ProcessEnvironmentVariableExact {
99+ param (
100+ [Parameter (Mandatory = $true )]
101+ [string ] $Name ,
102+ [Parameter (Mandatory = $true )]
103+ [bool ] $Exists ,
104+ [AllowNull ()]
105+ [string ] $Value
106+ )
107+
108+ if (-not $Exists ) {
109+ Remove-Item " Env:$Name " - ErrorAction SilentlyContinue
110+ return
111+ }
112+
113+ if ($Value.Length -eq 0 ) {
114+ # Windows PowerShell 5.1 maps an empty value passed through
115+ # Environment.SetEnvironmentVariable to deletion. Call Win32 directly
116+ # so an inherited empty entry remains distinguishable from absence.
117+ if (-not (" OpenShellMxcProcessEnvironmentNative" -as [type ])) {
118+ Add-Type - TypeDefinition @'
119+ using System.Runtime.InteropServices;
120+
121+ public static class OpenShellMxcProcessEnvironmentNative
122+ {
123+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
124+ [return: MarshalAs(UnmanagedType.Bool)]
125+ public static extern bool SetEnvironmentVariable(string name, string value);
126+ }
127+ '@
128+ }
129+ if (-not [OpenShellMxcProcessEnvironmentNative ]::SetEnvironmentVariable($Name , [string ]::Empty)) {
130+ $errorCode = [Runtime.InteropServices.Marshal ]::GetLastWin32Error()
131+ throw " failed to restore empty process environment variable '$Name ' (Win32 error $errorCode )"
132+ }
133+ return
134+ }
135+
136+ [Environment ]::SetEnvironmentVariable($Name , $Value , " Process" )
137+ }
138+
139+ function Enter-IsolatedCliEnvironment {
140+ $processEnvironment = [Environment ]::GetEnvironmentVariables(" Process" )
141+ foreach ($name in $cliEnvironmentNames ) {
142+ $exists = $processEnvironment.Contains ($name )
143+ $script :cliEnvironmentSnapshot [$name ] = [pscustomobject ]@ {
144+ Exists = $exists
145+ Value = if ($exists ) { [string ] $processEnvironment [$name ] } else { $null }
146+ }
147+ }
148+ $script :cliStateRoot = Join-Path ([IO.Path ]::GetTempPath()) " openshell-mxc-e2e-cli-$PID -$ ( [Guid ]::NewGuid().ToString(' N' )) "
149+ $isolatedPaths = @ {
150+ APPDATA = Join-Path $script :cliStateRoot " appdata"
151+ LOCALAPPDATA = Join-Path $script :cliStateRoot " localappdata"
152+ XDG_CONFIG_HOME = Join-Path $script :cliStateRoot " xdg-config"
153+ XDG_STATE_HOME = Join-Path $script :cliStateRoot " xdg-state"
154+ XDG_DATA_HOME = Join-Path $script :cliStateRoot " xdg-data"
155+ }
156+ try {
157+ New-Item - ItemType Directory - Force - Path @ ($isolatedPaths.Values ) | Out-Null
158+ foreach ($entry in $isolatedPaths.GetEnumerator ()) {
159+ [Environment ]::SetEnvironmentVariable($entry.Key , $entry.Value , " Process" )
160+ }
161+ foreach ($name in $cliEnvironmentNames | Where-Object { -not $isolatedPaths.ContainsKey ($_ ) }) {
162+ Remove-Item " Env:$name " - ErrorAction SilentlyContinue
163+ }
164+ } catch {
165+ Exit-IsolatedCliEnvironment
166+ throw
167+ }
168+ }
169+
170+ function Exit-IsolatedCliEnvironment {
171+ foreach ($name in $cliEnvironmentNames ) {
172+ if (-not $script :cliEnvironmentSnapshot.ContainsKey ($name )) { continue }
173+ $snapshot = $script :cliEnvironmentSnapshot [$name ]
174+ Set-ProcessEnvironmentVariableExact - Name $name - Exists $snapshot.Exists - Value $snapshot.Value
175+ }
176+ if ($script :cliStateRoot -and (Test-Path - LiteralPath $script :cliStateRoot )) {
177+ if ($KeepRunning -and $gw -and -not $gw.HasExited ) {
178+ Write-Host " Retaining isolated CLI/runtime state for live gateway: $script :cliStateRoot "
179+ return
180+ }
181+ # Resolve the generated target before recursive cleanup; never remove an
182+ # arbitrary caller path or the temporary directory itself.
183+ $cleanupPath = [IO.Path ]::GetFullPath($script :cliStateRoot )
184+ $tempPrefix = [IO.Path ]::GetFullPath([IO.Path ]::GetTempPath()).TrimEnd(' \' ) + ' \'
185+ if (-not $cleanupPath.StartsWith ($tempPrefix , [StringComparison ]::OrdinalIgnoreCase) -or
186+ (Split-Path $cleanupPath - Leaf) -notmatch ' ^openshell-mxc-(e2e|ocsf)-cli-[0-9]+-[0-9a-f]{32}$' ) {
187+ throw " refusing unsafe CLI state cleanup: $cleanupPath "
188+ }
189+ Remove-Item - LiteralPath $cleanupPath - Recurse - Force - ErrorAction SilentlyContinue
190+ }
191+ }
192+
85193function Step ([string ]$m ) { Write-Host " `n === $m ===" - ForegroundColor Cyan }
86194function Info ([string ]$m ) { Write-Host " $m " }
87195function Ok ([string ]$m ) { Write-Host " [OK] $m " - ForegroundColor Green }
@@ -247,14 +355,13 @@ function Stop-Gw($p) {
247355
248356function Register-Cli {
249357 if ($script :registered ) { return }
250- $env: OPENSHELL_GATEWAY = " "
251358
252359 $addResult = Invoke-NativeCaptured $cli @ (
253360 " gateway" , " add" , " http://127.0.0.1:$Port " , " --local" , " --name" , $GatewayName
254361 )
255362 $addText = ($addResult.Output -join " `n " )
256363 if ($addText ) { $addResult.Output | ForEach-Object { Info $_ } }
257- if ($addResult.ExitCode -ne 0 -and $addText -notmatch ' (?i)already exists ' ) {
364+ if ($addResult.ExitCode -ne 0 ) {
258365 throw " gateway add failed (exit $ ( $addResult.ExitCode ) ): $addText "
259366 }
260367
@@ -510,6 +617,7 @@ $backendProbe = @{ Live = $false; Reason = "not probed" }
510617$runId = Get-Date - Format ' MMddHHmmss'
511618
512619try {
620+ Enter-IsolatedCliEnvironment
513621 # Start the transcript inside the guarded region so a Start-Transcript failure
514622 # is caught and the results bundle is still produced. Pre-flight runs
515623 # immediately below, so the transcript still captures the whole run.
@@ -541,7 +649,6 @@ try {
541649
542650 # Capture the pristine TOML once; every scenario renders a fresh copy from this.
543651 $tomlBase = Get-Content $tomlTemplate - Raw
544- $env: XDG_CONFIG_HOME = Join-Path $resultDir " cli-config"
545652 $openssl = (Get-Command openssl - ErrorAction Stop).Source
546653 New-Item - ItemType Directory $secretDir | Out-Null
547654 $ownerSid = [Security.Principal.WindowsIdentity ]::GetCurrent().User.Value
@@ -929,7 +1036,11 @@ ingress works, not that direct host ingress is blocked.
9291036 }
9301037 if (Test-Path $secretDir ) { Remove-Item - LiteralPath $secretDir - ErrorAction SilentlyContinue }
9311038 }
932- foreach ($name in $savedEnv.Keys ) { [Environment ]::SetEnvironmentVariable($name , $savedEnv [$name ], " Process" ) }
1039+ Exit-IsolatedCliEnvironment
1040+ foreach ($name in $savedEnv.Keys ) {
1041+ $snapshot = $savedEnv [$name ]
1042+ Set-ProcessEnvironmentVariableExact - Name $name - Exists $snapshot.Exists - Value $snapshot.Value
1043+ }
9331044}
9341045
9351046if ($harnessError -or $failCount -gt 0 ) {
0 commit comments