Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Add a Windows probe for code integrity blocks, and audit bundle signatures in CI (#10408)
Daniel Han5a2855717b27
diff --git a/.github/workflows/windows-llama-signature-audit.yml b/.github/workflows/windows-llama-signature-audit.ymlnew file mode 100644index 00000000000..4b53ffba48b--- /dev/null+++ b/.github/workflows/windows-llama-signature-audit.yml@@ -0,0 +1,551 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++name: "Windows: llama.cpp signature audit"++# Reports how much of the llama.cpp runtime we ask users to download is Authenticode signed.++on:+ workflow_dispatch:+ inputs:+ release_tag:+ description: 'llama.cpp release tag to audit, or "latest"'+ required: false+ default: 'latest'+ enforce:+ description: 'Fail the job when an unsigned PE is found'+ required: false+ default: 'true'+ schedule:+ - cron: '17 6 * * 1'+ pull_request:+ paths:+ - '.github/workflows/windows-llama-signature-audit.yml'+ - 'scripts/windows_sac_probe/**'++permissions:+ contents: read++concurrency:+ group: ${{ github.workflow }}-${{ github.ref }}+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}++jobs:+ audit:+ name: Audit signatures+ runs-on: windows-latest+ timeout-minutes: 30+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false++ - name: Report Smart App Control state on this runner+ shell: pwsh+ run: |+ $ErrorActionPreference = 'Continue'+ $state = $null+ try {+ $state = (Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\CI\Policy' `+ -Name 'VerifiedAndReputablePolicyState' -ErrorAction Stop).VerifiedAndReputablePolicyState+ } catch { }+ $mode = switch ($state) { 0 {'off'} 1 {'enforcement'} 2 {'evaluation'} default {'absent'} }+ Write-Host "Smart App Control on this runner: $mode"+ & CiTool.exe -lp 2>&1 | Select-String -Pattern 'Friendly Name|Is Enforced' | Write-Host++ - name: Enumerate the Windows bundles+ shell: pwsh+ env:+ GH_TOKEN: ${{ github.token }}+ RELEASE_TAG: ${{ github.event.inputs.release_tag || 'latest' }}+ run: |+ $ErrorActionPreference = 'Stop'+ New-Item -ItemType Directory -Force -Path bundles | Out-Null+ if ($env:RELEASE_TAG -eq 'latest') {+ $tag = (gh release view --repo unslothai/llama.cpp --json tagName -q .tagName)+ } else {+ $tag = $env:RELEASE_TAG+ }+ Write-Host "auditing release $tag"+ Add-Content -Path $env:GITHUB_ENV -Value "AUDIT_TAG=$tag"+ $assets = @(gh release view $tag --repo unslothai/llama.cpp --json assets -q '.assets[].name' |+ Where-Object { $_ -like '*windows*' -and $_ -like '*.zip' })+ if ($LASTEXITCODE -ne 0) { throw "gh release view exited $LASTEXITCODE" }+ if ($assets.Count -eq 0) { throw "no Windows assets on $tag" }+ Write-Host "auditing $($assets.Count) Windows asset(s):"+ $assets | ForEach-Object { Write-Host " $_" }+ $assets -join "`n" | Set-Content -LiteralPath windows-assets.txt -Encoding UTF8++ - name: Inventory Authenticode signatures+ id: inventory+ shell: pwsh+ env:+ GH_TOKEN: ${{ github.token }}+ run: |+ $ErrorActionPreference = 'Continue'+ $ext = @('.exe', '.dll', '.pyd', '.sys', '.ocx', '.cpl', '.scr')+ $rows = @()+ New-Item -ItemType Directory -Force -Path bundles | Out-Null+ $assets = @(Get-Content -LiteralPath windows-assets.txt | Where-Object { $_ })+ foreach ($asset in $assets) {+ Write-Host "--- $asset"+ gh release download $env:AUDIT_TAG --repo unslothai/llama.cpp --pattern $asset --dir bundles --clobber+ if ($LASTEXITCODE -ne 0) {+ Write-Host "::error::gh release download exited $LASTEXITCODE for $asset"+ exit 1+ }+ $zip = Get-Item (Join-Path 'bundles' $asset) -ErrorAction SilentlyContinue+ if (-not $zip) {+ Write-Host "::error::$asset did not download"+ exit 1+ }+ $dest = Join-Path $env:RUNNER_TEMP ("x-" + $zip.BaseName)+ Remove-Item $dest -Recurse -Force -ErrorAction SilentlyContinue+ Expand-Archive -LiteralPath $zip.FullName -DestinationPath $dest -Force+ $files = @(Get-ChildItem $dest -Recurse -File | Where-Object { $ext -contains $_.Extension.ToLowerInvariant() })+ if ($files.Count -eq 0) {+ Write-Host "::error::no PE payload inside $($zip.Name)"+ exit 1+ }+ foreach ($f in $files) {+ $s = Get-AuthenticodeSignature -LiteralPath $f.FullName+ $rows += [pscustomobject]@{+ Bundle = $zip.Name+ Name = $f.Name+ Status = [string]$s.Status+ Subject = if ($s.SignerCertificate) { $s.SignerCertificate.Subject } else { '' }+ }+ }+ Remove-Item $dest -Recurse -Force -ErrorAction SilentlyContinue+ Remove-Item $zip.FullName -Force -ErrorAction SilentlyContinue+ }+ # Every enumerated asset has to appear, or a download that produced a zip with no rows would shrink the audit silently.+ $audited = @($rows | Group-Object Bundle).Count+ if ($audited -ne $assets.Count) {+ Write-Host "::error::enumerated $($assets.Count) Windows asset(s) but inventoried $audited"+ exit 1+ }++ $rows | Export-Csv -LiteralPath signature-inventory.csv -NoTypeInformation -Encoding UTF8++ $summary = @()+ $summary += "# llama.cpp Windows signature audit"+ $summary += ""+ $summary += "Release: ``$env:AUDIT_TAG``"+ $summary += ""+ $summary += "| bundle | PE files | signed | unsigned |"+ $summary += "| --- | ---: | ---: | ---: |"+ $totalUnsigned = 0+ foreach ($bundle in ($rows | Group-Object Bundle)) {+ $signed = @($bundle.Group | Where-Object { $_.Status -eq 'Valid' }).Count+ $unsigned = $bundle.Count - $signed+ $totalUnsigned += $unsigned+ $summary += "| $($bundle.Name) | $($bundle.Count) | $signed | $unsigned |"+ }+ $summary += ""+ if ($totalUnsigned -gt 0) {+ $summary += "$totalUnsigned unsigned PE file(s). Smart App Control evaluates each of these as it loads."+ $summary += ""+ $summary += "Signed files, for contrast:"+ $summary += ""+ $signedRows = @($rows | Where-Object { $_.Status -eq 'Valid' } | Select-Object -Unique Name, Subject)+ if ($signedRows.Count -eq 0) {+ $summary += "- none"+ } else {+ foreach ($r in $signedRows) { $summary += "- ``$($r.Name)`` $($r.Subject)" }+ }+ } else {+ $summary += "Every PE in every audited bundle is validly signed."+ }+ $summary -join "`n" | Add-Content -Path $env:GITHUB_STEP_SUMMARY+ Add-Content -Path $env:GITHUB_OUTPUT -Value "unsigned=$totalUnsigned"+ Write-Host "$totalUnsigned unsigned PE file(s)"++ - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ if: always()+ with:+ name: signature-inventory+ path: signature-inventory.csv+ if-no-files-found: warn++ - name: Verdict+ shell: pwsh+ env:+ ENFORCE: ${{ github.event.inputs.enforce || 'true' }}+ UNSIGNED: ${{ steps.inventory.outputs.unsigned }}+ run: |+ $ErrorActionPreference = 'Continue'+ $unsigned = [int]$env:UNSIGNED+ if ($unsigned -eq 0) {+ Write-Host 'Every audited binary is signed.'+ exit 0+ }+ # Hard failure by default.+ if ($env:ENFORCE -eq 'true') {+ Write-Host "::error::$unsigned unsigned PE file(s) in the published Windows bundles"+ exit 1+ }+ Write-Host "::warning::$unsigned unsigned PE file(s) in the published Windows bundles. See the job summary."++ # The job above reads certificate tables.+ code-integrity:+ name: App Control audit (signature-only)+ runs-on: windows-latest+ timeout-minutes: 30+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false++ - name: Require a runner that can host a policy+ shell: pwsh+ run: |+ $ErrorActionPreference = 'Stop'+ # CiTool is inbox from Windows 11 22H2 / Server 2025.+ $citool = Get-Command CiTool.exe -ErrorAction SilentlyContinue+ if (-not $citool) { throw 'CiTool.exe is absent; this runner cannot host an App Control policy' }+ Write-Host "CiTool: $($citool.Source)"+ Write-Host "OS: $((Get-CimInstance Win32_OperatingSystem).Caption) $([Environment]::OSVersion.Version)"++ $log = 'Microsoft-Windows-CodeIntegrity/Operational'+ & wevtutil.exe sl $log /e:true /ms:67108864+ if ($LASTEXITCODE -ne 0) { throw "wevtutil sl $log exited $LASTEXITCODE; the channel could not be configured" }+ $cfg = (& wevtutil.exe gl $log) -join "`n"+ if ($cfg -notmatch 'enabled:\s*true') { throw "$log is still disabled; the audit cannot collect evidence" }+ if ($cfg -match 'maxSize:\s*(\d+)') { $maxSize = [int64]$Matches[1] } else { throw "$log reported no maxSize" }+ if ($maxSize -lt 67108864) { throw "$log maxSize is $maxSize, below the 64 MB this job asks for" }+ Write-Host "$log enabled, maxSize $maxSize"++ - name: Fetch the Smart App Control audit policies+ shell: pwsh+ run: |+ $ErrorActionPreference = 'Stop'+ New-Item -ItemType Directory -Force -Path policy | Out-Null+ Invoke-WebRequest -Uri 'https://aka.ms/sacauditpolicies' -OutFile policy/sac.zip -UseBasicParsing+ Expand-Archive -LiteralPath policy/sac.zip -DestinationPath policy/extracted -Force+ $noisg = Get-ChildItem -LiteralPath policy/extracted -Recurse -File |+ Where-Object { $_.Name -like 'SmartAppControlAuditNoISG*' } | Select-Object -First 1+ if (-not $noisg) {+ Write-Host 'archive contents:'+ Get-ChildItem -LiteralPath policy/extracted -Recurse -File | ForEach-Object { Write-Host " $($_.FullName)" }+ throw 'SmartAppControlAuditNoISG was not in the downloaded archive'+ }+ Write-Host "policy: $($noisg.FullName)"+ Add-Content -Path $env:GITHUB_ENV -Value "SAC_POLICY=$($noisg.FullName)"++ - name: Apply the policy and verify it is active+ id: apply+ shell: pwsh+ run: |+ $ErrorActionPreference = 'Stop'+ $out = & CiTool.exe --update-policy "$env:SAC_POLICY" 2>&1 | Out-String+ Write-Host $out+ & CiTool.exe --refresh 2>&1 | Out-String | Write-Host++ # Listing a policy is not the same as it being active.+ $policies = (& CiTool.exe -lp -json 2>$null | ConvertFrom-Json).Policies+ $sac = @($policies | Where-Object { $_.FriendlyName -like '*AuditNoISG*' })+ foreach ($p in $policies) { Write-Host (" policy {0} enforced={1}" -f $p.FriendlyName, $p.IsEnforced) }+ if ($sac.Count -eq 0) { throw 'the Smart App Control audit policy is not in the active policy set after refresh' }+ # Audit, never enforcement.+ if ($sac[0].FriendlyName -notlike '*Audit*') { throw "refusing to continue: $($sac[0].FriendlyName) is not an audit policy" }+ Add-Content -Path $env:GITHUB_ENV -Value "SAC_POLICY_ID=$($sac[0].PolicyID)"+ Add-Content -Path $env:GITHUB_ENV -Value "AUDIT_START=$((Get-Date).ToUniversalTime().ToString('o'))"++ - name: Positive control -- an unsigned binary must raise 3076+ id: control+ shell: powershell+ run: |+ $ErrorActionPreference = 'Continue'+ # Without this the whole job is unfalsifiable+ $src = 'public class UnsignedControl { public static void Main() { System.Console.WriteLine("control"); } }'+ $exe = Join-Path $PWD 'unsigned-control.exe'+ Add-Type -TypeDefinition $src -OutputAssembly $exe -OutputType ConsoleApplication+ if (-not (Test-Path $exe)) { throw 'could not build the unsigned control binary' }+ & $exe 2>&1 | Write-Host++ # Polled rather than slept once.+ $policyBare = "$env:SAC_POLICY_ID".Trim('{', '}').ToLowerInvariant()+ $fromPolicy = {+ param($e)+ $named = $false+ $otherId = $false+ try {+ foreach ($node in ([xml] $e.ToXml()).Event.EventData.Data) {+ $v = [string] $node.'#text'+ if (-not $v) { continue }+ if ($policyBare -and $v.ToLowerInvariant().Contains($policyBare)) { return $true }+ if ($node.Name -like 'PolicyName*') {+ if ($v -like '*AuditNoISG*') { $named = $true }+ } elseif ($node.Name -like 'Policy*' -and $v -match '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}') {+ $otherId = $true+ }+ }+ } catch { }+ # The name is a fallback for events without a policy ID; an ID naming another policy wins.+ return ($named -and -not $otherId)+ }+ $since = [datetime]::Parse($env:AUDIT_START).ToUniversalTime()+ $events = @()+ $fired = @()+ foreach ($attempt in 1..10) {+ Start-Sleep -Seconds 3+ $events = @(Get-WinEvent -FilterHashtable @{+ LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; Id = 3076; StartTime = $since+ } -ErrorAction SilentlyContinue)+ $named = @($events | Where-Object { $_.Message -like '*unsigned-control*' })+ $fired = @($named | Where-Object { & $fromPolicy $_ })+ if ($fired.Count -gt 0) { break }+ }+ Write-Host "3076 events since policy apply: $($events.Count); naming the control: $($named.Count); from the installed policy: $($fired.Count)"+ if ($fired.Count -eq 0) {+ Write-Host '::error::the unsigned positive control raised no 3076 event, so this policy is not evaluating loads here; the bundle result below would be meaningless'+ "control_fired=false" | Add-Content -Path $env:GITHUB_OUTPUT+ exit 1+ }+ "control_fired=true" | Add-Content -Path $env:GITHUB_OUTPUT+ Write-Host 'positive control fired; the policy is evaluating loads on this runner'++ - name: Load the shipped runtime under the policy+ id: exercise+ shell: pwsh+ env:+ GH_TOKEN: ${{ github.token }}+ RELEASE_TAG: ${{ github.event.inputs.release_tag || 'latest' }}+ run: |+ $ErrorActionPreference = 'Stop'+ $tag = if ($env:RELEASE_TAG -eq 'latest') {+ gh release view --repo unslothai/llama.cpp --json tagName -q .tagName+ } else { $env:RELEASE_TAG }+ Write-Host "exercising release $tag"++ $asset = @(gh release view $tag --repo unslothai/llama.cpp --json assets -q '.assets[].name' |+ Where-Object { $_ -like '*windows-x64-cpu*' -and $_ -like '*.zip' })[0]+ if (-not $asset) { throw "no windows-x64-cpu asset on $tag" }+ gh release download $tag --repo unslothai/llama.cpp --pattern $asset --dir . --clobber+ Expand-Archive -LiteralPath $asset -DestinationPath runtime -Force++ $server = Get-ChildItem -LiteralPath runtime -Recurse -Filter 'llama-server.exe' | Select-Object -First 1+ if (-not $server) { throw 'llama-server.exe not found in the bundle' }+ Add-Content -Path $env:GITHUB_ENV -Value "RUNTIME_DIR=$($server.Directory.FullName)"++ & $server.FullName --version 2>&1 | Write-Host+ $code = $LASTEXITCODE+ Add-Content -Path $env:GITHUB_ENV -Value "EXERCISE_EXIT=$code"+ Write-Host "llama-server --version exited $code"+ # Studio also runs llama-quantize, which loads its own llama-quantize-impl.dll.+ $quantize = Get-ChildItem -LiteralPath $server.Directory.FullName -Filter 'llama-quantize.exe' | Select-Object -First 1+ if ($quantize) {+ & $quantize.FullName --help 2>&1 | Out-Null+ Add-Content -Path $env:GITHUB_ENV -Value "QUANTIZE_EXIT=$LASTEXITCODE"+ Write-Host "llama-quantize --help exited $LASTEXITCODE"+ } else {+ Write-Host '::warning::llama-quantize.exe is not in the bundle, so only llama-server was loaded'+ }+ Add-Content -Path $env:GITHUB_ENV -Value 'EXERCISE_COMPLETED=true'+ # The exit codes are recorded for the verdict; llama-quantize --help exits 1 after printing usage.+ exit 0++ - name: Verdict+ if: always() && steps.control.outputs.control_fired == 'true'+ shell: pwsh+ env:+ ENFORCE: ${{ github.event.inputs.enforce || 'true' }}+ run: |+ $ErrorActionPreference = 'Continue'+ $since = [datetime]::Parse($env:AUDIT_START).ToUniversalTime()++ # Scope to the extracted runtime.+ $dir = $env:RUNTIME_DIR+ if (-not $dir) {+ # The exercise step sets RUNTIME_DIR once the bundle is extracted and llama-server.exe is found.+ Write-Host '::error::the shipped runtime was never extracted, so there is no verdict to give; see the exercise step'+ "## App Control audit (signature-only)`n`nNo verdict: the shipped runtime was never loaded under the policy.`n" |+ Add-Content -Path $env:GITHUB_STEP_SUMMARY+ exit 1+ }+ $tail = if ($dir) {+ [Management.Automation.WildcardPattern]::Escape(+ ($dir -replace '^[A-Za-z]:', '').TrimEnd('\')) + '\'+ } else { $null }++ # Polled on the same bounded interval as the positive control, and for the same reason+ $policyBare = "$env:SAC_POLICY_ID".Trim('{', '}').ToLowerInvariant()+ $fromPolicy = {+ param($e)+ $named = $false+ $otherId = $false+ try {+ foreach ($node in ([xml] $e.ToXml()).Event.EventData.Data) {+ $v = [string] $node.'#text'+ if (-not $v) { continue }+ if ($policyBare -and $v.ToLowerInvariant().Contains($policyBare)) { return $true }+ if ($node.Name -like 'PolicyName*') {+ if ($v -like '*AuditNoISG*') { $named = $true }+ } elseif ($node.Name -like 'Policy*' -and $v -match '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}') {+ $otherId = $true+ }+ }+ } catch { }+ # The name is a fallback for events without a policy ID; an ID naming another policy wins.+ return ($named -and -not $otherId)+ }+ $events = @()+ $ours = @()+ $seen = -1+ foreach ($attempt in 1..10) {+ $events = @()+ try {+ $events = @(Get-WinEvent -FilterHashtable @{+ LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; Id = 3076; StartTime = $since+ } -ErrorAction Stop)+ } catch {+ # Only "nothing matched" is an empty window.+ if ($_.FullyQualifiedErrorId -notlike 'NoMatchingEventsFound*') {+ Write-Host "::error::could not read the CodeIntegrity channel, so this verdict has no evidence behind it: $_"+ exit 1+ }+ }+ # The evaluated file, not the whole message+ $ours = @($events | Where-Object {+ $subject = $_.Message+ try {+ foreach ($node in ([xml] $_.ToXml()).Event.EventData.Data) {+ if ($node.Name -eq 'File Name' -and $node.'#text') { $subject = [string] $node.'#text'; break }+ if ($node.Name -eq 'FileNameBuffer' -and $node.'#text') { $subject = [string] $node.'#text' }+ }+ } catch { }+ $tail -and $subject -like "*$tail*" -and (& $fromPolicy $_)+ })+ # Settled: events for later loads can land after the first one.+ if ($ours.Count -gt 0 -and $ours.Count -eq $seen) { break }+ $seen = $ours.Count+ if ($attempt -lt 10) { Start-Sleep -Seconds 3 }+ }++ Write-Host "3076 events in window: $($events.Count); naming the shipped runtime: $($ours.Count)"+ $rows = foreach ($e in $ours) {+ $file = if ($e.Message -match '(?m)^\s*File Name:\s*(.+)$') { $Matches[1].Trim() } else { '(unparsed)' }+ [pscustomobject]@{ Time = $e.TimeCreated; File = $file }+ }+ if ($rows) { $rows | Format-Table -AutoSize | Out-String | Write-Host }++ # A process-creation error throws before its exit code can be recorded.+ if ($ours.Count -eq 0 -and $env:EXERCISE_COMPLETED -ne 'true') {+ Write-Host '::error::the runtime exercise did not finish; no verdict'+ "## App Control audit (signature-only)`n`nNo verdict: the runtime exercise did not finish.`n" |+ Add-Content -Path $env:GITHUB_STEP_SUMMARY+ exit 1+ }+ # An allow needs a load that completed. --help may exit 1; a negative code is the loader's NTSTATUS.+ if ($ours.Count -eq 0 -and $env:QUANTIZE_EXIT -and [int]$env:QUANTIZE_EXIT -lt 0) {+ Write-Host "::error::llama-quantize failed to load (exit $env:QUANTIZE_EXIT) and no 3076 names the shipped runtime; no verdict"+ "## App Control audit (signature-only)`n`nNo verdict: llama-quantize failed to load (exit $env:QUANTIZE_EXIT).`n" |+ Add-Content -Path $env:GITHUB_STEP_SUMMARY+ exit 1+ }+ if ($ours.Count -eq 0 -and $env:EXERCISE_EXIT -ne '0') {+ Write-Host "::error::llama-server --version exited '$env:EXERCISE_EXIT' and no 3076 names the shipped runtime, so the load may never have happened; no verdict"+ "## App Control audit (signature-only)`n`nNo verdict: llama-server --version exited '$env:EXERCISE_EXIT', so the runtime was not shown to load under the policy.`n" |+ Add-Content -Path $env:GITHUB_STEP_SUMMARY+ exit 1+ }++ $summary = "## App Control audit (signature-only)`n`n" ++ "Policy: SmartAppControlAuditNoISG (signatures only, no cloud reputation)`n`n" ++ "3076 events naming the shipped runtime: **$($ours.Count)**`n"+ $summary | Add-Content -Path $env:GITHUB_STEP_SUMMARY++ if ($ours.Count -eq 0) {+ Write-Host 'No binary in the shipped runtime would be refused on signature grounds.'+ exit 0+ }+ if ($env:ENFORCE -eq 'true') {+ Write-Host "::error::$($ours.Count) file(s) in the shipped runtime would be blocked by the signature-only policy"+ exit 1+ }+ Write-Host "::warning::$($ours.Count) file(s) in the shipped runtime would be blocked by the signature-only policy"++ - name: Export the CodeIntegrity events+ if: always()+ shell: pwsh+ run: |+ $ErrorActionPreference = 'Continue'+ # The records the artifact is named for.+ $since = if ($env:AUDIT_START) {+ [datetime]::Parse($env:AUDIT_START).ToUniversalTime()+ } else { (Get-Date).AddHours(-2).ToUniversalTime() }+ $events = @()+ try {+ $events = @(Get-WinEvent -FilterHashtable @{+ LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; StartTime = $since+ } -ErrorAction Stop)+ } catch {+ if ($_.FullyQualifiedErrorId -notlike 'NoMatchingEventsFound*') {+ $_.ToString() | Set-Content -LiteralPath code-integrity-events-error.txt -Encoding UTF8+ }+ }+ $shaped = @($events | ForEach-Object {+ [pscustomobject]@{+ TimeCreated = $_.TimeCreated.ToString('o')+ Id = $_.Id+ ActivityID = $_.ActivityId+ Message = $_.Message+ }+ })+ ConvertTo-Json -InputObject $shaped -Depth 4 |+ Set-Content -LiteralPath code-integrity-events.json -Encoding UTF8+ & wevtutil.exe epl 'Microsoft-Windows-CodeIntegrity/Operational' CodeIntegrity-Operational.evtx /ow:true+ Write-Host "exported $($shaped.Count) CodeIntegrity record(s)"++ - name: Remove the policy+ if: always()+ shell: pwsh+ run: |+ $ErrorActionPreference = 'Continue'+ # Hosted runners are disposable, but a self-hosted runner picking this workflow up would otherwise keep the policy for every later job.+ $id = $env:SAC_POLICY_ID+ if (-not $id) {+ $id = (@((& CiTool.exe -lp -json 2>$null | ConvertFrom-Json).Policies |+ Where-Object { $_.FriendlyName -like '*AuditNoISG*' }) | Select-Object -First 1).PolicyID+ }+ if ($id) {+ & CiTool.exe --remove-policy $id 2>&1 | Out-String | Write-Host+ $removeExit = $LASTEXITCODE+ & CiTool.exe --refresh 2>&1 | Out-String | Write-Host+ $refreshExit = $LASTEXITCODE+ $raw = & CiTool.exe -lp -json 2>$null+ $listExit = $LASTEXITCODE+ $listing = $null+ try { $listing = $raw | Out-String | ConvertFrom-Json -ErrorAction Stop } catch { }+ if ($removeExit -ne 0) {+ Write-Host "::error::CiTool --remove-policy $id exited $removeExit, so the audit policy was not removed"+ exit 1+ }+ $bare = "$id".Trim('{', '}').ToLowerInvariant()+ $still = @($listing.Policies |+ Where-Object { "$($_.PolicyID)".Trim('{', '}').ToLowerInvariant() -eq $bare -and $_.IsEnforced })+ if ($refreshExit -ne 0 -or $listExit -ne 0 -or $null -eq $listing -or $null -eq $listing.PSObject.Properties['Policies']) {+ Write-Host "::warning::the audit policy $id was removed but its removal could not be verified (refresh exited $refreshExit, policy listing exited $listExit or was unreadable); it may stay active until this machine reboots"+ } elseif ($still.Count -gt 0) {+ Write-Host "::warning::the audit policy $id was removed but is still listed as enforced after refresh; it stays active until this machine reboots"+ } else {+ Write-Host "audit policy $id removed and no longer active"+ }+ } else {+ Write-Host 'no audit policy to remove'+ }+ & CiTool.exe -lp 2>&1 | Select-String -Pattern 'Friendly Name' | Write-Host+ exit 0++ - name: Upload code integrity events+ if: always()+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: code-integrity-events+ path: |+ code-integrity-events.json+ code-integrity-events-error.txt+ CodeIntegrity-Operational.evtx+ unsigned-control.exe+ if-no-files-found: ignorediff --git a/.github/workflows/workflow-trigger-lint.yml b/.github/workflows/workflow-trigger-lint.ymlindex c88a80e8a3f..0d5c9bcf178 100644--- a/.github/workflows/workflow-trigger-lint.yml+++ b/.github/workflows/workflow-trigger-lint.yml@@ -177,6 +177,7 @@ jobs:tests/studio/test_uv_cache_discipline.py \tests/studio/test_version_compat_bundle.py \tests/studio/test_windows_small_checks_stay_on_their_image.py \+ tests/studio/test_windows_sac_probe.py \tests/studio/test_windows_ui_lanes_are_isolated.py \tests/studio/test_workflow_guards_run_unfiltered.py \tests/studio/test_wsl_shortcut_script_is_valid_powershell.py \diff --git a/scripts/windows_sac_probe/README.md b/scripts/windows_sac_probe/README.mdnew file mode 100644index 00000000000..6e308f7aca7--- /dev/null+++ b/scripts/windows_sac_probe/README.md@@ -0,0 +1,380 @@+# Windows Smart App Control probe++Collects evidence about Windows code integrity blocking the Unsloth Studio+llama.cpp runtime, on a real machine, in a form that can be attached to an issue+or a pull request.++## What we are trying to settle++**Start with an AMD machine if you have one.** Every Smart App Control report so+far has been AMD, not NVIDIA: unslothai/unsloth#6588 (unsigned ROCm libraries),+unslothai/unsloth#6648 (`rocfft.dll`, with the verdict changing on a byte+identical file), and the report that prompted this. The ROCm bundle also has by+far the largest unsigned surface, 75 PE files against 47 for CUDA, because it+carries AMD's own TheRock runtime DLLs (`amdhip64_*.dll`, `rocblas.dll`,+`hipblas.dll`, `amd_comgr.dll`, `origami.dll` and more) which ship unsigned.++Users report Studio installing and launching, then failing to load a model, with+the failure clearing when Smart App Control is turned off and returning after a+reboot. The dialog is:++```+llama-server.exe - Bad Image+C:\Users\...\.unsloth\llama.cpp\build\bin\Release\llama-common.dll is either not+designed to run on Windows or it contains an error. Error status 0xc0e90002.+```++`0xc0e90002` is a code integrity refusal, not a corrupt file. On the affected+releases every PE we shipped in the Windows bundles was unsigned (47 of 47 in the+CUDA bundle, 51 of 52 in the CPU bundle, the one exception being Microsoft's own+OpenMP runtime), and VirusTotal had never seen any of them, so they carried no+cloud reputation either. Smart App Control decides per file, on signature first+and reputation second.++**The current release is signed**: `b10830-mix-d5c17a0` is 992 of 992 across all+seventeen Windows bundles, which is why `.github/workflows/windows-llama-signature-audit.yml`+now fails on an unsigned PE rather than warning. So a probe run against a current+bundle measures the signed baseline, not the unsigned surface above; use+`UNSLOTH_LLAMA_RELEASE_TAG` (see "The matrix") to pin an affected release when+reproducing the original report. The reputation half is unchanged either way: a+freshly published hash carries no ISG reputation whether or not it is signed.++So far this rests on one screenshot. This probe is how it becomes a measurement.++**The llama.cpp runtime is not the whole surface, and may not even be the+likeliest one.** The first enforced block this probe caught on a real+enforcing machine was not in llama.cpp at all. It was+`sentencepiece\_sentencepiece.cp313-win_amd64.pyd`, loaded by a validly signed+`python.exe`, refused with event 3077, and it failed **silently**: no+`ImportError`, no "DLL load failed", inference carried on afterwards. On that+same machine the entirely unsigned llama.cpp bundle launched three times and was+never blocked.++Measured on that install:++| scope | PE files | unsigned |+| --- | ---: | ---: |+| `~/.unsloth/llama.cpp` | 27 | 27 |+| the `unsloth_studio` venv | 673 | **657** |++657 unsigned native modules across about 70 packages, roughly 1.1 GB, mostly+`.pyd`: `scipy`, `sklearn`, `numpy`, `av`, `pandas`, `pyarrow`, and `torch` and+`triton` by size. Only 16 files in the venv are validly signed and none of them+are ours. `sentencepiece` is a small contributor; it was drawn from 657+candidates because it happened to sit on a startup import path.++So the probe inventories **both** trees. An inventory that stopped at the+runtime directory would have missed the only enforcement evidence on that+machine.++## What this does not do++It never turns Smart App Control on or off. Switching it through Settings is a+one-way operation that cannot be undone without reinstalling Windows, and the+registry route needs BitLocker suspended and a boot into recovery. The script+only adds and removes an **audit** App Control policy, which is reversible, and+reports whichever mode it finds the machine in.++## Requirements++- Windows 11, elevated PowerShell (right click Windows Terminal, Run as administrator)+- Any Python 3 on `PATH`. The scenario uses only the standard library: no pip install, no browser+- Optional but strongly preferred: `SmartAppControlAuditNoISG.bin` from <https://aka.ms/sacauditpolicies>++The NoISG policy is the useful one. It checks signatures and skips the cloud+reputation lookup, which means it works **even with Smart App Control off**, so+any machine can produce evidence. It logs event 3076 for every file it would+have refused. That is exactly the half of the verdict that signing changes.++## Getting it onto the machine++```powershell+git clone --depth 1 https://github.com/unslothai/unsloth C:\unsloth-probe+cd C:\unsloth-probe\scripts\windows_sac_probe+```++These scripts are not Authenticode signed. On Windows 11 Home the effective+execution policy is often `Restricted`, which refuses **any** script, cloned or+not, so a clean `git clone` still needs this. Set it for the current process+only, which touches no machine-wide state and is gone when the window closes:++```powershell+Get-ExecutionPolicy -List # see what this machine actually has+Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force+```++If you downloaded the files individually rather than cloning, they also carry+Mark-of-the-Web:++```powershell+Get-ChildItem . -Recurse | Unblock-File+```++Do not change the machine-wide execution policy. It is part of what we are+measuring.++## Running it++Four stages, in order. Use a distinct `-Label` per cell of the matrix below so+runs do not overwrite each other.++```powershell+cd scripts\windows_sac_probe++.\sac-probe.ps1 -Stage prepare -Label custom-sac-on -AuditPolicy C:\path\to\SmartAppControlAuditNoISG.bin+.\sac-probe.ps1 -Stage run -Label custom-sac-on+.\sac-probe.ps1 -Stage collect -Label custom-sac-on+.\sac-probe.ps1 -Stage revert -Label custom-sac-on+```++`run` needs the Studio password, always:++```powershell+$env:UNSLOTH_STUDIO_PASSWORD = 'your studio password'+.\sac-probe.ps1 -Stage run -Label custom-sac-on+```++On a Studio that has already been opened, that is the password you sign in+with. On one that has never been opened, the bootstrap credential is still on+disk and the scenario rotates it to the value you give here; the rotation is+permanent and `revert` does not undo it, which is why there is no default. The+password is never written to the evidence.++The probe reads that variable and then **removes it from its own environment**+before launching anything, re-exporting it as `SAC_PROBE_STUDIO_PASSWORD` for+the scenario process alone and clearing that again once the scenario exits.+It is deliberately not passed as `--password`: an argument is readable from the+process table by anything that can see it and is captured verbatim by+process-creation auditing and EDR telemetry, for the whole length of a run that+can take minutes. `unsloth_cli` reads `UNSLOTH_STUDIO_PASSWORD` itself and+treats it as *set the initial password*, so a Studio that already has one+refuses to start with++```+Error: an Unsloth admin password is already set; --password only sets the+initial password.+```++which is exactly the case the variable is needed for. One name, two+incompatible consumers.++If Studio runs from a custom home (`UNSLOTH_STUDIO_HOME`), a portable root (`UNSLOTH_HOME`) or a custom runtime+(`UNSLOTH_LLAMA_CPP_PATH`), set the same variables in the shell that runs the+probe, so it inventories the runtime Studio actually loads and reads the logs+Studio actually writes.++`prepare` runs `Update-MpSignature`; add `-SkipUpdates` to skip it. It does not+upgrade packages unless you pass `-UpgradePackages`: `winget upgrade --all` changes+every managed package on the machine and `revert` cannot put them back, so it is+not part of the reversible run. The same goes for Defender's sample submission:+`prepare` raises real-time protection, MAPS and the cloud block level, all of+which `revert` restores, but sets `SubmitSamplesConsent` only with `-SendSamples`,+since a sample uploaded during the probe cannot be recalled.++`prepare` restarts a Studio that is already running. Studio's startup is where the+venv's native modules load, and those loads have to happen inside the event window+and under the audit policy to be measured.++With `-AuditPolicy`, `prepare` also runs a **positive control**: it builds a small+unsigned executable, runs it, and requires the policy to raise a 3076 (or a 3077 on+a machine where Smart App Control is genuinely enforcing) naming it. Without that,+a cell with no events is unfalsifiable, since "nothing would be blocked" and "the+policy loaded but evaluates nothing" look identical. `prepare` refuses to continue+when the control does not fire. Building the control needs Windows PowerShell 5.1;+PowerShell 7 dropped assembly emission from `Add-Type`, so on pwsh the control is+skipped, the cell is recorded as unverified, and `collect` says so rather than+reading an empty window as an allow. The control binary is built outside the run+directory and deleted immediately, so it never reaches the evidence zip.++Without `-AuditPolicy`, on a machine where Smart App Control reads as enforcing,+`prepare` runs the same control for the same reason: there the 3077 refusing it+is the only thing that shows enforcement is live. The registry mode is an+intent, not an observation, and Windows settles it on the boot path, so `run`+asks again whenever the machine booted since the baseline was captured, and+`collect` refuses the allow line unless the control fired on the boot that+measured. A control `run` has to repeat lands inside the window, so its own+3076 or 3077 shows up in the export naming `unsigned-control.exe`; it is scoped+`other`, is not part of any Unsloth count, and is the proof, not the finding.++Running `prepare` again with the same label (after a failure, or to add+`-AuditPolicy`) keeps the baseline the first pass captured, so `revert` still+restores the machine as it was before the first pass. Once `revert` has+finished, that baseline is spent: a later `prepare` on the same label captures a+new one, so a `revert` after it restores the machine as it is now rather than as+it was before a run that has already been undone. `collect` refuses a label that+was never prepared rather than exporting unrelated events.++`collect` refuses a label whose `revert` already completed: collect first, then revert.++`prepare` refuses a new label while another label has not been reverted, including+one kept under a different `-WorkDir` (tracked under+`%ProgramData%\unsloth-sac-probe\pending`): revert that label first. A `prepare` that fails after applying the audit policy removes+it again. If `revert` finds the policy still active after removing it (Windows 11+before 24H2 needs a restart for that), or `CiTool -lp` cannot list the policies to+confirm it is gone, it leaves the baseline pending: restart (or fix CiTool) and+run `revert` again.++### On a machine with no Unsloth on it++Nothing extra to do. `prepare` detects that Studio is absent and installs it with+the documented command, then starts it and waits for it to answer:++```+=== Unsloth Studio ===+Studio is not installed on this machine.++=== Install Unsloth Studio ===+irm https://unsloth.ai/install.ps1 | iex+...+managed interpreter: C:\Users\you\.unsloth\studio\unsloth_studio\Scripts\python.exe+starting Studio on port 8888+Studio answering on port 8888 after 65s+```++The install happens **after** the event log window opens, on purpose: installing+is what downloads the llama.cpp bundle, and first launch is what loads it, so+both are inside the window `collect` exports. On an affected machine the block+may well appear during `prepare` rather than during `run`.++Studio is started through the managed interpreter, not the generated+`unsloth.exe`. Windows materialises that console script as an unsigned PE and+Application Control denies it (unslothai/unsloth#8490) while the signed+interpreter beside it keeps running, so on exactly the machines this probe+targets, launching the normal way would fail for a reason unrelated to what is+being measured. The supported entry point is documented in+`unsloth_cli/__main__.py`:++```powershell+python -X utf8 -I -m unsloth_cli studio -p 8888+```++Pass `-SkipInstall` to refuse to install, or `-Port` if 8888 is taken. `run`+re-checks and restarts an installed Studio too, since a machine may have been+rebooted between stages, which is itself part of the reported behaviour; it+never installs one, so a `prepare -SkipInstall` stays in force. `run` also+evicts the model before the measured load, because a model already resident+would make the load a no-op that loads no PE inside the window.++### What each stage does++| stage | what it changes | how it is undone |+| --- | --- | --- |+| `prepare` | records a baseline; updates packages and Defender signatures; turns Defender real-time, MAPS advanced, cloud block level high and PUA on; raises the CodeIntegrity log to 64 MB; applies the audit policy if given (a pre-existing policy with the same GUID is saved first); installs Unsloth Studio if it is missing, then starts it | `revert` (Studio is left installed) |+| `run` | nothing on the machine beyond restarting Studio if it stopped; inventories signatures and drives Studio (rotates a never-used bootstrap password to yours, see above) | n/a |+| `collect` | nothing; exports events and zips the evidence | n/a |+| `revert` | removes the audit policy (or restores the pre-existing one), restores the CodeIntegrity log settings and the Defender settings from the baseline, and regrants the invoking user access to the Studio trees (below); the EFI partition is never left mounted | n/a |++Because every stage is elevated, a Studio that `prepare` installs is installed+**as administrator**, and the trees its installer creates (`llama.cpp`,+`whisper.cpp`, `node`, `.cache`) come out owned by `BUILTIN\Administrators`.+The user's own non-elevated Studio can then fail to read its own runtime; on a+machine where `prepare` did the install, `llama.cpp`, `whisper.cpp` and `node`+all refused `Get-Acl` to the owning user afterwards. This is a side effect of+running elevated at all, not something `prepare` sets, so there is no baseline+value for it. `revert` regrants access. If you never run `revert`:++```powershell+icacls $env:USERPROFILE\.unsloth /grant "${env:USERNAME}:(OI)(CI)F" /T+```++The braces are load bearing: `"$env:USERNAME:(OI)(CI)F"` parses the trailing+colon as part of the variable name, so icacls receives `(OI)(CI)F` as a+separate argument and fails with `Invalid parameter "(OI)(CI)F"`.++`revert` reads `baseline.json` from the same `-Label` directory, so use the label+you prepared with.++## The matrix++One run is not a result. Run all four cells, ideally across the machines+available:++| | Smart App Control enforcing | Smart App Control off |+| --- | --- | --- |+| our build (`unslothai/llama.cpp`) | C-on | C-off |+| upstream build (`ggml-org/llama.cpp`) | U-on | U-off |++The upstream row separates "our additive-merge build is the problem" from "the+whole unsigned llama.cpp ecosystem is the problem". Upstream is also 0 of N+signed, and so is `lemonade-sdk/llamacpp-rocm` (72 PE files, 0 signed), so U-on+is what tells us whether download prevalence alone carries a build through.++To pin a specific runtime for a cell, the runtime has to be **installed** with+that pin **before `prepare`**.+`UNSLOTH_LLAMA_RELEASE_TAG` is read by the installer only, and `run`+never installs. The order is not a formality:+`prepare` opens the event window and then installs or restarts Studio, so a+runtime swapped in afterwards leaves loads from *both* releases inside one+window. `collect` scopes those events by directory, and the installer overwrites+the same managed `llama.cpp` directory, while the signature inventory hashes only+the files that survive the swap. A 3076 or 3077 raised by the release you+replaced would then be read as the pinned release's, which is exactly the+comparison the matrix exists to make.++```powershell+$env:UNSLOTH_LLAMA_RELEASE_TAG = 'b10715-mix-86bd2d3' # an older, more established build+# re-run the Studio installer (studio\setup.ps1) so it fetches that release, then:+.\sac-probe.ps1 -Stage prepare -Label custom-b10715-sac-on+.\sac-probe.ps1 -Stage run -Label custom-b10715-sac-on+```++If you already ran `prepare` for the cell, run `prepare` again once the pinned+release is installed. A second `prepare` on the same label reopens the window and+deletes the previous one's evidence, and it keeps the baseline the first pass+captured, so `revert` still restores the machine as it was before the first pass.++For the upstream row, point Studio at an upstream build through its custom+llama.cpp folder setting (or `UNSLOTH_LLAMA_CPP_PATH`) and restart it, again+before `prepare` and for the same reason. Either way, check+`signature-inventory.json` afterwards: the SHA-256 of each file is what says+which build a cell actually exercised, not the label.++## Reading the output++`collect` writes a zip to `%USERPROFILE%\unsloth-sac-probe\`. Inside:++- `runtime-selection.json`: the llama-server Studio resolved, in its own order (`LLAMA_SERVER_PATH`, `UNSLOTH_LLAMA_CPP_PATH`, the folder selected in Studio's settings, the managed default). The inventory is of that build.+- `signature-inventory.csv` and `.json`: every PE under that runtime with its Authenticode `Status`, `StatusMessage`, signer subject, thumbprint and SHA-256. Record `Status`, not merely whether a certificate is present: an unsigned file and one whose chain did not build both report `UnknownError`, and `StatusMessage` is what separates them+- `venv-signature-inventory.csv` and `.json`: the same for every PE in the `unsloth_studio` venv, which is around 25 times as many files and is where the only enforced block so far actually landed. `run` also prints the ten worst packages by unsigned count+- `scenario-status.json`: whether the Studio scenario ran and its exit code. Read this **before** reading the event count. A scenario that never authenticated or never loaded a model produces an empty window, and an empty window looks identical to a clean allow. `collect` warns loudly when this happened, and refuses to imply a result+- `code-integrity-events.json` and `.txt`: events 3033, 3076, 3077, 3089 and 3090 to 3099 in the run window, each tagged with a `Scope` of `llama.cpp`, `venv` or `other`. The channel is machine-wide, so unrelated software lands in the same window: one run picked up seven 3076 events from a Git Bash session (`msys-2.0.dll`, `head.exe`, `tail.exe`). `collect` counts only the Unsloth scopes in its headline and reports the rest separately; nothing is dropped from the export+- `CodeIntegrity-Operational.evtx`: the raw log, bounded to the same window as the JSON+- `defender-query-error.txt`: present only when the Defender detection query itself failed. If you see this file, the absence of `defender-detections.json` is not a clean window, it is an uncollected one+- `scenario-results.json`: every HTTP call with its duration, plus the status-poll summary+- `studio-logs\`: Studio's own logs, the redirected Studio stdout from a start the probe did, and the scenario's console output, all passed through Studio's log redactor. The raw copies stay in `raw-logs\` on the machine and are not archived+- `studio-logs\`: Studio's own backend and llama-server logs+- `baseline.json`, `sac-state-after.json`: what the machine looked like before and after++**Grade the events correctly.** They are not interchangeable:++- **3077** is an enforced block. This is proof.+- **3076** is audit only: "would have been blocked". Strong, but not enforcement.+- **3089** carries the signature detail for a block. Correlate it to a 3077 by `ActivityID`, never by timestamp alone.+- **3090 to 3092** are allow and origin context, and prove nothing on their own.+- Events scoped `other` are somebody else's binaries and say nothing about Studio. Do not quote a raw total off the evtx; read the scoped counts.++Also keep "unsigned" and "low reputation" apart. Smart App Control may allow a+validly signed file whose reputation is inconclusive, which is the behaviour the+signing fix depends on. Search the events for **every** PE path in the bundle:+the file that gets blocked can be a dependent `ggml`, HIP, OpenMP or VC runtime+DLL rather than `llama-server.exe` itself.++Do not enable Windows test-signing mode. It changes enforcement conditions and+invalidates the run.++## The status timing half++`scenario-results.json` also answers a separate question. Field diagnostics show+`/api/inference/status` taking over 80 seconds, which starves `/api/health` and+gets the backend killed by the desktop watchdog at its 3 strike, roughly 75+second budget, surfacing as "Server stopped unexpectedly". Those stalls were+observed with **no model loaded**, so the cause is not yet established. The+scenario polls status at the same 5 second cadence the frontend uses and reports+`max_ms`, `over_10s` and `over_75s`, which is the measurement that has been+missing.++## What to send back++Attach the zip. It contains your Windows user name inside file paths. Redacting+the user name is fine; keep the file names and the rest of each path, because+which file was blocked is the entire point.diff --git a/scripts/windows_sac_probe/redact_logs.py b/scripts/windows_sac_probe/redact_logs.pynew file mode 100644index 00000000000..e2b2bb4787f--- /dev/null+++ b/scripts/windows_sac_probe/redact_logs.py@@ -0,0 +1,86 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+"""Copy Studio's logs into the evidence with the backend's own redactor applied."""++from __future__ import annotations++import argparse+import sys+from pathlib import Path+++def backend_dir(explicit: str | None) -> Path:+ if explicit:+ return Path(explicit)+ import studio # the installed package, beside the interpreter this runs under+ return Path(studio.__file__).resolve().parent / "backend"+++def load_redactor(backend: Path):+ sys.path.insert(0, str(backend))+ from utils.log_redaction import redact_log_text+ return redact_log_text+++FAMILY_CAP = 10+++def family_of(log: Path) -> str:+ return log.parent.name + "/" + log.name.split("-", 1)[0].lower()+++def select(source: Path, since: float | None) -> list[Path]:+ logs = sorted((p for p in source.rglob("*") if p.is_file()), key = lambda p: p.stat().st_mtime)+ if since is not None:+ logs = [p for p in logs if p.stat().st_mtime >= since]+ kept: dict[str, list[Path]] = {}+ for log in logs:+ kept.setdefault(family_of(log), []).append(log)+ out: list[Path] = []+ for family in sorted(kept):+ out.extend(kept[family][-FAMILY_CAP:])+ return sorted(out)+++def copy_redacted(+ source: Path,+ destination: Path,+ redact,+ since: float | None = None,+) -> list[str]:+ destination.mkdir(parents = True, exist_ok = True)+ written: list[str] = []+ for log in select(source, since):+ text = log.read_text(encoding = "utf-8", errors = "replace")+ target = destination / log.relative_to(source)+ target.parent.mkdir(parents = True, exist_ok = True)+ target.write_text(redact(text), encoding = "utf-8")+ written.append(str(log.relative_to(source)))+ return written+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("source")+ ap.add_argument("destination")+ ap.add_argument(+ "--backend", default = None, help = "studio/backend directory (default: the installed one)"+ )+ ap.add_argument(+ "--since",+ default = None,+ help = "ISO 8601 start of the probe window; older logs are left out of the evidence",+ )+ args = ap.parse_args()+ since = None+ if args.since:+ from datetime import datetime+ since = datetime.fromisoformat(args.since).timestamp()+ redact = load_redactor(backend_dir(args.backend))+ for name in copy_redacted(Path(args.source), Path(args.destination), redact, since):+ print(f" {name}")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/windows_sac_probe/sac-probe.ps1 b/scripts/windows_sac_probe/sac-probe.ps1new file mode 100644index 00000000000..65fcd2518b6--- /dev/null+++ b/scripts/windows_sac_probe/sac-probe.ps1@@ -0,0 +1,1789 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+<#+.SYNOPSIS+ Collect evidence about Windows code integrity blocking the Unsloth Studio+ llama.cpp runtime.++.DESCRIPTION+ Stages prepare, run, collect, revert. Never toggles Smart App Control (one-way);+ only adds and removes a reversible audit policy. 3077 = enforced block,+ 3076 = audit only, 3089 matched to 3077 by ActivityID, never by timestamp.++.EXAMPLE+ .\sac-probe.ps1 -Stage prepare+ .\sac-probe.ps1 -Stage run+ .\sac-probe.ps1 -Stage collect+ .\sac-probe.ps1 -Stage revert+#>++[CmdletBinding()]+param(+ [Parameter(Mandatory = $true)]+ [ValidateSet('prepare', 'run', 'collect', 'revert')]+ [string] $Stage,++ # Where evidence and the baseline are kept. Must survive between stages.+ [string] $WorkDir = "$env:USERPROFILE\unsloth-sac-probe",++ # Path to SmartAppControlAuditNoISG.bin from https://aka.ms/sacauditpolicies.+ [string] $AuditPolicy,++ # Label for this run, so the four matrix cells do not overwrite each other.+ [string] $Label = 'run',++ [string] $Model = 'unsloth/Qwen3.5-2B-MTP-GGUF:UD-Q4_K_XL',++ # prepare only: skip the Defender signature update, which is slow.+ [switch] $SkipUpdates,++ [switch] $UpgradePackages,++ # run only: skip the Studio scenario and just do the signature inventory.+ [switch] $SkipStudio,++ # prepare only: do not install Unsloth Studio when it is missing.+ [switch] $SkipInstall,++ [switch] $SendSamples,++ [int] $Port = 8888+)++# A relative -WorkDir resolves against this shell's location once, so every path below is absolute.+$WorkDir = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($WorkDir)++$ErrorActionPreference = 'Stop'++$NOISG_GUID = '{5283AC0F-FFF1-49AE-ADA1-8A933130CAD6}'+$NOISG_DEST = "S:\efi\microsoft\boot\cipolicies\active\$NOISG_GUID.cip"+$CI_LOG = 'Microsoft-Windows-CodeIntegrity/Operational'++# A configured path the way Studio normalises one (utils/paths/storage_roots.studio_root)+function Resolve-ConfiguredPath([string] $value) {+ if (-not $value) { return $null }+ $trimmed = $value.Trim()+ if (-not $trimmed) { return $null }+ $userHome = if ($env:USERPROFILE) { $env:USERPROFILE } else { $HOME }+ if ($trimmed -eq '~') { $trimmed = $userHome }+ elseif ($trimmed.StartsWith('~\') -or $trimmed.StartsWith('~/')) {+ $trimmed = Join-Path $userHome $trimmed.Substring(2)+ }+ try { return [IO.Path]::GetFullPath($trimmed) } catch { return $trimmed }+}++# The configured Studio home, in Studio's precedence+function Get-StudioHomeOverride {+ $override = Resolve-ConfiguredPath $env:UNSLOTH_STUDIO_HOME+ if (-not $override) { $override = Resolve-ConfiguredPath $env:STUDIO_HOME }+ return $override+}++# UNSLOTH_HOME, the portable master root: studio\ is its child and llama.cpp\ its sibling+function Get-UnslothMasterRoot {+ return (Resolve-ConfiguredPath $env:UNSLOTH_HOME)+}++function Get-StudioHome {+ $override = Get-StudioHomeOverride+ if ($override) { return $override }+ $master = Get-UnslothMasterRoot+ if ($master) { return (Join-Path $master 'studio') }+ return (Join-Path $env:USERPROFILE '.unsloth\studio')+}++# The runtime Studio actually loads, in Studio's own order (llama_cpp.py _find_llama_server_binary)+function Get-LlamaDir {+ $binary = Resolve-ConfiguredPath $env:LLAMA_SERVER_PATH+ if ($binary) { return (Split-Path -Parent $binary) }+ $installDir = Resolve-ConfiguredPath $env:UNSLOTH_LLAMA_CPP_PATH+ if ($installDir) { return $installDir }+ # The master root outranks a studio home here, as in _resolved_studio_root_and_is_legacy+ $master = Get-UnslothMasterRoot+ if ($master) { return (Join-Path $master 'llama.cpp') }+ $override = Get-StudioHomeOverride+ if ($override) { return (Join-Path $override 'llama.cpp') }+ return (Join-Path $env:USERPROFILE '.unsloth\llama.cpp')+}+# The managed venv.+$VENV_DIR = Join-Path (Get-StudioHome) 'unsloth_studio'++function Resolve-LlamaDir([string] $dir) {+ $selection = Join-Path $dir 'runtime-selection.json'+ if (Test-Path -LiteralPath $selection) {+ $sel = Get-Content -LiteralPath $selection -Raw | ConvertFrom-Json+ if ($sel.resolved_binary) {+ Write-Host ("runtime selected by Studio ({0}): {1}" -f $sel.source, $sel.resolved_binary)+ # The selected root, not the binary's directory.+ if ($sel.path -and (Test-Path -LiteralPath $sel.path -PathType Container)) {+ return $sel.path+ }+ return (Split-Path -Parent $sel.resolved_binary)+ }+ Write-Warning "Studio reported no resolvable llama-server (source $($sel.source), path $($sel.path)); inventorying $(Get-LlamaDir)"+ } elseif (-not $env:LLAMA_SERVER_PATH -and -not $env:UNSLOTH_LLAMA_CPP_PATH) {+ Write-Warning 'no runtime-selection.json from the scenario: a folder selected in Studio settings cannot be seen from here, so the managed default is inventoried'+ }+ return (Get-LlamaDir)+}+$PE_EXT = @('.exe', '.dll', '.pyd', '.sys', '.ocx', '.cpl', '.scr')++# unsloth_cli reads UNSLOTH_STUDIO_PASSWORD itself and treats it as set-the-initial-password, so launching with it set hard-errors on any Studio that already has one+$STUDIO_PASSWORD = $env:UNSLOTH_STUDIO_PASSWORD+Remove-Item Env:\UNSLOTH_STUDIO_PASSWORD -ErrorAction SilentlyContinue+$CI_EVENT_IDS = @(3033, 3076, 3077, 3089, 3090, 3091, 3092, 3099)++# Native commands do not throw under $ErrorActionPreference = 'Stop' in Windows PowerShell+function Invoke-Native([string] $Exe, [string[]] $Arguments) {+ & $Exe @Arguments+ if ($LASTEXITCODE -ne 0) {+ throw "$Exe $($Arguments -join ' ') exited $LASTEXITCODE"+ }+}++# The audit policy lives in the EFI system partition.+$EFI_OWNED_MARKER = Join-Path $WorkDir '.efi-mounted-by-probe'++function Mount-Efi {+ if (Test-Path -LiteralPath 'S:\') {+ if (-not (Test-Path -LiteralPath 'S:\EFI\Microsoft\Boot')) {+ throw 'S: is mapped to a volume that is not the EFI system partition; free the drive letter and run again'+ }+ if (Test-Path -LiteralPath $EFI_OWNED_MARKER) {+ Write-Warning 'S: is the EFI system partition left mounted by an earlier stage of this probe; this stage will unmount it'+ return $true+ }+ return $false+ }+ New-Item -ItemType Directory -Force -Path $WorkDir | Out-Null+ Invoke-Native 'mountvol.exe' @('S:', '/S')+ (Get-Date).ToString('o') | Set-Content -LiteralPath $EFI_OWNED_MARKER -Encoding UTF8+ return $true+}++# Set when a dismount failed, and read by prepare and revert before either reports success.+$script:EfiStillMounted = $false++function Dismount-Efi([bool] $Mounted) {+ if ($Mounted) {+ & mountvol.exe S: /D+ if ($LASTEXITCODE -ne 0) {+ $script:EfiStillMounted = $true+ Write-Warning "could not unmount S: (mountvol exited $LASTEXITCODE)"+ } else {+ Remove-Item -LiteralPath $EFI_OWNED_MARKER -Force -ErrorAction SilentlyContinue+ }+ }+}++# Retries a dismount an earlier stage could not complete.+function Clear-EfiOwnership {+ if (-not (Test-Path -LiteralPath $EFI_OWNED_MARKER)) { return }+ if (-not (Test-Path -LiteralPath 'S:\')) {+ Remove-Item -LiteralPath $EFI_OWNED_MARKER -Force -ErrorAction SilentlyContinue+ return+ }+ if (-not (Test-Path -LiteralPath 'S:\EFI\Microsoft\Boot')) {+ # Somebody else's volume took the letter after our mount went away.+ Write-Warning 'S: is no longer the EFI system partition; leaving the drive letter alone and dropping this probe''s claim on it'+ Remove-Item -LiteralPath $EFI_OWNED_MARKER -Force -ErrorAction SilentlyContinue+ return+ }+ Write-Warning 'S: was left mounted by an earlier stage of this probe; unmounting it'+ Dismount-Efi $true+}++# $null when CiTool could not list the policies. -lp also lists inactive policies, which carry IsEnforced=false.+function Test-PolicyActive([string] $Guid) {+ $bare = $Guid.Trim('{', '}').ToLowerInvariant()+ $policies = (Get-SacState).Policies+ if ($null -eq $policies) { return $null }+ foreach ($p in $policies) {+ if ((([string]$p.PolicyID) -replace '[{}]', '') -eq $bare -and [string]$p.IsEnforced -ne 'False') { return $true }+ }+ return $false+}++function Get-CiLogSettings {+ $enabled = $null+ $maxSize = $null+ try {+ $lines = & wevtutil.exe gl $CI_LOG 2>$null+ if ($LASTEXITCODE -eq 0) {+ foreach ($line in $lines) {+ if ($line -match '^\s*enabled:\s*(\S+)') { $enabled = ($Matches[1] -eq 'true') }+ if ($line -match '^\s*maxSize:\s*(\d+)') { $maxSize = [int64]$Matches[1] }+ }+ }+ } catch { }+ return [pscustomobject]@{ Enabled = $enabled; MaxSize = $maxSize }+}++# Does a preference that reads back as $actual carry the value $expected asked for? $true match, $false mismatch, $null when it could not be decided.+function Test-MpPreferenceMatch($actual, $expected, [Type] $type) {+ if ($null -eq $actual) { return $false }+ if ($expected -is [bool] -or $actual -is [bool]) { return ([bool]$actual -eq [bool]$expected) }+ if ([string]$actual -eq [string]$expected) { return $true }+ if ($type -and $type.IsEnum) {+ try {+ $want = [int]([Enum]::Parse($type, [string]$expected, $true))+ $have = [int]([Enum]::Parse($type, [string]$actual, $true))+ return ($have -eq $want)+ } catch { }+ }+ return $null+}++function Get-MpPreferenceType([string] $name) {+ try {+ $cmd = Get-Command Set-MpPreference -ErrorAction Stop+ $p = $cmd.Parameters[$name]+ if ($p) { return $p.ParameterType }+ } catch { }+ return $null+}++function Write-Section([string] $Text) {+ Write-Host ''+ Write-Host "=== $Text ===" -ForegroundColor Cyan+}++function Assert-Elevated {+ $id = [Security.Principal.WindowsIdentity]::GetCurrent()+ $principal = New-Object Security.Principal.WindowsPrincipal($id)+ if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {+ throw 'Run this from an elevated PowerShell. Right click Windows Terminal or PowerShell and pick "Run as administrator".'+ }+}++function Get-RollbackPolicyPath([string] $dir) {+ return (Join-Path (Join-Path $dir 'rollback') 'preexisting-policy.cip')+}++function Get-RunDir {+ $dir = Join-Path $WorkDir $Label+ New-Item -ItemType Directory -Force -Path $dir | Out-Null+ return $dir+}++function Get-SacState {+ # 0 off, 1 enforcement, 2 evaluation. Absent on hardware that never offered it.+ $state = $null+ try {+ $state = (Get-ItemProperty -LiteralPath 'HKLM:\SYSTEM\CurrentControlSet\Control\CI\Policy' `+ -Name 'VerifiedAndReputablePolicyState' -ErrorAction Stop).VerifiedAndReputablePolicyState+ } catch {+ $state = $null+ }+ $name = switch ($state) {+ 0 { 'off' }+ 1 { 'enforcement' }+ 2 { 'evaluation' }+ default { 'absent' }+ }+ # $null, not empty, when the listing failed or is not the expected JSON+ $policies = $null+ try {+ $raw = & CiTool.exe -lp --json 2>$null+ if ($LASTEXITCODE -eq 0 -and $raw) {+ $parsed = ($raw | Out-String | ConvertFrom-Json)+ if ($null -eq $parsed -or -not $parsed.PSObject.Properties['Policies']) { throw 'no Policies in the CiTool listing' }+ $policies = @()+ foreach ($p in $parsed.Policies) {+ $policies += [pscustomobject]@{+ FriendlyName = $p.FriendlyName+ PolicyID = $p.PolicyID+ IsEnforced = $p.IsEnforced+ }+ }+ }+ } catch {+ $policies = $null+ }+ return [pscustomobject]@{+ RegistryState = $state+ Mode = $name+ Policies = $policies+ }+}++function Get-StudioPython {+ <# The managed interpreter. Not unsloth.exe: that console script is an unsigned PE that SAC/WDAC deny (issue 8490). #>+ $legacy = Join-Path $env:USERPROFILE '.unsloth\studio'+ $roots = @((Get-StudioHome))+ if ($roots[0] -ne $legacy) { $roots += $legacy }+ foreach ($root in $roots) {+ $py = Join-Path $root 'unsloth_studio\Scripts\python.exe'+ if (Test-Path -LiteralPath $py) { return $py }+ }+ return $null+}++# The venv the RUNNING Studio uses, not the default location.+function Resolve-VenvDir([string] $dir) {+ # Recorded by run and read back by collect when $dir is given, the way the llama.cpp selection already is.+ if ($dir) {+ $recorded = Join-Path $dir 'venv-selection.txt'+ if (Test-Path -LiteralPath $recorded) {+ $recordedPath = (Get-Content -LiteralPath $recorded -Raw).Trim()+ if ($recordedPath) { return $recordedPath }+ }+ }+ $studioPython = Get-StudioPython+ if ($studioPython) { return (Split-Path -Parent (Split-Path -Parent $studioPython)) }+ return $VENV_DIR+}++function Resolve-StudioHomeFor([string] $dir) {+ # run records the home the backend was launched with.+ if ($dir) {+ $recordedHome = Join-Path $dir 'studio-home.txt'+ if (Test-Path -LiteralPath $recordedHome) {+ $homePath = "$(Get-Content -LiteralPath $recordedHome -Raw)".Trim()+ if ($homePath) { return $homePath }+ }+ }+ $venv = Resolve-VenvDir $dir+ if ($venv) {+ $parent = Split-Path -Parent $venv+ if ($parent) { return $parent }+ }+ return (Get-StudioHome)+}++function Resolve-StudioPythonFor([string] $dir) {+ $venv = Resolve-VenvDir $dir+ if ($venv) {+ $py = Join-Path $venv 'Scripts\python.exe'+ if (Test-Path -LiteralPath $py) { return $py }+ }+ return (Get-StudioPython)+}++function Test-StudioResponding([int] $port) {+ try {+ $r = Invoke-WebRequest -Uri "http://127.0.0.1:$port/api/liveness" -TimeoutSec 5 -UseBasicParsing+ if ($r.StatusCode -ne 200) { return $false }+ # Identity, not a bare status code.+ $body = $null+ try { $body = $r.Content | ConvertFrom-Json } catch { return $false }+ return ($body.service -eq 'Unsloth UI Backend')+ } catch {+ return $false+ }+}++function Get-ScopeTail([string] $root) {+ $trimmed = ($root -replace '^[A-Za-z]:', '').TrimEnd('\', '/')+ # A runtime at the root of a volume trims to nothing, and the tail would then be a lone separator, which every path in this machine-wide channel contains.+ if (-not $trimmed) {+ throw "cannot scope CodeIntegrity events to '${root}': a runtime or venv at the root of a volume leaves no path tail, so every event on this machine would be counted as an Unsloth verdict. Move it into a subdirectory, point UNSLOTH_LLAMA_CPP_PATH or LLAMA_SERVER_PATH at that, and run this label again from prepare."+ }+ # UNC names reach CodeIntegrity through \Device\Mup\server\share, with one separator before the server; the DOS spelling has two.+ if ($trimmed.StartsWith('\\')) { $trimmed = $trimmed.Substring(1) }+ return ([Management.Automation.WildcardPattern]::Escape($trimmed) + '\')+}++function Get-EventDataMap($record) {+ $map = [ordered]@{}+ try {+ $xml = [xml] $record.ToXml()+ $i = 0+ foreach ($node in $xml.Event.EventData.Data) {+ $i+++ $name = if ($node.Name) { $node.Name } else { "Data$i" }+ $map[$name] = $node.'#text'+ }+ } catch {+ }+ return $map+}++function Install-Studio {+ Write-Section 'Install Unsloth Studio'+ # The documented install command, run exactly as a user would.+ Write-Host 'irm https://unsloth.ai/install.ps1 | iex'+ $prev = $ErrorActionPreference+ $ErrorActionPreference = 'Continue'+ try {+ # Out-Host, not a bare call.+ Invoke-Expression (Invoke-RestMethod -Uri 'https://unsloth.ai/install.ps1' -TimeoutSec 120) | Out-Host+ } catch {+ Write-Warning "installer failed: $_"+ } finally {+ $ErrorActionPreference = $prev+ }+ return (Get-StudioPython)+}++function Start-Studio([string] $python, [int] $port, [string] $logPath) {+ Write-Host "starting Studio on port $port"+ # -X utf8 -I -m unsloth_cli is the supported entry point on a locked-down machine, per unsloth_cli/__main__.py.+ $cliArgs = @('-X', 'utf8', '-I', '-m', 'unsloth_cli', 'studio', '-p', "$port")+ # One record, so one probe Studio at a time.+ if (-not (Stop-ProbeStudio (Get-RunDir))) {+ throw "the Studio this probe started earlier (see probe-studio.json under $(Get-RunDir)) is still running and could not be stopped; stop it by hand and run this stage again."+ }+ $proc = Start-Process -FilePath $python -ArgumentList $cliArgs `+ -RedirectStandardOutput $logPath -RedirectStandardError "$logPath.err" `+ -WindowStyle Hidden -PassThru+ try {+ @{ Id = $proc.Id; StartTicks = $proc.StartTime.ToUniversalTime().Ticks } | ConvertTo-Json |+ Set-Content -LiteralPath (Join-Path (Get-RunDir) 'probe-studio.json') -Encoding UTF8 -ErrorAction Stop+ } catch {+ $recordError = $_+ Stop-ProcessTree $proc.Id+ throw "could not record the elevated Studio process for revert, so it was stopped rather than left running unrecorded: $recordError"+ }++ foreach ($i in 1..60) {+ Start-Sleep -Seconds 5+ if (Test-StudioResponding $port) {+ Write-Host "Studio answering on port $port after $($i * 5)s"+ return $true+ }+ }+ Write-Warning "Studio did not answer on port $port within 5 minutes; see $logPath"+ return $false+}++function Stop-Studio([int] $port) {+ <# Stop the Studio answering on $port, children (llama-server, workers) first. #>+ # Only the listeners that can be serving the endpoint Test-StudioResponding actually verified, which is http://127.0.0.1:$port.+ $owners = @(Get-NetTCPConnection -LocalPort $port -State Listen -ErrorAction SilentlyContinue |+ Where-Object { $_.LocalAddress -eq '127.0.0.1' -or $_.LocalAddress -eq '0.0.0.0' } |+ Select-Object -ExpandProperty OwningProcess -Unique)+ if (-not $owners) {+ Write-Warning "Studio answers on http://127.0.0.1:$port but no local process listens on 127.0.0.1 or 0.0.0.0 there; it cannot be restarted from here"+ return $false+ }+ foreach ($owner in $owners) {+ Get-CimInstance Win32_Process -Filter "ParentProcessId = $owner" -ErrorAction SilentlyContinue |+ ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }+ Stop-Process -Id $owner -Force -ErrorAction SilentlyContinue+ }+ foreach ($i in 1..30) {+ Start-Sleep -Seconds 1+ if (-not (Test-StudioResponding $port)) { return $true }+ }+ Write-Warning "Studio is still answering on port $port after being stopped"+ return $false+}++function Stop-ProcessTree([int] $id) {+ Get-CimInstance Win32_Process -Filter "ParentProcessId = $id" -ErrorAction SilentlyContinue |+ ForEach-Object { Stop-ProcessTree ([int] $_.ProcessId) }+ Stop-Process -Id $id -Force -ErrorAction SilentlyContinue+}++function Stop-ProbeStudio([string] $dir) {+ <# Stop the elevated Studio this probe started, if it is still that process. Returns $false if it survives. #>+ $record = Join-Path $dir 'probe-studio.json'+ if (-not (Test-Path -LiteralPath $record)) { return $true }+ $r = Get-Content -LiteralPath $record -Raw | ConvertFrom-Json+ $p = Get-Process -Id ([int] $r.Id) -ErrorAction SilentlyContinue+ # Start time guards PID reuse+ if ($p -and $p.StartTime.ToUniversalTime().Ticks -eq [int64] $r.StartTicks) {+ Stop-ProcessTree $p.Id+ if (-not $p.WaitForExit(10000)) { return $false }+ }+ Remove-Item -LiteralPath $record -Force -ErrorAction SilentlyContinue+ return $true+}++function Initialize-Studio([string] $dir, [bool] $allowInstall) {+ <# Only prepare may install. prepare restarts a running Studio so its native loads land inside the event window. #>+ Write-Section 'Unsloth Studio'+ if (Test-StudioResponding $Port) {+ if (-not $allowInstall) {+ Write-Host "Studio already answering on port $Port"+ return+ }+ Write-Host "Studio is already answering on port $Port; restarting it so its startup loads land inside the window"+ if (-not (Stop-Studio $Port)) {+ throw "Studio is still answering on port $Port and could not be restarted, so its startup loads cannot be observed in this window. Stop it by hand and run prepare again."+ }+ }++ $python = Get-StudioPython+ if (-not $python) {+ if (-not $allowInstall) {+ Write-Warning 'Studio is not installed; the run stage does not install it, so there is nothing to drive. Run prepare without -SkipInstall, or install by hand.'+ return+ }+ if ($SkipInstall) {+ Write-Warning 'Studio is not installed and -SkipInstall was given; the run stage will have nothing to drive.'+ return+ }+ Write-Host 'Studio is not installed on this machine.'+ # Which of the trees the installer creates did not exist beforehand.+ $unslothHome = Join-Path $env:USERPROFILE '.unsloth'+ # node and whisper.cpp do NOT always live under %USERPROFILE%\.unsloth.+ $override = Get-StudioHomeOverride+ $installRoots = @($unslothHome, $override, (Split-Path -Parent (Get-LlamaDir))) |+ Where-Object { $_ } | Select-Object -Unique+ $candidates = @(+ $unslothHome,+ (Get-StudioHome),+ (Join-Path (Get-StudioHome) 'unsloth_studio'),+ (Get-LlamaDir)+ ) + @($installRoots | ForEach-Object {+ (Join-Path $_ 'node')+ (Join-Path $_ 'whisper.cpp')+ (Join-Path $_ '.cache')+ }) | Where-Object { $_ } | Select-Object -Unique+ $absentBefore = @($candidates | Where-Object { -not (Test-Path -LiteralPath $_) })+ try {+ $python = Install-Studio+ } finally {+ # The installer may be cancelled after creating administrator-owned trees.+ # Record them even when Ctrl+C bypasses its catch and normal return.+ $created = @($absentBefore | Where-Object { Test-Path -LiteralPath $_ })+ $baselinePath = Join-Path $dir 'baseline.json'+ if ($created.Count -gt 0 -and (Test-Path -LiteralPath $baselinePath)) {+ $b = Get-Content -LiteralPath $baselinePath -Raw | ConvertFrom-Json+ $b.StudioInstalledByProbe = $true+ # Merged, not replaced.+ $b.StudioInstallRoots = @(@($b.StudioInstallRoots) + $created |+ Where-Object { $_ } | Select-Object -Unique)+ Save-ProbeBaseline $b $baselinePath+ }+ }+ if (-not $python) {+ # prepare cannot go on: no Studio to start, so nothing loads inside the window.+ if ($allowInstall) {+ throw 'the installer ran but produced no managed interpreter, so there is no Studio to start and this window would observe nothing. Install Studio by hand and run prepare again; the machine is left prepared, so run revert if you stop here.'+ }+ Write-Warning 'Studio still not found after the installer ran. Install it by hand, then re-run this stage.'+ return+ }+ }+ Write-Host "managed interpreter: $python"+ # Under raw-logs\, which collect redacts into studio-logs\ and never archives as is+ New-Item -ItemType Directory -Force -Path (Join-Path $dir 'raw-logs') | Out-Null+ $startLog = Join-Path (Join-Path $dir 'raw-logs') 'studio-start.log'+ # Not discarded.+ if (-not (Start-Studio $python $Port $startLog)) {+ if ($allowInstall) {+ throw "Studio did not answer on port $Port within 5 minutes, so its startup loads cannot be observed in this window. See $startLog, fix the cause and run prepare again."+ }+ Write-Warning "Studio did not answer on port $Port; the scenario will have nothing to drive. See $startLog."+ }+}++function Save-Baseline([string] $dir) {+ $mp = $null+ $mpError = $null+ try { $mp = Get-MpPreference } catch { $mpError = $_ }+ $status = $null+ try { $status = Get-MpComputerStatus } catch { }+ $ciLog = Get-CiLogSettings++ # Fail before mutating anything whose old value we could not read.+ if (-not $mp) {+ throw "could not read the Defender preferences that prepare changes, so revert would not be able to restore them. Refusing to modify this machine. Underlying error: $mpError"+ }+ $missing = @('DisableRealtimeMonitoring', 'MAPSReporting', 'SubmitSamplesConsent', 'CloudBlockLevel', 'PUAProtection') |+ Where-Object { $null -eq $mp.$_ }+ if ($missing.Count -gt 0) {+ throw "Defender preference(s) $($missing -join ', ') read back as null, so revert could not restore them. Refusing to modify this machine."+ }+ if ($null -eq $ciLog.Enabled -or $null -eq $ciLog.MaxSize) {+ throw "could not read the $CI_LOG channel settings (enabled=$($ciLog.Enabled), maxSize=$($ciLog.MaxSize)), which prepare raises and revert restores. Refusing to modify this machine."+ }++ $baseline = [pscustomobject]@{+ CapturedAt = (Get-Date).ToString('o')+ ComputerName = $env:COMPUTERNAME+ WindowsBuild = (Get-CimInstance Win32_OperatingSystem).BuildNumber+ WindowsVersion = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').DisplayVersion+ Sac = Get-SacState+ DisableRealtimeMonitoring = if ($mp) { $mp.DisableRealtimeMonitoring } else { $null }+ MAPSReporting = if ($mp) { $mp.MAPSReporting } else { $null }+ SubmitSamplesConsent = if ($mp) { $mp.SubmitSamplesConsent } else { $null }+ CloudBlockLevel = if ($mp) { $mp.CloudBlockLevel } else { $null }+ PUAProtection = if ($mp) { $mp.PUAProtection } else { $null }+ AMProductVersion = if ($status) { $status.AMProductVersion } else { $null }+ AntivirusSignatureVersion = if ($status) { $status.AntivirusSignatureVersion } else { $null }+ CiLogEnabled = $ciLog.Enabled+ CiLogMaxSize = $ciLog.MaxSize+ # revert repairs ACLs only on trees this run created; see Invoke-Revert.+ StudioInstalledByProbe = $false+ StudioInstallRoots = @()+ AuditPolicyApplied = $false+ # $true when an unsigned control raised 3076/3077 under the applied policy, $false never (prepare throws), $null when no control could be built.+ AuditPolicyControlFired = $null+ # The same question for the cell that runs with no -AuditPolicy at all, where the only thing that can produce a verdict is Smart App Control enforcing for real.+ SacControlFired = $null+ AuditPolicyPreexisting = $false+ RevertCompletedAt = $null+ }+ $path = Join-Path $dir 'baseline.json'+ Save-ProbeBaseline $baseline $path+ Write-Host "baseline written to $path"+ return $baseline+}++# Proves the audit policy is not merely listed but actually evaluating loads.+function Save-ProbeBaseline($Baseline, [string] $Path) {+ $tmp = "$Path.tmp"+ $Baseline | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $tmp -Encoding UTF8+ if (Test-Path -LiteralPath $Path) {+ [System.IO.File]::Replace($tmp, $Path, [NullString]::Value)+ } else {+ Move-Item -LiteralPath $tmp -Destination $Path+ }+}++# A -WorkDir on roaming or shared storage can carry another machine's baseline; its settings are not this machine's.+function Assert-BaselineIsThisMachine($Baseline) {+ if ($Baseline -and $Baseline.ComputerName -and $Baseline.ComputerName -ne $env:COMPUTERNAME) {+ throw "label '$Label' was prepared on $($Baseline.ComputerName), not $($env:COMPUTERNAME); its baseline describes that machine, so no stage uses it here. Use a -WorkDir local to this machine, or a new -Label."+ }+}++function Test-EventFromPolicy($record, [string] $Guid, [string] $NamePattern = '*AuditNoISG*') {+ return (Test-EventDataFromPolicy (Get-EventDataMap $record) $Guid $NamePattern)+}++function Test-EventDataFromPolicy($data, [string] $Guid, [string] $NamePattern = '*AuditNoISG*') {+ if ($null -eq $data) { return $false }+ $bare = $Guid.Trim('{', '}').ToLowerInvariant()+ $named = $false+ $otherId = $false+ foreach ($key in @($data.Keys)) {+ $value = [string] $data[$key]+ if (-not $value) { continue }+ if ($value.ToLowerInvariant().Contains($bare)) { return $true }+ if ($key -like 'PolicyName*') {+ if ($NamePattern -and $value -like $NamePattern) { $named = $true }+ } elseif ($key -like 'Policy*' -and $value -match '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}') {+ $otherId = $true+ }+ }+ # The name is a fallback for events without a policy ID; an ID naming another policy wins.+ return ($named -and -not $otherId)+}++function Test-AuditPolicyEvaluating([int[]] $AcceptIds = @(3076, 3077), [string] $FromPolicy = $null) {+ $dir = Join-Path $WorkDir ".control-$Label"+ Remove-Item -LiteralPath $dir -Recurse -Force -ErrorAction SilentlyContinue+ New-Item -ItemType Directory -Force -Path $dir | Out-Null+ try {+ $control = Join-Path $dir 'unsigned-control.exe'+ $since = (Get-Date).AddSeconds(-1)+ try {+ # Windows PowerShell 5.1 only.+ $src = 'public class UnsignedControl { public static void Main() { System.Console.WriteLine("control"); } }'+ Add-Type -TypeDefinition $src -OutputAssembly $control -OutputType ConsoleApplication -ErrorAction Stop+ } catch {+ Write-Warning "could not build an unsigned control binary ($_); the audit policy is listed as active but has NOT been shown to evaluate loads here. Run prepare from Windows PowerShell 5.1 for a verified cell."+ return $null+ }+ if (-not (Test-Path -LiteralPath $control)) {+ Write-Warning 'Add-Type reported success but produced no control binary; the audit policy has NOT been shown to evaluate loads here.'+ return $null+ }+ # Launch failure is not an error here.+ try { & $control 2>&1 | Out-Null } catch { }+ # Polled, not slept once.+ foreach ($attempt in 1..10) {+ Start-Sleep -Seconds 3+ $fired = @(Get-WinEvent -FilterHashtable @{+ LogName = $CI_LOG; StartTime = $since+ } -ErrorAction SilentlyContinue |+ Where-Object {+ $AcceptIds -contains $_.Id -and $_.Message -like '*unsigned-control*' -and+ (-not $FromPolicy -or (Test-EventFromPolicy $_ $FromPolicy))+ })+ if ($fired.Count -gt 0) {+ $what = if ($fired[0].Id -eq 3077) { 'refused on this machine' } else { 'evaluated on this machine' }+ Write-Host "positive control raised $($fired[0].Id): unsigned code is $what"+ return $true+ }+ }+ return $false+ } finally {+ # Never left behind, and never staged into the evidence+ Remove-Item -LiteralPath $dir -Recurse -Force -ErrorAction SilentlyContinue+ }+}++# Machine-wide, so a label prepared under another -WorkDir is seen too.+function Get-PendingRegistry {+ return (Join-Path $env:ProgramData 'unsloth-sac-probe\pending')+}++function Get-PendingEntry([string] $dir) {+ $key = [System.IO.Path]::GetFullPath($dir).TrimEnd('\', '/').ToLowerInvariant()+ $sha = [System.Security.Cryptography.SHA256]::Create()+ try { $hash = -join ($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($key)) | ForEach-Object { $_.ToString('x2') }) }+ finally { $sha.Dispose() }+ return (Join-Path (Get-PendingRegistry) ($hash.Substring(0, 16) + '.txt'))+}++# A label whose baseline is not spent still has its changes on this machine.+function Get-UnrevertedLabel([string] $dir) {+ $candidates = @(Get-ChildItem -LiteralPath (Split-Path -Parent $dir) -Directory -ErrorAction SilentlyContinue |+ ForEach-Object { $_.FullName })+ $self = Get-PendingEntry $dir+ foreach ($entry in @(Get-ChildItem -LiteralPath (Get-PendingRegistry) -File -Filter '*.txt' -ErrorAction SilentlyContinue)) {+ if ($entry.FullName -eq $self) {+ # Retry only against the original baseline. A missing WorkDir must+ # not turn this label's installed policy into a fresh baseline.+ if (-not (Test-Path -LiteralPath (Join-Path $dir 'baseline.json'))) { return $dir }+ continue+ }+ # A pending machine-wide claim remains authoritative when its WorkDir is+ # disconnected, renamed or unreadable. Do not snapshot its changes as baseline.+ $recorded = Get-Content -LiteralPath $entry.FullName -Raw -ErrorAction Stop+ if (-not $recorded -or -not $recorded.Trim()) {+ throw "pending probe entry $($entry.FullName) is empty; recover its baseline and revert before preparing another label"+ }+ $other = $recorded.Trim()+ $path = Join-Path $other 'baseline.json'+ if (-not (Test-Path -LiteralPath $path)) { return $other }+ try { $b = Get-Content -LiteralPath $path -Raw -ErrorAction Stop | ConvertFrom-Json }+ catch { return $other }+ if (-not $b -or -not $b.RevertCompletedAt) { return $other }+ }+ foreach ($other in $candidates) {+ if ((Get-PendingEntry $other) -eq $self) { continue }+ $path = Join-Path $other 'baseline.json'+ if (-not (Test-Path -LiteralPath $path)) { continue }+ $b = $null+ try { $b = Get-Content -LiteralPath $path -Raw | ConvertFrom-Json } catch { }+ if ($b -and -not $b.RevertCompletedAt) { return $other }+ }+ return $null+}++function Invoke-Prepare {+ Assert-Elevated+ $dir = Get-RunDir+ $unreverted = Get-UnrevertedLabel $dir+ if ($unreverted) {+ $name = Split-Path -Leaf $unreverted+ throw "label '$name' has not been reverted, so this machine still carries its changes (and its audit policy would be taken for a pre-existing one). Run .\sac-probe.ps1 -Stage revert -Label $name -WorkDir '$(Split-Path -Parent $unreverted)' first, then prepare label '$Label'. If that evidence folder is gone for good, restore the machine by hand and delete its record under $(Get-PendingRegistry)."+ }+ $ROLLBACK_POLICY = Get-RollbackPolicyPath $dir+ Write-Section 'Baseline'+ $baselinePath = Join-Path $dir 'baseline.json'+ $previous = $null+ if (Test-Path -LiteralPath $baselinePath) {+ $previous = Get-Content -LiteralPath $baselinePath -Raw | ConvertFrom-Json+ Assert-BaselineIsThisMachine $previous+ }+ if ($previous -and -not $previous.RevertCompletedAt) {+ # A retry of this label whose changes are still on the machine.+ $baseline = $previous+ Write-Warning "reusing the baseline captured at $($baseline.CapturedAt) by an earlier prepare of this label; revert restores that state"+ } else {+ # No baseline, or one whose revert completed+ if ($previous) {+ Write-Host "the previous run of label '$Label' was reverted at $($previous.RevertCompletedAt); capturing a fresh baseline"+ }+ $baseline = Save-Baseline $dir+ }+ $pending = Get-PendingEntry $dir+ New-Item -ItemType Directory -Force -Path (Split-Path $pending) | Out-Null+ [System.IO.Path]::GetFullPath($dir) | Set-Content -LiteralPath $pending -Encoding UTF8+ Write-Host ("Smart App Control: {0} (registry state {1})" -f $baseline.Sac.Mode, $baseline.Sac.RegistryState)+ foreach ($p in $baseline.Sac.Policies) {+ Write-Host (" policy {0} enforced={1}" -f $p.FriendlyName, $p.IsEnforced)+ }++ if (-not $SkipUpdates) {+ Write-Section 'Updates'+ # Best effort.+ try {+ Write-Host 'Update-MpSignature ...'+ Update-MpSignature -ErrorAction Stop+ } catch { Write-Warning "Update-MpSignature failed: $_" }+ }+ # Always cleared, so the transcript in the run directory describes this pass+ Remove-Item -LiteralPath (Join-Path $dir 'winget-upgrade.log') -Force -ErrorAction SilentlyContinue+ if ($UpgradePackages) {+ try {+ Write-Host 'winget upgrade --all ...'+ & winget upgrade --all --accept-source-agreements --accept-package-agreements --silent 2>&1 |+ Tee-Object -FilePath (Join-Path $dir 'winget-upgrade.log') | Out-Null+ } catch { Write-Warning "winget upgrade failed: $_" }+ }++ Write-Section 'Raise security settings'+ # Deliberately only the reversible ones.+ $wanted = [ordered]@{+ DisableRealtimeMonitoring = $false+ MAPSReporting = 'Advanced'+ CloudBlockLevel = 'High'+ PUAProtection = 'Enabled'+ }+ if ($SendSamples) {+ $wanted['SubmitSamplesConsent'] = 'SendAllSamples'+ }+ $mpFailed = @()+ foreach ($name in $wanted.Keys) {+ try {+ $params = @{ $name = $wanted[$name] }+ Set-MpPreference @params+ } catch {+ $mpFailed += "${name}: $_"+ Write-Warning "could not set Defender $name : $_"+ }+ }+ # Read back, because a tamper-protected or policy-managed preference is IGNORED rather than refused+ $applied = $null+ try { $applied = Get-MpPreference } catch { }+ if (-not $applied) {+ $mpFailed += 'the Defender preferences could not be read back, so this cell cannot show that it carries the documented baseline'+ } else {+ foreach ($name in $wanted.Keys) {+ $actual = $applied.$name+ $expected = $wanted[$name]+ $same = Test-MpPreferenceMatch $actual $expected (Get-MpPreferenceType $name)+ if ($false -eq $same) {+ $mpFailed += "${name}: set to $expected but reads back as $actual (tamper protection or policy?)"+ Write-Warning "Defender $name reads back as $actual after being set to $expected"+ } elseif ($null -eq $same) {+ $mpFailed += "${name}: set to $expected and reads back as $actual, which could not be compared, so this cell cannot show it carries that setting"+ Write-Warning "Defender $name reads back as $actual, which could not be compared to $expected"+ }+ }+ }+ $mpErrorPath = Join-Path $dir 'defender-preference-errors.txt'+ if ($mpFailed.Count -gt 0) {+ $mpFailed -join "`n" | Set-Content -LiteralPath $mpErrorPath -Encoding UTF8+ Write-Warning "$($mpFailed.Count) Defender preference(s) were NOT applied; this cell does not carry the documented baseline. See defender-preference-errors.txt."+ } else {+ Remove-Item -LiteralPath $mpErrorPath -Force -ErrorAction SilentlyContinue+ Write-Host 'Defender: real-time on, MAPS advanced, cloud block level high, PUA on'+ if ($SendSamples) { Write-Host 'Defender: sample submission set to SendAllSamples (-SendSamples)' }+ }++ Write-Section 'CodeIntegrity log'+ # The default 1 MB fills quickly once a policy is auditing every load, and a wrapped log silently loses the events this whole exercise exists to catch.+ try {+ Invoke-Native 'wevtutil.exe' @('sl', $CI_LOG, '/e:true', '/ms:67108864')+ } catch {+ throw "could not enable $CI_LOG at 64 MB, so no code integrity event could be collected: $_"+ }+ $ciNow = Get-CiLogSettings+ if (-not $ciNow.Enabled) {+ throw "$CI_LOG is still disabled after wevtutil sl (policy-controlled?); the probe cannot collect evidence here"+ }+ if ($null -eq $ciNow.MaxSize -or $ciNow.MaxSize -lt 67108864) {+ throw "$CI_LOG is $($ciNow.MaxSize) bytes after wevtutil sl asked for 64 MB (policy-controlled?); auditing every load would wrap the channel before collect reads it, so the probe cannot collect trustworthy evidence here"+ }+ Write-Host ("CodeIntegrity/Operational enabled, max size {0} (was enabled={1}, maxSize={2})" -f $ciNow.MaxSize, $baseline.CiLogEnabled, $baseline.CiLogMaxSize)++ # Every failure from here on rolls back the policy once it was copied.+ $policyCopied = $false+ $prepareCompleted = $false+ try {+ if ($AuditPolicy) {+ Write-Section 'Audit policy'+ if (-not (Test-Path -LiteralPath $AuditPolicy)) {+ throw "audit policy not found: $AuditPolicy"+ }+ # The NoISG policy checks signatures only and skips the cloud reputation lookup, which is why it works even with Smart App Control off.+ $mounted = Mount-Efi+ try {+ # A file already there is somebody's policy only if this label did not put it there+ if ((Test-Path -LiteralPath $NOISG_DEST) -and -not $baseline.AuditPolicyApplied) {+ # Keep it so revert restores it instead of deleting an administrator's policy.+ New-Item -ItemType Directory -Force -Path (Split-Path $ROLLBACK_POLICY) | Out-Null+ Copy-Item -LiteralPath $NOISG_DEST -Destination $ROLLBACK_POLICY -Force+ $baseline.AuditPolicyPreexisting = $true+ Write-Warning "a policy with $NOISG_GUID was already installed; saved to rollback\preexisting-policy.cip and will be restored by revert"+ }+ # Persisted before anything on the EFI partition changes+ $baseline.AuditPolicyApplied = $true+ Save-ProbeBaseline $baseline $baselinePath+ New-Item -ItemType Directory -Force -Path (Split-Path $NOISG_DEST) | Out-Null+ $policyCopied = $true+ Copy-Item -LiteralPath $AuditPolicy -Destination $NOISG_DEST -Force+ Invoke-Native 'CiTool.exe' @('-r')+ } finally {+ Dismount-Efi $mounted+ }+ if ($script:EfiStillMounted) {+ throw "the EFI system partition is still mounted as S: and could not be unmounted; the next stage would see it as already mounted and never retry, so run 'mountvol S: /D' by hand before continuing"+ }+ Write-Host "applied $(Split-Path $AuditPolicy -Leaf) as $NOISG_GUID and refreshed policy"++ Write-Section 'Policy state after applying'+ $after = Get-SacState+ foreach ($p in $after.Policies) {+ Write-Host (" policy {0} enforced={1}" -f $p.FriendlyName, $p.IsEnforced)+ }+ # Printing whatever is listed is not verification.+ if ($null -eq $after.Policies) {+ throw "CiTool could not list the policies, so the audit policy cannot be verified as active"+ }+ if ($after.Policies.Count -gt 0 -and -not (Test-PolicyActive $NOISG_GUID)) {+ throw "the audit policy $NOISG_GUID is not in the active policy set after refresh"+ }+ if ($after.Policies.Count -eq 0) {+ # No policy list means no evidence the policy is active, and a run with no 3076 events would then read as an allow verdict.+ throw "CiTool listed no policies, so the audit policy cannot be verified as active"+ }++ Write-Section 'Positive control'+ $controlFired = Test-AuditPolicyEvaluating -FromPolicy $NOISG_GUID+ if ($false -eq $controlFired) {+ throw "the audit policy $NOISG_GUID is listed as active but an unsigned control binary raised no 3076 or 3077 attributed to that policy, so it is not evaluating loads on this machine; a run with no events would be meaningless. Run revert and re-apply the policy."+ }+ $baseline.AuditPolicyControlFired = $controlFired+ Save-ProbeBaseline $baseline $baselinePath+ } else {+ Write-Host ''+ Write-Host 'No -AuditPolicy given. Download the sample policies from https://aka.ms/sacauditpolicies'+ Write-Host 'and re-run with -AuditPolicy <path to SmartAppControlAuditNoISG.bin> to log what'+ Write-Host 'would be blocked. Without it, only real enforcement (3077) shows up, and only on a'+ Write-Host 'machine where Smart App Control is genuinely on.'+ # So establish that it is, rather than letting collect infer an allow from a registry read.+ $sacBefore = Get-SacState+ if ($sacBefore.Mode -eq 'enforcement') {+ Write-Section 'Positive control'+ # 3077 only.+ $sacFired = Test-AuditPolicyEvaluating -AcceptIds @(3077)+ if ($false -eq $sacFired) {+ throw "Smart App Control reads as 'enforcement' but an unsigned control binary ran here without being refused with a 3077, so nothing is enforcing against unsigned code on this boot and a window with no events would be meaningless. Re-run prepare with -AuditPolicy, or on a machine where enforcement is live."+ }+ $baseline | Add-Member -NotePropertyName SacControlFired -NotePropertyValue $sacFired -Force+ Save-ProbeBaseline $baseline $baselinePath+ }+ }++ # Marks the window collect will export.+ foreach ($stale in @(+ 'scenario-status.json', 'scenario-results.json', 'runtime-selection.json',+ 'venv-selection.txt', 'studio-home.txt',+ 'signature-inventory.json', 'signature-inventory.csv',+ 'venv-signature-inventory.json', 'venv-signature-inventory.csv',+ 'code-integrity-events.json', 'code-integrity-events.txt',+ 'CodeIntegrity-Operational.evtx', 'defender-detections.json',+ 'defender-query-error.txt', 'sac-state-after.json',+ 'events-collection-error.txt', 'inventory-enumeration-errors.txt'+ )) {+ Remove-Item -LiteralPath (Join-Path $dir $stale) -Force -ErrorAction SilentlyContinue+ }+ foreach ($staleDir in @('studio-logs', 'raw-logs')) {+ Remove-Item -LiteralPath (Join-Path $dir $staleDir) -Recurse -Force -ErrorAction SilentlyContinue+ }++ (Get-Date).ToString('o') | Set-Content -LiteralPath (Join-Path $dir 'window-start.txt') -Encoding UTF8++ Initialize-Studio $dir $true+ $prepareCompleted = $true+ } finally {+ # Pipeline cancellation bypasses catch, but finally still rolls the policy back.+ if ($policyCopied -and -not $prepareCompleted) {+ Write-Warning 'prepare failed after applying the audit policy; rolling the policy back'+ try {+ $mounted = Mount-Efi+ try {+ if ($baseline.AuditPolicyPreexisting) {+ Copy-Item -LiteralPath $ROLLBACK_POLICY -Destination $NOISG_DEST -Force+ } elseif (Test-Path -LiteralPath $NOISG_DEST) {+ Remove-Item -LiteralPath $NOISG_DEST -Force+ }+ Invoke-Native 'CiTool.exe' @('-r')+ } finally {+ Dismount-Efi $mounted+ }+ $stillActive = Test-PolicyActive $NOISG_GUID+ if ($baseline.AuditPolicyPreexisting -and $null -ne $stillActive) { $stillActive = -not $stillActive }+ if ($null -eq $stillActive) {+ Write-Warning "the audit policy $NOISG_GUID was rolled back but CiTool could not list the policies to confirm it; run .\sac-probe.ps1 -Stage revert -Label $Label"+ } elseif ($stillActive -and $baseline.AuditPolicyPreexisting) {+ Write-Warning "the pre-existing audit policy $NOISG_GUID was restored but is not active until Windows restarts; restart, then run .\sac-probe.ps1 -Stage revert -Label $Label"+ } elseif ($stillActive) {+ Write-Warning "the audit policy $NOISG_GUID was removed but is still active until Windows restarts; restart, then run .\sac-probe.ps1 -Stage revert -Label $Label"+ } else {+ # Re-read: Initialize-Studio may have recorded the roots it created since $baseline was loaded.+ $saved = Get-Content -LiteralPath $baselinePath -Raw | ConvertFrom-Json+ $saved.AuditPolicyApplied = $false+ Save-ProbeBaseline $saved $baselinePath+ Write-Host 'audit policy rolled back'+ }+ } catch {+ Write-Warning "could not roll back the audit policy: $_ (run .\sac-probe.ps1 -Stage revert -Label $Label)"+ }+ }+ }++ Write-Host ''+ Write-Host "prepare complete. Next: .\sac-probe.ps1 -Stage run -Label $Label"+}++$script:InventoryErrors = @()++function Get-SignatureInventory([string] $root) {+ if (-not (Test-Path -LiteralPath $root)) {+ Write-Warning "nothing to inventory at $root"+ return @()+ }+ $enumErrors = @()+ Get-ChildItem -LiteralPath $root -Recurse -File -ErrorAction SilentlyContinue -ErrorVariable enumErrors |+ Where-Object { $PE_EXT -contains $_.Extension.ToLowerInvariant() } |+ ForEach-Object {+ $sig = Get-AuthenticodeSignature -LiteralPath $_.FullName+ [pscustomobject]@{+ Name = $_.Name+ FullName = $_.FullName+ Length = $_.Length+ SHA256 = (Get-FileHash -LiteralPath $_.FullName -Algorithm SHA256).Hash+ Status = [string]$sig.Status+ StatusMessage = $sig.StatusMessage+ Subject = if ($sig.SignerCertificate) { $sig.SignerCertificate.Subject } else { $null }+ Thumbprint = if ($sig.SignerCertificate) { $sig.SignerCertificate.Thumbprint } else { $null }+ TimeStamped = if ($sig.TimeStamperCertificate) { $true } else { $false }+ }+ }+ if ($enumErrors.Count -gt 0) {+ # A subtree that could not be read is exactly where the access-denied native module being investigated would sit, and the caller only rejects a completely empty result.+ $script:InventoryErrors += @($enumErrors | ForEach-Object { "${root}: $_" })+ Write-Warning "$($enumErrors.Count) path(s) under $root could not be enumerated; this inventory is PARTIAL. See inventory-enumeration-errors.txt."+ }+}++function Invoke-Run {+ Assert-Elevated+ $dir = Get-RunDir++ # Before anything else.+ if (-not (Test-Path -LiteralPath (Join-Path $dir 'baseline.json')) -or+ -not (Test-Path -LiteralPath (Join-Path $dir 'window-start.txt'))) {+ throw "label '$Label' has no baseline.json and window-start.txt under ${dir}: prepare did not complete for it, so there is nothing to run against. Check the -Label, or run prepare for it first."+ }++ $runBaselinePath = Join-Path $dir 'baseline.json'+ if (Test-Path -LiteralPath $runBaselinePath) {+ $runBaseline = Get-Content -LiteralPath $runBaselinePath -Raw | ConvertFrom-Json+ Assert-BaselineIsThisMachine $runBaseline+ # A label whose revert already completed.+ if ($runBaseline.RevertCompletedAt) {+ throw "label '$Label' was reverted at $($runBaseline.RevertCompletedAt), so its baseline is spent and the event window on disk belongs to the run that was undone. Running now would file events from that window against this run's inventory. Run prepare for this label again (or use a new -Label) first."+ }+ # The window on disk has to belong to THIS baseline, and the check above cannot see when it does not.+ $runStartPath = Join-Path $dir 'window-start.txt'+ if (Test-Path -LiteralPath $runStartPath) {+ $runStart = $null+ $runPrepared = $null+ try {+ $runStart = [datetime]::Parse(+ (Get-Content -LiteralPath $runStartPath -Raw).Trim(),+ [cultureinfo]::InvariantCulture)+ $runPrepared = [datetime]::Parse([string]$runBaseline.CapturedAt,+ [cultureinfo]::InvariantCulture)+ } catch { }+ if ($runStart -and $runPrepared -and $runStart -lt $runPrepared) {+ throw "the event window on disk opened at $($runStart.ToString('o')), before this label's baseline was captured at $($runPrepared.ToString('o')): prepare took a new baseline and then failed before it reopened the window, so collect would export the previous run's events against this run's inventory. Run prepare for label '$Label' again first."+ }+ }+ if ($runBaseline.AuditPolicyApplied) {+ Write-Section 'Audit policy still active'+ $state = Get-SacState+ if ($state.Policies.Count -eq 0) {+ throw "CiTool listed no policies, so the audit policy applied by prepare cannot be verified as active; this run would measure nothing. Run revert and prepare again."+ }+ if (-not (Test-PolicyActive $NOISG_GUID)) {+ throw "the audit policy $NOISG_GUID is no longer in the active policy set (a reboot since prepare?), so this run would not be audited and its empty window would read as an allow. Run revert and prepare again."+ }+ Write-Host "audit policy $NOISG_GUID is active"+ $bootedAt = $null+ try { $bootedAt = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime } catch { }+ $preparedAt = $null+ # Invariant, and on the string form, because CapturedAt arrives here in two shapes and the default parse reads neither safely.+ try {+ $preparedAt = [datetime]::Parse([string]$runBaseline.CapturedAt,+ [cultureinfo]::InvariantCulture)+ } catch { }+ if ($bootedAt -and $preparedAt -and $bootedAt -gt $preparedAt) {+ Write-Host 'the machine booted after this baseline was captured; re-running the positive control on this boot'+ $controlFired = Test-AuditPolicyEvaluating -FromPolicy $NOISG_GUID+ if ($false -eq $controlFired) {+ throw "the audit policy $NOISG_GUID is listed as active but an unsigned control raised no 3076 or 3077 attributed to that policy on this boot, so it is not evaluating loads and this run would be meaningless. Run revert and prepare again."+ }+ $runBaseline.AuditPolicyControlFired = $controlFired+ Save-ProbeBaseline $runBaseline $runBaselinePath+ }+ } elseif ([string]$runBaseline.Sac.Mode -eq 'enforcement') {+ # The same revalidation for the cell with no audit policy, where the only thing that can produce a verdict is Smart App Control refusing code for real.+ Write-Section 'Smart App Control still enforcing'+ $sacNow = Get-SacState+ if ($sacNow.Mode -ne 'enforcement') {+ throw "Smart App Control read as 'enforcement' when this label was prepared but reads as '$($sacNow.Mode)' now (a reboot since prepare?), so nothing here can log a verdict and this run's empty window would read as an allow. Run revert and prepare again."+ }+ Write-Host 'Smart App Control is enforcing'+ $bootedAt = $null+ try { $bootedAt = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime } catch { }+ $preparedAt = $null+ # Invariant, and on the string form, because CapturedAt arrives here in two shapes and the default parse reads neither safely.+ try {+ $preparedAt = [datetime]::Parse([string]$runBaseline.CapturedAt,+ [cultureinfo]::InvariantCulture)+ } catch { }+ if (($bootedAt -and $preparedAt -and $bootedAt -gt $preparedAt) -or+ ($true -ne $runBaseline.SacControlFired)) {+ Write-Host 'confirming on this boot that unsigned code is actually refused here'+ # 3077 only, for the reason prepare gives+ $sacFired = Test-AuditPolicyEvaluating -AcceptIds @(3077)+ if ($false -eq $sacFired) {+ throw "Smart App Control reads as 'enforcement' but an unsigned control ran on this boot without being refused with a 3077, so it is not enforcing against unsigned code and this run would be meaningless. Run revert and prepare again."+ }+ $runBaseline | Add-Member -NotePropertyName SacControlFired -NotePropertyValue $sacFired -Force+ Save-ProbeBaseline $runBaseline $runBaselinePath+ }+ }+ }++ # A machine that was prepared earlier may have been rebooted since, which is itself part of the reported behaviour+ if (-not $SkipStudio -and -not (Test-StudioResponding $Port)) { Initialize-Studio $dir $false }++ # The venv, separately.+ Write-Section 'Venv signature inventory'+ $studioPython = Get-StudioPython+ $venvDir = Resolve-VenvDir+ Write-Host "venv: $venvDir"+ # Recorded for collect, which may run from a shell where a custom UNSLOTH_STUDIO_HOME was never set.+ $venvDir | Set-Content -LiteralPath (Join-Path $dir 'venv-selection.txt') -Encoding UTF8+ Get-StudioHome | Set-Content -LiteralPath (Join-Path $dir 'studio-home.txt') -Encoding UTF8+ $venvInventory = @(Get-SignatureInventory $venvDir)+ ConvertTo-Json -InputObject @($venvInventory) -Depth 4 |+ Set-Content -LiteralPath (Join-Path $dir 'venv-signature-inventory.json') -Encoding UTF8+ $venvInventory | Export-Csv -LiteralPath (Join-Path $dir 'venv-signature-inventory.csv') -NoTypeInformation -Encoding UTF8+ $venvTotal = $venvInventory.Count+ if ($venvTotal -eq 0) {+ # The venv is where the only enforced block so far landed+ throw "no PE files found under $venvDir; Studio's environment was not found, so the cell is invalid. Check UNSLOTH_STUDIO_HOME or install Studio first"+ }+ $venvValid = @($venvInventory | Where-Object { $_.Status -eq 'Valid' }).Count+ Write-Host "$venvValid of $venvTotal PE files in the venv report a valid Authenticode signature"+ if ($venvTotal -gt 0) {+ $venvInventory | Where-Object { $_.Status -ne 'Valid' } |+ Group-Object { ($_.FullName -split '\\site-packages\\')[-1].Split('\')[0] } |+ Sort-Object Count -Descending | Select-Object -First 10 |+ Format-Table @{n = 'package'; e = { $_.Name } }, Count -AutoSize | Out-String | Write-Host+ }++ $scenarioStatus = [pscustomobject]@{ Ran = $false; ExitCode = $null; Reason = 'skipped' }+ if ($SkipStudio) {+ Write-Host 'skipping the Studio scenario (-SkipStudio)'+ } else {+ Write-Section 'Studio scenario'+ $scenario = Join-Path $PSScriptRoot 'studio_scenario.py'+ New-Item -ItemType Directory -Force -Path (Join-Path $dir 'raw-logs') | Out-Null+ $log = Join-Path (Join-Path $dir 'raw-logs') 'studio-scenario.log'+ if (-not $STUDIO_PASSWORD) {+ Write-Warning 'UNSLOTH_STUDIO_PASSWORD is not set; the scenario needs it (see README) and will stop at login'+ }+ $scenarioArgs = @($scenario, '--model', $Model, '--out', $dir, '--port', "$Port")+ # Neither UNSLOTH_STUDIO_PASSWORD (unsloth_cli claims that name and hard-errors, see $STUDIO_PASSWORD) nor --password on the command line.+ # Only the password captured from UNSLOTH_STUDIO_PASSWORD, never one inherited under this name.+ Remove-Item Env:\SAC_PROBE_STUDIO_PASSWORD -ErrorAction SilentlyContinue+ if ($STUDIO_PASSWORD) { $env:SAC_PROBE_STUDIO_PASSWORD = $STUDIO_PASSWORD }+ Write-Host "python $scenario --model $Model --out $dir --port $Port"+ $prev = $ErrorActionPreference+ $ErrorActionPreference = 'Continue'+ try {+ & python @scenarioArgs 2>&1 | Tee-Object -FilePath $log+ $code = $LASTEXITCODE+ $scenarioStatus = [pscustomobject]@{+ Ran = $true+ ExitCode = $code+ Reason = if ($code -eq 0) { 'ok' } else { 'scenario exited non-zero' }+ }+ Write-Host "scenario exit code: $code"+ } catch {+ $scenarioStatus = [pscustomobject]@{ Ran = $true; ExitCode = $null; Reason = "$_" }+ Write-Warning "scenario failed: $_"+ } finally {+ Remove-Item Env:\SAC_PROBE_STUDIO_PASSWORD -ErrorAction SilentlyContinue+ $ErrorActionPreference = $prev+ }+ }+ $scenarioStatus | ConvertTo-Json -Depth 3 |+ Set-Content -LiteralPath (Join-Path $dir 'scenario-status.json') -Encoding UTF8+++ # After the scenario, which records the runtime Studio resolved+ Write-Section 'Signature inventory'+ $llamaDir = Resolve-LlamaDir $dir+ Write-Host "runtime: $llamaDir"+ $inventory = @(Get-SignatureInventory $llamaDir)+ ConvertTo-Json -InputObject @($inventory) -Depth 4 |+ Set-Content -LiteralPath (Join-Path $dir 'signature-inventory.json') -Encoding UTF8+ $inventory | Export-Csv -LiteralPath (Join-Path $dir 'signature-inventory.csv') -NoTypeInformation -Encoding UTF8++ $total = $inventory.Count+ if ($total -eq 0) {+ # A runtime with no PE files is a stale UNSLOTH_LLAMA_CPP_PATH, an absent install or a failed enumeration+ throw "no PE files found under ${llamaDir}: there is no llama.cpp runtime on this machine, so the cell is invalid. Run 'python -X utf8 -I -m unsloth_cli studio setup' to download one (or point UNSLOTH_LLAMA_CPP_PATH / UNSLOTH_STUDIO_HOME at an existing install), then re-run this stage"+ }+ $valid = @($inventory | Where-Object { $_.Status -eq 'Valid' }).Count+ Write-Host "$valid of $total PE files report a valid Authenticode signature"+ if ($total -gt 0 -and $valid -lt $total) {+ Write-Host 'unsigned or unverifiable:' -ForegroundColor Yellow+ $inventory | Where-Object { $_.Status -ne 'Valid' } |+ Select-Object Name, Status | Format-Table -AutoSize | Out-String | Write-Host+ }++ $enumPath = Join-Path $dir 'inventory-enumeration-errors.txt'+ if ($script:InventoryErrors.Count -gt 0) {+ $script:InventoryErrors -join "`n" | Set-Content -LiteralPath $enumPath -Encoding UTF8+ Write-Warning "$($script:InventoryErrors.Count) path(s) could not be enumerated; the inventories in this cell are PARTIAL and inventory-enumeration-errors.txt names them. Do not read an absent file as an absent PE."+ } else {+ Remove-Item -LiteralPath $enumPath -Force -ErrorAction SilentlyContinue+ }++ Write-Host ''+ if (-not $SkipStudio -and $scenarioStatus.ExitCode -ne 0) {+ # A scenario that never authenticated or never loaded a model produces a window with nothing in it, and an empty window reads exactly like a clean allow.+ Write-Warning 'the scenario did NOT complete, so this cell has not exercised model loading.'+ Write-Warning "See $log. Fix the cause and re-run this stage before collecting."+ }+ Write-Host "run complete. Next: .\sac-probe.ps1 -Stage collect -Label $Label"+}++# Reads the event window until delivery has settled.+function Read-SettledCiEvents([datetime] $Start, [int[]] $Ids, [int] $Attempts = 20, [int] $IntervalSeconds = 3, [int] $MinSettleSeconds = 30) {+ $previous = -1+ $waited = 0+ $events = @()+ foreach ($attempt in 1..$Attempts) {+ $events = @()+ try {+ $events = @(Get-WinEvent -FilterHashtable @{+ LogName = $CI_LOG+ StartTime = $Start+ } -ErrorAction Stop | Where-Object { $Ids -contains $_.Id })+ } catch {+ if ($_.FullyQualifiedErrorId -notlike 'NoMatchingEventsFound*') { throw }+ }+ if ($events.Count -eq $previous -and $waited -ge $MinSettleSeconds) { break }+ $previous = $events.Count+ if ($attempt -lt $Attempts) {+ Start-Sleep -Seconds $IntervalSeconds+ $waited += $IntervalSeconds+ }+ }+ return $events+}++function Invoke-Collect {+ Assert-Elevated+ $dir = Get-RunDir++ $startPath = Join-Path $dir 'window-start.txt'+ if (-not (Test-Path -LiteralPath $startPath)) {+ # Get-RunDir creates the directory, so a mistyped label or a collect without a prepare lands here.+ throw "no window-start.txt under ${dir}: prepare did not run for label '$Label', so there is no event window to collect"+ }+ $start = [datetime]::Parse((Get-Content -LiteralPath $startPath -Raw).Trim())+ # The same window checks run makes: a reverted label no longer carries the state its events are judged by.+ $collectBaselinePath = Join-Path $dir 'baseline.json'+ if (Test-Path -LiteralPath $collectBaselinePath) {+ $collectBaseline = Get-Content -LiteralPath $collectBaselinePath -Raw | ConvertFrom-Json+ Assert-BaselineIsThisMachine $collectBaseline+ if ($collectBaseline.RevertCompletedAt) {+ throw "label '$Label' was reverted at $($collectBaseline.RevertCompletedAt); collect runs before revert, since revert clears the audit-policy state collect attributes events by and the log keeps growing past the run. Run prepare, run and collect for this label again."+ }+ $prepared = $null+ try { $prepared = [datetime]::Parse([string]$collectBaseline.CapturedAt, [cultureinfo]::InvariantCulture) } catch { }+ if ($prepared -and $start -lt $prepared) {+ throw "the event window on disk opened at $($start.ToString('o')), before this label's baseline was captured at $($prepared.ToString('o')), so it belongs to an earlier run. Run prepare for label '$Label' again first."+ }+ }+ Write-Section "Events since $($start.ToString('o'))"++ # Everything that went wrong while gathering evidence.+ $collectionProblems = @()+ $events = @()+ try {+ $events = @(Read-SettledCiEvents $start $CI_EVENT_IDS)+ if ($events.Count -eq 0) { Write-Host 'no CodeIntegrity events in the window' }+ } catch {+ # Only "nothing matched" is an empty window, and Read-SettledCiEvents already treats it as one.+ $_.ToString() | Set-Content -LiteralPath (Join-Path $dir 'events-collection-error.txt') -Encoding UTF8+ throw "could not read $CI_LOG, so the event window was not collected: $_"+ }+ # A retry that got through clears the earlier attempt's marker+ Remove-Item -LiteralPath (Join-Path $dir 'events-collection-error.txt') -Force -ErrorAction SilentlyContinue++ $tail = Get-ScopeTail (Resolve-LlamaDir $dir)+ $venvTail = Get-ScopeTail (Resolve-VenvDir $dir)+ # Studio's CPU fallback copy of the runtime: <studio home>\runtime\llama-cpu-*, the home run.py exports+ $cpuTail = (Get-ScopeTail (Join-Path (Resolve-StudioHomeFor $dir) 'runtime')) + 'llama-cpu-*\'+ $shaped = @($events | ForEach-Object {+ $msg = $_.Message+ $data = Get-EventDataMap $_+ # The evaluated file, not the whole message.+ $subject = $msg+ foreach ($field in @('File Name', 'FileNameBuffer')) {+ if ($data.Contains($field) -and $data[$field]) { $subject = [string]$data[$field]; break }+ }+ $scope =+ if ($subject -like "*$tail*" -or $subject -like "*$cpuTail*") { 'llama.cpp' }+ elseif ($subject -like "*$venvTail*") { 'venv' }+ else { 'other' }+ [pscustomobject]@{+ TimeCreated = $_.TimeCreated.ToString('o')+ Id = $_.Id+ # 3077 is an enforced block; 3076 only says it would have been.+ Kind = switch ($_.Id) {+ 3076 { 'audit-would-block' }+ 3077 { 'ENFORCED-BLOCK' }+ 3089 { 'signature-detail' }+ default { 'context' }+ }+ Scope = $scope+ ScopeFrom = 'path'+ ActivityID = $_.ActivityId+ Message = $msg+ # 3089's rendered Message is the fixed string "Signature information for another event.+ EventData = $data+ }+ })+ $scopeByActivity = @{}+ foreach ($e in $shaped) {+ if ($e.Scope -ne 'other' -and $e.ActivityID -and -not $scopeByActivity.ContainsKey($e.ActivityID)) {+ $scopeByActivity[$e.ActivityID] = $e.Scope+ }+ }+ $inherited = 0+ foreach ($e in $shaped) {+ if ($e.Scope -eq 'other' -and $e.ActivityID -and $scopeByActivity.ContainsKey($e.ActivityID)) {+ $e.Scope = $scopeByActivity[$e.ActivityID]+ $e.ScopeFrom = 'correlation'+ $inherited+++ }+ }+ if ($inherited -gt 0) {+ Write-Host "$inherited event(s) scoped by ActivityID correlation rather than by path"+ }++ ConvertTo-Json -InputObject $shaped -Depth 4 |+ Set-Content -LiteralPath (Join-Path $dir 'code-integrity-events.json') -Encoding UTF8+ $shaped | Format-List | Out-String |+ Set-Content -LiteralPath (Join-Path $dir 'code-integrity-events.txt') -Encoding UTF8++ $ours = @($shaped | Where-Object { $_.Scope -ne 'other' })+ $blocks = @($ours | Where-Object { $_.Id -eq 3077 }).Count+ # A 3076 is this probe's audit verdict only when the NoISG policy it installed raised it.+ $auditApplied = $false+ $baselineForAttribution = Join-Path $dir 'baseline.json'+ if (Test-Path -LiteralPath $baselineForAttribution) {+ try {+ $auditApplied = [bool] (Get-Content -LiteralPath $baselineForAttribution -Raw | ConvertFrom-Json).AuditPolicyApplied+ } catch { $auditApplied = $false }+ }+ $isOurAudit = {+ param($e)+ $e.Id -eq 3076 -and $auditApplied -and (Test-EventDataFromPolicy $e.EventData $NOISG_GUID)+ }+ $audits = @($ours | Where-Object { & $isOurAudit $_ }).Count+ $otherPolicyAudits = @($ours | Where-Object { $_.Id -eq 3076 }).Count - $audits+ if ($otherPolicyAudits -gt 0) {+ $ourPolicy = if ($auditApplied) { 'the NoISG audit policy this probe installed' } else { 'this probe (no audit policy was applied)' }+ $collectionProblems += "$otherPolicyAudits audit event(s) (3076) on Unsloth paths did not come from $ourPolicy; they are not counted as signature verdicts, and the machine carries another audit policy that can confound this cell"+ Write-Warning "$otherPolicyAudits 3076 event(s) on Unsloth paths came from another policy and are not counted (see code-integrity-events.json)"+ }+ $foreign = @($shaped | Where-Object { $_.Scope -eq 'other' }).Count+ Write-Host "Unsloth paths: $blocks enforced block(s) (3077), $audits audit would-block(s) (3076), $($ours.Count) event(s)"+ foreach ($g in ($ours | Group-Object Scope | Sort-Object Name)) {+ $b = @($g.Group | Where-Object { $_.Id -eq 3077 }).Count+ $a = @($g.Group | Where-Object { & $isOurAudit $_ }).Count+ Write-Host (" {0,-10} {1} x 3077, {2} x 3076, {3} event(s)" -f $g.Name, $b, $a, $g.Count)+ }+ # Whether a model was actually loaded inside this window.+ $scenarioStatus = $null+ $statusPath = Join-Path $dir 'scenario-status.json'+ if (Test-Path -LiteralPath $statusPath) {+ $scenarioStatus = Get-Content -LiteralPath $statusPath -Raw | ConvertFrom-Json+ }+ $loadOk = $false+ $failedSteps = @()+ $resultsPath = Join-Path $dir 'scenario-results.json'+ if (Test-Path -LiteralPath $resultsPath) {+ $results = Get-Content -LiteralPath $resultsPath -Raw | ConvertFrom-Json+ $loadOk = [bool]$results.steps.load.ok+ $failedSteps = @($results.steps.PSObject.Properties | Where-Object { -not $_.Value.ok } | ForEach-Object { $_.Name })+ }+ $scenarioProblem = $null+ if (-not $scenarioStatus) {+ $scenarioProblem = 'no scenario-status.json: the run stage did not complete for this label, so nothing is known to have loaded inside this window and an empty event list is a NULL result, not an allow'+ } elseif ($scenarioStatus.Reason -eq 'skipped') {+ $scenarioProblem = 'the Studio scenario was skipped (-SkipStudio), so this zip is a signature inventory only: it does not show whether anything was blocked at load time'+ } elseif ($scenarioStatus.ExitCode -ne 0 -and -not $loadOk) {+ $scenarioProblem = "the Studio scenario did NOT load a model (exit $($scenarioStatus.ExitCode): $($scenarioStatus.Reason); failed steps: $($failedSteps -join ', ')), so an empty event list here is a NULL result, not an allow"+ }+ if ($scenarioProblem) { $collectionProblems += $scenarioProblem }++ # An empty window is an allow only if the policy was shown to be evaluating loads.+ $verdicts = $blocks + $audits+ $baselineForControl = Join-Path $dir 'baseline.json'+ $sacNow = Get-SacState+ if ($verdicts -eq 0 -and (Test-Path -LiteralPath $baselineForControl)) {+ $b = Get-Content -LiteralPath $baselineForControl -Raw | ConvertFrom-Json+ # Both ends of the window, and neither is redundant.+ $sacMode = [string]$sacNow.Mode+ $sacAtPrepare = [string]$b.Sac.Mode+ if ($b.AuditPolicyApplied -and $true -ne $b.AuditPolicyControlFired) {+ $collectionProblems += 'no positive control confirmed the audit policy was evaluating loads, so a window with no 3076 or 3077 here is a NULL result, not an allow'+ Write-Warning 'No Unsloth path raised a 3076 or 3077, but no positive control confirmed the audit policy was evaluating loads on this machine. Do NOT report this cell as "not blocked".'+ } elseif (-not $loadOk) {+ # Recorded as a collection problem above+ Write-Warning 'No Unsloth path raised a 3076 or 3077, but nothing was observed loading in this window (see collection-warnings.txt in the zip). Do NOT report this cell as "not blocked".'+ } elseif ($b.AuditPolicyApplied) {+ Write-Host 'no Unsloth path raised a 3076 or 3077, and the positive control confirmed the policy was evaluating loads'+ } elseif ($sacMode -ne 'enforcement' -or $sacAtPrepare -ne 'enforcement') {+ $collectionProblems += "no audit policy was applied and Smart App Control is '$sacMode' now ('$sacAtPrepare' when this label was prepared), so nothing on this machine could log a 3076 and nothing could enforce a 3077 for the whole window: a window with no verdict is a NULL result, not an allow. Re-run prepare with -AuditPolicy."+ Write-Warning "No Unsloth path raised a 3076 or 3077, but this cell ran with no audit policy and Smart App Control '$sacMode' ('$sacAtPrepare' at prepare), so no verdict could have been logged either way. Do NOT report this cell as `"not blocked`"; re-run prepare with -AuditPolicy."+ } elseif ($true -ne $b.SacControlFired) {+ # Enforcement in the registry is an intent, not an observation.+ $collectionProblems += 'no audit policy was applied and no unsigned positive control confirmed that Smart App Control actually refused code on the boot that measured, so a window with no 3077 here is a NULL result, not an allow. Re-run prepare and run from Windows PowerShell 5.1, which can build the control.'+ Write-Warning 'No Unsloth path raised a 3077 and Smart App Control reads as enforcing, but no unsigned positive control confirmed it was refusing code on this boot. Do NOT report this cell as "not blocked".'+ } else {+ Write-Host 'no Unsloth path raised a 3077, Smart App Control is enforcing, and an unsigned positive control confirmed it refuses code on this boot, so this window is a real allow'+ }+ }++ # Reported, never folded into the totals above.+ Write-Host "unrelated to Unsloth: $foreign event(s) (kept in the export, excluded from the counts)"+ Write-Host "$($shaped.Count) event(s) in the window overall"++ $windowStart = $start.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffZ')+ $query = "*[System[TimeCreated[@SystemTime>='$windowStart']]]"+ try {+ Invoke-Native 'wevtutil.exe' @('epl', $CI_LOG, (Join-Path $dir 'CodeIntegrity-Operational.evtx'), "/q:$query", '/ow:true')+ } catch {+ $collectionProblems += "raw evtx export failed, so CodeIntegrity-Operational.evtx is missing from this zip: $_"+ Write-Warning "evtx export failed: $_"+ }++ try {+ # Captured into an array first+ $detections = @(Get-MpThreatDetection -ErrorAction Stop |+ Where-Object { $_.InitialDetectionTime -ge $start } |+ Select-Object InitialDetectionTime, ThreatID, Resources)+ ConvertTo-Json -InputObject $detections -Depth 4 |+ Set-Content -LiteralPath (Join-Path $dir 'defender-detections.json') -Encoding UTF8+ Remove-Item -LiteralPath (Join-Path $dir 'defender-query-error.txt') -Force -ErrorAction SilentlyContinue+ } catch {+ # A failed query wrote the same `[]` a clean machine writes, so the evidence claimed a quarantine-free window when Defender had simply not answered.+ $_.ToString() | Set-Content -LiteralPath (Join-Path $dir 'defender-query-error.txt') -Encoding UTF8+ Remove-Item -LiteralPath (Join-Path $dir 'defender-detections.json') -Force -ErrorAction SilentlyContinue+ Write-Warning "Defender detections were NOT collected: $_. defender-query-error.txt records why; do not read the absence of detections as a clean window."+ }++ $sacNow | ConvertTo-Json -Depth 6 |+ Set-Content -LiteralPath (Join-Path $dir 'sac-state-after.json') -Encoding UTF8++ # Studio's own logs, which carry the request timings and the backend errors.+ $sources = @()+ $studioLogs = Join-Path (Resolve-StudioHomeFor $dir) 'logs'+ if (Test-Path -LiteralPath $studioLogs) { $sources += $studioLogs }+ $rawLogs = Join-Path $dir 'raw-logs'+ if (Test-Path -LiteralPath $rawLogs) { $sources += $rawLogs }+ if ($sources.Count -gt 0) {+ $python = Resolve-StudioPythonFor $dir+ if ($python) {+ $redactor = Join-Path $PSScriptRoot 'redact_logs.py'+ foreach ($source in $sources) {+ try {+ Invoke-Native $python @('-X', 'utf8', '-I', $redactor, $source, (Join-Path $dir 'studio-logs'), '--since', $start.ToString('o'))+ } catch {+ $collectionProblems += "log redaction failed for ${source}, so studio-logs\ is missing from this zip: $_"+ Write-Warning "logs under $source were not copied (redaction failed): $_"+ Remove-Item -LiteralPath (Join-Path $dir 'studio-logs') -Recurse -Force -ErrorAction SilentlyContinue+ break+ }+ }+ } else {+ # Same absence, same marker+ $collectionProblems += 'Studio logs were not copied: no managed interpreter to run the redactor, so studio-logs\ is missing from this zip'+ Write-Warning 'Studio logs were not copied: no managed interpreter to run the redactor'+ }+ }++ # Stage a copy before compressing.+ $stage = Join-Path $WorkDir ".stage-$Label"+ Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction SilentlyContinue+ New-Item -ItemType Directory -Force -Path $stage | Out-Null+ # Get-ChildItem returns absolute FullName values even for a relative -WorkDir.+ $dir = (Get-Item -LiteralPath $dir).FullName+ foreach ($item in Get-ChildItem -LiteralPath $dir -Recurse -File) {+ $rel = $item.FullName.Substring($dir.Length).TrimStart('\')+ if ($rel -like 'rollback\*' -or $rel -like 'raw-logs\*') { continue }+ $target = Join-Path $stage $rel+ New-Item -ItemType Directory -Force -Path (Split-Path $target) | Out-Null+ try {+ # FileShare::ReadWrite so a writer holding the file does not block the read, which Copy-Item cannot express.+ $src = [System.IO.File]::Open($item.FullName, [System.IO.FileMode]::Open,+ [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite)+ try {+ $dst = [System.IO.File]::Create($target)+ try { $src.CopyTo($dst) } finally { $dst.Dispose() }+ } finally { $src.Dispose() }+ } catch {+ $collectionProblems += "${rel} could not be staged and is missing from this zip: $_"+ Write-Warning "could not stage $($item.FullName): $_"+ }+ }+ if ($collectionProblems.Count -gt 0) {+ # Into the staged copy, after the loop, so it is inside the archive the operator attaches rather than only in a console they will not send.+ $collectionProblems -join "`n" |+ Set-Content -LiteralPath (Join-Path $stage 'collection-warnings.txt') -Encoding UTF8+ Write-Warning "this collection is INCOMPLETE: $($collectionProblems.Count) problem(s), recorded in collection-warnings.txt inside the zip"+ }++ $zip = Join-Path $WorkDir ("unsloth-sac-{0}-{1}-{2}.zip" -f $env:COMPUTERNAME, $Label, (Get-Date -Format 'yyyyMMdd-HHmmss'))+ try {+ Compress-Archive -Path (Join-Path $stage '*') -DestinationPath $zip -Force -ErrorAction Stop+ } catch {+ # Never announce a path Compress-Archive did not produce.+ Write-Host "::error::could not write $zip : $_"+ throw+ } finally {+ Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction SilentlyContinue+ }+ if (-not (Test-Path -LiteralPath $zip)) {+ throw "Compress-Archive reported success but $zip does not exist"+ }++ Write-Host ''+ Write-Host "evidence: $zip" -ForegroundColor Green++ # An empty window is only a result if the scenario actually ran.+ if ($loadOk) {+ if ($scenarioStatus -and $scenarioStatus.ExitCode -ne 0) {+ Write-Warning "The model loaded, so the load-time events are valid; later scenario step(s) failed: $($failedSteps -join ', ') (exit $($scenarioStatus.ExitCode))."+ }+ } elseif ($scenarioProblem) {+ Write-Warning $scenarioProblem+ Write-Warning 'Do not report this cell as "not blocked".'+ }++ Write-Host ''+ Write-Host 'Attach that zip to the pull request. It contains your user name in file paths;'+ Write-Host 'redact it if you like, but keep the file names and the rest of each path.'+ Write-Host ''+ Write-Host "When you are done: .\sac-probe.ps1 -Stage revert -Label $Label"+}++function Invoke-Revert {+ Assert-Elevated+ $dir = Get-RunDir+ $baselinePath = Join-Path $dir 'baseline.json'+ if (-not (Test-Path -LiteralPath $baselinePath)) {+ throw "no baseline at $baselinePath; nothing to revert to. Was -Label $Label used for prepare?"+ }+ $baseline = Get-Content -LiteralPath $baselinePath -Raw | ConvertFrom-Json+ Assert-BaselineIsThisMachine $baseline+ $ROLLBACK_POLICY = Get-RollbackPolicyPath $dir++ Clear-EfiOwnership++ # A baseline this script already considers spent.+ if ($baseline.RevertCompletedAt) {+ if ($script:EfiStillMounted) {+ throw "the EFI system partition is still mounted as S: and could not be unmounted; run 'mountvol S: /D' by hand"+ }+ Write-Host "label '$Label' was already reverted at $($baseline.RevertCompletedAt); this baseline is spent and nothing was changed. Run prepare again for a new run on this label."+ return+ }++ # The policy block may throw (mount, copy or CiTool).+ $policyError = $null+ if ($baseline.AuditPolicyApplied) {+ try {+ Write-Section 'Remove audit policy'+ $saved = $ROLLBACK_POLICY+ $mounted = Mount-Efi+ try {+ if ($baseline.AuditPolicyPreexisting -and -not (Test-Path -LiteralPath $saved)) {+ # Falling through to the removal branch would delete an administrator's policy and then report a completed rollback.+ throw "the baseline says a policy with $NOISG_GUID was already installed, but the saved copy is missing from $saved, so it cannot be restored. Nothing was changed; restore that .cip by hand (or remove AuditPolicyPreexisting from baseline.json once you have) and run revert again."+ }+ if ($baseline.AuditPolicyPreexisting) {+ Copy-Item -LiteralPath $saved -Destination $NOISG_DEST -Force+ Write-Host 'pre-existing audit policy restored'+ } elseif (Test-Path -LiteralPath $NOISG_DEST) {+ Remove-Item -LiteralPath $NOISG_DEST -Force+ Write-Host 'audit policy removed'+ } else {+ Write-Host 'audit policy file already absent'+ }+ # Refreshed in every branch+ Invoke-Native 'CiTool.exe' @('-r')+ Write-Host 'policy refreshed'+ } finally {+ Dismount-Efi $mounted+ }+ # Before Windows 11 24H2 a removed policy can stay active until a restart.+ $stillActive = Test-PolicyActive $NOISG_GUID+ if ($baseline.AuditPolicyPreexisting) {+ # A restored policy has to be back in force, not merely copied into place.+ if ($null -eq $stillActive) {+ throw "the pre-existing audit policy $NOISG_GUID was restored and refreshed but CiTool could not list the policies to confirm it is active; run .\sac-probe.ps1 -Stage revert -Label $Label again once CiTool -lp works"+ }+ if (-not $stillActive) {+ throw "the pre-existing audit policy $NOISG_GUID was restored and refreshed but is not active; restart Windows, then run .\sac-probe.ps1 -Stage revert -Label $Label again"+ }+ $stillActive = $false+ }+ if ($null -eq $stillActive) {+ throw "the audit policy $NOISG_GUID was removed and refreshed but CiTool could not list the policies to confirm it is gone; run .\sac-probe.ps1 -Stage revert -Label $Label again once CiTool -lp works"+ }+ if ($stillActive) {+ throw "the audit policy $NOISG_GUID was removed and refreshed but is still active; restart Windows, then run .\sac-probe.ps1 -Stage revert -Label $Label again"+ }+ # Only once the refresh succeeded and the policy is gone+ $baseline.AuditPolicyApplied = $false+ Save-ProbeBaseline $baseline (Join-Path $dir 'baseline.json')+ } catch {+ $policyError = $_+ Write-Warning "audit policy was not reverted: $_ (continuing with the other settings; run revert again)"+ }+ }++ Write-Section 'Restore CodeIntegrity log'+ $ciRestoreError = $null+ try {+ if ($null -ne $baseline.CiLogMaxSize -and $null -ne $baseline.CiLogEnabled) {+ $enabled = if ($baseline.CiLogEnabled) { 'true' } else { 'false' }+ Invoke-Native 'wevtutil.exe' @('sl', $CI_LOG, "/e:$enabled", "/ms:$($baseline.CiLogMaxSize)")+ Write-Host ("CodeIntegrity/Operational restored: enabled={0}, maxSize={1}" -f $enabled, $baseline.CiLogMaxSize)+ } else {+ Write-Host 'no CodeIntegrity log baseline recorded; left as is'+ }+ } catch {+ $ciRestoreError = $_+ Write-Warning "could not restore the CodeIntegrity log settings: $_"+ }++ Write-Section 'Restore Defender preferences'+ # Only what prepare changed, and only where a baseline value was captured.+ $restores = @(+ @{ Name = 'DisableRealtimeMonitoring'; Value = $baseline.DisableRealtimeMonitoring },+ @{ Name = 'MAPSReporting'; Value = $baseline.MAPSReporting },+ @{ Name = 'SubmitSamplesConsent'; Value = $baseline.SubmitSamplesConsent },+ @{ Name = 'CloudBlockLevel'; Value = $baseline.CloudBlockLevel },+ @{ Name = 'PUAProtection'; Value = $baseline.PUAProtection }+ )+ $failed = 0+ foreach ($r in $restores) {+ if ($null -eq $r.Value) { continue }+ try {+ $params = @{ $r.Name = $r.Value }+ Set-MpPreference @params+ } catch {+ $failed+++ Write-Warning "could not restore $($r.Name): $_"+ }+ }+ $restored = $null+ try { $restored = Get-MpPreference } catch { }+ if (-not $restored) {+ $failed+++ Write-Warning 'could not read the Defender preferences back, so this revert cannot show the machine was restored'+ } else {+ foreach ($r in $restores) {+ if ($null -eq $r.Value) { continue }+ $same = Test-MpPreferenceMatch $restored.($r.Name) $r.Value (Get-MpPreferenceType $r.Name)+ if ($true -ne $same) {+ $failed+++ Write-Warning "$($r.Name) reads back as $($restored.($r.Name)) after being restored to $($r.Value)"+ }+ }+ }+ if ($failed -eq 0) { Write-Host 'Defender preferences restored' }+ else { Write-Warning "$failed Defender preference(s) were not restored; see above" }+ # Carried to the exit status below rather than left as a console warning+ $restoreFailures = $failed++ Write-Section 'Stop the elevated Studio'+ $studioStillRunning = -not (Stop-ProbeStudio $dir)+ if ($studioStillRunning) { Write-Warning 'the Studio prepare/run started as administrator is still running; stop it by hand' }+ else { Write-Host 'no probe-started Studio left running; start Studio normally (unelevated) to use it' }++ Write-Section 'Restore Studio tree access'+ # Every stage is elevated, so a Studio that prepare installs is installed as administrator, and the trees the installer creates (llama.cpp, whisper.cpp, node, .cache) come out owned by BUILTIN\Administrators.+ $user = "$env:USERDOMAIN\$env:USERNAME"+ $override = Get-StudioHomeOverride+ $allowedRoots = @(+ $env:USERPROFILE, $override, (Get-StudioHome),+ (Get-LlamaDir), (Split-Path -Parent (Get-LlamaDir))+ ) | Where-Object { $_ } |+ ForEach-Object { try { [IO.Path]::GetFullPath($_).TrimEnd('\') } catch { $null } } |+ Where-Object { $_ } | Select-Object -Unique+ $recorded = @()+ if ($baseline.StudioInstalledByProbe) { $recorded = @($baseline.StudioInstallRoots) }+ $trees = @()+ $rejected = @()+ foreach ($path in $recorded) {+ if (-not $path) { continue }+ if (-not (Test-Path -LiteralPath $path)) { continue }+ $full = [IO.Path]::GetFullPath($path).TrimEnd('\')+ $inside = @($allowedRoots | Where-Object {+ $full -eq $_ -or $full.StartsWith($_ + '\', [StringComparison]::OrdinalIgnoreCase)+ }).Count -gt 0+ if ($inside) { $trees += $full }+ else {+ $rejected += $full+ Write-Warning "not repairing ACLs on ${full}: outside the configured install roots ($($allowedRoots -join ', ')). prepare recorded this tree, so it is administrator-owned and still unreadable to you: set the UNSLOTH_STUDIO_HOME / UNSLOTH_LLAMA_CPP_PATH this label was prepared with and run revert again."+ }+ }+ $trees = @($trees | Select-Object -Unique)+ $rejected = @($rejected | Select-Object -Unique)+ if ($trees.Count -eq 0 -and $rejected.Count -eq 0) {+ Write-Host 'nothing to repair: this run did not install Studio'+ }+ # Counted, not just warned about.+ $aclFailures = $rejected.Count+ foreach ($tree in $trees) {+ try {+ # Grants the invoking user only.+ & icacls.exe $tree /grant "${user}:(OI)(CI)F" /T /C /Q | Out-Null+ if ($LASTEXITCODE -eq 0) { Write-Host "restored $user access to $tree" }+ else {+ $aclFailures+++ Write-Warning "icacls exited $LASTEXITCODE for $tree"+ }+ } catch {+ $aclFailures+++ Write-Warning "could not restore access to ${tree}: $_"+ }+ }++ if ($null -ne $policyError) {+ throw "revert restored the log and Defender settings but the audit policy is still applied: $policyError"+ }+ Write-Host ''+ # Every restoration is attempted first, then the failures decide the exit status.+ if ($restoreFailures -gt 0 -or $null -ne $ciRestoreError -or $aclFailures -gt 0 -or $studioStillRunning -or $script:EfiStillMounted) {+ if ($null -ne $ciRestoreError) {+ Write-Warning "the $CI_LOG channel settings were not restored: $ciRestoreError"+ }+ if ($script:EfiStillMounted) {+ Write-Warning "the EFI system partition is still mounted as S:; run 'mountvol S: /D' by hand"+ }+ throw "revert did not fully restore this machine: $restoreFailures Defender preference(s), $aclFailures Studio tree ACL repair(s), $(if ($null -ne $ciRestoreError) { 'the CodeIntegrity log settings' } else { 'no log settings' })$(if ($script:EfiStillMounted) { ' and the EFI mount' }) still differ from the baseline. See the warnings above."+ }+ # Only here, past every failure check+ $baseline | Add-Member -NotePropertyName RevertCompletedAt `+ -NotePropertyValue ((Get-Date).ToString('o')) -Force+ Save-ProbeBaseline $baseline $baselinePath+ Remove-Item -LiteralPath (Get-PendingEntry $dir) -Force -ErrorAction SilentlyContinue+ Write-Host 'revert complete. Smart App Control itself was never changed by this script.'+}++switch ($Stage) {+ 'prepare' { Invoke-Prepare }+ 'run' { Invoke-Run }+ 'collect' { Invoke-Collect }+ 'revert' { Invoke-Revert }+}diff --git a/scripts/windows_sac_probe/studio_scenario.py b/scripts/windows_sac_probe/studio_scenario.pynew file mode 100644index 00000000000..3a49549d464--- /dev/null+++ b/scripts/windows_sac_probe/studio_scenario.py@@ -0,0 +1,679 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+"""Exercise a running Studio and time every request."""++from __future__ import annotations++import argparse+import json+import os+import statistics+import sys+import threading+import time+import urllib.error+import urllib.request+from pathlib import Path+from typing import Any, Optional+++DEFAULT_PORTS = list(range(8888, 8896))+++def split_model_ref(ref: str) -> tuple[str, Optional[str]]:+ """`repo:variant` into the two fields /api/inference/load takes."""+ repo, sep, variant = ref.rpartition(":")+ if not sep or not repo or "/" in variant or "\\" in variant:+ return ref, None+ return repo, variant+++class Timed:+ """Every HTTP call this script makes, with how long it took."""++ def __init__(self) -> None:+ self.calls: list[dict[str, Any]] = []+ self._lock = threading.Lock()++ def record(+ self,+ method: str,+ path: str,+ ms: float,+ status: Any,+ note: str = "",+ ) -> None:+ with self._lock:+ self.calls.append(+ {+ "at": time.strftime("%Y-%m-%dT%H:%M:%S"),+ "method": method,+ "path": path,+ "ms": round(ms, 1),+ "status": status,+ "note": note,+ }+ )++ def slowest(self, n: int = 10) -> list[dict[str, Any]]:+ with self._lock:+ return sorted(self.calls, key = lambda c: -c["ms"])[:n]+++TIMED = Timed()+++class Credentials:+ """The session login returned, renewed when the access token expires."""++ def __init__(+ self,+ access: str,+ refresh: Optional[str] = None,+ ) -> None:+ self.access = access+ self.refresh = refresh+ self._lock = threading.Lock()++ def renew(self, base_url: str, stale: str) -> bool:+ """Replace `stale`; True when a fresh access token is now held."""+ with self._lock:+ if self.access != stale:+ return True+ if not self.refresh:+ return False+ status, body = _request_once(+ base_url, "POST", "/api/auth/refresh", {"refresh_token": self.refresh}, None, 30+ )+ if status != 200 or not isinstance(body, dict) or not body.get("access_token"):+ # Only a refusal spends the token.+ if status in (400, 401, 403):+ self.refresh = None+ return False+ self.access = body["access_token"]+ self.refresh = body.get("refresh_token")+ return True+++def _bearer(token: Any) -> Optional[str]:+ return token.access if isinstance(token, Credentials) else token+++def _request(+ base_url: str,+ method: str,+ path: str,+ payload: Optional[dict] = None,+ token: Any = None,+ timeout: int = 900,+) -> tuple[int, Any]:+ """One call; an expired session is renewed and the call made once more."""+ bearer = _bearer(token)+ status, body = _request_once(base_url, method, path, payload, bearer, timeout)+ if status == 401 and isinstance(token, Credentials) and token.renew(base_url, bearer):+ status, body = _request_once(base_url, method, path, payload, token.access, timeout)+ return status, body+++def _request_once(+ base_url: str,+ method: str,+ path: str,+ payload: Optional[dict],+ token: Optional[str],+ timeout: float,+) -> tuple[int, Any]:+ headers = {"Content-Type": "application/json"}+ if token:+ headers["Authorization"] = f"Bearer {token}"+ data = json.dumps(payload).encode() if payload is not None else None+ req = urllib.request.Request(base_url + path, data = data, headers = headers, method = method)+ start = time.monotonic()+ try:+ with urllib.request.urlopen(req, timeout = timeout) as response:+ body = response.read()+ ms = (time.monotonic() - start) * 1000.0+ TIMED.record(method, path, ms, response.status)+ try:+ return response.status, json.loads(body)+ except ValueError:+ return response.status, body.decode("utf-8", "replace")+ except urllib.error.HTTPError as exc:+ ms = (time.monotonic() - start) * 1000.0+ body = exc.read().decode("utf-8", "replace")+ TIMED.record(method, path, ms, exc.code, body[:400])+ return exc.code, body+ except Exception as exc: # noqa: BLE001 - a transport failure is a result here+ ms = (time.monotonic() - start) * 1000.0+ TIMED.record(method, path, ms, "error", str(exc)[:400])+ return 0, str(exc)+++# /api/inference/load and /unload commit a 200 after about 15 seconds and pad the body so a proxy cannot time the call out+_DEFERRED_ERROR_KEY = "_deferred_error"+++def padded_route_failure(status: int, body: Any) -> Optional[str]:+ """Why a /load or /unload reply is not a success, or None when it is."""+ if status != 200:+ return str(body)[:800]+ if not isinstance(body, dict) or not body:+ return "the connection closed before the server's reply arrived (empty or truncated body)"+ deferred = body.get(_DEFERRED_ERROR_KEY)+ if isinstance(deferred, dict):+ return f"deferred {deferred.get('status_code')}: {str(deferred.get('detail'))[:700]}"+ return None+++def _stream_events(+ base_url: str,+ path: str,+ payload: dict,+ token: Any,+ timeout: int = 900,+) -> tuple[int, list[dict], Optional[str]]:+ """POST a streaming request and return every parsed `data:` object."""+ bearer = _bearer(token)+ result = _stream_events_once(base_url, path, payload, bearer, timeout)+ if result[0] == 401 and isinstance(token, Credentials) and token.renew(base_url, bearer):+ result = _stream_events_once(base_url, path, payload, token.access, timeout)+ return result+++def _stream_events_once(+ base_url: str, path: str, payload: dict, token: Optional[str], timeout: int+) -> tuple[int, list[dict], Optional[str]]:+ headers = {+ "Content-Type": "application/json",+ "Accept": "text/event-stream",+ # tool_start / tool_end carry no `choices`, so /v1/chat/completions suppresses them for external clients and emits a clean OpenAI stream+ "X-Unsloth-Events": "1",+ }+ if token:+ headers["Authorization"] = f"Bearer {token}"+ req = urllib.request.Request(+ base_url + path, data = json.dumps(payload).encode(), headers = headers, method = "POST"+ )+ start = time.monotonic()+ events: list[dict] = []+ error: Optional[str] = None+ done = False+ try:+ with urllib.request.urlopen(req, timeout = timeout) as response:+ for raw in response:+ line = raw.decode("utf-8", "replace").strip()+ if not line.startswith("data:"):+ continue+ data = line[5:].strip()+ if data == "[DONE]":+ done = True+ break+ try:+ parsed = json.loads(data)+ except ValueError:+ continue+ if not isinstance(parsed, dict):+ continue+ events.append(parsed)+ if "error" in parsed and error is None:+ detail = parsed["error"]+ message = detail.get("message") if isinstance(detail, dict) else detail+ error = f"stream error: {str(message)[:300]}"+ if error is None and not done:+ error = "stream ended without [DONE]: the turn did not complete"+ TIMED.record("POST", path, (time.monotonic() - start) * 1000.0, response.status)+ return response.status, events, error+ except urllib.error.HTTPError as exc:+ body = exc.read().decode("utf-8", "replace")+ TIMED.record("POST", path, (time.monotonic() - start) * 1000.0, exc.code, body[:400])+ return exc.code, events, body[:400]+ except Exception as exc: # noqa: BLE001 - a transport failure is a result here+ TIMED.record("POST", path, (time.monotonic() - start) * 1000.0, "error", str(exc)[:400])+ return 0, events, str(exc)[:400]+++def discover_port(explicit: Optional[int]) -> int:+ ports = [explicit] if explicit else DEFAULT_PORTS+ for port in ports:+ status, body = _request(f"http://127.0.0.1:{port}", "GET", "/api/liveness", timeout = 5)+ # The identity marker, not the status code.+ if status == 200 and isinstance(body, dict) and body.get("service") == "Unsloth UI Backend":+ return port+ raise SystemExit(+ "no Studio backend answered /api/liveness on "+ + ", ".join(str(p) for p in ports)+ + ". Start Unsloth Studio first, or pass --port."+ )+++def default_studio_home() -> str:+ """Studio's own precedence (utils/paths/storage_roots.studio_root)"""+ override = (os.environ.get("UNSLOTH_STUDIO_HOME") or "").strip()+ if not override:+ override = (os.environ.get("STUDIO_HOME") or "").strip()+ if override:+ return override+ master = (os.environ.get("UNSLOTH_HOME") or "").strip()+ if master:+ return str(Path(master).expanduser() / "studio")+ return str(Path.home() / ".unsloth" / "studio")+++def resolve_studio_home(value: str) -> Path:+ """The same normalization Studio applies"""+ home = Path(value.strip()).expanduser()+ try:+ return home.resolve()+ except (OSError, ValueError):+ return home+++def authenticate(base_url: str, home: Path, password: Optional[str]) -> Credentials:+ """Log in, rotating the bootstrap credential when this home has never been used."""+ boot_file = home / "auth" / ".bootstrap_password"+ if not password:+ raise SystemExit(+ "no password given. Pass --password (or set UNSLOTH_STUDIO_PASSWORD): on a "+ "Studio that has never been opened it becomes the account password, on one "+ "that has it must be the password you sign in with."+ )+ # An EMPTY file is a rotated installation+ bootstrap = boot_file.read_text(encoding = "utf-8").strip() if boot_file.exists() else ""+ if bootstrap:+ secret = bootstrap+ rotate = True+ else:+ secret = password+ rotate = False++ status, body = _request(+ base_url, "POST", "/api/auth/login", {"username": "unsloth", "password": secret}+ )+ if status != 200:+ raise SystemExit(f"login failed ({status}): {str(body)[:300]}")+ token = body["access_token"]+ refresh = body.get("refresh_token")++ if rotate:+ status, body = _request(+ base_url,+ "POST",+ "/api/auth/change-password",+ {"current_password": secret, "new_password": password},+ token = token,+ )+ if status != 200:+ raise SystemExit(f"password rotation failed ({status}): {str(body)[:300]}")+ token = body["access_token"]+ refresh = body.get("refresh_token")+ print(" rotated the bootstrap password to the one given with --password")+ return Credentials(token, refresh)+++STATUS_INTERVAL_S = 5.0+STATUS_READ_TIMEOUT_S = 10.0+++class StatusPoller(threading.Thread):+ """Poll /api/inference/status the way the frontend does, and time it."""++ def __init__(+ self,+ base_url: str,+ token: Any,+ interval: float = STATUS_INTERVAL_S,+ read_timeout: float = STATUS_READ_TIMEOUT_S,+ ) -> None:+ super().__init__(daemon = True)+ self.base_url = base_url+ self.token = token+ self.interval = interval+ self.read_timeout = read_timeout+ self.polls: list[tuple[float, float, bool]] = []+ self._stop_event = threading.Event()+ self.in_flight_since: Optional[float] = None++ @property+ def durations(self) -> list[float]:+ return [ms for _, ms, _ in self.polls]++ def run(self) -> None:+ while not self._stop_event.is_set():+ start = time.monotonic()+ self.in_flight_since = start+ status, body = _request(+ self.base_url,+ "GET",+ "/api/inference/status",+ token = self.token,+ timeout = self.read_timeout,+ )+ self.in_flight_since = None+ elapsed = time.monotonic() - start+ # Windows timer granularity can end a timed-out read a few ms before the timeout.+ timed_out = status == 0 and (elapsed >= self.read_timeout or "timed out" in str(body))+ self.polls.append((start, elapsed * 1000.0, timed_out))+ # A read that ran past the tick is followed at once by the tick it blocked, as the frontend's queued refresh does+ self._stop_event.wait(max(0.0, self.interval - elapsed))++ def stalls_ms(self) -> list[float]:+ """Length of each run of consecutive abandoned reads."""+ runs: list[float] = []+ run_start: Optional[float] = None+ run_end = 0.0+ for start, ms, timed_out in self.polls:+ if timed_out:+ run_start = start if run_start is None else run_start+ run_end = start + ms / 1000.0+ elif run_start is not None:+ runs.append((start + ms / 1000.0 - run_start) * 1000.0)+ run_start = None+ if run_start is not None:+ runs.append((run_end - run_start) * 1000.0)+ return runs++ def stop(self) -> None:+ self._stop_event.set()++ def in_flight_ms(self) -> Optional[float]:+ """How long the current poll has been waiting, if one is."""+ since = self.in_flight_since+ return None if since is None else (time.monotonic() - since) * 1000.0+++TOOL_REJECTED_MESSAGE = "The user declined to run this tool call."+TOOL_NOT_RUN_PREFIXES = ("Unsloth did not ", "Unsloth stopped this tool call")+TOOL_ERROR_PREFIXES = (+ "Error:",+ "Error ",+ "Search failed",+ "Execution error",+ "Blocked:",+ "Exit code",+ "Failed to fetch",+ "Failed to resolve",+ "No query provided",+)+++def tool_end_failure(result: Any) -> Optional[str]:+ """Why a tool_end did not come from an executed tool, or None if it did."""+ if not isinstance(result, str) or not result.strip():+ return "empty result"+ text = result.strip()+ if text == TOOL_REJECTED_MESSAGE:+ return "declined before running"+ if text.startswith(TOOL_ERROR_PREFIXES) or text.startswith(TOOL_NOT_RUN_PREFIXES):+ return text[:160]+ return None+++def chat(+ base_url: str,+ token: Any,+ model: str,+ prompt: str,+ *,+ tools: bool = False,+ enabled_tools: Optional[list[str]] = None,+) -> dict[str, Any]:+ payload: dict[str, Any] = {+ "model": model,+ "messages": [{"role": "user", "content": prompt}],+ "max_tokens": 256,+ "stream": False,+ }+ if tools:+ # Streamed, because tool_start / tool_end ride the stream and nothing else says a tool ran+ names = enabled_tools or ["web_search"]+ payload["stream"] = True+ payload["enable_tools"] = True+ payload["enabled_tools"] = names+ payload["tool_choice"] = {"type": "function", "function": {"name": names[0]}}+ # Nobody is at the keyboard.+ payload["permission_mode"] = "off"+ status, events, error = _stream_events(+ base_url, "/v1/chat/completions", payload, token = token+ )+ text = ""+ started: list[str] = []+ finished: list[str] = []+ failed: list[dict[str, str]] = []+ for event in events:+ kind = event.get("type")+ if kind == "tool_start":+ started.append(str(event.get("tool_name") or ""))+ elif kind == "tool_end":+ name = str(event.get("tool_name") or "")+ why = tool_end_failure(event.get("result"))+ if why is None:+ finished.append(name)+ else:+ failed.append({"tool": name, "why": why})+ for choice in event.get("choices", []) or []:+ text += (choice.get("delta") or {}).get("content") or ""+ if error:+ reason = error+ elif finished:+ reason = None+ elif failed:+ reason = "tool ended without executing: " + "; ".join(f["why"] for f in failed)[:300]+ else:+ reason = "no tool_end event: the turn executed no tool"+ return {+ "status": status,+ "ok": status == 200 and bool(finished) and error is None,+ "chars": len(text),+ "tool_calls": len(finished),+ "tools_started": started,+ "tools_run": finished,+ "tools_failed": failed,+ "text": text[:600],+ "error": reason,+ }+ status, body = _request(base_url, "POST", "/v1/chat/completions", payload, token = token)+ text = ""+ if status == 200 and isinstance(body, dict):+ for choice in body.get("choices", []) or []:+ message = choice.get("message") or {}+ text += message.get("content") or ""+ return {+ "status": status,+ "ok": status == 200 and bool(text.strip()),+ "chars": len(text),+ "tool_calls": 0,+ "text": text[:600],+ "error": None if status == 200 else str(body)[:400],+ }+++def main() -> int:+ parser = argparse.ArgumentParser(description = __doc__)+ parser.add_argument("--model", default = "unsloth/Qwen3.5-2B-MTP-GGUF:UD-Q4_K_XL")+ parser.add_argument("--out", default = ".", help = "directory for scenario-results.json")+ parser.add_argument("--port", type = int, default = None)+ parser.add_argument("--password", default = os.environ.get("SAC_PROBE_STUDIO_PASSWORD"))+ parser.add_argument(+ "--home",+ default = default_studio_home(),+ help = "Studio home (where auth/ lives); follows UNSLOTH_STUDIO_HOME like Studio does",+ )+ parser.add_argument(+ "--poll-seconds",+ type = float,+ default = 5.0,+ help = "status poll cadence; 5s matches the frontend",+ )+ args = parser.parse_args()++ out_dir = Path(args.out)+ out_dir.mkdir(parents = True, exist_ok = True)++ port = discover_port(args.port)+ base_url = f"http://127.0.0.1:{port}"+ print(f"Studio on {base_url}")++ token = authenticate(base_url, resolve_studio_home(args.home), args.password)+ print("authenticated")++ # Which llama-server Studio will run, in its own precedence+ status, body = _request(base_url, "GET", "/api/settings/llama-cpp-path", token = token)+ runtime = (+ body+ if status == 200 and isinstance(body, dict)+ else {"error": f"{status}: {str(body)[:200]}"}+ )+ (out_dir / "runtime-selection.json").write_text(json.dumps(runtime, indent = 2), encoding = "utf-8")+ print(+ f"runtime: {runtime.get('resolved_binary') or runtime.get('error') or 'unresolved'} ({runtime.get('source')})"+ )++ poller = StatusPoller(base_url, token, args.poll_seconds)+ poller.start()++ repo, variant = split_model_ref(args.model)+ results: dict[str, Any] = {+ "model": args.model,+ "model_path": repo,+ "gguf_variant": variant,+ "port": port,+ "runtime": runtime,+ "steps": {},+ }+ load_payload: dict[str, Any] = {"model_path": repo}+ if variant:+ load_payload["gguf_variant"] = variant+ try:+ # A model already resident makes /load a no-op ("already_loaded"), and then no PE is loaded inside the evidence window+ status, body = _request(+ base_url,+ "POST",+ "/api/inference/unload",+ {"model_path": repo},+ token = token,+ timeout = 300,+ )+ results["evicted_before_load"] = {"status": status, "body": str(body)[:200]}++ print(f"loading {args.model} ...")+ status, body = _request(+ base_url,+ "POST",+ "/api/inference/load",+ load_payload,+ token = token,+ timeout = 1800,+ )+ load_error = padded_route_failure(status, body)+ if load_error is None and isinstance(body, dict) and body.get("status") == "already_loaded":+ load_error = (+ "the model was already resident, so this load started no llama-server and "+ "loaded no PE; the evidence window contains nothing for it"+ )+ elif load_error is None and isinstance(body, dict) and body.get("is_gguf") is not True:+ load_error = (+ "the load answered is_gguf false, so no llama-server started and no llama.cpp PE "+ "was loaded; pass a GGUF model with -Model"+ )+ results["steps"]["load"] = {+ "status": status,+ "ok": load_error is None,+ "error": load_error,+ }+ if load_error is not None:+ print(f" load FAILED ({status}): {load_error[:400]}")+ else:+ print(" loaded")++ print("inference ...")+ results["steps"]["inference"] = chat(+ base_url,+ token,+ repo,+ "Reply with exactly one short sentence about the Antarctic.",+ )+ print(f" {results['steps']['inference']['chars']} chars")++ print("web search ...")+ results["steps"]["web_search"] = chat(+ base_url,+ token,+ repo,+ "Search the web for today's date in Reykjavik and tell me what you found.",+ tools = True,+ enabled_tools = ["web_search"],+ )+ print(f" tool calls: {results['steps']['web_search']['tool_calls']}")++ print("tool calls ...")+ results["steps"]["tool_calls"] = chat(+ base_url,+ token,+ repo,+ "Use your tools to look up what the tallest building in the world is.",+ tools = True,+ enabled_tools = ["web_search"],+ )+ print(f" tool calls: {results['steps']['tool_calls']['tool_calls']}")++ # UnloadRequest.model_path is required+ status, body = _request(+ base_url,+ "POST",+ "/api/inference/unload",+ {"model_path": repo},+ token = token,+ timeout = 300,+ )+ unload_error = padded_route_failure(status, body)+ results["steps"]["unload"] = {+ "status": status,+ "ok": unload_error is None,+ "error": unload_error,+ }+ print(+ " unloaded"+ if unload_error is None+ else f" unload FAILED ({status}): {unload_error[:200]}"+ )+ finally:+ poller.stop()+ poller.join(timeout = STATUS_READ_TIMEOUT_S + 15)++ durations = poller.durations+ in_flight = poller.in_flight_ms() if poller.is_alive() else None+ stalls = poller.stalls_ms()+ results["status_poll"] = {+ "count": len(durations),+ "in_flight_ms": None if in_flight is None else round(in_flight, 1),+ "max_ms": round(max(durations), 1) if durations else None,+ "median_ms": round(statistics.median(durations), 1) if durations else None,+ # Reads the frontend would have abandoned, and how long each run of them lasted.+ "abandoned_reads": sum(1 for _, _, t in poller.polls if t),+ "stalls_ms": [round(x, 1) for x in stalls],+ "over_10s": sum(1 for d in durations if d >= 10_000),+ "over_75s": sum(1 for x in stalls if x >= 75_000),+ }+ results["slowest_calls"] = TIMED.slowest(15)+ results["all_calls"] = TIMED.calls++ path = out_dir / "scenario-results.json"+ path.write_text(json.dumps(results, indent = 2), encoding = "utf-8")++ print()+ print("=" * 60)+ for name, step in results["steps"].items():+ print(f"{name:12s} {'ok' if step.get('ok') else 'FAILED'} ({step.get('status')})")+ poll = results["status_poll"]+ print(+ f"status polls {poll['count']}, median {poll['median_ms']} ms, max {poll['max_ms']} ms, "+ f"{poll['abandoned_reads']} abandoned at {STATUS_READ_TIMEOUT_S:.0f}s, "+ f"{poll['over_75s']} stall(s) over 75s"+ )+ print(f"written to {path}")++ return 0 if all(s.get("ok") for s in results["steps"].values()) else 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/studio/test_windows_sac_probe.py b/tests/studio/test_windows_sac_probe.pynew file mode 100644index 00000000000..e137c0df719--- /dev/null+++ b/tests/studio/test_windows_sac_probe.py@@ -0,0 +1,2543 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+"""Guards for scripts/windows_sac_probe, the Smart App Control evidence probe."""++from __future__ import annotations++import fnmatch+import functools+import importlib.util+import json+import os+import shutil+import subprocess+import sys+import threading+from pathlib import Path++import pytest+import yaml++from unsloth_pwsh_runner import run_pwsh++REPO_ROOT = Path(__file__).resolve().parents[2]+PROBE_DIR = REPO_ROOT / "scripts" / "windows_sac_probe"+WORKFLOW = REPO_ROOT / ".github" / "workflows" / "windows-llama-signature-audit.yml"+SCENARIO = PROBE_DIR / "studio_scenario.py"+PS1 = PROBE_DIR / "sac-probe.ps1"+++def _text(path):+ return Path(path).read_text(encoding = "utf-8")+++def _cut(+ text,+ start,+ end = None,+):+ return text[text.index(start) :] if end is None else text[text.index(start) : text.index(end)]+++def _ps1(start = None, end = None):+ return _text(PS1) if start is None else _cut(_text(PS1), start, end)+++def _prepare():+ return _ps1("function Invoke-Prepare", "function Get-SignatureInventory")+++def _run():+ return _ps1("function Invoke-Run", "function Invoke-Collect")+++def _collect():+ return _ps1("function Invoke-Collect", "function Invoke-Revert")+++def _revert():+ return _ps1("function Invoke-Revert")+++def _init():+ return _ps1("function Initialize-Studio", "function Save-Baseline")+++def _verdict():+ verdict = _cut(_text(WORKFLOW), " - name: Verdict\n if: always()")+ return verdict[: verdict.index(" - name: Export the CodeIntegrity events")]+++def _has(text, *needles):+ missing = [n for n in needles if n not in text]+ assert not missing, missing+++def _lacks(text, *needles):+ present = [n for n in needles if n in text]+ assert not present, present+++def _before(text, first, *later):+ for other in later:+ assert text.index(first) < text.index(other), (first, other)+++def _job():+ import yaml+ return yaml.safe_load(_text(WORKFLOW))["jobs"]["code-integrity"]+++def _step(key, value):+ return next(s for s in _job()["steps"] if s.get(key) == value)["run"]+++def _run_ps(script, *args):+ pwsh = shutil.which("pwsh")+ if pwsh is None:+ pytest.skip("pwsh is required")+ return run_pwsh(+ [pwsh, "-NoProfile", "-File", str(script), *map(str, args)],+ capture_output = True,+ text = True,+ timeout = 120,+ )+++def _assert_ok(proc):+ assert proc.returncode == 0, proc.stdout[-1500:] + proc.stderr[-1500:]+++def _drive(+ tmp_path,+ names,+ body,+ strict = True,+ **params,+):+ """Run body after defining the named sac-probe.ps1 functions from their AST."""+ head = "param([string]$Src" + "".join(f",[string]${k}" for k in params) + ")\n"+ head += (+ "$a=[System.Management.Automation.Language.Parser]::ParseFile($Src,[ref]$null,[ref]$null)\n"+ )+ if strict:+ head += "$ErrorActionPreference = 'Stop'\n"+ head += f"$want = '{','.join(names)}'.Split(',')\n"+ head += "foreach($f in $a.FindAll({$args[0] -is [System.Management.Automation.Language.FunctionDefinitionAst]},$true)){\n"+ head += " if($want -contains $f.Name){ Invoke-Expression $f.Extent.Text } }\n"+ if strict:+ head += (+ "$CI_LOG = 'Microsoft-Windows-CodeIntegrity/Operational'\nfunction Start-Sleep { }\n"+ )+ driver = tmp_path / "drive.ps1"+ driver.write_text(head + body, encoding = "utf-8")+ args = ["-Src", PS1]+ for key, value in params.items():+ args += [f"-{key}", value]+ _assert_ok(_run_ps(driver, *args))+++def _load_scenario():+ spec = importlib.util.spec_from_file_location("studio_scenario", SCENARIO)+ module = importlib.util.module_from_spec(spec)+ assert spec.loader is not None+ spec.loader.exec_module(module)+ return module+++def s():+ return _load_scenario()+++TOOL_START = {"type": "tool_start", "tool_name": "web_search"}+++def _tool_end(result):+ return {"type": "tool_end", "tool_name": "web_search", "result": result}+++def _events(+ monkeypatch,+ s,+ events,+ error = None,+):+ monkeypatch.setattr(s, "_stream_events", lambda *a, **k: (200, events, error))+++def _chat(s):+ return s.chat("http://x", "t", "m", "look it up", tools = True)+++def _bootstrap(s, tmp_path, monkeypatch, password):+ (tmp_path / "auth").mkdir()+ (tmp_path / "auth" / ".bootstrap_password").write_text(password, encoding = "utf-8")+ posted: list[tuple[str, dict]] = []++ def fake(+ base_url,+ method,+ path,+ payload = None,+ token = None,+ timeout = 900,+ ):+ posted.append((path, payload or {}))+ return 200, {"access_token": "tok"}++ monkeypatch.setattr(s, "_request", fake)+ return posted+++def _main(+ s,+ monkeypatch,+ tmp_path,+ model = "m",+ replies = None,+ events = (),+):+ """Run the scenario against a fake Studio; returns (exit code, calls, results)."""+ calls: list[tuple[str, str, dict]] = []+ answers = {+ "/api/liveness": (200, {"status": "alive", "service": "Unsloth UI Backend"}),+ "/api/auth/login": (200, {"access_token": "tok"}),+ "/api/inference/load": (200, {"status": "loaded", "is_gguf": True}),+ **(replies or {}),+ }++ def fake(+ base_url,+ method,+ path,+ payload = None,+ token = None,+ timeout = 900,+ ):+ calls.append((method, path, payload or {}))+ return answers.get(path, (200, {"status": "done"}))++ def fake_stream(+ base_url,+ path,+ payload,+ token = None,+ timeout = 900,+ ):+ calls.append(("STREAM", path, payload or {}))+ return 200, list(events), None++ monkeypatch.setattr(s, "_request", fake)+ monkeypatch.setattr(s, "_stream_events", fake_stream)+ argv = ["--model", model, "--out", tmp_path, "--port", "1", "--password", "pw"]+ argv += ["--home", tmp_path, "--poll-seconds", "0.05"]+ monkeypatch.setattr(sys, "argv", ["studio_scenario.py", *map(str, argv)])+ rc = s.main()+ results = tmp_path / "scenario-results.json"+ return rc, calls, json.loads(_text(results)) if results.exists() else None+++ "ref, expected",+ [+ ("unsloth/Qwen3.5-2B-MTP-GGUF:UD-Q4_K_XL", ("unsloth/Qwen3.5-2B-MTP-GGUF", "UD-Q4_K_XL")),+ ("unsloth/Qwen3.5-2B-GGUF", ("unsloth/Qwen3.5-2B-GGUF", None)),+ (r"C:\models\x.gguf", (r"C:\models\x.gguf", None)),+ ("C:/models/x.gguf", ("C:/models/x.gguf", None)),+ ],+)+def test_the_repo_variant_shorthand_is_split_into_the_two_load_fields(s, ref, expected):+ """/api/inference/load has no shorthand parser"""+ assert s.split_model_ref(ref) == expected+++def test_the_status_poller_does_not_shadow_thread_stop(s, monkeypatch):+ """Thread.join() calls its own internal _stop()"""+ monkeypatch.setattr(s, "_request", lambda *a, **k: (200, {}))+ poller = s.StatusPoller("http://127.0.0.1:1", "t", interval = 0.01)+ assert not isinstance(getattr(poller, "_stop", None), threading.Event)+ poller.start()+ poller.stop()+ poller.join(timeout = 5)+ assert not poller.is_alive()+ assert poller.in_flight_ms() is None+++def test_a_never_opened_studio_is_not_rotated_to_a_published_password(+ s, tmp_path, monkeypatch, capsys+):+ """The rotation is permanent and revert does not undo it"""+ posted = _bootstrap(s, tmp_path, monkeypatch, "boot-secret")+ with pytest.raises(SystemExit, match = "password"):+ s.authenticate("http://x", tmp_path, None)+ assert posted == [], "nothing may be rotated without an operator password"+ s.authenticate("http://x", tmp_path, "operators-choice")+ change = [p for p in posted if p[0] == "/api/auth/change-password"]+ assert change and change[0][1] == {+ "current_password": "boot-secret",+ "new_password": "operators-choice",+ }+ assert "operators-choice" not in capsys.readouterr().out+ assert "unsloth-sac-probe" not in _text(SCENARIO)+++def test_the_scenario_loads_with_the_variant_field_and_unloads_by_model_path(+ s, tmp_path, monkeypatch+):+ """UnloadRequest.model_path is required"""+ events = [+ TOOL_START,+ _tool_end("Reykjavik: 7 September"),+ {"choices": [{"delta": {"content": "found it"}}]},+ ]+ reply = {"choices": [{"message": {"content": "hi", "tool_calls": []}}]}+ rc, calls, results = _main(+ s,+ monkeypatch,+ tmp_path,+ "unsloth/Qwen3.5-2B-MTP-GGUF:UD-Q4_K_XL",+ {"/v1/chat/completions": (200, reply)},+ events,+ )+ assert rc == 0+ load = next(c for c in calls if c[1] == "/api/inference/load")+ assert load[2] == {"model_path": "unsloth/Qwen3.5-2B-MTP-GGUF", "gguf_variant": "UD-Q4_K_XL"}+ unloads = [c for c in calls if c[1] == "/api/inference/unload"]+ assert len(unloads) == 2, "one eviction before the load, one unload after"+ assert all(u[2] == {"model_path": "unsloth/Qwen3.5-2B-MTP-GGUF"} for u in unloads)+ chat = next(c for c in calls if c[1] == "/v1/chat/completions")+ assert chat[2]["model"] == "unsloth/Qwen3.5-2B-MTP-GGUF"+ streamed = [c for c in calls if c[0] == "STREAM"]+ assert len(streamed) == 2 and all(c[2]["stream"] is True for c in streamed)+ assert all(c[2]["tool_choice"]["function"]["name"] == "web_search" for c in streamed)+ assert results["steps"]["unload"]["ok"] is True+ assert "in_flight_ms" in results["status_poll"] and "stalls_ms" in results["status_poll"]+ assert results["gguf_variant"] == "UD-Q4_K_XL"+++def test_a_timed_out_read_that_returns_early_is_still_abandoned(s, monkeypatch):+ """Windows timer granularity can end a timed-out read a few ms before the timeout."""++ def early(+ base_url,+ method,+ path,+ payload = None,+ token = None,+ timeout = 900,+ ):+ threading.Event().wait(timeout * 0.5)+ return 0, "<urlopen error timed out>"++ monkeypatch.setattr(s, "_request", early)+ poller = s.StatusPoller("http://127.0.0.1:1", "t", interval = 0.02, read_timeout = 0.1)+ poller.start()+ threading.Event().wait(0.3)+ poller.stop()+ poller.join(timeout = 5)+ assert poller.polls and all(timed_out for _, _, timed_out in poller.polls)+++def test_the_exercise_step_leaves_the_verdict_to_judge_exit_codes():+ """Actions' pwsh exits with the last native exit code, and llama-quantize --help exits 1."""+ workflow = yaml.safe_load(_text(WORKFLOW))+ steps = [st for job in workflow["jobs"].values() for st in job["steps"]]+ exercise = next(st for st in steps if st.get("id") == "exercise")["run"].strip()+ assert exercise.splitlines()[-1].strip() == "exit 0"+++def test_the_poller_abandons_a_read_at_the_frontend_timeout_and_measures_the_stall(s, monkeypatch):+ """The frontend ticks every 5 s and abandons a status read after 10 s, so a stall is a stream of abandoned reads"""+ assert s.STATUS_READ_TIMEOUT_S == 10.0 and s.STATUS_INTERVAL_S == 5.0+ source = _text(SCENARIO)+ status_call = source[source.index('"/api/inference/status"') :]+ assert "timeout = self.read_timeout" in status_call[: status_call.index(")")]+ assert "poller.join(timeout = STATUS_READ_TIMEOUT_S + 15)" in source++ def stalled(+ base_url,+ method,+ path,+ payload = None,+ token = None,+ timeout = 900,+ ):+ threading.Event().wait(timeout)+ return 0, "timed out"++ monkeypatch.setattr(s, "_request", stalled)+ poller = s.StatusPoller("http://127.0.0.1:1", "t", interval = 0.02, read_timeout = 0.05)+ poller.start()+ threading.Event().wait(0.4)+ poller.stop()+ poller.join(timeout = 5)+ assert len(poller.polls) >= 4, "abandoned reads must be followed at once by the next"+ assert all(timed_out for _, _, timed_out in poller.polls)+ stalls = poller.stalls_ms()+ assert len(stalls) == 1 and stalls[0] >= 200, stalls+ poller.polls = [(0.0, 50.0, True), (0.06, 50.0, True), (0.2, 5.0, False), (0.3, 50.0, True)]+ assert [round(x) for x in poller.stalls_ms()] == [205, 50]+++def test_an_empty_bootstrap_file_means_rotated(s, tmp_path, monkeypatch):+ """Studio truncates .bootstrap_password on Windows when it cannot delete it, so an existence check picked the empty string over the operator's password."""+ posted = _bootstrap(s, tmp_path, monkeypatch, "")+ s.authenticate("http://x", tmp_path, "operators-choice")+ assert posted[0] == ("/api/auth/login", {"username": "unsloth", "password": "operators-choice"})+ assert not any(p[0] == "/api/auth/change-password" for p in posted)+++def test_a_model_already_resident_is_evicted_first_and_never_counts_as_loaded(+ s, tmp_path, monkeypatch+):+ """/load answers already_loaded for a resident model and starts nothing, so no PE is loaded inside the evidence window."""+ already = {"/api/inference/load": (200, {"status": "already_loaded", "model": "x"})}+ rc, calls, results = _main(s, monkeypatch, tmp_path, replies = already)+ assert rc == 1+ paths = [c[1] for c in calls]+ assert paths.index("/api/inference/unload") < paths.index("/api/inference/load")+ assert results["steps"]["load"]["ok"] is False+ assert "already resident" in results["steps"]["load"]["error"]+ assert results["evicted_before_load"]["status"] == 200+++def test_a_load_that_is_not_gguf_never_counts_as_loaded(s, tmp_path, monkeypatch):+ """A non-GGUF -Model loads through transformers, so the window holds no llama.cpp load to judge."""+ reply = {"/api/inference/load": (200, {"status": "loaded", "is_gguf": False})}+ rc, _, results = _main(s, monkeypatch, tmp_path, replies = reply)+ assert rc == 1+ assert results["steps"]["load"]["ok"] is False+ assert "is_gguf false" in results["steps"]["load"]["error"]+++def test_a_tool_end_carrying_a_refusal_or_error_is_not_an_execution(s, monkeypatch):+ """The loop emits tool_end for a declined call, a lost runtime and an interrupted call too, with the reason in `result`."""+ assert s.tool_end_failure("") is not None+ assert s.tool_end_failure(None) is not None+ assert s.tool_end_failure(s.TOOL_REJECTED_MESSAGE) == "declined before running"+ assert s.tool_end_failure(+ "Error: lost connection to llama-server before the tool call completed."+ )+ assert s.tool_end_failure('{"results": [{"title": "Burj Khalifa"}]}') is None+ _events(monkeypatch, s, [TOOL_START, _tool_end(s.TOOL_REJECTED_MESSAGE)])+ turn = _chat(s)+ assert turn["ok"] is False and turn["tools_run"] == []+ assert turn["tools_failed"][0]["why"] == "declined before running"+++def test_the_powershell_probe_collects_honestly_and_never_installs_from_run():+ ps1 = _ps1()+ _has(+ ps1,+ "Initialize-Studio $dir $false",+ "Initialize-Studio $dir $true",+ "function Initialize-Studio([string] $dir, [bool] $allowInstall)",+ "CiTool listed no policies",+ "NoMatchingEventsFound*",+ "events-collection-error.txt",+ "foreach ($r in $restores)",+ )+ _lacks(+ ps1,+ "could not be verified as active; read the 3076 count",+ 'Write-Warning "no CodeIntegrity events in the window',+ )+ assert ps1.count("Set-MpPreference @params") == 2+++def test_the_new_guard_runs_in_the_unfiltered_lint_job():+ lint = _text(REPO_ROOT / ".github" / "workflows" / "workflow-trigger-lint.yml")+ assert "tests/studio/test_windows_sac_probe.py" in lint+++def test_the_powershell_probe_restores_what_prepare_changed_and_unmounts_efi():+ ps1 = _ps1()+ # Both stages and prepare's rollback unmount an EFI only the probe mounted.+ assert ps1.count("Dismount-Efi $mounted") == 3+ _has(+ ps1,+ "mountvol.exe S: /D",+ "Invoke-Native 'CiTool.exe' @('-r')",+ "Invoke-Native 'mountvol.exe'",+ "Test-PolicyActive $NOISG_GUID",+ "AuditPolicyPreexisting",+ "preexisting-policy.cip",+ "CiLogMaxSize",+ "CiLogEnabled",+ "/ms:$($baseline.CiLogMaxSize)",+ "ConvertTo-Json -InputObject $shaped",+ "ConvertTo-Json -InputObject @($inventory)",+ "UNSLOTH_LLAMA_CPP_PATH",+ "UNSLOTH_STUDIO_HOME",+ )+ assert "Join-Path $env:USERPROFILE '.unsloth\\studio\\logs'" not in ps1+++def test_the_signature_audit_covers_every_windows_family():+ body = _text(WORKFLOW)+ _has(+ body,+ "gh release view $tag --repo unslothai/llama.cpp --json assets",+ "Where-Object { $_ -like '*windows*' -and $_ -like '*.zip' }",+ 'throw "no Windows assets on $tag"',+ "enumerated $($assets.Count) Windows asset(s) but inventoried $audited",+ )+ # A hard coded profile would silently shrink the set again.+ _lacks(+ body,+ "*windows-x64-cuda12-legacy.zip",+ "*windows-x64-rocm-gfx110X.zip",+ "*windows-arm64-cpu.zip",+ )+++def test_the_readme_does_not_claim_the_release_tag_pins_a_run():+ body = _text(PROBE_DIR / "README.md")+ assert "read\nby the installer only" in body or "read by the installer only" in body+ _has(body, "re-run the Studio installer", "$env:UNSLOTH_STUDIO_PASSWORD")+++def test_a_padded_load_reply_is_read_for_its_deferred_error(s):+ """/api/inference/load commits a 200 after 15 seconds and reports a later failure only in the body."""+ assert s.padded_route_failure(200, {"status": "loaded"}) is None+ assert s.padded_route_failure(500, {"detail": "boom"}) == "{'detail': 'boom'}"+ deferred = s.padded_route_failure(+ 200, {"_deferred_error": {"status_code": 500, "detail": "llama-server was blocked"}}+ )+ assert deferred and "llama-server was blocked" in deferred+ assert s.padded_route_failure(200, {}) is not None, "a truncated padded body is not a load"+ assert s.padded_route_failure(200, "") is not None+ assert _text(SCENARIO).count("padded_route_failure(status, body)") == 2, "both padded routes"+++def test_a_tool_turn_is_ok_only_when_a_tool_actually_ran(s, monkeypatch):+ """The non-streaming route drains the tool loop and returns the final text alone, so a model answering from memory passed as a tool turn."""+ _events(monkeypatch, s, [{"choices": [{"delta": {"content": "Burj Khalifa"}}]}])+ memory = _chat(s)+ assert memory["ok"] is False and memory["tool_calls"] == 0 and "no tool_end" in memory["error"]+ _events(monkeypatch, s, [TOOL_START, _tool_end("Burj Khalifa, 828 m")])+ ran = _chat(s)+ assert ran["ok"] is True and ran["tools_run"] == ["web_search"]+++def test_the_powershell_probe_handles_retries_skips_and_occupied_drives():+ ps1 = _ps1()+ _has(+ ps1,+ "if (-not $SkipStudio -and -not (Test-StudioResponding $Port)) { Initialize-Studio $dir $false }",+ "no window-start.txt under",+ "'S:\\EFI\\Microsoft\\Boot'",+ "ConvertTo-Json -InputObject $detections",+ "if ($UpgradePackages) {",+ "if (-not $SkipUpdates) {",+ "$baseline = Get-Content -LiteralPath $baselinePath -Raw | ConvertFrom-Json",+ "(Test-Path -LiteralPath $NOISG_DEST) -and -not $baseline.AuditPolicyApplied",+ )+ assert "(Get-Date).AddHours(-2)" not in ps1+ # winget upgrade --all is opt-in, since revert cannot undo it.+ winget = ps1.index("winget upgrade --all --accept")+ assert ps1.rfind("if ($UpgradePackages) {", 0, winget) > ps1.rfind(+ "if (-not $SkipUpdates) {", 0, winget+ )+ applied = ps1.index("$baseline.AuditPolicyApplied = $true")+ persist = ps1.index("Save-ProbeBaseline $baseline $baselinePath", applied)+ assert applied < persist < ps1.index("Invoke-Native 'CiTool.exe' @('-r')")+ locator = _ps1("function Get-StudioPython", "function Test-StudioResponding")+ assert "Get-StudioHome" in locator and "$env:UNSLOTH_STUDIO_HOME" not in locator+++def test_the_signature_audit_fails_on_any_missing_bundle():+ """A native exit code is not terminating in pwsh and a later download replaces $LASTEXITCODE."""+ block = _cut(+ _text(WORKFLOW),+ "gh release download $env:AUDIT_TAG",+ "$audited = @($rows | Group-Object Bundle).Count",+ )+ _has(+ block,+ 'Write-Host "::error::gh release download exited $LASTEXITCODE for $asset"',+ 'Write-Host "::error::$asset did not download"',+ "Get-Item (Join-Path 'bundles' $asset)",+ )+++def test_the_signature_audit_streams_one_bundle_at_a_time():+ """Seventeen Windows assets are several GB"""+ block = _cut(_text(WORKFLOW), "- name: Inventory Authenticode signatures")+ assert "Remove-Item $zip.FullName -Force" in block, "the bundle is never deleted"+ _before(+ block, "Remove-Item $zip.FullName -Force", "$audited = @($rows | Group-Object Bundle).Count"+ )+++class _FakeStream:+ def __init__(self, lines):+ self.status = 200+ self._lines = [line.encode() for line in lines]++ def __enter__(self):+ return self++ def __exit__(self, *exc):+ return False++ def __iter__(self):+ return iter(self._lines)+++def _stream(monkeypatch, s, lines):+ monkeypatch.setattr(s.urllib.request, "urlopen", lambda req, timeout = 0: _FakeStream(lines))+ return s._stream_events("http://x", "/v1/chat/completions", {"stream": True}, "t")+++def test_a_stream_that_errors_after_the_tool_ran_is_not_a_success(s, monkeypatch):+ """A failure after the status line went out arrives in band as an error frame with the 200 kept, and the stream ends without [DONE]"""+ tool_end = 'data: {"type": "tool_end", "tool_name": "web_search", "result": "found"}\n'+ error_frame = 'data: {"error": {"message": "llama-server exited", "type": "server_error"}}\n'+ status, events, error = _stream(monkeypatch, s, [tool_end, error_frame])+ assert status == 200 and error and "llama-server exited" in error+ status, events, error = _stream(monkeypatch, s, [tool_end])+ assert error and "without [DONE]" in error+ status, events, error = _stream(monkeypatch, s, [tool_end, "data: [DONE]\n"])+ assert error is None and len(events) == 1+ _events(monkeypatch, s, [_tool_end("found")], "stream error: llama-server exited")+ turn = _chat(s)+ assert turn["ok"] is False and turn["tools_run"] == ["web_search"] and "exited" in turn["error"]+++def test_the_powershell_probe_fails_closed_on_the_log_and_finishes_the_policy_refresh():+ ps1 = _ps1()+ assert "could not configure the CodeIntegrity log" not in ps1+ assert "is still disabled after wevtutil sl" in ps1+ block = _ps1("Write-Section 'Remove audit policy'", "Write-Section 'Restore CodeIntegrity log'")+ refresh = "Invoke-Native 'CiTool.exe' @('-r')"+ assert block.count(refresh) == 1+ _before(block, "audit policy file already absent", refresh)+ _before(block, refresh, "$baseline.AuditPolicyApplied = $false")+ _before(block, "Dismount-Efi $mounted", "$baseline.AuditPolicyApplied = $false")+ assert "Where-Object { $_.InitialDetectionTime -ge $start }" in ps1+++def test_a_tool_end_the_loop_closed_without_running_is_not_an_execution(s):+ """studio_tool_loop.py closes a truncated, cancelled, disabled or budget-exhausted call with a non-empty result that is neither the refusal nor an Error"""+ for result in (+ "Unsloth did not execute this tool call because the provider stopped mid-call at its output limit.",+ "Unsloth stopped this tool call before it returned, so there is no result. The tool may have already done part of its work.",+ "Unsloth did not execute this tool call because the tool is disabled.",+ "Unsloth did not run this call because an identical one had already completed.",+ ):+ assert s.tool_end_failure(result) is not None, result+ assert s.tool_end_failure("Unsloth Studio docs: https://docs.unsloth.ai") is None+++def test_studio_logs_reach_the_evidence_only_through_the_backend_redactor(tmp_path):+ """The zip is attached to an issue."""+ ps1 = _ps1()+ _lacks(ps1, "Copy-Item -LiteralPath $studioLogs", "Redact-Secrets")+ _has(ps1, "redact_logs.py", "no managed interpreter to run the redactor")+ assert "$python = Resolve-StudioPythonFor $dir" in _ps1("function Invoke-Collect")+ src = tmp_path / "logs"+ src.mkdir()+ secrets = (+ "hf_AbCdEfGhIjKlMnOpQrStUvWxYz012345",+ "opaquevalue123456",+ "horse battery staple",+ "abcdef ghijklmnop",+ "dXNlcm5hbWU6c3VwZXJzZWNyZXQ=",+ "8f3c9d1ab77e4f0a9c2b3d4e",+ )+ lines = [+ "Downloading with token hf_AbCdEfGhIjKlMnOpQrStUvWxYz012345",+ "OPENAI_API_KEY=opaquevalue123456",+ 'password="correct horse battery staple"',+ 'llama-server --api-key "abcdef ghijklmnop" --port 8080',+ "Authorization: Basic dXNlcm5hbWU6c3VwZXJzZWNyZXQ=",+ "Cookie: unsloth_session=8f3c9d1ab77e4f0a9c2b3d4e",+ "n_tokens = 4096",+ ]+ (src / "studio.log").write_text("\n".join(lines), encoding = "utf-8")+ redactor = [sys.executable, str(PROBE_DIR / "redact_logs.py"), str(src), str(tmp_path / "out")]+ redactor += ["--backend", str(REPO_ROOT / "studio" / "backend")]+ proc = subprocess.run(redactor, capture_output = True, text = True, timeout = 120)+ assert proc.returncode == 0, proc.stderr[-1500:]+ out = (tmp_path / "out" / "studio.log").read_text(encoding = "utf-8")+ _lacks(out, *secrets)+ assert "n_tokens = 4096" in out+++def test_the_powershell_probe_rejects_empty_inventories_and_keeps_reverting():+ assert "no PE files found under ${llamaDir}:" in _ps1()+ revert = _revert()+ _has(revert, "$policyError = $_", "the audit policy is still applied")+ _before(revert, "$policyError = $_", "Write-Section 'Restore CodeIntegrity log'")+ _before(revert, "Write-Section 'Restore Defender preferences'", "if ($null -ne $policyError) {")+++def test_rollback_state_is_persisted_before_the_efi_partition_changes_and_stays_out_of_the_zip():+ block = _ps1("Write-Section 'Audit policy'", "Write-Section 'Policy state after applying'")+ persist = block.index("$baseline.AuditPolicyApplied = $true")+ assert block.index("Copy-Item -LiteralPath $NOISG_DEST -Destination $ROLLBACK_POLICY") < persist+ assert (+ persist+ < block.index("Save-ProbeBaseline $baseline $baselinePath", persist)+ < block.index("Copy-Item -LiteralPath $AuditPolicy -Destination $NOISG_DEST")+ )+ ps1 = _ps1()+ _has(+ ps1,+ "Join-Path (Join-Path $dir 'rollback') 'preexisting-policy.cip'",+ "if ($rel -like 'rollback\\*' -or $rel -like 'raw-logs\\*') { continue }",+ )+ assert "Compress-Archive -Path (Join-Path $dir '*')" not in ps1+ assert "$saved = $ROLLBACK_POLICY" in _revert()+++def test_the_inventory_is_of_the_runtime_studio_resolved(s, tmp_path, monkeypatch):+ """A folder selected in Studio's settings, or LLAMA_SERVER_PATH, wins over the managed default in Studio"""+ llama = _ps1("function Get-LlamaDir", "function Resolve-LlamaDir")+ _before(llama, "$env:LLAMA_SERVER_PATH", "$env:UNSLOTH_LLAMA_CPP_PATH")+ resolve = _ps1("function Resolve-LlamaDir", "function Invoke-Native")+ _has(resolve, "runtime-selection.json", "$sel.resolved_binary")+ _before(_run(), "& python @scenarioArgs", "$llamaDir = Resolve-LlamaDir $dir")+ selection = {+ "path": "D:\\llama",+ "source": "studio",+ "resolved_binary": "D:\\llama\\llama-server.exe",+ }+ _, calls, _ = _main(+ s, monkeypatch, tmp_path, replies = {"/api/settings/llama-cpp-path": (200, selection)}+ )+ sel = json.loads(_text(tmp_path / "runtime-selection.json"))+ assert sel["resolved_binary"].endswith("llama-server.exe") and sel["source"] == "studio"+ seen = [c[1] for c in calls]+ assert seen.index("/api/settings/llama-cpp-path") < seen.index("/api/inference/load")+++def test_prepare_restarts_a_running_studio_and_only_prepare_may():+ """Studio's startup is where the venv's native modules load"""+ assert "function Stop-Studio" in _ps1()+ init = _init()+ answering = init.index("if (Test-StudioResponding $Port) {")+ assert init.index("if (-not $allowInstall) {", answering) < init.index(+ "Stop-Studio $Port", answering+ )+ stop = _ps1("function Stop-Studio", "function Initialize-Studio")+ assert "ParentProcessId = $owner" in stop, "children (llama-server, workers) are stopped first"+++def test_redirected_studio_output_and_the_scenario_console_are_redacted_too():+ _has(+ _ps1(),+ "$startLog = Join-Path (Join-Path $dir 'raw-logs') 'studio-start.log'",+ "Start-Studio $python $Port $startLog",+ "$log = Join-Path (Join-Path $dir 'raw-logs') 'studio-scenario.log'",+ "if ($rel -like 'rollback\\*' -or $rel -like 'raw-logs\\*') { continue }",+ )+ _has(_collect(), "$rawLogs = Join-Path $dir 'raw-logs'", "foreach ($source in $sources)")+++def test_sample_submission_is_opt_in():+ assert "[switch] $SendSamples" in _ps1()+ block = _ps1("Write-Section 'Raise security settings'", "Write-Section 'CodeIntegrity log'")+ _before(block, "if ($SendSamples) {", "$wanted['SubmitSamplesConsent'] = 'SendAllSamples'")+ assert block.count("SubmitSamplesConsent") == 1+++def test_collect_judges_the_load_step_not_the_exit_code():+ """A failed search, chat or unload after a working load is still a valid load-time measurement"""+ _has(+ _collect(),+ "$loadOk = [bool]$results.steps.load.ok",+ "if ($loadOk) {",+ "later scenario step(s) failed",+ "did NOT load a model",+ )+++def test_the_venv_inventory_comes_from_the_running_interpreter_and_cannot_be_empty():+ _has(+ _ps1(),+ "function Resolve-VenvDir",+ "$venvDir = Resolve-VenvDir",+ "no PE files found under $venvDir",+ )+ # collect reads run's recorded venv instead of resolving it again in this shell.+ collect = _collect()+ _has(collect, "$venvTail = ", "Get-ScopeTail (Resolve-VenvDir $dir)")+ assert "$VENV_DIR -replace" not in collect+++def test_the_readme_clones_a_durable_ref():+ body = _text(PROBE_DIR / "README.md")+ assert "--branch windows-sac-probe" not in body+ _has(body, "git clone --depth 1 https://github.com/unslothai/unsloth", "-SendSamples")+++def test_the_app_control_audit_keeps_its_positive_control():+ """No 3076 events must never be reportable as a pass on its own."""+ steps = {s.get("name", ""): s for s in _job()["steps"]}+ control = next(n for n in steps if n.startswith("Positive control"))+ _has(steps[control]["run"], "control_fired=true", "control_fired=false")+ assert steps["Verdict"]["if"] == "always() && steps.control.outputs.control_fired == 'true'"+ apply_step = next(steps[n] for n in steps if n.startswith("Apply the policy"))+ assert "not in the active policy set after refresh" in apply_step["run"]+ # Audit, never enforcement: an enforcing policy could brick the runner.+ _has(_text(WORKFLOW), "SmartAppControlAuditNoISG", "--remove-policy")+++_LISTED = '{"Policies":[{"PolicyID":"{AAAA}","FriendlyName":"X AuditNoISG","IsEnforced":true}]}'+_UNLISTED = '{"Policies":[]}'+++def _removal_step(+ tmp_path,+ name,+ remove_exit = 0,+ refresh_exit = None,+ list_exit = 0,+ listing = "",+):+ stub = "function CiTool.exe {\n"+ stub += f" if ($args -contains '--remove-policy') {{ $global:LASTEXITCODE = {remove_exit}; return 'remove' }}\n"+ if refresh_exit is not None:+ stub += f" if ($args -contains '--refresh') {{ $global:LASTEXITCODE = {refresh_exit}; return 'refresh' }}\n"+ stub += f" if ($args -contains '-json') {{ $global:LASTEXITCODE = {list_exit}; return '{listing}' }}\n"+ stub += " $global:LASTEXITCODE = 0; return 'Friendly Name: none'\n}\n$env:SAC_POLICY_ID = '{AAAA}'\n"+ script = tmp_path / f"remove_{name}.ps1"+ script.write_text(stub + _step("name", "Remove the policy"), encoding = "utf-8")+ return _run_ps(script)+++ "remove_exit, listing, code, marker",+ [+ (5, _LISTED, 1, "::error::"),+ (0, _LISTED, 0, "::warning::"),+ (0, _UNLISTED, 0, "removed and no longer active"),+ ],+ ids = ["failed", "lingering", "clean"],+)+def test_the_policy_removal_step_fails_when_citool_could_not_remove_it(+ tmp_path, remove_exit, listing, code, marker+):+ """The refresh and the listing after --remove-policy overwrote its exit code, so a failed removal reported a clean one."""+ proc = _removal_step(tmp_path, "r", remove_exit = remove_exit, listing = listing)+ assert proc.returncode == code, proc.stdout + proc.stderr+ assert marker in proc.stdout+++def test_the_inventory_root_is_the_selected_runtime_not_the_binary_directory():+ r"""<root>\build\bin\Release is a supported layout, so the parent of resolved_binary inventoried Release\ alone."""+ resolve = _ps1("function Resolve-LlamaDir", "$PE_EXT = ")+ assert resolve.index("Test-Path -LiteralPath $sel.path -PathType Container") < resolve.index(+ "return (Split-Path -Parent $sel.resolved_binary)"+ ), "the selected root wins; the binary's parent is only the direct-binary fallback"+ assert "return $sel.path" in resolve+++def test_event_scoping_matches_path_tails_literally():+ """-like reads [ and ] as pattern syntax, and a directory called [llama] is legal and supported."""+ collect = _collect()+ for name in ("$tail = ", "$venvTail = "):+ assert "Get-ScopeTail" in collect[collect.index(name) : collect.index(name) + 200], name+ assert "WildcardPattern]::Escape($trimmed) + '\\'" in _ps1()+ workflow = _text(WORKFLOW)+ verdict = _cut(workflow, "$dir = $env:RUNTIME_DIR")+ assert "WildcardPattern]::Escape" in verdict+ assert "-replace '^[A-Za-z]:', ''" in verdict, "device-form paths are matched on the tail"+ assert '$_.Message -like "*$dir*"' not in workflow+++def test_installer_trees_under_a_custom_studio_home_are_recorded_for_revert():+ """setup.ps1 resolves $NodeParent from UNSLOTH_STUDIO_HOME/STUDIO_HOME and $UnslothHome from the managed llama.cpp dir's parent."""+ init = _init()+ assert "$installRoots = @($unslothHome, $override, (Split-Path -Parent (Get-LlamaDir)))" in init+ for tree in ("'node'", "'whisper.cpp'", "'.cache'"):+ assert f"(Join-Path $_ {tree})" in init+ assert f"(Join-Path $unslothHome {tree})" not in init+++def test_trees_the_installer_created_are_recorded_even_when_the_install_fails():+ init = _init()+ warning = "Write-Warning 'Studio still not found after the installer ran."+ _before(init, "$created = @($absentBefore", warning)+ _before(init, "$b.StudioInstallRoots = @(", warning)+ # Ctrl+C mid-install skips a catch and the normal return, never a finally.+ _before(init, "$python = Install-Studio", "} finally {", "$created = @($absentBefore")+++def test_prepare_fails_when_a_running_studio_cannot_be_restarted():+ """The existing process loaded its venv native modules before the policy and the window existed."""+ init = _init()+ assert "if (-not (Stop-Studio $Port)) { return }" not in init+ stop = _cut(init, "if (-not (Stop-Studio $Port))")+ assert stop[: stop.index("}")].count("throw") == 1+++def test_each_defender_preference_is_applied_on_its_own_and_deviations_recorded():+ """One shared try meant the first policy-controlled setting threw and every later Set-MpPreference was never called."""+ block = _ps1("Write-Section 'Raise security settings'", "Write-Section 'CodeIntegrity log'")+ _has(+ block,+ "foreach ($name in $wanted.Keys)",+ "DisableRealtimeMonitoring",+ "MAPSReporting",+ "CloudBlockLevel",+ "PUAProtection",+ "$mpErrorPath = Join-Path $dir 'defender-preference-errors.txt'",+ "Remove-Item -LiteralPath $mpErrorPath",+ )+ stale = _ps1("foreach ($stale in @(")+ assert "events-collection-error.txt" in stale[: stale.index(")) {")]+++def test_an_efi_dismount_failure_is_never_reported_as_a_completed_stage():+ """The next stage's Mount-Efi finds the EFI tree already there and so never retries the unmount."""+ dismount = _ps1("function Dismount-Efi", "function Test-PolicyActive")+ assert "$script:EfiStillMounted = $true" in dismount+ assert "if ($script:EfiStillMounted) {" in _prepare()+ assert "-or $script:EfiStillMounted" in _revert()+++def test_revert_exits_nonzero_when_a_studio_tree_acl_repair_failed():+ """The ACL loop sat outside the aggregate failure accounting."""+ revert = _revert()+ assert revert.count("$aclFailures++") == 2, "both the nonzero icacls and the catch count"+ assert "$aclFailures -gt 0" in revert+ _before(revert, "$aclFailures = $rejected.Count", "$aclFailures -gt 0")+++def test_a_partial_inventory_says_so_in_the_evidence():+ """Get-ChildItem discarded the error for a subtree it could not read."""+ _has(+ _ps1(),+ "-ErrorAction SilentlyContinue -ErrorVariable enumErrors",+ "$script:InventoryErrors += ",+ )+ _has(_run(), "inventory-enumeration-errors.txt", "$script:InventoryErrors.Count -gt 0")+++def test_a_partial_collection_is_marked_inside_the_zip():+ """A console warning does not travel with the archive."""+ collect = _collect()+ # evtx export, staging, redaction, no interpreter, unverified empty window, no policy,+ # no SAC refusal shown, nothing loaded, and audits from another policy+ assert collect.count("$collectionProblems += ") == 9+ redact = _cut(collect, "$redactor = Join-Path")+ assert redact.index('$collectionProblems += "log redaction failed') < redact.index(+ "Remove-Item -LiteralPath (Join-Path $dir 'studio-logs')"+ ), "recorded before the partial redacted output is deleted"+ assert "no managed interpreter to run the redactor, so studio-logs" in collect+ warn = "Set-Content -LiteralPath (Join-Path $stage 'collection-warnings.txt')"+ _before(collect, "foreach ($item in Get-ChildItem -LiteralPath $dir -Recurse -File)", warn)+ _before(collect, warn, "Compress-Archive -Path (Join-Path $stage '*')")+ _before(+ collect,+ "could not read $CI_LOG, so the event window was not collected",+ "Remove-Item -LiteralPath (Join-Path $dir 'events-collection-error.txt')",+ )+++def test_the_app_control_verdict_cannot_pass_on_an_unread_channel():+ """SilentlyContinue turned a failed query into an empty array."""+ _has(+ _verdict(),+ "-ErrorAction Stop",+ "NoMatchingEventsFound",+ "::error::could not read the CodeIntegrity channel",+ )+++def test_the_code_integrity_artifact_carries_the_events_it_is_named_for():+ workflow = _text(WORKFLOW)+ assert "- name: Export the CodeIntegrity events" in workflow+ upload = _cut(workflow, "name: code-integrity-events")+ _has(upload, "code-integrity-events.json", "CodeIntegrity-Operational.evtx")+ export = _cut(workflow, "- name: Export the CodeIntegrity events")+ head = export[: export.index("run: |")]+ assert head.count("if: always()") == 1 and "control_fired" not in head+++def test_the_audit_channel_resize_is_verified_not_assumed():+ """A channel that was already enabled reads back enabled even when the resize failed."""+ step = _cut(_text(WORKFLOW), "- name: Require a runner that can host a policy")+ step = step[: step.index("- name: Fetch the Smart App Control audit policies")]+ _has(step, 'if ($LASTEXITCODE -ne 0) { throw "wevtutil sl $log exited', "$maxSize -lt 67108864")+++def test_acl_repair_reaches_a_custom_home_outside_the_user_profile():+ r"""An UNSLOTH_STUDIO_HOME on another volume (D:\Unsloth) is exactly where the elevated installer leaves administrator-owned trees."""+ revert = _revert()+ assert "$profileRoot" not in revert+ assert "$allowedRoots = @(" in revert+ roots = _cut(revert, "$allowedRoots = @(")+ roots = roots[: roots.index("$recorded = @()")]+ _has(roots, "$env:USERPROFILE", "$override", "(Get-StudioHome)", "(Get-LlamaDir)")+ _has(+ revert,+ "if ($baseline.StudioInstalledByProbe) { $recorded = @($baseline.StudioInstallRoots) }",+ "$full.StartsWith($_ + '\\', [StringComparison]::OrdinalIgnoreCase)",+ )+++_CONTROL_SIGNATURE = "function Test-AuditPolicyEvaluating([int[]] $AcceptIds = @(3076, 3077), [string] $FromPolicy = $null) {"+++def test_prepare_proves_the_audit_policy_actually_evaluates_loads():+ """Being in CiTool's policy list is not evidence of evaluation"""+ fn = _ps1("function Test-AuditPolicyEvaluating", "function Invoke-Prepare")+ _has(+ fn,+ "-OutputType ConsoleApplication",+ _CONTROL_SIGNATURE,+ "$AcceptIds -contains $_.Id",+ "foreach ($attempt in 1..10)",+ "Remove-Item -LiteralPath $dir -Recurse -Force -ErrorAction SilentlyContinue",+ '$dir = Join-Path $WorkDir ".control-$Label"',+ )+ prepare = _prepare()+ assert prepare.index("-not (Test-PolicyActive $NOISG_GUID)") < prepare.index(+ "$controlFired = Test-AuditPolicyEvaluating"+ ), "the control runs only once the policy is verified to be in the active set"+ _has(+ prepare,+ "if ($false -eq $controlFired) {",+ "$baseline.AuditPolicyControlFired = $controlFired",+ )+ assert "AuditPolicyControlFired = $null" in _ps1()+ _has(_collect(), "$true -ne $b.AuditPolicyControlFired", "NULL result, not an allow")+++def test_only_a_3076_or_3077_counts_as_a_verdict_for_the_null_result_warning():+ """3033 and 3090-3092 are context."""+ collect = _collect()+ _has(+ collect,+ "$verdicts = $blocks + $audits",+ "if ($verdicts -eq 0 -and (Test-Path -LiteralPath $baselineForControl))",+ )+ assert "if ($ours.Count -eq 0 -and (Test-Path -LiteralPath $baselineForControl))" not in collect+++def test_a_completed_revert_spends_its_baseline():+ """A later prepare on the same label reused the first run's snapshot."""+ assert "RevertCompletedAt = $null" in _ps1()+ _has(+ _prepare(),+ "if ($previous -and -not $previous.RevertCompletedAt) {",+ "$baseline = Save-Baseline $dir",+ )+ revert = _revert()+ assert "-NotePropertyName RevertCompletedAt" in revert+ _before(+ revert, "revert did not fully restore this machine", "-NotePropertyName RevertCompletedAt"+ )+++def test_the_app_control_verdict_polls_before_reporting_an_allow():+ """3076 delivery is asynchronous and the exercise step ends the moment llama-server exits."""+ verdict = _verdict()+ _has(+ verdict,+ "foreach ($attempt in 1..10) {",+ "if ($ours.Count -gt 0 -and $ours.Count -eq $seen) { break }",+ "Start-Sleep -Seconds 3",+ )+ _before(verdict, "foreach ($attempt in 1..10) {", '$tail -and $subject -like "*$tail*"')+++def test_the_scenario_password_is_cleared_even_when_the_run_is_interrupted():+ """Ctrl+C skips both the normal path and the catch, and the console is the operator's own."""+ run = _run()+ clear = "Remove-Item Env:\\SAC_PROBE_STUDIO_PASSWORD -ErrorAction SilentlyContinue"+ assert run.count(clear) == 2+ assert run.index("} finally {") < run.rindex(clear)+ # An inherited value is dropped before the captured one is set.+ _before(run, clear, "if ($STUDIO_PASSWORD) { $env:SAC_PROBE_STUDIO_PASSWORD")+++def test_a_custom_studio_home_is_normalized_the_way_studio_normalizes_it(s, monkeypatch):+ r"""UNSLOTH_STUDIO_HOME=~\my-studio is supported (storage_roots.studio_root calls expanduser().resolve())."""+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", " ~/my-studio ")+ monkeypatch.delenv("STUDIO_HOME", raising = False)+ assert s.resolve_studio_home(s.default_studio_home()) == Path.home() / "my-studio"+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", " ")+ monkeypatch.delenv("UNSLOTH_HOME", raising = False)+ assert s.default_studio_home() == str(Path.home() / ".unsloth" / "studio")+ monkeypatch.setenv("UNSLOTH_HOME", "~/portable")+ assert s.resolve_studio_home(s.default_studio_home()) == Path.home() / "portable" / "studio"+ ps1 = _ps1()+ _has(ps1, "function Resolve-ConfiguredPath", "function Get-StudioHomeOverride")+ assert "$override = if ($env:UNSLOTH_STUDIO_HOME)" not in ps1+ home = _ps1("function Get-StudioHome {", "function Get-LlamaDir")+ assert "$override = Get-StudioHomeOverride" in home+++def test_a_portable_unsloth_home_resolves_studio_and_its_runtime(tmp_path):+ """UNSLOTH_HOME puts studio under the master root and llama.cpp beside it, ahead of a studio home."""+ body = r"""+$env:USERPROFILE = Join-Path $Work 'profile'+foreach ($v in 'LLAMA_SERVER_PATH', 'UNSLOTH_LLAMA_CPP_PATH', 'UNSLOTH_STUDIO_HOME', 'STUDIO_HOME') { Remove-Item "Env:\$v" -ErrorAction SilentlyContinue }+$env:UNSLOTH_HOME = Join-Path $Work 'portable'+if ((Get-StudioHome) -ne (Join-Path $env:UNSLOTH_HOME 'studio')) { exit 61 }+if ((Get-LlamaDir) -ne (Join-Path $env:UNSLOTH_HOME 'llama.cpp')) { exit 62 }+$env:UNSLOTH_STUDIO_HOME = Join-Path $Work 'custom'+if ((Get-StudioHome) -ne $env:UNSLOTH_STUDIO_HOME) { exit 63 }+if ((Get-LlamaDir) -ne (Join-Path $env:UNSLOTH_HOME 'llama.cpp')) { exit 64 }+Remove-Item Env:\UNSLOTH_HOME+if ((Get-LlamaDir) -ne (Join-Path $env:UNSLOTH_STUDIO_HOME 'llama.cpp')) { exit 65 }+exit 0+"""+ names = [+ "Resolve-ConfiguredPath",+ "Get-StudioHomeOverride",+ "Get-UnslothMasterRoot",+ "Get-StudioHome",+ "Get-LlamaDir",+ ]+ _drive(tmp_path, names, body, Work = tmp_path)+++def test_a_prefix_colliding_sibling_is_not_scoped_as_the_selected_runtime():+ r"""...\llama.cpp-b10830 beside the selected ...\llama.cpp had its 3076/3077 counted as a verdict on the selected build."""+ fn = _ps1("function Get-ScopeTail", "function Get-EventDataMap")+ _has(fn, "TrimEnd('\\', '/')", "WildcardPattern]::Escape($trimmed) + '\\'")+ verdict = _cut(_text(WORKFLOW), "$dir = $env:RUNTIME_DIR")+ assert "($dir -replace '^[A-Za-z]:', '').TrimEnd('\\')) + '\\'" in verdict+++def test_a_window_with_no_audit_policy_is_a_null_result_unless_sac_enforces():+ """-AuditPolicy is optional."""+ collect = _collect()+ branch = "} elseif ($sacMode -ne 'enforcement' -or $sacAtPrepare -ne 'enforcement') {"+ _has(collect, "$sacMode = [string]$sacNow.Mode", "$sacAtPrepare = [string]$b.Sac.Mode", branch)+ guard = collect[collect.index(branch) + len(branch) :]+ guard = guard[: guard.index("} elseif ")]+ _has(guard, "$collectionProblems +=", "NULL result, not an allow")+++def test_an_empty_window_with_no_observed_load_never_reads_as_an_allow():+ """A scenario that stopped at login loaded no PE under the policy, so the positive control alone must not earn the clean-allow line."""+ collect = _collect()+ marked = "if ($scenarioProblem) { $collectionProblems += $scenarioProblem }"+ _has(collect, "$scenarioProblem = $null", marked, "} elseif (-not $loadOk) {")+ _before(collect, marked, "$stage = Join-Path $WorkDir")+ _before(collect, "$scenarioProblem = $null", "$verdicts = $blocks + $audits")+++def test_a_studio_that_never_answered_fails_prepare():+ """Start-Studio's result was discarded, so prepare printed 'prepare complete' over a Studio that never started."""+ init = _init()+ start = "Start-Studio $python $Port $startLog"+ assert "if (-not (Start-Studio $python $Port $startLog)) {" in init+ assert "| Out-Null\n}" not in init.split(start)[-1]+ # prepare fails; run only warns, because its inventories are still evidence.+ assert "if ($allowInstall) {" in init.split(start)[1]+ assert 'throw "Studio did not answer on port $Port within 5 minutes' in init+++def test_only_studio_is_treated_as_studio_on_the_port():+ """prepare force-stops whatever owns the port, and 8888 is a busy default."""+ fn = _ps1("function Test-StudioResponding", "function Get-EventDataMap")+ assert "$body.service -eq 'Unsloth UI Backend'" in fn+ assert "return $r.StatusCode -eq 200" not in fn+ main = _text(REPO_ROOT / "studio" / "backend" / "main.py")+ assert '"service": "Unsloth UI Backend"' in _cut(main, '@app.get("/api/liveness")')[:1200]+++def test_the_defender_baseline_is_read_back_not_assumed():+ """A tamper-protected or policy-managed preference is ignored rather than refused"""+ prepare = _prepare()+ _has(+ prepare,+ "$applied = Get-MpPreference",+ "but reads back as $actual",+ '$mpFailed += "${name}: set to $expected but reads back as $actual',+ )+ _before(+ prepare,+ "$applied = Get-MpPreference",+ "$mpErrorPath = Join-Path $dir 'defender-preference-errors.txt'",+ )+++def test_a_numeric_defender_readback_is_compared_not_waved_through():+ """Get-MpPreference returns CIM numbers on some builds."""+ fn = _ps1("function Test-MpPreferenceMatch", "function Get-MpPreferenceType")+ _has(+ fn,+ "[Enum]::Parse($type, [string]$expected, $true)",+ "[Enum]::Parse($type, [string]$actual, $true)",+ "return $null\n}",+ )+ assert "$cmd.Parameters[$name]" in _ps1()+ _has(+ _prepare(),+ "$same = Test-MpPreferenceMatch $actual $expected (Get-MpPreferenceType $name)",+ "} elseif ($null -eq $same) {",+ )+++def test_revert_reads_the_defender_values_back_before_spending_the_baseline():+ """An ignored restore leaves $failed at zero."""+ revert = _revert()+ assert (+ "$same = Test-MpPreferenceMatch $restored.($r.Name) $r.Value (Get-MpPreferenceType $r.Name)"+ in revert+ )+ _before(+ revert,+ "$restored = Get-MpPreference",+ "$restoreFailures = $failed",+ "-NotePropertyName RevertCompletedAt",+ )+++def test_install_roots_survive_a_prepare_retry():+ """A retry finds the first attempt's trees already present."""+ init = _init()+ assert "$b.StudioInstallRoots = @(@($b.StudioInstallRoots) + $created |" in init+ assert "$b.StudioInstallRoots = $created" not in init+++def test_an_installer_that_produced_no_interpreter_fails_prepare():+ tail = _cut(_init(), "if (-not $python) {\n # prepare cannot go on")+ _has(+ tail,+ "if ($allowInstall) {",+ "throw 'the installer ran but produced no managed interpreter",+ "Write-Warning 'Studio still not found after the installer ran.",+ )+++def test_the_ci_verdict_needs_a_runtime_that_was_actually_extracted():+ """The verdict runs on always(), so a download or expand failure left a clean verdict."""+ verdict = _verdict()+ _has(verdict, "if (-not $dir) {", "::error::the shipped runtime was never extracted")+ _before(verdict, "if (-not $dir) {", "foreach ($attempt in 1..10) {")+++def test_the_scenario_will_not_hand_its_password_to_an_unidentified_server(s, monkeypatch):+ """discover_port picks the port the operator's password is posted to, and 8888 is Jupyter's."""++ def fake(+ base_url,+ method,+ path,+ payload = None,+ token = None,+ timeout = 900,+ ):+ if base_url.endswith(":8888"):+ return 200, {"status": "alive"}+ if base_url.endswith(":8890"):+ return 200, {"status": "alive", "service": "Unsloth UI Backend"}+ return 0, "refused"++ monkeypatch.setattr(s, "_request", fake)+ assert s.discover_port(None) == 8890+ with pytest.raises(SystemExit):+ s.discover_port(8888)+++def test_an_efi_mount_this_probe_owns_is_retried_by_the_next_stage():+ """$script:EfiStillMounted dies with the process."""+ assert "$EFI_OWNED_MARKER = Join-Path $WorkDir '.efi-mounted-by-probe'" in _ps1()+ mount = _ps1("function Mount-Efi", "$script:EfiStillMounted = $false")+ _has(+ mount,+ "if (Test-Path -LiteralPath $EFI_OWNED_MARKER) {",+ "Set-Content -LiteralPath $EFI_OWNED_MARKER",+ )+ _before(mount, "Test-Path -LiteralPath $EFI_OWNED_MARKER", "return $false")+ dismount = _ps1("function Dismount-Efi", "function Test-PolicyActive")+ assert "Remove-Item -LiteralPath $EFI_OWNED_MARKER" in dismount+++def test_a_lost_preexisting_policy_backup_is_a_revert_failure():+ """Falling through to the removal branch deleted an administrator's policy."""+ revert = _revert()+ assert (+ "if ($baseline.AuditPolicyPreexisting -and -not (Test-Path -LiteralPath $saved)) {"+ in revert+ )+ guard = _cut(revert, "$baseline.AuditPolicyPreexisting -and -not")+ _before(+ guard,+ 'throw "the baseline says a policy with $NOISG_GUID',+ "Remove-Item -LiteralPath $NOISG_DEST",+ )+++def test_prepare_requires_the_log_capacity_it_asked_for():+ """The 1 MB default wraps while every venv load is audited"""+ prepare = _prepare()+ assert "$ciNow.MaxSize -lt 67108864" in prepare+ _before(prepare, "$ciNow.MaxSize -lt 67108864", "Initialize-Studio $dir $true")+++def test_run_revalidates_the_policy_and_the_control_after_a_reboot():+ """Only the file on the EFI partition survives a reboot."""+ run = _run()+ _has(+ run,+ "if (-not (Test-PolicyActive $NOISG_GUID)) {",+ "LastBootUpTime",+ "$controlFired = Test-AuditPolicyEvaluating",+ "$runBaseline.AuditPolicyControlFired = $controlFired",+ )+ _before(run, "Test-PolicyActive $NOISG_GUID", "Write-Section 'Venv signature inventory'")+++def test_a_failed_dismount_is_reclaimed_by_the_next_revert():+ """The policy block clears AuditPolicyApplied even when the dismount after the refresh failed."""+ assert "function Clear-EfiOwnership {" in _ps1()+ reclaim = _ps1("function Clear-EfiOwnership", "function Test-PolicyActive")+ # Reclaims only a drive still pointing at the partition we left; never mounts.+ assert "mountvol.exe" not in reclaim+ _has(reclaim, "Dismount-Efi $true", "Test-Path -LiteralPath 'S:\\EFI\\Microsoft\\Boot'")+ revert = _revert()+ assert "Clear-EfiOwnership" in revert+ _before(revert, "Clear-EfiOwnership", "if ($baseline.AuditPolicyApplied) {")+++def test_a_recorded_tree_revert_refuses_to_touch_is_a_rollback_failure():+ """A UNSLOTH_STUDIO_HOME set for the prepare shell only is gone after a reboot."""+ revert = _revert()+ _has(+ revert,+ "$rejected += $full",+ "$aclFailures = $rejected.Count",+ "if (-not (Test-Path -LiteralPath $path)) { continue }",+ "if ($trees.Count -eq 0 -and $rejected.Count -eq 0) {",+ )+ _before(revert, "$aclFailures = $rejected.Count", "foreach ($tree in $trees)")+++def test_an_allow_needs_live_enforcement_and_a_control_on_the_boot_that_measured():+ """Without -AuditPolicy the allow verdict rested on Sac.Mode as prepare read it."""+ collect = _collect()+ fired = "} elseif ($true -ne $b.SacControlFired) {"+ _has(+ collect,+ "$sacMode = [string]$sacNow.Mode",+ "$sacAtPrepare = [string]$b.Sac.Mode",+ fired,+ "$sacNow | ConvertTo-Json -Depth 6 |",+ )+ _before(collect, "$sacNow = Get-SacState", "$sacMode = [string]$sacNow.Mode")+ _before(collect, fired, "so this window is a real allow")+ assert "Get-SacState | ConvertTo-Json" not in collect+ assert "SacControlFired = $null" in _ps1()[: _ps1().index("function Invoke-Run")]+ prepare = _prepare()+ _has(prepare, "$sacBefore = Get-SacState", "$sacFired = Test-AuditPolicyEvaluating")+ _before(prepare, "$sacFired = Test-AuditPolicyEvaluating", "'window-start.txt'")+ _has(+ _run(),+ "} elseif ([string]$runBaseline.Sac.Mode -eq 'enforcement') {",+ "if ($sacNow.Mode -ne 'enforcement') {",+ "($true -ne $runBaseline.SacControlFired)",+ "-NotePropertyName SacControlFired",+ )+++def test_the_readme_pins_the_runtime_before_the_window_opens():+ """Installing the pinned release after prepare put loads from two releases in one window."""+ pin = _cut(+ _text(PROBE_DIR / "README.md"),+ "To pin a specific runtime for a cell",+ "## Reading the output",+ )+ _has(+ pin,+ "before `prepare`",+ "-Stage prepare -Label custom-b10715-sac-on",+ "again\nbefore `prepare`",+ )+ _before(+ pin,+ "-Stage prepare -Label custom-b10715-sac-on",+ "-Stage run -Label custom-b10715-sac-on",+ )+ assert "restart Studio, then:" not in pin+++def test_a_spent_baseline_is_never_written_back_over_the_machine():+ """revert reapplied a spent baseline, silently undoing anything changed since, including lowering Defender protections."""+ revert = _revert()+ guard = "if ($baseline.RevertCompletedAt) {"+ assert guard in revert+ _before(revert, "Clear-EfiOwnership", guard)+ _before(+ revert,+ guard,+ "Write-Section 'Restore CodeIntegrity log'",+ "if ($baseline.AuditPolicyApplied) {",+ )+++def test_the_sac_positive_control_counts_only_an_enforced_refusal():+ """The audit-policy path wants a 3076 or a 3077"""+ ps1 = _ps1()+ assert _CONTROL_SIGNATURE in ps1+ fn = _ps1("function Test-AuditPolicyEvaluating", "function Invoke-Prepare")+ assert "$AcceptIds -contains $_.Id" in fn+ assert "$_.Id -eq 3076 -or $_.Id -eq 3077" not in fn+ # Both Smart App Control call sites pin 3077; the audit-policy ones do not.+ assert ps1.count("Test-AuditPolicyEvaluating -AcceptIds @(3077)") == 2+ for stage in (_prepare(), _run()):+ _has(+ stage,+ "$controlFired = Test-AuditPolicyEvaluating -FromPolicy $NOISG_GUID\n",+ "$sacFired = Test-AuditPolicyEvaluating -AcceptIds @(3077)",+ )+ assert "without raising a 3076 or 3077, so nothing is refusing" not in stage+ assert ps1.count("without being refused with a 3077") == 2+++def test_only_the_verified_loopback_listener_is_ever_stopped():+ """-LocalPort on its own returns every listener holding that port on any local address."""+ stop = _ps1("function Stop-Studio", "function Initialize-Studio")+ assert "$_.LocalAddress -eq '127.0.0.1' -or $_.LocalAddress -eq '0.0.0.0'" in stop+ _before(stop, "LocalAddress", "Stop-Process", "if (-not $owners) {")+ assert "http://127.0.0.1:$port/api/liveness" in _ps1()+++def test_the_managed_venv_is_recorded_when_the_studio_home_already_exists():+ r"""The elevated installer creates <home>\unsloth_studio, which was in no candidate list."""+ cands = _cut(_init(), "$candidates = @(", "$absentBefore = @(")+ assert "(Join-Path (Get-StudioHome) 'unsloth_studio')" in cands+ assert "(Get-StudioHome)" in _cut(_revert(), "$allowedRoots = @(", "$recorded = @()")+++def test_run_refuses_a_label_whose_revert_already_completed():+ """revert leaves window-start.txt behind."""+ run = _run()+ guard = "if ($runBaseline.RevertCompletedAt) {"+ assert guard in run+ _before(+ run,+ guard,+ "if ($runBaseline.AuditPolicyApplied) {",+ "Write-Section 'Venv signature inventory'",+ )+ assert "if ($baseline.RevertCompletedAt) {" in _revert()+++def test_collect_scopes_the_venv_run_measured_not_the_one_this_shell_resolves():+ """A collect from a shell without the UNSLOTH_STUDIO_HOME override scoped against the legacy default."""+ assert "function Resolve-VenvDir([string] $dir) {" in _ps1()+ fn = _ps1("function Resolve-VenvDir", "function Test-StudioResponding")+ assert "$recorded = Join-Path $dir 'venv-selection.txt'" in fn+ _before(fn, "$recorded = Join-Path", "$studioPython = Get-StudioPython")+ run = _run()+ assert "$venvDir | Set-Content -LiteralPath (Join-Path $dir 'venv-selection.txt')" in run+ _before(run, "$venvDir = Resolve-VenvDir", "'venv-selection.txt'")+ stale = _cut(_prepare(), "foreach ($stale in @(")+ assert "'venv-selection.txt'" in stale[: stale.index(")) {")]+++def test_the_prepare_timestamp_is_read_back_culture_invariantly():+ """[datetime]::Parse reads the CURRENT culture, not the invariant one PowerShell stringified with."""+ run = _run()+ assert "[datetime]::Parse($runBaseline.CapturedAt)" not in run+ assert run.count("[datetime]::Parse([string]$runBaseline.CapturedAt,") == 3+ assert run.count("[cultureinfo]::InvariantCulture") == 4+ assert run.count("$bootedAt -and $preparedAt -and $bootedAt -gt $preparedAt") == 2+++def test_the_streamed_turns_opt_into_the_tool_control_frames(s, monkeypatch):+ """/v1/chat/completions emits a clean OpenAI stream for external clients"""+ backend = _text(REPO_ROOT / "studio" / "backend" / "routes" / "inference.py")+ assert 'UI_STREAM_EVENTS_HEADER = "X-Unsloth-Events"' in backend+ chat_api = (+ REPO_ROOT / "studio" / "frontend" / "src" / "features" / "chat" / "api" / "chat-api.ts"+ )+ assert '"X-Unsloth-Events": "1"' in _text(chat_api)+ seen: dict[str, str] = {}+ lines = [+ 'data: {"type": "tool_end", "tool_name": "web_search", "result": "x"}\n',+ "data: [DONE]\n",+ ]++ def fake_urlopen(req, timeout = None):+ seen.update(req.headers)+ return _FakeStream(lines)++ monkeypatch.setattr(s.urllib.request, "urlopen", fake_urlopen)+ status, events, error = s._stream_events("http://x", "/v1/chat/completions", {}, token = "t")+ assert seen.get("X-unsloth-events") == "1", seen+ assert status == 200 and error is None+ assert any(e.get("type") == "tool_end" for e in events)+++def test_collect_reads_the_studio_logs_of_the_install_run_measured():+ """Both the log root and the redactor interpreter went through Get-StudioHome."""+ _has(+ _ps1(),+ "function Resolve-StudioHomeFor([string] $dir) {",+ "function Resolve-StudioPythonFor([string] $dir) {",+ )+ helpers = _ps1("function Resolve-StudioHomeFor", "function Test-StudioResponding")+ assert helpers.count("Resolve-VenvDir $dir") == 2+ _has(helpers, "return (Get-StudioHome)", "return (Get-StudioPython)")+ collect = _collect()+ _has(+ collect,+ "$studioLogs = Join-Path (Resolve-StudioHomeFor $dir) 'logs'",+ "$python = Resolve-StudioPythonFor $dir",+ )+ assert "Join-Path (Get-StudioHome) 'logs'" not in collect+++def test_run_refuses_an_event_window_older_than_its_own_baseline():+ """A prepare that throws between the fresh baseline and the reopened window leaves an unspent baseline beside the old window-start.txt."""+ run = _run()+ _has(+ run,+ "$runStartPath = Join-Path $dir 'window-start.txt'",+ "$runStart -and $runPrepared -and $runStart -lt $runPrepared",+ )+ _before(run, "$runStartPath = Join-Path", "Write-Section 'Venv signature inventory'")+ _before(run, "if ($runBaseline.RevertCompletedAt) {", "$runStartPath = Join-Path")+ assert "$runPrepared" not in _collect(), "collect must NOT gain the same guard"+ prepare = _prepare()+ assert prepare.rindex("Test-AuditPolicyEvaluating") < prepare.index("'window-start.txt'")+++def test_the_unattended_tool_turns_never_wait_on_an_approval_nobody_reads():+ """Opting into the control frames also opens the confirm gate"""+ scenario = _text(SCENARIO)+ tools = _cut(scenario, " if tools:", ' text = ""')+ assert 'payload["permission_mode"] = "off"' in tools+ _lacks(scenario, 'payload["permission_mode"] = "full"', 'payload["bypass_permissions"]')+ models = _text(REPO_ROOT / "studio" / "backend" / "models" / "inference.py")+ assert '_KNOWN_PERMISSION_MODES = ("ask", "auto", "off", "full")' in models+ backend = _text(REPO_ROOT / "studio" / "backend" / "routes" / "inference.py")+ assert 'if mode in ("off", "full"):' in backend+++def test_a_runtime_at_the_root_of_a_volume_is_refused_not_matched_against_everything():+ r"""UNSLOTH_LLAMA_CPP_PATH=D:\ left a lone-separator tail that every path in the machine-wide channel contains."""+ fn = _ps1("function Get-ScopeTail", "function Get-EventDataMap")+ _before(fn, "if (-not $trimmed) {", "WildcardPattern]::Escape($trimmed)")+ assert "throw" in _cut(fn, "if (-not $trimmed) {", "return (")+ _has(+ fn,+ "($root -replace '^[A-Za-z]:', '').TrimEnd('\\', '/')",+ "WildcardPattern]::Escape($trimmed) + '\\'",+ )+ _has(+ _collect(),+ "$tail = Get-ScopeTail (Resolve-LlamaDir $dir)",+ "$venvTail = Get-ScopeTail (Resolve-VenvDir $dir)",+ )+++def test_revert_stops_only_the_elevated_studio_this_probe_started(tmp_path):+ """The Studio that prepare/run starts holds an administrator token."""+ _has(_revert(), "Stop-ProbeStudio $dir", "$studioStillRunning -or")+ if os.name == "nt":+ fake = tmp_path / "fakepy.cmd"+ fake.write_text("@ping -n 300 127.0.0.1 >nul\r\n")+ else:+ fake = tmp_path / "fakepy"+ fake.write_text("#!/bin/sh\nexec sleep 300\n")+ fake.chmod(0o755)+ run = tmp_path / "run"+ run.mkdir()+ body = r"""+function Get-RunDir { $Run }+function Test-StudioResponding($p){ $true }+function Start-Sleep { }+function Get-CimInstance { }+function Start-Process { param($FilePath,$ArgumentList,$RedirectStandardOutput,$RedirectStandardError,$WindowStyle,[switch]$PassThru)+ Microsoft.PowerShell.Management\Start-Process -FilePath $FilePath -ArgumentList $ArgumentList `+ -RedirectStandardOutput $RedirectStandardOutput -RedirectStandardError $RedirectStandardError -PassThru:$PassThru }+Start-Studio $Py 8888 "$Run/log" | Out-Null+$r = Get-Content "$Run/probe-studio.json" -Raw | ConvertFrom-Json+if (-not (Stop-ProbeStudio $Run)) { exit 11 }+if (Get-Process -Id $r.Id -ErrorAction SilentlyContinue) { exit 12 }+Start-Studio $Py 8888 "$Run/log" | Out-Null+$r = Get-Content "$Run/probe-studio.json" -Raw | ConvertFrom-Json+@{ Id = $r.Id; StartTicks = 1 } | ConvertTo-Json | Set-Content "$Run/probe-studio.json"+[void](Stop-ProbeStudio $Run)+$alive = [bool](Get-Process -Id $r.Id -ErrorAction SilentlyContinue)+Stop-Process -Id $r.Id -Force -ErrorAction SilentlyContinue+if (-not $alive) { exit 13 }+exit 0+"""+ names = ["Start-Studio", "Stop-ProcessTree", "Stop-ProbeStudio"]+ _drive(tmp_path, names, body, strict = False, Run = run, Py = fake)+++def test_run_refuses_a_label_that_was_never_prepared():+ """Get-RunDir creates the directory, so a new or mistyped -Label reached run empty."""+ run = _run()+ guard = "-not (Test-Path -LiteralPath (Join-Path $dir 'baseline.json'))"+ assert "-not (Test-Path -LiteralPath (Join-Path $dir 'window-start.txt'))" in run+ _before(+ run,+ guard,+ "throw \"label '$Label' has no baseline.json",+ "Initialize-Studio $dir $false",+ "Write-Section 'Venv signature inventory'",+ )+++def test_a_second_studio_launch_stops_the_first_probe_studio():+ """probe-studio.json holds one record."""+ fn = _ps1("function Start-Studio", "function Stop-Studio")+ stop = "if (-not (Stop-ProbeStudio (Get-RunDir))) {"+ _before(fn, stop, "$proc = Start-Process", "'probe-studio.json'")+ assert "throw" in _cut(fn, stop, "$proc = Start-Process")+++def test_a_reused_label_never_archives_an_earlier_upgrade_transcript():+ """collect stages the whole run directory, and the stale sweep runs after the winget block."""+ _before(+ _prepare(),+ "Remove-Item -LiteralPath (Join-Path $dir 'winget-upgrade.log')",+ "if ($UpgradePackages) {",+ "Tee-Object -FilePath (Join-Path $dir 'winget-upgrade.log')",+ )+++def test_events_are_scoped_by_the_evaluated_file_not_the_requesting_process():+ """A 3076/3077 message names both the requesting process and the file."""+ shaped = _cut(_collect(), "$shaped = @($events", "$scopeByActivity = @{}")+ _has(+ shaped,+ "foreach ($field in @('File Name', 'FileNameBuffer'))",+ 'if ($subject -like "*$tail*" -or',+ 'elseif ($subject -like "*$venvTail*")',+ "$subject = $msg",+ "EventData = $data",+ )+ assert "$msg -like" not in shaped+++def test_the_app_control_verdict_scopes_by_the_evaluated_file(tmp_path):+ """Matching the whole 3076 message counted an in-runtime llama-server loading an outside file as a runtime file blocked."""+ verdict = _verdict()+ start = verdict.index(" $ours = @($events | Where-Object {")+ end = verdict.index(" })\n", start) + len(" })\n")+ snippet = verdict[start:end]+ assert "$_.Message -like" not in snippet+ _has(+ snippet,+ "'File Name'",+ "'FileNameBuffer'",+ "([xml] $_.ToXml()).Event.EventData.Data",+ '$tail -and $subject -like "*$tail*"',+ )+ driver = tmp_path / "drive.ps1"+ driver.write_text(+ r"""+param([string]$Snippet)+$fromPolicy = { $true }+function New-Ev([string]$msg, [hashtable]$data) {+ $x = '<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event"><EventData>'+ foreach ($k in $data.Keys) { $x += "<Data Name='$k'>$([Security.SecurityElement]::Escape($data[$k]))</Data>" }+ $x += '</EventData></Event>'+ $o = [pscustomobject]@{ Message = $msg; Tag = '' }+ $o | Add-Member -MemberType ScriptMethod -Name ToXml -Value ([scriptblock]::Create("'" + $x.Replace("'", "''") + "'"))+ $o+}+$tail = [Management.Automation.WildcardPattern]::Escape('\a\rt') + '\'+$rt = '\Device\HarddiskVolume3\a\rt\'+$out = '\Device\HarddiskVolume3\elsewhere\x.dll'+$e1 = New-Ev "Process $($rt)llama-server.exe attempted to load $out" @{ 'File Name' = $out; 'Process Name' = "$($rt)llama-server.exe" }+$e1.Tag = 'outside'+$e2 = New-Ev "Process C:\w\pwsh.exe attempted to load $($rt)ggml.dll" @{ 'File Name' = "$($rt)ggml.dll"; 'Process Name' = 'C:\w\pwsh.exe' }+$e2.Tag = 'inside'+$e3 = New-Ev "Process $($rt)llama-server.exe attempted to load $out" @{ 'FileNameBuffer' = $out }+$e3.Tag = 'outside-buffer'+$e4 = New-Ev "no data, loaded $($rt)cuda.dll" @{ }+$e4.Tag = 'fallback'+$events = @($e1, $e2, $e3, $e4)+. ([scriptblock]::Create($Snippet))+($ours | ForEach-Object Tag) -join ','+""",+ encoding = "utf-8",+ )+ proc = _run_ps(driver, "-Snippet", snippet)+ _assert_ok(proc)+ assert proc.stdout.strip() == "inside,fallback", proc.stdout + proc.stderr+++def test_a_studio_whose_record_cannot_be_written_is_stopped_and_fails(tmp_path):+ """An elevated Studio with no probe-studio.json is one revert can neither stop nor report."""+ body = r"""+$global:stopped = @()+function Get-RunDir { $Run }+function Stop-ProbeStudio($d){ $true }+function Test-StudioResponding($p){ $true }+function Start-Sleep { }+function Stop-ProcessTree([int]$id){ $global:stopped += $id }+function Start-Process { [pscustomobject]@{ Id = 4242; StartTime = [datetime]::UtcNow } }+function Set-Content { throw 'disk full' }+$threw = $false+try { Start-Studio 'py' 8888 "$Run/log" | Out-Null } catch { $threw = $true; Write-Host $_ }+if (-not $threw) { exit 21 }+if ($global:stopped -notcontains 4242) { exit 22 }+exit 0+"""+ _drive(tmp_path, ["Start-Studio"], body, strict = False, Run = tmp_path)+++def test_the_audit_policy_control_needs_an_event_from_the_audit_policy_itself(tmp_path):+ """On a Smart App Control enforcing machine the unsigned control is refused by Smart App Control's own policy with a 3077 whether or not the audit policy evaluates anything."""+ for stage in (_prepare(), _run()):+ _has(+ stage,+ "$controlFired = Test-AuditPolicyEvaluating -FromPolicy $NOISG_GUID",+ "$sacFired = Test-AuditPolicyEvaluating -AcceptIds @(3077)",+ )+ body = r"""+$WorkDir = $Work; $Label = 't'+$NOISG = '{5283AC0F-FFF1-49AE-ADA1-8A933130CAD6}'+function Add-Type { param($TypeDefinition,$OutputAssembly,$OutputType)+ Set-Content -LiteralPath $OutputAssembly -Value "#!/bin/sh`ntrue"; chmod +x $OutputAssembly }+function New-Ev([int]$id, [hashtable]$data) {+ $x = '<Event><EventData>' + (($data.GetEnumerator() | ForEach-Object { "<Data Name='$($_.Key)'>$($_.Value)</Data>" }) -join '') + '</EventData></Event>'+ $e = [pscustomobject]@{ Id = $id; Message = 'a process attempted to load C:\x\unsigned-control.exe' }+ $e | Add-Member -MemberType ScriptMethod -Name ToXml -Value ({ $x }.GetNewClosure())+ $e }+$global:evs = @(New-Ev 3077 @{ 'File Name' = 'C:\x\unsigned-control.exe'; PolicyGUID = '{0283AC0F-FFF1-49AE-ADA1-8A933130CAD6}'; PolicyNameBuffer = 'VerifiedAndReputableDesktop' })+function Get-WinEvent { $global:evs }+if ($true -eq (Test-AuditPolicyEvaluating -FromPolicy $NOISG)) { exit 31 }+if ($true -ne (Test-AuditPolicyEvaluating -AcceptIds @(3077))) { exit 32 }+$global:evs = @(New-Ev 3076 @{ 'File Name' = 'C:\x\unsigned-control.exe'; PolicyGUID = $NOISG.ToLower() })+if ($true -ne (Test-AuditPolicyEvaluating -FromPolicy $NOISG)) { exit 33 }+$global:evs = @(New-Ev 3076 @{ 'File Name' = 'C:\x\unsigned-control.exe'; PolicyNameBuffer = 'VerifiedAndReputableDesktopEvaluationAuditNoISG' })+if ($true -ne (Test-AuditPolicyEvaluating -FromPolicy $NOISG)) { exit 34 }+exit 0+"""+ names = [+ "Get-EventDataMap",+ "Test-EventFromPolicy",+ "Test-EventDataFromPolicy",+ "Test-AuditPolicyEvaluating",+ ]+ _drive(tmp_path, names, body, Work = tmp_path)+++def test_collect_waits_for_code_integrity_delivery_to_settle(tmp_path):+ """The channel is written asynchronously, so a single early snapshot could grade zero events."""+ collect = _collect()+ assert "$events = @(Read-SettledCiEvents $start $CI_EVENT_IDS)" in collect+ assert "Get-WinEvent -FilterHashtable" not in collect[: collect.index("$shaped = @($events")]+ body = r"""+$global:reads = 0+$global:script = @('none', 1, 3, 3, 3)+function Get-WinEvent { param($FilterHashtable, $ErrorAction)+ $n = $global:script[[math]::Min($global:reads, $global:script.Count - 1)]; $global:reads+++ if ($n -eq 'none') { Write-Error -ErrorId 'NoMatchingEventsFound' -Message 'No events were found' -ErrorAction Stop }+ if ($n -eq 'denied') { Write-Error -ErrorId 'AccessDenied' -Message 'denied' -ErrorAction Stop }+ foreach ($i in 1..$n) { [pscustomobject]@{ Id = 3076 } }+ [pscustomobject]@{ Id = 3000 } }+$got = @(Read-SettledCiEvents ([datetime]::UtcNow) @(3076, 3077))+if ($got.Count -ne 3) { Write-Host "got $($got.Count) after $global:reads reads"; exit 41 }+# Two equal empty reads 3 s apart are not settled: polling runs at least the 30 s floor.+$global:slept = 0+function Start-Sleep { param([int]$Seconds) $global:slept += $Seconds }+$global:reads = 0; $global:script = @('none', 'none', 'none', 'none', 'none', 1)+$got = @(Read-SettledCiEvents ([datetime]::UtcNow) @(3076, 3077))+if ($got.Count -ne 1) { Write-Host "late record missed: got $($got.Count) after $global:reads reads"; exit 44 }+if ($global:slept -lt 30) { Write-Host "settled after only $global:slept s"; exit 45 }+$global:reads = 0; $global:slept = 0; $global:script = @(1..100)+[void](Read-SettledCiEvents ([datetime]::UtcNow) @(3076))+if ($global:reads -gt 25 -or $global:slept -gt 75) { exit 46 }+$global:reads = 0; $global:script = @(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)+$got = @(Read-SettledCiEvents ([datetime]::UtcNow) @(3076) -Attempts 5)+if ($global:reads -ne 5 -or $got.Count -ne 5) { exit 42 }+$global:reads = 0; $global:script = @('denied')+$threw = $false+try { [void](Read-SettledCiEvents ([datetime]::UtcNow) @(3076)) } catch { $threw = $true }+if (-not $threw) { exit 43 }+exit 0+"""+ _drive(tmp_path, ["Read-SettledCiEvents"], body, Work = tmp_path)+++def test_the_ci_verdict_needs_a_completed_exercise_before_an_allow():+ """A --version that exited non-zero without raising a 3076 used to reach the clean verdict."""+ exercise = _cut(_text(WORKFLOW), " - name: Load the shipped runtime under the policy")+ exercise = exercise[: exercise.index(" - name: Verdict")]+ assert '"EXERCISE_EXIT=$code"' in exercise+ _before(exercise, "$code = $LASTEXITCODE", '"EXERCISE_EXIT=$code"')+ verdict = _verdict()+ gate = "if ($ours.Count -eq 0 -and $env:EXERCISE_EXIT -ne '0') {"+ _before(verdict, "foreach ($attempt in 1..10) {", gate)+ _before(+ verdict,+ gate,+ "No binary in the shipped runtime would be refused",+ '$summary = "## App Control audit (signature-only)',+ )+ assert "exit 1" in _cut(verdict, gate, '$summary = "## App Control audit')+++def test_collect_counts_only_the_installed_policys_audit_events(tmp_path):+ """Another audit-mode policy already on the machine logs 3076s too."""+ collect = _collect()+ _has(+ collect,+ "Test-EventDataFromPolicy $e.EventData $NOISG_GUID",+ "$audits = @($ours | Where-Object { & $isOurAudit $_ }).Count",+ '$collectionProblems += "$otherPolicyAudits audit event(s)',+ )+ assert "$audits = @($ours | Where-Object { $_.Id -eq 3076 }).Count" not in collect+ start = collect.index(" $isOurAudit = {")+ predicate = collect[start : collect.index("\n }\n", start) + 6]+ body = r"""+$NOISG = '{5283AC0F-FFF1-49AE-ADA1-8A933130CAD6}'+$ours = [ordered]@{ 'File Name' = 'C:\s\llama.cpp\ggml.dll'; PolicyGUID = $NOISG.ToLower() }+$byName = [ordered]@{ 'File Name' = 'C:\s\llama.cpp\ggml.dll'; PolicyNameBuffer = 'VerifiedAndReputableDesktopEvaluationAuditNoISG' }+$other = [ordered]@{ 'File Name' = 'C:\s\llama.cpp\ggml.dll'; PolicyGUID = '{11111111-2222-3333-4444-555555555555}'; PolicyNameBuffer = 'ContosoAllowList' }+if ($true -ne (Test-EventDataFromPolicy $ours $NOISG)) { exit 51 }+if ($true -ne (Test-EventDataFromPolicy $byName $NOISG)) { exit 52 }+if ($true -eq (Test-EventDataFromPolicy $other $NOISG)) { exit 53 }+if ($true -eq (Test-EventDataFromPolicy $null $NOISG)) { exit 54 }+# Another policy with a matching name but its own ID is not ours: the name only stands in for a missing ID.+$lookalike = [ordered]@{ 'File Name' = 'C:\s\llama.cpp\ggml.dll'; PolicyGUID = '{11111111-2222-3333-4444-555555555555}'; PolicyNameBuffer = 'OtherAuditNoISG' }+if ($true -eq (Test-EventDataFromPolicy $lookalike $NOISG)) { exit 55 }+"""+ body += (+ predicate+ + r"""+$NOISG_GUID = $NOISG+$evOurs = [pscustomobject]@{ Id = 3076; EventData = $ours }+$evOther = [pscustomobject]@{ Id = 3076; EventData = $other }+$auditApplied = $true+if ($true -ne (& $isOurAudit $evOurs)) { exit 55 }+if ($true -eq (& $isOurAudit $evOther)) { exit 56 }+$auditApplied = $false+if ($true -eq (& $isOurAudit $evOurs)) { exit 57 }+if ($true -eq (& $isOurAudit $evOther)) { exit 58 }+exit 0+"""+ )+ _drive(tmp_path, ["Test-EventDataFromPolicy"], body, Work = tmp_path)+++def test_a_baseline_write_that_dies_keeps_the_previous_snapshot(tmp_path):+ """revert restores from baseline.json, so a rewrite that fails part way must leave the last good snapshot."""+ ps1 = _ps1()+ rest = ps1.replace(_ps1("function Save-ProbeBaseline", "function Test-EventFromPolicy"), "")+ assert "ConvertTo-Json -Depth 6 | Set-Content" not in rest+ assert rest.count("Save-ProbeBaseline ") >= 9+ body = r"""+$path = Join-Path $Work 'baseline.json'+Save-ProbeBaseline ([pscustomobject]@{ Label = 'first'; AuditPolicyApplied = $true }) $path+if ((Get-Content -LiteralPath $path -Raw | ConvertFrom-Json).Label -ne 'first') { exit 61 }+Save-ProbeBaseline ([pscustomobject]@{ Label = 'second'; AuditPolicyApplied = $true }) $path+if ((Get-Content -LiteralPath $path -Raw | ConvertFrom-Json).Label -ne 'second') { exit 62 }+if (Test-Path -LiteralPath "$path.tmp") { exit 63 }+function Set-Content {+ param([string]$LiteralPath, [string]$Encoding, [Parameter(ValueFromPipeline = $true)]$InputObject)+ process {+ [System.IO.File]::WriteAllText($LiteralPath, '{"Lab')+ throw 'disk full'+ }+}+try { Save-ProbeBaseline ([pscustomobject]@{ Label = 'third' }) $path; exit 64 } catch { }+$after = Get-Content -LiteralPath $path -Raw | ConvertFrom-Json+if ($after.Label -ne 'second' -or $true -ne $after.AuditPolicyApplied) { exit 65 }+exit 0+"""+ _drive(tmp_path, ["Save-ProbeBaseline"], body, Work = tmp_path)+++def test_collect_reads_the_studio_home_run_recorded(tmp_path):+ """With a custom home that has no interpreter of its own, the venv is the legacy one while logs go under the configured home."""+ run = _run()+ assert "Get-StudioHome | Set-Content -LiteralPath (Join-Path $dir 'studio-home.txt')" in run+ assert "'venv-selection.txt', 'studio-home.txt'," in _ps1()+ body = r"""+$legacyHome = Join-Path $Work 'legacy-home'+$script:legacyVenv = Join-Path $legacyHome 'unsloth_studio'+function Resolve-VenvDir([string] $dir) { return $script:legacyVenv }+function Get-StudioHome { return 'C:\live' }+$d = Join-Path $Work 'label'+New-Item -ItemType Directory -Force -Path $d | Out-Null+if ((Resolve-StudioHomeFor $d) -ne $legacyHome) { exit 71 }+Set-Content -LiteralPath (Join-Path $d 'studio-home.txt') -Value 'D:\custom-home' -Encoding UTF8+if ((Resolve-StudioHomeFor $d) -ne 'D:\custom-home') { exit 72 }+exit 0+"""+ _drive(tmp_path, ["Resolve-StudioHomeFor"], body, Work = tmp_path)+++def test_a_stall_is_measured_through_the_read_that_ended_it(s):+ """Seven abandoned 10 s reads and a reply 6 s into the next one is a 76 s stall, past the watchdog's ~75 s budget."""+ poller = s.StatusPoller("http://127.0.0.1:1", "t")+ poller.polls = [(10.0 * i, 10_000.0, True) for i in range(7)] + [(70.0, 6_000.0, False)]+ assert [round(x) for x in poller.stalls_ms()] == [76_000]+++def test_the_tool_error_prefixes_mirror_the_backend_set(s):+ """The loop reports a failed tool with any of the backend's error prefixes, not only "Error:"."""+ import ast++ parser = REPO_ROOT / "studio" / "backend" / "core" / "inference" / "tool_call_parser.py"+ backend = next(+ ast.literal_eval(node.value)+ for node in ast.parse(_text(parser)).body+ if isinstance(node, ast.Assign)+ and any(getattr(t, "id", None) == "TOOL_ERROR_PREFIXES" for t in node.targets)+ )+ assert tuple(s.TOOL_ERROR_PREFIXES) == tuple(backend)+ for result in (+ *(prefix + " something went wrong" for prefix in backend),+ "Search failed: HTTP 429",+ "Execution error: NameError",+ "Blocked: the sandbox refused this path",+ "Failed to fetch https://example.com",+ ):+ assert s.tool_end_failure(result) is not None, result+++def test_an_expired_session_is_renewed_with_the_refresh_token(s, tmp_path, monkeypatch):+ """Studio's access token lasts 60 minutes and a scenario can outlive it"""+ live = {"access": "a1", "refresh": "r1"}+ refreshes: list[str] = []++ def once(base_url, method, path, payload, token, timeout):+ if path == "/api/auth/login":+ return 200, {"access_token": "a1", "refresh_token": "r1"}+ if path == "/api/auth/refresh":+ refreshes.append(payload["refresh_token"])+ if payload["refresh_token"] != live["refresh"]:+ return 401, "Invalid or expired refresh token"+ n = len(refreshes) + 1+ live.update(access = f"a{n}", refresh = f"r{n}")+ return 200, {"access_token": f"a{n}", "refresh_token": f"r{n}"}+ return (200, {"ok": token}) if token == live["access"] else (401, "expired")++ def status(token):+ return s._request("http://x", "GET", "/api/inference/status", token = token)++ monkeypatch.setattr(s, "_request_once", once)+ creds = s.authenticate("http://x", tmp_path, "pw")+ assert isinstance(creds, s.Credentials) and creds.refresh == "r1"+ assert status(creds) == (200, {"ok": "a1"})+ live["access"] = "expired-by-server"+ assert status(creds) == (200, {"ok": "a2"})+ assert refreshes == ["r1"] and creds.refresh == "r2"+ assert creds.renew("http://x", "a1") is True and refreshes == ["r1"]+ streamed: list[str] = []++ def stream_once(base_url, path, payload, token, timeout):+ streamed.append(token)+ return (200, [], None) if token == live["access"] else (401, [], "expired")++ monkeypatch.setattr(s, "_stream_events_once", stream_once)+ live["access"] = "expired-again"+ assert s._stream_events("http://x", "/v1/chat/completions", {}, creds)[0] == 200+ assert streamed == ["a2", "a3"] and refreshes == ["r1", "r2"]+ assert status("stale")[0] == 401+++def test_a_transient_refresh_failure_keeps_the_refresh_token(s, monkeypatch):+ """A transport error or a 5xx from /api/auth/refresh may never have reached Studio's store, so the single-use token is kept."""+ answers = [+ (0, "connection reset"),+ (503, "busy"),+ (200, {"access_token": "a2", "refresh_token": "r2"}),+ ]++ def once(base_url, method, path, payload, token, timeout):+ assert path == "/api/auth/refresh" and payload["refresh_token"] == "r1"+ return answers.pop(0)++ monkeypatch.setattr(s, "_request_once", once)+ creds = s.Credentials("a1", "r1")+ assert creds.renew("http://x", "a1") is False and creds.refresh == "r1"+ assert creds.renew("http://x", "a1") is False and creds.refresh == "r1"+ assert creds.renew("http://x", "a1") is True and (creds.access, creds.refresh) == ("a2", "r2")+ monkeypatch.setattr(s, "_request_once", lambda *a: (401, "Invalid or expired refresh token"))+ assert creds.renew("http://x", "a2") is False and creds.refresh is None+++def test_the_workflow_attributes_its_3076_events_to_the_installed_policy(tmp_path):+ """Another audit-mode policy on the runner logs 3076s as well."""+ body = _text(WORKFLOW)+ marker = " $fromPolicy = {\n"+ assert body.count(marker) == 2+ _has(+ body,+ "$fired = @($named | Where-Object { & $fromPolicy $_ })",+ '$tail -and $subject -like "*$tail*" -and (& $fromPolicy $_)',+ )+ start = body.index(" $policyBare = ")+ end = body.index("\n }\n", body.index(marker)) + len("\n }\n")+ block = "\n".join(line[10:] for line in body[start:end].splitlines())+ script = tmp_path / "attr.ps1"+ script.write_text(+ "$env:SAC_POLICY_ID = '{5283AC0F-FFF1-49AE-ADA1-8A933130CAD6}'\n"+ + block+ + r"""+function Ev([string]$xml) { $o = [pscustomobject]@{ X = $xml }; $o | Add-Member ScriptMethod ToXml { $this.X }; $o }+$ns = 'http://schemas.microsoft.com/win/2004/08/events/event'+$ours = Ev "<Event xmlns='$ns'><EventData><Data Name='File Name'>C:\x\unsigned-control.exe</Data><Data Name='PolicyGUID'>{5283ac0f-fff1-49ae-ada1-8a933130cad6}</Data></EventData></Event>"+$byName = Ev "<Event xmlns='$ns'><EventData><Data Name='PolicyNameBuffer'>VerifiedAndReputableDesktopEvaluationAuditNoISG</Data></EventData></Event>"+$other = Ev "<Event xmlns='$ns'><EventData><Data Name='File Name'>C:\x\unsigned-control.exe</Data><Data Name='PolicyGUID'>{11111111-2222-3333-4444-555555555555}</Data><Data Name='PolicyNameBuffer'>ContosoAllowList</Data></EventData></Event>"+$broken = Ev "not xml"+if ($true -ne (& $fromPolicy $ours)) { exit 81 }+if ($true -ne (& $fromPolicy $byName)) { exit 82 }+if ($true -eq (& $fromPolicy $other)) { exit 83 }+if ($true -eq (& $fromPolicy $broken)) { exit 84 }+exit 0+""",+ encoding = "utf-8",+ )+ _assert_ok(_run_ps(script))+++_PROBE_MOCKS = r"""+$WorkDir = $Work; $SkipUpdates = $true; $UpgradePackages = $false; $SendSamples = $false+$NOISG_GUID = '{AAAA}'; $NOISG_DEST = Join-Path $Work 'efi/active/test.cip'+$AuditPolicy = Join-Path $Work 'source.bin'; 'probe policy' | Set-Content -LiteralPath $AuditPolicy+$script:EfiStillMounted = $false+function Assert-Elevated { }+function Write-Section { }+function Clear-EfiOwnership { }+function Mount-Efi { $true }+function Dismount-Efi { }+function Invoke-Native { }+function Set-MpPreference { }+function Get-MpPreference { [pscustomobject]@{ DisableRealtimeMonitoring = $false } }+function Get-MpPreferenceType { [string] }+function Test-MpPreferenceMatch { $true }+function Get-CiLogSettings { [pscustomobject]@{ Enabled = $true; MaxSize = 67108864 } }+function Initialize-Studio { }+function Stop-ProbeStudio { $true }+function Get-StudioHomeOverride { $Work }+function Get-StudioHome { $Work }+function Get-LlamaDir { Join-Path $Work 'runtime' }+function Save-Baseline([string] $dir) {+ $b = [pscustomobject]@{ CapturedAt = (Get-Date).ToString('o'); Sac = [pscustomobject]@{ Mode = 'off'; RegistryState = 0; Policies = @() }+ AuditPolicyApplied = $false; AuditPolicyPreexisting = $false; AuditPolicyControlFired = $null; RevertCompletedAt = $null }+ Save-ProbeBaseline $b (Join-Path $dir 'baseline.json'); $b }+function Get-PendingRegistry { Join-Path $Work '.machine' }+function Read-Baseline([string] $label) { Get-Content -LiteralPath (Join-Path (Join-Path $Work $label) 'baseline.json') -Raw | ConvertFrom-Json }+"""+++def _drive_stages(tmp_path, body):+ names = [+ "Get-RunDir",+ "Get-RollbackPolicyPath",+ "Save-ProbeBaseline",+ "Test-PolicyActive",+ "Get-PendingEntry",+ "Get-UnrevertedLabel",+ "Assert-BaselineIsThisMachine",+ "Invoke-Prepare",+ "Invoke-Revert",+ ]+ _drive(tmp_path, names, _PROBE_MOCKS + body, Work = tmp_path)+++def test_prepare_refuses_while_another_label_is_unreverted(tmp_path):+ """prepare B while A was unreverted saved A's policy as B's pre-existing one, so reverting A then B put the probe policy back."""+ _drive_stages(+ tmp_path,+ r"""+function Get-RollbackPolicyPath { throw 'PAST-GUARD' }+New-Item -ItemType Directory -Force -Path (Join-Path $Work 'A') | Out-Null+Save-ProbeBaseline ([pscustomobject]@{ AuditPolicyApplied = $true; RevertCompletedAt = $null }) (Join-Path $Work 'A/baseline.json')+$Label = 'B'+try { Invoke-Prepare; exit 71 } catch { if ("$_" -notlike "*label 'A' has not been reverted*revert -Label A*") { Write-Host "$_"; exit 72 } }+# A retry of the same label, and a label whose revert completed, are not refused.+$Label = 'A'+try { Invoke-Prepare; exit 73 } catch { if ("$_" -ne 'PAST-GUARD') { Write-Host "$_"; exit 74 } }+Save-ProbeBaseline ([pscustomobject]@{ AuditPolicyApplied = $false; RevertCompletedAt = 'done' }) (Join-Path $Work 'A/baseline.json')+$Label = 'B'+try { Invoke-Prepare; exit 75 } catch { if ("$_" -ne 'PAST-GUARD') { Write-Host "$_"; exit 76 } }+exit 0+""",+ )+++def test_prepare_refuses_a_label_left_unreverted_under_another_workdir(tmp_path):+ """The guard scanned one -WorkDir, so B saved A's probe policy as pre-existing and reverting B put it back."""+ _drive_stages(+ tmp_path,+ r"""+function Get-SacState { [pscustomobject]@{ Policies = @(if (Test-Path -LiteralPath $NOISG_DEST) { [pscustomobject]@{ PolicyID = '{aaaa}'; FriendlyName = 'AuditNoISG' } }) } }+function Test-AuditPolicyEvaluating { $true }+$other = Join-Path $Work 'second'+$Label = 'A'; Invoke-Prepare+$WorkDir = $other; $Label = 'B'+try { Invoke-Prepare; exit 81 } catch { if ("$_" -notlike "*label 'A' has not been reverted*revert -Label A -WorkDir*") { Write-Host "$_"; exit 82 } }+$WorkDir = $Work; $Label = 'A'; Invoke-Revert+if (@(Get-ChildItem -LiteralPath (Get-PendingRegistry) -File).Count -ne 0) { exit 83 }+$WorkDir = $other; $Label = 'B'; Invoke-Prepare+if ((Read-Baseline 'second/B').AuditPolicyPreexisting) { exit 84 }+exit 0+""",+ )+++def test_collect_refuses_a_reverted_label_and_a_window_older_than_its_baseline(tmp_path):+ """After revert the audit-policy flag reads false and the log runs past the run; a window older than the baseline was an earlier run's."""+ names = [+ "Get-RunDir",+ "Save-ProbeBaseline",+ "Read-SettledCiEvents",+ "Assert-BaselineIsThisMachine",+ "Invoke-Collect",+ ]+ body = r"""+$WorkDir = $Work; $Label = 'cell'; $CI_EVENT_IDS = @(3076, 3077)+function Assert-Elevated { }+function Write-Section { }+function Get-WinEvent { [CmdletBinding()] param([hashtable] $FilterHashtable) throw 'PAST-GUARD' }+$dir = Get-RunDir+(Get-Date).AddMinutes(-15).ToString('o') | Set-Content (Join-Path $dir 'window-start.txt')+$b = [pscustomobject]@{ CapturedAt = (Get-Date).AddMinutes(-20).ToString('o'); RevertCompletedAt = (Get-Date).ToString('o') }+Save-ProbeBaseline $b (Join-Path $dir 'baseline.json')+try { Invoke-Collect; exit 101 } catch { if ("$_" -notlike "*label 'cell' was reverted*collect runs before revert*") { Write-Host "$_"; exit 102 } }+$b.RevertCompletedAt = $null; $b.CapturedAt = (Get-Date).ToString('o')+Save-ProbeBaseline $b (Join-Path $dir 'baseline.json')+try { Invoke-Collect; exit 103 } catch { if ("$_" -notlike '*before this label*baseline was captured*') { Write-Host "$_"; exit 104 } }+# Control: a live baseline and its own window get past both guards to the event read.+$b.CapturedAt = (Get-Date).AddMinutes(-20).ToString('o')+Save-ProbeBaseline $b (Join-Path $dir 'baseline.json')+try { Invoke-Collect; exit 105 } catch { if ("$_" -notlike '*PAST-GUARD*') { Write-Host "$_"; exit 106 } }+exit 0+"""+ _drive(tmp_path, names, body, Work = tmp_path)+++def test_no_stage_uses_a_baseline_prepared_on_another_machine(tmp_path):+ """A roaming or shared -WorkDir carried machine A's unspent baseline, and revert wrote A's settings onto B."""+ _drive_stages(+ tmp_path,+ r"""+function Get-RollbackPolicyPath { throw 'PAST-GUARD' }+$env:COMPUTERNAME = 'HOST-B'+New-Item -ItemType Directory -Force -Path (Join-Path $Work 'A') | Out-Null+Save-ProbeBaseline ([pscustomobject]@{ ComputerName = 'HOST-A'; AuditPolicyApplied = $true; RevertCompletedAt = $null }) (Join-Path $Work 'A/baseline.json')+$Label = 'A'+try { Invoke-Revert; exit 111 } catch { if ("$_" -notlike "*prepared on HOST-A, not HOST-B*") { Write-Host "$_"; exit 112 } }+function Get-RollbackPolicyPath { Join-Path $Work 'rollback.cip' }+try { Invoke-Prepare; exit 113 } catch { if ("$_" -notlike "*prepared on HOST-A, not HOST-B*") { Write-Host "$_"; exit 114 } }+# Control: the same baseline on its own machine gets past the guard.+function Get-RollbackPolicyPath { throw 'PAST-GUARD' }+$env:COMPUTERNAME = 'HOST-A'+try { Invoke-Revert } catch { if ("$_" -ne 'PAST-GUARD') { Write-Host "$_"; exit 115 } }+exit 0+""",+ )+++def test_studios_cpu_fallback_runtime_is_scoped_as_llama_cpp():+ """A crashed Vulkan launch reruns from a staged CPU copy under <studio home>\\runtime\\llama-cpu-*, whose 3076s read as 'other'."""+ shaped = _cut(_collect(), "$tail = Get-ScopeTail", "$scopeByActivity = @{}")+ _has(+ shaped,+ "$cpuTail = (Get-ScopeTail (Join-Path (Resolve-StudioHomeFor $dir) 'runtime')) + 'llama-cpu-*\\'",+ 'if ($subject -like "*$tail*" -or $subject -like "*$cpuTail*")',+ )+ tail = "\\Users\\u\\.unsloth\\studio\\runtime\\" + "llama-cpu-*\\"+ assert fnmatch.fnmatchcase(+ "C:\\Users\\u\\.unsloth\\studio\\runtime\\llama-cpu-ab12\\ggml-cpu.dll", "*" + tail + "*"+ )+++def test_a_cancelled_prepare_still_rolls_the_policy_back(tmp_path):+ """Ctrl+C during the positive control or Studio startup skipped the catch that held the rollback."""+ _drive_stages(+ tmp_path,+ r"""+function Get-SacState { [pscustomobject]@{ Policies = @(if (Test-Path -LiteralPath $NOISG_DEST) { [pscustomobject]@{ PolicyID = '{aaaa}'; FriendlyName = 'AuditNoISG' } }) } }+function Test-AuditPolicyEvaluating { $true }+# break from inside a called function unwinds like a pipeline stop: finally runs, catch does not.+function Initialize-Studio { break }+$Label = 'cancelled'+foreach ($once in 1) { Invoke-Prepare }+if (Test-Path -LiteralPath $NOISG_DEST) { exit 121 }+if ($false -ne (Read-Baseline 'cancelled').AuditPolicyApplied) { exit 122 }+exit 0+""",+ )+++def test_a_pending_label_whose_workdir_is_unavailable_still_blocks_prepare(tmp_path):+ """A disconnected or renamed -WorkDir hid A's baseline, so B saved A's probe policy as pre-existing."""+ _drive_stages(+ tmp_path,+ r"""+function Get-SacState { [pscustomobject]@{ Policies = @(if (Test-Path -LiteralPath $NOISG_DEST) { [pscustomobject]@{ PolicyID = '{aaaa}'; FriendlyName = 'AuditNoISG' } }) } }+function Test-AuditPolicyEvaluating { $true }+$first = Join-Path $Work 'first'; $other = Join-Path $Work 'second'+$WorkDir = $first; $Label = 'A'; Invoke-Prepare+Rename-Item -LiteralPath $first -NewName 'first-offline'+$WorkDir = $other; $Label = 'B'+try { Invoke-Prepare; exit 131 } catch { if ("$_" -notlike "*label 'A' has not been reverted*delete its record under*") { Write-Host "$_"; exit 132 } }+if (Test-Path -LiteralPath (Join-Path $other 'B/rollback')) { exit 133 }+exit 0+""",+ )+++def test_revert_keeps_the_baseline_pending_while_the_policy_is_still_active(tmp_path):+ """Before Windows 11 24H2 a removed policy stays active until a restart, and revert spent the baseline anyway."""+ _drive_stages(+ tmp_path,+ r"""+$global:listed = $true+function Get-SacState { [pscustomobject]@{ Policies = @(if ($global:listed) { [pscustomobject]@{ PolicyID = '{aaaa}'; FriendlyName = 'AuditNoISG' } }) } }+$Label = 'r'+New-Item -ItemType Directory -Force -Path (Split-Path $NOISG_DEST) | Out-Null+'probe policy' | Set-Content -LiteralPath $NOISG_DEST+New-Item -ItemType Directory -Force -Path (Join-Path $Work 'r') | Out-Null+Save-ProbeBaseline ([pscustomobject]@{ AuditPolicyApplied = $true; AuditPolicyPreexisting = $false; RevertCompletedAt = $null }) (Join-Path $Work 'r/baseline.json')+try { Invoke-Revert; exit 51 } catch { if ("$_" -notlike '*still active*restart*revert -Label r again*') { Write-Host "$_"; exit 52 } }+$b = Read-Baseline 'r'+if ($b.RevertCompletedAt -or $true -ne $b.AuditPolicyApplied) { exit 53 }+# After the restart the policy is gone and the same baseline completes.+$global:listed = $false+Invoke-Revert+$b = Read-Baseline 'r'+if (-not $b.RevertCompletedAt -or $false -ne $b.AuditPolicyApplied) { exit 54 }+exit 0+""",+ )+++def test_revert_keeps_the_baseline_pending_until_a_restored_policy_is_active(tmp_path):+ """Restoring an administrator's policy under the same GUID was recorded as done without checking it took effect."""+ _drive_stages(+ tmp_path,+ r"""+$global:listed = $false+function Get-SacState { [pscustomobject]@{ Policies = @(if ($global:listed) { [pscustomobject]@{ PolicyID = '{aaaa}'; FriendlyName = 'AuditNoISG' } }) } }+$Label = 'r'+New-Item -ItemType Directory -Force -Path (Split-Path $NOISG_DEST), (Join-Path $Work 'r/rollback') | Out-Null+'probe policy' | Set-Content -LiteralPath $NOISG_DEST+'admin policy' | Set-Content -LiteralPath (Get-RollbackPolicyPath (Join-Path $Work 'r'))+Save-ProbeBaseline ([pscustomobject]@{ AuditPolicyApplied = $true; AuditPolicyPreexisting = $true; RevertCompletedAt = $null }) (Join-Path $Work 'r/baseline.json')+try { Invoke-Revert; exit 51 } catch { if ("$_" -notlike '*restored and refreshed but is not active*restart*revert -Label r again*') { Write-Host "$_"; exit 52 } }+$b = Read-Baseline 'r'+if ($b.RevertCompletedAt -or $true -ne $b.AuditPolicyApplied) { exit 53 }+if ((Get-Content -LiteralPath $NOISG_DEST -Raw).Trim() -ne 'admin policy') { exit 54 }+# Once it is in force again the same baseline completes.+$global:listed = $true+Invoke-Revert+$b = Read-Baseline 'r'+if (-not $b.RevertCompletedAt -or $false -ne $b.AuditPolicyApplied) { exit 55 }+exit 0+""",+ )+++def test_a_prepare_that_fails_after_applying_the_policy_rolls_it_back(tmp_path):+ """A failed positive control threw with the probe policy still installed."""+ _drive_stages(+ tmp_path,+ r"""+function Get-SacState { [pscustomobject]@{ Policies = @([pscustomobject]@{ PolicyID = 'other' }; if (Test-Path -LiteralPath $NOISG_DEST) { [pscustomobject]@{ PolicyID = '{aaaa}'; FriendlyName = 'AuditNoISG' } }) } }+function Test-AuditPolicyEvaluating { $false }+$Label = 'fresh'+try { Invoke-Prepare; exit 41 } catch { if ("$_" -notlike '*raised no 3076 or 3077*') { Write-Host "$_"; exit 42 } }+if (Test-Path -LiteralPath $NOISG_DEST) { exit 43 }+if ($false -ne (Read-Baseline 'fresh').AuditPolicyApplied) { exit 44 }+Save-ProbeBaseline ([pscustomobject]@{ RevertCompletedAt = 'done' }) (Join-Path $Work 'fresh/baseline.json')+# An administrator's policy under the same GUID is put back, not deleted.+New-Item -ItemType Directory -Force -Path (Split-Path $NOISG_DEST) | Out-Null+'admin policy' | Set-Content -LiteralPath $NOISG_DEST+$Label = 'admin'+try { Invoke-Prepare; exit 45 } catch { }+if ((Get-Content -LiteralPath $NOISG_DEST -Raw).Trim() -ne 'admin policy') { exit 46 }+Save-ProbeBaseline ([pscustomobject]@{ RevertCompletedAt = 'done' }) (Join-Path $Work 'admin/baseline.json')+Remove-Item -LiteralPath $NOISG_DEST+# A prepare that succeeds keeps the policy for the stages after it.+function Test-AuditPolicyEvaluating { $true }+$Label = 'ok'+Invoke-Prepare+if (-not (Test-Path -LiteralPath $NOISG_DEST) -or $true -ne (Read-Baseline 'ok').AuditPolicyApplied) { exit 47 }+exit 0+""",+ )+++def test_a_prepare_that_fails_starting_studio_rolls_the_policy_back(tmp_path):+ """Initialize-Studio ran outside the rollback, so a Studio startup failure left the policy installed."""+ _drive_stages(+ tmp_path,+ r"""+function Get-SacState { [pscustomobject]@{ Policies = @(if (Test-Path -LiteralPath $NOISG_DEST) { [pscustomobject]@{ PolicyID = '{aaaa}'; IsEnforced = $true } }) } }+function Test-AuditPolicyEvaluating { $true }+function Initialize-Studio { throw 'STUDIO-TIMEOUT' }+$Label = 'late'+try { Invoke-Prepare; exit 61 } catch { if ("$_" -ne 'STUDIO-TIMEOUT') { Write-Host "$_"; exit 62 } }+if (Test-Path -LiteralPath $NOISG_DEST) { exit 63 }+if ($false -ne (Read-Baseline 'late').AuditPolicyApplied) { exit 64 }+exit 0+""",+ )+++def test_a_late_prepare_rollback_keeps_what_initialize_studio_recorded(tmp_path):+ """The rollback saved its older baseline copy over the install roots Initialize-Studio had just recorded."""+ _drive_stages(+ tmp_path,+ r"""+function Get-SacState { [pscustomobject]@{ Policies = @(if (Test-Path -LiteralPath $NOISG_DEST) { [pscustomobject]@{ PolicyID = '{aaaa}'; IsEnforced = $true } }) } }+function Test-AuditPolicyEvaluating { $true }+function Initialize-Studio($dir, $prepare) {+ $path = Join-Path $dir 'baseline.json'+ $b = Get-Content -LiteralPath $path -Raw | ConvertFrom-Json+ $b | Add-Member -Force NoteProperty StudioInstalledByProbe $true+ $b | Add-Member -Force NoteProperty StudioInstallRoots @('C:\probe-root')+ Save-ProbeBaseline $b $path+ throw 'STUDIO-TIMEOUT'+}+$Label = 'late2'+try { Invoke-Prepare; exit 71 } catch { if ("$_" -ne 'STUDIO-TIMEOUT') { Write-Host "$_"; exit 72 } }+$b = Read-Baseline 'late2'+if ($false -ne $b.AuditPolicyApplied) { exit 73 }+if ($true -ne $b.StudioInstalledByProbe -or @($b.StudioInstallRoots).Count -ne 1) { exit 74 }+exit 0+""",+ )+++def test_revert_keeps_the_baseline_pending_when_the_policy_list_is_unreadable(tmp_path):+ """A failed CiTool -lp became an empty list, so revert read 'cannot tell' as 'removed' and spent the baseline."""+ names = [+ "Get-RunDir",+ "Get-RollbackPolicyPath",+ "Save-ProbeBaseline",+ "Test-PolicyActive",+ "Get-SacState",+ "Get-PendingEntry",+ "Assert-BaselineIsThisMachine",+ "Invoke-Revert",+ ]+ body = r"""+$global:listExit = 7+function CiTool.exe { $global:LASTEXITCODE = $global:listExit; if ($global:listExit) { 'query failed' } else { '{"Policies":[]}' } }+$Label = 'u'+New-Item -ItemType Directory -Force -Path (Split-Path $NOISG_DEST) | Out-Null+'probe policy' | Set-Content -LiteralPath $NOISG_DEST+New-Item -ItemType Directory -Force -Path (Join-Path $Work 'u') | Out-Null+Save-ProbeBaseline ([pscustomobject]@{ AuditPolicyApplied = $true; AuditPolicyPreexisting = $false; RevertCompletedAt = $null }) (Join-Path $Work 'u/baseline.json')+try { Invoke-Revert; exit 91 } catch { if ("$_" -notlike '*could not list the policies*') { Write-Host "$_"; exit 92 } }+$b = Read-Baseline 'u'+if ($b.RevertCompletedAt -or $true -ne $b.AuditPolicyApplied) { exit 93 }+$global:listExit = 0+Invoke-Revert+if (-not (Read-Baseline 'u').RevertCompletedAt) { exit 94 }+exit 0+"""+ _drive(tmp_path, names, _PROBE_MOCKS + body, Work = tmp_path)++[email protected]("enforced, active", [("false", "False"), ("true", "True")])+def test_a_listed_policy_that_is_not_enforced_is_not_active(tmp_path, enforced, active):+ """CiTool -lp lists inactive policies too; IsEnforced says whether one is active."""+ body = (+ "function CiTool.exe { $global:LASTEXITCODE = 0; "+ f"""'{{"Policies":[{{"PolicyID":"{{aaaa}}","IsEnforced":{enforced}}}]}}' }}\n"""+ f"if ([string](Test-PolicyActive '{{AAAA}}') -ne '{active}') {{ exit 95 }}\nexit 0\n"+ )+ _drive(tmp_path, ["Get-SacState", "Test-PolicyActive"], body)+++ "refresh_exit, list_exit, listing",+ [(5, 0, _UNLISTED), (0, 7, _UNLISTED), (0, 0, "INVALID JSON")],+ ids = ["refresh", "listing", "malformed"],+)+def test_the_policy_removal_step_never_reports_an_unverified_removal(+ tmp_path, refresh_exit, list_exit, listing+):+ """A failed refresh or policy listing, or a listing that is not JSON, read as an empty list."""+ proc = _removal_step(tmp_path, "u", 0, refresh_exit, list_exit, listing)+ assert proc.returncode == 0, proc.stdout + proc.stderr+ _has(proc.stdout, "::warning::", "could not be verified")+ assert "removed and no longer active" not in proc.stdout+++def test_the_audit_loads_every_shipped_entry_point():+ body = _step("id", "exercise")+ assert "& $server.FullName --version" in body+ assert "& $quantize.FullName --help" in body, "llama-quantize loads its own impl DLL"+++def test_a_quantize_that_failed_to_load_gives_no_verdict():+ _has(_text(WORKFLOW), 'Add-Content -Path $env:GITHUB_ENV -Value "QUANTIZE_EXIT=$LASTEXITCODE"')+ _has(_verdict(), "[int]$env:QUANTIZE_EXIT -lt 0", "llama-quantize failed to load")+++def test_the_event_poll_waits_for_the_count_to_settle():+ verdict = _verdict()+ _has(verdict, "$ours.Count -gt 0 -and $ours.Count -eq $seen) { break }", "$seen = $ours.Count")+ _lacks(verdict, "if ($ours.Count -gt 0) { break }")++[email protected]("workdir", [".\\evidence", "C:\\review\\evidence"])+def test_the_archive_filter_holds_for_a_relative_workdir(tmp_path, workdir):+ """A relative -WorkDir made $dir shorter than Get-ChildItem's absolute FullName, so raw-logs and rollback reached the zip."""+ source = _text(PS1)+ assert (+ "$WorkDir = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($WorkDir)"+ in source+ )+ block = source[source.index(' $stage = Join-Path $WorkDir ".stage-$Label"') :]+ block = block[: block.index(" $target = Join-Path $stage $rel")]+ prelude = r"""+param([string]$WorkDir)+$ErrorActionPreference = 'Stop'+$Label = 'run'+function Join-Path { param($Path, $ChildPath) "$Path\$ChildPath" }+function Remove-Item { }+function New-Item { }+function Get-Item { [pscustomobject]@{ FullName = 'C:\review\evidence\run' } }+function Get-ChildItem {+ foreach ($name in @('raw-logs\studio-start.log', 'rollback\preexisting-policy.cip', 'studio-logs\studio-start.log', 'scenario-results.json')) {+ [pscustomobject]@{ FullName = "C:\review\evidence\run\$name" }+ }+}+$dir = Join-Path $WorkDir $Label+"""+ script = tmp_path / "stage.ps1"+ script.write_text(prelude + block + "Write-Output $rel\n}\n", encoding = "utf-8")+ result = _run_ps(script, "-WorkDir", workdir)+ assert result.returncode == 0, result.stderr+ assert result.stdout.split() == [+ "studio-logs\\studio-start.log",+ "scenario-results.json",+ ], result.stdout++[email protected]("quantize_mode", ["start-failure", "exit-0", "exit-1", "loader-failure"])+def test_the_ci_allow_needs_an_exercise_that_finished(tmp_path, quantize_mode):+ """A llama-quantize that failed to start left no QUANTIZE_EXIT, and an empty window then printed a clean allow."""+ if shutil.which("pwsh") is None:+ pytest.skip("pwsh is required")+ steps = yaml.safe_load(_text(WORKFLOW))["jobs"]["code-integrity"]["steps"]+ exercise = next(s["run"] for s in steps if s.get("id") == "exercise")+ verdict = next(s["run"] for s in steps if s.get("name") == "Verdict")+ env = dict(+ os.environ,+ GITHUB_ENV = str(tmp_path / "env"),+ GITHUB_STEP_SUMMARY = str(tmp_path / "summary"),+ RELEASE_TAG = "fixed-test-release",+ AUDIT_START = "2026-09-27T00:00:00Z",+ SAC_POLICY_ID = "{5283AC0F-FFF1-49AE-ADA1-8A933130CAD6}",+ ENFORCE = "true",+ )+ for name in ("QUANTIZE_EXIT", "EXERCISE_EXIT", "EXERCISE_COMPLETED", "RUNTIME_DIR"):+ env.pop(name, None)+ quantize = {+ "start-failure": "throw 'process creation refused (simulated)'",+ "exit-0": "$global:LASTEXITCODE = 0",+ "exit-1": "$global:LASTEXITCODE = 1",+ "loader-failure": "$global:LASTEXITCODE = -1073741701",+ }[quantize_mode]+ prelude = r"""+function gh { $global:LASTEXITCODE = 0; if ($args[1] -eq 'view') { 'llama-windows-x64-cpu.zip' } }+function Expand-Archive { }+function Get-ChildItem {+ param($LiteralPath, [switch]$Recurse, $Filter)+ if ($Filter -eq 'llama-server.exe') {+ [pscustomobject]@{ FullName = 'Test-Server'; Directory = [pscustomobject]@{ FullName = 'C:\runtime' } }+ } else { [pscustomobject]@{ FullName = 'Test-Quantize' } }+}+function Test-Server { $global:LASTEXITCODE = 0; 'version: test' }+function Test-Quantize { QUANTIZE }+""".replace("QUANTIZE", quantize)+ script = tmp_path / "exercise.ps1"+ script.write_text(prelude + exercise, encoding = "utf-8")+ ran = run_pwsh(+ ["pwsh", "-NoProfile", "-File", str(script)], env = env, capture_output = True, text = True+ )+ assert (ran.returncode != 0) == (quantize_mode == "start-failure"), ran.stdout + ran.stderr+ for line in (tmp_path / "env").read_text(encoding = "utf-8-sig").splitlines():+ key, value = line.split("=", 1)+ env[key] = value+ script = tmp_path / "verdict.ps1"+ script.write_text(+ "function Start-Sleep { }\nfunction Get-WinEvent { }\n" + verdict, encoding = "utf-8"+ )+ ran = run_pwsh(+ ["pwsh", "-NoProfile", "-File", str(script)], env = env, capture_output = True, text = True+ )+ refuse = quantize_mode in ("start-failure", "loader-failure")+ assert (ran.returncode != 0) == refuse, ran.stdout+ assert (+ "No binary in the shipped runtime would be refused" not in ran.stdout+ ) == refuse, ran.stdout+++def test_pending_self_cannot_recapture_a_missing_baseline(tmp_path):+ """A label whose evidence moved re-captured a baseline with its own probe policy as pre-existing, so revert left it installed."""+ _drive_stages(+ tmp_path,+ r"""+function Get-SacState { [pscustomobject]@{ Policies = @(if (Test-Path -LiteralPath $NOISG_DEST) { [pscustomobject]@{ PolicyID = '{aaaa}'; FriendlyName = 'AuditNoISG' } }) } }+function Test-AuditPolicyEvaluating { $true }+$WorkDir = Join-Path $Work 'evidence'; $Label = 'A'+Invoke-Prepare+$pending = Get-PendingEntry (Join-Path $WorkDir $Label)+$claimBefore = Get-Content -LiteralPath $pending -Raw+# Move the evidence tree, as with renamed/disconnected storage. The machine-wide claim survives.+$relocated = Join-Path $Work 'relocated'+Move-Item -LiteralPath $WorkDir -Destination $relocated+$refused = $false+try { Invoke-Prepare } catch {+ if ("$_" -notlike '*has not been reverted*' -and "$_" -notlike '*baseline*') { throw }+ $refused = $true+}+if (-not $refused) {+ $replacement = Get-Content -LiteralPath (Join-Path $WorkDir 'A/baseline.json') -Raw | ConvertFrom-Json+ Invoke-Revert+ $after = Get-Content -LiteralPath (Join-Path $WorkDir 'A/baseline.json') -Raw | ConvertFrom-Json+ Write-Host "BUG: recaptured_preexisting=$($replacement.AuditPolicyPreexisting) policy_left=$(Test-Path -LiteralPath $NOISG_DEST) revert_completed=$([bool]$after.RevertCompletedAt) pending_left=$(Test-Path -LiteralPath $pending)"+ throw 'pending self claim was ignored; revert completed with the probe policy still installed'+}+if ((Get-Content -LiteralPath $pending -Raw) -cne $claimBefore) { throw 'pending claim changed during refusal' }+if (Test-Path -LiteralPath (Join-Path $WorkDir 'A/baseline.json')) { throw 'refusal wrote a replacement baseline' }+# Restore the ORIGINAL evidence and prove the guard still permits retry and revert.+Remove-Item -LiteralPath $WorkDir -Recurse -Force+Move-Item -LiteralPath $relocated -Destination $WorkDir+Invoke-Prepare+Invoke-Revert+if (Test-Path -LiteralPath $NOISG_DEST) { throw 'original revert left policy behind' }+if (Test-Path -LiteralPath $pending) { throw 'original revert left pending claim' }+Write-Host 'pending-self recovery passed'+""",+ )+++def test_unc_runtime_events_match_the_nt_network_path(tmp_path):+ _drive(+ tmp_path,+ ["Get-ScopeTail"],+ r"""+$tail = Get-ScopeTail '\\fileserver\models\llama.cpp'+foreach ($subject in @(+ '\\fileserver\models\llama.cpp\ggml.dll',+ '\Device\Mup\fileserver\models\llama.cpp\ggml.dll',+ '\Device\LanmanRedirector\fileserver\models\llama.cpp\ggml.dll'+)) {+ if ($subject -notlike "*$tail*") { throw "selected runtime excluded: $subject" }+}+foreach ($subject in @(+ '\Device\Mup\another-server\models\llama.cpp\ggml.dll',+ '\Device\Mup\fileserver\other-share\llama.cpp\ggml.dll',+ '\Device\Mup\fileserver\models\llama.cpp-other\ggml.dll'+)) {+ if ($subject -like "*$tail*") { throw "unrelated runtime included: $subject" }+}+""",+ )