Skip to content

[staging] control: current main alone — CI baseline - #38

Closed
Lyxot wants to merge 40 commits into
staging-control-base-11044from
staging-base-11044
Closed

Lyxot wants to merge 40 commits into
staging-control-base-11044from
staging-base-11044

Conversation

@Lyxot

@Lyxot Lyxot commented Sep 16, 2026

Copy link
Copy Markdown
Owner

Staging only — do not merge. Control run: unmodified upstream main (ce66f60) against an older snapshot, to establish which CI failures are pre-existing. Closed once the run reports.

oobabooga and others added 30 commits September 15, 2026 10:06
iOS Safari zooms the page when a focused field renders below 16px and never zooms back out, which pushed the header and send button off screen after every message. Floor every text-entry control at max(16px, 1rem * --ui-font-scale) under (hover: none) and (pointer: coarse), in @layer base so the important declaration beats the important utilities in the utilities layer.

Three compact controls were sized against 9px to 12px text and clip their value at the floor, so each gets a pointer-coarse companion: the GPU monitor select, and the two mono numeric fields in the training params. Mouse layouts are unchanged.

Co-authored-by: oobabooga <[email protected]>
…op discarding the false-positive submission packets (unslothai#10986)

* Capture the evidence six reports of this never contained, and stop discarding the packets

Every report of security software blocking Unsloth (unslothai#8523, unslothai#6326, unslothai#6588, unslothai#6648, unslothai#10540, unslothai#10805) named
no antivirus product, no detection name and no AMSI provider. Clearance is per hash and vendors act on
a detection name, so not one of those reports could be submitted anywhere, and not one of the six
hardening passes since can be shown to have fixed what it aimed at. That is the gap here.

## A required-field issue form

`.github/ISSUE_TEMPLATE/install-blocked-windows.yml`, a form rather than a markdown template for one
reason: a form can mark a field `required` and a template cannot. Required: the product and version,
the detection name exactly as displayed, the full error including the `FullyQualifiedErrorId` line,
and the output of a collection script. Also a dropdown separating "the script would not run at all"
from "something it created was blocked", because those are different mechanisms with different fixes
and have been conflated in past reports.

The script reads registered antivirus products from `root/SecurityCenter2`, resolves each AMSI
provider CLSID through `InprocServer32` to a DLL and reads its `CompanyName`/`ProductName`/version,
then `Get-MpComputerStatus` and recent Defender events. The provider resolution is the part that
actually answers "which product", since a bare CLSID is not actionable. So is `AMRunningMode`:
anything other than `Normal` means another product is primary.

It downloads nothing, writes nothing, and changes nothing -- and it deliberately carries none of the
shapes the installers are being cleaned of, because a diagnostic that trips the same product that
blocked the installer is worthless. A test enforces that: no `Add-Type`, no `Invoke-Expression`, no
base64, no `Set-MpPreference`, no `Remove-Item`, no `Start-Process`.

## The packets that were being thrown away

Two false-positive submission packets are built today and discarded. `release-desktop.yml` writes a
Microsoft submission packet to `$RUNNER_TEMP` and never uploads it, so `flagged-windows-bundles-*`
held the flagged bundles and nothing describing them; it is now included in that artifact. And
`scripts/virustotal_scan.py`'s packet went only into a job summary, which is ephemeral, so the one
document written for the purpose of disputing a detection was discarded along with the run; it is now
kept as an artifact.

Retention on the flagged bundles goes from 7 days to 90. Clearance is per hash and a rebuild hashes
differently, so those copies are the only submittable sample for that release, and a vendor round trip
plus our own reaction routinely outlasts a week -- after which the evidence for the detection being
disputed is gone.

`test_the_scan_job_is_not_conditioned_away` allowed `if: always()` on exactly one step. The new upload
needs it for the identical stated reason, "precisely so the evidence survives a failed scan", so the
exception becomes a named set of two rather than a shape a future step could inherit by resembling.

## Verification

- 675 passed, 6 skipped across `tests/security/` and `tests/python/test_virustotal_scan.py`.
- The collection script is extracted from the YAML and **parsed**, not eyeballed. It is pasted
  verbatim by people who are already stuck, so a syntax error in it costs them a round trip and
  reports our form instead of their antivirus. It also runs end to end under pwsh on Linux, where
  every Windows-only facility reports itself unavailable and nothing crashes.
- That guard earned itself immediately: the first draft put the script in a YAML **folded** scalar
  (`>`), which joins every line and silently collapsed the whole code block to nothing. The test
  catches that specific mistake and names it as the likely cause.
- Both new guards confirmed to bite: reverting the scalar to `>` fails three tests, and making
  `detection-name` optional fails with the reason the field exists.

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

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

* Upload the submission packet after the step that writes it, and make the form's labels real

Two defects found reviewing this PR, both of which would have failed silently.

## The packet was uploaded sixty lines before it was written

`Preserve flagged Windows bundles` is step 24; the packet is assembled in step 26. Steps run top to
bottom, so `${{ runner.temp }}/ms-submission-packet.md` never existed when that upload ran -- and
`if-no-files-found: ignore` would have hidden it permanently. The artefact meant to carry a vendor
submission would have held the flagged bundles and nothing describing them, which is the exact
failure this PR exists to fix, reintroduced one step higher up.

The packet now has its own upload step immediately after the step that writes it. The path is
removed from the earlier step rather than left in as harmless, because a path that cannot match is a
claim the file is covered. Removing it also avoids a side effect worth knowing: upload-artifact
computes the artefact root from glob pattern prefixes rather than matched files, so the second path
would have re-rooted that zip from flat to nested.

`if-no-files-found: ignore`, not `warn`: the packet is only assembled when there is something to
submit, so its absence on a clean release is the normal case and must not add an annotation to every
green run.

## Two of the form's three labels did not exist

`windows` and `antivirus-false-positive` were not among the repository's labels. GitHub does not
error on an unknown label, it drops it -- so every issue filed through this form would have arrived
with `bug` only, losing precisely the two triage labels the form exists to attach, with nothing
reporting the loss.

Both labels now exist on the repository, and `test_the_labels_the_form_declares_are_real` keeps the
form and the repository in step. It checks against a checked-in list rather than the GitHub API,
because a test that needs the network is a test that gets skipped.

* Start pwsh through the shared runner here too

Same reason as the sibling fix in the AMSI probe lane: tests/studio/test_pwsh_calls_use_the_shared_runner.py
bans a direct subprocess call to pwsh, because a direct one shares a single
$XDG_CACHE_HOME/powershell startup cache with every xdist worker and an interpreter that dies at
startup then reads as the script under test having failed.

Caught only by running the full suite against all ten open PRs merged into one tree; the guard lives
in tests/studio/ and never ran against this branch alone.

* Redact the profile directory and account name before the report is published

The collection block is a required field, so its output goes into a public issue, and it
printed Path and Process Name for every Defender detection in the last two hours whether or
not it had anything to do with Unsloth. On a normal machine those paths begin with the profile
directory and therefore carry the account name, and the file name can be anything the person
had open. The description also promised it touched no personal data, which was not true.

Redact at the point of printing rather than asking the reporter to do it, since the reporter is
someone whose install is already broken and who is pasting a block they did not write. Say
plainly what is still printed and tell them to read it first. Verified against paths with a
space in the name and with mismatched case.

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

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

* Match the Defender event fields, which are indented

Defender renders 1116 and its siblings as a header line followed by indented 'Field: value'
lines, so anchoring on '^Name:' matched none of them and the section that exists to carry the
detection name, the path and the triggering process emitted a timestamp and an event id and
nothing else. Measured against a message in the documented shape: the old filter selects the
empty string, the new one selects all six fields.

Severity is included now too, since it is free once the line is being read and it is the field
that tells us whether a report is a block or a warning. The guard drives the snippet's own filter
rather than asserting the regex text, so a future rewrite is judged on what it extracts.

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

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

* Give screenshots their own field, survive localised Defender labels, warn on the error field too

A render: textarea wraps everything it contains in a code fence, attachments included, so the
error field invited a screenshot it could never display. It keeps render: text, because it carries
pasted console output where the monospace block earns its place, and screenshots get their own
unrendered field.

Defender localises the event field labels, so the English-only filter missed them and a
non-English reporter would have sent a timestamp and an event id. Testing for an empty result is
not enough: German renders Name: identically, so one match out of six looks like a successful
extraction. The fallback counts instead, and prints the whole message, redacted and truncated,
when fewer than two fields resolve. Measured on English, German and Japanese messages.

The privacy note covered the probe output only. A PowerShell error quotes the script's location,
so on the documented cloned-checkout path the required error field carries the reporter's user
name and they are told to paste it verbatim before they reach that note. It now says the issue is
public and suggests the substitution.

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

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

* Warn on the issue form field that asks for a full path

The error and probe fields say the issue is public and show what to
write instead, but the file path field asked for a full path with only a
profile-shaped placeholder to follow, so a reporter doing what it says
publishes their user name. Give it the same warning and the same worked
replacement.

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

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

* Redact only real account components, and scope the probe's error preference

The username replacement rewrote every case-insensitive occurrence
anywhere in the line, so an account named win rewrote Windows Defender
and one named cat rewrote Wacatac. Those are the product and detection
names the form exists to collect, and the reporter cannot see it happen.
Require a path separator before the name and no word character after it.

The probe also set ErrorActionPreference at the prompt, which persists
for the rest of that session, against the field's own promise that it
changes nothing. Run the body in a script block so the assignment is
scoped to it.

* [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>
…ain (unslothai#11019)

main is not formatted the way its own pre-commit hook formats. Running
scripts/run_ruff_format.py with the pinned ruff 0.6.9 over every file the hook
selects changes three files on 52fb7b0:

    studio/backend/tests/test_diffusers_prewarm.py   (unslothai#10989)
    studio/backend/utils/torch_warmup.py             (unslothai#10989)
    tests/python/test_amd_extras_contract.py         (unslothai#7536)

Both of those PRs merged in the last hour with `pre-commit.ci - pr` in ERROR.

That is not only a tidiness problem, because it takes pre-commit.ci's autofix
down for every OTHER pull request. The hook runs against the PR merged with
main, so every PR's tree now contains these three files needing reformatting;
the autofix patch is computed over them and then cannot be applied to a head
that does not carry main's copy. Three PRs are red on exactly that, each with a
one-or-two-line formatting delta it cannot self-heal, all reporting:

    a conflict occurred when applying fixes to the pr.
    try pulling the upstream branch

So this is self-sustaining: unformatted code on main disables the autofix, and
PRs then merge red because nothing can push the fix for them.

The formatter, not the code, is the thing to trust here: it is pinned in
.pre-commit-config.yaml, and it is idempotent. Running it again over these files
changes nothing on the second or third pass, so this is a fixed point rather
than one step of a moving target. One hunk expands a short signature, which
looks wrong until you see why: the hook rewrites `path=None` to `path = None`
first, and the longer line then no longer fits.

Nothing but whitespace: comment_tools.py check --strict-ext reports 3/3 OK, so
every AST is unchanged. test_diffusers_prewarm.py 28 passed,
test_amd_extras_contract.py 10 passed. Re-running the hook over the whole tree
afterwards touches these three files and nothing else.
unslothai#10984)

* Measure whether the host property can replace the native console thunk

Measurement only. Changes no installer code and gates nothing. It is the prerequisite for the
largest AV-shape reduction available, and it is built so that it can say no.

## What it decides

`GetStdHandle` / `GetConsoleMode` / `SetConsoleMode` are three of the ten native imports left in
`install.ps1`, and in `studio/setup.ps1` they are the ONLY reason that file carries the
reflection-emit helpers, the child-process capability probe and a Device Guard CIM query at all --
roughly 300 lines whose entire purpose is colouring a banner. "Defines a dynamic assembly, P/Invokes
kernel32, spawns a hidden child interpreter" is the densest malicious-looking region in either
script, and VirusTotal's only high-severity Sigma hit on install.ps1 is `Potential WinAPI Calls Via
CommandLine`, which is that probe.

`$Host.UI.SupportsVirtualTerminal` is the documented replacement: the PowerShell console host runs
the same enable-VT sequence on its own stdout at startup and reports the outcome. Whether it agrees
on Windows PowerShell 5.1's conhost is a measurement, not a deduction, and being wrong prints raw
escape sequences at a user instead of a banner. So this measures both answers side by side.

## Why an ordinary CI step could not answer it

Actions captures stdout, so `[Console]::IsOutputRedirected` is true in every step and both answers
come back as the redirected ones -- which is precisely the case the installers decide early and never
reach the native path for. Confirming that: run locally under pwsh here, the property answers `True`
while stdout is redirected, which is exactly why `Enable-StudioVirtualTerminal`'s
`$script:StudioStdoutRedirected` early return has to stay whatever else changes.

The console case therefore runs under `conhost.exe`, which allocates a real console so the child's
stdout is a console handle and `GetConsoleMode` can answer. Results travel through a file, because
that console's output goes nowhere a runner can read. Windows PowerShell 5.1 specifically, since it
is the interpreter `install.rs:433-440` spawns and a different host implementation from pwsh 7.

## The control

Without it this lane would be worthless. A `conhost` that silently failed to attach would leave both
runs redirected, the two answers would trivially agree, and the job would report SAFE having measured
nothing. So the console run must report `isOutputRedirected=False` before any verdict is printed;
otherwise the job fails as an unmeasured console rather than a safe one.

Three outcomes, all explicit: SAFE (the two agree at a real console), UNSAFE (they disagree, do not
swap the implementation), or could-not-measure. There is no path where silence reads as success.

The probe emits its own P/Invoke stubs rather than using `Add-Type`, so the lane that exists to
remove a compiler does not introduce one, and it loads under RemoteSigned rather than a relaxed
policy for the same reason.

## Verification

- `Probe-VirtualTerminal.ps1` parses clean over 633 tokens; the workflow's inline step parses clean
  over 325.
- Run for real under pwsh on Linux, where it degrades honestly: the property answers, the native call
  records `GetStdHandle` failing because kernel32 is absent, and nothing crashes.
- `lint_workflow_triggers.py` clean over 51 workflows; `tests/studio/test_ci_shell_suite_coverage.py`
  and `tests/security/test_lint_workflow_triggers.py` green. Action SHAs pinned to the versions the
  rest of the repo already uses.

* Measure the console on every available Windows host, not just Server 2025

The lane reported one global SAFE verdict after sampling windows-latest, which is Windows
Server 2025 and is not what any user runs. The property and the startup virtual-terminal
behaviour are supplied by the OS, so ConsoleHost and the in-box Windows PowerShell differ
between images and agreement on one says nothing about another.

Measure windows-latest, windows-2022 and windows-11-arm. The last is the only client SKU a
hosted runner offers and so the closest thing here to the machine in the report. windows-2019
is not an option, GitHub retired it. fail-fast is off because one UNSAFE answer is the most
valuable result this lane can produce and cancelling its siblings would lose the comparison.

Each leg now states its own verdict and says it speaks for its own image; a summary job holds
the combined claim and names what is still not covered, which is Windows 10 and x64 Windows 11
client. The probe records the OS caption, build and architecture, because a verdict that does
not say which ConsoleHost produced it cannot be checked against the host a user reports.

Artifacts are named per leg: upload-artifact refuses a duplicate name, so one shared name would
have left a single leg's measurements.

* [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>
…fill (unslothai#10973)

* Studio: stop a short video clip from taking minutes to prefill

* Bound the shrunk video clip at the upload cap

* Drop restating comments

* Cap the re-encode at the frame rate llama-server samples

The scale filter changed the frame size but not the frame rate, so a 30 fps
source was re-encoded at 30 fps while this same change tells llama-server to
sample it at 1. Twenty-nine frames in thirty were encoded, counted against
max_bytes, and then dropped by mtmd.

Those wasted bytes are not free, because they are what the cap guard measures.
A legal 53 MB 12-minute 1080p30 upload transcodes to more than 64 MB, so the
guard fires and the ORIGINAL full-size clip is forwarded -- after a 25 second
ffmpeg pass. The slowest clips, which is the case this whole change exists for,
paid the conversion and got none of it:

    as merged      wall 24.7s   out 53.0MB   shrink applied: no
    fps=4 first    wall 10.7s   out 16.9MB   shrink applied: yes

Cap at MAX_FRAME_RATE = 4, llama-server's own --video-fps default, rather than
at the 1 Studio asks for. Then no configuration samples a frame the container
no longer has: Studio asks for 1, a build too old for --video-fps samples at 4,
and the documented Qwen override of 2 is still whole.

The cap only ever reduces. ffmpeg's fps filter DUPLICATES frames when asked for
more than the source has, so a 1 fps timelapse would come back four times
heavier; the rate now comes back from the probe alongside the area and the
filter is only prepended when the source is genuinely faster.

Measured on Qwen3-VL-2B-Instruct-Q4_K_M with llama.cpp b10976, 5s 720p clip:
prompt tokens are unchanged at every sampling rate (10172 / 2472 / 2796 / 696
for original-4fps / shrunk-4fps / original-1fps / shrunk-1fps) while the
attachment drops from 966,757 to 211,690 bytes. The model reads the burned-in
per-second captions back correctly either way.

Also in this change, all from the same review pass:

* Reject through _reject when the conversion raises, like the audio path
  directly above it. The helper absorbs its own ffmpeg failures, so anything
  reaching the route is unmodelled -- previously a raw 500 with a non-OpenAI
  body, and a leaked api_monitor entry with it.
* Fall back instead of raising AttributeError when ffprobe answers `-of json`
  with something that is not an object.
* Drop the decoded copy once it is on disk. It was held to the end only so the
  log line could read len(raw), keeping 64 MiB alive beside the output and both
  base64 strings.
* Correct the -q:v comment: -fs bounds the result at the upload cap, it does
  not keep it near the source size. Near-static 1080p still grows ~3.4x.

Tests: frames beyond the sampled rate are not re-encoded, a clip slower than
the cap keeps every frame, a long clip is really shrunk rather than forwarded,
and a non-object probe falls back. The route-ordering test matched source text,
so it stayed green when the conversion's result was discarded and the original
injected -- a change that silently disables the feature. It is now paired with
an AST check that the awaited call is bound and that the bound name is the one
_inject_video_part receives; verified to fail on exactly that edit.

23 pass, 0 skipped, with real ffmpeg 6.1.1. ruff 0.6.9 check and
scripts/run_ruff_format.py are clean.

* Keep a sub-second clip from reaching the model with no frames

Pinning --video-fps 1 introduced a regression at the short end. ffmpeg's fps
filter places its first output frame half an interval in, so at 1 fps a clip
under about half a second decodes to NOTHING and the model answers about a
video it never saw. Measured against llama-server's own `-vf fps=1` call:

    0.1s -> 0 frames   0.3s -> 0 frames   0.4s -> 0 frames
    0.49s -> 1 frame   0.6s -> 1 frame    1.0s -> 1 frame

and end to end on Qwen3-VL-2B-Instruct-Q4_K_M, a 0.2s and a 0.3s clip both
cost 21 prompt tokens, the bare text prompt, against 252 for the same clips at
the 4 fps default. Those clips worked before this PR, so this is a regression
guard rather than a new feature.

Hold the last frame out to MIN_SAMPLED_SECONDS with tpad, so every real frame
keeps the timestamp it was shot at and only the tail is invented. The floor is
a whole second rather than 0.5 to leave room for a rate typed into the
advanced arguments.

Two details that cost a round each:

* The pad has to run BEFORE the rate cap. `fps=4` has the same blind spot it
  exists to cover, so on a 0.1s clip the cap emitted nothing, tpad had no
  frame to clone, and the result was an undecodable 733 bytes. Padding first
  gives both filters something to work on.
* Scaling is now skipped for a clip already inside the pixel budget. A short
  clip can be small as well, and the scale factor is greater than one there,
  so the old unconditional chain would have UPSCALED it.

The probe returns the duration alongside the area and rate, and a clip that is
both big enough and long enough is still forwarded untouched with no re-encode.

Tests: a 0.1s, 0.3s and 0.4s clip each reach the sampler with at least one
frame and come back at the floor, and a within-budget two-second clip is still
returned by identity. 27 pass, 0 skipped, real ffmpeg 6.1.1. ruff 0.6.9 check
and scripts/run_ruff_format.py clean. The earlier long-clip, rotation, VFR,
byte-cap and degraded-environment suites all still pass unchanged.

* Let an explicit frame-rate override reach the encoder

Codex is right that pinning the transcode at 4 fps silently caps a user who
asked llama-server for more. The transcode runs BEFORE the server samples, so
the server can only duplicate what was dropped here.

Measured on a 5s 720p clip with --video-fps 8, counting frames the server
actually receives:

    transcode capped at 4   40 frames, 20 exact duplicates -> 20 distinct
    transcode honours 8     40 frames,  0 exact duplicates -> 40 distinct

Prompt tokens are 4692 either way, which is why this does not show up in the
token measurements: the user pays for 40 frames in both cases and, capped,
half of them carry no new information.

requested_video_fps() reads what the user actually asked for: the environment
first, since Studio suppresses its own flag entirely when LLAMA_ARG_VIDEO_FPS
is set, otherwise the LAST --video-fps in the extras, matching how llama.cpp
resolves a repeated flag. The route passes it to the encoder.

The ceiling only ever rises. Below llama-server's own 4 fps default it stays
at MAX_FRAME_RATE, so the two rates Studio produces on its own (1 when the
build takes the flag, 4 when it does not) keep the shape every earlier
measurement was taken against: the sub-second floor, the long-clip guard and
the 93% token reduction are all unchanged.

Also re-anchored the route-ordering test on the bare function name. It matched
the full argument list, so reflowing that call broke it with a ValueError from
str.index rather than an ordering failure -- twice now. The AST test added
alongside it already covers the semantics.

Tests: the rate is read from extras and environment including last-wins,
`--video-fps=N`, garbage and zero; the ceiling rises only above the default;
and an 8 fps override really keeps 8 fps of frames through real ffmpeg. 30
pass. ruff 0.6.9 and run_ruff_format.py clean. The edge, integrity and
sub-second suites all still pass.

* Resolve the requested frame rate from argv first, and match both spellings

Two follow-ups to the override fix, both confirmed against llama-server
b10976 rather than from the argument list alone.

argv beats the environment. llama.cpp reads the env var while registering the
option and argv overrides it afterwards, so an inherited LLAMA_ARG_VIDEO_FPS=1
alongside an advanced `--video-fps 8` samples at 8, not 1. Measured on a 5s
720p clip, prompt tokens:

    env=1, no argv      2796
    env=8, no argv     19392
    env=1 AND argv=8   19392   <- argv wins

Reading the environment first therefore capped the transcode at 4 for exactly
the case the previous commit set out to fix. Resolve argv first, fall back to
the environment only when argv says nothing.

llama.cpp also accepts the underscore spelling. `--video_fps 8` starts the
server while `--totally-bogus-flag 8` is rejected with "invalid argument", so
this is a real alias rather than a tolerated typo, and Studio's pass-through
validator permits it. An exact match on the hyphen missed it silently. Match
through `_flag_name`, which already normalises long-option underscores the way
llama.cpp does and peels `--key=value`, so `--video_fps=8` resolves too. Last
occurrence still wins across both spellings.

Tests cover the combined env-plus-argv case, both spellings with and without
`=`, last-wins across a mixed pair, and the environment still answering when
argv is silent. Verified to fail against the previous implementation. 30 pass.

* Pad a short clip whose container reports no duration

The sub-second floor read `format.duration`, which a raw elementary stream
does not carry, so `duration` stayed None, `_filter_chain` omitted the pad and
a 0.3s `.h264` still reached the model with no frames at all. Reproduced end
to end: probe returned duration None, the shrink was skipped, and ffmpeg's
`fps=1` emitted 0 frames.

Fall back to packet timing when the container is silent. Two shapes, because
the obvious one is not enough on its own: a stream with presentation times
gives max(pts_time + duration_time), and Annex B, which carries no timestamps
at all, gives the sum of the per-packet durations. The h264 fixture resolves
to 0.299997s that way and comes back with a frame.

Bounded by `-read_intervals` to twice the floor. The only question being asked
is whether the clip is SHORTER than the floor, so a clip still producing
packets past that window is long enough by definition and walking the rest of
it would buy nothing.

The fallback is consulted only when `format.duration` is absent, so an
ordinary mp4 never pays for it; a test pins that by failing if the packet
probe is called for a two-second clip.

Also stopped the test helper reading `format.duration` to size a frame. It
needs only the dimensions, and on the raw fixture it raised KeyError before
the assertion it was there to make could run.

Verified to fail with the fallback removed. 32 pass, and the edge, integrity
and sub-second suites are unchanged.

* Trim the comments to the facts the code does not state

---------

Co-authored-by: danielhanchen <[email protected]>
…10907)

* Studio: ask before a tool reads or writes outside the sandbox

The session sandbox directory is a working directory, not an OS boundary: for
the installation owner account_confinement() returns None, so a tool child runs
with the user's own permissions and an absolute path in a tool call reaches the
real filesystem. Deleting outside it already prompted in auto mode, but reading
and overwriting did not, so a model could clobber or exfiltrate host files with
no approval.

Relative paths still resolve inside the per-session workdir and stay silent, so
ordinary in-sandbox work is unaffected. An absolute path outside a set of
silent roots (the sandbox and project workspaces, the interpreter and its
site-packages, installed-software trees, the configured model and HF caches, the
model folders the owner registered) now asks first. The credential checks run
before the allowlist, so /etc/shadow still asks even though /etc is read-silent.

Both classifiers are covered: the terminal scan gates file operands and
redirection targets of read and write commands, and the python scan folds reader
and writer call arguments through the existing _folded_path machinery.

Measured on the benign corpus: 239us -> 246us per classifier call, which runs
once per tool call.

* Studio: close indirect routes to an out-of-sandbox path

cd / pushd / os.chdir re-point every relative path that follows, xargs builds
another command's argv out of the pipeline, tar takes its paths after a flag
word, subprocess hands the path to a child this scan cannot follow, and
ZipFile / Path.open carry the path as a constructor argument or a receiver.
Each of those reached a file outside the sandbox without ever putting it in an
operand position the first pass read.

* Studio: close the out-of-sandbox routes review found

A review of the first two commits turned up routes that still reached a host
path with no prompt, several confirmed by executing them. Each is a different
way of losing the path or its access mode, not a variation on one mistake.

Write mode was being re-derived from a table that does not list open, so
open(file = ..., mode = "w") was checked against the READ allowlist and every
read-silent root became silently writable. Path(p).open("w") carries its mode in
the first argument, because the receiver is the path, so it read as a read.
Archive constructors had the same defect.

The shell lexer is not given < and > as punctuation, so echo X>/media/y arrived
as one token and the redirect target was never seen. A wrapper brings its own
options, so skipping only its name left timeout 5 cat /media/x reading 5 as the
command. A path can arrive as a flag value, and the flag decides whether it is
read or written, so flags now resolve against a per-command table: that also
stops cut -d / and sort -t / from reading a field separator as the root
directory.

The rest: a name rebound after a read no longer reclassifies that read; walrus,
annotated and tuple bindings fold; a later absolute component discards the
earlier one, so os.path.join("/usr", "/media/x") is judged as /media/x; a child
process argv is screened as a command line so its write targets stay writes;
torch.save and joblib.dump put the destination second; Path.rename keeps its
receiver as the source; a single leading backslash is root-relative on Windows;
and C:relative.txt is not.

Two inversions are fixed. \x02 marks a pathlib .parent walking out of its root,
and grouping it with the unresolved marker turned an escape signal into a pass.
The stricter classifier gated the new check behind a leading / or ~, which made
it no longer a superset of the looser one for Windows spellings.

Path(p).write_text(content) took its first argument as a destination, so an
ordinary config value that looked like a path prompted; the builtin input()
prompt was read as a filename; numpy.save takes its path first, unlike
torch.save. All three now stay silent.

Credentials inside an allowlisted root are named explicitly, so a relocated
HF_HOME cannot hide a token store from a regex that keys on the directory name,
and Studio's own auth database stays gated.

* Studio: cut tool-call classifier cost by roughly 2.8x with no verdict change

The auto-mode classifiers cost ~289 us (high risk) and ~225 us (potentially
unsafe) per tool call, nearly all of it repeated work rather than analysis:

- _command_references_sensitive built twelve candidate strings per call (three
  base forms times four expansions) and scanned every one. For an ordinary
  command all twelve are the same string, so the superlinear credential pattern
  ran up to twelve times over identical text. Deduplicating the candidates keeps
  every distinct form and drops only exact repeats.
- The glob scans ran the fnmatch loops for tokens that contain no glob
  metacharacter at all. Nothing the rewrites do can introduce one, so a command
  without ? * or [ can skip the scan outright.
- _references_sensitive_path always searched three spellings of the text. The
  redundant-slash and de-bracketed rewrites are identity for an ordinary
  command, and re-scanning text the pattern already rejected cannot change the
  answer, so only a rewrite that changed the text is scanned again.
- The python classifiers swept the whole tree twenty-one times between them,
  each ast.walk rebuilding the same traversal. The node list is identical for
  all of them, so it is built once per parsed tree.
- Classifying one python call parsed the same source two or three times over.
  The tree is read-only, so one bounded cached parse serves all of them.
- The terminal operand scan built its segment machinery even when no token
  could spell an absolute path, and recomputed a basename per token for scans
  that mostly do not need one.

Verdicts are unchanged: 1461 payloads drawn from both classifier corpora, 2922
verdicts, zero differences, and zero classifier exceptions before or after. The
same comparison holds across 8 threads (23376 verdicts under contention), which
matters because the parse cache and the node list are now shared.

Measured on the fixed 2817-call corpus, median of five runs:

  is_high_risk_tool_call           289.0 us -> 103.4 us
  is_potentially_unsafe_tool_call  224.9 us ->  68.2 us
  p95                              611 us   -> ~240 us
  p99                              791 us   -> ~390 us

* Studio: keep Studio's own state out of the silent roots

studio_root() was allowlisted, and in the default layout tmp_root() and
shared_sandbox_root() resolve to that same directory, so studio.db (chat
history, provider and MCP configuration) and auth/ sat inside a silent root:
cat and echo > against them both ran with no approval.

Only the output subdirectories are silent now, and a structural guard drops any
root that is the studio home or an ancestor of it, so a producer that falls back
to the home cannot re-grant it later.

The root cache keyed only on the account id, so repointing the studio home or a
cache mid-process kept serving the previous install's roots for up to the TTL.
The key now carries that environment.

* Close four operand-scan bypasses in the tool path gate

tar: the positional skip exists for the legacy option word (tar cf out.tar src),
which GNU tar only accepts as the first argument. Applying it unconditionally ate
a real operand from the ordinary spelling, so tar -cf local.tar /media/private
archived an out-of-sandbox tree with no prompt. Scope the skip to args[0], and add
-g/--listed-incremental, a snapshot file tar creates, as a write in both spellings.
Archive create mode is now read from every short-flag token rather than args[0]
alone, so -g before -cf no longer hides it.

python: an attribute call is not always receiver-based. io.open(p), gzip.open(p),
os.open(p) and friends are module functions taking the path first, so folding the
receiver produced the bare module name and the read escaped. Split those out from
Path(p).open(), where the receiver really is the path, and take the mode from the
matching argument position.

python: a chained assignment (source = backup = '/media/private/x') has more than
one target and was skipped whole, leaving the name unfoldable at the later
open(source). Bind every simple target, and expand tuple targets elementwise so
a, b = c, d = ... is reached too.

Regression rows for all four, plus benign controls: relative tar operands in each
spelling, a filename containing a c not reading as create mode, relative
io.open/gzip.open, and Path(p).open() keeping its receiver.

* Close three more operand-scan bypasses

tar -C is where the operation happens, so its sense is the inverse of the
archive's: extracting creates and overwrites members under it, while creating
only reads them from it. It was classified as a read unconditionally, so
tar -C /usr/share -xf local.tar wrote into a read-silent root with no prompt,
while the equivalent cp prompted.

An aliased import (import io as stream) leaves a receiver that is in no table, so
stream.open('/media/private/x') read as a Path-style method and its first
argument was never looked at. Resolve Import aliases back to the root module
before the receiver tables are consulted.

shlex keeps a command substitution as one token, and that token is not itself
absolute, so cat "$(printf /media/private/x)" produced no operand at all while
the shell handed cat the real path. Literal absolute paths inside $(...),
backticks and ${...} now count as operands of the position they sit in, keeping
the read/write sense of that position. Only literals are recovered; a genuinely
dynamic substitution still yields nothing, which stays the documented gap rather
than a claim this closes.

Regression rows for all three, plus controls: -C in create mode is still only a
read, substitutions naming no path ($(date), $(ls)) stay silent, and relative
aliased opens stay silent. Classifier median is unchanged at ~105 us.

* Close five more operand-scan bypasses

grep -f / sed -e and friends supply the pattern from a flag, so no positional is
owed to one. The unconditional skip discarded the first real input file instead,
leaving grep -f patterns.txt /media/private/report.txt unclassified. The skip is
now cleared when a pattern-supplying flag is seen, in both the attached and
separate spellings.

grep --exclude-from names a file grep reads and was absent from the table, so the
attached form was discarded as an unknown flag.

A token may carry several redirections before the command word: bash accepts
</dev/null>/media/private/out printf payload. Kept whole because it STARTS with a
redirection, it recorded one read of /dev/null>/media/private/out under the silent
/dev root and the write past it was never seen. A single leading redirection with
its target attached is still left whole, which is the case that guard was for.

from io import open as fopen leaves a plain Name in no table, so the call was
never dispatched and its path argument never read. ImportFrom aliases of the
module open functions now resolve back to the real name.

A derived binding lost the alternate values of the name it was built from:
base = 'local'; base = '/media/x'; p = base + '/f' folded p to local/f only. Each
rebound dependency is now substituted one at a time, which keeps this linear in
the number of rebindings rather than a cartesian product, and is capped.

Regression rows for all five plus controls: ordinary grep with -e/-f, a plain
redirect, a relative from-import alias, and a derived binding that was never
rebound all stay silent. Classifier median unchanged at ~105 us.

* Distinguish module functions from receiver methods, and cap work not coverage

os.rename(src, dst) and shutil.copy(src, dst) are spelled as attributes but are
the FUNCTION form: both paths are arguments. Reading the receiver as the source
folded the bare module name and lost the destination entirely, so a statically
known out-of-sandbox move ran unprompted. The module-vs-receiver question is now
decided once per call and resolved through the import aliases, since every branch
that treats a receiver as a path has a module-function counterpart that does not.

tarfile.open takes the path first like the other module opens and was missing from
the receiver set, so the archive operand was never scanned.

import torch as t left _serializes_to_second_arg looking at receiver 't', which is
in no table, so t.save(model, '/media/private/model.pt') fell through to a branch
that never inspects the second argument. The receiver is resolved through the
aliases first.

The alternate cap I added last round discarded by POSITION, so eight benign
reassignments ahead of base = '/media/private' hid the only value that mattered.
It now keeps absolute candidates first and spends the cap on the remainder, so the
bound limits work rather than coverage.

Regression rows for all four plus relative controls. Performance: measured on
interleaved pairs against the previous commit; the two are indistinguishable. The
absolute figures are not quotable right now because the host is at load ~124, which
inflates both sides equally -- only the paired comparison means anything.

* Fold joins with POSIX semantics, and five more operand-scan fixes

The absolute-component rule was applied to EVERY folded path rather than at the
join that needs it. A doubled separator inside one literal is just a separator,
which the OS collapses, so /home/alice//usr/report.txt was read as a second root
and reduced to /usr, which is read-silent: the user's own file went unprompted.
os.path.join, Path(a, b) and the Path / operator now resolve an absolute component
at the join itself, where the meaning is unambiguous, and literals are left alone.

tar -cf/media/private/out.tar was rejected the moment the cluster body contained a
separator, because the whole body had to be alphabetic. A cluster whose last letter
takes an ATTACHED value is now split at the first non-letter.

tar --create carries the same mode as -c and was not read at all, so
tar --create --file=/usr/share/out.tar classified the archive as a read.

Function aliases were collected only for the open-like imports, so
from pandas import read_csv as rc left every other modeled reader and writer
reachable under an alias. The aliasable set is now derived from the path tables
themselves rather than listed by hand.

The alternate cap ranked by absolute rather than by need, so nine /usr rebindings
crowded out the one /media value that actually required approval. It now ranks by
_path_needs_approval.

A command string recovered from a variable is now split like a literal one. Worth
being precise about this one: it was a real gap in the operand scan but not a live
bypass, because a string passed to subprocess is unconditionally high risk already,
including subprocess.run('ls'). Fixed because the scan should be right on its own
rather than leaning on that.

Regression rows for all six plus controls. Performance measured against 96071e0
on interleaved pairs: high-risk min 104-108 us versus 111-117 us, so this round is
slightly faster, most likely from dropping the per-path absolute-component rewrite.

* Close the /proc magic symlink, diff's attached file options, assigned reader aliases, and the write half of the alternate cap

* Rename the wrapper duration pattern so it stops colliding with the existing one

* Model builtins.open and the interpreters that load a script

* Follow a dotted open receiver and an alias of an alias

* Join with POSIX rules in joinpath, let rg --files keep its path, and read a plain tilde as the sandbox

* Qualify numpy load, carry fold aliases into the operand pass, gate git -C, and root a Windows backslash join

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

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

* Classify a file URI, take each wrapper's own value flags, and read unzip's archive

* Move the out-of-sandbox approval subsystem into its own module

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

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

* Read curl's file URL, write sqlite3's database, and keep tar's sources read-only

* Keep a Windows path through the lexer, and read credential suffixes on any separator

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

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

* Merge the wget spec, read date -f and rg --ignore-file, and keep from-import provenance

* Follow an assigned path constructor, and make install -d a write

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

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

* Write curl's output dir and wget's long prefix, and follow a copied module

* Gate a reader reached through a ConfigParser instance

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

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

* Read git archive's added file, fileinput's files keyword, and an annotated alias

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

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

* Read sort's random source and reader-specific path keywords, and leave here-documents alone

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

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

* Gate wget's log, git's separate metadata dir, aliases used before rebinding and rebound names in expressions

* Scan commands inside control structures and backtick substitutions

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

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

* Run a double-quoted substitution as a command, read iconv, and follow an annotated reader

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

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

* Match task-scoped proc links, fold literal subscripts, read io.FileIO, and narrow the subprocess fallback

* Count quoted occurrences per token so a live redirection is not spared by a quoted twin

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

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

* A mv source is a write, and tar's short append and update modes write the archive

* Expand a literal kwargs splat, and reach fileinput through its alias and constructor

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

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

* A python move writes its source, and a named literal sequence reaches the sequence readers

* Keep user-owned tmpfs out of the read-silent roots, and read the stat family

* An ln target is a write, and a capped container keeps the paths that need approval

* Read the shell file predicates, and fileinput imported by name

* Unwrap a multicall binary, screen os.popen, and write an extraction destination

* Read make's selected makefile and directory, and the python path predicates

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

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

* Classify without creating the database, and close the Windows path gaps

* Read jq's module directory and the path a pandas ExcelFile opens

* Write a python link target and a sqlite connection, and read curl's config file

* Run a here-string substitution, and classify a subprocess executable on its own

* Resolve symlinks before accepting a silent root, and rebuild roots when the database changes

* Read redirections from the raw command, keep str.join semantics, and follow a reader's own keyword

* Fix/adjust test operand and filesystem-root reads for PR unslothai#10907

* Fix/adjust env's lone dash, subprocess argv[0] and sqlite's database keyword for PR unslothai#10907

* Fix/adjust archive sources and shutil archive helpers for PR unslothai#10907

* Fix/adjust make_archive positions, aliased archive ctors and literal splats for PR unslothai#10907

* Fix/adjust an archive constructor imported from its module for PR unslothai#10907

* Fix/adjust process substitutions, io.open_code, the WAL revision and two platform fixtures for PR unslothai#10907

* Fix/adjust zcat readers, nested substitutions, read_excel and resolved credentials for PR unslothai#10907

* Fix/adjust the cost of validating a cached root set for PR unslothai#10907

* Fix/adjust basename, dirname and the ambiguous replace and remove methods for PR unslothai#10907

* Slim the name tables in the approval module for PR unslothai#10907

* Fix/adjust quoted shell words, shared account roots and stdout compressors for PR unslothai#10907

* Fix/adjust tar mutation modes and the 7z command word for PR unslothai#10907

* Fix/adjust a cd before a write, tar --add-file and zip sources for PR unslothai#10907

* Fix/adjust an interpreter payload and a chdir before a write for PR unslothai#10907

* Fix/adjust h5py File and date --reference for PR unslothai#10907

* Fix/adjust clustered in-place flags, xargs write mode, h5py modes and chdir subprocess writes for PR unslothai#10907

* Fix/adjust abbreviated long path options for PR unslothai#10907

* Fix/adjust fd custom ignore file as a read for PR unslothai#10907

* Fix/adjust keyword constructor modes and sqlite Connection for PR unslothai#10907

* Fix/adjust permission commands and tempfile destinations for PR unslothai#10907

* Fix/adjust compiler output, make directories and git init for PR unslothai#10907

* Fix/adjust launched binaries and nested interpreter writes for PR unslothai#10907

* Fix/adjust recursive reads of the filesystem root and managed account subtrees for PR unslothai#10907

---------

Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…ot answer, and setup.ps1 keeps a working GPU prebuilt over a source build (unslothai#11007)

* Bootstrap selectors read the NVIDIA driver library when nvidia-smi cannot answer; setup.ps1 keeps a working GPU prebuilt over a source build

* Reject a failed driver-version read, feed the inventory to the CUDA toolkit filter, and probe once per installer invocation for PR unslothai#11007

* Void a partial capability inventory, initialise the setup.ps1 cache with its script state for PR unslothai#11007

* Read legacy prebuilt marker shapes in the setup.ps1 keep guard, for PR unslothai#11007

* master asks for a source build, so the keep guard does not keep over it, for PR unslothai#11007

* Read the driver library inventory once per run, for PR unslothai#11007

* Read the driver library with the managed venv's interpreter when there is no system python3, and do not remember a missing one, for PR unslothai#11007

* The inline driver-library reader falls through to the CUDA driver API when NVML raises, and the presence check primes its memo in the parent shell, for PR unslothai#11007

* Name nvml.dll by its System32 or NVSMI path in both PowerShell copies, for PR unslothai#11007

* Keep a Vulkan prebuilt for any Intel adapter, as the selector routes them, for PR unslothai#11007

* Emit the driver-library P/Invoke methods instead of compiling them, read them in a runspace under the deadline, and print the inventory notice through Write-StudioLine, for PR unslothai#11007

* Compare the nvml.dll path as returned, for PR unslothai#11007

* Allow the inventory's native imports and stub the keep guard in the routing harness, for PR unslothai#11007

* Skip the NVIDIA prime for a pinned index or no torch, for PR unslothai#11007

* Read the CUDA driver API with the visibility mask lifted, in the shell and PowerShell readers, for PR unslothai#11007

* Do not rediscover a rejected nvidia-smi once the library stood in, for PR unslothai#11007

* Gate the emitted probe type on the native-type capability, for PR unslothai#11007

* Balance the helper-file expression in the inventory test, for PR unslothai#11007

---------

Co-authored-by: danielhanchen <[email protected]>
…rs a GPU-capable llama-server beside a CPU build (unslothai#11005)

* Runtime NVML memory fallback, GPU-capable llama-server preference, Windows embedding DLL path

* Honour uuid CUDA_VISIBLE_DEVICES masks in the NVML fallback and prefer the GPU build this host's vendor runs

* Keep a denied pinned candidate ahead of the GPU-capable reorder for PR unslothai#11005

* An ambiguous uuid abbreviation hides every GPU; the real-host probe test allows a card with no free memory

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

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

* List MIG slices in the probe so a MIG assignment is honoured, and prefer only backends this process can reach, for PR unslothai#11005

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

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

* Hand a uuid mask back to the child as uuids, keep a known-empty vendor set, void the probe on a missing handle, for PR unslothai#11005

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

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

* Keep the devices before an invalid mask entry, prefer the GPU build in the legacy in-tree fallback, read the CUDA mask for HIP, for PR unslothai#11005

* A MIG parent is its first slice to CUDA: report the slice memory and pin the child to it, for PR unslothai#11005

* A MIG slice the mask names stays that slice, for PR unslothai#11005

* One MIG slice per card, and the uuid map is reset for every memory query, for PR unslothai#11005

* Apply the repository kwarg spacing, for PR unslothai#11005

* Read the WSL2 runtimes behind /dev/dxg as the GPU vendor, for PR unslothai#11005

* Derive the child's uuid pin from the NVML rows on each call, let a GPU build for another vendor yield, skip the Linux path test on Windows, for PR unslothai#11005

* Make the embedding and sibling-build tests independent of the host, for PR unslothai#11005

* Tell the probe child to emit utf-8, and pin the embedding test off Apple Silicon, for PR unslothai#11005

* A visible NVML row without a memory reading voids the answer, for PR unslothai#11005

* The two ROCm visibility masks stack when deciding whether AMD is reachable, for PR unslothai#11005

* A full card is a reading; only a missing total voids the NVML answer, for PR unslothai#11005

---------

Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…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>
…l output (unslothai#10895)

* fix(studio): keep Studio's auth directory out of the tool loop

The CLI caches the raw API key at $STUDIO_HOME/auth/.cli_api_key_<stem>_<digest>
so a relaunch reuses it instead of minting another (unslothai#10595). Tool subprocesses
run as the backend's own OS user, so the 0600 mode on that file is no boundary
against them, and the sandbox does not confine absolute paths. The auto-mode
classifier did not recognise the auth directory either, so a model-emitted
`cat ~/.unsloth/studio/auth/.cli_api_key_*` ran with no confirmation and the
plaintext bearer went back to the provider in the next request. The same
directory holds the bootstrap password, the desktop secret, the llama stream
key and auth.db with the JWT secret.

Two independent guards, so neither one has to be complete:

- `_references_studio_credential` recognises those basenames, the default
  `.unsloth/studio/auth` layout, and the resolved `auth_root()` so a custom
  UNSLOTH_STUDIO_HOME is covered exactly. It feeds the existing
  `_references_sensitive_path`, so terminal, python and MCP all treat these as
  high risk, and it refuses the call outright in `_bash_exec`, `_python_exec`,
  `_edit_file` and MCP dispatch. That refusal holds in every permission mode,
  Bypass Permissions included: no user flow asks a tool to read Studio's own
  credentials, and an approval should not be able to hand them out.
- Any sk-unsloth key or desktop secret that reaches a result by some other
  route is masked in `strip_result_for_model`, which is the one transform every
  model-bound tool result passes through. Only that copy: `record_result` and
  `tool_end_event` are untouched, so the tool card the user sees renders exactly
  as before. `_split_frontend_suffix` opts out, since it subtracts the stripped
  body from the text and needs the strip to stay suffix-only.

The cache itself is unchanged (minting, reuse, revocation cleanup), so the
launch flow still reuses one key across restarts; `_write_auth_secret` just
chmods auth/ to 0700 the way the DB connection already does.

Deliberately narrow, so ordinary work stays unprompted: an application's own
auth/ package, auth.py, `grep -rn auth src/`, `sqlite3 ./auth/auth.db` and a
`llama_api_key` variable all match nothing.

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

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

* fix(studio): close the relative auth-dir read, mask half keys, prefilter the guard

Three things simulation turned up.

A platform matrix over what `auth_root()` resolves to (Linux default, custom
STUDIO_HOME, venv prefix install, legacy home, WSL, macOS default and
Application Support, Windows default / custom drive / ProgramData, and the case
where the root cannot be resolved at all) found one spelling that reached the
directory anyway: `cd <studio home> && ls -a auth`, which carries no absolute
auth path and no Studio basename. The root spelling is now recognised too, but
only together with a `cd` INTO it, so `grep -rn auth <studio root>/logs/studio.log`
and `ls <studio root>/models && grep -c auth app.log` stay ordinary work.

A result cut to fit the context window can end mid-key, and half a bearer is
still credential material, so the redaction floor drops from 16 characters to 8.
`sk-unsloth-` with nothing after it (prose about the format) still reads through.

The terminal classifier calls the path check once per candidate token of every
command, and the added ~2.5us per call showed up as +10% on that classifier. A
literal prefilter over the five substrings every pattern needs takes the
predicate to 0.63us and the classifier to +5.6% (about 20us per command).

Tests cover the relative-read case with a temporary studio home, the benign
root-mention commands next to it, and the truncated key.

* fix(studio): cover the coding-agent key cache in the same directory

`unsloth start` keeps the keys it mints for coding agents in
$STUDIO_HOME/auth/agent_api_key.json, in the clear, next to the CLI cache. The
directory patterns already covered it by path; naming the file counts now too,
so it is refused the same way whatever route names it.

* Studio: normalize auth paths, require a segment boundary, mask the stored card

Three issues from review.

The guard matched the raw text, so OS-equivalent spellings walked past it:
<home>//auth/auth.db and <home>/./auth/auth.db both opened the protected
database while reading as ordinary paths. The path is collapsed with the
existing redundant-separator normalization before the Studio checks now, and
both spellings are matched.

The marker test was a bare substring, so any path merely starting with the auth
directory name was refused in every permission mode: <home>/authors/notes.txt
and <home>/auth-backup/readme.md are harmless and were blocked. A marker now has
to end at a separator or at the end of the path.

Redaction ran on the model path only, so the card kept the raw text. That is a
replay hole rather than a cosmetic difference: the frontend persists this
payload and serializes the stored value back into a role=tool message on the
user's next turn, so a leaked key was hidden from the continuation and sent to
the provider one turn later. tool_end_payload masks it too, which also closes
the stored copy. The card shows the user their own key, so masking it there
costs nothing.

* Canonicalize auth paths and bound the cd root match

The guard matched only the tidiest spelling of the auth path. The OS opens
<home>/bin/../auth/auth.db and, on a Windows custom install, C:\Studio\.\auth\auth.db
as the same protected database, and both walked past it: the existing collapse
only handled // and /./ forward-slash forms. Canonicalize lexically instead --
separators unified, . dropped, x/.. cancelled -- and compare the markers in the
same spelling, since on Windows they carry backslashes the canonical text no
longer has. Lexical, not realpath: no filesystem access and nothing to race, and
it is an extra candidate rather than a replacement, so a match in the raw text
still counts.

The cd marker had no trailing boundary, so it fired on any path merely starting
with the Studio root. cd <home>/models && grep auth README and cd <home>-backup
&& ls auth were both refused in every permission mode despite never going near
the auth directory. Require the root to end where it matched, or to continue into
auth itself.

Regression tests for all six equivalent spellings, both false positives, and the
two real cd forms they must not cost.

* Studio: cover the variable and escaped-space spellings of the auth dir

Three gaps found while testing the guard across Linux, macOS, Windows, WSL and custom
studio homes, plus one false positive:

- `cat $STUDIO_HOME/auth/auth.db` reached the file. Both studio-home variables survive into
  the tool subprocess environment, so the shell expands them for real. The variable
  spellings of the home ($VAR, ${VAR}, %VAR%, $env:VAR) are now markers in their own right,
  as is ${HOME} alongside $HOME and ~.
- A home whose name contains a space, which is the normal macOS case, is spelled with a
  backslash escape in a shell. Read as a separator it split the directory name in half, so
  unescape before canonicalising.
- A bare auth path ending at a newline missed the segment boundary.
- `print('agent_api_key.json')` was refused. The bare name is an ordinary string, so only
  its path form counts now; a relative read still needs a cd into the auth directory, which
  the existing rule catches.

The marker set grew, so it is now resolved into (marker, canonical marker) pairs once per
process, and the variable spellings are skipped for any text containing no $, % or ~. The
terminal classifier cost went from +5.6% to +5.1% while covering more spellings, and the
executor entry check from 3.3 us to 1.3 us per command.

Parity over the 1861-string corpus is unchanged: the same 25 verdicts move, all of them
reads of this install's own credentials.

* Studio: dequote path fragments, and keep the key mask to hex

Two more from the review:

- A shell concatenates adjacent fragments, so `sqlite3 "$UNSLOTH_STUDIO_HOME"/auth/auth.db`
  opens the same file as the unquoted spelling. With the quote left in place no marker could
  span it, so the candidate is dequoted before matching.
- The cached key is `sk-unsloth-` + token_hex(16), but the mask accepted any alphanumeric
  suffix, so this repository's own `sk-unsloth-internal-workflow` came back as
  `[redacted]-workflow` in source listings and test output. The suffix is hex now, which
  still masks a key cut in half by the context-window fit.

Parity over the 1861-string corpus is unchanged at the same 25 moved verdicts.

* Mask Studio credentials in the LIVE tool output stream too

Masking tool_end alone was not enough. The card is painted from the tool_output
chunks that stream while the tool runs, and tool_end arrives afterwards, so a key
was rendered in full and persisted that way regardless of what the final payload
said. Caught by screenshotting the card: the output block showed the key with
[redacted] on the line below it.

Mask each chunk as it is emitted. A key can straddle a chunk boundary, where a
per-chunk regex sees two halves that each match nothing and prints both, so
_hold_back_partial_secret defers a tail that may still be an open credential
token into the next chunk. It also defers a tail that is only a partial PREFIX
(...sk-unslo), which no search for the complete marker can see. The carry is
flushed when the stream ends or is capped, so deferred text that turns out to be
ordinary is emitted rather than swallowed.

Regression test covers whole, mid-token, mid-prefix and surrounded spellings, a
chunk larger than the scan tail, and the two no-secret cases that must pass
through byte for byte.

* Studio: resolve traversal out of the sandbox before allowing it

The tool cwd is <studio home>/sandbox/<session>, a sibling of the auth directory, so
`open('../../auth/auth.db')` reads the protected database while naming neither the
directory nor a credential basename. Bypass Permissions skips the blocklist, so this guard
was the only thing left, and it only saw the unresolved text.

The two executors now resolve the `..` tokens of a command against the cwd they are about
to use, and refuse when one of them lands in the auth directory. Only traversal is
resolved: a relative path without `..` stays inside the sandbox, which is not where the
credentials are, and the whole step is skipped for a command that contains no `..` at all,
so the ordinary command pays nothing. Traversal that lands anywhere else, `cat
../notes.txt`, `ls ../../models`, still runs.

* Catch the auth path assembled through a shell variable

Bypass Permissions keeps STUDIO_HOME in the child env, so the shell resolves
r=$STUDIO_HOME; sqlite3 "$r/auth/auth.db" to the protected database while the
literal text names neither the directory nor a credential basename. The direct
$STUDIO_HOME spelling was already covered; one level of indirection was not. That
matters more than it looks, because auth.db carries no sk-unsloth- prefix either,
so the result redactor cannot mask the JWT secret on the way back out.

Reuses _expand_shell_assignments, the same best-effort substitution the
sensitive-path scan already applies, rather than adding a second mechanism. It
only ever adds detections, and the whole step is skipped for a command with no $
in it, so the guard stays at ~1.5 us per tool call.

Regression test covers the sqlite3, cat, literal-assignment and direct spellings,
and the four benign shapes that must not be refused, including `r=$STUDIO_HOME;
ls $r/models` -- naming the studio home is ordinary work.

Being explicit about what this does not do: this is still literal analysis. A path
the shell computes at runtime, or one assembled past what this can fold, reaches
the filesystem regardless. The durable answer is the OS-level boundary, which is
tracked separately.

* Studio: check the path the tool actually opens, not only the text

Two more shapes that named the auth directory without spelling it:

- `os.path.join("..", "..", "auth", "auth.db")` in python. The text scan sees four
  ordinary strings and no path; Bypass Permissions has already skipped the code analyzer.
  The executor now folds the paths the code builds, with the same `_folded_path` the
  sensitive-path analyzer uses, and resolves them against the cwd like any other relative
  path. A dynamic piece or a name bound more than once is left to that analyzer.
- `edit_file` with a relative path. The guard ran on the raw argument, but the resolve joins
  it to the sandbox workdir, a sibling of the auth directory, and Bypass Permissions lifts
  containment, so `../../auth/agents/opencode/opencode.json` reached the protected tree and
  the receipt echoes a window of the file back. The resolved target and its realpath are
  checked too, which also closes the symlink alias.

Ordinary work is untouched: `os.path.join("..", "data", "x.csv")`,
`os.path.join("src", "auth", "views.py")` and a relative edit inside the sandbox all still
run, and parity over the 1861-string corpus is unchanged at the same 25 moved verdicts.

* Follow the working directory across a cd in the same command

cd ../.. from the session sandbox lands on the Studio root, and the auth/auth.db
that follows is then the protected database under a name that matches nothing on
its own. Resolving the traversal and the later relative path independently against
the ORIGINAL cwd misses it: neither half reaches the auth directory, only the
composition does. Bypass Permissions skips the blocklist, so this guard was the
only thing left, and auth.db carries no prefix the result redactor can mask.

Track the directory each cd moves to and re-resolve the command's relative paths
against it. Bounded: the walk stops after eight directories, the whole step is
skipped for a command with no cd in it, and the guard stays near 1 us per call.

The false-positive side is what decides how aggressive this can be, since a
refusal here applies in every permission mode. cd ../.. && ls models, cd build &&
make and cd subdir && cat auth/config.json all still run -- that last one matters,
because an auth directory the user owns deeper in the sandbox is still theirs.

Still literal analysis: a path the shell computes at runtime reaches the
filesystem regardless. The durable answer is the OS-level boundary, tracked
separately.

* Studio: the walked directory itself, and the proc cwd symlink

Two more ways to name the auth directory without writing its path:

- `cd ../..; cd auth; sqlite3 auth.db` never writes a path with a separator in it, so every
  token in it reads as an ordinary filename. The cwd walk already reached the directory; now
  the walked directory itself is tested, not only what is opened from it.
- `/proc/self/cwd/../../auth/auth.db`. The kernel resolves that symlink to the session
  sandbox first and applies `..` to the result, while a lexical normpath reads it as
  `/proc/self/auth/auth.db` and misses. The cwd is substituted back before the test, which
  is what the kernel is about to do anyway.

`cd ../..; cd models; ls`, `cd .. && cd data && cat x.csv`, `cat /proc/self/status` and
`ls /proc/self/cwd` all still run, and parity over the 1861-string corpus is unchanged at
the same 25 moved verdicts.

* Studio: pad-proof the cwd walk, the shell PID alias, the studio-home variable

Three more shapes from the review, all of them ways to name the auth directory that the
literal scan cannot see:

- The walk counted `cd` commands, so `cd .` eight times filled the budget and the two that
  entered the auth directory after it were never looked at. It counts distinct directories
  now, and the cap sits at 64, which no real command reaches.
- `/proc/$$/cwd/../../auth/auth.db`. The shell expands `$$` (and `$BASHPID`, `$PPID`) to a
  PID before opening the path, so it names the same symlink a literal number does.
- `os.environ["UNSLOTH_STUDIO_HOME"] + "/auth/auth.db"`. The fold marks the dynamic prefix
  and this guard skipped it, but bypass mode keeps that variable in the child env, so when
  the code reads one of the studio-home variables the prefix has a known value and
  substituting it is not a guess. Any other dynamic path is still left to the sensitive-path
  analyzer.

`cd .; cd models; ls`, `echo $$`, `cat /proc/self/status`, and the same variable pointed at
`/models` all still run. Parity over the 1861-string corpus is unchanged at the same 25
moved verdicts.

* Studio: cmd.exe cds and Windows env lookups are case-insensitive

* Studio: read a wildcard path the way the shell will expand it

* Studio: collapse doubled separators in the canonical path, and fix a Windows-only test

Both found by running the suite on a Windows runner rather than by reading the code.

The canonical fold claimed to collapse `//` but only dropped `.` and `..` segments; the
collapse lived in the separate slash-normalised candidate, which is built from the RAW
text. A Windows path written with mixed separators, `C:\Studio\studio-home//auth//auth.db`,
therefore matched neither candidate and was allowed. The fold collapses empty segments now,
keeping the first two positions so a leading slash and a UNC `//server/share` survive.

The other failure was the test's own: a Windows path inside a python string literal turns
its separators into escapes (\U, \A, \t), so the snippet under test stopped being the path
it named. It is written with as_posix() now, and the mixed-separator spelling that failed is
pinned as a case of its own.

* Studio: HOME is the workdir under bypass, so resolve it that way

* Studio: pushd, a python chdir, and a lower-case %home%

Three more ways to move the working directory before naming the file:

- `pushd DIR` makes DIR the working directory exactly as `cd` does, so the walk recognises it
  now.
- `os.chdir('../..')` moves every path after it in the same snippet. The fold checked each
  expression against the starting workdir, so the move reached only the studio root and the
  `auth/auth.db` after it still looked like it was inside the sandbox. The fold follows the
  chdir chain in source order now, and resolves a relative path against the directory the
  code is standing in by then. Plain string constants are folded too, since
  `sqlite3.connect('auth/auth.db')` is not a path constructor and the argument is the path.
- cmd.exe environment names are case-insensitive, so `%home%` expands like `%HOME%`.

`pushd ../models; ls`, `popd`, `os.chdir('../data')` then reading a csv, an `auth/auth.db`
opened from the sandbox itself, and `auth` used as an ordinary string all still run. Parity
over the 1861-string corpus is unchanged at the same 25 moved verdicts.

* Studio: a studio-home variable pointing at another app is not ours

* Studio: tighten the comments on the auth guard

Comments and docstrings only, no code touched. 167 added comment lines across the three
backend files become 86: the narration and the restatements go, every load-bearing fact
stays, and the multi-line rationales are one line each.

* Studio: compare the studio-home value case-insensitively

Windows paths are case-insensitive, so a value spelled with a different drive-letter case is
the same directory. Comparing it exactly made the variable look like it pointed somewhere
else and dropped every spelling of it from the guard, which is worse than the over-block the
comparison was added to remove. normcase on both sides, and two tests: the same directory in
another case is still ours, a genuinely different directory still is not.

* Studio: a symlinked studio home is still this install

`studio_root()` resolves aliases, so a STUDIO_HOME that is a symlink or a Windows junction to
the configured root compared unequal to it and every spelling of the variable was dropped
from the guard, while the child still inherits the alias and reaches the real database
through it. The comparison falls back to realpath on both sides, so the alias is recognised
as the same directory and stays registered as a marker in its own spelling.

* Studio: a failed directory change leaves the cwd where it was

`cd missing` fails and the shell carries on, so the next `cd ../..` starts from the real
sandbox and reaches the studio root; python catching the OSError from a `chdir` is the same
shape. Both walks assumed every change succeeded, which resolved the rest of the command
against a directory it was never in.

Each walk now carries the set of directories the command could be standing in, moved and
unmoved, capped at the same 64 so a long chain cannot grow it without bound. Ordinary work is
unaffected: `cd missing; ls`, `cd ../data && cat x.csv` and a chdir into a subdirectory
followed by reading its own auth.db all still run, and parity over the 1861-string corpus is
unchanged at the same 25 moved verdicts.

* Studio: cd options, padded failures, and a keyword chdir

- bash documents `cd [-L|[-P [-e]] [-@]] [dir]`, so `cd -P ../..` has its target after the
  option; the option was being read as the target and then skipped for starting with a dash.
- Seven failing `cd`s produce enough hypothetical states to fill the cap, and the truncation
  dropped the starting directory, which is exactly where the shell is when every one of them
  fails. The starting directory is kept first now, and the cap bounds the state set only,
  never the scan.
- `os.chdir(path='../..')` is the same call as the positional spelling.

`cd -P ../models; ls`, `cd -; ls`, a padded command that then reads an ordinary file, and
`os.chdir(path='../data')` all still run. Parity over the 1861-string corpus is unchanged at
the same 25 moved verdicts.

* Studio: read a glob per path token, not per command

`sqlite3 <studio home>/a?th/auth.db` starts its segments at `sqlite3 <studio home>`, so
comparing from segment zero could never line up with an absolute marker and the expansion
walked through. The glob pass reads each path-shaped token on its own now, which is the unit
a shell expands.

Listing a parent stays ordinary work: `ls <studio home>/*`, `ls <studio home>/models/*.gguf`
and `cat <studio home>/logs/*.log` all still run, and parity over the 1861-string corpus is
unchanged at the same 25 moved verdicts.

* Studio: resolve the workdir for any move, and only for what follows it

- `pushd <studio home>; sqlite3 auth/auth.db` carries no `..`, so the executor passed no
  workdir and the walk that would have caught it never ran. The workdir is resolved for
  anything that can MOVE the directory now, not only for traversal.
- The other half is an over-block: every relative token in the command was resolved against
  every directory reached later, so `cat auth/auth.db; cd ../..` was refused even though the
  read happens in the sandbox, before the move. The walk records where each `cd` ends and only
  what comes after it is resolved against the new directory.

Parity over the 1861-string corpus is unchanged at the same 25 moved verdicts.

* Studio: pathlib parent walks, and the option terminator

- `Path.cwd().parents[1] / "auth" / "auth.db"` walks up from the sandbox without writing a
  `..`, and the fold marks that walk rather than spelling it. The guard reads the mark now
  and tests the tail against every ancestor of the cwd, because `parents[n]` folds to a
  single marker whatever n is. Only a tail that lands exactly in the auth directory matches,
  so `Path.cwd().parent / "data" / "x.csv"` and a parents walk into `models/` still run.
- bash accepts `--` as the end of options, so `cd -- ../..` has its target after it.

Parity over the 1861-string corpus is unchanged at the same 25 moved verdicts.

* Studio: command positions, explicit bases, chdir aliases

Two over-blocks and one hole, all from the same review:

- `cd` counted wherever the word appeared after a space, so `echo cd ../..; cat
  auth/config.json` recorded a directory change that never happens and refused a project's own
  auth/ file. It is matched at a command position now: start of line, after a separator, or
  after `then`, `do`, `else`.
- A parent walk from an EXPLICIT base is that base's parent: `Path('/tmp').parent / 'auth' /
  'auth.db'` is `/auth/auth.db`, not something under the sandbox. The base and the level count
  come from the expression now, rather than the tail being tried against every ancestor, which
  also makes `parents[n]` exact: from `<home>/sandbox/<session>`, parents[1] is the home and
  parents[3] is well past it.
- `from os import chdir as move` and `move = os.chdir` are ordinary python, and a walk that
  knew only the literal name resolved everything after `move('../..')` against the wrong
  place.

Parity over the 1861-string corpus is unchanged at the same 25 moved verdicts.

* Studio: resolve PWD to the tool workdir before validating paths

Bash rewrites PWD on every cd, so under Bypass Permissions it names the tool
workdir. The guard treated $PWD as a literal directory segment, so
$PWD/../../auth/auth.db resolved as <workdir>/$PWD/../../auth/auth.db and
missed the auth directory. Substitute the shell spellings ($PWD, ${PWD},
%CD%, $env:PWD) with the workdir before traversal is resolved, the same way
$HOME already is, and resolve a python snippet's dynamic piece against the
cwd when the code reads os.environ["PWD"], os.getcwd() or Path.cwd().

* Studio: builtin-wrapped cd, and named literal bases are not the cwd

`builtin cd ../..` and `command cd ../..` run the same shell builtin with the
same argument, so every relative path after them is resolved from the new
directory. The walk matched only the bare name, so the move went unrecorded
and an auth/auth.db that followed still looked like the sandbox's.

A parent walk from a name also assumed the name held the working directory.
`root = Path('/tmp/project'); root.parent.parent / 'auth' / 'auth.db'` is
/auth/auth.db, not this install's, and refusing it blocked a project from
reading its own auth directory. Names bound once to a literal path now resolve
to that path; a name that is rebound, or bound to something the fold cannot
read, still falls back to the working directory.

* Studio: shell punctuation ends a credential name

`cat /tmp/.bootstrap_password; echo done` names the file, but the boundary
after a credential basename accepted only whitespace or a quote, so attached
punctuation hid the name from the match. The boundary now ends where the shell
ends a word, taking the separators, redirects, subshell parentheses and
backtick with it. Ordinary work carrying the same punctuation stays ordinary:
`cat notes.txt; echo done`, `grep -rn auth src/;` and `cat auth.py;` all run.

* Studio: a quoted cd into the studio root is not a move

The cd-into-the-root rule matched wherever the text appeared, so
`echo 'cd <root>'; grep auth README` read as a move into the studio root and
refused an ordinary source search in every mode. It now matches only where a
shell would run one, the same command positions the relative-directory walk
already uses, including the builtin wrappers. A real move still counts in each
of those positions: after a separator, inside then/do/else, and via pushd.

* Studio: a chdir to a parent walk moves the directory

os.chdir(Path.cwd().parents[1]) is an ordinary move into the studio root, but
the fold writes a parent walk as a single marker and the chdir branch skipped
any target carrying one. The move went unrecorded, so a later relative
auth/auth.db was resolved against the stale sandbox directory. The walk is now
resolved the same way it is everywhere else, from the bases the expression
names, so a walk from a literal base still lands on that base's parent.

* Studio tests: drop a duplicate definition of the same guard test

Two tests were named test_a_studio_home_variable_pointing_elsewhere_is_not_ours
and the later one silently won, so the first never ran. The copies asserted the
same thing, so the redundant one is gone.

* Studio: a cd in a conditional position moves the directory

`if cd ../..; then sqlite3 auth/auth.db ...; fi` runs the move as the
condition itself, and a brace group is another command position, but only
then/do/else were recognised. Those moves went unrecorded, so the later
relative path was resolved against the stale sandbox directory. Both the walk
and the cd-into-the-root rule now also accept if, elif, while, until and an
opening brace.

* Studio: a terminator anywhere ends a streamed credential

The live-stream hold-back looked for a terminator only at the ends of the text
after a credential prefix, so a chunk like `sk-unsloth-<key> done` read as a
token still open and was held back whole, along with every chunk after it,
until the tool finished. A tool that keeps producing such chunks then emits no
tool_output at all. A terminator anywhere after the token ends it, so the
redacted text is released at once; a token still open at the end of a chunk is
still carried.

* Studio: a subshell cd dies with the subshell, and only os moves the process

Two over-blocks. A cd inside `( ... )` or `$( ... )` was carried through the
rest of the command, so `(cd ../..; ls models); cat auth/config.json` refused a
read that runs where it started; the move now stops at the closing bracket
while everything inside it still counts. And a `.chdir` method was taken as a
process directory change whatever the receiver, so `ftp.chdir('../..')`
followed by a local read was refused; only os and contextlib, under their own
names or an import alias, move this process.

* Studio: quoted brackets are not subshells, and a child runs from its cwd

`echo '('; cd ../..; echo ')'; strings auth/auth.db` opens no subshell, but
the bracket scan counted the quoted pair as syntax and ended a subshell that
was never entered, dropping the real cd between them. Brackets inside quotes
are now skipped, escapes included.

And `subprocess.run(["strings", "auth/auth.db"], cwd = "../..")` moves nothing
in this process, so every literal argument was tested against the sandbox
rather than against the directory the child opens them from. A call that hands
a child a directory now resolves its own arguments there, with the same parent
walk resolution used elsewhere.

* Studio: a backslash is an escape as well as a separator

On POSIX bash drops the backslash and opens auth/auth.db, but the join that
resolves a path against the directory a cd moved into read the backslash as a
separator and produced au/th/auth.db, which names nothing. Both spellings are
now tried, because the same character really is the separator on Windows, so
neither platform's reading is lost.

* Studio: an alias of somebody else's chdir is not os.chdir

`move = ftp.chdir` registered move as a process directory change, so a later
local read of a project's own auth/config.json was refused for a move that
happened on a remote server. An attribute alias now has to come from a module
that owns this process's directory, and a from-import alias is taken from
contextlib as well as os.

* Studio: a cwd keyword is not a child process, and a scoped chdir restores

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

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

* Studio: resolve the import alias before deciding a call starts a process

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

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

* Studio: expand the cd target, and follow a renamed process import

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

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

* Studio: a snippet's own run is not a process, and a quoted substitution is a subshell

* Studio: carry a subshell move to its next command, and ignore an uncalled chdir

* Studio: let a wildcard reach the glob analysis without a literal hint

* Studio: fchdir is a move with an unknown target, and a local chdir is not one

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

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

* Studio: a reserved word before cd still moves, and an uncalled function body does not

* Studio: assignment words before cd do not stop it moving

* Studio: a singleton class is its literal, and an escaped builtin is still that builtin

* Studio: a chdir to the studio home variable is a move to the studio home

* Studio: a child's cwd from the home variable, and a directory descriptor used for a relative open

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

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

* Studio: a class body runs when the class statement does

* Studio: an invoked lambda moves, and the platform os module is the same chdir

* Studio: stop refusing ordinary directory work, catch root enumeration, and drive the real entry points in tests

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

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

* Fix/adjust recursive reads of the studio root for PR unslothai#10895

* Fix/adjust definition-time calls and shell-local studio home for PR unslothai#10895

* Fix/adjust the case-sensitivity fixture for Windows for PR unslothai#10895

* Fix/adjust 7z recursing without a flag for PR unslothai#10895

* Fix/adjust root case preservation and foreign home variables for PR unslothai#10895

* Fix/adjust assignment order when expanding the studio home for PR unslothai#10895

* Fix/adjust prefix assignments and dynamic environment attribution for PR unslothai#10895

* Studio: a bare cd returns to the sandbox, and every home variable is checked before the expansion

* Fix/adjust getcwd walks and foreign studio home values for PR unslothai#10895

* Fix/adjust windows path spellings in the root markers for PR unslothai#10895

* Fix/adjust recursive-walk detection to command position for PR unslothai#10895

* Slim the guard tests onto one fixture for PR unslothai#10895

* Skip the lexer pass when no walker is named for PR unslothai#10895

* Fix/adjust a trailing dot on a recursive copy source for PR unslothai#10895

* Cover the trailing dot spellings for PR unslothai#10895

* Fix/adjust parser resource failures in the python guard for PR unslothai#10895

* Fix/adjust recursive python copies, Path.home walks and two open secrets for PR unslothai#10895

* Fix/adjust leading whitespace before a directory change for PR unslothai#10895

* Fix/adjust quoted text mistaken for a shell assignment for PR unslothai#10895

* Fix/adjust escaped quotes before trusting a shell assignment for PR unslothai#10895

* Fix/adjust subshell assignments in the credential guard for PR unslothai#10895

* Fix/adjust python walks of the studio root for PR unslothai#10895

* Fix/adjust aliases passed to python walkers for PR unslothai#10895

* Fix/adjust shallow listings in the root walk guard for PR unslothai#10895

* Fix/adjust Windows root matching in the walk guard for PR unslothai#10895

* Fix/adjust Path-wrapped sources and escaped spaces in the root guard for PR unslothai#10895

* Fix/adjust doubled separators in the root naming test for PR unslothai#10895

* Fix/adjust separator styles in the root spellings and memoize them for PR unslothai#10895

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: danielhanchen <[email protected]>
…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>
…nslothai#11021)

* fix(studio): keep recipe workers alive when request threads retire

* [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>
…easurement says it was a no-op (unslothai#10999)

* Windows installers: read the console's virtual terminal support instead of emitting a P/Invoke thunk for it

install.ps1 and studio/setup.ps1 both emitted a reflection-built type declaring
GetStdHandle, GetConsoleMode and SetConsoleMode for one consumer: the ANSI colour
banner. That cluster (a dynamic assembly, a kernel32 P/Invoke, and in setup.ps1 a
hidden child interpreter to gate it) is the densest malicious-looking region in
either script and the only thing behind the one high-severity Sigma rule
VirusTotal reports, and it is decoration.

Windows PowerShell's console host performs that exact sequence at startup and
reports the outcome through $Host.UI.SupportsVirtualTerminal. The pre-flight in
PR unslothai#10984 measured 5.1.26100 attached to a real console: the property answers
True, the native call answers True, and the console mode read before touching it
is already 0x7, so the SetConsoleMode was re-setting a bit the host had set. The
property is also the stricter of the two, because TryTurnOnVirtualTerminal
re-reads the mode after setting it while the deleted code trusted SetConsoleMode's
return value.

The redirected case is unchanged and still decided first, by
$script:StudioStdoutRedirected, before the property is read, so the Tauri pipe
path and the CLI are untouched.

The emit apparatus itself stays in both files. setup.ps1's
Get-NvidiaLibraryProbeType emits the nvml and nvcuda imports through the same
gate, so its coverage in
tests/python/test_windows_installer_native_type_fallback.py stays parametrised
over both scripts; only the console-helper test is install-only.

Rebuilt as one commit on current main.

* [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>
…thai#10805 actually reports (unslothai#10994)

* Ask AMSI whether the installer compiles, which is the mechanism unslothai#10805 actually reports

The reporter in unslothai#10805 was not running install.ps1 and watching it misbehave. The script was refused
before its first statement ran, because PowerShell hands a script block to AMSI at COMPILE time. Not
one of the six hardening passes since has measured that, so none can be shown to have fixed it.

`[scriptblock]::Create` on the file's text reproduces that exact path with none of an install's side
effects: no download, no venv, no registry, no shortcut. Nothing is invoked, only compiled, which is
what makes running it on every candidate cheap and safe -- unlike the two-full-installs lane in
windows-installer-differential-ci.yml.

Under **Windows PowerShell 5.1** specifically. That is what install.rs spawns (install.rs:433-440),
what a clean Windows box ships and what the reporter ran; pwsh 7 is a different host with a different
AMSI integration, so its answer does not transfer. `RemoteSigned`, not a relaxed policy -- using
Bypass in the lane built to remove Bypass would be absurd.

The second half scans the same files with Defender's on-demand scanner, each copy stamped with
`Zone.Identifier` `ZoneId=3` first so block-at-first-sight consults the cloud rather than treating a
local file as trusted. A zero-prevalence script from the Internet zone is what the reporter had, and
it is the condition the heuristics are harshest under.

Both halves are differential. "install.ps1 compiles fine" is close to meaningless alone; "the merge
base compiles and the candidate does not" is a finding, and so is the reverse.

## Every verdict is gated on a positive control

  AMSI      Microsoft's documented test sample, assembled from fragments, submitted through the SAME
            code path in the SAME process as each measurement. One file per probe invocation exists
            for that reason: a control in a sibling process only shares a host configuration, which
            is a weaker claim than it looks.
  Defender  EICAR, assembled from fragments, through the same MpCmdRun invocation, with the
            quarantined-on-write case treated as the control firing.

If a control does not fire the lane reports that it could not measure and passes with a warning. It
never reports clean. That is not theoretical: release-desktop.yml's own comments record three
releases that shipped unscanned while their scan step was green, because a runner whose scanner is
not live looks exactly like a clean one. On hosted images that is the expected outcome more often
than not -- real-time protection off, passive mode forced, both drive roots excluded -- and this lane
deliberately does not spend the ~180 lines release-desktop.yml spends undoing it. The control decides.

## Fidelity

The base and head copies are written through `[System.IO.File]::WriteAllText` with a BOM-less
encoder, not `Set-Content`. install.ps1 is LF-only with no BOM; Set-Content rewrites every line
ending to CRLF and on 5.1 prepends a BOM, so the scanner would be handed a file this project never
serves and a verdict on it would not transfer to the one users get. A test pins both properties of
the shipped file, and names `.gitattributes` and the HashMismatch hazard as what to check first if it
ever fails.

Matching is on `FullyQualifiedErrorId`, never on message text, which is localised -- install.rs
already makes that distinction. `ScriptContainedMaliciousContent` and `ScriptHasAdminBlockedContent`
are kept separate because a signature match can be cleared with a vendor and an administrative policy
block cannot, and that difference is the only thing that tells a user what to do.

A syntax error is never reported as a scanner verdict. Conflating them would let a broken candidate
masquerade as a detection, or worse, the reverse.

## Not a required check

Definitions change daily and outside our control, so a required check that a Microsoft definition
push can turn red is a release-blocking hazard. The daily scheduled run exists to notice a new
signature that starts matching an unchanged tree, which is otherwise invisible until a user reports
it. Engine and definition version are recorded on every run: a verdict without them is not
reproducible, and a re-detection after a definition bump is a different event from one on the same
definitions.

## What it cannot answer

Nothing about Skyhigh, Bitdefender or Kaspersky, which are the products that have actually flagged
us. No hosted runner has them, and a Defender verdict is not a proxy for another vendor's. The last
step of the job says that out loud on every run, pass or fail, because a run whose summary is only
"green" teaches the next reader that the lane proves more than it does.

## Verification

- 600 passed, 6 skipped across `tests/security/`, including 12 new guards.
- The probe was run for real on this host, where no AMSI provider exists. That is the entire
  unmeasured path, and it must produce well-formed JSON saying so rather than crash -- otherwise a
  genuinely absent scanner is reported as a broken lane. A test performs that run.
- The probe is asserted to compile and never invoke. It is handed the real installer, from a base
  commit nobody reviewed for the purpose, so an `Invoke-Expression` creeping in would run a full
  install inside a measurement step.
- Both the AMSI sample and EICAR are asserted to be split across string fragments, so this repository
  is not itself a sample of either. That is the same self-inflicted detection class as the two
  fixture archives that made Panda flag the GitHub zip.
- One defect found and fixed while smoke-running: in `-File` mode the argument binder does not split
  a comma-separated value into an array, so a list of paths arrived as one string and the probe
  reported "file not found" for files that exist. 5.1 has to be invoked with `-File`, so this would
  have been silent on the only interpreter that matters.

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

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

* Stamp mark-of-the-web the documented way, and say so when the stamp fails

The lane wrote the Zone.Identifier stream by appending it to -LiteralPath:

    Set-Content -LiteralPath "$($file.FullName):Zone.Identifier" ... -ErrorAction SilentlyContinue

PowerShell documents exactly one way to address an alternate data stream -- the -Stream parameter --
and -LiteralPath is specified as taking the path "exactly as typed". This repo's own working code
does it correctly at release-desktop.yml:1470.

The failure shape is what makes this worth fixing rather than tidying. If the suffix form does not
bind, the -ErrorAction SilentlyContinue sitting next to it swallows the error: the mark is never
applied, block-at-first-sight never consults the cloud, the scan runs against a MyComputer-zone file,
and the step still prints "clean". A silent downgrade of the exact condition the step exists to
create, reported as the result it was supposed to prove.

Now -Stream with -ErrorAction Stop in a try/catch, and a failed stamp is announced twice: once with
the exception, once as a warning that the file was scanned WITHOUT mark-of-the-web. A weaker scan
than the lane claims to run is fine; a reader not knowing which one they got is not.

A guard pins all three properties. It strips comment lines before applying the ban, because the
comment above the fixed code has to name the broken form to explain it -- a substring search over
the raw file matches its own explanation. That has now caught me three times in this series of
guards, which is a good argument for never grepping a file for a string its own prose is obliged to
contain.

* Start pwsh through the shared runner, as every other test in this repo does

tests/studio/test_pwsh_calls_use_the_shared_runner.py bans a direct subprocess call to pwsh, and this
file had two. The reason is not tidiness: a direct call shares one $XDG_CACHE_HOME/powershell startup
cache with every other xdist worker, and pwsh dying at startup (PowerShell/PowerShell#24461, 'Stack
overflow.' then SIGABRT) renders as CalledProcessError carrying the whole script -- so an interpreter
crash reads exactly like the script under test having failed. Backend CI run 32341628757 lost 284
tests across 19 files to precisely that, and every one looked like a Windows-installer regression.

run_pwsh takes the argv the call site already built, so this is a one-word change per site and no
invocation flags move.

Worth noting how this was caught, because it says something about the method: this guard lives in
tests/studio/ and never ran against this branch in isolation. It only fired when all ten open PRs
were merged together into one tree and the full suite run against that -- 13,153 passed, and this was
one of two failures that exist in no single branch.

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

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

* Refuse a clean verdict for anything this lane did not actually measure

Three ways the lane could publish clean without having measured the head side:

A candidate that failed to compile for a reason unrelated to a scanner came back with an
errorId and blocked=false. The verdict loop only collected blocked results, so the row was
dropped and, with nothing else blocked, the lane reported clean. A script that does not parse
is now its own verdict and fails the job, because AMSI never got to judge it either.

MpCmdRun's exit code was never read. A scan that did not run produces no threat text, so $hit
was false and the row printed clean. Capture $LASTEXITCODE immediately and treat a non-zero
exit with no match as unscanned, which is the contract release-desktop.yml:1472-1489 already
uses for the same tool.

The AMSI control was a single job-wide flag. -Control runs in the same process as the file it
vouches for, so a live base invocation followed by a head invocation where no provider loaded
let the head answer borrow credibility it had not earned. The control is now a property of the
row, and a row whose own control stayed silent is unmeasured.

A probe that wrote no result file also just vanished from the set, which is the same
false-clean by subtraction, so it is recorded instead.

Eight simulations drive the real verdict logic, extracted from the workflow by step id so it
cannot drift from what CI runs. Six of the eight fail against the previous revision.

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

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

* Assign causality per script, and say what a broken verdict means

Whether a block is introduced or pre-existing was decided by comparing counts across the two
sides. That called an install.ps1 block pre-existing whenever the base had a block on any file at
all, setup.ps1 included, and called it introduced whenever the base had none, including when the
base row for that same script was never validly measured. Both send a reader to the wrong commit.
Causality is now looked up per script name against a base row that has to be valid, and an
invalid or absent base row says so instead of guessing.

The summary switch also had no case for the verdict the previous commit introduced, so a
candidate that failed to compile was reported as the probe not completing, which is the opposite
of what happened: the probe ran and gave a definite answer. The unmeasured wording was likewise
still claiming a dead provider is the only way to get there, which stopped being true once a
silent per-row control, an unreadable file and a missing result file all led here.

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

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

* Report a real refusal before a coverage gap, and say when Defender could not reach the cloud

Two ordering defects, both introduced by the previous commit in this PR.

The unmeasured check returned before the blocked list was ever evaluated, so a script a live
provider genuinely refused went unreported whenever some other invocation happened to write no
result, and the job stayed green on a real detection. Incomplete coverage is a warning; it is not
a reason to stop looking at what was found.

The per-row control gated every classification, including parse errors. A parse error is a
property of the script rather than of the scanner, since the compiler rejects it whether or not a
provider is listening, so a broken candidate in a process whose control stayed silent was filed as
unmeasured and exited zero. Only the BLOCKED verdict actually depends on a live provider, and it
still requires one.

Separately, EICAR proves the local engine scans and nothing more. This lane stamps mark-of-the-web
on every candidate so block-at-first-sight consults the cloud, which is the condition a
zero-prevalence script is judged under and the one the report was made under, and with MAPS off
that half is simply absent while an exit-0 scan still reads as clean. release-desktop.yml:1290-1343
verifies MAPS separately for the same reason. This lane is the cheap one and does not repair the
configuration, so it checks and labels: a clean result that could not reach the cloud now says it
is local signatures only.

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

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

* Copy the blob, decide compile failures before the control gate, and require block-at-first-sight

The base and head copies were reconstructed from git show captured as
PowerShell text, so CRLF became LF, a byte outside UTF-8 became the
replacement character, trailing blank lines collapsed and a final newline
appeared. The lane promises to scan what ships, so stream the blob
instead. Demonstrated on a blob carrying all three properties.

Whether a script compiles does not depend on AMSI, but the compile
verdict sat after the gate that reports a scanner-less runner as
unmeasured, so a candidate with a syntax error there exited zero.

Cloud readiness checked MAPS reporting and connectivity only, then said
block-at-first-sight could act. With DisableBlockAtFirstSeen set it
cannot, and release-desktop.yml already treats that as fatal.

* Apply the kwarg-spacing formatter to the tests added in this branch

* Reject a malformed probe result, and report blocks alongside a parse failure

The step runs with Continue, so an existing but truncated result file
made ConvertFrom-Json return nothing and the row went in with a null
payload. Such a row iterates no results, so the file left the measured
set without being counted as unmeasured, and another process whose
control fired carried the job to clean. Parse under Stop, check the
shape, and route failures into the no-result list.

Moving the compile verdict ahead of the control gate also put it ahead of
the point where the blocks were derived, so a refusal by a live provider
went unreported whenever another script failed to parse. Derive both
first and print both.

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

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

* Scan the EICAR control with the candidate flags, and exempt the copies from on-access scanning

The control ran without -DisableRemediation while the candidates ran with
it. That flag also makes the explicit scan ignore file exclusions, which
this repository's release scanner records, and the hosted images ship
with both drive roots excluded, so the control scan could be skipped
while the candidate scans worked and the step exited having measured
nothing.

Real-time protection also acts on open and on write, and
-DisableRemediation governs only the explicit scan, so a live provider
could quarantine a laid-out copy mid-stamp and turn a detection into a
missing file. Exempt the directory holding them, which does not weaken
the verdict because the explicit scan ignores exclusions.

* Apply the kwarg-spacing formatter

* Establish the on-access exclusion before the copies are written

Excluding the directory in the Defender step left both earlier steps
exposed: the layout step writes every copy and the AMSI step opens them,
and real-time protection acts on open and on write while
-DisableRemediation governs only the explicit scan. A quarantined copy
then vanishes from the later enumerations and another valid row can carry
both halves to clean. Move it into its own step ahead of the layout, and
read the preference back, because Add-MpPreference is non-terminating
here and a refusal otherwise looks exactly like success.

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

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

* Measure the set that was laid out, not the files that survived

Both loops enumerated the laid-out directory, so a copy quarantined by
real-time protection before they ran left the set entirely: it became
neither an unmeasured row nor a detection, and a surviving sibling could
carry the job to a clean verdict. That is reachable whenever
Add-MpPreference is refused, which the previous commit made visible but
could not prevent. The layout step now records what it wrote and both
loops read that, reporting anything absent into their own verdict.

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

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

* Decode the candidate as UTF-8, and stop claiming block-at-first-sight

Windows PowerShell 5.1 reads a BOM-less file as ANSI and the shipped
installers are BOM-less UTF-8, so Get-Content handed AMSI a mojibake
version of any non-ASCII text. That is the one host this probe exists to
reproduce, and it is also not what irm | iex does.

The on-access exclusion that keeps a detection from quarantining the
evidence also removes the path block-at-first-sight needs: it consults
the cloud only on an on-access open, which this lane never performs. What
the mark of the web plus MAPS buys is an on-demand cloud scan, which is
what the low-prevalence verdicts still reach, so say that instead.

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

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

* Read the AMSI error id off the inner parse error

Calling a .NET static method from PowerShell wraps whatever it threw in a
MethodInvocationException, so the outer FullyQualifiedErrorId is the
generic ParseException regardless of why the parse failed. The id that
separates a scanner refusal from an ordinary syntax error is on the inner
ParseException's Errors collection. Verified by execution: a deliberate
syntax error gives outer ParseException and inner
IfStatementMissingCondition.

Matching the outer id alone meant ScriptContainedMaliciousContent was
never recognised, so not even the positive control could fire and the
lane could only ever report that it had not measured. Walk the exception
chain and record every id found.

* Assert the committed blob has no CRLF, not the working tree

A Windows checkout with the default core.autocrlf=true rewrites
install.ps1 to CRLF on disk, because .gitattributes carries no *.ps1
rule, so this failed on Windows runners while the bytes the project
serves were unchanged. Found by the cross-platform staging run. The lane
copies blobs out of git precisely so the checkout cannot matter, and the
assertion now looks where the lane looks.

* Assign Defender causality per script, the way the AMSI half does

The Defender verdict kept only head-side results, so a signature that already
flags the merge base read exactly like a regression this change introduced, and
a base-only detection read as a plain clean head rather than the improvement it
is. Per-script base state is now recorded and consulted, with a vanished copy
keyed as unmeasured rather than absent.

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

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

* Never infer a fired EICAR control from an exception

The catch around the control write and scan set the control live and printed that
real-time protection blocked the file. A permission or I/O failure under
RUNNER_TEMP, or MpCmdRun failing to launch, took the same path, and every
candidate result after it was then trusted, so an unavailable scanner reporting
no hit could be reported as clean. That is the exact condition this control
exists to catch.

The write and the scan are now separate, and the control is only declared live on
an observation: the control file is gone. Anything else says what failed and
leaves the control unfired.

* Attribute the EICAR control to Defender, and decide cloud readiness on MAPS

Two corrections to the Defender half.

The control accepted absence as a block. This step runs with
ErrorActionPreference Continue, so a non-terminating Set-Content failure did not
even raise and fell straight through to treating the missing file as quarantine;
an ACL, a full disk or a transient I/O error could satisfy the control with no
scanner running. Both writes are terminating now, existence is observed rather
than assumed, and a benign file of the same size is written the same way into the
same directory first. Absence of the EICAR file is only read as Defender when
that identical write succeeded; if the directory is not writable the half reports
no positive control and measures nothing.

Cloud readiness no longer gates on DisableBlockAtFirstSeen. That was right while
the step claimed block-at-first-sight had acted on the mark of the web, and wrong
once it was corrected to say what it does: block-at-first-sight only consults the
cloud on an on-access open, and this lane never opens the copies. Gating on it
labelled a runner whose cloud the on-demand scan can reach as local signatures
only. The preference is still read and still printed alongside the verdict.

* Fire the control through the command the candidates are read with, and let a missing manifest reach the verdict

The candidates sit in a directory exempted from on-access scanning and are
measured only by the explicit MpCmdRun scan, so a control that fired by being
quarantined on write proved a provider was live and proved nothing about that
command: an on-demand scanner that silently skipped files would still have been
trusted. The control now lives inside the same exempt root, survives its write,
and is fired by the scan output alone. A control removed before the scan reads it
says the measurement path is unproven rather than counting as a pass.

Separately, when the layout manifest is missing both halves fell back to
enumerating survivors, which cannot notice that an expected candidate is absent,
so a quarantined copy left its siblings to carry the run to a clean verdict. That
condition is now recorded and reaches noResult and unscanned.

* [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>
…i#10974)

Group Data settings controls and add searchable, localized chat and media archives. Preserve bulk selection and deletion scope, refresh galleries once per restore batch, and retain visible thumbnails during filtering and sorting.
…stead of arguing that it does not (unslothai#10992)

* Windows: a base vs head installer differential, so a hardening change has to prove it changed nothing

The claim every antivirus-shape change in this series rests on is that the
installer still does exactly what it did. Nothing measured that. This lane runs
install.ps1 to completion twice on windows-latest, once from the merge base and
once from the candidate, and compares four contracts:

- the transcript, first run and reinstall, so a change to what a user sees fails
- the shortcut manifest, every field of the launch contract including the
  description install.ps1 reads back when it decides whether a shortcut is
  already correct
- the generated launch-studio.ps1 and unsloth.cmd, by content, encoding and
  location
- idempotency, by running the installer a second time and requiring it to write
  nothing

The design rule throughout is that unmeasured is not passed. Both legs are
produced by the same collector, so malformed evidence is symmetric and compares
equal to itself, and every check is written for that: an empty shortcut object, a
content contract with no captured content, a manifest of the wrong shape, an
installer that exited non-zero, an unmeasured idempotency run and an unknown
expected set are all VOID rather than agreement. The comparer carries a positive
control it must call different and a pair it must call equal, because a differ
that reports no differences looks the same whether it is working or broken.

Normalisation is deliberately narrow. Console output and generated files get
different rules: a port, a size or an elapsed time is noise in a transcript and
content in a launcher. Only values that genuinely vary between two installs of two
commits are erased, and the one rule that can reach a deliberate change, the
version normaliser, prints what it erased.

Two full installs per run, so a pull request opts in with the
installer-differential label, the label event is scoped so an unrelated label
cannot cancel a measurement in flight, and a weekly run keeps the lane known to
work before it is relied on to judge anything.

No shipped file is touched: two CI scripts, one workflow and its tests.

* [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>
…unslothai#10439)

* feat(studio): accept OpenAI-style video_url content parts on /v1/chat/completions

A `{"type": "video_url", "video_url": {"url": ...}}` part inside `messages[].content` was rejected by the request schema before any backend ran, and the error named the string branch of the content union ("Input should be a valid string") rather than the unknown part type. Clients following the OpenAI / DashScope vision shape could not send a clip at all, on the MLX and GGUF paths alike.

The part now rides the same pipeline as the top-level `video_base64` field. Every gate that read that field reads one predicate covering both spellings: the external-provider refusal, the pre-switch modality label and size check, the non-GGUF refusal, the guided-decoding and client-tools refusal, the llama-server video capability gate, and token counting. On the GGUF branch the parts are rewritten in place as llama-server's `input_video` (a data URI as its payload, a remote URL forwarded for llama-server to fetch, as remote `image_url` parts already are), at the point the legacy clip is injected.

The preview route refuses a clip in its preflight, beside the unsupported-part check already there: a preview target is a training checkpoint on the non-GGUF backend, so the refusal the completion handler would raise came only after a load that evicts the resident model. A clip on any non-user message is refused at validation: OpenAI places media on user turns only, and llama-server renders the marker into whichever turn carried it, so anywhere else the outcome is template-dependent. KV admission compacts a `video_url` part the way it compacts an image and charges a remote clip at llama-server's own download ceiling; the rolling context window leaves the part unpriced.

Fixes unslothai#10389

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

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

* Tighten the video comments and docstrings for PR unslothai#10439

Comment and docstring only. Verified by comparing docstring-stripped ASTs against
the previous commit: routes/inference.py, models/inference.py, routes/preview.py
and the behaviour suite are all identical, so no code changed. 1126 tests pass.

* Drop the em dash from the VideoUrl docstring for PR unslothai#10439

* Keep a video_url part out of durable chat runs

The durable-run media gate is field-shaped: it reads image_base64, audio_base64 and
video_base64 plus _messages_have_input_audio. A clip carried as a video_url part passed
it and its data URI was persisted verbatim into request_json, which is the blob the gate
exists to prevent. Read it through _request_has_video so both spellings are caught.

An image_url part slips the same gate and is left alone here: it predates this branch and
refusing it now would break durable runs that work today. Tracked in unslothai#10983.

* Reduce comment lines on the video path

Opening comment-reduction pass. Section banners deleted outright, multi-line blocks
collapsed where the extra lines carried no distinct fact. Comment lines added by this
branch: 46 to 30. Survivors each name something the code does not state, mostly
llama.cpp handle_media behaviour.

Comments and docstrings only, AST-verified against 0793d39.

* Refuse a second clip on a non-GGUF backend instead of dropping it

_local_video_clip took clips[0], so a request carrying two video_url parts, or the legacy
field beside a part, silently lost every clip after the first while still answering 200.
GGUF forwards all of them, so the same request meant two different things depending on
which backend happened to be resident.

Generation takes a single video kwarg, so there is nothing to forward the rest to. Refuse
the request by name rather than quietly changing the prompt.

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

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

* Lowercase the scheme on a remote video URL before forwarding it

handle_media classifies remote media with a case-sensitive string_starts_with(url, "http")
and applies no normalisation, so HTTPS://host/clip.mp4 fell through to its raw-base64 branch
and the completion failed instead of fetching the clip. _is_remote_video classified it
correctly, which made this invisible: the request was routed as remote and then forwarded in
a spelling llama-server does not recognise.

Only the scheme is lowercased. RFC 3986 makes the scheme case-insensitive; the path is not,
and folding it would 404 on any host serving case-sensitive paths.

Two tests asserted the old spelling, so both are updated: they pinned a wire shape that
cannot work downstream.

* Fix admission recosting of translated video parts and scheme rejection on the non-GGUF path for PR unslothai#10439

* Refuse remote video URLs aimed at non-public hosts for PR unslothai#10439

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

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

* Refuse legacy numeric loopback forms and malformed remote video URLs for PR unslothai#10439

* Refuse remote video hosts that resolve to non-public addresses for PR unslothai#10439

* Treat an invalid port in a remote video URL as a client error for PR unslothai#10439

* Refuse remote video URLs outright for PR unslothai#10439

* Refuse a clip on an older turn off GGUF and document video_url as inline-only for PR unslothai#10439

* Validate a clip's size without copying its payload for PR unslothai#10439

* Apply repo formatting and drop a duplicate import for PR unslothai#10439

* Bound aggregate video work, recost from the live conversation, and unblock the loggers stub for PR unslothai#10439

* Stop double-charging the legacy clip during recost and skip a Windows-illegal path test for PR unslothai#10439

* Cap video clip count and retarget the frame-budget tests at the helper for PR unslothai#10439

---------

Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…#10980)

Add queue steering and reordering controls, composer preferences, and draft preview. Preserve explicit model selections during local loading and prevent row controls from submitting unsent drafts.
Add reasoning budget and exhaustion-message controls for llama.cpp models, including persistence, status reporting and runtime capability validation. Preserve inherited launch intent through settings, presets and resident-model reuse.
… repo-root pytest runs (unslothai#11028)

84 test files stub `loggers` with a bare `ModuleType`, which has no `__path__` and so is not a package. Once one wins the slot, `from loggers.media_progress import ...` (routes/inference.py, at module level) dies with "'loggers' is not a package". It only bites when pytest is invoked from the repo root, which is why the repo's own CI, run from studio/backend, never saw it.

Reproduced before and after: without the preload, collecting a stub-first file ahead of an inference-routes file from the repo root gives 1 collection error; with it, 59 tests collect.

The preload is conditional. `loggers.handlers` imports structlog, and some tests stub structlog to stay runnable without it; where it is missing, the import this protects would die on structlog anyway. With structlog hidden, test_model_picker_regression.py still collects 38 tests.

The `__path__` assertion keeps the import used, so scripts/verify_import_hoist.py keeps its rename-clash signal on this file rather than having it suppressed, and it upgrades the failure mode: a stub winning the slot now stops collection naming the cause instead of dying twelve frames deep.
…t cannot load (unslothai#8642)

* Studio: report a torchcodec that installed but cannot load

pyproject declares torchcodec on linux and win32, and notebook_validator enforces
a torch/torchcodec compatibility matrix for it, but its wheel is Python-side only:
at import it dlopens FFmpeg's avcodec/avutil. Windows ships neither, and pip has
no FFmpeg wheel to depend on, so the package installs, reports a version, passes
the matrix, and then fails at import.

datasets 4.x decodes audio only through torchcodec and reports that failure as
"To support decoding audio data, please install 'torchcodec'" -- naming a package
that is already installed, on a host where the problem is FFmpeg. Nothing between
the install and that message says otherwise.

Both installers now probe the import once deps are in and say what they found. The
message names FFmpeg, says decoding falls back to soundfile, and gives that
fallback's real coverage (wav/flac/mp3/ogg via libsndfile, not m4a/aac/webm), so
it reads as a limitation rather than as audio being broken. An absent torchcodec
stays silent: that says nothing about FFmpeg, and the soundfile path still stands.

Reporting only. Vendoring an FFmpeg full-shared build would mean redistributing an
LGPL/GPL binary per arch, with its own update path, to reach formats most speech
datasets do not use. That is a bigger decision than this gap needs.

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

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

* Address review: bound the probe, gate llama-only, classify the failure

- setup.sh read _SKIP_PYTHON_DEPS outside the base install that assigns it, so
  UNSLOTH_STUDIO_LLAMA_ONLY=1 aborted the run under `set -u`. Gate on _LLAMA_ONLY
  as well: that path installs no Python deps, so there is nothing new to report.
  The read is defaulted too, so a later edit cannot reintroduce the unbound case.

- Importing torchcodec imports torch, so bound both probes the way this repo
  already bounds torch imports: `timeout 60` in setup.sh, next to the XPU probe
  that does the same, and Invoke-BoundedPythonProbe in setup.ps1.

- Split the unloadable state into ffmpeg and broken. A damaged wheel or a
  torch/torchcodec ABI mismatch also raises at import, and answering that with
  "install an FFmpeg build" sends the reader at the wrong thing. The split is
  between torchcodec's own loader and an unrelated import error; it does not
  claim to pick between the causes that loader lists, which it prints together.

- The missing-package test accepted all three states, so it could never fail.
  It now forces ModuleNotFoundError and requires absent.

The behavioural tests read the probe out of setup.sh rather than carrying a copy
of it, so they exercise what actually ships, and a new test holds the two
installers to the same probe body.

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

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

* Probe the studio venv, not whichever python is on PATH

install.ps1 runs setup.ps1 with SKIP_STUDIO_BASE=1, which skips the base install
the other bare-`python` probes sit in, and nothing puts the venv on PATH. So the
torchcodec probe read the system interpreter, found no torchcodec, and printed
nothing on the path every Windows install actually takes.

* Keep double quotes out of the Windows probe body

Invoke-BoundedPythonProbe builds -c <body> by wrapping the body in double quotes,
so the four in the comment closed that argument early. Windows split the rest into
stray argv entries and python ran the truncated head, which still parses: the
except-Exception branch lost its print, so the probe exited 0 with no output and
the report never fired on Windows.

The comment says the same thing without quoting it, and the pwsh test runs the
shipped helper against the shipped body with an unloadable torchcodec on
PYTHONPATH -- the one case a truncated body answers nothing at all.

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

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

* Bound the probe without timeout, name the missing module, read one line

Three findings from the review on 17ed9e7:

The shell fallback for hosts with no coreutils timeout, stock macOS above all,
ran the import with no deadline. The body now carries signal.alarm(60) like the
XPU probe in this same script; the default action ends the process, which reads
as the silent case. alarm is POSIX-only, and Windows is bounded by the helper.

ModuleNotFoundError from a transitive module reported an installed torchcodec as
absent, so a damaged install got no warning. Only a missing torchcodec itself is
absent now, read off the exception name.

The state was compared against all of stdout, so any banner ahead of the answer
matched no arm and dropped the report. Both installers now read a TORCHCODEC=
line, sed in setup.sh and a line-anchored match in setup.ps1.

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

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

* Only the top-level torchcodec miss is absent

A damaged wheel that fails on one of torchcodec's own submodules raises
ModuleNotFoundError naming torchcodec.<sub>, and folding that back to the
top-level name reported an installed-but-broken package as absent, which is
silent. An absent package always names itself exactly from import torchcodec,
so the exact comparison loses nothing and treats torchcodec.* as broken.

The test asserting the submodule form was absent was wrong; it now expects
broken.

* Only blame FFmpeg when FFmpeg is actually missing

The loader message names a missing FFmpeg, a torch mismatch and another native
dependency in one breath, so matching libtorchcodec in the traceback sent every
one of them to install FFmpeg. Documenting that limit in a comment was not
enough: the probe now asks the system instead, through find_library plus a PATH
walk for the versioned avutil-*.dll names Windows uses and find_library cannot
glob.

No FFmpeg on the loader path keeps the ffmpeg state and its advice. FFmpeg
present with the loader still failing is a new native state, which names the two
remaining causes without picking between them, since nothing available here can.

The tests pin the FFmpeg answer in both directions, so a runner that happens to
have it installed cannot flip the states this rests on.

* Merge main into fix/report-torchcodec-cannot-load and stop the pwsh probe test depending on host FFmpeg

* Require every FFmpeg library before calling FFmpeg present, and test the real guard

_ffmpeg_on_loader_path answered yes when ANY of avutil, avcodec or avformat was
found. Distros package the three separately and torchcodec dlopens all of them,
so a host carrying only libavutil was told FFmpeg was already on the loader path
and sent to debug a torch ABI mismatch, when the fix is the rest of FFmpeg. Check
each library, keeping the versioned-DLL glob per name so Windows is unaffected.

test_the_probe_is_skipped_when_python_deps_were_skipped searched backwards from
the probe for the skip variable, which found the assignment hundreds of lines
earlier and passed even with the guard deleted. Inspect the enclosing condition,
as the llama-only test alongside it already does.

* Name every cause the native-load state can have, with the right FFmpeg range

The native message listed an unsupported FFmpeg major or a torch mismatch, and
gave the range as 4 to 7. unsloth/import_fixes.py:2664 says 4 through 8, so an
FFmpeg 8 user was pointed at a downgrade that fixes nothing.

A missing CUDA NPP runtime lands in the same aggregate libtorchcodec error:
_cuda_major_for_npp records a +cu128 host that skipped NPP and then could not
import the codec. Naming a subset of the causes reads as a diagnosis and sends
people to rule out the wrong thing, so name all three.

* Check every FFmpeg library torchcodec links, not the first three

The check covered avutil, avcodec and avformat. torchcodec links seven. Read
from the shipped libtorchcodec_core*.so NEEDED entries:

  libavutil libavcodec libavformat libavdevice libavfilter libswscale libswresample

Distros package these separately, so a host missing only libswscale has an
FFmpeg that cannot load the codec, and the probe called it present and sent the
user to debug a torch ABI mismatch instead of installing the rest of FFmpeg.

Both installers, and the parity test now asserts each of the seven by name so
the two copies cannot drift or quietly shrink back to a subset.

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

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

* Run the torchcodec probe with the venv interpreter, as setup.ps1 already does

setup.sh activates the venv at line 1786, but the uv installer branch prepends
$HOME/.local/bin to PATH afterwards, so a pyenv, pipx or asdf python shim there
shadows the venv from that point on. The probe then imports torchcodec into the
wrong interpreter and answers a silent "absent" for an install that has it.
Name $VENV_DIR/bin/python when it exists, and keep bare python only where no
venv exists (Colab installs into the system interpreter). The PowerShell probe
already names $VenvDir for the same reason; add the matching test on the sh side.

* Spawn the probe under test with sys.executable, not a bare python

Seven tests ran the probe body through ["python", "-c", ...]. On a host whose
PATH has only python3 (Debian without python-is-python3, the self-hosted AMD
runners) subprocess raises FileNotFoundError before the probe runs, so the file
failed on real hardware for a reason unrelated to the change. The installers
name the venv interpreter by path; the tests now do the same through
sys.executable.

* Tighten the comments this change adds and drop a stray setup.sh.orig for PR unslothai#8642

* Skip the bash syntax test when bash is the WSL stub for PR unslothai#8642

* Count Windows FFmpeg DLLs on PATH only on Windows for PR unslothai#8642

* Mark torchcodec unusable on any import failure, as the probe promises for PR unslothai#8642

* Probe torchcodec on the fast update path when a venv exists for PR unslothai#8642

* Test the venv path literally in the fast-path probe guard for PR unslothai#8642

* Count versioned FFmpeg libraries on the loader path for PR unslothai#8642

* Decode audio datasets through PyAV when torchcodec cannot load, in Studio and the library, for PR unslothai#8642

* Honour Audio stream_index in the PyAV fallback and summarise numpy audio cells in the dataset preview for PR unslothai#8642

* Declare soundfile and PyAV in the audio extras and disable torchcodec on any import failure for PR unslothai#8642

* Raise the Studio PyAV floor to 12.3 for PR unslothai#8642

* Fall back to PyAV resampling when librosa is installed but cannot import for PR unslothai#8642

* Move the torchcodec load probe into import_fixes and load it from both installers for PR unslothai#8642

* Drop the installer probe and report a broken torchcodec from import_fixes instead for PR unslothai#8642

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

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

* Pick the default audio track when no stream_index is set, as torchcodec does, for PR unslothai#8642

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

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

* Write channel-first and Arrow-shaped arrays correctly in the soundfile encoder for PR unslothai#8642

* [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>
Co-authored-by: danielhanchen <[email protected]>
… itself (unslothai#11013)

`main` fails **Frontend build + bundle sanity** with nothing on a branch to blame, and has been bought back twice in one day: unslothai#10974 added 10,000 bytes and did not survive a single merge, and the next raise added 10,000 more. Each leaves a few kilobytes, which is one locale string, and the next PR to cross it pays for drift it did not cause.

Both halves move together to the headroom the earlier raise chose, which is what the note beside it asked for:

- `rawBytes` to 5,730,000
- `transferBytes` to 1,715,000

Verified on a real runner rather than only locally. The staging run of this branch reports:

```
eager startup JS: 5394.1 KB raw, 1612.3 KB transfer, 84 chunks
within budget (62.5 KB transfer, 201.6 KB raw to spare)
```

Nothing became eager. The eager set is still 84 chunks with the same top five (chat, index, chunk-BO2N2NFS, providers-api, katex); the raw total grew inside chunks that were already eager, the locale messages most of all. That is drift, so there is nothing here to lazy-load.

The per-raise ledger in the comment above the constants, which had grown a paragraph per raise, is reduced to the current measurement and the invariant.
…MD) (unslothai#8762)

* Unsloth Studio Installer: name the actual GPU, whichever vendor it is

The GPU line said a different kind of thing per vendor, and on two of the
three it did not say which card:

  gpu            NVIDIA GPU detected          <- no name, ever
  gpu            Intel GPU detected           <- name on the substep below
                 Intel Arc A770
  gpu            AMD ROCm (gfx1200)           <- arch, not a name

Every probe already had the answer. nvidia-smi is resolved and run before
this point and was simply never asked; the shell scripts resolve the AMD
marketing name into $_gpu_disp_mkt / $_setup_mkt for their own name -> arch
inference and never print it; and the backend prints the real name at
startup seconds later:

  Hardware detected: ROCm (HIP 7.13.99004) -- AMD Radeon RX 9060 XT

One shape for all three now: `step "gpu"` is the device, the runtime detail
drops to a substep.

  gpu            NVIDIA GeForce RTX 4090
  gpu            Intel Arc A770
  gpu            AMD Radeon RX 9060 XT (gfx1200)
                 HIP SDK: C:\Program Files\AMD\ROCm\7.1

Each vendor honours its own visible-device mask when picking which card to
name (CUDA_VISIBLE_DEVICES, HIP/ROCR_VISIBLE_DEVICES), so a masked run names
the card it is actually going to use.

On the AMD side the name is kept in its own variable rather than folded into
$ROCmGpuLabel: that one doubles as the input to the name -> arch tables, so
changing its shape would move wheel selection. It is read from hipinfo's
per-device "Name:", amd-smi's Market Name, or the WMI adapter name, always
at the index the arch pick landed on and only when the name and arch lists
line up, so a format change can mislabel nothing and the arch that selects
the wheel is never taken from it.

Also stops setup.ps1 reporting a known ROCm version as unknown. It probed
hipconfig then amd-smi and, on a runtime-only layout with neither on PATH,
printed

  rocm           ROCm (version unknown)

one line after the summary printed C:\Program Files\AMD\ROCm\7.1. The SDK
root is versioned, so that is now the last-resort source.

* Give NVIDIA the same compute target and runtime line as AMD

The first pass unified the device name across vendors but left AMD as the
only one showing what it would actually compile for:

  gpu            NVIDIA GeForce RTX 4090
  gpu            AMD Radeon RX 9060 XT (gfx1200)
                 HIP SDK: C:\Program Files\AMD\ROCm\7.1

compute_cap is the counterpart of the gfx arch, and the driver version the
counterpart of the HIP SDK line. Both come back from the query that already
fetches the name, so this costs no extra call:

  gpu            NVIDIA GeForce RTX 4090 (sm_89)
                 Driver: 550.54.15

The installer was already reading compute_cap, but only inside
Get-NvidiaCu126Verdict, which runs on the cu128/cu130 path to decide a
fallback and returns early otherwise, so it was never available where the
banner is printed.

Fields are split from the right because nvidia-smi does not quote its CSV,
so a comma in a device name would otherwise shift every column. A row with
fewer fields than requested falls back to using the whole row as the name
rather than reporting a driver version that is really a compute capability.

Intel keeps the name alone. There is no counterpart to gfx1200 / sm_89 that
any probe here already resolves, and inventing one to make the column look
even is worse than the gap.

* Installer GPU banner: name the GPU, not the CPU, and keep the probe bounded

Simulated the banner against fake nvidia-smi / rocminfo / amd-smi on a 74-case
matrix (both shell entry points x NVIDIA / AMD / Intel / CPU-only host shapes),
running the merge base and this branch against identical fixtures. Three
problems only showed up once the name was actually printed.

rocminfo enumerates the CPU as Agent 1, and that agent carries its own
"Marketing Name:". Taking the first match in the stream therefore named the
processor: an RX 7900 XTX box read "AMD Ryzen 9 7950X 16-Core Processor
(gfx1100)". On Strix Halo it is worse, because the CPU agent's name is
"AMD RYZEN AI MAX+ 395 w/ Radeon 8060S" -- it contains a Radeon model, so it
reads like a GPU name, and $_setup_mkt also feeds the name -> arch table. The
parse is now per agent and only an agent whose Device Type is GPU can name the
banner. Agents are collected as gfx/name pairs and the banner takes the name
belonging to the arch that was picked, so an iGPU + dGPU host no longer prints
the integrated name against the discrete arch.

The new nvidia-smi query ran unbounded. Every other nvidia-smi call in these
files goes through _run_bounded / _setup_run_smi / Invoke-NvidiaSmiBounded
precisely because a wedged driver blocks nvidia-smi indefinitely; in the matrix
a hung probe took the whole installer down on this branch while the merge base
finished normally. It now uses the bounded runner, and the shell side reuses the
executable the detection helper already resolved into $_nvsmi rather than
re-resolving with `command -v` -- detection also succeeds via /usr/bin/nvidia-smi
off PATH and via /proc/driver/nvidia/gpus with no nvidia-smi at all, and those
hosts would otherwise silently lose the name.

Placeholder rows are no longer treated as device names. An nvidia-smi too old
for compute_cap answers "[N/A]" rather than failing, which printed a GPU called
"[N/A]"; a short row used the whole row, printing "RTX 4090, 8.9". Short rows now
keep field 1 and the placeholders fall back to the old text.

Also on the AMD side: amd-smi spells the field MARKET_NAME in caps, so the
[Mm]arket.?[Nn]ame class matched no real casing and that probe never yielded a
name at all. Matched case-insensitively now, and the rocminfo and amd-smi calls
in install.sh are bounded like their setup.sh counterparts.

In setup.ps1 the device index is carried forward from Resolve-VisibleGpuIndex
instead of being recovered from the arch value. The arch list is deliberately not
deduplicated, so [array]::IndexOf always returned the first occurrence: two
same-arch cards with different SKUs (RX 7900 XTX + PRO W7900) named the first one
even when the mask selected the second. The WMI adapter name is likewise moved
onto the adapter the arch pick landed on, which the mask, the nameArches[0]
borrow and the shadowing repick can all change.

CPU-only and Intel hosts print exactly what they printed before this branch, and
all 21 tests in tests/studio/*.ps1 pass.

* Resolve UUID and MIG GPU masks, and read hipinfo at logical device zero

Three more cases from the review, each reproduced in the fixture matrix before
being changed.

nvidia-smi does not honour CUDA_VISIBLE_DEVICES, so the mask has to be resolved
against its physical rows by hand, and only a numeric token was. A UUID mask
therefore left the index at 0 and named the first card rather than the visible
one. UUIDs are the form NVIDIA recommends over indices, may be abbreviated to
any unique leading portion, and a MIG id (MIG-<GPU-UUID>/<gi>/<ci>) embeds one,
so a non-numeric token is now looked up against --query-gpu=uuid by prefix, with
MIG unwrapped to its parent GPU. A token matching nothing still falls back to
row 0. The lookup runs only on the non-numeric path, so the ordinary case costs
no extra call and the CSV parse keeps its three documented columns.

hipinfo is itself a HIP application, so HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES
have already filtered its output and renumbered the survivors from zero.
install.ps1 indexed that output by the physical token as well, applying the mask
twice and landing on the wrong device; studio/setup.ps1 has always taken entry 0
and says so in a comment. install.ps1 now matches it. This was previously only an
arch selection, which is why it went unnoticed; printing the name made it visible.

setup.sh could resolve a marketing name but no gfx target and then drop the name,
falling through to a bare "AMD ROCm" while install.sh printed the name. The
name-only arm is added below the unsupported-GPU arm, not above it: a card with
no ROCm wheels also arrives here with a name, and naming it quietly would drop
the warning that training will not run.

Matrix is now 80 cases, all completing with no hang; tests/studio/*.ps1 all pass.

* Pick amd-smi's market name by device index, and unbreak the hipinfo probe test

Two findings from the last review round, both on the previous commits here.

The amd-smi fallback took the first MARKET_NAME in the output while the arch was
taken at the masked index, so a multi-AMD host with no rocminfo and
HIP_VISIBLE_DEVICES=1 paired GPU 0's name with GPU 1's arch. The rocminfo path
was already fixed by pairing name to agent, and the PowerShell paths by carrying
the index forward, but the shell amd-smi fallback still read only the first name.
It now collects every device's name and selects at the same index the arch came
from. In the fixture matrix the masked two-GPU case goes from "Radeon RX 7900 XTX
(gfx1100)" to "Radeon PRO W7900 (gfx1100)", and the unmasked case still names the
XTX.

_assert_accepts_partial_hipinfo_output sliced a fixed 1600 characters from the
hipinfo probe and asserted the gcnArchName diagnostic was inside it. The name
selection added here pushed that diagnostic past the cut, so
test_setup_accepts_hipinfo_gcnarchname_on_nonzero_exit and its install.ps1 twin
failed against correct code. The slice is now bounded at the catch that closes the
probe's own try, which does not move when the parse gains a branch.

tests/studio/install/test_rocm_support.py is 492 passed, 1 skipped; the fixture
matrix is 82 cases with no hang; tests/studio/*.ps1 all pass.

* Resolve opaque MIG UUIDs, and keep the device index when arches repeat

Three findings from the last round, all on the previous commits here.

Since R470 each MIG instance carries its OWN opaque UUID, MIG-<UUID>, which
contains nothing of the parent GPU; only the pre-R470 name embedded one as
MIG-<GPU-UUID>/<gi>/<ci>. The unwrap added earlier assumed the legacy form, so a
modern MIG mask matched no --query-gpu=uuid row and the banner fell back to GPU 0.
The two forms are now split: the legacy one still resolves through the embedded
parent, and the opaque one resolves through the GPU nesting in `nvidia-smi -L`,
which is the documented way to map an instance back to its card.

Two places still recovered a device index from an arch VALUE, which is not unique.
On rocminfo the agent lookup exited on the first agent carrying the selected arch,
and in the setup.ps1 WMI fallback IndexOf did the same over $nameArches. Two cards
of one arch with different names (RX 7900 XTX and PRO W7900 are both gfx1100) then
named the first regardless of the mask. Both now keep the index that was actually
selected, falling back to the arch match only where a shadowing repick moved the
arch off it, so the name and the arch always describe the same device.

Found while testing the above rather than by review: the new agent lookup wrote
a[n] with n unset, and an unset awk variable subscripts as "" rather than 0, so
a[0] was never assigned and the unmasked two-card case named the second GPU. The
counter is initialised explicitly now. The sibling snippets use a[n++], where the
increment forces numeric context, and were unaffected.

Matrix is 88 cases with no hang, PowerShell 36 cases, test_rocm_support.py 492
passed 1 skipped, tests/studio/*.ps1 all passing.

* Do not pay the probe timeout twice when nvidia-smi is wedged

Detection already runs nvidia-smi -L under the 10s bound, and a host whose
driver is wedged still detects as an NVIDIA GPU through /proc/driver/nvidia.
The banner then asked the same hung binary for a name and waited out the bound
again, so the installer stalled 20s where main stalled 10.

Detection now records the timeout (timeout's 124, and the PowerShell runner's
own 124) and the banner skips its query when it is set, falling back to the
vendor-only wording main already printed. Measured over the 88-case fixture
matrix: the wedged case is back to 10s, every other case adds at most one probe
process and 25ms.

* Do not name an NVIDIA card that CUDA_VISIBLE_DEVICES hides

CUDA_VISIBLE_DEVICES=-1 or "" hides every device. The Windows resolver matched
neither the numeric nor the MIG form, so -1 fell through to the UUID branch,
spent a probe that can never match, and left the index at 0 -- naming row 0 and
printing its compute target while CUDA exposes no GPU at all. The shell
installers already treat both spellings as all-hidden in _cvd_hides_nvidia.

Only the naming is skipped. HasNvidiaSmi still drives wheel selection, as on
main, so the banner falls back to the vendor-only wording main already printed
rather than claiming a card that is not there.

* Judge the CUDA mask by its first entry, and do not guess a CUDA ordinal

Two defects in the NVIDIA banner's device selection.

CUDA truncates enumeration at the first invalid index, so the documented "2,-1"
means "device 2, then stop". Both shell scripts classified the WHOLE mask, saw
the minus sign, called it non-numeric and sent a plain ordinal down the UUID
lookup, which matched nothing and named row 0. They now classify the first
entry, which is the one that selects the device. The PowerShell copies already
did this.

A numeric entry is a CUDA ordinal, not an nvidia-smi row. CUDA defaults to
CUDA_DEVICE_ORDER=FASTEST_FIRST, which puts the fastest card at 0 and leaves the
rest unspecified, while nvidia-smi always lists in PCI order. An ordinal
therefore identifies a row only when the order is pinned to PCI_BUS_ID, or when
the cards are interchangeable and every row gives the same answer anyway.
Otherwise the banner keeps the vendor-only wording and reports the driver alone,
which is what the AMD path already does when the mask and the records disagree.
A UUID or MIG id identifies the device outright, so it is unaffected.

* An unresolved GPU identity is not row 0, and a borrowed arch carries its name

Two more selection defects.

NVIDIA accepts an abbreviated UUID only when it is a unique leading portion, so
a prefix matching two cards selects no device at all. The helper returned the
first match, and both PowerShell copies stopped at the first hit, so the banner
named one of them. They now count matches and resolve only on exactly one.

That exposed the same wrong assumption one level up: an identity mask that does
not resolve, whether ambiguous or naming a card that is not present, was falling
back to row 0. Row 0 is not a fallback for "CUDA selected nothing", it is a
different card. Those masks now keep the vendor-only wording.

In studio/setup.ps1, an unmappable adapter ahead of a supported one leaves
$nameArches shorter than $gpuNames, which skipped the block that moves the
banner name onto the adapter the arch came from. A generic integrated Radeon in
front of an RX 9070 therefore printed the integrated name against the discrete
arch. The source adapter is now recorded while $nameArches is built, so a
borrowed arch takes its own card's name with it.

* An out-of-range CUDA ordinal selects nothing, not GPU 0

CUDA stops enumerating at the first invalid index, so CUDA_VISIBLE_DEVICES=1 on
a one-GPU host exposes no device at all. The row pick clamps an out-of-range
index to 0 so the driver version still reads, and the banner then named row 0:
a card the process cannot use.

An ordinal past the last row now counts as unresolved, the same as an identity
mask that matches nothing, so the banner keeps the vendor-only wording.

The existing out-of-range fixture did not catch this. It used two different
cards under CUDA's default order, so the ordering guard suppressed the name for
an unrelated reason and the range bug stayed invisible. The new fixtures pin
CUDA_DEVICE_ORDER and use identical cards, which disables that guard and leaves
the range check as the only thing that can answer.

* Name the adapter that supplied the arch, selected or borrowed

The previous fix only moved the banner name when the arch was BORROWED from
another adapter. A visible-device mask selecting a supported adapter that sits
behind an unmappable one resolves the arch directly, so the borrow never fires,
$nameArches is still shorter than $gpuNames, and neither naming branch ran:
HIP_VISIBLE_DEVICES=1 over ["AMD Radeon Graphics", "AMD Radeon RX 9070"]
printed the integrated name against the discrete arch.

One index now records which adapter supplied the arch in either case.

It is spelled `if ($pickedName -and $_archSrcIdx -lt 0)` rather than a bare
truthiness test because `if ($pickedName) {` is the end anchor
TestSetupPs1ShadowingParity slices the borrow block on. A second copy closed
that window early and hid the pinned-mask guard from it, which failed the test
on the first attempt. A new case pins the occurrence count so the anchor cannot
be shadowed again.

* Canonicalise the device ordinal before subscripting or comparing with it

Self-review turned up two ways a numerically valid ordinal slipped past the
checks added over this review.

awk subscripts arrays by the STRING form of the key, so a["0000"] is a different
cell from a[0]. Rows are stored with a[n++], whose keys are "0", "1", so a
CUDA_VISIBLE_DEVICES of "0000" or "01" read an empty cell, the row came back
blank and the banner degraded to the vendor wording with no driver line. Six
sites across the two scripts, NVIDIA and AMD alike; every one now forces numeric
context on the subscript.

The bash test builtin parses with strtol and errors on a value wider than a
long. An all-digit ordinal that overflows printed a shell diagnostic into the
user's terminal and skipped the out-of-range check entirely, so it named row 0,
the exact case that check exists to refuse. The ordinal is now clamped to 9999,
which is past any real host, so it stays out of range and declines.

Eight fixtures pin the non-canonical spellings, with the cards differing and the
device order pinned so only the ordinal can decide the outcome.

---------

Co-authored-by: danielhanchen <[email protected]>
… ab_plan row (unslothai#11015)

## torchvision

A torchvision whose compiled extension failed to load does not always surface as a loader error. Reached through a lazy import it arrives as a circular-import message, and CPython words that one fault four ways:

```
3.9 - 3.12   partially initialized module 'torchvision' has no attribute 'extension'
3.13, 3.14   partially initialized module 'torchvision' from '<file>' has no attribute
from-import  cannot import name 'extension' from partially initialized module 'torchvision'
submodule    cannot access submodule 'ops' of module 'torchvision'
```

Measured on this box (3.12.3 omits the `from` clause, 3.13.12 carries it) and confirmed against the interpreter's own strings for the fourth. The marker anchors on `partially initialized module 'torchvision'` and stops there, with one alternative for the submodule wording. A typo on a healthy torchvision still cannot match, because none of these occur without "partially initialized".

A local `torchvision` earlier on sys.path raises the same words while the metadata still describes the installed distribution, so the check would have answered a shadowing bug with "reinstall", which cannot change which sys.path entry is searched first. `_shadowing_torchvision_path` asks identity rather than shape, since a `torchvision/` directory is a package exactly like the real one: it compares what `find_spec` resolves against what the distribution's metadata installed, and declines to answer when that layout is not on disk. `find_spec` rather than `sys.modules`, because CPython has already removed the half-built module by the time the `except` runs.

`test_the_marker_matches_what_this_interpreter_actually_says` provokes the error on whatever interpreter runs the suite and checks the marker against it, so the pattern cannot drift from CPython again without a red test.

## studiobench ab_plan

`--resume` emits a fresh `ab_plan` for the work that session was asked to do, so collapsing the section to `[0]` dropped the cells a later session added while `record_counts` still reported both plans. That is the same silent loss that moved this row out of `header`, one layer down.

- `order` is the union across sessions.
- `balanced` is ANDed over the sessions that still own a cell, taking ownership from `latest_attempt_rows`: `ATTEMPT_ROW_TYPES` rather than `cell` rows alone, keyed on `session_id`. Keying on cell rows would have reintroduced the bug that module already fixed, since an attempt hard-killed mid-cell never writes its terminal row.
- Each verdict is recomputed over what that session attempted, because the row's own was computed over the whole plan before it ran. A `--reps 2` interrupted after rep 0 planned base, treatment, treatment, base and ran base, treatment, so base led every pair that happened.
- The merged object no longer carries `plans[0]`'s `session_id`, which labelled the result with a session that supplied none of the verdict. It names every contributor instead.

Every fix is mutation-tested: restoring the old marker fails 4 tests, shape-based shadow detection fails 1, `cell`-only ownership fails 1, plan-membership liveness fails 2, reading `balanced` off the plan fails 1, dropping the single-arm rule fails 1, `[0]` for `ab_plan` fails 2.
…mand (unslothai#11036)

The README Docker quickstart used Bash syntax without saying so, pointed Windows users at Docker Desktop with WSL 2 without linking anywhere, and gave `docker logs -f` without the container argument the command requires.

- The run block is labelled `Linux / WSL (Bash):`.
- The Windows note links to the Docker installation guide.
- `docker logs -f <container>` takes its argument, and the sentence now says where that value comes from: the ID printed by `docker run -d`, or a name from `docker ps`.

Both `unsloth.ai/docs/get-started/install/docker` and `docs.unsloth.ai/get-started/install/docker` return 200 and resolve to the same page.

Note for anyone reading this section: it does not yet mount the Hugging Face cache, so models downloaded in the container are lost on `docker rm`. That is tracked in unslothai#10923 and fixed separately.
…hai#11062)

Reported in unslothai#10923: models downloaded in the container disappear on docker rm.

Measured in unsloth/unsloth@sha256:3b88aa35b378: HF_HOME is
/workspace/.cache/huggingface, huggingface_hub and Studio's own resolver both
put downloads under it, and it is on no volume, so it lives in the container's
writable layer. The unsloth-studio volume covers accounts, chats and Studio
state, not model weights.

Reproduced by container replacement rather than restart: a fresh container from
the same digest could not resolve a previously downloaded model with
HF_HUB_OFFLINE=1, and could once the cache was mounted.

The mount is copied verbatim from docker/DOCKERHUB.md, which already documents
it, so the README stops being the outlier rather than inventing a third
variant. The surrounding sentence now says which store keeps what, since
'keeps your accounts, chats and trained models' reads as though downloads are
covered too.
…tree (unslothai#11063)

`Repo tests (CPU, studio)` failed on unslothai#11054, which touches three frontend files and cannot reach an installer test:

```
shutil.Error: [('.../studio/backend/requirements/.extras-filtered-_30x7ggm.txt',
  ..., "[Errno 2] No such file or directory")]
FAILED tests/studio/install/test_studio_deps_cli.py::test_malformed_core_metadata_is_a_foreign_conflict
```

`install_python_stack._filter_requirements` writes its filtered copy beside the source on purpose, so relative -r and -c includes resolve, and its source is the real requirements tree this fixture copies into every fake venv. Under xdist that is two workers on one directory: the name was there when copytree listed the tree and gone when it read it.

The fixture skips `.*-filtered-*.txt`. Ignored names are never scheduled for copying, so there is no window to lose, and a tree meant to mirror the shipped requirements no longer picks up another process's scratch either.

Two tests, both failing without the ignore: the generated file is not copied, and the file vanishing between the listing and the read no longer fails the copy. The second was vacuous as first written, since copytree binds copy2 as a default argument and patching shutil.copy2 does not reach it; it passes copy_function explicitly now.

No product file changes.
… the rest (unslothai#11069)

* Release: sign every shipped PowerShell script and publish digests for the rest

install.ps1 was already signed, but only the copy the Windows bundler packs. A user who
clones the repo or fetches from raw.githubusercontent gets an unsigned file, and
studio/setup.ps1 and scripts/uninstall.ps1 were never signed at all.

The release now stages all seven shipped scripts, signs the three PowerShell ones with the
same Trusted Signing path the bundle already uses, and attaches them to the release along
with SHA256SUMS.txt.

Copies rather than the working tree, except install.ps1, which has to be signed in place
because the bundler packs it. Signing setup.ps1 or uninstall.ps1 in place would append a
signature block to files later steps and tests still read.

Every staged .ps1 is verified with Get-AuthenticodeSignature afterwards, including the one
the existing step signed, so a release cannot carry a script whose signature does not check
out on the machine that produced it.

.sh and .bat cannot carry an Authenticode signature. There is no subject interface package
for either, and Windows performs no signature check on a batch file at all, so the most that
can be done for those is a published digest. They are staged alongside so SHA256SUMS.txt
describes exactly the bytes the release serves, and the format is the two-space form
`sha256sum -c` accepts unmodified.

The artifact is deliberately not named desktop-release-*: the publish job merges that pattern
into one directory and validates it against an exact bundle name list, which these would
break. It gets its own artifact, its own download and its own upload, leaving the bundle
contract untouched. No --clobber, matching the bundle upload, so a re-run fails rather than
quietly replacing bytes whose digest has already been published.

Also adds the *.ps1 -text rule this depends on. Authenticode signs the bytes, so a line
ending rewrite invalidates the signature. install.ps1 is LF with no BOM, and a Windows clone
with core.autocrlf=true stored it back as CRLF, after which the signature reads HashMismatch,
which WDAC treats as tampering and is worse than shipping unsigned. Verified by cloning with
core.autocrlf=true both ways: without the rule the checkout gains CRLF, with it the bytes are
unchanged.

Note this does not change `irm https://unsloth.ai/install.ps1 | iex`, which compiles a string
and checks no signature. What it buys is signer identity on VirusTotal, acceptance under
AllSigned and RemoteSigned for the downloaded file, WDAC and Smart App Control evaluation,
and the signature every vendor false positive form asks for first.

* Include the script asset names in the pre-upload collision guard

Review caught a real ordering hazard. The signed scripts upload after the bundles and without
--clobber, but the guard that refuses to republish a release only looked for Unsloth-Desktop-*
and latest.json. A release already carrying install.ps1 or SHA256SUMS.txt therefore passed the
pre-flight, the bundles uploaded, and only then did the script upload fail on the duplicate
name, leaving the release publicly half replaced and without its manifest.

The eight script asset names now sit in the same guard, in both copies of it (prepare-version
and publish-release), so the clash is reported before any upload rather than after the bundles
are already public.

tests/security/test_release_desktop_integrity.py covers it: an existing install.ps1,
SHA256SUMS.txt or uninstall.sh on the target release each fail the guard and are named in the
output. The fake gh gained an optional TARGET_ASSET_NAMES so a test can put an arbitrary asset
on the release; its previous behaviour is unchanged when the variable is unset. Shown failing
with the guard extension removed.

Verified: 23 passed in the release integrity suite.

* Upload the scripts after the manifest, not before it

Independent review pointed out that the new upload sat between the bundle upload and the
latest.json upload, so a failure in it would leave a release carrying bundles with no manifest.
That is the one state that stops every updater client, and the scripts are secondary to the
update contract, so they now go last.

Also records why the Windows checkout matters here. GitHub's windows-latest image ships Git for
Windows with core.autocrlf=true and actions/checkout offers no way to override it, so without
the *.ps1 -text rule the runner checks install.ps1 out as CRLF while raw.githubusercontent
serves LF. The signed release asset and the raw copy would then be two different files with two
different digests, which would make SHA256SUMS.txt describe neither reliably.

* Tighten the new comments

Comment pass over this PR's own additions: 38 added comment lines down to 31, keeping the facts
that are not recoverable from the code (why copies rather than the working tree, why .sh and
.bat cannot be signed at all, why the digest format is the one sha256sum -c accepts, and why the
script upload has to follow the manifest).
…e error position in diagnostics (unslothai#11064)

* Windows: stop uv splitting a requirements path, and stop redaction eating the error position

Two separate defects, both surfaced by issue unslothai#11012.

uv splits -r, -c and --overrides on whitespace and gives no way to quote around it, so a
path containing a space arrives as two bogus requirement files. unslothai#10765 fixed --overrides by
making the file install.ps1 writes space-free. The same flaw is still live on -r: the
no-torch runtime list resolves under $RepoRoot or $VenvDir, both chosen by the user, and was
handed to uv verbatim at two call sites. On a machine whose install root has a space that
install fails with exit code 2, reporting either "File not found" or "Unexpected '['"
depending only on what the first fragment happens to land on.

Get-UvSafeRequirementsPath sanitises it: the path is returned untouched when it has no
space, otherwise the 8.3 short name, otherwise a copy in a space-free location, and the
original as a last resort so the helper never invents a failure of its own. It returns
whether it made a copy, so the caller deletes a copy it owns and never the user's own file.

Requirements only, and the name says so deliberately. Relocating is safe here because
no-torch-runtime.txt is a flat list with no relative -r/-c includes, whereas uv resolves an
override's relative references against that file's own directory, so New-UnslothTorchOverridesFile
keeps its own handling rather than calling this.

The second defect is why the report was expensive to read. The Windows redaction patterns
used [^\/\r\n\s]+, which permits a colon, so for a single-segment path they swallowed
everything after it:

    at C:\Users\Alex:1:1                          ->  at %USERPROFILE%
    at C:\Users\Alex\AppData\...\tmp1.tmp:1:1     ->  at %USERPROFILE%\AppData\...\tmp1.tmp:1:1

uv reports a bad requirements path as <path>:<line>:<col>, so the position and the file name
arrived already deleted. A colon cannot appear in a Windows path segment, and the Unix rules
never had this because their class is [A-Za-z0-9._-]. Excluding it in redaction.rs and in the
TypeScript twin keeps the suffix while still redacting the user name.

Tests, each shown failing against main first:
- tests/python/test_uv_requirements_path_space.py asserts every uv -r argument traces back to
  the helper, keyed on the assignment chain rather than on a naming convention, and that the
  Remove-Item is guarded on .Temporary so a pass-through path cannot delete the user's file.
  Static because the failure only reproduces on Windows with a spaced install root.
- windows_home_redaction_keeps_the_line_and_column_suffix covers the single-segment case and
  pins the deeper path that was never affected.

Verified: 874 passed, 2 skipped across the installer shape, ROCm, uv override and new suites;
the three redaction tests pass; install.ps1 parses; redaction.rs is rustfmt clean.

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

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

* Fall back through several space-free locations, and say so when none exists

Review caught a real gap: when the requirements path has a space, %TEMP% also has one, and 8.3
name creation is disabled, the helper handed back the original spaced path. Both callers then
gave that to uv, reproducing exactly the split this is meant to prevent. 8.3 creation is
commonly off on non-system volumes, so that combination is reachable rather than theoretical.

The copy destination is now chosen from an ordered candidate list (the .NET temp path, %TEMP%,
%TMP%, the Windows\Temp directory on the temp volume, and the requirements file's own
directory), each accepted only once confirmed space-free and writable, with a directory 8.3
name tried before a candidate is discarded.

When every candidate fails the original still comes back, so the install behaves as it does
today rather than failing somewhere new, but it now warns and names the variables to change.
Without that, the case is indistinguishable from success until uv reports a fragment of the
install root as a missing requirements file, which is what made unslothai#11012 expensive to read.

tests/studio/test_uv_safe_requirements_path.ps1 covers the contract: pass-through leaves a
space-free path untouched and emits nothing, a spaced path never comes back spaced while
anywhere usable exists, only a copy is ever reported temporary so only a copy is deleted, and
the give-up path warns. The fourth case sets TMPDIR as well as TEMP and TMP, because .NET reads
TMPDIR for GetTempPath off Windows and without it that case silently took the success branch
and never exercised the warning at all.

Verified: 875 passed, 2 skipped; the new suite passes all ten checks; install.ps1 parses.

* Tighten the new comments, and add the missing licence header

Comment pass over this PR's own additions: 23 added comment lines down to 12, keeping every
load-bearing fact (why the path must be space-free, why relocating a requirements file is safe
where relocating an override is not, why %TEMP% is not trusted on its own, and why the give-up
path still returns the original). comment_tools.py check reports install.ps1 code unchanged,
comments only.

The pre-push gate caught the new pytest file missing the AGPL-3.0 header.

* Clean up a partially written copy instead of walking away from it

Independent review of the earlier revision flagged a leak: a temp file was created before the
copy, so a failed copy left it behind. The candidate loop removed that by not pre-creating
anything, but one case survived. Copy-Item that fails partway, on a full disk or an interrupted
write, leaves a partial destination, and `catch { continue }` moved to the next candidate
without removing it. The destination path is now chosen outside the try so the catch can delete
it.

The new test checks that a failed copy returns the original, reports it as not temporary, and
leaves no stray file. It is explicit in a comment that these two checks do NOT prove the
cleanup: in the scenario that can be forced portably, Copy-Item fails before creating anything,
so they pass either way. A genuine partial write cannot be simulated here, so the cleanup is
defensive rather than covered, and the comment says so rather than implying the assertion bites.

Verified: 246 passed, 1 skipped; all twelve checks in the helper suite pass; install.ps1 parses.

* Build the candidate list one element at a time so a bad TMP cannot abort the install

Review caught a worse failure than the one this helper exists to prevent. install.ps1 runs under
ErrorActionPreference = "Stop" (line 18) and an array literal is evaluated in full before the
loop over it starts, so a single throwing element terminates the install outright rather than
falling through to the next candidate or to the warning.

The element that throws is the Windows\Temp one. For a relative or malformed temp path
GetPathRoot returns an empty string and Join-Path then rejects it with a
ParameterBindingValidationException. Measured, with TMP, TEMP and TMPDIR set to a relative path:
the array literal throws and aborts, while building the list one guarded element at a time
yields 4 usable candidates and no throw.

Each candidate is now produced by its own scriptblock inside a try, so any of these Path calls
can fail without taking the install with it. The loop already skips empty entries.

The suite gains a case asserting that a relative temp path neither aborts the helper nor stops
it returning a usable result.

Verified: 246 passed, 1 skipped; fourteen checks in the helper suite pass; install.ps1 parses;
pre-push gate clean.

* Build the destination inside the try so an unmapped temp drive cannot abort the install

A regression I introduced with the previous commit. Moving the Join-Path out of the try, so the
catch could clean up a partial copy, left it unguarded, and Join-Path resolves the drive
qualifier: for a stale or disconnected drive it throws DriveNotFoundException, which under the
script-wide ErrorActionPreference = "Stop" terminates the install instead of moving to the next
candidate.

Measured: `Join-Path "Z:\temp" "unsloth-reqs-abc.txt"` throws "Cannot find drive. A drive with
the name 'Z' does not exist."

$tmp is now declared before the try and built inside it, so both properties hold: the catch can
still delete a partial destination, and a candidate on a missing drive is skipped rather than
fatal. The catch guards its Remove-Item on $tmp being set, since the throw can now happen before
there is a path to remove.

The suite gains a case with every temp variable pointing at an unmapped drive. It fails against
the previous commit with "an unmapped temp drive does not abort the helper" and passes here.

Verified: 246 passed, 1 skipped; sixteen checks in the helper suite pass; pre-push gate clean.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…users to opt in to CPU (unslothai#11071)

The Studio image turns UNSLOTH_IMAGE_ALLOW_CPU into UNSLOTH_ALLOW_CPU inside the entrypoint, so a plain image ENV of UNSLOTH_ALLOW_CPU would reach every process and disable training on a GPU host. Nothing checked that at publish time.

- build-studio now inspects the pushed image with buildx imagetools and fails when UNSLOTH_ALLOW_CPU is present in the image env, or when UNSLOTH_IMAGE_ALLOW_CPU=1 is missing.
- docker/DOCKERHUB.md no longer tells latest users to pass UNSLOTH_ALLOW_CPU=1; the image already defaults it, and the env table said as much, so the two contradicted each other.
- tests/python/test_docker_cpu_fallback.py asserts the Studio image bundles its own entrypoint at the base's path, declares no ENTRYPOINT of its own, and that the base still runs that file.
danielhanchen and others added 10 commits September 16, 2026 00:48
…lothai#11076)

`Backend CI` has been red on main since the reasoning-budget controls landed, with three
multi-account tests answering `{"detail":"Failed to get status"}`, a message naming neither
the field nor the cause.

Four reasoning fields were added to `_InferenceRuntimeFields` and they are not Optional,
which is right: `LlamaCppBackend.__init__` sets `_reasoning_budget = -1` and
`_reasoning_budget_message = ""`, so the real backend never answers None for them.
`_llama_runtime_fields` mirrors every field in that model off the backend, and the test
doubles answered None for anything nobody set, so /status raised ValidationError and the
route returned 500. The PR that added the fields is correct; the doubles were not.

## What changed

`FakeLlamaCppBackend` carries the runtime surface /status mirrors, at the values
`LlamaCppBackend.__init__` gives them. The same block was being re-declared by hand in the
per-test fakes, which is what the shared double exists to end. Fields the real backend holds
only as `_name` are declared under that name, so the double claims nothing production cannot
read.

The blanket `__getattr__` several fakes carried defeated that fallback: answering None for
the public name hides the private slot that has the value. It lives on the shared double now,
scoped to the names /status mirrors and taken from the model rather than listed. Everything
else raises `AttributeError` as before, so `getattr(backend, name, default)` keeps its
default; a blanket version broke `supports_tool_passthrough` defaulting to `supports_tools`,
which Codex caught during review.

Attributes the status route reads straight off the backend rather than through the model-field
loop are declared too, at the real backend's initial values.

## Coverage

The existing canary drives /chat/completions and never reaches this. A second one builds the
/status runtime payload from the bare double and validates it, failing with the offending
field in the message.

Mutation-tested: removing the four reasoning fields reproduces the original break and the
canary names all four; answering None instead of the private slot names the seven
private-only fields; restoring the blanket fallback fails the video chat-completions tests.

All nine files that use the double pass, 110 tests. `(Python 3.13, rest)` is green here,
against red on main.

The two remaining red jobs are inherited from main and fixed elsewhere: the studio shard by
unslothai#11065, and the python shard's kaggle launcher flake by unslothai#11085.
`Repo tests (CPU, python)` failed with a 120s timeout in
`test_a_reentrant_log_inside_the_delete_retries_does_not_abandon_them`:

    AssertionError: the launcher was still alive 120s after its signal.
    Launcher said: (nothing logged after READY)
    Stack at the abort: Current thread (most recent call first):
      File ".../runner.py", line 22 in <module>

The file's own faulthandler diagnostic answers it: line 22 is the stall, so the child never
reached its signal handler. The budget stopped measuring "did the handler run" and started
measuring "was the child ever scheduled".

## Why

The step runs `-n 4` with xdist's default `load` scheduling, so these tests are free to land on
four workers of a four-core runner at once. Each starts a real launcher subprocess and signals
it, so four together are eight processes contending for four cores. `_DEATH_BUDGET_SEC`'s own
comment records this pressure, noting the SIGINT case once needed over 30 seconds purely to be
scheduled.

## The fix

Put the file in one xdist group so its tests share a worker, and pass `--dist loadgroup` on the
two jobs that run them. Ungrouped tests distribute exactly as before, so no parallelism is lost
elsewhere.

Raising the budget was the alternative and it is the wrong lever: the test would still be timing
how loaded the box is, just with a larger number, and a real hang would take longer to report.

## Verification

Worker assignment over the same selection, measured rather than assumed:

    --dist loadgroup   gw3 only
    default load       gw0, gw1, gw2, gw3

Whole file under the CI flags, `-n 4 --dist loadgroup --timeout=330`: 27 passed.

The failure it addresses is a flake, so a green run proves little on its own. What is checked is
the mechanism: the tests now share a worker, which removes the contention the stack pointed at.
`Tauri Linux debug build (no codesign)` failed on one Rust test out of 555:

    ---- commands::tests::a_port_with_nothing_on_it_reads_as_death_not_a_stall stdout ----
    panicked at src/commands.rs:1573:14:
    nothing is listening on this port: Response { url: "http://127.0.0.1:36767/api/liveness", status: 200, ... }

Something answered on the port the test had just established was free.

## Why

The setup binds port 0, reads the assigned port, and drops the listener. That frees the port, it
does not reserve it. Rust runs the tests in this binary concurrently and several bind ephemeral
ports of their own, so the kernel can hand this one straight to one of those between the drop and
the probe.

## The fix

Draw from below the ephemeral range rather than retrying. Every other test here binds port 0, so
the allocator can only ever give them an ephemeral port: 32768 and up on Linux, 49152 and up on
macOS and Windows. A port below that cannot be assigned to a sibling at all, which removes the
race instead of reacting to it.

Retrying a port that answered was the first attempt and it was wrong: answering means the probe
had already consumed somebody's connection, and the one-shot fixture in `loopback_http` accepts
exactly once before its own test sends the request it cares about. That relocates the flake
rather than fixing it. Codex caught this during review.

A port in the chosen window being occupied is a real listener on the machine, not a sibling, so
the test walks a small range for a free one and then makes the same single assertion as before.

## Verification

`cargo check --bin unsloth-studio --tests` passes; its two warnings are pre-existing in `main.rs`
and `process.rs`.

Stated plainly: this workspace has no Rust toolchain of its own and `generate_context!` needs a
built `frontend/dist`, so the compile is verified but the test was not executed locally. CI is the
first place it runs.
…ed (unslothai#11065)

`Repo tests (CPU, studio)` has been red on main since the reasoning-budget controls landed:

    FAILED tests/studio/test_chat_preset_load_config.py::test_preset_sheet_reacts_to_a_reasoning_budget_change
    AssertionError: the preset sheet never subscribes to reasoningBudget

The sheet does subscribe. The guard required the literal `(s) => s.reasoningBudget` and counted
the field at two fixed indentations, so writing the same subscription as a multi-line conditional
turned it red. A guard a legal refactor breaks says nothing about the behaviour it guards.

## What it asserts now

That every value the selector can return depends on the field, and that the two memos calling
`capturePresetLoadConfig()` name it as a dependency. Not a spelling.

The parameter name comes from the selector's own signature, and a destructured parameter is read
through its local name. Bracketed string access is normalised to dot access, comments are stripped
before anything is discovered or compared, and block bodies are read through their own returns,
excluding functions declared inside them but not the selector's own control blocks.

A condition naming the field is not on its own a subscription: it says which arm is taken, not
what the arms return, so some arm has to return the field. Where one does, a guard naming it
accounts for the rest, which is what keeps `s.budget != null ? s.budget : null` a subscription and
rejects `s.budget > 0 ? s.other : null`.

## What it cannot do

It reads source text. It cannot prove the returned value is distinct for distinct field values,
and a sufficiently indirect selector will defeat it. That limit is recorded in the test's
docstring rather than implied away.

## Coverage

A case table over the predicate itself, since that is the part a refactor of the sheet walks into
first. Mutations against the real sheet, all caught: a selector that reads the field and returns
something else, a dropped memo dependency, the field moved from `currentLoadSummary` into an
unrelated memo, a renamed capture memo, the panel's selector repointed while a sibling component
keeps the subscription, a block body that reads and discards, arms differing only by a comment, an
early return of another field from inside an if-block, a guard-only reference with neither arm
returning the field, and the real subscription commented out beside a repointed live one.

Renaming the selector parameter, destructuring it, naming the value before returning it, and
returning through a nested helper all stay green.
* Move composer settings into the More submenu

* Move comparison composer settings into More
…slothai#11049)

* Studio: only send grammar response_format for recipe structured columns on GGUF models

* Studio: read the GGUF gate at the injection site, and tie it to the route's refusal

Follow-up to the recipe structured-column fix on the same branch. The gate was threaded out of _loaded_local_model_identity and _ensure_selected_local_model_loaded as a fourth tuple member and a return value, which left an "ensure" helper reporting the backend kind and a four-member tuple whose two booleans sit at opposite ends. _inject_local_providers is synchronous with no await between the model-loaded check and the injection, and get_llama_cpp_backend is a module-global accessor, so reading is_loaded again at the injection site cannot disagree with the first read. Both original signatures are restored, which also makes the existing _ensure_selected_local_model_loaded stub in test_job_accounts.py correct again.

The comment above the gate now says why a non-GGUF backend is excluded and what it falls back to, rather than only describing the injection the called function already documents.

Adds a test asserting that the payload the GGUF path injects is exactly what the local /v1 route refuses without llama.cpp, so teaching the safetensors/MLX backend guided decoding fails here instead of leaving recipes asking it for prompt-level JSON. The non-GGUF test now compares whole columns rather than aliases, since output_format is what that prompt-level schema is built from, and the schema constant is deep-copied into the recipe so it stays a pristine expectation against an injector that forwards it by reference.

---------

Co-authored-by: Lyxot <[email protected]>
The README's Docker section only described the CUDA image, and docker/DOCKERHUB.md still said AMD GPUs are not supported by these images, which stopped being the whole story once unsloth/unsloth-rocm was published.

- README.md gains one line pointing AMD users at unsloth/unsloth-rocm, saying it carries the training stack only (no Studio, no JupyterLab) and that it needs native Linux, since WSL exposes /dev/dxg rather than the /dev/kfd ROCm needs.
- docker/DOCKERHUB.md now says these images are CUDA only and names the ROCm image, instead of a flat 'not supported'.
- The sticker URL had literal spaces; they are percent-encoded now.
…lothai#11059)

unsloth/unsloth-rocm was published with no Docker Hub page, and nothing in the publish workflow writes one, so it would have stayed whatever was set by hand.

- docker/DOCKERHUB-ROCM.md is that page: the run command (device nodes and numeric group ids built the way docker/run.sh builds them, so a host without /dev/dri or without a render group still works), the Hugging Face cache mount and why it is not optional, the tags, the supported hardware including the three cases that need care, and what the image does and does not contain.
- The measured section reports the gfx1151 Strix Halo numbers from the published digest: 4-bit QLoRA loss 2.8146 to 1.2242, sd-turbo at 118 s and 4.21 GB, text-to-video-ms-1.7b at 279 s and 4.77 GB.
- docker-publish-rocm.yml gains a hub-readme job mirroring docker-publish.yml's: it syncs the page whenever :latest moves, reads the result back rather than trusting the PATCH, and fails when the token cannot edit the description. It uses the namespace-scoped Hub route because the legacy /v2/repositories/{owner}/{repo}/ path answers organization access tokens with 403.
…hich one loaded (unslothai#11052)

* Studio: fall back to the largest GGUF quant that fits on low disk and report it

* Size-check cached variants before counting them as free in the low-disk fallback

* Studio: show the low-disk fallback warning in unsloth start and in Studio

* Format load warning test for the kwarg hook

* Print the load warning only when it belongs to the resolved model

* Keep the low-disk fallback on the requested checkpoint

* fix(studio): replay the quant the low-disk fallback served, not the one that did not fit

The fallback records the served quant in `_hf_variant`, so /status, the Studio header and the load dedup all name what is actually running. `_last_load_intent` was left on the requested quant, and that snapshot is what the crash-respawn watchdog replays and what /api/inference/load inherits as `source.hf_variant` when a request omits the variant. Either one re-resolved the quant that did not fit: on a disk since freed that starts a multi-GB download nobody asked for, and on a disk still tight it can land on a quant other than the one that was serving. The snapshot now carries the served variant too.

In the selection itself: when nothing leaves the 5 GB reserve free, variants already complete in the cache tie on new bytes, and the tie went to the smaller one for no saving. The size tie-break now takes the better quant of two that are equally free. Only cached candidates can tie, so nothing else moves.

`_gguf_variant_fallback` becomes `_pending_variant_fallback`; one character from `_variant_fallback_warning` was too close for two fields with different lifetimes.

Tests: the served-variant case now asserts the replayed snapshot, plus new cases for the cached tie-break and for the joined load warning including which notice the teardown keeps. The frontend test drives the real `loadModel`, so the notice wiring is proven rather than matched in source, and the CLI test pins the warning to stderr.

* test(studio): teach the shared backend double the load warning /status now reads

`FakeLlamaCppBackend` answers only `_InferenceRuntimeFields` from `__getattr__` and raises for anything else, so the new unguarded `llama_backend.last_load_warning` read in `get_status` is an `AttributeError` under every double-driven status test. It does not show on this branch's own CI because the double gained that guard after this branch forked, which is the drift its docstring asks new shared attributes to be added here to prevent.

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: Lyxot <[email protected]>
@Lyxot

Lyxot commented Sep 16, 2026

Copy link
Copy Markdown
Owner Author

Control baseline captured. Closing.

@Lyxot Lyxot closed this Sep 16, 2026
@Lyxot
Lyxot deleted the staging-base-11044 branch September 16, 2026 10:02
Lyxot pushed a commit that referenced this pull request Nov 16, 2026
…nslothai#17459)

## Summary

Moves Studio's stable-diffusion.cpp prebuilt from
`master-982-0518b34-uba6ac30` to `master-982-0518b34-ueb0e729`, the
release built from fork master `eb0e729`. That is 36 fork commits on top
of the current pin. The tag keeps the `master-982` prefix because the
fork's release naming still counts from its last upstream release tag.

What the new build brings:

- Upstream resync to `master-1056` (unslothai/stable-diffusion.cpp#54):
packed INT4 convrot, MiniMax-H3 QKV chunking, RelayVSR, SDXL ControlNet
Union. Also Cosmos3-Nano-Sim-Transfer video-to-video (#53).
- x86 CPU: llamafile tinyBLAS GEMM for Q8_0 (#42), F16 / BF16 (#47) and
Q4_1 / Q5_0 / Q5_1 (#56) weights; an int8 tiled GEMM for Q8_0 / Q4_0 /
Q4_1 / Q5_0 / Q5_1 / IQ4_NL (#76); AVX512 kernels on Intel and a faster
direct convolution by default (#36, #70); Q4_K / Q2_K kept on the tiled
matmul on AMD (#57); Q5_0 / Q5_1 / Q4_1 through the Q8_0 GEMM at
diffusion batch sizes (#74); tiled flash attention and SIMD max fixes
(#66, #68, #62).
- aarch64 CPU: ik_llama.cpp GEMM kernels for K-quant and I-quant weights
(#48, #75), a NEON + i8mm variant for 128-bit SVE cores (#58), SVE flash
attention on the NEON path (#69), a 4x4 flash attention register tile
(#67).
- Metal: long graphs spread over more command buffers so the GPU
watchdog does not fire (#44), a coalesced im2col kernel (#45), flash
attention `auto` now means on without the timing probe (#46).
- Vulkan: RMS norm for short rows (#37), direct convolution chosen by an
output check instead of a timing race (#38), no host-buffer import on
AMD and MoltenVK (#60).
- HIP: bf16 WMMA operands for gfx11 / gfx12 (#59), FP32 accumulators in
the tile flash attention kernel (#61).
- CUDA: the Q8_1 block sum is computed from the quantized values, which
lowers matmul error for Q4_1 / Q5_1 / Q4_K / Q5_K / Q2_K weights (#63);
BF16 cuBLAS for large Q8_0 matmuls on A100, Hopper and datacenter
Blackwell (#39).
- Memory: the conditioning cache keeps entries across output sizes and
denoiser-only LoRA changes (#71); auto-fit charges unified-memory
devices against the RAM budget (#73, `SD_AUTOFIT_UMA=0` disables);
CPU-resident text-encoder weights are released when the next phase would
not fit (#72, `SD_TE_RELEASE=0` disables); `--mmap` repacks only what
the CPU repacks (#43); Qwen Image 2.1 prefix cache concatenated in F16
(#64).
- Packaging: bundles are smaller (#41; the Linux CPU bundle is 38.4 to
26.0 MiB, Linux CUDA 12 is 368.5 to 338.3 MiB, Linux Vulkan is 57.9 to
30.5 MiB), the Linux CPU bundles are run on emulated CPUs before
shipping (#49), and there is a new native Windows arm64 CPU bundle
(#55).

## Changes

- `studio/install_sd_cpp_prebuilt.py`: `DEFAULT_TAG` now names the new
release.
- Tests that pin the release name and its asset list now point at the
new tag. `test_sd_cpp_args.py` keeps the old pin in its list of builds
that support `--mmap`.
- The pinned asset lists gain `win-cpu-arm64`, with a test that a
Windows ARM64 host gets that bundle for `auto` / `cpu` while an x64 host
keeps `win-cpu-x64`, and that ARM64 with `cuda` or `vulkan` still gets
no match.

No Studio code changes. The existing selector already filters Windows
bundles by host architecture, so a Windows arm64 host, which today finds
no bundle in the pinned release and falls through to the upstream
fallback, now installs the native arm64 CPU build. An x64 Python running
under emulation on Windows arm64 reports `AMD64` and keeps the x64
bundle, as before. No option was removed from `sd-cli --help` or
`sd-server --help`; the new build only adds `--control-type`,
`--input-frames`, `--upscale-factor` and `--vsr-window-size`.

## Testing

- The sd.cpp, args, families, install, pin upgrade and download retry
tests pass (1406 passed). One test and one fixture error fail on main
and on this branch alike on this host, because its huggingface_hub is
older than the installed diffusers expects:
`test_create_causal_mask_patch_is_self_disabling_and_idempotent` and
`test_selection_installs_the_cuda_build`.
- Asset names: every bundle the selector can return was enumerated over
Linux x86_64 / aarch64, Windows AMD64 / ARM64 and macOS arm64 / x86_64,
with `auto`, `cpu`, `cuda` (no major, 12, 13), `vulkan` and `rocm`,
against the real asset list of the new release. Every returned name
exists in the release. The only change from the current pin is Windows
ARM64 `auto` / `cpu`, which goes from no match to `win-cpu-arm64`.
- SD1.5 (`v1-5-pruned-emaonly`), 512x512, 8 steps on CPU and 20 steps on
CUDA, euler, cfg 7, seed 42, both builds on the same machine. Each arm
repeated two or three times; every repeat was pixel-identical to the
first run of its arm. LPIPS is AlexNet.

Linux x86_64 CPU bundle, Xeon Platinum 8559C, 32 threads, wall time per
image:

| Weights | current pin | this branch | old vs new LPIPS | max pixel
diff |
| --- | --- | --- | --- | --- |
| f16 | 34.8 / 34.8 s | 16.4 / 17.2 s | 0.0001 | 13 |
| q8_0 | 31.3 / 32.4 s | 15.7 / 15.2 s | 0.007 | 118 |
| q4_K | 35.5 / 35.0 s | 18.7 / 19.0 s | 0.023 | 211 |

VAE decode alone went from 10 to 12 s down to 3.6 to 3.7 s. The
quantized CPU renders are not bit-identical to the current pin, but they
stay as close to the f16 render as before (q8_0 LPIPS to f16: 0.038 old,
0.046 new; q4_K: 0.163 old, 0.173 new).

Linux CUDA 12 bundle, Colab L4, wall time per image:

| Weights | current pin | this branch | old vs new LPIPS | max pixel
diff |
| --- | --- | --- | --- | --- |
| f16 | 4.70 / 4.70 / 4.71 s | 4.70 / 4.91 / 4.73 s | 0 | 0 |
| q8_0 | 7.42 / 4.92 / 4.90 s | 4.94 / 4.93 / 4.93 s | 0 | 0 |
| q4_1 | 18.13 / 17.97 / 17.94 s | 18.02 / 17.97 / 18.01 s | 0.025 | 198
|
| q4_K | 19.14 / 17.63 / 17.79 s | 17.74 / 17.63 / 17.61 s | 0.106 | 253
|

The current pin's first q8_0 run includes a cold start. f16 and q8_0 are
pixel-identical. q4_K moves, as the Q8_1 fix intends, and moves toward
the f16 render: LPIPS to f16 drops from 0.240 to 0.176 (q4_1: 0.327 to
0.322).

## Not covered

- macOS (Metal) and Windows were not run on hardware yet; the
cross-platform staging legs (Ubuntu, macOS 15, Windows) are still to
run.
- The new Windows arm64 bundle is covered only by the selector test and
the asset check. No Windows arm64 host ran it.
- No Vulkan, ROCm or HIP render with this build, no aarch64 Linux
render, and no Studio HTTP flow run (only `sd-cli` directly).
- No MiniMax-H3, MOSS-Image, Qwen-Image or FLUX.2 render with this
build; only SD1.5.
- CPU timings are from a shared host (both arms ran back to back with
the same thread count), and the CUDA timings come from one L4 VM, three
runs per arm. No T4 run.
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.

8 participants