Skip to content

Reduce antivirus false positives in the desktop installers - #8586

Merged
danielhanchen merged 59 commits into
mainfrom
harden-installer-av-false-positives
Aug 13, 2026
Merged

danielhanchen merged 59 commits into
mainfrom
harden-installer-av-false-positives

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Aug 12, 2026 •

Copy link
Copy Markdown
Member

Fixes #8523, and takes the same pass over the Linux bundle.

What is happening

Two separate false positives, same underlying cause: we ship large scripts whose shape scores badly.

#8523. A third party AMSI provider blocked C:\Program Files\Unsloth\install.ps1 at parse time with ScriptContainedMaliciousContent. Worth being precise about the error, because it reads as though line 1 is the problem:

At C:\Program Files\Unsloth\install.ps1:1 char:1
+ # Unsloth Studio Installer for Windows PowerShell
This script contains malicious content and has been blocked by your antivirus software.
    + FullyQualifiedErrorId : ScriptContainedMaliciousContent

PowerShell 5.1 and later hand the whole top level script block to AMSI while compiling it, before the first statement runs. The reported extent is therefore the entire file, not the offending construct, and nothing in the installer gets to run: no [TAURI:ERROR] marker, no phase log, no diagnostics. Every byte of the file is scanned, comments included.

Release CI. The VirusTotal scan on 0.1.701-beta came back clean on every bundle except the Linux AppImage, which Microsoft flagged Trojan:Script/Wacatac.B!ml, a generic ML verdict on script content.

Neither is reproducible here, so none of this is a proven fix for either verdict. It removes the constructs that AMSI providers and script classifiers are known to weight, and it adds a test so they cannot come back.

What was actually in there

Where What
studio/setup.ps1:4281 Invoke-Expression (Invoke-RestMethod astral.sh/uv/install.ps1). The only live download and execute left in either PowerShell installer, and the construct that scores hardest. install.ps1 replaced its own copy with a pinned SHA-256 archive in #7819 and this one was missed.
install.ps1:1521 -WindowStyle Hidden next to -ExecutionPolicy Bypass on the shortcut command line. studio/src-tauri/src/install.rs:244 already refuses that exact pair for the app's own launch, with a test pinning it.
Both headers The piped web one liner rehearsed five times over, a [scriptblock]::Create form and an execution policy bypass. All of it duplicated from the README, none of it read by the scripts, all of it scanned.
tauri.conf.json:61 bundle.resources shipped both installers into every target. resolve_install_script picks install.sh on unix and install.ps1 everywhere else, so the Linux AppImage carried 280 KB of Windows PowerShell it can never run, which is the largest script body a classifier walking the squashfs reads.
install.sh:2432, studio/setup.sh:1486 Download astral's installer to a temp file, run it, delete the file. Shape for shape, what a dropper does.

Changes

  • studio/setup.ps1 installs uv from the pinned release archive, porting Install-UvFromRelease from install.ps1. install.sh and studio/setup.sh do the same. The POSIX side pins only the four mainstream targets: musl, armv7 and any host with no digest tool keep the path they have today, because guessing a target triple wrong breaks the install outright and that costs far more than the heuristic score of a fallback.
  • The shortcut and the generated launcher move to RemoteSigned. The hidden window stays. The installer writes launch-studio.ps1 itself, so it has no mark of the web and RemoteSigned loads it, which is the same reasoning install.rs already documents.
  • Headers point at the README instead of repeating the one liner, and the in body comments that quoted it as shorthand are reworded.
  • bundle.resources moves into the per platform configs, so each bundle ships only the installer it can run. The clean machine job already failed when a Linux bundle shipped no install.sh; it now also fails when one ships install.ps1, so the split cannot regress in either direction.
  • install.rs recognises ScriptContainedMaliciousContent and ScriptHasAdminBlockedContent on either stream and appends what the user needs: nothing was installed, nothing was changed, it is a false positive, update definitions and retry, do not turn off endpoint protection. The raw error id stays in the message, because the diagnostics report and any vendor submission both need it. Matched on the error id rather than the message text, which is localized.
  • The VirusTotal job emits a false positive submission packet for any flagged asset. The build job assembles one today, but only for the Windows -setup.exe, so the one detection that actually arrived produced nothing to submit.
  • tests/studio/test_installer_av_shapes.py pins all of it: no remote script run in process, no encoded or base64 payload, no hidden window paired with a bypassed policy, no process memory API, and no new runtime compiled native import outside an allowlist that carries a reason per entry.

Output is unchanged

This is hardening, not a behaviour change. I diffed every substep, step, Write-StudioLine, Write-Host, echo and printf in all five scripts against the merge base: zero user visible differences. The only new echo calls are inside $(...) capture.

The remediation lines that print irm https://unsloth.ai/install.ps1 | iex and curl -fsSL https://unsloth.ai/install.sh | sh are deliberately untouched. Taking the one liner out of comments is the point; taking it out of what we tell the user to run would be a regression, so the new test asserts those strings verbatim.

One thing tried and reverted

I replaced the OpenProcess and QueryFullProcessImageNameW pair in the inline C# with a single Win32_Process query, then found tests/python/test_windows_installer_concurrency_guard.py bans Get-CimInstance and $process.Path from that detector outright and requires the native lookup. That contract came out of #7764, which closed races where the installer inferred "in use" from something other than a confirmed executable identity and blocked installs that should have gone ahead. A wrongly blocked install costs more than three native imports, so the revert stands and those imports are recorded in the allowlist with that reasoning. The commit and its revert are both on the branch so the reasoning is not lost.

Verification

  • 4701 passed across tests/studio/, tests/python/, tests/security/ and tests/test_installer_*.py. Three failures and eight errors remain and reproduce on the merge base in a separate worktree; the branch touches no Python source under unsloth/, unsloth_zoo/ or studio/backend/.
  • 283 cargo test in studio/src-tauri, including five new cases driving the exact stderr from [Bug] Windows Setup ran into a problem Installation failed: + FullyQualifiedError #8523.
  • The AST parse gate over install.ps1, studio/setup.ps1 and scripts/uninstall.ps1, plus the five PowerShell unit tests wired into the Windows smoke.
  • bash -n and sh -n, the existing shell suites, and a new tests/sh/test_uv_pinned_release.sh covering the digest check, the extraction and the decline path.
  • The pinned uv path run end to end for real on Linux x86_64: downloads, verifies, extracts, and uv --version reports 0.12.1. Decline paths confirmed not to trip set -e or set -euo pipefail.

Left to CI: the Windows Pester and VS jobs, and a release dry run to confirm the bundle split and the submission packet.

Still worth doing

#8523 was closed without recording the antivirus vendor, the detection name or the provider DLL, so nothing here can be proven against the product that actually blocked it. Asking for Get-CimInstance -Namespace root/SecurityCenter2 AntiVirusProduct and the registered provider under HKLM\SOFTWARE\Microsoft\AMSI\Providers would make a real reproduction possible, and is the only way to know whether this is enough.

danielhanchen and others added 11 commits August 12, 2026 14:12
…mote script text

studio/setup.ps1 piped astral's install.ps1 straight into Invoke-Expression. That
download-and-execute shape is the single construct AMSI providers and cloud ML
scanners score hardest, and install.ps1 already replaced it with a pinned-SHA-256
archive download. Port the same implementation across.

Progress goes to the pipeline rather than the console, so the quiet path swallows
it exactly as it swallowed astral's installer output and the printed lines around
the call site are unchanged.
The Studio shortcut launched launch-studio.ps1 with -WindowStyle Hidden and
-ExecutionPolicy Bypass on the same command line. That pair is what Microsoft's
own detections key on, and studio/src-tauri/src/install.rs already refuses it for
the app's own launch of install.ps1.

The installer writes launch-studio.ps1 itself, so the file carries no
mark-of-the-web and RemoteSigned loads it. The hidden window is unchanged, so the
shortcut behaves exactly as before. The generated launcher's own child launch
moves to RemoteSigned for the same reason: it runs an inline -Command against an
executable, where no script file is loaded and the two policies are equivalent.

Also refresh a stale comment in studio/setup.ps1 that attributed the PSModulePath
fix to astral's uv installer, which no longer runs in-process.
…ript text

AMSI scans install.ps1 in full before a single line of it runs, and generic
script classifiers read install.sh the same way inside the Linux bundle. Both
headers rehearsed the piped web one-liner five times over, plus a scriptblock
form and an execution-policy bypass, none of which anything in the scripts reads
and all of which the README already documents.

Point at the README instead and reword the in-body comments that quoted the
one-liner as shorthand. Every printed line is untouched: the remediation text the
installers show users still spells out the command in full.

Same treatment for scripts/uninstall.ps1's header.
install.ps1's venv-holder probe opened a handle to every running PID through
inline C# compiled at runtime. Opening a handle per process is a shape AV
heuristics score hard, and it bought nothing: Win32_Process reports
ExecutablePath for exactly the processes those handles could be opened against,
and answers for all of them in a single query instead of once per PID.

The remaining file-canonicalisation imports stay -- handle-based resolution of
linked ancestors has no faithful Windows PowerShell 5.1 equivalent, and it runs
on security-relevant paths.

Falls back to the per-process .Path when the query is unavailable, so a degraded
WMI repository degrades exactly as the old code did on a process it could not
open.
PowerShell hands the whole top-level script block to AMSI while compiling it, so
a security product's verdict arrives as a parse error over the entire file before
install.ps1 runs a statement: no [TAURI:ERROR] marker, no phase log, and a stderr
tail the user cannot act on. unsloth#8523 shows what that looks like in the UI --
"Installation failed: + FullyQualifiedErrorId : ScriptContainedMaliciousContent".

Recognise the two stable error ids on either stream and append what the user
actually needs: nothing was installed, nothing was changed, it is a false
positive, update definitions and retry, do not turn off endpoint protection. The
raw id stays in the message, because the diagnostics report and any vendor
submission both need it.

Matches the id, never the message text, which is localized, and tolerates the
cmdlet suffix the Invoke-Expression form carries.
resolve_install_script picks install.sh on unix and install.ps1 everywhere else,
but the shared Tauri config bundled both into every target. The Linux AppImage
therefore carried 280 KB of Windows PowerShell it can never execute -- and it is
the largest script body a generic classifier walking the squashfs reads, which is
where Microsoft's Trojan:Script/Wacatac.B!ml verdict on 0.1.701-beta landed.

Move the resource map into the per-platform configs. The clean-machine job
already fails when a Linux bundle ships no install.sh; it now also fails when one
ships install.ps1, so the split cannot silently regress in either direction.

The .deb scanned clean with the same payload, so this is surface reduction rather
than a proven fix for that verdict.
install.sh downloaded astral's install.sh to a temp file, ran it and deleted the
file; studio/setup.sh piped it straight into a shell. Both are, shape for shape,
what a dropper does, and generic ML script classifiers score them accordingly --
the 0.1.701-beta Linux AppImage came back Trojan:Script/Wacatac.B!ml while the
.deb carrying the same scripts came back clean.

Fetch the pinned release archive and verify a hardcoded SHA-256 instead, matching
what install.ps1 already does on Windows. Only the four mainstream targets are
pinned: musl, armv7 and any host without a digest tool keep the path they have
today, because guessing a target triple wrong would break the install outright
and that costs far more than the heuristic score of the fallback.

Destination, PATH handling and every printed line are unchanged, so a host that
takes either path ends up in the same state it did before.
One file collecting what was removed, so it cannot drift back: no remote script
run in-process, no encoded or base64 payload, no hidden window paired with a
bypassed execution policy, no handle opened against another process, and no new
runtime-compiled native import outside an allowlist that carries a reason for
each entry that stays.

The last test is the other half of the contract. Hardening must not change what a
user sees, so the remediation lines the installers print -- which still spell out
the web one-liner in full -- are asserted verbatim. Removing the one-liner from
comments is the point; removing it from what the user is told to run would be a
regression.

Runs on the existing discovery-based pytest step, no workflow list to update.
…agged

The build job assembles a Microsoft submission packet, but only for the Windows
-setup.exe. The detection that actually arrived on 0.1.701-beta was
Trojan:Script/Wacatac.B!ml on the Linux AppImage, so nothing was produced for the
one asset that needed it.

The VirusTotal job already knows which assets were flagged and by which engines,
so put the packet there: hash, size and both portals, for every flagged asset
whatever platform it came from, with a note that clearance is per hash and per
vendor. Engine names are not repeated -- they are third-party text and already
appear escaped under Flagging engines.

The gate stays advisory; this only makes acting on it take seconds.
…uery"

This reverts commit 7897865.

tests/python/test_windows_installer_concurrency_guard.py bans Get-CimInstance
and $process.Path from Get-RunningStudioVenvProcesses outright, and requires the
native image-path lookup. That contract came out of #7764, which closed a set of
races where the installer inferred "in use" from something other than a confirmed
executable identity and blocked installs that should have proceeded.

Win32_Process.ExecutablePath does answer the same question, but a wrongly blocked
install costs far more than the heuristic weight of three native imports. Record
the imports in the AV-shapes allowlist with that reasoning instead, and keep the
ban on the process-memory APIs, which the installer has no use for.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Opening comment-reduction pass over the PR diff: same intent, fewer lines. Cut
hardest on the prose that restated the PR description rather than explaining the
code next to it. Comments and docstrings only, verified with comment_tools.py
check --strip-docstrings across every Python file in the diff.
Stray-resource check aborted the step it was meant to assert. grep exits 1 when
it selects nothing, and under this step's set -o pipefail plus the runner's
bash -e that kills the assignment outright, so every correctly split .deb failed
clean-machine CI before reaching the check. Both lookups take || true now: no
match is the passing case for the stray one, and for install.sh it was swallowing
the explicit annotation in favour of a bare exit 1.

studio/setup.sh skipped astral's XDG_DATA_HOME/../bin destination tier, which
install.sh, install.ps1 and studio/setup.ps1 all honour. A host that configured
an XDG location got uv under ~/.local/bin instead, where no later shell looks for
it. The session PATH prepend hid it at install time.

The AMSI guidance claimed nothing was changed even when the block landed on the
nested studio/setup.ps1, which install.ps1 launches through the same inherited
pipes after the venv, PyTorch and the packages are already on disk. Split the
wording on whether a [TAURI:STEP] marker has been seen: a pre-start block
produces none, so the reassurance is only given where it is true.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

stats and results are separate fields of the same VirusTotal response, so an
asset can carry a flagged count with no readable results map. The summary table
reports that asset and the packet skipped it, which is exactly the one that needs
a packet. Select on stats.flagged and keep the engine list for the Flagging
engines section, which is correctly keyed on having engines to name.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: d9413705b1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

That job downloads a published release, never a bundle built from the branch, so
asserting the new resource split there turns every run red until a release ships
with it. The split is a property of the Tauri config, and
tests/studio/test_tauri_installer_resource_contract.py already enforces it at the
right layer.

The || true on the install.sh lookup stays: it is what lets the explicit
annotation print instead of the step dying on grep's exit 1 under pipefail.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 0d99d79ab3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

CI triage for this PR: nothing here is this PR's fault, and two of the red checks are not failures at all.

The three Backend failures on Python 3.10 through 3.13 are main's own defect, reproduced on a clean detached worktree at origin/main with no PR applied:

3 failed, 3 passed in 9.92s
tests/test_desktop_auth.py::test_health_response_reports_desktop_capability_fields
  ImportError: cannot import name 'openai_codex_auth_router' from 'routes' (unknown location)
tests/test_external_provider_usage_chunk.py::test_other_providers_do_not_get_the_continuation_flags[openai-...]
  ValueError: Responses event type is missing
tests/test_gemini_provider.py::test_openai_responses_forced_function_tool_choice_drops_hosted_tools
  ValueError: Responses event type is missing

with event = {}, event_name = '' at core/inference/openai_responses_shared.py:93. #8590 fixes the first, #8608 the other two; both are open. This PR is blocked behind those merges.

mac macos-15-intel / mask / file is red on main and does not block. The installer correctly declines torch on an Intel Mac ("PyTorch is unavailable for this platform (dropped Jan 2024)"), and then clean-machine-install-ci.yml:358 asserts import torch anyway, because that matrix row passes empty flags instead of --no-torch. The row is experimental: true under continue-on-error, so the workflow still concludes success; gh pr checks lists it as fail regardless. Byte-identical on a clean main run. That one wants a separate main-side CI fix.

One extra Backend failure on this PR only, and it is also main's, already fixed:

tests/test_warm_window_review_fixes.py::test_the_warm_epoch_is_retired_before_any_shutdown_await
assert 781 < 771

That assertion is pure AST analysis of studio/backend/main.py::lifespan, and this PR does not touch that file. Replaying it across main:

main commit retire / first await result
3c590a536^ 781 / 771 FAIL
3c590a536 746 / 752 PASS
origin/main PASS

3c590a536 is "Studio: defer optional GPU startup work (#8564)", merged 17:22Z. This PR's run was created before that, so it ran against a main that still had the bug. A re-run picks up the fix.

@danielhanchen

Copy link
Copy Markdown
Member Author

Verification: before/after, idempotency, and simulations

Recording the full verification pass for this PR, since it touches the installers every user runs.

Before this PR vs after this PR

before after
studio/setup.ps1 uv bootstrap Invoke-Expression (Invoke-RestMethod https://astral.sh/uv/install.ps1), remote script text executed in-process pinned release zip, SHA-256 verified before anything is extracted
install.sh / studio/setup.sh uv bootstrap download to a temp file, sh it, rm it (and curl ... | sh) pinned release tarball, SHA-256 verified; the old path stays as the fallback for musl/armv7/unpinned hosts
Start Menu and Desktop shortcut args -WindowStyle Hidden -ExecutionPolicy Bypass -WindowStyle Hidden -ExecutionPolicy RemoteSigned
Linux .deb / AppImage payload usr/lib/Unsloth/install.ps1 (280,216 bytes) and install.sh install.sh only, no .ps1 anywhere
An AMSI block in the desktop UI Installation failed: ... FullyQualifiedErrorId : ScriptContainedMaliciousContent same line, plus what it means and what to do

Everything the user sees on a successful install is unchanged. See the output parity section below.

Is this a real issue

Yes, on both counts, and I can now point at the bytes.

The AppImage that VirusTotal returned malicious=1 Microsoft (Trojan:Script/Wacatac.B!ml) for in run 31528647838 was Unsloth-Desktop-0_1_701_beta-Linux.AppImage. Extracting the shipped asset:

280216  squashfs-root/usr/lib/Unsloth/install.ps1
248932  squashfs-root/usr/lib/Unsloth/install.sh

A 280 KB Windows PowerShell script inside a Linux bundle that can never run it, and the detection family Microsoft returned is a script family. Building this branch on staging and unpacking the .deb it produces:

-rwxr-xr-x  265847  usr/lib/Unsloth/install.sh
(no .ps1 anywhere in the deb)

For #8523 I still cannot prove the fix, because the report never recorded which product blocked it. What I can say is that the reported error is a parse-time AMSI verdict (PowerShell 5.1 submits the whole top-level script block to AMSI during compilation, which is why the extent is line 1 char 1 and why no installer code ran), so the only lever is the text we ship. The single highest-scoring construct in that text was the in-process remote script in setup.ps1, and it is gone.

RemoteSigned

Not a new idea here. 458778e3e ("Reduce the Windows false positive surface: no Bypass/Hidden PowerShell, no in-process remote script, complete VERSIONINFO", #7822) made exactly this change for the app's own launch in install.rs::spawn_script, with #7943 and #7969 hardening it further, and it has been shipping since. This PR applies the same treatment to the two remaining call sites: the shortcut args and the launcher's own Start-Process.

The mechanism is the mark of the web. RemoteSigned requires a signature only for files carrying a Zone.Identifier alternate data stream, and launch-studio.ps1 is written locally by [System.IO.File]::WriteAllText into %LOCALAPPDATA%\Unsloth Studio, so it has no such stream. -ExecutionPolicy on a command line sets Process scope, which a MachinePolicy/UserPolicy GPO overrides identically whether the value is Bypass or RemoteSigned, so no configuration that worked before stops working. The hidden window is untouched: it is the Hidden + Bypass pair that Microsoft ships as a detection test, not the hidden window on its own.

Output parity

Diffed every printed line (substep, step, Write-StudioLine, Write-Host, Write-Warning, Write-Error, echo, printf) across install.sh, install.ps1, studio/setup.sh, studio/setup.ps1 and scripts/uninstall.ps1 against the merge base:

before: 1718 lines   after: 1726 lines
removed: 0   changed: 0
added:   8   all of them `echo "uv-<triple>.tar.gz <sha256>"` inside _uv_pinned_asset,
             consumed by $(...) and never written to a terminal

The 7 new Write-Output lines in setup.ps1 sit inside Invoke-SetupCommand { ... } | Out-Null, which is the same wrapper the removed Invoke-Expression used: the quiet path captures them into a variable and prints nothing. Verbose mode (UNSLOTH_VERBOSE=1) does show different words, since our progress lines replace astral's, and that is the only user-visible difference in the PR.

Idempotency and simulations

All offline, driven against stubbed hosts and transports so triples this machine is not still get exercised.

Shell, 72 checks (install.sh and studio/setup.sh):

  • 21 host combinations per implementation across Linux/Darwin/FreeBSD/SunOS/MINGW/CYGWIN/unknown x x86_64/amd64/aarch64/arm64/armv7l/i686/ppc64le/riscv64/s390x/sparc64/i386 x glibc/musl. Every pinned host resolves to the archive for its own triple; every other host declines so the pre-PR fallback runs. No combination selects a wrong triple.
  • Runs 1, 2 and 3 into the same HOME produce a byte-identical tree and the same return code. A stale uv already at the destination is replaced in place, not duplicated.
  • Digest mismatch, both mirrors down, and an empty response body each decline and write nothing. releases.astral.sh down falls through to github.com.
  • No tar and no digest tool each decline rather than install unverified.
  • Destination priority matches astral's installer exactly: UV_INSTALL_DIR > UV_UNMANAGED_INSTALL > XDG_BIN_HOME > XDG_DATA_HOME/../bin > $HOME/.local/bin, including when several are set at once.

PowerShell, 27 checks (functions pulled out of setup.ps1 by AST so the sim runs the shipped text):

  • install.ps1, studio/setup.ps1 and scripts/uninstall.ps1 all parse.
  • 8 Windows host signal sets: x64 native, x64 under WOW64, ARM64 native, ARM64 running x64 and x86 emulation, 32-bit, lowercase signals, and Itanium. Every one resolves to a pinned arch or declines.
  • Every pin table entry names a uv-<triple>-pc-windows-msvc.zip with a full 64-hex digest and a triple matching its own key.
  • Three runs into the same destination leave identical uv.exe/uvx.exe/uvw.exe hashes; a stale uv.exe is overwritten.
  • Digest mismatch and network failure install nothing; releases.astral.sh down falls through to github.com.
  • Destination priority as above, and UV_NO_MODIFY_PATH / UV_UNMANAGED_INSTALL both suppress the user-PATH write, as they do for astral's installer.

Against the real thing:

  • All 7 pinned digests verified against astral's published <asset>.sha256 for 0.12.1, and each digest appears exactly once across the four installers, so the tables cannot drift.
  • Both mirrors downloaded and hashed: byte-identical, matching the pin.
  • _uv_install_pinned run twice for real into a sandbox HOME: rc=0 both times, installs uv and uvx, uv --version reports 0.12.1 (x86_64-unknown-linux-gnu), and that uv creates a working venv, which is what setup.sh actually needs it for.

Suites: 3574 passed, 26 skipped across tests/studio/, tests/python/test_cross_platform_parity.py, test_virustotal_scan.py, test_windows_installer_concurrency_guard.py and tests/security/. The 8 errors in tests/studio/test_chat_thread_title_cas.py are a local import problem and reproduce identically on the merge base. tests/sh/test_uv_pinned_release.sh 14/14, test_install_pipe_safety.sh 7/7, test_install_rollback_lifecycle.sh all pass, bash -n clean.

Hardware paths and the OS x GPU product

No new hardware path is added, so there is nothing for an old one to lose to. Every line in the four installers matching CUDA, ROCm, HIP, gfx targets, Vulkan, XPU, nvidia-smi, rocminfo, --index-url or TORCH_BACKEND is byte-identical to the merge base: 372 in install.ps1, 189 in studio/setup.sh, 600 in studio/setup.ps1, and the install.sh set differs by one comment reword. WSL detection line counts are unchanged in all four files. The whole [Windows, Linux, WSL, Mac] x [NVIDIA, AMD, CPU only] product runs the same code it ran before; the only thing this PR changes upstream of it is how the uv binary arrives, and the simulations above cover that for every host in the product.

Existing installs

  • The shortcut is rewritten unconditionally on every install.ps1 run, so an upgrade over an old install picks up the RemoteSigned args. A shortcut that is never upgraded keeps Bypass and keeps working, since nothing removes it.
  • An installed uv short-circuits the whole block before any of this code is reached (if ! command -v uv in the shell scripts, if (Get-Command uv) in setup.ps1), so a working install stays exactly as it is.
  • Dropping install.ps1 from the Linux and macOS bundles cannot break resolution: resolve_install_script in install.rs only ever asks for install.sh under cfg!(unix) and only ever asks for install.ps1 otherwise, on both the dev and the bundled-resource path.
  • Nothing under studio/frontend is touched, so there is no browser-facing change to check across Firefox, Safari, Chrome or Edge.

Staging CI

Replicated onto a staging repo, which is where the .deb above came from: an unsigned Tauri build on ubuntu-22.04, since a staging repo has no Azure Trusted Signing, no Apple identity and no updater key, and none of those affect bundle contents. The matching windows-latest and macos-latest legs are running. The earlier staging pass came back green on ubuntu-latest, macos-14 and windows-latest for the installer suites plus Clean machine install and the Windows/Mac suites.

VirusTotal

The scan runs from release-desktop.yml with VIRUS_TOTAL_API_TOKEN, which only exists on this repo, so a staging build cannot be scanned. What this PR changes for that scan is concrete either way: the Linux payload no longer contains the 280 KB PowerShell script, and scripts/virustotal_scan.py now emits a Microsoft submission packet for every flagged asset rather than only for the Windows ones, so a repeat of the AppImage verdict produces something actionable instead of nothing.

… test

The pinned path picks an archive per host triple, and a wrong pick installs a
binary that cannot execute, which is worse than not installing at all. Drive
_uv_pinned_asset over 20 host combinations and require each one to return its
own triple or decline to the fallback.

Also run the installer three times over one HOME and require an identical tree,
and require a stale uv at the destination to be replaced rather than joined by a
second copy: the installer is re-run on every upgrade and every repair.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

… of musl

An independent audit pass found the Linux selector accepts any host whose ldd
output does not say musl. That is not the same question astral's installer asks:
it checks a minimum glibc and drops to its musl-static archive below it, so
three hosts that worked before this branch now get a GNU binary that cannot exec,
and the helper reports success so the fallback never runs.

  aarch64 with glibc below 2.28 (Ubuntu 18.04)
  x86_64 with glibc below 2.17 (RHEL 6)
  a musl image with no ldd at all, where the probe simply finds nothing

Read the version instead, from ldd or getconf, and require it to clear astral's
floor for the triple. Anything unreadable declines to the fallback. Also ask the
userland for its bitness rather than trusting uname on a 64-bit kernel running a
32-bit userland, and follow astral in reading hw.optional.arm64 so a translated
shell under Rosetta 2 still gets the native macOS build.

Three more from the same pass:

Report success only when the destination uv is executable. A copy onto a busy or
read-only destination could leave a file that is not, and reporting success there
skipped the fallback. Nothing is unwound on the failure path on purpose: the
fallback installs over whatever is at the destination, and deleting there would
take out a working uv the host already had.

Clear the mark of the web on the launcher we author. WriteAllText replaces the
unnamed data stream and leaves other NTFS streams alone, so a launch-studio.ps1
that somehow carried one would keep it across the rewrite, and RemoteSigned
refuses a marked unsigned script.

Store the security-block kind and resolve its wording in message(). stdout and
stderr are read by independent threads, so a [TAURI:STEP] written before a block
can be observed after it, and freezing the wording at observation time could tell
a user nothing was changed on a run that had already installed PyTorch. Also
require the error id to appear as the value of a FullyQualifiedErrorId field, so
a scanner log that merely names it cannot attach antivirus guidance to whatever
fails next.

The host matrix in the shell test grows to 28 rows covering every case above, and
removing the new gate fails 8 of them. install.rs gains two tests: 37 pass.
@danielhanchen
danielhanchen force-pushed the harden-installer-av-false-positives branch from d1f42b4 to c57ad2e Compare August 13, 2026 01:00
@danielhanchen

Copy link
Copy Markdown
Member Author

Followed up on the mapped-drive question from the comment above, and it is a real gap. A mapped network drive resolves to the same share and lands in the same zone as the UNC path it points at, so RemoteSigned refuses an unsigned launcher on Z:\Users\... exactly as it does on \\server\share\..., and -like "\\*" misses it. 2237a8ec7 keeps the -like as the fast path and falls back to DriveInfo on the path root, treating Network as remote:

$launcherIsRemote = $launcherPs1 -like "\\*"
if (-not $launcherIsRemote) {
    try {
        $launcherIsRemote = ([System.IO.DriveInfo]::new(
            [System.IO.Path]::GetPathRoot($launcherPs1))).DriveType -eq 'Network'
    } catch {}
}

The try matters: GetPathRoot on a UNC path returns \\server\share, which DriveInfo will not take, so the first branch has to stay and the second has to be allowed to fail. The \\?\ note is right and stays unreachable, since nothing the installer builds uses the extended-length prefix.

On the load-bearing last output: that is gone as of cef8011ab. Install-UvFromPinnedRelease now sets a script-scope $script:UvPinnedInstalled and the caller reads the flag, so a Write-Output added after a return cannot flip the winget fallback any more.

Also in 2237a8ec7, from review on the branch: the profile duplicate check was matching the destination anywhere on an active line, so UV_CACHE=/opt/uv in a profile suppressed the PATH export and left the next shell without uv. It now restricts to lines that touch a path, in both install.sh and studio/setup.sh. Test drives the real block against a mention-only profile.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2237a8ec77

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread install.sh Outdated
Comment on lines +5476 to +5477
if ! grep -v '^[[:space:]]*#' "$_SHELL_PROFILE" 2>/dev/null \
| grep -iF path | grep -qE "$_plp_pattern"; then

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Parse actual PATH assignments before suppressing persistence

When a startup file contains another variable whose name includes path, such as export PYTHONPATH="/opt/uv", this pipeline selects that line and the following regex treats /opt/uv as an existing PATH entry. With UV_INSTALL_DIR=/opt/uv and no inherited entry, installation works only in the current process, while later shells cannot resolve uv; studio/setup.sh has the same check. Fresh evidence in this revision is that the prior duplicate-check fix filters on any line containing the text path, rather than restricting the match to assignments that modify PATH itself.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, PYTHONPATH holds the text PATH and my filter had no name boundary. Fixed in 3b020d5be: both files now match on a line that actually sets PATH, (^|[^[:alnum:]_])(PATH[[:space:]]*=|fish_add_path|pathmunge|path_helper), so PYTHONPATH=/opt/uv and UV_CACHE=/opt/uv are both out while export PATH=, a bare PATH= and the three common helper spellings are in. Tests cover the mention-only profile for install.sh and for studio/setup.sh separately; reverting either filter fails its own case.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 3b020d5be7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen
danielhanchen merged commit 5a5bf64 into main Aug 13, 2026
77 of 97 checks passed
@danielhanchen
danielhanchen deleted the harden-installer-av-false-positives branch August 13, 2026 14:02

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a9c05de566

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread install.sh
Comment on lines +5481 to +5482
if ! grep -v '^[[:space:]]*#' "$_SHELL_PROFILE" 2>/dev/null \
| grep -E "$_PATH_LINE_RE" | grep -qE "$_plp_pattern"; then

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Ignore inline comments when detecting PATH entries

When a startup file has a PATH assignment whose inline comment mentions the destination, such as export PATH="$HOME/bin:$PATH" # /opt/uv removed, the first grep selects the line and the unanchored destination regex matches the comment. With UV_INSTALL_DIR=/opt/uv, persistence is therefore skipped even though /opt/uv is not a PATH entry, so later shells cannot resolve the pinned uv; strip inline comments or parse only the PATH assignment value before testing entries. The equivalent pipeline in studio/setup.sh has the same behavior.

Useful? React with 👍 / 👎.

danielhanchen added a commit that referenced this pull request Aug 13, 2026
#8586 went in as a single squashed commit, so main's copy of that work shares no
history with the copies this branch merged, and git saw every line the two have
in common as a conflict. Resolved file by file:

* install.sh, studio/setup.sh and tests/sh/test_uv_pinned_release.sh are #8586's
  alone and this branch never touched them, so they take main's version whole.
  That is also the newer one: #8586 gained commits after the last merge here.

* install.ps1, six hunks. The Studio launcher command, the launch-studio.ps1
  byte comparison and its Unblock-File rationale stay this branch's, since they
  are #8586's substance plus this branch's changes on top. The UNC launcher
  check, the uv source-precedence comment and the staged-probe comment take
  main's: all three are newer there, and the UNC one now covers mapped drives
  through DriveInfo, which the version here did not.

* studio/setup.ps1 takes main's on both hunks. It reads the pinned-install
  verdict off a script-scope flag rather than the pipeline, because
  Invoke-SetupCommand returns [int]$LASTEXITCODE and not the block's value, so
  the Select-Object form here could not have driven the winget fallback at all.

* studio/src-tauri/src/process.rs, one region where both sides added disjoint
  functions: this branch's managed CLI invocation builders and main's
  working-directory and environment context helpers. Both kept. The conflict cut
  through build_managed_cli_command_tokio, whose closing brace was on the far
  side, so that had to be put back by hand.

* preflight/managed.rs merged clean but not correct: main widened run_cli_probe
  and probe_cli_capability to Result so a context failure can be told apart from
  a bad install, and the two early returns this branch added still handed back
  bare values. They return Ok(false) and Ok(None): a venv with no interpreter
  beside the launcher is a verdict, not a failure to ask.

Verified on the merged tree: 4657 Python tests, 359 Rust tests, every PowerShell
suite, and #8586's test_uv_pinned_release.sh. The three frontend contract tests
and test_amd_venv_repair_loop.ps1 that were red on this branch an hour ago are
green, fixed by #8703 on main.
danielhanchen added a commit that referenced this pull request Aug 13, 2026
#8586 went in as a single squashed commit, so main's copy of that work shares no
history with the copies this branch merged, and git saw every line the two have
in common as a conflict. Resolved file by file:

* install.sh, studio/setup.sh and tests/sh/test_uv_pinned_release.sh are #8586's
  alone and this branch never touched them, so they take main's version whole.
  That is also the newer one: #8586 gained commits after the last merge here.

* install.ps1, six hunks. The Studio launcher command, the launch-studio.ps1
  byte comparison and its Unblock-File rationale stay this branch's, since they
  are #8586's substance plus this branch's changes on top. The UNC launcher
  check, the uv source-precedence comment and the staged-probe comment take
  main's: all three are newer there, and the UNC one now covers mapped drives
  through DriveInfo, which the version here did not.

* studio/setup.ps1 takes main's on both hunks. It reads the pinned-install
  verdict off a script-scope flag rather than the pipeline, because
  Invoke-SetupCommand returns [int]$LASTEXITCODE and not the block's value, so
  the Select-Object form here could not have driven the winget fallback at all.

* studio/src-tauri/src/process.rs, one region where both sides added disjoint
  functions: this branch's managed CLI invocation builders and main's
  working-directory and environment context helpers. Both kept. The conflict cut
  through build_managed_cli_command_tokio, whose closing brace was on the far
  side, so that had to be put back by hand.

* preflight/managed.rs merged clean but not correct: main widened run_cli_probe
  and probe_cli_capability to Result so a context failure can be told apart from
  a bad install, and the two early returns this branch added still handed back
  bare values. They return Ok(false) and Ok(None): a venv with no interpreter
  beside the launcher is a verdict, not a failure to ask.

Verified on the merged tree: 4657 Python tests, 359 Rust tests, every PowerShell
suite, and #8586's test_uv_pinned_release.sh. The three frontend contract tests
and test_amd_venv_repair_loop.ps1 that were red on this branch an hour ago are
green, fixed by #8703 on main.
danielhanchen added a commit that referenced this pull request Sep 15, 2026
…atchet the policy sites

Stacked on the WSL compiler fix, which shares this file.

Two problems, both found while investigating #10805, and both about the guard rather than the code
it guards.

## Two shipped scripts were in no list

`PS_SCRIPTS` and `SH_SCRIPTS` between them missed `studio/setup.bat` and `scripts/uninstall.sh`. A
shipped `.bat` is scanned like any other file, and `setup.bat` launches PowerShell, so every rule
here applies to it. That is how its `-ExecutionPolicy Bypass` survived the passes in #7822 and
#8586: the guards were reading a set of files that did not include it. Both are added to
`ALL_SCRIPTS`.

## The hidden-window pair check only ever looked at one line

`test_a_hidden_window_never_pairs_with_a_bypassed_policy` iterated `splitlines()` and compared the
two flags within a single physical line. `install.ps1` assigns `$shortcutArgs` a hidden window at
:3419 and overwrites it with a relaxed policy at :3433, fourteen lines apart in the same function,
and that passed for as long as it existed. A scanner reads the file, not the line.

Three layers now:

1. Same line, unchanged, because it gives the clearest message when it is the real shape.
2. A ratchet on how many relaxed policies the file contains at all, against `KNOWN_BYPASS_SITES`,
   which records each remaining site with the reason and what would remove it. It fails **both**
   ways: too many is a new site, too few is a stale entry that has quietly stopped guarding
   anything. This is the layer that catches a policy arriving somewhere the other two do not model.
3. Same variable, any distance: the union of everything assigned to one name must not contain both
   flags. This is the layer that sees the 3419/3433 shape.

`install.ps1`'s `$shortcutArgs` is recorded in `KNOWN_SPLIT_PAIR_VARIABLES` rather than failed on.
Removing it needs `launch-studio.ps1` written to a guaranteed-local directory first, because
`%LOCALAPPDATA%` can be folder-redirected to a UNC path where RemoteSigned refuses an unsigned
script, and a shortcut that silently does nothing is worse than the token. Recording it lets the
guard land now and lock in "no new ones", which is the part that matters going forward.

## Verification

70 passed in the suite, and each new layer was confirmed to bite rather than assumed to:

- A new relaxed policy injected into `studio/setup.sh` fails layer 2, naming the file, line number,
  the offending line, and what to do about it.
- Removing the recorded site from `studio/setup.bat` without lowering its count fails layer 2 the
  other way, telling the reader to lower the count in the same commit.
- Layer 3 proved in isolation by renaming `$shortcutArgs` to `$launchArgs` in `install.ps1`: the
  relaxed-policy count is unchanged so layer 2 passes, and layer 3 fires on its own.

The tree was restored after each and re-verified clean. `tests/studio/install/` and the shape suite
are green; `test_pr10648_offline_and_status.py::test_the_pr_only_added_new_arms_to_the_setup_status_blocks`
fails identically on `main` in a separate worktree and is untouched by this change.
danielhanchen added a commit that referenced this pull request Sep 15, 2026
…stead of arguing that it does not

Six antivirus-hardening passes have shipped (#7822, #8586, #6326, #10540, #10560, #10504). Each was
argued safe in prose, because there was no way to show it. The worry that hardening breaks
functionality is the right worry, and the answer to it is a measurement, not a more careful argument.

This lane installs from the merge base and from the candidate on two identical Windows runners and
compares four things. Zero differences is the pass condition.

- **The transcript.** Every line the installer printed, normalised. `step` pads its label to exactly
  15 columns and the output lock pins the indent, so leading whitespace is compared and only
  trailing whitespace is stripped.
- **The `.lnk` launch contract**, read back through the shell rather than taken from the installer's
  own log: target, arguments, working directory, window style, icon. `arguments` carries
  `-WindowStyle` and `-ExecutionPolicy`, which is the pair this whole effort is about, and a change
  there is completely invisible in the transcript -- which is what a prose review looks at.
- **The generated files** whose text is a contract: `launch-studio.ps1`, `unsloth.cmd`,
  `share/studio.conf`, plus the shape of the install tree.
- **Idempotency**, by installing twice. Several of the changes this lane judges touch
  content-comparison paths -- the code deciding whether a launcher needs rewriting at all -- so "a
  reinstall writes nothing" is a contract that can break silently.

## VOID is not a pass

Same commit on both sides, missing evidence, an installer that did not finish, a checkout that
resolved to the wrong tree: each is reported as "nothing was measured" and exits **3**, distinct from
**2** for "it changed", because those need different reactions from whoever reads the run.

Two of those guards exist because the failure actually happened while building this:

- A collection error on both sides compared equal to itself. Two runs that both failed to read any
  shortcut reported "1 compared, every field equal" and exited zero. Failures are symmetric far more
  often than behaviour changes are, since they come from the host and both sides share it, so the
  symmetry is no comfort at all. Any entry carrying an `error` is now VOID.
- `ConvertTo-Json` unwraps a one-element collection into a bare object, and `-AsArray` does not exist
  on Windows PowerShell 5.1. With exactly one shortcut found, `shortcuts.json` was an object;
  iterating that yields dictionary *keys*, so two different launch contracts would have compared as
  agreement. Forced to an array on the producing side and tolerated on the consuming side.

The `measure` job also asserts that `git rev-parse HEAD` equals the SHA it asked for. A checkout that
silently resolved to the default branch would make both sides the same tree, the comparison trivially
pass, and the lane report that a change broke nothing while never having seen the change.

Both sides are measured with the tools from the candidate, never each side's own copy: a base commit
that predates them has neither, and measuring two sides with two different rulers is not a
measurement.

## The comparer can fail, and that is tested

A differ reporting no differences looks identical whether it is working or broken, so the comparer
carries positive controls and refuses to produce a verdict if they fail. They run twice: once before
either install starts, so a drifted normaliser costs seconds rather than ninety minutes of runner
time ending in a meaningless green check, and once immediately before the verdict.

20 unit tests in `tests/python/test_installer_differential_comparer.py`, weighted toward the failure
direction. A changed output line, a lost indent, `RemoteSigned` becoming `Bypass` in a shortcut, a
shortcut that stopped being created, a changed generated launcher, a second run that rewrote
something -- each must be reported. One of them widens the normaliser until it erases every line and
requires the self-test to notice, because a control that cannot fail is decoration.

The other direction is tested too, since a lane that fails on every run gets disabled, which costs
the same coverage by a slower route: a `uv` patch release and a 30-second timing difference must not
fail it. Version drift is normalised away **and printed anyway** -- silently normalising something
and never mentioning it is how a lane stops being able to tell you anything. Every normalisation rule
carries a written cause, enforced by a test, because that list is exactly where a future "just make
it green" change would land.

## Cost

Two full clean-machine installs, so it opts in: the `installer-differential` label, a dispatch, or
the weekly schedule. `synchronize` is in the trigger list so a labelled PR keeps being re-measured as
it is pushed to, rather than the verdict being about whichever commit was there when the label went
on. Not a required check.

## What it cannot answer

Nothing about a third-party antivirus: hosted runners have none, and installing an endpoint agent per
run is neither fast nor faithful. Nothing about Windows PowerShell 5.1 at a real console either --
that is `windows-vt-preflight.yml`.

## Verification

- 887 passed, 9 skipped across `tests/security/`, the new comparer tests, the workflow-trigger lint
  and the installer shape suite.
- The collector was run end to end under `pwsh` on Linux, feeding the real comparer. That is what
  exposed both JSON defects above and a third: `Join-Path` throws on a null path, and composing
  `%APPDATA%` unconditionally made a parse-clean script print a binding error before doing any work.
- `Parser::ParseFile` clean on the collector; the workflow parses as YAML with the three expected
  jobs.
danielhanchen added a commit that referenced this pull request Sep 15, 2026
…already worked

Six hardening passes shipped with no measurement (#7822, #8586, #6326, #10540, #10560, #10504). There
was no baseline to measure against. There is one now: install.ps1 at commit 1ad4467 is the revision
reported in #10805, it hashes to ec29980b..., and VirusTotal holds its verdict.

## The result, run live against the real key

    | | baseline (1ad4467) | main (2c70592a) |
    | engines flagging | 1 / 60                | 1 / 61          |
    | which            | Skyhigh BehavesLike.PS.Suspicious.gr | the same |
    | Sigma            | 17 (high 1, medium 11, low 5) | 14 (medium 10, low 4) |
    | YARA             | 2                     | 0               |

The **high**-severity Sigma rule is gone. So are both crowdsourced YARA hits,
`INDICATOR_SUSPICIOUS_PWSH_B64Encoded_Concatenated_FileEXEC` and `Windows_API_Function`. Three fewer
Sigma rules overall. The Skyhigh verdict has not moved, and that is reported as unchanged rather than
dressed up: a cloud behavioural verdict is not recomputed because we deleted some code.

So the static indicators, which are what drives the alarming scores third-party analysis sites report,
already improved measurably. That was not knowable before.

Two corrections to what I wrote in the plan, both from running this rather than reasoning about it:

- I recorded current main's install.ps1 as **not on VirusTotal**. It is. It has been scanned since,
  so the delta above is real and not a projection.
- I treated the prior passes as unverifiable. They are verifiable, retroactively, and they worked on
  the axis they could affect.

## Three axes, separately

Reporting only the engine count makes every shape win look like it achieved nothing. Reporting only
Sigma overclaims. Both, or the number is not worth having.

Engines are compared **by name**, not by count. A count-only comparison calls the single most
consequential possible change -- Skyhigh's detection being replaced by Microsoft's, one engine before
and one after -- "no difference". Defender is on every Windows machine; Skyhigh is enterprise-deployed.
There is a test for exactly that case.

Sigma is compared **per severity**, not in total. Trading one high for three lows is an improvement a
total calls a regression, and the reverse is a regression a total calls an improvement.

## GET only, and VOID is not clean

There is no upload path, and that is a deliberate omission rather than an oversight. A freshly
uploaded file is a prevalence-zero, first-seen sample, which is exactly what `CloudBlockLevel
HighPlus` and ASR rule `01443614` punish -- so uploading a candidate can *create* the detection it was
meant to measure, under a hash no user will ever have. Released artefacts are uploaded by
`virustotal_scan.py` at release time; branches are not. A test parses the module and asserts no
non-GET method appears, having first been written as a grep and caught matching the module's own
explanation of why there is no upload.

So an unknown hash is VOID, exit 3, never clean. Also VOID: a missing `VT_API_KEY`, and a file
VirusTotal knows but has never analysed -- that last one being the subtle case, because zero engine
verdicts is not sixty engines clearing the file. Exit codes are distinct: 3 could-not-measure, 2
worse, 0 not worse.

## The baseline is checked, not trusted

A baseline hash copied out of an issue is a number nobody can verify, and if it ever pointed at the
wrong file every delta reported against it would be wrong while the lane looked perfectly healthy. So
both a test and a workflow step recompute it from this repository's history -- `git show
1ad4467:install.ps1` -- and assert the 427,113 bytes the sample is recorded as. A shallow clone
skips rather than fails.

## Verification

- 613 passed, 6 skipped across `tests/security/`, including 25 new tests.
- Run live against the real key; the table above is its actual output.
- Weighted toward the failure direction: a new high-severity rule, a new YARA hit, an engine swap at
  an unchanged count, and a medium promoted to high must each be reported as worse. One test replaces
  the comparison with one that reports nothing and requires the self-test to notice, because a
  control that cannot fail is decoration.
- Both parsers are fuzzed against schema drift. VirusTotal has renamed and added buckets over time,
  and a crash would break the measurement on precisely the day the schema moved.
danielhanchen added a commit that referenced this pull request Sep 15, 2026
…igned (#10982)

* AV shape guards: watch the two shipped scripts nothing watched, and ratchet the policy sites

Stacked on the WSL compiler fix, which shares this file.

Two problems, both found while investigating #10805, and both about the guard rather than the code
it guards.

## Two shipped scripts were in no list

`PS_SCRIPTS` and `SH_SCRIPTS` between them missed `studio/setup.bat` and `scripts/uninstall.sh`. A
shipped `.bat` is scanned like any other file, and `setup.bat` launches PowerShell, so every rule
here applies to it. That is how its `-ExecutionPolicy Bypass` survived the passes in #7822 and
#8586: the guards were reading a set of files that did not include it. Both are added to
`ALL_SCRIPTS`.

## The hidden-window pair check only ever looked at one line

`test_a_hidden_window_never_pairs_with_a_bypassed_policy` iterated `splitlines()` and compared the
two flags within a single physical line. `install.ps1` assigns `$shortcutArgs` a hidden window at
:3419 and overwrites it with a relaxed policy at :3433, fourteen lines apart in the same function,
and that passed for as long as it existed. A scanner reads the file, not the line.

Three layers now:

1. Same line, unchanged, because it gives the clearest message when it is the real shape.
2. A ratchet on how many relaxed policies the file contains at all, against `KNOWN_BYPASS_SITES`,
   which records each remaining site with the reason and what would remove it. It fails **both**
   ways: too many is a new site, too few is a stale entry that has quietly stopped guarding
   anything. This is the layer that catches a policy arriving somewhere the other two do not model.
3. Same variable, any distance: the union of everything assigned to one name must not contain both
   flags. This is the layer that sees the 3419/3433 shape.

`install.ps1`'s `$shortcutArgs` is recorded in `KNOWN_SPLIT_PAIR_VARIABLES` rather than failed on.
Removing it needs `launch-studio.ps1` written to a guaranteed-local directory first, because
`%LOCALAPPDATA%` can be folder-redirected to a UNC path where RemoteSigned refuses an unsigned
script, and a shortcut that silently does nothing is worse than the token. Recording it lets the
guard land now and lock in "no new ones", which is the part that matters going forward.

## Verification

70 passed in the suite, and each new layer was confirmed to bite rather than assumed to:

- A new relaxed policy injected into `studio/setup.sh` fails layer 2, naming the file, line number,
  the offending line, and what to do about it.
- Removing the recorded site from `studio/setup.bat` without lowering its count fails layer 2 the
  other way, telling the reader to lower the count in the same commit.
- Layer 3 proved in isolation by renaming `$shortcutArgs` to `$launchArgs` in `install.ps1`: the
  relaxed-policy count is unchanged so layer 2 passes, and layer 3 fires on its own.

The tree was restored after each and re-verified clean. `tests/studio/install/` and the shape suite
are green; `test_pr10648_offline_and_status.py::test_the_pr_only_added_new_arms_to_the_setup_status_blocks`
fails identically on `main` in a separate worktree and is untouched by this change.

* Load the installer scripts under RemoteSigned instead of relaxing the policy

Removes three of the four relaxed execution policies the ratchet in the previous commit recorded.
RemoteSigned refuses an unsigned script only in the Internet or Untrusted zone, so for a local,
unmarked script it behaves identically to Bypass while dropping a token endpoint products score.

## studio/setup.bat

`powershell -ExecutionPolicy Bypass -File "%~dp0setup.ps1"` becomes RemoteSigned. setup.ps1 ships
beside the batch file inside an installed package, so it is MyComputer-zone and loads unsigned
either way.

One population could regress: a package unzipped from a download, where setup.ps1 carries a mark of
the web that RemoteSigned honours and Bypass ignored. So the mark is cleared first. Execution policy
governs script *files* and not `-Command`, so that call runs under any machine policy, and clearing
an absent stream writes nothing. The path travels in an environment variable rather than being
interpolated into the command string, because an apostrophe in an install path is a real Windows user
name and would otherwise break the quoting.

`-NoProfile` is on the unblock call and deliberately **not** on the launch. The launch has always run
setup.ps1 with profiles loaded, and `tests/studio/test_amd_venv_repair_loop.ps1` drives a profile
that sets `Set-StrictMode -Version Latest` against it. Adding the flag would have retired that
coverage with nothing failing, so the new test asserts its absence and says why.

## scripts/uninstall.ps1 and README.md

Both print `Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass` as the documented way to run
a cloned script. Changed to RemoteSigned rather than dropped: the Windows client default is
`Restricted`, which blocks every script file including a local unsigned one, so the
`Set-ExecutionPolicy` itself is load-bearing and removing it would break the documented path.
RemoteSigned is sufficient because a git clone carries no mark of the web, and both now say so and
point a zip user at `Unblock-File`, which is the case where the two policies genuinely differ.

The uninstaller line is never executed -- it lives in the printed `_Usage` here-string -- but AMSI
scans the file whole and a classifier cannot tell a string from a statement.

## Where that leaves the ratchet

Four recorded sites down to one. The survivor is `install.ps1:3433`, the roaming-profile fallback for
a launcher on a share, and it stays because `%LOCALAPPDATA%` can be folder-redirected to a UNC path
where RemoteSigned would refuse the launcher, and a desktop shortcut that silently does nothing is
worse than the token. Removing it needs `launch-studio.ps1` written to a guaranteed-local directory
first, which is a larger change than this one.

## Verification

- 751 passed, 6 skipped across the shape suite, `tests/test_installer_interactive_prompts.py` and
  `tests/security/`. All of `tests/sh` passing. The parse gate clean over all three `.ps1` files.
- Both new `setup.bat` assertions confirmed to bite: adding `-NoProfile` to the launch fails with the
  reason and names the test that would lose coverage, and reverting the policy to Bypass fails naming
  the offending line. The tree was restored after each.
- Relaxed-policy sites counted directly across all seven shipped scripts afterwards: one, in
  install.ps1, as recorded.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Step setup.bat down to Bypass for a script on a share, the way install.ps1 already does

Tightening setup.bat from Bypass to RemoteSigned had one case that is a genuine regression rather
than a theoretical one, and it needed handling rather than accepting.

Execution policy is judged on the script file's ZONE. A plain \\server\share and a mapped drive are
Intranet and load fine under RemoteSigned -- but a dotted-FQDN UNC (\\corp.example.com\...), a DFS
path or an IP-literal share is the Internet zone, where RemoteSigned refuses an unsigned script. And
Unblock-File cannot save that case: with no Zone.Identifier stream present the PATH decides, so
clearing a stream that was never there changes nothing and exits silently. Bypass worked; RemoteSigned
does not.

install.ps1:3405-3421 already solves exactly this when it writes the Start Menu shortcut -- UNC
prefix, then DriveInfo.DriveType -eq 'Network' -- and the new test's own comment calls that site "the
only one that is genuinely load-bearing" for the same reason. setup.bat got no such exemption. Now it
reuses the identical logic rather than inventing a second answer.

The probe does the Unblock-File too, so this costs one process rather than two, and it runs under
-Command, which execution policy does not govern at all.

Two details that matter more than they look:

- The batch variable DEFAULTS to RemoteSigned. A probe that fails to run therefore leaves the
  tightened policy in place rather than silently restoring the relaxed one.
- -NoProfile is on the probe and still deliberately absent from the launch.
  tests/studio/test_amd_venv_repair_loop.ps1 drives a profile that sets Set-StrictMode against
  setup.ps1, and adding it would retire that coverage with nothing failing.

Tests: the embedded probe is extracted from the batch file and PARSED, because it is one long line
inside a `for /f` backquote block and a syntax error there fails quietly -- the `for /f` captures
nothing, the RemoteSigned default stands, and the mark is never cleared, so an unzipped download gets
a refusal with no hint that the probe was what broke. The pre-existing setup.bat test located the
launch by literal filename, which is now an environment variable, so it matches on the flags instead.

5713 passed, 39 skipped across tests/studio/test_installer_av_shapes.py, tests/studio/install/ and
tests/security/. The single failure, test_pr10648_offline_and_status, is pre-existing on main.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Group the hidden/bypass pair by casefolded variable name

PowerShell variable names are not case-sensitive, so $shortcutArgs and $ShortcutArgs are one
variable. The same-variable layer keyed its map on the captured spelling, so writing the two
assignments with different capitalisation filed them as two unrelated names, each holding only
one of the two flags, and the pair went through. The file-wide ratchet did not catch it either,
since install.ps1 already records one permitted relaxed policy.

Verified by constructing that exact evasion: renaming the two install.ps1 assignments to
$launchArgs and $LaunchArgs passes under the old grouping and fails under this one, naming
both spellings.

* Stop the installers from explaining, in prose a classifier reads, which antivirus flagged them (#10990)

* Stop the installers from explaining, in prose a classifier reads, which antivirus flagged them

PowerShell hands the entire top-level script block to AMSI at compile time, before the first
statement runs, so every byte of install.ps1 is classifier input -- comments included. VirusTotal's
analysis of the file quoted one of our own comments back as grounds for suspicion:

  "The presence of comments that suggest the script is designed to evade detection by security
  tools (e.g. "AMSI scans this file in full before a line of it runs") further adds to the
  suspicion."

Six hardening passes wrote careful explanations of which product flagged which shape directly into
the files being scanned. The explanations are worth keeping. Their location is not.

- A comment in a shipped script says **what the code does and what breaks if you change it**.
- `AV_SHAPES_RECORD`, in `tests/studio/test_installer_av_shapes.py`, says **which scanner flagged
  which shape, and when**.

The record lives in that test rather than a doc because the file already owns the guards that enforce
the split, it ships to nobody, it is not packaged, and nothing scans it. Each relocated comment keeps
its operational content verbatim and gains a pointer. The diff over the five shipped scripts contains
no non-comment line, which is checked mechanically rather than asserted.

The record is not a dumping ground. It holds the measured detections (Skyhigh
`BehavesLike.PS.Suspicious.gr` on install.ps1, Bitdefender `Gen:Variant.MSILHeracles.272113` on the
csc.exe output in #10540, Kaspersky `HEUR:Trojan.VBS.Agent.gen` on the .vbs launcher shape, the two
fixture archives that made Panda flag the repo zip), the measured before-and-after from
`virustotal_delta.py` including the part that did NOT move, why each decision is a robustness fix and
not an evasion, the five shapes we are **keeping** on purpose with the reason each is load-bearing,
and how to report a new detection.

Three things a future pass will otherwise rediscover are written down there, because each one already
cost a wrong proposal: execution policy is evaluated against the script file's zone and not against
who launched PowerShell, so a `.cmd` shim cannot launder a remote-zone script; UNC paths are a remote
zone, which is the whole reason install.sh resolves the Windows `%TEMP%`; and the Windows client
default is `Restricted`, so documentation telling a user to set a process-scoped policy is
load-bearing and only the word `Bypass` needed to go.

A banned-token test alone is satisfiable by deleting the knowledge rather than moving it, so there
are three:

- `test_no_shipped_script_names_a_detection` over every shipped script including `studio/setup.bat`
  and `scripts/uninstall.sh`, which no shape test read before.
- `test_the_record_survives_and_keeps_its_evidence`, which requires the sections AND the specific
  detection strings -- a record with headings and no evidence is the same loss with extra steps.
- `test_every_script_that_dropped_its_explanation_points_at_the_record`, because a comment reduced to
  "security software blocks this" with no forward reference is worse than the prose it replaced: the
  next maintainer cannot tell whether it is still true.

Deliberately not banned: `antivirus`, `quarantine`, `scanner`, `blocked`. Those describe a real
runtime hazard the code handles and one of them reaches the user.

Also not banned, for a more interesting reason: **`false positive`**. It was on the list, and the
test immediately found it in install.ps1 and studio/setup.ps1 -- where it means a *statistical* false
positive in a registry probe and has nothing to do with a scanner. A token list is only as good as
its words having one meaning, and that one does not.

- 14 of the new assertions fail against `main` and none against this branch, so they are proved to
  bite rather than to pass vacuously.
- No non-comment line changed in any of the five scripts (`git diff -U0` filtered for lines that are
  not comments returns empty).
- `bash -n` clean on both shell scripts; `Parser::ParseFile` clean on all three `.ps1` files.
- Existing tests and CI that reference the old detection strings are unaffected: they live in
  `tests/` and `.github/`, which ship to nobody and are scanned by nothing.
- One self-inflicted bug caught while writing this: a blanket rename of the old doc path rewrote the
  "must not still point at the doc" assertion into asserting the opposite. The stale path is now
  assembled from fragments so a future rename cannot do it again.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Match banned vendor tokens on word boundaries, and drop the one that cannot work

The guard searched for each token as a raw substring, so it rejected ordinary installer prose:
'panda' is inside 'pandas', a real dependency name, and 'rising' is inside 'surprising',
'arising' and 'comprising'. The failure message then accuses a normal sentence of naming an
antivirus vendor, and the fix the next reader reaches for is to delete the guard.

Boundaries are conditional on the token's own edges, because 'heur:' and 'gen:variant' sit on a
colon where \b asserts the opposite of what is wanted.

'rising' is removed rather than bounded. It is a real engine and one of the two that flagged the
fixture archives, but the word is also ordinary English -- 'rising memory use' is a sentence
someone will write -- and no amount of boundary matching separates the two. A guard that fails on
valid prose is worth less than nothing. 'tencent', the other engine that flagged those archives,
has no such problem and stays.

Verified both directions against studio/setup.sh: a comment naming Bitdefender, Gen:Variant and
Panda still produces three failures, while 'rising memory use' plus 'installs pandas' now passes
and produced two misleading failures before.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit that referenced this pull request Sep 15, 2026
…already worked (#10996)

* Give this work a before-and-after number, and find out the hardening already worked

Six hardening passes shipped with no measurement (#7822, #8586, #6326, #10540, #10560, #10504). There
was no baseline to measure against. There is one now: install.ps1 at commit 1ad4467 is the revision
reported in #10805, it hashes to ec29980b..., and VirusTotal holds its verdict.

## The result, run live against the real key

    | | baseline (1ad4467) | main (2c70592a) |
    | engines flagging | 1 / 60                | 1 / 61          |
    | which            | Skyhigh BehavesLike.PS.Suspicious.gr | the same |
    | Sigma            | 17 (high 1, medium 11, low 5) | 14 (medium 10, low 4) |
    | YARA             | 2                     | 0               |

The **high**-severity Sigma rule is gone. So are both crowdsourced YARA hits,
`INDICATOR_SUSPICIOUS_PWSH_B64Encoded_Concatenated_FileEXEC` and `Windows_API_Function`. Three fewer
Sigma rules overall. The Skyhigh verdict has not moved, and that is reported as unchanged rather than
dressed up: a cloud behavioural verdict is not recomputed because we deleted some code.

So the static indicators, which are what drives the alarming scores third-party analysis sites report,
already improved measurably. That was not knowable before.

Two corrections to what I wrote in the plan, both from running this rather than reasoning about it:

- I recorded current main's install.ps1 as **not on VirusTotal**. It is. It has been scanned since,
  so the delta above is real and not a projection.
- I treated the prior passes as unverifiable. They are verifiable, retroactively, and they worked on
  the axis they could affect.

## Three axes, separately

Reporting only the engine count makes every shape win look like it achieved nothing. Reporting only
Sigma overclaims. Both, or the number is not worth having.

Engines are compared **by name**, not by count. A count-only comparison calls the single most
consequential possible change -- Skyhigh's detection being replaced by Microsoft's, one engine before
and one after -- "no difference". Defender is on every Windows machine; Skyhigh is enterprise-deployed.
There is a test for exactly that case.

Sigma is compared **per severity**, not in total. Trading one high for three lows is an improvement a
total calls a regression, and the reverse is a regression a total calls an improvement.

## GET only, and VOID is not clean

There is no upload path, and that is a deliberate omission rather than an oversight. A freshly
uploaded file is a prevalence-zero, first-seen sample, which is exactly what `CloudBlockLevel
HighPlus` and ASR rule `01443614` punish -- so uploading a candidate can *create* the detection it was
meant to measure, under a hash no user will ever have. Released artefacts are uploaded by
`virustotal_scan.py` at release time; branches are not. A test parses the module and asserts no
non-GET method appears, having first been written as a grep and caught matching the module's own
explanation of why there is no upload.

So an unknown hash is VOID, exit 3, never clean. Also VOID: a missing `VT_API_KEY`, and a file
VirusTotal knows but has never analysed -- that last one being the subtle case, because zero engine
verdicts is not sixty engines clearing the file. Exit codes are distinct: 3 could-not-measure, 2
worse, 0 not worse.

## The baseline is checked, not trusted

A baseline hash copied out of an issue is a number nobody can verify, and if it ever pointed at the
wrong file every delta reported against it would be wrong while the lane looked perfectly healthy. So
both a test and a workflow step recompute it from this repository's history -- `git show
1ad4467:install.ps1` -- and assert the 427,113 bytes the sample is recorded as. A shallow clone
skips rather than fails.

## Verification

- 613 passed, 6 skipped across `tests/security/`, including 25 new tests.
- Run live against the real key; the table above is its actual output.
- Weighted toward the failure direction: a new high-severity rule, a new YARA hit, an engine swap at
  an unchanged count, and a medium promoted to high must each be reported as worse. One test replaces
  the comparison with one that reports nothing and requires the self-test to notice, because a
  control that cannot fail is decoration.
- Both parsers are fuzzed against schema drift. VirusTotal has renamed and added buckets over time,
  and a crash would break the measurement on precisely the day the schema moved.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Read the VirusTotal secret this repository actually has, so the lane can measure something

`secrets.VT_API_KEY` does not exist. `VT_API_KEY` is the ENV VAR name the Python reads
(`scripts/virustotal_scan.py:37`); the repository secret is `VIRUS_TOTAL_API_TOKEN`, which is the only
VirusTotal secret in all 51 workflows, and `release-desktop.yml:2193` maps it the same way.

As written the expression expanded to empty and the lane exited 3 / VOID on every dispatch. That is
the right failure shape -- it refuses to report a clean it did not measure -- but a lane that can
never measure anything is not worth having, and the failure only surfaces after someone dispatches
it and waits.

Two guards added, because both halves of this were invisible:

- `test_the_workflow_reads_the_secret_this_repository_actually_has` pins the secret name in both
  directions and also asserts the checkout keeps `fetch-depth: 0`, since the step that reverifies
  the baseline against commit 1ad4467 reverifies nothing on a shallow clone.
- `test_the_baseline_hash_is_the_file_the_reporter_ran` now checks the constant's shape
  unconditionally before the git half. That git half skips on a shallow clone, which is every CI lane
  that collects `tests/security` -- so the one assertion tying the baseline to real history was green
  locally and silently absent everywhere it mattered.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Compare Sigma severities in order, and void an unanalysed baseline too

The per-severity comparison reported each bucket independently, which cannot express a trade:
swapping the single high rule for three extra low ones moves two buckets in opposite
directions, so it landed in worse and in better at once and exit_code answered worse. The
comment beside that loop calls exactly that swap an improvement. SEVERITIES is ordered most
severe first, so the most severe bucket that moved now decides and the rest are reported
alongside it without flipping the verdict.

The zero-engine guard was on the candidate only. A baseline hash VirusTotal knows but has never
analysed carries no engines, no Sigma and no YARA, so every finding on the candidate read as
newly introduced and the run exited 2 having compared against nothing.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Bound the lookups, keep ruleset identity, and escape third-party text

Neither lookup carried a deadline, and request can spend four 300-second socket attempts plus 20,
40 and 80 seconds of backoff. The workflow gives the whole job 20 minutes, so the baseline lookup
alone could exhaust it and the runner would kill the step before it fetched the candidate or wrote
its summary, which is a lost run rather than a reported one. Both lookups now share a 420 second
budget and an expired budget is reported as VOID, since we did not find out.

YARA hits were keyed on the rule name alone, so the same rule identifier appearing in two
crowdsourced rulesets collapsed to one entry: a candidate could gain a hit from a second ruleset,
parse to the same list as the baseline, and exit 0 on a real regression. Keyed on ruleset and rule
now.

Engine names and detection labels are third-party text and the report is appended to
GITHUB_STEP_SUMMARY, where a newline ends the row, a pipe opens a cell and an angle bracket starts
HTML that GitHub renders. virustotal_scan._md_text exists for exactly this and the report was
bypassing it; reused rather than duplicated.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Stop labelling an overridden baseline as the recorded install.ps1

A dispatch can supply baseline_sha256, and the lookup and the comparison then use that hash while
the header still announced the recorded identity and printed install.ps1's historical scores
beside the override's live table. That is an artifact built to be misattributed: the numbers
belong to one file and the name to another.

The note is now printed only when the baseline hash really is the recorded one, and an override
says so and disclaims the historical comparison.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Catch a spent deadline in the VirusTotal delta lookup

VirusTotalClient.request signals an expired deadline with TimeoutError,
which inherits from OSError rather than RuntimeError, so the handler in
fetch never ran and the workflow died with a traceback before render
wrote its summary. That is the lost run the deadline was meant to
prevent. Catch both and keep returning a VOID row.

* Keep Sigma buckets this tool cannot rank

The parser warned in its own docstring that VirusTotal renames and adds
severity buckets, then read a fixed key list, so a candidate that gained
rules only in a new bucket produced a dictionary identical to the
baseline's and the run exited 0 on a regression. Keep every reported
bucket. Unrankable ones stay out of the ordered trade-off, which depends
on knowing which of two buckets is more severe, and a rise in one is
reported as worse rather than assumed minor.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Count every engine verdict bucket, not the five the dataclass carries

parse_stats names type-unsupported and failure as categories VirusTotal
has added, but ScanStats has fields only for five buckets, so the engine
count this report prints was short by however many engines answered that
way, and a response made up entirely of those buckets summed to zero and
voided the run as unanalysed. Sum every numeric bucket from the raw
stats, which leaves the shared dataclass alone for the release scanner.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Require an explicit verdict before calling an engine cleared

An engine that flagged the baseline and is absent from the candidate's
results has not cleared it, it did not evaluate it, and a set difference
cannot tell those apart. Since Skyhigh is the one engine that actually
flags this file, a sparse candidate analysis could print the single most
consequential sentence in the report and exit 0. Track which engines
returned a verdict of any kind, call only an answering non-flagging
engine cleared, and report the silent ones as an unanswered question.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Only a conclusive verdict clears a prior detection

The responder set was built on the truthiness of the category, so
timeout, confirmed-timeout, failure and type-unsupported counted as
answers while parse_detections correctly left them out of the flagging
list. An engine returning one of those appeared in neither set and was
reported as having stopped flagging the candidate, which is the same
mistake as treating absence as a clean verdict.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit that referenced this pull request Sep 15, 2026
…hine (#10978)

* WSL installer: stop running the C# compiler on the user's Windows machine

`install.sh` generates a PowerShell script and runs it on the Windows side to create the WSL
shortcut. Two constructs in that path were removed from `install.ps1` in earlier passes and left
live here, where nothing looked:

- `install.sh:2249` declared `SHChangeNotify` with `Add-Type -MemberDefinition`. On Windows
  PowerShell 5.1 that writes C# to `%TEMP%` and runs `csc.exe`, producing a DLL on the user's
  machine. #10540 traced exactly that chain to Bitdefender `Gen:Variant.MSILHeracles.272113`:
  `unsloth-stud... -> powershell.exe -> csc.exe -> %TEMP%\<random>.dll`. It replaced the
  declaration in `install.ps1` with reflection emit and missed this copy.
- `install.sh:2273` launched the generated script with `-ExecutionPolicy Bypass`, the flag #7822
  removed everywhere else.

Neither was caught because `test_the_installer_never_runs_the_c_sharp_compiler` parametrised over
`("install.ps1", "studio/setup.ps1")` only, and `windows-no-compiler-ci.yml` did not list
`install.sh` in its path triggers. A shell script that emits PowerShell can put a compiler on a
Windows machine without touching a `.ps1`.

## The compile

`SHChangeNotify` is now emitted, mirroring `install.ps1:3485-3499`: a `DefineDynamicAssembly` /
`DefineDynamicModule` / `DefineType` / `DefinePInvokeMethod` / `CreateType` block inlined, since the
generated script is standalone and cannot call `New-StudioEmittedNativeType`. The enclosing
`try {} catch {}` stays, so a failure still costs only a stale icon, and both notifications stay:
per-item `SHCNE_UPDATEITEM` + `SHCNF_PATHW` per `.lnk`, then the global `SHCNE_ASSOCCHANGED`. The
per-item call is not redundant, and the `ALLOWED_PINVOKES` entry records why: `ie4uinit.exe -show`
does not recover a stale same-name `.lnk`.

I ran the emitted type rather than assuming it: under pwsh it produces
`void SHChangeNotify(Int32, UInt32, String, IntPtr)`, identical to the `Add-Type` declaration,
`PreserveSig` set, and `Assembly.Location` empty, which is the point. Nothing reaches disk.

## The execution policy

`Bypass` was load-bearing, for one reason: `wslpath -w /tmp/unsloth-shortcut-XXXXXX.ps1` yields a
`\\wsl.localhost\<distro>\...` UNC path, PowerShell treats a script there as remote, and
`RemoteSigned` refuses an unsigned remote script. So rather than relax the policy, the script now
goes to the Windows `%TEMP%` (`cmd.exe /c echo %TEMP%`, CR stripped, `wslpath -u`), which is a local
volume and therefore `MyComputer` zone, where `RemoteSigned` loads it unsigned. Same generated
script, same launch, same result.

When `%TEMP%` cannot be resolved there is deliberately **no fallback to WSL's `/tmp`**, because that
is the case that needed the relaxed policy in the first place. Nothing is allocated and the caller
takes the notice it already prints when interop is unavailable. That population is very nearly the
population where interop is already broken.

## Tripwires, with messages that say what is wrong

`tests/sh/test_wsl_shortcut_script_location.sh` evals the real resolution block out of `install.sh`
with `cmd.exe` and `wslpath` stubbed, covering resolved, no-interop, unexpanded `%TEMP%`, and a
`%TEMP%` that is not a directory, then asserts statically that the launch uses `RemoteSigned`, that
the file relaxes the policy nowhere, that it compiles no C#, and that both refreshes survive. A
failed extraction is reported as a failure rather than exiting early, so the output names every
problem at once, and it still fails closed.

`clean-machine-install-ci.yml`'s `wsl` job is the only lane that runs this branch, so it gains the
behavioural half: read the created `.lnk` back and refuse a script-host target, require the
generated script to have been cleaned up, and fail on any `.cmdline`/`.rsp` under the Windows
`%TEMP%`, which is csc.exe output and nothing else. That check plants two intermediates and requires
the search to find both before trusting a negative result, because a detector that sees nothing looks
exactly like a clean run and every reason it might see nothing is silent. If the control does not
fire the job fails as a broken detector instead of reporting a pass. Shortcut absence is a warning,
not an error, since the installer itself treats shortcut creation as best-effort.

`install.sh` is added to the compiler test's parametrise list and to
`windows-no-compiler-ci.yml`'s paths. The `DefinePInvokeMethod` assertion in that test becomes
conditional on the file declaring a native import at all, so it does not fail for being satisfied on
`scripts/uninstall.ps1` or `studio/setup.sh`.

## Verification

- The new shell suite: 16 passed on this branch, and against `main` in a worktree it exits 1 with 6
  named failures. Proved to bite rather than assumed to.
- The generated WSL script rendered and parsed with
  `[System.Management.Automation.Language.Parser]::ParseFile`: clean over 765 tokens. No existing
  gate parses that here-string, and this change edits it.
- `bash -n` and `sh -n` on `install.sh`; all of `tests/sh` passing; the parse gate clean over
  `install.ps1`, `studio/setup.ps1` and `scripts/uninstall.ps1`.
- `tests/studio/test_installer_av_shapes.py`, `tests/studio/install/`, `tests/security/`: green.
- The new CI PowerShell parsed standalone, and its positive control plus detector exercised for real
  against a planted `csc.exe`-style intermediate: control 2 of 2, simulated compile caught, clean
  directory reports zero.

I have no Windows or WSL here, so the runtime behaviour of the shortcut path rests on the
`clean-machine-install-ci.yml` WSL job, not on a local run. This is a shape fix with a confirmed
detection behind the shape; it is not a claim that any particular user report is resolved.

* Fix a test of mine that passed for the wrong reason, and could only fail on a real CI machine

`test_wsl_shortcut_script_location.sh` asserted that the generated shortcut script's path does not
start with `/tmp`, as a proxy for "not in WSL's own temp, which wslpath turns into a \\wsl.localhost
UNC path that RemoteSigned refuses". The proxy is broken: the harness builds its *fake Windows temp*
with `mktemp -d`, so on any machine with `TMPDIR=/tmp` -- which is every normal CI runner -- the
stub's own directory matched the pattern and the test failed while install.sh was behaving exactly as
intended.

It passed locally only because this workspace sets `TMPDIR` elsewhere. That is precisely the class of
accidental pass the rest of this work has been built to catch, so it is worth naming rather than
quietly correcting.

The replacement asserts the property the proxy was standing in for, structurally: the block contains
exactly one `mktemp`, so there is no second path to fall back to, and that `mktemp` allocates inside
`$_css_win_temp`. Both are true or false regardless of where anyone's temp directory happens to live.

Verified under the exact condition that broke it: `TMPDIR=/tmp` gives 17 passed, 0 failed on this
branch, and 6 failed on `main` in a clean worktree -- so the test still bites.

* WSL installer: read %TEMP% with cmd /d, so an AutoRun command cannot cost the user their shortcut

Reading the Windows %TEMP% through interop is new in this branch, and it reads it with
`cmd.exe /c echo %TEMP%`. Without /d, cmd first runs the AutoRun command from
HKLM or HKCU \Software\Microsoft\Command Processor, and `cmd /c` is not exempt from
that. AutoRun writes to the same stdout, so its output arrives ahead of the path and
`tr -d '\r\n'` glues the two into one string. wslpath then rejects it, the directory
check fails, and the branch takes its "couldn't create the Windows shortcut" notice.

Clink sets an AutoRun, so Cmder does, and so do plenty of corporate images. Every one
of those users got a working shortcut before this branch and would silently stop
getting one, while being told WSL interop is disabled, which is not what happened.

So: /d, which is the cheap fix rather than out-parsing whatever prints. Then the last
line rather than the whole stream, for anything that still reaches stdout by another
route, and trailing blanks trimmed, because Win32 strips them from a path and [ -d ]
does not, so a %TEMP% set with one resolved to a directory that appeared not to exist.
The || stays: this file runs under set -e, where a failed substitution ends the install.

Tests
-----
tests/sh/test_wsl_shortcut_script_location.sh grows the AutoRun and trailing-blank
cases and a static check for /d, and its wslpath stub is now input-sensitive. It was
not, and that mattered: a stub that returns the fake Windows temp whatever it is handed
cannot tell "install.sh read the path" from "install.sh read a banner glued to a path",
so both new cases passed against the unfixed file until the stub compared its argument.
Against the unfixed install.sh the four new assertions fail; with it they pass.

tests/studio/test_wsl_shortcut_script_is_valid_powershell.py is new and covers a gap
nothing else did: that what install.sh generates is PowerShell at all. bash -n sees the
here-string as a here-string, the contents only run on Windows with both streams sent to
/dev/null, and the icon-refresh block runs inside try/catch, so a parse error there is
not a crash and not a message, just no shortcut and a misleading notice. The block was
just rewritten into a twenty-line reflection-emit sequence, which is when that matters
most. The file renders the here-string with a real shell rather than keeping a copy,
parses it, and then executes the emit sequence retargeted at a symbol this host exports,
so a wrong call order or argument count fails on Linux. Five mutations of the shipped
file were tried; four fail it, and the docstring names the fifth that does not and why.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Watch the WSL install live, instead of searching for what CodeDom already deleted

The lane looked for .cmdline and .rsp files in the Windows temp after the install had finished.
CodeDom removes its whole intermediate directory once the assembly is loaded, which
Watch-ForCompiler.ps1 records as a before-and-after diff seeing nothing at all while 4688 recorded
csc.exe, so that search could not fail for the case this lane exists to catch. Its positive
control planted persistent files, which proves the search can traverse a directory and nothing
about whether ephemeral compiler output is observable.

The install now runs inside Invoke-WithCompilerWatch, the same detector windows-no-compiler-ci.yml
uses, which unions 4688 with a live FileSystemWatcher and treats an unreadable Security log as
void rather than clean. The dropped-library half is checked too, since that is what the
Bitdefender report in #10540 keyed on. The post-hoc listing stays for what genuinely is left
behind, which is the other half of the union, and its message now says that is what it means.

Watch-ForCompiler.ps1 is in both path filters now, because this job's detection depends on it, and
the new guard is registered in the unfiltered lint job since it reads a workflow file.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Arm the 4688 half of the compiler watch in the WSL lane

Watch-ForCompiler.ps1 requires the caller to enable process creation
auditing, and this job never did, so its Security log query returned an
empty compiler list whatever ran while the step still printed that no
compiler process was seen. Enable and verify the audit policy before the
install, and require a deliberate compile to be detected first, so a
clean verdict is distinguishable from a detector that never attached.

* Close the AV shape-guard holes, and load the installers under RemoteSigned (#10982)

* AV shape guards: watch the two shipped scripts nothing watched, and ratchet the policy sites

Stacked on the WSL compiler fix, which shares this file.

Two problems, both found while investigating #10805, and both about the guard rather than the code
it guards.

## Two shipped scripts were in no list

`PS_SCRIPTS` and `SH_SCRIPTS` between them missed `studio/setup.bat` and `scripts/uninstall.sh`. A
shipped `.bat` is scanned like any other file, and `setup.bat` launches PowerShell, so every rule
here applies to it. That is how its `-ExecutionPolicy Bypass` survived the passes in #7822 and
#8586: the guards were reading a set of files that did not include it. Both are added to
`ALL_SCRIPTS`.

## The hidden-window pair check only ever looked at one line

`test_a_hidden_window_never_pairs_with_a_bypassed_policy` iterated `splitlines()` and compared the
two flags within a single physical line. `install.ps1` assigns `$shortcutArgs` a hidden window at
:3419 and overwrites it with a relaxed policy at :3433, fourteen lines apart in the same function,
and that passed for as long as it existed. A scanner reads the file, not the line.

Three layers now:

1. Same line, unchanged, because it gives the clearest message when it is the real shape.
2. A ratchet on how many relaxed policies the file contains at all, against `KNOWN_BYPASS_SITES`,
   which records each remaining site with the reason and what would remove it. It fails **both**
   ways: too many is a new site, too few is a stale entry that has quietly stopped guarding
   anything. This is the layer that catches a policy arriving somewhere the other two do not model.
3. Same variable, any distance: the union of everything assigned to one name must not contain both
   flags. This is the layer that sees the 3419/3433 shape.

`install.ps1`'s `$shortcutArgs` is recorded in `KNOWN_SPLIT_PAIR_VARIABLES` rather than failed on.
Removing it needs `launch-studio.ps1` written to a guaranteed-local directory first, because
`%LOCALAPPDATA%` can be folder-redirected to a UNC path where RemoteSigned refuses an unsigned
script, and a shortcut that silently does nothing is worse than the token. Recording it lets the
guard land now and lock in "no new ones", which is the part that matters going forward.

## Verification

70 passed in the suite, and each new layer was confirmed to bite rather than assumed to:

- A new relaxed policy injected into `studio/setup.sh` fails layer 2, naming the file, line number,
  the offending line, and what to do about it.
- Removing the recorded site from `studio/setup.bat` without lowering its count fails layer 2 the
  other way, telling the reader to lower the count in the same commit.
- Layer 3 proved in isolation by renaming `$shortcutArgs` to `$launchArgs` in `install.ps1`: the
  relaxed-policy count is unchanged so layer 2 passes, and layer 3 fires on its own.

The tree was restored after each and re-verified clean. `tests/studio/install/` and the shape suite
are green; `test_pr10648_offline_and_status.py::test_the_pr_only_added_new_arms_to_the_setup_status_blocks`
fails identically on `main` in a separate worktree and is untouched by this change.

* Load the installer scripts under RemoteSigned instead of relaxing the policy

Removes three of the four relaxed execution policies the ratchet in the previous commit recorded.
RemoteSigned refuses an unsigned script only in the Internet or Untrusted zone, so for a local,
unmarked script it behaves identically to Bypass while dropping a token endpoint products score.

## studio/setup.bat

`powershell -ExecutionPolicy Bypass -File "%~dp0setup.ps1"` becomes RemoteSigned. setup.ps1 ships
beside the batch file inside an installed package, so it is MyComputer-zone and loads unsigned
either way.

One population could regress: a package unzipped from a download, where setup.ps1 carries a mark of
the web that RemoteSigned honours and Bypass ignored. So the mark is cleared first. Execution policy
governs script *files* and not `-Command`, so that call runs under any machine policy, and clearing
an absent stream writes nothing. The path travels in an environment variable rather than being
interpolated into the command string, because an apostrophe in an install path is a real Windows user
name and would otherwise break the quoting.

`-NoProfile` is on the unblock call and deliberately **not** on the launch. The launch has always run
setup.ps1 with profiles loaded, and `tests/studio/test_amd_venv_repair_loop.ps1` drives a profile
that sets `Set-StrictMode -Version Latest` against it. Adding the flag would have retired that
coverage with nothing failing, so the new test asserts its absence and says why.

## scripts/uninstall.ps1 and README.md

Both print `Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass` as the documented way to run
a cloned script. Changed to RemoteSigned rather than dropped: the Windows client default is
`Restricted`, which blocks every script file including a local unsigned one, so the
`Set-ExecutionPolicy` itself is load-bearing and removing it would break the documented path.
RemoteSigned is sufficient because a git clone carries no mark of the web, and both now say so and
point a zip user at `Unblock-File`, which is the case where the two policies genuinely differ.

The uninstaller line is never executed -- it lives in the printed `_Usage` here-string -- but AMSI
scans the file whole and a classifier cannot tell a string from a statement.

## Where that leaves the ratchet

Four recorded sites down to one. The survivor is `install.ps1:3433`, the roaming-profile fallback for
a launcher on a share, and it stays because `%LOCALAPPDATA%` can be folder-redirected to a UNC path
where RemoteSigned would refuse the launcher, and a desktop shortcut that silently does nothing is
worse than the token. Removing it needs `launch-studio.ps1` written to a guaranteed-local directory
first, which is a larger change than this one.

## Verification

- 751 passed, 6 skipped across the shape suite, `tests/test_installer_interactive_prompts.py` and
  `tests/security/`. All of `tests/sh` passing. The parse gate clean over all three `.ps1` files.
- Both new `setup.bat` assertions confirmed to bite: adding `-NoProfile` to the launch fails with the
  reason and names the test that would lose coverage, and reverting the policy to Bypass fails naming
  the offending line. The tree was restored after each.
- Relaxed-policy sites counted directly across all seven shipped scripts afterwards: one, in
  install.ps1, as recorded.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Step setup.bat down to Bypass for a script on a share, the way install.ps1 already does

Tightening setup.bat from Bypass to RemoteSigned had one case that is a genuine regression rather
than a theoretical one, and it needed handling rather than accepting.

Execution policy is judged on the script file's ZONE. A plain \\server\share and a mapped drive are
Intranet and load fine under RemoteSigned -- but a dotted-FQDN UNC (\\corp.example.com\...), a DFS
path or an IP-literal share is the Internet zone, where RemoteSigned refuses an unsigned script. And
Unblock-File cannot save that case: with no Zone.Identifier stream present the PATH decides, so
clearing a stream that was never there changes nothing and exits silently. Bypass worked; RemoteSigned
does not.

install.ps1:3405-3421 already solves exactly this when it writes the Start Menu shortcut -- UNC
prefix, then DriveInfo.DriveType -eq 'Network' -- and the new test's own comment calls that site "the
only one that is genuinely load-bearing" for the same reason. setup.bat got no such exemption. Now it
reuses the identical logic rather than inventing a second answer.

The probe does the Unblock-File too, so this costs one process rather than two, and it runs under
-Command, which execution policy does not govern at all.

Two details that matter more than they look:

- The batch variable DEFAULTS to RemoteSigned. A probe that fails to run therefore leaves the
  tightened policy in place rather than silently restoring the relaxed one.
- -NoProfile is on the probe and still deliberately absent from the launch.
  tests/studio/test_amd_venv_repair_loop.ps1 drives a profile that sets Set-StrictMode against
  setup.ps1, and adding it would retire that coverage with nothing failing.

Tests: the embedded probe is extracted from the batch file and PARSED, because it is one long line
inside a `for /f` backquote block and a syntax error there fails quietly -- the `for /f` captures
nothing, the RemoteSigned default stands, and the mark is never cleared, so an unzipped download gets
a refusal with no hint that the probe was what broke. The pre-existing setup.bat test located the
launch by literal filename, which is now an environment variable, so it matches on the flags instead.

5713 passed, 39 skipped across tests/studio/test_installer_av_shapes.py, tests/studio/install/ and
tests/security/. The single failure, test_pr10648_offline_and_status, is pre-existing on main.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Group the hidden/bypass pair by casefolded variable name

PowerShell variable names are not case-sensitive, so $shortcutArgs and $ShortcutArgs are one
variable. The same-variable layer keyed its map on the captured spelling, so writing the two
assignments with different capitalisation filed them as two unrelated names, each holding only
one of the two flags, and the pair went through. The file-wide ratchet did not catch it either,
since install.ps1 already records one permitted relaxed policy.

Verified by constructing that exact evasion: renaming the two install.ps1 assignments to
$launchArgs and $LaunchArgs passes under the old grouping and fails under this one, naming
both spellings.

* Stop the installers from explaining, in prose a classifier reads, which antivirus flagged them (#10990)

* Stop the installers from explaining, in prose a classifier reads, which antivirus flagged them

PowerShell hands the entire top-level script block to AMSI at compile time, before the first
statement runs, so every byte of install.ps1 is classifier input -- comments included. VirusTotal's
analysis of the file quoted one of our own comments back as grounds for suspicion:

  "The presence of comments that suggest the script is designed to evade detection by security
  tools (e.g. "AMSI scans this file in full before a line of it runs") further adds to the
  suspicion."

Six hardening passes wrote careful explanations of which product flagged which shape directly into
the files being scanned. The explanations are worth keeping. Their location is not.

- A comment in a shipped script says **what the code does and what breaks if you change it**.
- `AV_SHAPES_RECORD`, in `tests/studio/test_installer_av_shapes.py`, says **which scanner flagged
  which shape, and when**.

The record lives in that test rather than a doc because the file already owns the guards that enforce
the split, it ships to nobody, it is not packaged, and nothing scans it. Each relocated comment keeps
its operational content verbatim and gains a pointer. The diff over the five shipped scripts contains
no non-comment line, which is checked mechanically rather than asserted.

The record is not a dumping ground. It holds the measured detections (Skyhigh
`BehavesLike.PS.Suspicious.gr` on install.ps1, Bitdefender `Gen:Variant.MSILHeracles.272113` on the
csc.exe output in #10540, Kaspersky `HEUR:Trojan.VBS.Agent.gen` on the .vbs launcher shape, the two
fixture archives that made Panda flag the repo zip), the measured before-and-after from
`virustotal_delta.py` including the part that did NOT move, why each decision is a robustness fix and
not an evasion, the five shapes we are **keeping** on purpose with the reason each is load-bearing,
and how to report a new detection.

Three things a future pass will otherwise rediscover are written down there, because each one already
cost a wrong proposal: execution policy is evaluated against the script file's zone and not against
who launched PowerShell, so a `.cmd` shim cannot launder a remote-zone script; UNC paths are a remote
zone, which is the whole reason install.sh resolves the Windows `%TEMP%`; and the Windows client
default is `Restricted`, so documentation telling a user to set a process-scoped policy is
load-bearing and only the word `Bypass` needed to go.

A banned-token test alone is satisfiable by deleting the knowledge rather than moving it, so there
are three:

- `test_no_shipped_script_names_a_detection` over every shipped script including `studio/setup.bat`
  and `scripts/uninstall.sh`, which no shape test read before.
- `test_the_record_survives_and_keeps_its_evidence`, which requires the sections AND the specific
  detection strings -- a record with headings and no evidence is the same loss with extra steps.
- `test_every_script_that_dropped_its_explanation_points_at_the_record`, because a comment reduced to
  "security software blocks this" with no forward reference is worse than the prose it replaced: the
  next maintainer cannot tell whether it is still true.

Deliberately not banned: `antivirus`, `quarantine`, `scanner`, `blocked`. Those describe a real
runtime hazard the code handles and one of them reaches the user.

Also not banned, for a more interesting reason: **`false positive`**. It was on the list, and the
test immediately found it in install.ps1 and studio/setup.ps1 -- where it means a *statistical* false
positive in a registry probe and has nothing to do with a scanner. A token list is only as good as
its words having one meaning, and that one does not.

- 14 of the new assertions fail against `main` and none against this branch, so they are proved to
  bite rather than to pass vacuously.
- No non-comment line changed in any of the five scripts (`git diff -U0` filtered for lines that are
  not comments returns empty).
- `bash -n` clean on both shell scripts; `Parser::ParseFile` clean on all three `.ps1` files.
- Existing tests and CI that reference the old detection strings are unaffected: they live in
  `tests/` and `.github/`, which ship to nobody and are scanned by nothing.
- One self-inflicted bug caught while writing this: a blanket rename of the old doc path rewrote the
  "must not still point at the doc" assertion into asserting the opposite. The stale path is now
  assembled from fragments so a future rename cannot do it again.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Match banned vendor tokens on word boundaries, and drop the one that cannot work

The guard searched for each token as a raw substring, so it rejected ordinary installer prose:
'panda' is inside 'pandas', a real dependency name, and 'rising' is inside 'surprising',
'arising' and 'comprising'. The failure message then accuses a normal sentence of naming an
antivirus vendor, and the fix the next reader reaches for is to delete the guard.

Boundaries are conditional on the token's own edges, because 'heur:' and 'gen:variant' sit on a
colon where \b asserts the opposite of what is wanted.

'rising' is removed rather than bounded. It is a real engine and one of the two that flagged the
fixture archives, but the word is also ordinary English -- 'rising memory use' is a sentence
someone will write -- and no amount of boundary matching separates the two. A guard that fails on
valid prose is worth less than nothing. 'tencent', the other engine that flagged those archives,
has no such problem and stays.

Verified both directions against studio/setup.sh: a comment naming Bitdefender, Gen:Variant and
Panda still produces three failures, while 'rising memory use' plus 'installs pandas' now passes
and produced two misleading failures before.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Carry the AppDomain fallback into the WSL emit, and quote TEMP inside cmd

The generated script had only the static AssemblyBuilder spelling under a
bare catch, so on any host lacking that overload both SHChangeNotify
refreshes would stop with nothing printed. install.ps1 already tries both
for this reason; mirror it.

cmd expands a variable before it parses metacharacters, so an unquoted
echo %TEMP% on a profile holding an ampersand, which is legal in a
Windows account name, splits into two commands and the captured line is
not the temp path. Quote it inside cmd and strip the quotes back off. The
test stub now reproduces cmd's expand-then-parse order so the ordinary
path still passes and only the ampersand case moves.

* Keep the backend prewarm files as they are on main

An all-files formatter pass reflowed two studio/backend files that have
nothing to do with the WSL installer change and pulled them into this
PR's diff. Restore them so the blast radius is only the installer.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Strip cmd's quotes before trimming trailing blanks

Trimming first found nothing to trim, because the closing quote was still
the last character, so a Windows TEMP ending in spaces came back
untrimmed and the directory check then cleared it. Win32 strips those
spaces from a path and [ -d ] does not.

The test stub was also wrong in a way that hid this: it consumed the
quotes itself, but cmd's echo prints its argument verbatim, quotes
included. With the stub corrected the new case fails against the previous
commit and the rest still pass.

* Fall through to a local Windows temp when TEMP is on a share

A script written under a redirected %TEMP% is a remote script, and
RemoteSigned refuses an unsigned one, so roaming-profile users would
silently stop getting the shortcut they used to get. Rather than relax
the policy back to Bypass, try %LOCALAPPDATA%\Temp and then
%SystemRoot%\Temp, skipping any candidate that is UNC or still
unexpanded. install.ps1 solves the same problem for the launcher by
relaxing the policy because the launcher cannot move; this script can.

* Reject mapped network drives as temporary locations too

Z:\Temp is the same share and the same remote zone as its UNC spelling,
and install.ps1 treats DriveType.Network as remote for that reason, but
the filter only rejected paths beginning with two backslashes. A mapped
drive was therefore accepted and then refused by RemoteSigned at launch.
Read the mapped letters from net use and skip candidates on them; if that
cannot be read the set is empty and only the UNC check applies, which is
the previous behaviour rather than a new failure.

* Keep shortcuts working when no Windows drive is mounted

With [automount] enabled=false, interop still works but no Windows
directory is reachable as a Linux path, so no candidate can be allocated
and the file-based launch cannot run at all. Those users got a shortcut
before the move off /tmp, so losing it silently is a regression rather
than a pre-existing gap.

The generated script is now captured once and either written to the
Windows temp and run with -File, or handed to powershell on stdin. The
stdin path needs no policy relaxation, because execution policy applies
to -File and not to -Command, and nothing has to be mounted. It is fed
from its own pipe so it cannot drink the installer's stdin under
curl | sh.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Validate both halves of the compiler watch in the WSL control

The control checked only the process half, so a FileSystemWatcher that
never attached, or stopped reporting creations, looked exactly like a run
that dropped no library. TempLibraries is the half the Bitdefender report
in #10540 keyed on, and the install below trusts it. Require both, as
windows-no-compiler-ci.yml already does.

* Check the shell suite's failure counter after the last assertion

The only $FAIL check sat before the static half of the file. `bad` records a
failure and returns success, so an assertion that ran after it printed FAIL and
left the script exiting 0, which made the launch-path regression checks
ineffective in CI. Moved the summary and the check to the end of the file.

* Do not render install.sh with a Windows bash

The new here-string renderer drives install.sh through bash, and on a Windows
runner bash is Git Bash or the WSL stub in System32, neither of which install.sh
is ever run by: its WSL arm is gated on /proc/version naming microsoft, so the
shell reading this here-string is always a POSIX one inside the distro. The
rendered text is a pure function of install.sh's bytes, so the Linux and macOS
legs cover the subject and the Windows leg only contributed three failures.
Skipped there, the way the repository already skips its other bash-driven
installer tests.

Also report the shell's own diagnostic rather than letting CalledProcessError
replace it with a 6 KB repr of the script.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…already worked (unslothai#10996)

* Give this work a before-and-after number, and find out the hardening already worked

Six hardening passes shipped with no measurement (unslothai#7822, unslothai#8586, unslothai#6326, unslothai#10540, unslothai#10560, unslothai#10504). There
was no baseline to measure against. There is one now: install.ps1 at commit 1ad4467 is the revision
reported in unslothai#10805, it hashes to ec29980b..., and VirusTotal holds its verdict.

## The result, run live against the real key

    | | baseline (1ad4467) | main (2c70592a) |
    | engines flagging | 1 / 60                | 1 / 61          |
    | which            | Skyhigh BehavesLike.PS.Suspicious.gr | the same |
    | Sigma            | 17 (high 1, medium 11, low 5) | 14 (medium 10, low 4) |
    | YARA             | 2                     | 0               |

The **high**-severity Sigma rule is gone. So are both crowdsourced YARA hits,
`INDICATOR_SUSPICIOUS_PWSH_B64Encoded_Concatenated_FileEXEC` and `Windows_API_Function`. Three fewer
Sigma rules overall. The Skyhigh verdict has not moved, and that is reported as unchanged rather than
dressed up: a cloud behavioural verdict is not recomputed because we deleted some code.

So the static indicators, which are what drives the alarming scores third-party analysis sites report,
already improved measurably. That was not knowable before.

Two corrections to what I wrote in the plan, both from running this rather than reasoning about it:

- I recorded current main's install.ps1 as **not on VirusTotal**. It is. It has been scanned since,
  so the delta above is real and not a projection.
- I treated the prior passes as unverifiable. They are verifiable, retroactively, and they worked on
  the axis they could affect.

## Three axes, separately

Reporting only the engine count makes every shape win look like it achieved nothing. Reporting only
Sigma overclaims. Both, or the number is not worth having.

Engines are compared **by name**, not by count. A count-only comparison calls the single most
consequential possible change -- Skyhigh's detection being replaced by Microsoft's, one engine before
and one after -- "no difference". Defender is on every Windows machine; Skyhigh is enterprise-deployed.
There is a test for exactly that case.

Sigma is compared **per severity**, not in total. Trading one high for three lows is an improvement a
total calls a regression, and the reverse is a regression a total calls an improvement.

## GET only, and VOID is not clean

There is no upload path, and that is a deliberate omission rather than an oversight. A freshly
uploaded file is a prevalence-zero, first-seen sample, which is exactly what `CloudBlockLevel
HighPlus` and ASR rule `01443614` punish -- so uploading a candidate can *create* the detection it was
meant to measure, under a hash no user will ever have. Released artefacts are uploaded by
`virustotal_scan.py` at release time; branches are not. A test parses the module and asserts no
non-GET method appears, having first been written as a grep and caught matching the module's own
explanation of why there is no upload.

So an unknown hash is VOID, exit 3, never clean. Also VOID: a missing `VT_API_KEY`, and a file
VirusTotal knows but has never analysed -- that last one being the subtle case, because zero engine
verdicts is not sixty engines clearing the file. Exit codes are distinct: 3 could-not-measure, 2
worse, 0 not worse.

## The baseline is checked, not trusted

A baseline hash copied out of an issue is a number nobody can verify, and if it ever pointed at the
wrong file every delta reported against it would be wrong while the lane looked perfectly healthy. So
both a test and a workflow step recompute it from this repository's history -- `git show
1ad4467:install.ps1` -- and assert the 427,113 bytes the sample is recorded as. A shallow clone
skips rather than fails.

## Verification

- 613 passed, 6 skipped across `tests/security/`, including 25 new tests.
- Run live against the real key; the table above is its actual output.
- Weighted toward the failure direction: a new high-severity rule, a new YARA hit, an engine swap at
  an unchanged count, and a medium promoted to high must each be reported as worse. One test replaces
  the comparison with one that reports nothing and requires the self-test to notice, because a
  control that cannot fail is decoration.
- Both parsers are fuzzed against schema drift. VirusTotal has renamed and added buckets over time,
  and a crash would break the measurement on precisely the day the schema moved.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Read the VirusTotal secret this repository actually has, so the lane can measure something

`secrets.VT_API_KEY` does not exist. `VT_API_KEY` is the ENV VAR name the Python reads
(`scripts/virustotal_scan.py:37`); the repository secret is `VIRUS_TOTAL_API_TOKEN`, which is the only
VirusTotal secret in all 51 workflows, and `release-desktop.yml:2193` maps it the same way.

As written the expression expanded to empty and the lane exited 3 / VOID on every dispatch. That is
the right failure shape -- it refuses to report a clean it did not measure -- but a lane that can
never measure anything is not worth having, and the failure only surfaces after someone dispatches
it and waits.

Two guards added, because both halves of this were invisible:

- `test_the_workflow_reads_the_secret_this_repository_actually_has` pins the secret name in both
  directions and also asserts the checkout keeps `fetch-depth: 0`, since the step that reverifies
  the baseline against commit 1ad4467 reverifies nothing on a shallow clone.
- `test_the_baseline_hash_is_the_file_the_reporter_ran` now checks the constant's shape
  unconditionally before the git half. That git half skips on a shallow clone, which is every CI lane
  that collects `tests/security` -- so the one assertion tying the baseline to real history was green
  locally and silently absent everywhere it mattered.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Compare Sigma severities in order, and void an unanalysed baseline too

The per-severity comparison reported each bucket independently, which cannot express a trade:
swapping the single high rule for three extra low ones moves two buckets in opposite
directions, so it landed in worse and in better at once and exit_code answered worse. The
comment beside that loop calls exactly that swap an improvement. SEVERITIES is ordered most
severe first, so the most severe bucket that moved now decides and the rest are reported
alongside it without flipping the verdict.

The zero-engine guard was on the candidate only. A baseline hash VirusTotal knows but has never
analysed carries no engines, no Sigma and no YARA, so every finding on the candidate read as
newly introduced and the run exited 2 having compared against nothing.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Bound the lookups, keep ruleset identity, and escape third-party text

Neither lookup carried a deadline, and request can spend four 300-second socket attempts plus 20,
40 and 80 seconds of backoff. The workflow gives the whole job 20 minutes, so the baseline lookup
alone could exhaust it and the runner would kill the step before it fetched the candidate or wrote
its summary, which is a lost run rather than a reported one. Both lookups now share a 420 second
budget and an expired budget is reported as VOID, since we did not find out.

YARA hits were keyed on the rule name alone, so the same rule identifier appearing in two
crowdsourced rulesets collapsed to one entry: a candidate could gain a hit from a second ruleset,
parse to the same list as the baseline, and exit 0 on a real regression. Keyed on ruleset and rule
now.

Engine names and detection labels are third-party text and the report is appended to
GITHUB_STEP_SUMMARY, where a newline ends the row, a pipe opens a cell and an angle bracket starts
HTML that GitHub renders. virustotal_scan._md_text exists for exactly this and the report was
bypassing it; reused rather than duplicated.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Stop labelling an overridden baseline as the recorded install.ps1

A dispatch can supply baseline_sha256, and the lookup and the comparison then use that hash while
the header still announced the recorded identity and printed install.ps1's historical scores
beside the override's live table. That is an artifact built to be misattributed: the numbers
belong to one file and the name to another.

The note is now printed only when the baseline hash really is the recorded one, and an override
says so and disclaims the historical comparison.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Catch a spent deadline in the VirusTotal delta lookup

VirusTotalClient.request signals an expired deadline with TimeoutError,
which inherits from OSError rather than RuntimeError, so the handler in
fetch never ran and the workflow died with a traceback before render
wrote its summary. That is the lost run the deadline was meant to
prevent. Catch both and keep returning a VOID row.

* Keep Sigma buckets this tool cannot rank

The parser warned in its own docstring that VirusTotal renames and adds
severity buckets, then read a fixed key list, so a candidate that gained
rules only in a new bucket produced a dictionary identical to the
baseline's and the run exited 0 on a regression. Keep every reported
bucket. Unrankable ones stay out of the ordered trade-off, which depends
on knowing which of two buckets is more severe, and a rise in one is
reported as worse rather than assumed minor.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Count every engine verdict bucket, not the five the dataclass carries

parse_stats names type-unsupported and failure as categories VirusTotal
has added, but ScanStats has fields only for five buckets, so the engine
count this report prints was short by however many engines answered that
way, and a response made up entirely of those buckets summed to zero and
voided the run as unanalysed. Sum every numeric bucket from the raw
stats, which leaves the shared dataclass alone for the release scanner.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Require an explicit verdict before calling an engine cleared

An engine that flagged the baseline and is absent from the candidate's
results has not cleared it, it did not evaluate it, and a set difference
cannot tell those apart. Since Skyhigh is the one engine that actually
flags this file, a sparse candidate analysis could print the single most
consequential sentence in the report and exit 0. Track which engines
returned a verdict of any kind, call only an answering non-flagging
engine cleared, and report the silent ones as an unanswered question.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Only a conclusive verdict clears a prior detection

The responder set was built on the truthiness of the category, so
timeout, confirmed-timeout, failure and type-unsupported counted as
answers while parse_detections correctly left them out of the flagging
list. An engine returning one of those appeared in neither set and was
reported as having stopped flagging the candidate, which is the same
mistake as treating absence as a clean verdict.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…hine (unslothai#10978)

* WSL installer: stop running the C# compiler on the user's Windows machine

`install.sh` generates a PowerShell script and runs it on the Windows side to create the WSL
shortcut. Two constructs in that path were removed from `install.ps1` in earlier passes and left
live here, where nothing looked:

- `install.sh:2249` declared `SHChangeNotify` with `Add-Type -MemberDefinition`. On Windows
  PowerShell 5.1 that writes C# to `%TEMP%` and runs `csc.exe`, producing a DLL on the user's
  machine. unslothai#10540 traced exactly that chain to Bitdefender `Gen:Variant.MSILHeracles.272113`:
  `unsloth-stud... -> powershell.exe -> csc.exe -> %TEMP%\<random>.dll`. It replaced the
  declaration in `install.ps1` with reflection emit and missed this copy.
- `install.sh:2273` launched the generated script with `-ExecutionPolicy Bypass`, the flag unslothai#7822
  removed everywhere else.

Neither was caught because `test_the_installer_never_runs_the_c_sharp_compiler` parametrised over
`("install.ps1", "studio/setup.ps1")` only, and `windows-no-compiler-ci.yml` did not list
`install.sh` in its path triggers. A shell script that emits PowerShell can put a compiler on a
Windows machine without touching a `.ps1`.

## The compile

`SHChangeNotify` is now emitted, mirroring `install.ps1:3485-3499`: a `DefineDynamicAssembly` /
`DefineDynamicModule` / `DefineType` / `DefinePInvokeMethod` / `CreateType` block inlined, since the
generated script is standalone and cannot call `New-StudioEmittedNativeType`. The enclosing
`try {} catch {}` stays, so a failure still costs only a stale icon, and both notifications stay:
per-item `SHCNE_UPDATEITEM` + `SHCNF_PATHW` per `.lnk`, then the global `SHCNE_ASSOCCHANGED`. The
per-item call is not redundant, and the `ALLOWED_PINVOKES` entry records why: `ie4uinit.exe -show`
does not recover a stale same-name `.lnk`.

I ran the emitted type rather than assuming it: under pwsh it produces
`void SHChangeNotify(Int32, UInt32, String, IntPtr)`, identical to the `Add-Type` declaration,
`PreserveSig` set, and `Assembly.Location` empty, which is the point. Nothing reaches disk.

## The execution policy

`Bypass` was load-bearing, for one reason: `wslpath -w /tmp/unsloth-shortcut-XXXXXX.ps1` yields a
`\\wsl.localhost\<distro>\...` UNC path, PowerShell treats a script there as remote, and
`RemoteSigned` refuses an unsigned remote script. So rather than relax the policy, the script now
goes to the Windows `%TEMP%` (`cmd.exe /c echo %TEMP%`, CR stripped, `wslpath -u`), which is a local
volume and therefore `MyComputer` zone, where `RemoteSigned` loads it unsigned. Same generated
script, same launch, same result.

When `%TEMP%` cannot be resolved there is deliberately **no fallback to WSL's `/tmp`**, because that
is the case that needed the relaxed policy in the first place. Nothing is allocated and the caller
takes the notice it already prints when interop is unavailable. That population is very nearly the
population where interop is already broken.

## Tripwires, with messages that say what is wrong

`tests/sh/test_wsl_shortcut_script_location.sh` evals the real resolution block out of `install.sh`
with `cmd.exe` and `wslpath` stubbed, covering resolved, no-interop, unexpanded `%TEMP%`, and a
`%TEMP%` that is not a directory, then asserts statically that the launch uses `RemoteSigned`, that
the file relaxes the policy nowhere, that it compiles no C#, and that both refreshes survive. A
failed extraction is reported as a failure rather than exiting early, so the output names every
problem at once, and it still fails closed.

`clean-machine-install-ci.yml`'s `wsl` job is the only lane that runs this branch, so it gains the
behavioural half: read the created `.lnk` back and refuse a script-host target, require the
generated script to have been cleaned up, and fail on any `.cmdline`/`.rsp` under the Windows
`%TEMP%`, which is csc.exe output and nothing else. That check plants two intermediates and requires
the search to find both before trusting a negative result, because a detector that sees nothing looks
exactly like a clean run and every reason it might see nothing is silent. If the control does not
fire the job fails as a broken detector instead of reporting a pass. Shortcut absence is a warning,
not an error, since the installer itself treats shortcut creation as best-effort.

`install.sh` is added to the compiler test's parametrise list and to
`windows-no-compiler-ci.yml`'s paths. The `DefinePInvokeMethod` assertion in that test becomes
conditional on the file declaring a native import at all, so it does not fail for being satisfied on
`scripts/uninstall.ps1` or `studio/setup.sh`.

## Verification

- The new shell suite: 16 passed on this branch, and against `main` in a worktree it exits 1 with 6
  named failures. Proved to bite rather than assumed to.
- The generated WSL script rendered and parsed with
  `[System.Management.Automation.Language.Parser]::ParseFile`: clean over 765 tokens. No existing
  gate parses that here-string, and this change edits it.
- `bash -n` and `sh -n` on `install.sh`; all of `tests/sh` passing; the parse gate clean over
  `install.ps1`, `studio/setup.ps1` and `scripts/uninstall.ps1`.
- `tests/studio/test_installer_av_shapes.py`, `tests/studio/install/`, `tests/security/`: green.
- The new CI PowerShell parsed standalone, and its positive control plus detector exercised for real
  against a planted `csc.exe`-style intermediate: control 2 of 2, simulated compile caught, clean
  directory reports zero.

I have no Windows or WSL here, so the runtime behaviour of the shortcut path rests on the
`clean-machine-install-ci.yml` WSL job, not on a local run. This is a shape fix with a confirmed
detection behind the shape; it is not a claim that any particular user report is resolved.

* Fix a test of mine that passed for the wrong reason, and could only fail on a real CI machine

`test_wsl_shortcut_script_location.sh` asserted that the generated shortcut script's path does not
start with `/tmp`, as a proxy for "not in WSL's own temp, which wslpath turns into a \\wsl.localhost
UNC path that RemoteSigned refuses". The proxy is broken: the harness builds its *fake Windows temp*
with `mktemp -d`, so on any machine with `TMPDIR=/tmp` -- which is every normal CI runner -- the
stub's own directory matched the pattern and the test failed while install.sh was behaving exactly as
intended.

It passed locally only because this workspace sets `TMPDIR` elsewhere. That is precisely the class of
accidental pass the rest of this work has been built to catch, so it is worth naming rather than
quietly correcting.

The replacement asserts the property the proxy was standing in for, structurally: the block contains
exactly one `mktemp`, so there is no second path to fall back to, and that `mktemp` allocates inside
`$_css_win_temp`. Both are true or false regardless of where anyone's temp directory happens to live.

Verified under the exact condition that broke it: `TMPDIR=/tmp` gives 17 passed, 0 failed on this
branch, and 6 failed on `main` in a clean worktree -- so the test still bites.

* WSL installer: read %TEMP% with cmd /d, so an AutoRun command cannot cost the user their shortcut

Reading the Windows %TEMP% through interop is new in this branch, and it reads it with
`cmd.exe /c echo %TEMP%`. Without /d, cmd first runs the AutoRun command from
HKLM or HKCU \Software\Microsoft\Command Processor, and `cmd /c` is not exempt from
that. AutoRun writes to the same stdout, so its output arrives ahead of the path and
`tr -d '\r\n'` glues the two into one string. wslpath then rejects it, the directory
check fails, and the branch takes its "couldn't create the Windows shortcut" notice.

Clink sets an AutoRun, so Cmder does, and so do plenty of corporate images. Every one
of those users got a working shortcut before this branch and would silently stop
getting one, while being told WSL interop is disabled, which is not what happened.

So: /d, which is the cheap fix rather than out-parsing whatever prints. Then the last
line rather than the whole stream, for anything that still reaches stdout by another
route, and trailing blanks trimmed, because Win32 strips them from a path and [ -d ]
does not, so a %TEMP% set with one resolved to a directory that appeared not to exist.
The || stays: this file runs under set -e, where a failed substitution ends the install.

Tests
-----
tests/sh/test_wsl_shortcut_script_location.sh grows the AutoRun and trailing-blank
cases and a static check for /d, and its wslpath stub is now input-sensitive. It was
not, and that mattered: a stub that returns the fake Windows temp whatever it is handed
cannot tell "install.sh read the path" from "install.sh read a banner glued to a path",
so both new cases passed against the unfixed file until the stub compared its argument.
Against the unfixed install.sh the four new assertions fail; with it they pass.

tests/studio/test_wsl_shortcut_script_is_valid_powershell.py is new and covers a gap
nothing else did: that what install.sh generates is PowerShell at all. bash -n sees the
here-string as a here-string, the contents only run on Windows with both streams sent to
/dev/null, and the icon-refresh block runs inside try/catch, so a parse error there is
not a crash and not a message, just no shortcut and a misleading notice. The block was
just rewritten into a twenty-line reflection-emit sequence, which is when that matters
most. The file renders the here-string with a real shell rather than keeping a copy,
parses it, and then executes the emit sequence retargeted at a symbol this host exports,
so a wrong call order or argument count fails on Linux. Five mutations of the shipped
file were tried; four fail it, and the docstring names the fifth that does not and why.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Watch the WSL install live, instead of searching for what CodeDom already deleted

The lane looked for .cmdline and .rsp files in the Windows temp after the install had finished.
CodeDom removes its whole intermediate directory once the assembly is loaded, which
Watch-ForCompiler.ps1 records as a before-and-after diff seeing nothing at all while 4688 recorded
csc.exe, so that search could not fail for the case this lane exists to catch. Its positive
control planted persistent files, which proves the search can traverse a directory and nothing
about whether ephemeral compiler output is observable.

The install now runs inside Invoke-WithCompilerWatch, the same detector windows-no-compiler-ci.yml
uses, which unions 4688 with a live FileSystemWatcher and treats an unreadable Security log as
void rather than clean. The dropped-library half is checked too, since that is what the
Bitdefender report in unslothai#10540 keyed on. The post-hoc listing stays for what genuinely is left
behind, which is the other half of the union, and its message now says that is what it means.

Watch-ForCompiler.ps1 is in both path filters now, because this job's detection depends on it, and
the new guard is registered in the unfiltered lint job since it reads a workflow file.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Arm the 4688 half of the compiler watch in the WSL lane

Watch-ForCompiler.ps1 requires the caller to enable process creation
auditing, and this job never did, so its Security log query returned an
empty compiler list whatever ran while the step still printed that no
compiler process was seen. Enable and verify the audit policy before the
install, and require a deliberate compile to be detected first, so a
clean verdict is distinguishable from a detector that never attached.

* Close the AV shape-guard holes, and load the installers under RemoteSigned (unslothai#10982)

* AV shape guards: watch the two shipped scripts nothing watched, and ratchet the policy sites

Stacked on the WSL compiler fix, which shares this file.

Two problems, both found while investigating unslothai#10805, and both about the guard rather than the code
it guards.

## Two shipped scripts were in no list

`PS_SCRIPTS` and `SH_SCRIPTS` between them missed `studio/setup.bat` and `scripts/uninstall.sh`. A
shipped `.bat` is scanned like any other file, and `setup.bat` launches PowerShell, so every rule
here applies to it. That is how its `-ExecutionPolicy Bypass` survived the passes in unslothai#7822 and
unslothai#8586: the guards were reading a set of files that did not include it. Both are added to
`ALL_SCRIPTS`.

## The hidden-window pair check only ever looked at one line

`test_a_hidden_window_never_pairs_with_a_bypassed_policy` iterated `splitlines()` and compared the
two flags within a single physical line. `install.ps1` assigns `$shortcutArgs` a hidden window at
:3419 and overwrites it with a relaxed policy at :3433, fourteen lines apart in the same function,
and that passed for as long as it existed. A scanner reads the file, not the line.

Three layers now:

1. Same line, unchanged, because it gives the clearest message when it is the real shape.
2. A ratchet on how many relaxed policies the file contains at all, against `KNOWN_BYPASS_SITES`,
   which records each remaining site with the reason and what would remove it. It fails **both**
   ways: too many is a new site, too few is a stale entry that has quietly stopped guarding
   anything. This is the layer that catches a policy arriving somewhere the other two do not model.
3. Same variable, any distance: the union of everything assigned to one name must not contain both
   flags. This is the layer that sees the 3419/3433 shape.

`install.ps1`'s `$shortcutArgs` is recorded in `KNOWN_SPLIT_PAIR_VARIABLES` rather than failed on.
Removing it needs `launch-studio.ps1` written to a guaranteed-local directory first, because
`%LOCALAPPDATA%` can be folder-redirected to a UNC path where RemoteSigned refuses an unsigned
script, and a shortcut that silently does nothing is worse than the token. Recording it lets the
guard land now and lock in "no new ones", which is the part that matters going forward.

## Verification

70 passed in the suite, and each new layer was confirmed to bite rather than assumed to:

- A new relaxed policy injected into `studio/setup.sh` fails layer 2, naming the file, line number,
  the offending line, and what to do about it.
- Removing the recorded site from `studio/setup.bat` without lowering its count fails layer 2 the
  other way, telling the reader to lower the count in the same commit.
- Layer 3 proved in isolation by renaming `$shortcutArgs` to `$launchArgs` in `install.ps1`: the
  relaxed-policy count is unchanged so layer 2 passes, and layer 3 fires on its own.

The tree was restored after each and re-verified clean. `tests/studio/install/` and the shape suite
are green; `test_pr10648_offline_and_status.py::test_the_pr_only_added_new_arms_to_the_setup_status_blocks`
fails identically on `main` in a separate worktree and is untouched by this change.

* Load the installer scripts under RemoteSigned instead of relaxing the policy

Removes three of the four relaxed execution policies the ratchet in the previous commit recorded.
RemoteSigned refuses an unsigned script only in the Internet or Untrusted zone, so for a local,
unmarked script it behaves identically to Bypass while dropping a token endpoint products score.

## studio/setup.bat

`powershell -ExecutionPolicy Bypass -File "%~dp0setup.ps1"` becomes RemoteSigned. setup.ps1 ships
beside the batch file inside an installed package, so it is MyComputer-zone and loads unsigned
either way.

One population could regress: a package unzipped from a download, where setup.ps1 carries a mark of
the web that RemoteSigned honours and Bypass ignored. So the mark is cleared first. Execution policy
governs script *files* and not `-Command`, so that call runs under any machine policy, and clearing
an absent stream writes nothing. The path travels in an environment variable rather than being
interpolated into the command string, because an apostrophe in an install path is a real Windows user
name and would otherwise break the quoting.

`-NoProfile` is on the unblock call and deliberately **not** on the launch. The launch has always run
setup.ps1 with profiles loaded, and `tests/studio/test_amd_venv_repair_loop.ps1` drives a profile
that sets `Set-StrictMode -Version Latest` against it. Adding the flag would have retired that
coverage with nothing failing, so the new test asserts its absence and says why.

## scripts/uninstall.ps1 and README.md

Both print `Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass` as the documented way to run
a cloned script. Changed to RemoteSigned rather than dropped: the Windows client default is
`Restricted`, which blocks every script file including a local unsigned one, so the
`Set-ExecutionPolicy` itself is load-bearing and removing it would break the documented path.
RemoteSigned is sufficient because a git clone carries no mark of the web, and both now say so and
point a zip user at `Unblock-File`, which is the case where the two policies genuinely differ.

The uninstaller line is never executed -- it lives in the printed `_Usage` here-string -- but AMSI
scans the file whole and a classifier cannot tell a string from a statement.

## Where that leaves the ratchet

Four recorded sites down to one. The survivor is `install.ps1:3433`, the roaming-profile fallback for
a launcher on a share, and it stays because `%LOCALAPPDATA%` can be folder-redirected to a UNC path
where RemoteSigned would refuse the launcher, and a desktop shortcut that silently does nothing is
worse than the token. Removing it needs `launch-studio.ps1` written to a guaranteed-local directory
first, which is a larger change than this one.

## Verification

- 751 passed, 6 skipped across the shape suite, `tests/test_installer_interactive_prompts.py` and
  `tests/security/`. All of `tests/sh` passing. The parse gate clean over all three `.ps1` files.
- Both new `setup.bat` assertions confirmed to bite: adding `-NoProfile` to the launch fails with the
  reason and names the test that would lose coverage, and reverting the policy to Bypass fails naming
  the offending line. The tree was restored after each.
- Relaxed-policy sites counted directly across all seven shipped scripts afterwards: one, in
  install.ps1, as recorded.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Step setup.bat down to Bypass for a script on a share, the way install.ps1 already does

Tightening setup.bat from Bypass to RemoteSigned had one case that is a genuine regression rather
than a theoretical one, and it needed handling rather than accepting.

Execution policy is judged on the script file's ZONE. A plain \\server\share and a mapped drive are
Intranet and load fine under RemoteSigned -- but a dotted-FQDN UNC (\\corp.example.com\...), a DFS
path or an IP-literal share is the Internet zone, where RemoteSigned refuses an unsigned script. And
Unblock-File cannot save that case: with no Zone.Identifier stream present the PATH decides, so
clearing a stream that was never there changes nothing and exits silently. Bypass worked; RemoteSigned
does not.

install.ps1:3405-3421 already solves exactly this when it writes the Start Menu shortcut -- UNC
prefix, then DriveInfo.DriveType -eq 'Network' -- and the new test's own comment calls that site "the
only one that is genuinely load-bearing" for the same reason. setup.bat got no such exemption. Now it
reuses the identical logic rather than inventing a second answer.

The probe does the Unblock-File too, so this costs one process rather than two, and it runs under
-Command, which execution policy does not govern at all.

Two details that matter more than they look:

- The batch variable DEFAULTS to RemoteSigned. A probe that fails to run therefore leaves the
  tightened policy in place rather than silently restoring the relaxed one.
- -NoProfile is on the probe and still deliberately absent from the launch.
  tests/studio/test_amd_venv_repair_loop.ps1 drives a profile that sets Set-StrictMode against
  setup.ps1, and adding it would retire that coverage with nothing failing.

Tests: the embedded probe is extracted from the batch file and PARSED, because it is one long line
inside a `for /f` backquote block and a syntax error there fails quietly -- the `for /f` captures
nothing, the RemoteSigned default stands, and the mark is never cleared, so an unzipped download gets
a refusal with no hint that the probe was what broke. The pre-existing setup.bat test located the
launch by literal filename, which is now an environment variable, so it matches on the flags instead.

5713 passed, 39 skipped across tests/studio/test_installer_av_shapes.py, tests/studio/install/ and
tests/security/. The single failure, test_pr10648_offline_and_status, is pre-existing on main.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Group the hidden/bypass pair by casefolded variable name

PowerShell variable names are not case-sensitive, so $shortcutArgs and $ShortcutArgs are one
variable. The same-variable layer keyed its map on the captured spelling, so writing the two
assignments with different capitalisation filed them as two unrelated names, each holding only
one of the two flags, and the pair went through. The file-wide ratchet did not catch it either,
since install.ps1 already records one permitted relaxed policy.

Verified by constructing that exact evasion: renaming the two install.ps1 assignments to
$launchArgs and $LaunchArgs passes under the old grouping and fails under this one, naming
both spellings.

* Stop the installers from explaining, in prose a classifier reads, which antivirus flagged them (unslothai#10990)

* Stop the installers from explaining, in prose a classifier reads, which antivirus flagged them

PowerShell hands the entire top-level script block to AMSI at compile time, before the first
statement runs, so every byte of install.ps1 is classifier input -- comments included. VirusTotal's
analysis of the file quoted one of our own comments back as grounds for suspicion:

  "The presence of comments that suggest the script is designed to evade detection by security
  tools (e.g. "AMSI scans this file in full before a line of it runs") further adds to the
  suspicion."

Six hardening passes wrote careful explanations of which product flagged which shape directly into
the files being scanned. The explanations are worth keeping. Their location is not.

- A comment in a shipped script says **what the code does and what breaks if you change it**.
- `AV_SHAPES_RECORD`, in `tests/studio/test_installer_av_shapes.py`, says **which scanner flagged
  which shape, and when**.

The record lives in that test rather than a doc because the file already owns the guards that enforce
the split, it ships to nobody, it is not packaged, and nothing scans it. Each relocated comment keeps
its operational content verbatim and gains a pointer. The diff over the five shipped scripts contains
no non-comment line, which is checked mechanically rather than asserted.

The record is not a dumping ground. It holds the measured detections (Skyhigh
`BehavesLike.PS.Suspicious.gr` on install.ps1, Bitdefender `Gen:Variant.MSILHeracles.272113` on the
csc.exe output in unslothai#10540, Kaspersky `HEUR:Trojan.VBS.Agent.gen` on the .vbs launcher shape, the two
fixture archives that made Panda flag the repo zip), the measured before-and-after from
`virustotal_delta.py` including the part that did NOT move, why each decision is a robustness fix and
not an evasion, the five shapes we are **keeping** on purpose with the reason each is load-bearing,
and how to report a new detection.

Three things a future pass will otherwise rediscover are written down there, because each one already
cost a wrong proposal: execution policy is evaluated against the script file's zone and not against
who launched PowerShell, so a `.cmd` shim cannot launder a remote-zone script; UNC paths are a remote
zone, which is the whole reason install.sh resolves the Windows `%TEMP%`; and the Windows client
default is `Restricted`, so documentation telling a user to set a process-scoped policy is
load-bearing and only the word `Bypass` needed to go.

A banned-token test alone is satisfiable by deleting the knowledge rather than moving it, so there
are three:

- `test_no_shipped_script_names_a_detection` over every shipped script including `studio/setup.bat`
  and `scripts/uninstall.sh`, which no shape test read before.
- `test_the_record_survives_and_keeps_its_evidence`, which requires the sections AND the specific
  detection strings -- a record with headings and no evidence is the same loss with extra steps.
- `test_every_script_that_dropped_its_explanation_points_at_the_record`, because a comment reduced to
  "security software blocks this" with no forward reference is worse than the prose it replaced: the
  next maintainer cannot tell whether it is still true.

Deliberately not banned: `antivirus`, `quarantine`, `scanner`, `blocked`. Those describe a real
runtime hazard the code handles and one of them reaches the user.

Also not banned, for a more interesting reason: **`false positive`**. It was on the list, and the
test immediately found it in install.ps1 and studio/setup.ps1 -- where it means a *statistical* false
positive in a registry probe and has nothing to do with a scanner. A token list is only as good as
its words having one meaning, and that one does not.

- 14 of the new assertions fail against `main` and none against this branch, so they are proved to
  bite rather than to pass vacuously.
- No non-comment line changed in any of the five scripts (`git diff -U0` filtered for lines that are
  not comments returns empty).
- `bash -n` clean on both shell scripts; `Parser::ParseFile` clean on all three `.ps1` files.
- Existing tests and CI that reference the old detection strings are unaffected: they live in
  `tests/` and `.github/`, which ship to nobody and are scanned by nothing.
- One self-inflicted bug caught while writing this: a blanket rename of the old doc path rewrote the
  "must not still point at the doc" assertion into asserting the opposite. The stale path is now
  assembled from fragments so a future rename cannot do it again.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Match banned vendor tokens on word boundaries, and drop the one that cannot work

The guard searched for each token as a raw substring, so it rejected ordinary installer prose:
'panda' is inside 'pandas', a real dependency name, and 'rising' is inside 'surprising',
'arising' and 'comprising'. The failure message then accuses a normal sentence of naming an
antivirus vendor, and the fix the next reader reaches for is to delete the guard.

Boundaries are conditional on the token's own edges, because 'heur:' and 'gen:variant' sit on a
colon where \b asserts the opposite of what is wanted.

'rising' is removed rather than bounded. It is a real engine and one of the two that flagged the
fixture archives, but the word is also ordinary English -- 'rising memory use' is a sentence
someone will write -- and no amount of boundary matching separates the two. A guard that fails on
valid prose is worth less than nothing. 'tencent', the other engine that flagged those archives,
has no such problem and stays.

Verified both directions against studio/setup.sh: a comment naming Bitdefender, Gen:Variant and
Panda still produces three failures, while 'rising memory use' plus 'installs pandas' now passes
and produced two misleading failures before.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Carry the AppDomain fallback into the WSL emit, and quote TEMP inside cmd

The generated script had only the static AssemblyBuilder spelling under a
bare catch, so on any host lacking that overload both SHChangeNotify
refreshes would stop with nothing printed. install.ps1 already tries both
for this reason; mirror it.

cmd expands a variable before it parses metacharacters, so an unquoted
echo %TEMP% on a profile holding an ampersand, which is legal in a
Windows account name, splits into two commands and the captured line is
not the temp path. Quote it inside cmd and strip the quotes back off. The
test stub now reproduces cmd's expand-then-parse order so the ordinary
path still passes and only the ampersand case moves.

* Keep the backend prewarm files as they are on main

An all-files formatter pass reflowed two studio/backend files that have
nothing to do with the WSL installer change and pulled them into this
PR's diff. Restore them so the blast radius is only the installer.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Strip cmd's quotes before trimming trailing blanks

Trimming first found nothing to trim, because the closing quote was still
the last character, so a Windows TEMP ending in spaces came back
untrimmed and the directory check then cleared it. Win32 strips those
spaces from a path and [ -d ] does not.

The test stub was also wrong in a way that hid this: it consumed the
quotes itself, but cmd's echo prints its argument verbatim, quotes
included. With the stub corrected the new case fails against the previous
commit and the rest still pass.

* Fall through to a local Windows temp when TEMP is on a share

A script written under a redirected %TEMP% is a remote script, and
RemoteSigned refuses an unsigned one, so roaming-profile users would
silently stop getting the shortcut they used to get. Rather than relax
the policy back to Bypass, try %LOCALAPPDATA%\Temp and then
%SystemRoot%\Temp, skipping any candidate that is UNC or still
unexpanded. install.ps1 solves the same problem for the launcher by
relaxing the policy because the launcher cannot move; this script can.

* Reject mapped network drives as temporary locations too

Z:\Temp is the same share and the same remote zone as its UNC spelling,
and install.ps1 treats DriveType.Network as remote for that reason, but
the filter only rejected paths beginning with two backslashes. A mapped
drive was therefore accepted and then refused by RemoteSigned at launch.
Read the mapped letters from net use and skip candidates on them; if that
cannot be read the set is empty and only the UNC check applies, which is
the previous behaviour rather than a new failure.

* Keep shortcuts working when no Windows drive is mounted

With [automount] enabled=false, interop still works but no Windows
directory is reachable as a Linux path, so no candidate can be allocated
and the file-based launch cannot run at all. Those users got a shortcut
before the move off /tmp, so losing it silently is a regression rather
than a pre-existing gap.

The generated script is now captured once and either written to the
Windows temp and run with -File, or handed to powershell on stdin. The
stdin path needs no policy relaxation, because execution policy applies
to -File and not to -Command, and nothing has to be mounted. It is fed
from its own pipe so it cannot drink the installer's stdin under
curl | sh.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Validate both halves of the compiler watch in the WSL control

The control checked only the process half, so a FileSystemWatcher that
never attached, or stopped reporting creations, looked exactly like a run
that dropped no library. TempLibraries is the half the Bitdefender report
in unslothai#10540 keyed on, and the install below trusts it. Require both, as
windows-no-compiler-ci.yml already does.

* Check the shell suite's failure counter after the last assertion

The only $FAIL check sat before the static half of the file. `bad` records a
failure and returns success, so an assertion that ran after it printed FAIL and
left the script exiting 0, which made the launch-path regression checks
ineffective in CI. Moved the summary and the check to the end of the file.

* Do not render install.sh with a Windows bash

The new here-string renderer drives install.sh through bash, and on a Windows
runner bash is Git Bash or the WSL stub in System32, neither of which install.sh
is ever run by: its WSL arm is gated on /proc/version naming microsoft, so the
shell reading this here-string is always a POSIX one inside the distro. The
rendered text is a pure function of install.sh's bytes, so the Linux and macOS
legs cover the subject and the Windows leg only contributed three failures.
Skipped there, the way the repository already skips its other bash-driven
installer tests.

Also report the shell's own diagnostic rather than letting CalledProcessError
replace it with a 6 KB repr of the script.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Windows Setup ran into a problem Installation failed: + FullyQualifiedError

1 participant