Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Stop the uninstaller stranding old installs, and deleting directories that are not ours (#10471)
Daniel Han1ad44677d462
diff --git a/.github/workflows/cross-platform-parity-ci.yml b/.github/workflows/cross-platform-parity-ci.ymlindex 41d3e04c1fa..4ed61ddbc76 100644--- a/.github/workflows/cross-platform-parity-ci.yml+++ b/.github/workflows/cross-platform-parity-ci.yml@@ -57,6 +57,10 @@ on:- 'scripts/install*.ps1'- 'scripts/uninstall*.sh'- 'scripts/uninstall*.ps1'+ - 'tests/studio/test_uninstall_prebuilt_parity.ps1'+ - 'tests/studio/test_uninstall_reparse_stop_roots.ps1'+ - 'tests/studio/test_uninstall_legacy_layout_gate.ps1'+ - 'tests/sh/test_uninstall_legacy_layout_gate.sh'- 'scripts/build_whisper_cpp.sh'- 'studio/setup*.bat'- 'setup*.sh'@@ -129,6 +133,10 @@ on:- 'scripts/install*.ps1'- 'scripts/uninstall*.sh'- 'scripts/uninstall*.ps1'+ - 'tests/studio/test_uninstall_prebuilt_parity.ps1'+ - 'tests/studio/test_uninstall_reparse_stop_roots.ps1'+ - 'tests/studio/test_uninstall_legacy_layout_gate.ps1'+ - 'tests/sh/test_uninstall_legacy_layout_gate.sh'- 'scripts/build_whisper_cpp.sh'- 'studio/setup*.bat'- 'setup*.sh'@@ -287,6 +295,17 @@ jobs:- name: Application Control CLI fallback testsshell: pwshrun: pwsh -NoProfile -File tests/studio/test_application_control_cli_fallback.ps1+ # AST-based: they parse scripts/uninstall.ps1 instead of running it, so every row hosts them.+ - name: Uninstaller prebuilt parity tests+ shell: pwsh+ run: pwsh -NoProfile -File tests/studio/test_uninstall_prebuilt_parity.ps1+ # The runner is an administrator, so this covers the symlink kind, not just the junction.+ - name: Uninstaller reparse stop-root tests+ shell: pwsh+ run: pwsh -NoProfile -File tests/studio/test_uninstall_reparse_stop_roots.ps1+ - name: Uninstaller ownership gate tests+ shell: pwsh+ run: pwsh -NoProfile -File tests/studio/test_uninstall_legacy_layout_gate.ps1# Linux on purpose, and the only lane that can run it. Reflection emit succeeds on# this engine so the types build exactly as they do on 5.1, while kernel32 and# shell32 do not resolve, so every call through them fails the way it does on a@@ -298,6 +317,9 @@ jobs:- name: POSIX rollback lifecycle testsif: runner.os == 'Linux'run: sh tests/sh/test_install_rollback_lifecycle.sh+ - name: POSIX uninstaller ownership gate tests+ if: runner.os == 'Linux'+ run: bash tests/sh/test_uninstall_legacy_layout_gate.sh# bash, not sh: the helper under test is extracted from install.sh, which is bash.- name: install.sh XPU flavor probe testsif: runner.os != 'Windows'diff --git a/install.ps1 b/install.ps1index a3af5088500..e65a6a03b5b 100644--- a/install.ps1+++ b/install.ps1@@ -1592,6 +1592,72 @@ exit 1} catch { return $Cache }}+ # Claim the root before anything of ours goes into it: the uv cache, the venv and the venv's+ # own marker all land inside it, so an install that dies in between used to leave a directory+ # the uninstaller could only identify by guessing at leftovers. Never fatal.+ # A sentinel this list may trust: a regular file, never a link. Test-Path follows one, and a+ # planted link would otherwise short-circuit the emptiness test below.+ function Test-StudioPlainFile {+ param([string]$Path, [string]$Container)+ try {+ # The container too: -L / the ReparsePoint attribute answers for the named file only,+ # so a linked `share` or `unsloth_studio` holding a genuine marker would otherwise+ # read as proof that the whole workspace around it is ours.+ if (-not [string]::IsNullOrWhiteSpace($Container)) {+ $dir = Get-Item -LiteralPath $Container -Force -ErrorAction SilentlyContinue+ if ($dir -and (($dir.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0)) { return $false }+ }+ $item = Get-Item -LiteralPath $Path -Force -ErrorAction Stop+ return (-not $item.PSIsContainer -and+ (($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -eq 0))+ } catch { return $false }+ }++ # Only a root this run may take over: in env mode $StudioHome is a user-chosen workspace, so+ # an empty one, or one already carrying an unambiguous marker, and nothing else, or a run+ # that aborts at the venv-step guard leaves somebody's project marked. Shorter than that+ # guard's list on purpose: it only refuses to overwrite, this authorizes a delete.+ #+ # The emptiness test is inline, not Test-DirectoryHasEntries, which is defined below this+ # function's first caller: the name error would land in the catch and skip the claim in+ # silence. An unreadable root counts as occupied, so failure means "do not claim".+ function Write-StudioRootOwnerMarker {+ param([Parameter(Mandatory = $true)][string]$Root)+ try {+ $marker = Join-Path $Root ".unsloth-studio-owned"+ # Already ours and the right shape: leave it. This runs twice per install, and a run+ # killed between the delete and the write would lose the only proof this root is ours.+ if (Test-StudioPlainFile -Path $marker) { return }+ if (Test-Path -LiteralPath $Root) {+ $occupied = $true+ try {+ $occupied = @(Get-ChildItem -LiteralPath $Root -Force -ErrorAction Stop |+ Select-Object -First 1).Count -gt 0+ } catch { $occupied = $true }+ $claimable = (+ $StudioRedirectMode -ne 'env' -or+ (Test-StudioPlainFile -Path (Join-Path $Root "unsloth_studio\.unsloth-studio-owned") `+ -Container (Join-Path $Root "unsloth_studio")) -or+ (Test-StudioPlainFile -Path (Join-Path $Root "share\studio.conf") `+ -Container (Join-Path $Root "share")) -or+ -not $occupied+ )+ if (-not $claimable) { return }+ } else {+ # .NET API: New-Item -Path treats brackets as wildcards.+ [System.IO.Directory]::CreateDirectory($Root) | Out-Null+ }+ # Delete first, then confirm it: WriteAllText follows a file link and truncates its+ # TARGET, and the delete can fail on a root we cannot write while that target stays+ # writable. No marker is fine; the venv writes its own later.+ # Get-Item -Force, not Test-Path: the latter follows a dangling link and answers+ # false, after which WriteAllText follows the link and writes outside the root.+ Remove-Item -LiteralPath $marker -Force -ErrorAction SilentlyContinue+ if (Get-Item -LiteralPath $marker -Force -ErrorAction SilentlyContinue) { return }+ [System.IO.File]::WriteAllText($marker, "")+ } catch { }+ }+function Write-StudioUvCacheMarker {param([Parameter(Mandatory = $true)][string]$StudioRoot,@@ -4484,6 +4550,12 @@ exit 0return (Exit-InstallFailure "uv could not be installed")}+ # Ahead of the cache setup, which is the first thing to write inside the root and returns+ # early for a preset UV_CACHE_DIR. Here rather than inside it: the claim has nothing to do+ # with the uv cache, and that function is lifted out and run on its own by+ # tests/python/test_windows_python_venv_hardening.py, where a call into the rest of the+ # installer is a command-not-found.+ Write-StudioRootOwnerMarker -Root $StudioHomeSet-StudioUvCacheEnvironment -StudioRoot $StudioHome -Isolated $IsolateUvCache -UvExecutable $script:UvExe# Bytecode compilation can exceed uv's 60s default on slow machines ("0" disables).@@ -4500,10 +4572,7 @@ exit 0# ── Create the venv; hand uv the resolved exe path so it does not re-resolve back to conda. ──Write-TauriLog "STEP" "Creating virtual environment"- if (-not (Test-Path -LiteralPath $StudioHome)) {- # .NET API: New-Item -Path treats brackets as wildcards.- [System.IO.Directory]::CreateDirectory($StudioHome) | Out-Null- }+ Write-StudioRootOwnerMarker -Root $StudioHome$VenvPython = Join-Path $VenvDir "Scripts\python.exe"$_Migrated = $false@@ -4877,6 +4946,9 @@ exit 0# ours. Content-checked, never by name -- this guard gates a recursive delete.if ($StudioRedirectMode -eq 'env' -and+ # Test-StudioPlainFile, not Test-Path: the claim refuses to write a marker through a+ # link, so reading one through a link here would undo that decision.+ -not (Test-StudioPlainFile -Path (Join-Path $StudioHome ".unsloth-studio-owned")) -and-not (Test-Path -LiteralPath (Join-Path $VenvDir ".unsloth-studio-owned") -PathType Leaf) -and-not (Test-Path -LiteralPath (Join-Path $StudioHome "share\studio.conf") -PathType Leaf) -and-not (Test-Path -LiteralPath (Join-Path $StudioHome "bin\unsloth.exe") -PathType Leaf) -anddiff --git a/install.sh b/install.shindex 6eaff06d451..bfe418ffbfa 100755--- a/install.sh+++ b/install.sh@@ -781,6 +781,59 @@ _resolve_studio_destinations_UNSLOTH_LOGIN_PATH="$PATH"VENV_DIR="$STUDIO_HOME/unsloth_studio"+# Claim the root before anything of ours goes into it: the uv cache, the venv and the venv's own+# marker all land inside $STUDIO_HOME, so an install that dies in between used to leave a+# directory the uninstaller could only identify by guessing at leftovers. Never fatal.+#+# Only a root this run may take over: in env mode $STUDIO_HOME is a user-chosen workspace, so an+# empty one, or one already carrying an unambiguous marker, and nothing else, or a run that+# aborts at the venv-step guard leaves somebody's project marked. Shorter than that guard's list+# on purpose: it only refuses to overwrite, this authorizes a delete, so no bin/unsloth.+# A sentinel this list may trust: a regular file, never a link, never inside a linked directory+# ($2). -f follows a link and -L answers for the named file only, so a planted marker or a linked+# `share` holding a genuine one would otherwise short-circuit the emptiness test below.+_claim_sentinel() {+ [ -f "$1" ] || return 1+ [ -L "$1" ] && return 1+ [ -n "${2:-}" ] && [ -L "$2" ] && return 1+ return 0+}++_claim_studio_root() {+ _claim_marker="$STUDIO_HOME/.unsloth-studio-owned"+ # Already ours and the right shape: leave it. A run killed between the unlink and the write+ # would lose the only proof this root is ours.+ _claim_sentinel "$_claim_marker" && return 0+ if [ "$_STUDIO_HOME_REDIRECT" = "env" ] \+ && ! _claim_sentinel "$VENV_DIR/.unsloth-studio-owned" "$VENV_DIR" \+ && ! _claim_sentinel "$STUDIO_HOME/share/studio.conf" "$STUDIO_HOME/share"; then+ if [ -d "$STUDIO_HOME" ]; then+ # Not enumerable: without read the globs cannot expand and an occupied workspace+ # reads as empty. Fail closed like _dir_has_entries.+ { [ -r "$STUDIO_HOME" ] && [ -x "$STUDIO_HOME" ]; } || return 0+ # The globs ARE the emptiness check, so a caller's `sh -f` would make every workspace+ # look empty. Saved and restored like _dir_has_entries.+ _claim_glob=on+ case $- in *f*) _claim_glob=off ;; esac+ set +f+ _claim_empty=true+ for _claim_entry in "$STUDIO_HOME"/* "$STUDIO_HOME"/.[!.]* "$STUDIO_HOME"/..?*; do+ if [ -e "$_claim_entry" ] || [ -L "$_claim_entry" ]; then _claim_empty=false; break; fi+ done+ [ "$_claim_glob" = off ] && set -f+ [ "$_claim_empty" = true ] || return 0+ fi+ fi+ mkdir -p "$STUDIO_HOME" 2>/dev/null || true+ # Unlink first, then confirm it: the redirection follows a symlink here and truncates its+ # TARGET, and rm can fail on a root we cannot write while that target stays writable. No+ # marker is fine; the venv writes its own later.+ rm -f "$_claim_marker" 2>/dev/null || true+ if [ -e "$_claim_marker" ] || [ -L "$_claim_marker" ]; then return 0; fi+ printf '' > "$_claim_marker" 2>/dev/null || true+}+_claim_studio_root+# Keep uv's cache on the same filesystem as the venv it fills.# uv hardlinks wheels within one filesystem and copies across a boundary, so a moved# STUDIO_HOME paid double the disk and stranded the cache. An explicit UV_CACHE_DIR wins.@@ -2951,7 +3004,11 @@ if [ -x "$VENV_DIR/bin/python" ] || _dir_has_entries "$VENV_DIR"; then# not blocked. Sentinels must be regular files: -f follows symlinks# to files (the legitimate ln -s shim shape) but rejects directories# and broken/dir-targeted symlinks.+ # The root marker goes through _claim_sentinel, not -f: the claim refuses to write one+ # through a link, so reading one through a link here would undo that decision. The older+ # sentinels keep -f, since bin/unsloth is legitimately a symlink into the venv.if [ "$_STUDIO_HOME_REDIRECT" = "env" ] \+ && ! _claim_sentinel "$STUDIO_HOME/.unsloth-studio-owned" \&& [ ! -f "$VENV_DIR/.unsloth-studio-owned" ] \&& [ ! -f "$STUDIO_HOME/share/studio.conf" ] \&& [ ! -f "$STUDIO_HOME/bin/unsloth" ]; thendiff --git a/scripts/uninstall.ps1 b/scripts/uninstall.ps1index 92aa8a08074..f7f06427cd3 100644--- a/scripts/uninstall.ps1+++ b/scripts/uninstall.ps1@@ -14,6 +14,14 @@ function Uninstall-UnslothStudio {# second run in the same window would otherwise inherit the first run's flags.$script:RemoveFailed = $false$script:StudioDbRemoved = $false+ # The default root was REFUSED and still holds studio.db. Its own flag, not RemoveFailed:+ # nothing failed, so "remove those paths by hand" is the wrong thing to say about it.+ $script:StudioDbKept = $false+ # ONE budget for the run: what _RemovePath waits out is wall clock and shared, so whatever+ # the first blocked path waits, the next does not. Without it an undeletable root costs the+ # full escalation at each of the 18 call sites. Classifying the error instead does not work:+ # a delete-pending file and an antivirus hold both report access denied.+ $script:RemoveWaitBudgetMs = 20000function _Usage {Write-Host @'@@ -61,12 +69,39 @@ Environment:param([string]$Path)if ([string]::IsNullOrWhiteSpace($Path)) { return }if (-not (Test-Path -LiteralPath $Path)) { return }- for ($attempt = 1; $attempt -le 4; $attempt++) {+ # Escalating: torch inductor holds unattributable DATA handles under+ # TORCHINDUCTOR_CACHE_DIR for seconds after the server stops.+ $delays = @(250, 500, 1000, 2000, 4000, 4000, 4000, 4000)+ # 2100ms per path is free, exactly the flat 700ms x3 this replaced, so no path is retried+ # less than before: a lock only this path hits is not the shared wait. $false means both+ # are spent, so stop rather than retry with no pause in between.+ $freeLeft = 2100+ function _Wait {+ param([int]$Ms, [ref]$FreeLeft)+ $free = [Math]::Min($Ms, [Math]::Max(0, $FreeLeft.Value))+ $paid = $Ms - $free+ if ($paid -gt 0) {+ if ($script:RemoveWaitBudgetMs -le 0) {+ if ($free -le 0) { return $false }+ $paid = 0+ } else {+ $paid = [Math]::Min($paid, $script:RemoveWaitBudgetMs)+ $script:RemoveWaitBudgetMs -= $paid+ }+ }+ $FreeLeft.Value -= $free+ Start-Sleep -Milliseconds ($free + $paid)+ return $true+ }+ for ($attempt = 0; $attempt -le $delays.Count; $attempt++) {+ $lastTry = ($attempt -eq $delays.Count)try {Remove-Item -LiteralPath $Path -Recurse -Force -ErrorAction Stop} catch {- if ($attempt -lt 4) { Start-Sleep -Milliseconds 700; continue }- _Substep "could not remove: $Path ($($_.Exception.Message))" "Yellow"+ # Read before $wait runs, so nothing can shadow the error record.+ $failure = $_.Exception.Message+ if (-not $lastTry -and (_Wait $delays[$attempt] ([ref]$freeLeft))) { continue }+ _Substep "could not remove: $Path ($failure)" "Yellow"# The closing summary must not promise the data is gone.$script:RemoveFailed = $truereturn@@ -77,9 +112,10 @@ Environment:_Substep "removed: $Path" "Green"return}- if ($attempt -lt 4) { Start-Sleep -Milliseconds 700; continue }+ if (-not $lastTry -and (_Wait $delays[$attempt] ([ref]$freeLeft))) { continue }_Substep "still present (files held open): $Path" "Yellow"$script:RemoveFailed = $true+ return}}@@ -100,18 +136,32 @@ Environment:# install passes the before-check through the link, but the delete unlinks only the reparse# point. Verifying rather than chasing the link is deliberate: following a reparse point out of# the expected location to delete its target is what the deny list exists to stop.+ # A removal that got part way can take the sentinels and then fail on a locked child, leaving+ # a root the next run's gate would refuse. Put the marker back so a retry recognises it.+ function _RestoreOwnerMarker {+ param([string]$Path)+ if ([string]::IsNullOrWhiteSpace($Path)) { return }+ if (-not (Test-Path -LiteralPath $Path -PathType Container)) { return }+ # Get-Item -Force, not Test-Path: the latter follows a dangling link and answers false,+ # after which WriteAllText follows the link and writes outside the root.+ $marker = Join-Path $Path ".unsloth-studio-owned"+ if (Get-Item -LiteralPath $marker -Force -ErrorAction SilentlyContinue) { return }+ try { [System.IO.File]::WriteAllText($marker, "") } catch { }+ }+function _RemoveRootRecordingDb {param([string]$Path)if ([string]::IsNullOrWhiteSpace($Path)) { return }# Anchor a relative reparse-point target to the link's own parent, or Join-Path# resolves it from the uninstaller's working directory and the db test reads false.+ # -LiteralPath takes no -Parent (other parameter set; it throws) and already returns it.$resolveTarget = {param($Item, $Fallback)if (-not $Item -or -not $Item.Target) { return $Fallback }$t = @($Item.Target)[0]if ([string]::IsNullOrWhiteSpace($t)) { return $Fallback }if (-not [System.IO.Path]::IsPathRooted($t)) {- $t = Join-Path (Split-Path -LiteralPath $Item.FullName -Parent) $t+ $t = Join-Path (Split-Path -LiteralPath $Item.FullName) $t}return $t}@@ -130,6 +180,7 @@ Environment:} catch { }}_RemovePath $Path+ _RestoreOwnerMarker $Pathif ($hadDb) {if (Test-Path -LiteralPath $dbPath -PathType Leaf) {$script:RemoveFailed = $true@@ -364,13 +415,80 @@ Environment:# <root>\bin\unsloth.exe, or a <root>\bin\unsloth.cmd this installer wrote.# The .cmd is the launcher written where an Application Control policy denies the generated# console script, so an install whose .exe that policy quarantined still owns its root.- function _IsStudioRoot {+ # Plus the legacy venv shapes install.ps1 still migrates: share\studio.conf is never written+ # on Windows, so every sentinel above postdates the bin\ shim dir.+ # A sentinel this gate may trust. Deliberately a plain existence test, following links:+ # refusing a reparse point here, or a marker inside one, buys nothing and costs a supported+ # install. Nothing, because anyone who can plant a junction at that path can plant a plain+ # file there instead, which this has always accepted. A supported install, because relocating+ # a multi-gigabyte venv with a junction leaves a REAL marker behind one, and refusing it+ # strands the install, which is the failure this gate exists to prevent. The link test belongs+ # in install.ps1's claim, where following one would TRUNCATE the target rather than read it.+ function _IsOwnerMarker {+ param([string]$Path)+ if ([string]::IsNullOrWhiteSpace($Path)) { return $false }+ return (Test-Path -LiteralPath $Path -PathType Leaf)+ }++ # Is $Path a Python venv? What the gate reads out of one is evidence only if the directory+ # really is one; a bare name at that path is somebody else's.+ function _IsVenvDir {param([string]$Path)if ([string]::IsNullOrWhiteSpace($Path)) { return $false }- if (Test-Path -LiteralPath (Join-Path $Path "share\studio.conf") -PathType Leaf) { return $true }- if (Test-Path -LiteralPath (Join-Path $Path "unsloth_studio\.unsloth-studio-owned") -PathType Leaf) { return $true }+ # No reparse check here either, and for the same reason: a relocated venv is still a+ # venv. The leftover scan below rejects links on its own, where the name came from a+ # wildcard rather than from us.+ if (-not (Test-Path -LiteralPath $Path -PathType Container)) { return $false }+ if (Test-Path -LiteralPath (Join-Path $Path "pyvenv.cfg") -PathType Leaf) { return $true }+ return (Test-Path -LiteralPath (Join-Path $Path "Scripts\python.exe") -PathType Leaf)+ }++ # The exact shape an installer gives a moved-aside venv. install.ps1 keeps every other+ # spelling as the user's data (Test-StudioVenvRollbackMustBePreserved); do not be looser.+ function _IsInstallerLeftoverName {+ param([string]$Name)+ # Two patterns: only the rollback name carries a collision counter (install.ps1:4171).+ # No "time" alternative; that is install.sh's date(1) fallback and has no Windows twin.+ # [0-9], not \d, which matches every Unicode decimal digit; install.ps1 writes ASCII.+ if ($Name -match '^unsloth_studio\.rollback\.[0-9]{14}\.[0-9]+(\.[0-9]+)?$') { return $true }+ return ($Name -match '^\.venv\.invalid\.[0-9]{14}\.[0-9]+$')+ }++ function _IsStudioRoot {+ param([string]$Path, [switch]$ManagedDefaultRoot)+ if ([string]::IsNullOrWhiteSpace($Path)) { return $false }+ # install.ps1 writes the first when it creates the root, before the uv cache and long+ # before the venv, so a partial install identifies itself instead of being guessed at.+ if (_IsOwnerMarker (Join-Path $Path ".unsloth-studio-owned")) { return $true }+ if (_IsOwnerMarker (Join-Path $Path "share\studio.conf")) { return $true }+ if (_IsOwnerMarker (Join-Path $Path "unsloth_studio\.unsloth-studio-owned")) { return $true }+ if (_IsOwnerMarker (Join-Path $Path ".venv\.unsloth-studio-owned")) { return $true }if (Test-Path -LiteralPath (Join-Path $Path "bin\unsloth.exe") -PathType Leaf) { return $true }if (_IsUnslothCmdShim (Join-Path $Path "bin\unsloth.cmd")) { return $true }+ # Below here is INSIDE a venv, where pip puts it for any install of the wheel: it names+ # the wheel, not the owner. Proof only at the managed root, which install.ps1:4453 also+ # makes the only root that can hold the layout, or a stale UNSLOTH_STUDIO_HOME deletes it.+ if (-not $ManagedDefaultRoot) { return $false }+ foreach ($venv in @("unsloth_studio", ".venv")) {+ if (-not (_IsVenvDir (Join-Path $Path $venv))) { continue }+ if (Test-Path -LiteralPath (Join-Path $Path "$venv\Scripts\unsloth.exe") -PathType Leaf) { return $true }+ # Antivirus takes that .exe out of a venv that still runs; install.ps1:6412 repairs+ # through it, so a pre-marker root has nothing else left.+ foreach ($pkg in @("unsloth_cli", "unsloth")) {+ if (Test-Path -LiteralPath (Join-Path $Path "$venv\Lib\site-packages\$pkg") -PathType Container) { return $true }+ }+ }+ # An install that died between moving the old venv aside (install.ps1:4487, :4165) and+ # writing the marker (install.ps1:4524) leaves only these, and only install.ps1 makes+ # either name, always by renaming a venv.+ foreach ($leftover in @("unsloth_studio.rollback.*", ".venv.invalid.*")) {+ foreach ($dir in @(Get-ChildItem -LiteralPath $Path -Filter $leftover -Directory -Force -ErrorAction SilentlyContinue)) {+ # Never a reparse point: install.ps1 refuses to prune a linked rollback either.+ if (($dir.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) { continue }+ if (-not (_IsInstallerLeftoverName $dir.Name)) { continue }+ if (_IsVenvDir $dir.FullName) { return $true }+ }+ }return $false}@@ -388,7 +506,7 @@ Environment:$userProfile = $userProfile.TrimEnd('\','/')if ($norm -ieq $userProfile) { return $true }try {- $parent = Split-Path -LiteralPath $userProfile -Parent+ $parent = Split-Path -LiteralPath $userProfileif ($parent -and ($norm -ieq $parent.TrimEnd('\','/'))) { return $true }} catch { }}@@ -417,9 +535,9 @@ Environment:if ($line -match "^UNSLOTH_EXE\s*=\s*'(.*)'\s*$") {$exe = $Matches[1] -replace "''", "'"try {- $bin = Split-Path -LiteralPath $exe -Parent- $studio = Split-Path -LiteralPath $bin -Parent- $root = Split-Path -LiteralPath $studio -Parent+ $bin = Split-Path -LiteralPath $exe+ $studio = Split-Path -LiteralPath $bin+ $root = Split-Path -LiteralPath $studioif ($root) { return $root }} catch { }}@@ -541,6 +659,9 @@ Environment:# Anchoring on the venv path avoids matching unrelated python.exe / studio.exe.function _StopStudioProcesses {param([string[]]$KnownRoots)+ # An EXPLICIT empty list means "no root qualifies", not "do not scope". @() is false in+ # PowerShell, so `if ($KnownRoots)` swept the whole machine on a run with nothing to delete.+ $scoped = $PSBoundParameters.ContainsKey('KnownRoots')try {$procs = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue |Where-Object {@@ -549,7 +670,7 @@ Environment:}foreach ($p in $procs) {# Optional scope: only kill if the exe is under a known root.- if ($KnownRoots) {+ if ($scoped) {$match = $falseforeach ($r in $KnownRoots) {if ($p.ExecutablePath -and ($p.ExecutablePath -ilike "$r\*")) { $match = $true; break }@@ -595,7 +716,7 @@ Environment:# A symlink target may be relative; a junction's never is. Anchor it on the link's# own parent, or GetFullPath would read it from the uninstaller's working directory.if (-not [System.IO.Path]::IsPathRooted($t)) {- $t = Join-Path (Split-Path -LiteralPath $item.FullName -Parent) $t+ $t = Join-Path (Split-Path -LiteralPath $item.FullName) $t}$t = [System.IO.Path]::GetFullPath($t).TrimEnd('\', '/')if (-not $t) { continue }@@ -687,16 +808,29 @@ Environment:$knownRoots = @()if ($defaultStudioHome) { $knownRoots += $defaultStudioHome }$knownRoots += $customRoots+ # The roots this run would actually delete. Everything that stops, deletes or edits on behalf+ # of a root takes THIS list, never $knownRoots: all of it runs before the gates below, and a+ # stale studio.conf can name a directory another application has taken over. _IsUnsafeRoot as+ # well as _IsStudioRoot, because the removal loop refuses on either.+ $ownedRoots = @()+ if ($defaultStudioHome -and (_IsStudioRoot $defaultStudioHome -ManagedDefaultRoot) -and+ -not (_IsUnsafeRoot $defaultStudioHome)) {+ $ownedRoots += $defaultStudioHome+ }+ foreach ($r in $customRoots) {+ if ((_IsStudioRoot $r) -and -not (_IsUnsafeRoot $r)) { $ownedRoots += $r }+ }# ── Stop running servers ──_Step "Stopping any running Unsloth Studio servers..."if ($defaultDataDir) {- _StopByPortFile -PortFile (Join-Path $defaultDataDir "studio.port") -KnownRoots $knownRoots+ _StopByPortFile -PortFile (Join-Path $defaultDataDir "studio.port") -KnownRoots $ownedRoots}- foreach ($r in $customRoots) {- _StopByPortFile -PortFile (Join-Path $r "share\studio.port") -KnownRoots $knownRoots+ # $ownedRoots, not $customRoots: _StopByPortFile deletes the port file on its way out.+ foreach ($r in $ownedRoots) {+ _StopByPortFile -PortFile (Join-Path $r "share\studio.port") -KnownRoots $ownedRoots}- _StopStudioProcesses -KnownRoots $knownRoots+ _StopStudioProcesses -KnownRoots $ownedRoots# The app and the WebView2 helpers holding its profile open must both exit before the# EBWebView delete below. Same resolver as that removal, or the sweep misses the profile# we then try to delete and the helpers keep holding locks.@@ -767,17 +901,22 @@ Environment:# A custom/env-mode sd.cpp build now sits UNDER its root, which the $knownRoots prefix match# below already covers. Older builds put it BESIDE the root at <parent>\stable-diffusion.cpp,# outside $knownRoots; we delete those marker-owned dirs below, so scan them too.+ # Gated too: a stale root's PARENT can hold another install's marked sd.cpp.$customSdCppToStop = @()foreach ($r in $customRoots) {- $sdc = Join-Path (Split-Path -LiteralPath $r -Parent) "stable-diffusion.cpp"+ if (-not (_IsStudioRoot $r)) { continue }+ if (_IsUnsafeRoot $r) { continue }+ $sdc = Join-Path (Split-Path -LiteralPath $r) "stable-diffusion.cpp"if ((Test-Path -LiteralPath $sdc) -and (Test-Path -LiteralPath (Join-Path $sdc ".unsloth-studio-owned") -PathType Leaf)) {$customSdCppToStop += $sdc}}# Also stop anything holding a handle on the exact paths we delete (llama-server,# the CLI shim, an mp-fork python with a venv DLL) so the dir delete isn't refused.- $stopRoots = @($knownRoots) + @($defaultDataDir, $defaultLlamaCpp, $defaultCache, $defaultNode, $defaultWhisperCpp) + @($defaultSdCppToStop | Where-Object { $_ }) + @($customSdCppToStop)- _StopProcessesLockingRoots -Roots ($stopRoots + @(_ManagedPathsUnderReparseTargets $knownRoots))+ $stopRoots = @($ownedRoots) + @($defaultDataDir, $defaultLlamaCpp, $defaultCache, $defaultNode, $defaultWhisperCpp) + @($defaultSdCppToStop | Where-Object { $_ }) + @($customSdCppToStop)+ # The reparse expansion turns one path into generic subdirectories of wherever it points+ # (node, bin, unsloth_studio), so it is gated for the same reason.+ _StopProcessesLockingRoots -Roots ($stopRoots + @(_ManagedPathsUnderReparseTargets $ownedRoots))# ── Remove custom-root install trees ──_Step "Removing data and install directories..."@@ -800,7 +939,7 @@ Environment:# exactly what a git clone of the upstream project produces, so require our owner marker# (install_sd_cpp_prebuilt) before rm and keep any unowned checkout. The derived parent# path gets the deny-list check too.- $customSdCpp = Join-Path (Split-Path -LiteralPath $r -Parent) "stable-diffusion.cpp"+ $customSdCpp = Join-Path (Split-Path -LiteralPath $r) "stable-diffusion.cpp"if (_IsUnsafeRoot $customSdCpp) {_Substep "refusing to remove unsafe path: $customSdCpp" "Yellow"} elseif ((Test-Path -LiteralPath $customSdCpp) -and -not (Test-Path -LiteralPath (Join-Path $customSdCpp ".unsloth-studio-owned") -PathType Leaf)) {@@ -809,8 +948,19 @@ Environment:_RemovePath $customSdCpp}}- # Default install dir (always at %USERPROFILE%\.unsloth\studio when present).- if ($defaultStudioHome) { _RemoveRootRecordingDb $defaultStudioHome }+ # Default install dir (always at %USERPROFILE%\.unsloth\studio when present). Same sentinels+ # as a custom root: an ungated run takes a hand-made one, then ~/.unsloth with the prune below.+ if ($defaultStudioHome -and (Test-Path -LiteralPath $defaultStudioHome) -and+ -not (_IsStudioRoot $defaultStudioHome -ManagedDefaultRoot)) {+ _Substep "refusing to remove non-Unsloth path: $defaultStudioHome" "Yellow"+ # A refused CUSTOM root is somebody else's by definition. This is our own default path,+ # where a damaged install can sit, so a studio.db here is chat history.+ if (Test-Path -LiteralPath (Join-Path $defaultStudioHome "studio.db") -PathType Leaf) {+ $script:StudioDbKept = $true+ }+ } elseif ($defaultStudioHome) {+ _RemoveRootRecordingDb $defaultStudioHome+ }# Default data dir. The private temp sweep goes FIRST and hands back what it kept: the primary# temp directory lives under this data dir, so a wholesale removal here would erase a live# Unsloth's %TEMP% before the sweep ever looked at its owner.pid.@@ -914,11 +1064,12 @@ Environment:$removedAny = $false# Only remove PATH entries inside an Unsloth root we actually own. A literal# substring match on `unsloth_studio` would clobber unrelated user virtualenvs.+ # A root this run refused keeps its PATH entry, because it keeps its files.foreach ($e in $entries) {if ([string]::IsNullOrWhiteSpace($e)) { continue }$expanded = [Environment]::ExpandEnvironmentVariables($e).TrimEnd('\','/')$isStudio = $false- foreach ($r in $knownRoots) {+ foreach ($r in $ownedRoots) {if (-not $r) { continue }$rNorm = $r.TrimEnd('\','/')if ($expanded -ieq $rNorm -or $expanded -ilike "$rNorm\*") {@@ -971,8 +1122,16 @@ Environment:Write-Host "Note: this also removed the app's WebView data, so the desktop app's session"Write-Host " is gone. A browser session is not affected: its tokens live in the same"Write-Host " localStorage as the API keys below."- Write-Host " No studio.db was found, so any chat history in an install root this run"- Write-Host " did not see is still on disk."+ if ($script:StudioDbKept) {+ # Named, and with no advice to delete it: the gate kept it precisely because it+ # does not look like ours.+ Write-Host " $defaultStudioHome carries no Unsloth install marker, so it was"+ Write-Host " left alone. The studio.db inside it is still there; look at that"+ Write-Host " directory yourself before deciding what to do with it."+ } else {+ Write-Host " No studio.db was found, so any chat history in an install root this run"+ Write-Host " did not see is still on disk."+ }}Write-Host "Note: provider API keys are kept in the browser's localStorage, not in studio.db."Write-Host " Unless you ran Unsloth as the desktop app, clear site data for the"diff --git a/scripts/uninstall.sh b/scripts/uninstall.shindex 211e706ca05..e4a6ed8c2d8 100755--- a/scripts/uninstall.sh+++ b/scripts/uninstall.sh@@ -236,6 +236,8 @@ $_roots_from_conf"# where an assignment would never reach the summary.# remove-failed an rm failed, or a root was skipped while still holding data# db-removed a removed install root actually held studio.db+# db-kept the default root was REFUSED and still holds studio.db. Its own flag, not+# remove-failed: nothing failed, so "remove those paths by hand" is wrong here.# studio.db holds the chat history (backend/storage/studio_db.py), not the provider API keys:# providers_db.py keeps those in the browser's localStorage only. An env-mode install keeps it in# a custom root a bare run cannot discover, so claim the history is gone only if one was deleted.@@ -243,9 +245,11 @@ $_roots_from_conf"_MARKER_DIR=$(mktemp -d 2>/dev/null || true)_REMOVE_FAILED_FLAG=""_DB_REMOVED_FLAG=""+_DB_KEPT_FLAG=""if [ -n "$_MARKER_DIR" ] && [ -d "$_MARKER_DIR" ]; then_REMOVE_FAILED_FLAG="$_MARKER_DIR/remove-failed"_DB_REMOVED_FLAG="$_MARKER_DIR/db-removed"+ _DB_KEPT_FLAG="$_MARKER_DIR/db-kept"fi# `printf`, never `: > "$f"`: `:` is a POSIX special builtin, so a redirection error on it kills a@@ -274,6 +278,15 @@ _cleanup_markers() {}trap _cleanup_markers EXIT+# A removal that got part way can take the sentinels and then fail on a locked child, leaving a+# root the next run's gate would refuse. Put the marker back so a retry recognises it.+_restore_owner_marker() {+ [ -d "$1" ] || return 0+ if [ -e "$1/.unsloth-studio-owned" ] || [ -L "$1/.unsloth-studio-owned" ]; then return 0; fi+ printf '' > "$1/.unsloth-studio-owned" 2>/dev/null || true+ return 0+}+# Remove an install root and record whether its studio.db really went with it. The check runs on# the RESOLVED path: a relocated install (~/.unsloth/studio a symlink to another disk) passes# `-f "$root/studio.db"` through the link, but `rm -rf` unlinks only the link, after which the@@ -305,6 +318,7 @@ _remove_root_recording_db() {fifi_remove_path "$_rrd_root"+ _restore_owner_marker "$_rrd_root"if [ "$_rrd_had_db" = 1 ]; thenif [ -f "$_rrd_db" ]; then# Only the link went, or the delete failed: the data is still on disk.@@ -338,15 +352,91 @@ _xdg_dir() {# Accept as Unsloth root only if an Unsloth sentinel exists (matching install.sh's env-mode# ownership guard). A bare unsloth_studio/ directory is NOT enough: require the install-time owner# marker so a user directory that happens to contain such a folder is safe.+# Is $1 a Python venv? What the gate reads out of one is evidence only if the directory really+# is one; a bare file at that path is somebody else's.+# A sentinel this gate may trust. Deliberately just -f, following links: refusing one that is a+# link, or that sits inside a linked directory, buys nothing here and costs a supported install.+# It buys nothing because anyone who can plant a link at that path can plant a plain file there+# instead, which this has always accepted. It costs a supported install because relocating a+# multi-gigabyte venv with a symlink leaves a REAL marker behind a link, and refusing it strands+# the install, which is the failure this whole gate exists to prevent. The link test belongs in+# install.sh's _claim_sentinel, where following one would TRUNCATE the target rather than read it.+_is_owner_marker() { [ -f "$1" ]; }++# No -L here either, and for the same reason: a relocated venv is still a venv. The leftover scan+# below rejects links on its own, where the name came from a glob rather than from us.+_is_venv_dir() {+ [ -d "$1" ] || return 1+ [ -f "$1/pyvenv.cfg" ] && return 0+ [ -f "$1/bin/python" ] && return 0+ return 1+}++# The exact name an installer gives a moved-aside venv: <prefix>.<stamp>.<pid>[.<n>], with a+# 14-digit stamp or install.sh's "time" date(1) fallback. install.sh keeps every other spelling+# as the user's data (_studio_venv_rollback_must_be_preserved); do not be looser.+_is_installer_leftover_name() {+ _l=${1##*/}+ # Only the rollback name carries a collision counter (install.sh:823); .venv.invalid is+ # written once per run, so it takes no suffix.+ _l_suffix_ok=false+ case "$_l" in+ unsloth_studio.rollback.*) _l=${_l#unsloth_studio.rollback.}; _l_suffix_ok=true ;;+ .venv.invalid.*) _l=${_l#.venv.invalid.} ;;+ *) return 1 ;;+ esac+ _l_rest=${_l#*.}+ [ "$_l_rest" != "$_l" ] || return 1+ _l_stamp=${_l%%.*}+ case "$_l_stamp" in+ time) ;;+ ''|*[!0-9]*) return 1 ;;+ *) [ "${#_l_stamp}" -eq 14 ] || return 1 ;;+ esac+ _l_pid=${_l_rest%%.*}+ case "$_l_pid" in ''|*[!0-9]*) return 1 ;; esac+ _l_suffix=${_l_rest#*.}+ if [ "$_l_suffix" != "$_l_rest" ]; then+ [ "$_l_suffix_ok" = true ] || return 1+ case "$_l_suffix" in ''|*[!0-9]*) return 1 ;; esac+ fi+ return 0+}+_is_studio_root() {_r="$1"+ # $2 = "managed": $_r is the default root install.sh manages, $HOME/.unsloth/studio.+ _managed="${2:-}"[ -n "$_r" ] || return 1- [ -f "$_r/share/studio.conf" ] && return 0- [ -f "$_r/unsloth_studio/.unsloth-studio-owned" ] && return 0+ # install.sh writes the first when it creates the root, before the uv cache and long before+ # the venv, so a partial install identifies itself instead of being guessed at. The last is+ # the legacy venv name, which only install.sh writes.+ _is_owner_marker "$_r/.unsloth-studio-owned" && return 0+ _is_owner_marker "$_r/share/studio.conf" && return 0+ _is_owner_marker "$_r/unsloth_studio/.unsloth-studio-owned" && return 0+ _is_owner_marker "$_r/.venv/.unsloth-studio-owned" && return 0if [ -L "$_r/bin/unsloth" ]; then_t=$(readlink "$_r/bin/unsloth" 2>/dev/null || true)case "$_t" in *unsloth_studio/bin/unsloth) return 0 ;; esacfi+ # All a pre-marker install has left is bin/unsloth inside the venv, pip's console script,+ # which ANY venv with the wheel has: proof only at the managed root, which install.sh:2987+ # also makes the only root that can hold the layout, or a stale UNSLOTH_STUDIO_HOME deletes+ # the project it points at.+ [ "$_managed" = managed ] || return 1+ for _v in unsloth_studio .venv; do+ _is_venv_dir "$_r/$_v" || continue+ [ -f "$_r/$_v/bin/unsloth" ] && return 0+ done+ # An install that died between moving the old venv aside (install.sh:3027, :819) and writing+ # the marker (install.sh:3190) leaves only these, and only install.sh makes either name,+ # always by renaming a venv.+ for _p in "$_r"/unsloth_studio.rollback.* "$_r"/.venv.invalid.*; do+ # Never a link: install.sh refuses to prune a rollback symlink either.+ [ -L "$_p" ] && continue+ _is_installer_leftover_name "$_p" || continue+ _is_venv_dir "$_p" && return 0+ donereturn 1}@@ -557,7 +647,21 @@ _unsloth_uninstall_main() {_remove_path "$_lex_sd_cpp"fidone- _remove_root_recording_db "$HOME/.unsloth/studio"+ # Same gate as a custom root: an ungated run takes a hand-made ~/.unsloth/studio, and then+ # ~/.unsloth via the empty-dir prune below.+ # -e OR -L: -e follows a link and misses a dangling one, which _remove_path would still+ # unlink, so the gate has to see every entry that exists at that path.+ if { [ -e "$HOME/.unsloth/studio" ] || [ -L "$HOME/.unsloth/studio" ]; } \+ && ! _is_studio_root "$HOME/.unsloth/studio" managed; then+ echo " refusing to remove non-Unsloth path: $HOME/.unsloth/studio" >&2+ # A refused CUSTOM root is somebody else's by definition. This is our own default path,+ # where a damaged install can sit, so a studio.db here is chat history.+ if [ -f "$HOME/.unsloth/studio/studio.db" ]; then+ _set_marker "$_DB_KEPT_FLAG"+ fi+ else+ _remove_root_recording_db "$HOME/.unsloth/studio"+ fi# Shared llama.cpp build + cache, siblings of studio in default mode (deleting studio misses# them). No-op in env/custom mode and when absent. A user-set UNSLOTH_LLAMA_CPP_PATH is kept._remove_path "$HOME/.unsloth/llama.cpp"@@ -832,8 +936,16 @@ _unsloth_uninstall_main() {echo "Note: this also removed the app's WebView data, so the desktop app's session is"echo " gone. A browser session is not affected: its tokens live in the same"echo " localStorage as the API keys below."- echo " No studio.db was found, so any chat history in an install root this run"- echo " did not see is still on disk."+ if _marker_set "$_DB_KEPT_FLAG"; then+ # Named, and with no advice to delete it: the gate kept it precisely because it+ # does not look like ours.+ echo " $HOME/.unsloth/studio carries no Unsloth install marker, so it was left"+ echo " alone. The studio.db inside it is still there; look at that directory"+ echo " yourself before deciding what to do with it."+ else+ echo " No studio.db was found, so any chat history in an install root this run"+ echo " did not see is still on disk."+ fifiecho "Note: provider API keys are kept in the browser's localStorage, not in studio.db."echo " Unless you ran Unsloth as the desktop app, clear site data for the"diff --git a/tests/sh/test_uninstall_arg_guard.sh b/tests/sh/test_uninstall_arg_guard.shindex 8978cc8bc0d..5bd55dc885f 100755--- a/tests/sh/test_uninstall_arg_guard.sh+++ b/tests/sh/test_uninstall_arg_guard.sh@@ -80,6 +80,11 @@ make_home() {"$FIXTURE_HOME/.local/share/unsloth" \"$FIXTURE_HOME/.local/bin": > "$FIXTURE_HOME/.unsloth/studio/unsloth_studio/bin/unsloth"+ # What install.sh leaves behind, because the uninstaller's ownership gate reads it before it+ # deletes the root: the marker at install.sh:3190, and the venv the marker sits in.+ : > "$FIXTURE_HOME/.unsloth/studio/unsloth_studio/.unsloth-studio-owned"+ : > "$FIXTURE_HOME/.unsloth/studio/unsloth_studio/pyvenv.cfg"+ : > "$FIXTURE_HOME/.unsloth/studio/unsloth_studio/bin/python": > "$FIXTURE_HOME/.unsloth/studio/auth/.desktop_secret"ln -s "$FIXTURE_HOME/.unsloth/studio/unsloth_studio/bin/unsloth" "$FIXTURE_HOME/.local/bin/unsloth"}diff --git a/tests/sh/test_uninstall_legacy_layout_gate.sh b/tests/sh/test_uninstall_legacy_layout_gate.shnew file mode 100644index 00000000000..ebc5d328209--- /dev/null+++ b/tests/sh/test_uninstall_legacy_layout_gate.sh@@ -0,0 +1,409 @@+#!/bin/bash+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+# _is_studio_root decides whether ~/.unsloth/studio, or a UNSLOTH_STUDIO_HOME root, is recursively+# deleted, so both directions are asserted in both modes: a gate that accepts everything, anywhere,+# passes a one-sided test. The uninstaller body deletes trees, so the gate is sed'd out of it.+set -e++SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+UNINSTALL_SH="$SCRIPT_DIR/../../scripts/uninstall.sh"+INSTALL_SH="$SCRIPT_DIR/../../install.sh"+PASS=0+FAIL=0++_TMP_ROOT=$(mktemp -d)+trap 'rm -rf "$_TMP_ROOT"' EXIT+# Keep $HOME clear of the fixture trees: the gate's siblings consult it.+HOME="$_TMP_ROOT/home"+mkdir -p "$HOME"++# _is_studio_root calls all three helpers, so each comes across or the suite is vacuous.+for _name in _is_owner_marker _is_venv_dir _is_installer_leftover_name _is_studio_root; do+ _fn=$(sed -n "/^$_name() {/,/^}/p" "$UNINSTALL_SH")+ if [ -z "$_fn" ]; then+ echo " FAIL: could not extract $_name from $UNINSTALL_SH"+ exit 1+ fi+ eval "$_fn"+done++# name, expected (own|foreign), mode (managed|custom), then paths; a trailing / makes a dir.+# "managed" is the uninstaller's second argument, for $HOME/.unsloth/studio and nothing else.+check() {+ _name="$1"; _want="$2"; _mode="$3"; shift 3+ _root="$_TMP_ROOT/$(printf '%s' "$_name" | tr -c 'a-zA-Z0-9' '_')"+ mkdir -p "$_root"+ for _rel in "$@"; do+ case "$_rel" in+ */) mkdir -p "$_root/$_rel" ;;+ *) mkdir -p "$_root/$(dirname "$_rel")"; printf 'x' > "$_root/$_rel" ;;+ esac+ done+ case "$_mode" in+ managed) _is_studio_root "$_root" managed ;;+ *) _is_studio_root "$_root" ;;+ esac && _got=own || _got=foreign+ if [ "$_got" = "$_want" ]; then+ echo " PASS: $_name"; PASS=$((PASS+1))+ else+ echo " FAIL: $_name (got $_got, want $_want)"; FAIL=$((FAIL+1))+ fi+}++echo "Layouts Unsloth created at the managed root, which must stay removable:"+check "partial install: the root marker alone" own managed ".unsloth-studio-owned"+# A relocated install is still an install. Moving a multi-gigabyte venv to another disk and+# leaving a symlink behind puts a REAL marker behind a link, and refusing it would strand the+# install this gate exists to keep removable. Refusing links here would also buy nothing: anyone+# who can plant one at these paths can plant a plain file instead, which the gate has always+# taken. The link test belongs in install.sh's claim, where following one TRUNCATES the target.+: > "$_TMP_ROOT/linked_marker_target"+for _lm in ".unsloth-studio-owned" "unsloth_studio/.unsloth-studio-owned" \+ ".venv/.unsloth-studio-owned" "share/studio.conf"; do+ _lmroot="$_TMP_ROOT/lm_$(printf '%s' "$_lm" | tr -c 'a-zA-Z0-9' '_')"+ mkdir -p "$_lmroot/$(dirname "$_lm")"+ : > "$_lmroot/keepme.txt"+ ln -s "$_TMP_ROOT/linked_marker_target" "$_lmroot/$_lm"+ if _is_studio_root "$_lmroot"; then+ echo " PASS: a relocated $_lm is still recognised"; PASS=$((PASS+1))+ else+ echo " FAIL: a relocated $_lm stranded the install"; FAIL=$((FAIL+1))+ fi+done+# ... and the shape a user really produces: the whole venv directory moved and symlinked back.+_lmdir="$_TMP_ROOT/lm_linked_dir"+mkdir -p "$_lmdir" "$_TMP_ROOT/lm_real_venv/bin"+: > "$_TMP_ROOT/lm_real_venv/.unsloth-studio-owned"+: > "$_TMP_ROOT/lm_real_venv/pyvenv.cfg"+: > "$_lmdir/keepme.txt"+ln -s "$_TMP_ROOT/lm_real_venv" "$_lmdir/unsloth_studio"+if _is_studio_root "$_lmdir"; then+ echo " PASS: a relocated venv directory is still recognised"; PASS=$((PASS+1))+else+ echo " FAIL: a relocated venv directory stranded the install"; FAIL=$((FAIL+1))+fi+# The same relocation for a PRE-MARKER install, which reaches the gate by the venv fallback.+_lmpre="$_TMP_ROOT/lm_linked_premarker"+mkdir -p "$_lmpre" "$_TMP_ROOT/lm_pre_venv/bin"+: > "$_TMP_ROOT/lm_pre_venv/pyvenv.cfg"+: > "$_TMP_ROOT/lm_pre_venv/bin/python"+: > "$_TMP_ROOT/lm_pre_venv/bin/unsloth"+ln -s "$_TMP_ROOT/lm_pre_venv" "$_lmpre/.venv"+if _is_studio_root "$_lmpre" managed; then+ echo " PASS: a relocated pre-marker venv is still recognised"; PASS=$((PASS+1))+else+ echo " FAIL: a relocated pre-marker venv stranded the install"; FAIL=$((FAIL+1))+fi+check "current: share/studio.conf" own managed "share/studio.conf"+check "current: unsloth_studio owner marker" own managed "unsloth_studio/.unsloth-studio-owned"+check "legacy .venv carrying the owner marker" own managed ".venv/.unsloth-studio-owned"+check "pre-marker unsloth_studio venv" own managed "unsloth_studio/bin/unsloth" "unsloth_studio/bin/python"+check "pre-marker legacy .venv" own managed ".venv/bin/unsloth" ".venv/bin/python"+check "pre-marker venv proved by pyvenv.cfg alone" own managed ".venv/bin/unsloth" ".venv/pyvenv.cfg"+# An install that died before the marker was written. The root is ours and holds nothing else.+check "partial install: rollback copy only" own managed "unsloth_studio.rollback.20260908120000.4242/pyvenv.cfg"+check "partial install: invalid legacy venv only" own managed ".venv.invalid.20260908120000.4242/pyvenv.cfg"++echo+echo "A custom root proves itself with a marker, wherever the user put it:"+check "custom: the root marker alone" own custom ".unsloth-studio-owned"+check "custom: share/studio.conf" own custom "share/studio.conf"+check "custom: unsloth_studio owner marker" own custom "unsloth_studio/.unsloth-studio-owned"+check "custom: legacy .venv owner marker" own custom ".venv/.unsloth-studio-owned"++echo+echo "Directories that are not ours, which must stay refused:"+check "a bare project venv" foreign managed ".venv/bin/python"+check "a venv merely NAMED unsloth_studio" foreign managed "unsloth_studio/bin/python"+# bin/unsloth is pip's console script for the unsloth distribution, not just any console script.+check "a venv with an unrelated console script" foreign managed ".venv/bin/black" ".venv/bin/python"+check "a hand-made scratch directory" foreign managed "notes.txt"+check "an empty directory" foreign managed+# Why the split exists: pip writes bin/unsloth into ANY venv with the wheel.+check "a project venv with unsloth pip-installed, as a custom root" foreign custom \+ ".venv/bin/unsloth" ".venv/bin/python" "pyproject.toml" "src/main.py"+check "a project whose venv is NAMED unsloth_studio, as a custom root" foreign custom \+ "unsloth_studio/bin/unsloth" "unsloth_studio/bin/python"+check "a partial-install leftover at a custom root" foreign custom \+ ".venv.invalid.20260908120000.4242/pyvenv.cfg"+# The literal glob must not match itself when the directory holds nothing.+check "a directory named like the glob is not conjured" foreign managed "notes.txt"+# The name alone is not proof: only a renamed venv carries the shape.+check "a FILE named like a leftover" foreign managed ".venv.invalid.20260908120000.4242"+check "an empty directory named like a leftover" foreign managed "unsloth_studio.rollback.20260908120000.4242/"+check "a leftover-named directory holding the user's own files" foreign managed \+ ".venv.invalid.20260908120000.4242/notes.txt"+# bin/unsloth is only pip's console script when it is inside a venv; on its own it is a file.+check "a console script with no venv around it" foreign managed ".venv/bin/unsloth"+check "the same under a directory named unsloth_studio" foreign managed "unsloth_studio/bin/unsloth"+# install.sh keeps any rollback outside <stamp>.<pid>[.<n>] as user data; do not be looser.+check "a rollback-named venv outside the installer's format" foreign managed \+ "unsloth_studio.rollback.user-data/pyvenv.cfg"+check "an invalid-venv name outside the installer's format" foreign managed \+ ".venv.invalid.backup/pyvenv.cfg"+check "a rollback name with a non-numeric pid" foreign managed \+ "unsloth_studio.rollback.20260908120000.mine/pyvenv.cfg"+check "a rollback name with a short stamp" foreign managed \+ "unsloth_studio.rollback.2026.4242/pyvenv.cfg"+# Only the rollback name has a collision counter; .venv.invalid is written once per run.+check "an invalid-venv name with a rollback-style suffix" foreign managed \+ ".venv.invalid.20260908120000.4242.2/pyvenv.cfg"+# install.sh only ever renames a directory into place, so a link points at a venv it did not put.+_linked="$_TMP_ROOT/linked_leftover"+mkdir -p "$_linked" "$_TMP_ROOT/somebodys_venv"+: > "$_TMP_ROOT/somebodys_venv/pyvenv.cfg"+: > "$_linked/keepme.txt"+ln -s "$_TMP_ROOT/somebodys_venv" "$_linked/unsloth_studio.rollback.20260908120000.4242"+if _is_studio_root "$_linked" managed; then+ echo " FAIL: a symlinked leftover was claimed"; FAIL=$((FAIL+1))+else+ echo " PASS: a symlinked leftover is refused"; PASS=$((PASS+1))+fi+check "partial install: rollback with a numeric suffix" own managed \+ "unsloth_studio.rollback.20260908120000.4242.2/pyvenv.cfg"+check "partial install: install.sh's 'time' date fallback" own managed \+ ".venv.invalid.time.4242/pyvenv.cfg"+# install.sh claims the root before it creates the uv cache, so the cache is not a sentinel.+check "a uv cache with no root marker" foreign managed "cache/uv/" "notes.txt"+check "the same at a custom root" foreign custom "cache/uv/"++echo+echo "Edge cases:"+if _is_studio_root "" managed; then+ echo " FAIL: an empty path was claimed"; FAIL=$((FAIL+1))+else+ echo " PASS: an empty path is refused"; PASS=$((PASS+1))+fi+if _is_studio_root "$_TMP_ROOT/nothing-here" managed; then+ echo " FAIL: a missing path was claimed"; FAIL=$((FAIL+1))+else+ echo " PASS: a missing path is refused"; PASS=$((PASS+1))+fi+_spaced="$_TMP_ROOT/a dir with spaces/studio"+mkdir -p "$_spaced/unsloth_studio"+printf 'x' > "$_spaced/unsloth_studio/.unsloth-studio-owned"+if _is_studio_root "$_spaced"; then+ echo " PASS: a path containing spaces is handled"; PASS=$((PASS+1))+else+ echo " FAIL: a path containing spaces was refused"; FAIL=$((FAIL+1))+fi++# The other half of the question: install.sh decides when to WRITE the marker this gate reads,+# and claiming a workspace the installer is about to refuse hands it to the uninstaller.+# A removal that took the sentinels and then failed must leave the root identifiable, or the+# retry it asks for is refused.+echo+echo "After a partial removal:"+_fn=$(sed -n '/^_restore_owner_marker() {/,/^}/p' "$UNINSTALL_SH")+if [ -z "$_fn" ]; then+ echo " FAIL: could not extract _restore_owner_marker"; FAIL=$((FAIL+1))+else+ eval "$_fn"+ _partial="$_TMP_ROOT/partial_removal"+ mkdir -p "$_partial/locked"+ : > "$_partial/locked/held.bin"+ _restore_owner_marker "$_partial"+ if _is_studio_root "$_partial" managed; then+ echo " PASS: a half-removed root is still recognised on the next run"; PASS=$((PASS+1))+ else+ echo " FAIL: a half-removed root is stranded"; FAIL=$((FAIL+1))+ fi+ _gone="$_TMP_ROOT/partial_removal_gone"+ _restore_owner_marker "$_gone"+ if [ -e "$_gone" ]; then+ echo " FAIL: a fully removed root was recreated"; FAIL=$((FAIL+1))+ else+ echo " PASS: a fully removed root is not recreated"; PASS=$((PASS+1))+ fi+fi++echo+echo "Who the installer is allowed to claim:"+# _claim_studio_root calls _claim_sentinel, so both come across or every claim below is vacuous.+_fn=""+for _cname in _claim_sentinel _claim_studio_root; do+ _cfn=$(sed -n "/^$_cname() {/,/^}/p" "$INSTALL_SH")+ if [ -z "$_cfn" ]; then+ echo " FAIL: could not extract $_cname from $INSTALL_SH"; FAIL=$((FAIL+1)); _fn=""; break+ fi+ _fn="$_fn+$_cfn"+done+if [ -z "$_fn" ]; then+ :+else+ eval "$_fn"+ # name, expected (claimed|left), redirect mode, then paths.+ claim_check() {+ _cname="$1"; _cwant="$2"; _STUDIO_HOME_REDIRECT="$3"; shift 3+ STUDIO_HOME="$_TMP_ROOT/claim_$(printf '%s' "$_cname" | tr -c 'a-zA-Z0-9' '_')"+ VENV_DIR="$STUDIO_HOME/unsloth_studio"+ mkdir -p "$STUDIO_HOME"+ for _crel in "$@"; do+ mkdir -p "$STUDIO_HOME/$(dirname "$_crel")"+ : > "$STUDIO_HOME/$_crel"+ done+ _claim_studio_root+ if [ -f "$STUDIO_HOME/.unsloth-studio-owned" ]; then _cgot=claimed; else _cgot=left; fi+ if [ "$_cgot" = "$_cwant" ]; then+ echo " PASS: $_cname"; PASS=$((PASS+1))+ else+ echo " FAIL: $_cname (got $_cgot, want $_cwant)"; FAIL=$((FAIL+1))+ fi+ }+ claim_check "the default root, always" claimed default+ claim_check "an empty custom root" claimed env+ claim_check "a custom root already carrying our marker" claimed env "unsloth_studio/.unsloth-studio-owned"+ claim_check "a custom root with share/studio.conf" claimed env "share/studio.conf"+ # The case: the venv-step guard refuses this root, so the claim must not run ahead of it.+ claim_check "somebody's workspace" left env "pyproject.toml" "src/main.py"+ claim_check "somebody's workspace with a venv of their own" left env "unsloth_studio/pyvenv.cfg"+ # Any file of that name. The uninstaller reads it only as a symlink into the venv.+ claim_check "a workspace holding a plain bin/unsloth" left env "bin/unsloth" "notes.txt"+ # A LINKED share or unsloth_studio holding a genuine marker: -L answers for the file only.+ for _cl in "share/studio.conf" "unsloth_studio/.unsloth-studio-owned"; do+ _cldir=$(dirname "$_cl")+ STUDIO_HOME="$_TMP_ROOT/claim_linked_$(printf '%s' "$_cl" | tr -c 'a-zA-Z0-9' '_')"+ # shellcheck disable=SC2034 # read by the extracted _claim_studio_root+ VENV_DIR="$STUDIO_HOME/unsloth_studio"+ _STUDIO_HOME_REDIRECT="env"+ _clreal="$STUDIO_HOME.real"+ mkdir -p "$STUDIO_HOME" "$_clreal"+ : > "$_clreal/$(basename "$_cl")"+ : > "$STUDIO_HOME/notes.txt"+ ln -s "$_clreal" "$STUDIO_HOME/$_cldir"+ _claim_studio_root+ if [ -f "$STUDIO_HOME/.unsloth-studio-owned" ]; then+ echo " FAIL: a linked $_cldir got the workspace claimed"; FAIL=$((FAIL+1))+ else+ echo " PASS: a linked $_cldir is not ownership proof"; PASS=$((PASS+1))+ fi+ done++ # A link named like our marker: -f follows it, skipping the emptiness test.+ STUDIO_HOME="$_TMP_ROOT/claim_linked_marker"+ # shellcheck disable=SC2034 # read by the extracted _claim_studio_root+ VENV_DIR="$STUDIO_HOME/unsloth_studio"+ _STUDIO_HOME_REDIRECT="env"+ mkdir -p "$STUDIO_HOME"+ : > "$_TMP_ROOT/claim_linked_marker_target"+ : > "$STUDIO_HOME/notes.txt"+ ln -s "$_TMP_ROOT/claim_linked_marker_target" "$STUDIO_HOME/.unsloth-studio-owned"+ _claim_studio_root+ if [ -L "$STUDIO_HOME/.unsloth-studio-owned" ]; then+ echo " PASS: a linked marker is not read as proof, and is left as it was"; PASS=$((PASS+1))+ else+ echo " FAIL: a linked marker was replaced with a real one"; FAIL=$((FAIL+1))+ fi++ # The globs ARE the emptiness test, so `sh -f install.sh` would read every workspace as empty.+ STUDIO_HOME="$_TMP_ROOT/claim_noglob"+ VENV_DIR="$STUDIO_HOME/unsloth_studio"+ _STUDIO_HOME_REDIRECT="env"+ mkdir -p "$STUDIO_HOME"+ : > "$STUDIO_HOME/notes.txt"+ set -f+ _claim_studio_root+ set +f+ if [ -f "$STUDIO_HOME/.unsloth-studio-owned" ]; then+ echo " FAIL: with globbing off, a workspace read as empty and was claimed"; FAIL=$((FAIL+1))+ else+ echo " PASS: globbing off does not make a workspace look empty"; PASS=$((PASS+1))+ fi+ case $- in *f*) echo " FAIL: the scan left globbing disabled"; FAIL=$((FAIL+1)) ;;+ *) echo " PASS: and the caller's globbing setting is restored"; PASS=$((PASS+1)) ;;+ esac++ # Writable and searchable but not readable: the globs cannot enumerate it.+ STUDIO_HOME="$_TMP_ROOT/claim_unreadable"+ # shellcheck disable=SC2034 # read by the extracted _claim_studio_root+ VENV_DIR="$STUDIO_HOME/unsloth_studio"+ _STUDIO_HOME_REDIRECT="env"+ mkdir -p "$STUDIO_HOME"+ : > "$STUDIO_HOME/notes.txt"+ chmod 300 "$STUDIO_HOME"+ _claim_studio_root+ chmod 700 "$STUDIO_HOME"+ if [ -f "$STUDIO_HOME/.unsloth-studio-owned" ]; then+ echo " FAIL: an unreadable workspace read as empty and was claimed"; FAIL=$((FAIL+1))+ else+ echo " PASS: an unreadable workspace is treated as occupied"; PASS=$((PASS+1))+ fi++ # Called twice per install: the second call must not unlink a marker the first one wrote.+ STUDIO_HOME="$_TMP_ROOT/claim_twice"+ VENV_DIR="$STUDIO_HOME/unsloth_studio"+ _STUDIO_HOME_REDIRECT="default"+ mkdir -p "$STUDIO_HOME"+ _claim_studio_root+ printf 'first' > "$STUDIO_HOME/.unsloth-studio-owned"+ _claim_studio_root+ if [ "$(cat "$STUDIO_HOME/.unsloth-studio-owned")" = "first" ]; then+ echo " PASS: a second claim leaves a valid marker alone"; PASS=$((PASS+1))+ else+ echo " FAIL: a second claim rewrote a valid marker"; FAIL=$((FAIL+1))+ fi++ # A root we cannot write holding a link to a target we can: rm fails, and writing truncates.+ STUDIO_HOME="$_TMP_ROOT/claim_ro_root"+ # shellcheck disable=SC2034 # read by the extracted _claim_studio_root+ VENV_DIR="$STUDIO_HOME/unsloth_studio"+ _STUDIO_HOME_REDIRECT="default"+ mkdir -p "$STUDIO_HOME"+ printf 'precious' > "$_TMP_ROOT/claim_ro_target"+ ln -s "$_TMP_ROOT/claim_ro_target" "$STUDIO_HOME/.unsloth-studio-owned"+ chmod 500 "$STUDIO_HOME"+ _claim_studio_root+ chmod 700 "$STUDIO_HOME"+ if [ "$(cat "$_TMP_ROOT/claim_ro_target")" = "precious" ]; then+ echo " PASS: an unremovable link is not written through"; PASS=$((PASS+1))+ else+ echo " FAIL: an unremovable link had its target truncated"; FAIL=$((FAIL+1))+ fi++ # A symlink at the marker path: the redirection would follow it and truncate the target.+ STUDIO_HOME="$_TMP_ROOT/claim_symlink"+ # shellcheck disable=SC2034 # read by the extracted _claim_studio_root+ VENV_DIR="$STUDIO_HOME/unsloth_studio"+ _STUDIO_HOME_REDIRECT="default"+ mkdir -p "$STUDIO_HOME"+ printf 'precious' > "$_TMP_ROOT/claim_symlink_target"+ ln -s "$_TMP_ROOT/claim_symlink_target" "$STUDIO_HOME/.unsloth-studio-owned"+ _claim_studio_root+ if [ "$(cat "$_TMP_ROOT/claim_symlink_target")" = "precious" ]; then+ echo " PASS: a symlinked marker path does not truncate its target"; PASS=$((PASS+1))+ else+ echo " FAIL: a symlinked marker path truncated its target"; FAIL=$((FAIL+1))+ fi+ if [ -f "$STUDIO_HOME/.unsloth-studio-owned" ] && [ ! -L "$STUDIO_HOME/.unsloth-studio-owned" ]; then+ echo " PASS: and the marker is a regular file afterwards"; PASS=$((PASS+1))+ else+ echo " FAIL: the marker is still a link"; FAIL=$((FAIL+1))+ fi+fi++# A first install that dies after creating unsloth_studio leaves an occupied venv with no+# in-venv marker, so the retry guard has to read the root marker the same run wrote. Structural:+# the guard is a condition in the middle of the install.+_guard=$(sed -n '/why: matching guard to the .venv branch below/,/Move it aside or choose an empty/p' "$INSTALL_SH")+# ... the same way the claim writes it, or a link gets a foreign workspace past the guard.+_guard_pat2="_claim_sentinel \"[\$]STUDIO_HOME/[.]unsloth-studio-owned\""+if printf '%s' "$_guard" | grep -q "$_guard_pat2"; then+ echo " PASS: and through _claim_sentinel, not -f"; PASS=$((PASS+1))+else+ echo " FAIL: the retry guard reads the root marker with -f, which follows a link"; FAIL=$((FAIL+1))+fi+# Bracketed so the dollar stays a character: the guard's SOURCE text is what is searched.+_guard_pat="[\$]STUDIO_HOME/[.]unsloth-studio-owned"+if [ -z "$_guard" ]; then+ echo " FAIL: could not find install.sh's env-mode replacement guard"; FAIL=$((FAIL+1))+elif printf '%s' "$_guard" | grep -q "$_guard_pat"; then+ echo " PASS: the retry guard reads the root marker"; PASS=$((PASS+1))+else+ echo " FAIL: the retry guard ignores the root marker install.sh just wrote"; FAIL=$((FAIL+1))+fi++echo+echo "Results: $PASS passed, $FAIL failed"+[ "$FAIL" -eq 0 ]diff --git a/tests/sh/test_uninstall_sd_cpp_custom_root.sh b/tests/sh/test_uninstall_sd_cpp_custom_root.shindex 408f4371140..4b06cfb5a3f 100755--- a/tests/sh/test_uninstall_sd_cpp_custom_root.sh+++ b/tests/sh/test_uninstall_sd_cpp_custom_root.sh@@ -29,11 +29,14 @@ assert_dir() { _l="$1"; [ -d "$2" ] && { echo " PASS: $_l"; PASS=$((PASS+1));HELPERS_FILE=$(mktemp -p "$_TMP_ROOT"){sed -n '/^_remove_path() {/,/^}/p' "$UNINSTALL_SH"+ sed -n '/^_is_owner_marker() {/,/^}/p' "$UNINSTALL_SH"+ sed -n '/^_is_venv_dir() {/,/^}/p' "$UNINSTALL_SH"sed -n '/^_is_studio_root() {/,/^}/p' "$UNINSTALL_SH"sed -n '/^_is_unsafe_root() {/,/^}/p' "$UNINSTALL_SH"# The loop removes roots through this wrapper; without it and its marker helper the# fragment dies with "command not found" and every assertion below is vacuous.sed -n '/^_set_marker() {/,/^}/p' "$UNINSTALL_SH"+ sed -n '/^_restore_owner_marker() {/,/^}/p' "$UNINSTALL_SH"sed -n '/^_remove_root_recording_db() {/,/^}/p' "$UNINSTALL_SH"# The owned-root lister that decides which sd-servers are pkilled before a tree is deleted.sed -n '/^_owned_sd_cpp_roots() {/,/^}/p' "$UNINSTALL_SH"@@ -41,6 +44,10 @@ HELPERS_FILE=$(mktemp -p "$_TMP_ROOT")sed -n '/^_sd_cpp_sibling_bases() {/,/^}/p' "$UNINSTALL_SH"} > "$HELPERS_FILE"grep -q '_owned_sd_cpp_roots' "$HELPERS_FILE" || { echo "FAIL: helpers missing _owned_sd_cpp_roots"; exit 1; }+# _is_studio_root's own helpers, or every root reads as foreign and nothing below is removed.+for _needed in _is_owner_marker _is_venv_dir _restore_owner_marker; do+ grep -q "^$_needed() {" "$HELPERS_FILE" || { echo "FAIL: helpers missing $_needed"; exit 1; }+donegrep -q '_sd_cpp_sibling_bases() {' "$HELPERS_FILE" || { echo "FAIL: helpers missing _sd_cpp_sibling_bases"; exit 1; }# Both blocks sit inside the main removal function, so they are indented: anchor on optional# leading whitespace, never on column 0, or the range matches nothing and every assertion belowdiff --git a/tests/sh/test_uninstall_webview_data.sh b/tests/sh/test_uninstall_webview_data.shindex 7867f31c178..bc07df7048e 100755--- a/tests/sh/test_uninstall_webview_data.sh+++ b/tests/sh/test_uninstall_webview_data.sh@@ -566,6 +566,58 @@ for _case in dbremoved nodb; doesacdone+# ── 3j7. A default root the ownership gate refuses is skipped, not removed, so a studio.db+# sitting in it is still on disk. Unlike a refused CUSTOM root, which is somebody else's by+# definition, this is our own path: the summary must not answer "No studio.db was found". ──+H=$(new_home)+mkdir -p "$H/.unsloth/studio"+: > "$H/.unsloth/studio/studio.db"+_out=$(run_uninstall_out "$H" Linux)+# The refusal goes to stderr, like every other one in the script, so ask for it separately.+_err=$(printf '#!/bin/sh\necho Linux\n' > "$STUB_BIN/uname"; chmod +x "$STUB_BIN/uname";+ env -u UNSLOTH_STUDIO_HOME -u STUDIO_HOME UNSLOTH_APPLICATIONS_DIR="$APPS_DIR" \+ HOME="$H" PATH="$STUB_BIN:$PATH" sh "$UNINSTALL_SH" 2>&1 >/dev/null)+case "$_err" in+ *"refusing to remove non-Unsloth path"*)+ echo " PASS: refused default root: says it refused"; PASS=$((PASS+1)) ;;+ *) echo " FAIL: refused default root: never says it refused"; FAIL=$((FAIL+1)) ;;+esac+if [ -f "$H/.unsloth/studio/studio.db" ]; then+ echo " PASS: refused default root: the database survived"; PASS=$((PASS+1))+else+ echo " FAIL: refused default root: the database was removed"; FAIL=$((FAIL+1))+fi+case "$_out" in+ *"No studio.db was found"*)+ echo " FAIL: refused default root: claimed no studio.db was found"; FAIL=$((FAIL+1)) ;;+ *) echo " PASS: refused default root: no claim that none was found"; PASS=$((PASS+1)) ;;+esac+case "$_out" in+ *"carries no Unsloth install marker"*)+ echo " PASS: refused default root: names the kept directory"; PASS=$((PASS+1)) ;;+ *) echo " FAIL: refused default root: never names the kept directory"; FAIL=$((FAIL+1)) ;;+esac+# It was refused BECAUSE it is not ours, so the generic "remove those paths by hand" advice+# would undo the point of the gate.+case "$_out" in+ *"those paths by hand"*)+ echo " FAIL: refused default root: told the reader to delete a foreign directory"+ FAIL=$((FAIL+1)) ;;+ *) echo " PASS: refused default root: no advice to delete it"; PASS=$((PASS+1)) ;;+esac++# ── 3j8. A dangling symlink at ~/.unsloth/studio is still an entry at that path: -e follows the+# link and misses it, while _remove_path unlinks it as present. ──+H=$(new_home)+mkdir -p "$H/.unsloth"+ln -s "$H/.unsloth/nowhere" "$H/.unsloth/studio"+run_uninstall "$H" Linux+if [ -L "$H/.unsloth/studio" ]; then+ echo " PASS: a dangling symlink at the default root is refused, not unlinked"; PASS=$((PASS+1))+else+ echo " FAIL: a dangling symlink at the default root was removed"; FAIL=$((FAIL+1))+fi+# ── 3k. _set_marker must survive a write it cannot perform. 3i only proves the mktemp guard,# since an empty marker path never runs the redirection. This drives it directly: the marker# dir exists at startup and is gone by the write, as an operator clearing /tmp mid-run woulddiff --git a/tests/studio/test_uninstall_legacy_layout_gate.ps1 b/tests/studio/test_uninstall_legacy_layout_gate.ps1new file mode 100644index 00000000000..03c6edcb9cd--- /dev/null+++ b/tests/studio/test_uninstall_legacy_layout_gate.ps1@@ -0,0 +1,343 @@+#!/usr/bin/env pwsh+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+# The ownership gate must still recognise the layouts older installers left: on Windows every+# sentinel a root can show postdates the bin\ shim dir, while install.ps1 still migrates .venv.+# What is INSIDE a venv proves ownership only at the managed root, so every case names its mode.+# The uninstaller body writes to the registry, so the helpers are lifted out by AST.+# Run: pwsh -NoProfile -File tests/studio/test_uninstall_legacy_layout_gate.ps1++$ErrorActionPreference = "Stop"+$repoRoot = (Resolve-Path ([System.IO.Path]::Combine($PSScriptRoot, "..", ".."))).Path+$ps1Path = [System.IO.Path]::Combine($repoRoot, "scripts", "uninstall.ps1")++$failures = 0+function Check($name, $cond) {+ if ($cond) { Write-Host " PASS $name" }+ else { Write-Host " FAIL $name" -ForegroundColor Red; $script:failures++ }+}++$tokens = $null; $errors = $null+$ast = [System.Management.Automation.Language.Parser]::ParseFile($ps1Path, [ref]$tokens, [ref]$errors)+Check "uninstall.ps1 parses" ($null -eq $errors -or $errors.Count -eq 0)++# _IsStudioRoot calls the three helpers below, so all of them must come across or the suite is+# vacuous.+$allFns = $ast.FindAll({+ param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst]+ }, $true)+foreach ($name in @("_IsUnslothCmdShim", "_IsOwnerMarker", "_IsVenvDir", "_IsInstallerLeftoverName", "_IsStudioRoot")) {+ $fn = $allFns | Where-Object { $_.Name -eq $name } | Select-Object -First 1+ if (-not $fn) {+ Write-Host " FAIL $name not found in uninstall.ps1" -ForegroundColor Red+ exit 1+ }+ . ([scriptblock]::Create($fn.Extent.Text))+}++$shimText = @"+@echo off+rem unsloth-studio-managed-launcher+"%~dp0..\unsloth_studio\Scripts\python.exe" -X utf8 -c "from unsloth_cli import app" %*+"@++$tmp = Join-Path ([System.IO.Path]::GetTempPath()) ("unsloth-legacy-gate-" + [System.Guid]::NewGuid().ToString("N"))+New-Item -ItemType Directory -Path $tmp -Force | Out-Null+try {+ function Make([string]$Name, [string[]]$Files) {+ $root = Join-Path $tmp $Name+ New-Item -ItemType Directory -Path $root -Force | Out-Null+ foreach ($f in $Files) {+ $p = Join-Path $root $f+ New-Item -ItemType Directory -Path ([System.IO.Path]::GetDirectoryName($p)) -Force | Out-Null+ if ($f -eq "bin\unsloth.cmd") { Set-Content -LiteralPath $p -Value $shimText }+ else { Set-Content -LiteralPath $p -Value "x" }+ }+ # Every one of these stands for an install that holds chat history.+ Set-Content -LiteralPath (Join-Path $root "studio.db") -Value "chat history"+ return $root+ }++ # -ManagedDefaultRoot is passed for %USERPROFILE%\.unsloth\studio and for nothing else.+ Check "partial install: the root marker alone" `+ (_IsStudioRoot (Make "root-marker" @(".unsloth-studio-owned")) -ManagedDefaultRoot)+ Check "the root marker proves a custom root too" `+ (_IsStudioRoot (Make "custom-root-marker" @(".unsloth-studio-owned")))+ # A relocated install is still an install. Moving a multi-gigabyte venv to another drive and+ # leaving a junction behind puts a REAL marker behind one, and refusing it would strand the+ # install this gate exists to keep removable. Refusing links here would also buy nothing:+ # anyone who can plant one at these paths can plant a plain file instead. The link test+ # belongs in install.ps1's claim, where following one TRUNCATES the target.+ $markTarget = Join-Path $tmp "linked-marker-target.txt"+ Set-Content -LiteralPath $markTarget -Value "x"+ # (subdirectory, marker) rather than one backslash path: New-Item -Path treats a backslash+ # as an escape off Windows, so a combined literal would not create the link on the Linux row.+ foreach ($pair in @(@("", ".unsloth-studio-owned"), @("unsloth_studio", ".unsloth-studio-owned"),+ @(".venv", ".unsloth-studio-owned"), @("share", "studio.conf"))) {+ $label = (($pair | Where-Object { $_ }) -join "/")+ $r = Make ("lm-" + ($label -replace '[^A-Za-z0-9]', '_')) @("keepme.txt")+ $at = $r+ if ($pair[0]) { $at = Join-Path $r $pair[0]; New-Item -ItemType Directory -Path $at -Force | Out-Null }+ $ok = $null+ try { $ok = New-Item -ItemType SymbolicLink -Path (Join-Path $at $pair[1]) -Target $markTarget -ErrorAction Stop } catch { $ok = $null }+ if ($ok) { Check "a relocated $label is still recognised" (_IsStudioRoot $r -ManagedDefaultRoot) }+ else { Write-Host " SKIP no symlink could be created for $label" }+ }+ # ... and the shape a user really produces: the whole venv directory moved and linked back.+ $realVenvDir = Make "lm-real-venv" @(".unsloth-studio-owned", "pyvenv.cfg")+ $linkedDir = Make "lm-linked-dir" @("keepme.txt")+ $dl = $null+ foreach ($kind in @("Junction", "SymbolicLink")) {+ try {+ $dl = New-Item -ItemType $kind -Path (Join-Path $linkedDir "unsloth_studio") -Target $realVenvDir -ErrorAction Stop+ if ($dl -and -not [string]::IsNullOrWhiteSpace(@($dl.Target)[0])) { break }+ } catch { $dl = $null }+ }+ if ($dl -and -not [string]::IsNullOrWhiteSpace(@($dl.Target)[0])) {+ Check "a relocated venv directory is still recognised" (_IsStudioRoot $linkedDir -ManagedDefaultRoot)+ # The same relocation for a PRE-MARKER install, which reaches the gate by the fallback.+ $preVenv = Make "lm-pre-venv" @("pyvenv.cfg", "Scripts\python.exe", "Scripts\unsloth.exe")+ $preRoot = Make "lm-linked-premarker" @("keepme.txt")+ $dl2 = $null+ foreach ($kind in @("Junction", "SymbolicLink")) {+ try {+ $dl2 = New-Item -ItemType $kind -Path (Join-Path $preRoot ".venv") -Target $preVenv -ErrorAction Stop+ if ($dl2 -and -not [string]::IsNullOrWhiteSpace(@($dl2.Target)[0])) { break }+ } catch { $dl2 = $null }+ }+ if ($dl2) { Check "a relocated pre-marker venv is still recognised" (_IsStudioRoot $preRoot -ManagedDefaultRoot) }+ } else {+ Write-Host " SKIP no reparse point could be created here"+ }+ Check "current layout (venv owner marker)" `+ (_IsStudioRoot (Make "cur-marker" @("unsloth_studio\.unsloth-studio-owned")) -ManagedDefaultRoot)+ Check "shim .exe" `+ (_IsStudioRoot (Make "cur-exe" @("bin\unsloth.exe")) -ManagedDefaultRoot)+ Check "shim .cmd alone, when a policy quarantined the .exe" `+ (_IsStudioRoot (Make "cur-cmd" @("bin\unsloth.cmd")) -ManagedDefaultRoot)++ Check "legacy .venv carrying our owner marker" `+ (_IsStudioRoot (Make "old-marker" @(".venv\.unsloth-studio-owned", ".venv\Scripts\python.exe")) -ManagedDefaultRoot)+ Check "legacy .venv carrying the unsloth console script" `+ (_IsStudioRoot (Make "old-cli" @(".venv\Scripts\python.exe", ".venv\Scripts\unsloth.exe")) -ManagedDefaultRoot)+ Check "pre-marker unsloth_studio venv carrying the unsloth console script" `+ (_IsStudioRoot (Make "pre-marker" @("unsloth_studio\Scripts\python.exe", "unsloth_studio\Scripts\unsloth.exe")) -ManagedDefaultRoot)+ # Antivirus takes the .exe out of a venv that still runs, leaving nothing but the package.+ Check "pre-marker venv whose unsloth.exe antivirus quarantined" `+ (_IsStudioRoot (Make "quarantined" @(".venv\Scripts\python.exe", ".venv\Lib\site-packages\unsloth_cli\__init__.py")) -ManagedDefaultRoot)+ Check "pre-marker venv proved by pyvenv.cfg alone" `+ (_IsStudioRoot (Make "cfg-only" @(".venv\pyvenv.cfg", ".venv\Scripts\unsloth.exe")) -ManagedDefaultRoot)++ # An install that died before the marker was written. The root is ours and holds nothing else.+ Check "partial install: rollback copy only" `+ (_IsStudioRoot (Make "partial-rollback" @("unsloth_studio.rollback.20260908120000.4242\pyvenv.cfg")) -ManagedDefaultRoot)+ Check "partial install: invalid legacy venv only" `+ (_IsStudioRoot (Make "partial-invalid" @(".venv.invalid.20260908120000.4242\pyvenv.cfg")) -ManagedDefaultRoot)+ Check "partial install: rollback with a numeric suffix" `+ (_IsStudioRoot (Make "partial-suffix" @("unsloth_studio.rollback.20260908120000.4242.2\pyvenv.cfg")) -ManagedDefaultRoot)+ # install.ps1 claims the root before the uv cache, so the cache is not a sentinel.+ $uvOnly = Make "uvcache-only" @("notes.md")+ New-Item -ItemType Directory -Path (Join-Path $uvOnly "cache\uv") -Force | Out-Null+ Check "a uv cache with no root marker is refused" (-not (_IsStudioRoot $uvOnly -ManagedDefaultRoot))+ Check "the same at a custom root is refused" (-not (_IsStudioRoot $uvOnly))++ # A marker is proof wherever the root sits; it is the only thing a custom root can offer.+ Check "a custom root with the venv owner marker" `+ (_IsStudioRoot (Make "custom-marker" @("unsloth_studio\.unsloth-studio-owned")))+ Check "a custom root with share\studio.conf" `+ (_IsStudioRoot (Make "custom-conf" @("share\studio.conf")))++ Check "a hand-made directory is refused" `+ (-not (_IsStudioRoot (Make "scratch" @("notes.md")) -ManagedDefaultRoot))+ Check "an ordinary project venv is refused" `+ (-not (_IsStudioRoot (Make "plain-venv" @(".venv\Scripts\python.exe", "notes.md")) -ManagedDefaultRoot))+ Check "a venv merely NAMED unsloth_studio is refused" `+ (-not (_IsStudioRoot (Make "named-venv" @("unsloth_studio\Scripts\python.exe")) -ManagedDefaultRoot))+ Check "somebody else's bin\unsloth.cmd is refused" `+ (-not (_IsStudioRoot (Make "foreign-cmd" @("bin\python.exe")) -ManagedDefaultRoot))+ # Why the flag exists: pip writes Scripts\unsloth.exe into ANY venv with the wheel.+ Check "a project venv with unsloth pip-installed is refused as a custom root" `+ (-not (_IsStudioRoot (Make "custom-project" @(".venv\Scripts\python.exe", ".venv\Scripts\unsloth.exe", "pyproject.toml"))))+ Check "that project's site-packages is refused as a custom root too" `+ (-not (_IsStudioRoot (Make "custom-pkg" @(".venv\Scripts\python.exe", ".venv\Lib\site-packages\unsloth_cli\__init__.py"))))+ Check "a partial-install leftover is refused at a custom root" `+ (-not (_IsStudioRoot (Make "custom-partial" @(".venv.invalid.20260908120000.4242\pyvenv.cfg"))))+ # The name alone is not proof: only a renamed venv carries the shape.+ Check "a FILE named like a leftover is refused" `+ (-not (_IsStudioRoot (Make "leftover-file" @(".venv.invalid.20260908120000.4242")) -ManagedDefaultRoot))+ $emptyLeftover = Make "leftover-empty" @()+ New-Item -ItemType Directory -Path (Join-Path $emptyLeftover "unsloth_studio.rollback.20260908120000.4242") -Force | Out-Null+ Check "an empty directory named like a leftover is refused" `+ (-not (_IsStudioRoot $emptyLeftover -ManagedDefaultRoot))+ Check "a leftover-named directory holding the user's own files is refused" `+ (-not (_IsStudioRoot (Make "leftover-user" @(".venv.invalid.20260908120000.4242\notes.md")) -ManagedDefaultRoot))+ # Scripts\unsloth.exe and site-packages are only pip's work when they are inside a venv.+ Check "a console script with no venv around it is refused" `+ (-not (_IsStudioRoot (Make "loose-exe" @(".venv\Scripts\unsloth.exe")) -ManagedDefaultRoot))+ Check "a site-packages tree with no interpreter is refused" `+ (-not (_IsStudioRoot (Make "loose-pkg" @("unsloth_studio\Lib\site-packages\unsloth\__init__.py")) -ManagedDefaultRoot))+ # install.ps1 keeps any rollback outside <stamp>.<pid>[.<n>] as user data.+ Check "a rollback-named venv outside the installer's format is refused" `+ (-not (_IsStudioRoot (Make "leftover-freeform" @("unsloth_studio.rollback.user-data\pyvenv.cfg")) -ManagedDefaultRoot))+ Check "an invalid-venv name outside the installer's format is refused" `+ (-not (_IsStudioRoot (Make "leftover-backup" @(".venv.invalid.backup\pyvenv.cfg")) -ManagedDefaultRoot))+ # Only the rollback name has a collision counter; .venv.invalid is written once per run.+ Check "an invalid-venv name with a rollback-style suffix is refused" `+ (-not (_IsStudioRoot (Make "leftover-suffixed-invalid" @(".venv.invalid.20260908120000.4242.2\pyvenv.cfg")) -ManagedDefaultRoot))+ Check "a rollback name with a non-numeric pid is refused" `+ (-not (_IsStudioRoot (Make "leftover-badpid" @("unsloth_studio.rollback.20260908120000.mine\pyvenv.cfg")) -ManagedDefaultRoot))+ # \d matches every Unicode decimal digit; install.ps1 only ever writes ASCII.+ $arabicDigits = -join (0..13 | ForEach-Object { [char](0x0660 + ($_ % 10)) })+ Check "a leftover stamp in non-ASCII digits is refused" `+ (-not (_IsStudioRoot (Make "leftover-unicode" @(".venv.invalid.$arabicDigits.4242\pyvenv.cfg")) -ManagedDefaultRoot))+ # "time" is install.sh's date(1) fallback; install.ps1 always formats yyyyMMddHHmmss.+ Check "install.sh's time fallback is not a Windows name" `+ (-not (_IsStudioRoot (Make "leftover-time" @(".venv.invalid.time.4242\pyvenv.cfg")) -ManagedDefaultRoot))+ # A reparse point with the right name points at a venv the installer did not put there.+ $linkRoot = Make "leftover-link" @("keepme.txt")+ $realVenv = Make "somebodys-venv" @("pyvenv.cfg")+ $made = $null+ foreach ($kind in @("Junction", "SymbolicLink")) {+ try {+ $made = New-Item -ItemType $kind -Path (Join-Path $linkRoot "unsloth_studio.rollback.20260908120000.4242") -Target $realVenv -ErrorAction Stop+ if ($made -and -not [string]::IsNullOrWhiteSpace(@($made.Target)[0])) { break }+ } catch { $made = $null }+ }+ if ($made -and -not [string]::IsNullOrWhiteSpace(@($made.Target)[0])) {+ Check "a linked leftover is refused" (-not (_IsStudioRoot $linkRoot -ManagedDefaultRoot))+ } else {+ Write-Host " SKIP no reparse point could be created here"+ }+ $foreign = Make "foreign-shim" @()+ New-Item -ItemType Directory -Path (Join-Path $foreign "bin") -Force | Out-Null+ Set-Content -LiteralPath (Join-Path $foreign "bin\unsloth.cmd") -Value "@echo off`r`npython -m mytool %*`r`n"+ Check "a bin\unsloth.cmd without the trampoline is refused" (-not (_IsStudioRoot $foreign -ManagedDefaultRoot))+ Check "a missing path is refused" (-not (_IsStudioRoot (Join-Path $tmp "does-not-exist") -ManagedDefaultRoot))+ Check "an empty path is refused" (-not (_IsStudioRoot "" -ManagedDefaultRoot))++ # The other half of the question: install.ps1 decides when to WRITE the marker this gate+ # reads, and claiming a workspace it is about to refuse hands it to the uninstaller.+ $installPs1 = [System.IO.Path]::Combine($repoRoot, "install.ps1")+ $ie = $null; $it = $null+ $iast = [System.Management.Automation.Language.Parser]::ParseFile($installPs1, [ref]$it, [ref]$ie)+ $ifns = $iast.FindAll({+ param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst]+ }, $true)+ # Write-StudioRootOwnerMarker calls Test-StudioPlainFile, or every claim below is vacuous.+ foreach ($name in @("Test-StudioPlainFile", "Write-StudioRootOwnerMarker")) {+ $fn = $ifns | Where-Object { $_.Name -eq $name } | Select-Object -First 1+ if (-not $fn) {+ Write-Host " FAIL $name not found in install.ps1" -ForegroundColor Red+ $script:failures+++ } else {+ . ([scriptblock]::Create($fn.Extent.Text))+ }+ }+ function ClaimCheck([string]$Name, [bool]$WantClaimed, [string]$Mode, [string[]]$Files) {+ $root = Join-Path $tmp ("claim-" + $Name)+ New-Item -ItemType Directory -Path $root -Force | Out-Null+ foreach ($f in $Files) {+ $p = Join-Path $root $f+ New-Item -ItemType Directory -Path ([System.IO.Path]::GetDirectoryName($p)) -Force | Out-Null+ Set-Content -LiteralPath $p -Value "x"+ }+ $StudioRedirectMode = $Mode+ Write-StudioRootOwnerMarker -Root $root+ $claimed = Test-Path -LiteralPath (Join-Path $root ".unsloth-studio-owned") -PathType Leaf+ Check $Name ($claimed -eq $WantClaimed)+ }+ ClaimCheck "the default root, always" $true "default" @("notes.md")+ ClaimCheck "an empty custom root" $true "env" @()+ ClaimCheck "a custom root already carrying our marker" $true "env" @("unsloth_studio\.unsloth-studio-owned")+ ClaimCheck "a custom root with share\studio.conf" $true "env" @("share\studio.conf")+ ClaimCheck "somebody's workspace" $false "env" @("pyproject.toml")+ ClaimCheck "somebody's workspace with a venv of their own" $false "env" @("unsloth_studio\pyvenv.cfg")+ # A file called bin\unsloth.exe is any file of that name, and this list authorizes a delete.+ ClaimCheck "a workspace holding a plain bin\unsloth.exe" $false "env" @("bin\unsloth.exe", "notes.txt")+ # A LINKED share or unsloth_studio holding a genuine marker: the attribute answers for the+ # named file only.+ foreach ($pair in @(@("share", "studio.conf"), @("unsloth_studio", ".unsloth-studio-owned"))) {+ $wroot = Join-Path $tmp ("claim-linked-" + $pair[0])+ $wreal = Join-Path $tmp ("claim-linked-" + $pair[0] + "-real")+ New-Item -ItemType Directory -Path $wroot -Force | Out-Null+ New-Item -ItemType Directory -Path $wreal -Force | Out-Null+ Set-Content -LiteralPath (Join-Path $wreal $pair[1]) -Value "x"+ Set-Content -LiteralPath (Join-Path $wroot "notes.txt") -Value "mine"+ $dl = $null+ foreach ($kind in @("Junction", "SymbolicLink")) {+ try {+ $dl = New-Item -ItemType $kind -Path (Join-Path $wroot $pair[0]) -Target $wreal -ErrorAction Stop+ if ($dl -and -not [string]::IsNullOrWhiteSpace(@($dl.Target)[0])) { break }+ } catch { $dl = $null }+ }+ if ($dl -and -not [string]::IsNullOrWhiteSpace(@($dl.Target)[0])) {+ $StudioRedirectMode = "env"+ Write-StudioRootOwnerMarker -Root $wroot+ Check "a linked $($pair[0]) is not ownership proof" `+ (-not (Test-Path -LiteralPath (Join-Path $wroot ".unsloth-studio-owned") -PathType Leaf))+ }+ }+ # A link named like our marker: Test-Path follows it, which would skip the emptiness test.+ $lm = Join-Path $tmp "claim-linked-marker"+ New-Item -ItemType Directory -Path $lm -Force | Out-Null+ Set-Content -LiteralPath (Join-Path $lm "notes.txt") -Value "mine"+ $lmTarget = Join-Path $tmp "claim-linked-marker-target.txt"+ Set-Content -LiteralPath $lmTarget -Value "x"+ $lmLink = $null+ try {+ $lmLink = New-Item -ItemType SymbolicLink -Path (Join-Path $lm ".unsloth-studio-owned") -Target $lmTarget -ErrorAction Stop+ } catch { $lmLink = $null }+ if ($lmLink) {+ $StudioRedirectMode = "env"+ Write-StudioRootOwnerMarker -Root $lm+ $still = Get-Item -LiteralPath (Join-Path $lm ".unsloth-studio-owned") -Force+ Check "a linked marker is not read as proof, and is left as it was" `+ ((($still.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0))+ } else {+ Write-Host " SKIP no symlink could be created here"+ }+ # Called twice per install: the second call must not delete what the first one wrote.+ $twice = Join-Path $tmp "claim-twice"+ New-Item -ItemType Directory -Path $twice -Force | Out-Null+ $StudioRedirectMode = "default"+ Write-StudioRootOwnerMarker -Root $twice+ Set-Content -LiteralPath (Join-Path $twice ".unsloth-studio-owned") -Value "first" -NoNewline+ Write-StudioRootOwnerMarker -Root $twice+ Check "a second claim leaves a valid marker alone" `+ ((Get-Content -LiteralPath (Join-Path $twice ".unsloth-studio-owned") -Raw) -eq "first")+ # Test-DirectoryHasEntries is defined below the first call site, so the test must be inline.+ Check "the claim does not depend on Test-DirectoryHasEntries" `+ (-not ((($ifns | Where-Object { $_.Name -eq "Write-StudioRootOwnerMarker" } | Select-Object -First 1).Extent.Text) -match "Test-DirectoryHasEntries"))++ # A link at the marker path: WriteAllText would follow it and truncate the target.+ $linkClaim = Join-Path $tmp "claim-link"+ New-Item -ItemType Directory -Path $linkClaim -Force | Out-Null+ $target = Join-Path $tmp "precious.txt"+ Set-Content -LiteralPath $target -Value "precious"+ $linked = $null+ try {+ $linked = New-Item -ItemType SymbolicLink -Path (Join-Path $linkClaim ".unsloth-studio-owned") -Target $target -ErrorAction Stop+ } catch { $linked = $null }+ if ($linked) {+ $StudioRedirectMode = "default"+ Write-StudioRootOwnerMarker -Root $linkClaim+ Check "a linked marker path does not truncate its target" ((Get-Content -LiteralPath $target -Raw).Trim() -eq "precious")+ } else {+ Write-Host " SKIP no symlink could be created here"+ }++ # Same for install.ps1's replacement guard, and structural for the same reason.+ $installText = Get-Content -LiteralPath $installPs1 -Raw+ $guard = [regex]::Match($installText, "(?s)why: matching guard to the \.venv branch below.*?Move it aside or choose an empty").Value+ Check "install.ps1 has an env-mode replacement guard" ($guard.Length -gt 0)+ Check "and it reads the root marker" `+ ($guard -match [regex]::Escape('Join-Path $StudioHome ".unsloth-studio-owned"'))+ # ... the same way the claim writes it, or a link gets a foreign workspace past the guard.+ Check "and through Test-StudioPlainFile, not Test-Path" `+ ($guard -match [regex]::Escape('Test-StudioPlainFile -Path (Join-Path $StudioHome ".unsloth-studio-owned")'))+} finally {+ Remove-Item -LiteralPath $tmp -Recurse -Force -ErrorAction SilentlyContinue+}++if ($failures -gt 0) { Write-Host "$failures check(s) failed" -ForegroundColor Red; exit 1 }+Write-Host "all checks passed"diff --git a/tests/studio/test_uninstall_reparse_stop_roots.ps1 b/tests/studio/test_uninstall_reparse_stop_roots.ps1index 01d832c14f9..52ed3456f45 100644--- a/tests/studio/test_uninstall_reparse_stop_roots.ps1+++ b/tests/studio/test_uninstall_reparse_stop_roots.ps1@@ -42,43 +42,103 @@ if (-not $fn) {# The stop-scan call site has to actually pass the targets, or the helper is dead code.$ps1Text = Get-Content -LiteralPath $ps1Path -Raw+# $ownedRoots, not $knownRoots: the stop scan runs before the ownership gates, so an unowned root+# would have processes killed under its target and only then be refused.Check "the stop scan is given the managed paths under the target" `- ($ps1Text -match '_StopProcessesLockingRoots -Roots \(\$stopRoots \+ @\(_ManagedPathsUnderReparseTargets \$knownRoots\)\)')+ ($ps1Text -match '_StopProcessesLockingRoots -Roots \(\$stopRoots \+ @\(_ManagedPathsUnderReparseTargets \$ownedRoots\)\)')+Check "and that list is filtered by the ownership gate" `+ ($ps1Text -match '(?s)\$ownedRoots = @\(\).*?_IsStudioRoot \$defaultStudioHome -ManagedDefaultRoot.*?foreach \(\$r in \$customRoots\) \{\s*\r?\n\s*if \(\(_IsStudioRoot \$r\) -and -not \(_IsUnsafeRoot \$r\)\)')+# The removal loop refuses on EITHER gate, so a deny-listed install must not be swept either.+Check "and by the deny list, which the removal loop also refuses on" `+ ($ps1Text -match '(?s)\$ownedRoots = @\(\).*?-not \(_IsUnsafeRoot \$defaultStudioHome\)')+# The plain roots too: _RootFromConf only started resolving a root from studio.conf when+# Split-Path stopped throwing, and a stale conf can name a directory somebody else now uses.+Check "the stop scan is given the gated roots, not every known one" `+ ($ps1Text -match '(?m)^\s*\$stopRoots = @\(\$ownedRoots\) \+')+# _StopStudioProcesses selects victims from what it is given and also runs before the gates.+Check "and so is the process sweep" `+ ($ps1Text -match '(?m)^\s*_StopStudioProcesses -KnownRoots \$ownedRoots\s*$')+# ... and an EXPLICIT empty list has to mean "nothing qualifies": @() is false in PowerShell, so+# `if ($KnownRoots)` swept the whole machine on a run with nothing to delete.+Check "an explicitly empty root list still scopes the sweep" `+ ($ps1Text -match [regex]::Escape("`$scoped = `$PSBoundParameters.ContainsKey('KnownRoots')"))+Check "and the sweep branches on that, not on the array's truthiness" `+ ($ps1Text -match '(?m)^\s*if \(\$scoped\) \{\s*$')+# The port-file stopper kills too, and deletes the port file, which writes inside the root.+Check "the port-file stopper is gated as well" `+ (-not ($ps1Text -match '_StopByPortFile -PortFile [^\r\n]*-KnownRoots \$knownRoots'))+# ... which means the gated list has to exist before the stop step, not after it.+Check "and that list is built before the stop step" `+ ([regex]::Match($ps1Text, '(?m)^\s*\$ownedRoots = @\(\)').Index -lt+ [regex]::Match($ps1Text, '(?m)^\s*_StopStudioProcesses -KnownRoots').Index)+# A removal that got part way must leave the root identifiable, or the retry it asks for fails.+Check "a partial removal puts the ownership marker back" `+ ($ps1Text -match '(?m)^\s*_RemovePath \$Path\s*\r?\n\s*_RestoreOwnerMarker \$Path\s*$')+# The legacy <parent>\stable-diffusion.cpp sibling comes from the same corrected Split-Path.+Check "the legacy sd.cpp stop root is gated the same way" `+ ($ps1Text -match '(?s)\$customSdCppToStop = @\(\)\s*\r?\n\s*foreach \(\$r in \$customRoots\) \{\s*\r?\n\s*if \(-not \(_IsStudioRoot \$r\)\) \{ continue \}')-$tmp = Join-Path ([System.IO.Path]::GetTempPath()) ("unsloth-reparse-" + [System.Guid]::NewGuid().ToString("N"))-New-Item -ItemType Directory -Path $tmp -Force | Out-Null-try {- $target = Join-Path $tmp "physical"- New-Item -ItemType Directory -Path (Join-Path $target "stable-diffusion.cpp") -Force | Out-Null- $link = Join-Path $tmp "studio-home"- New-Item -ItemType SymbolicLink -Path $link -Target $target -ErrorAction Stop | Out-Null+# Both kinds: the helper reads only .Target; a symlink needs elevation, a junction never does.+# $IsWindows exists only on PowerShell 6+, so 5.1 falls through to $true.+$onWindows = if ($null -ne $IsWindows) { $IsWindows } else { $true }- $phys = [System.IO.Path]::GetFullPath($target).TrimEnd('\', '/')- $got = @(_ManagedPathsUnderReparseTargets @($link))- Check "a linked root yields the sd.cpp tree under its physical target" `- ($got -contains (Join-Path $phys "stable-diffusion.cpp"))- Check "... and the venv under it" ($got -contains (Join-Path $phys "unsloth_studio"))- # Never the bare target: the delete leaves it standing, so anything else there is not ours.- Check "the bare physical target is NOT in scope" (-not ($got -contains $phys))+# New-Item -ItemType Junction does NOT throw on Linux pwsh; it makes a plain dir with no .Target,+# so the kinds are chosen by platform rather than by catching a failure.+$kinds = if ($onWindows) { @("Junction", "SymbolicLink") } else { @("SymbolicLink") }- # A plain directory contributes nothing, so the scan does not widen for ordinary installs.- $plain = Join-Path $tmp "plain"- New-Item -ItemType Directory -Path $plain -Force | Out-Null- Check "a plain root adds nothing" (@(_ManagedPathsUnderReparseTargets @($plain)).Count -eq 0)+$ran = 0+foreach ($kind in $kinds) {+ $tmp = Join-Path ([System.IO.Path]::GetTempPath()) ("unsloth-reparse-" + [System.Guid]::NewGuid().ToString("N"))+ New-Item -ItemType Directory -Path $tmp -Force | Out-Null+ try {+ $target = Join-Path $tmp "physical"+ New-Item -ItemType Directory -Path (Join-Path $target "stable-diffusion.cpp") -Force | Out-Null+ $link = Join-Path $tmp "studio-home"+ try { New-Item -ItemType $kind -Path $link -Target $target -ErrorAction Stop | Out-Null }+ catch {+ # Not a failure: the other kind carries the assertions. Said out loud, or one kind+ # covered reads as both.+ Write-Host " SKIP $kind is not creatable here: $($_.Exception.Message)"+ continue+ }+ # Created is not the same as usable: a link with no .Target cannot exercise anything.+ $made = Get-Item -LiteralPath $link -Force -ErrorAction SilentlyContinue+ if (-not $made -or [string]::IsNullOrWhiteSpace(@($made.Target)[0])) {+ Write-Host " SKIP $kind produced no reparse target here"+ continue+ }+ $ran++- # Neither does a path that is not there at all, or an empty entry.- Check "a missing root adds nothing" (@(_ManagedPathsUnderReparseTargets @((Join-Path $tmp "nope"), "", $null)).Count -eq 0)+ $phys = [System.IO.Path]::GetFullPath($target).TrimEnd('\', '/')+ $got = @(_ManagedPathsUnderReparseTargets @($link))+ Check "$kind : a linked root yields the sd.cpp tree under its physical target" `+ ($got -contains (Join-Path $phys "stable-diffusion.cpp"))+ Check "$kind : ... and the venv under it" ($got -contains (Join-Path $phys "unsloth_studio"))+ # Never the bare target: the delete leaves it standing, so anything else there is not ours.+ Check "$kind : the bare physical target is NOT in scope" (-not ($got -contains $phys))- # Deduplicated: two links onto one target must not stack.- $link2 = Join-Path $tmp "studio-home-2"- New-Item -ItemType SymbolicLink -Path $link2 -Target $target -ErrorAction Stop | Out-Null- $both = @(_ManagedPathsUnderReparseTargets @($link, $link2))- Check "two links onto one target do not duplicate its subtrees" ($both.Count -eq $got.Count)-}-finally {- Remove-Item -LiteralPath $tmp -Recurse -Force -ErrorAction SilentlyContinue+ # A plain directory contributes nothing, so the scan does not widen for ordinary installs.+ $plain = Join-Path $tmp "plain"+ New-Item -ItemType Directory -Path $plain -Force | Out-Null+ Check "$kind : a plain root adds nothing" (@(_ManagedPathsUnderReparseTargets @($plain)).Count -eq 0)++ # Neither does a path that is not there at all, or an empty entry.+ Check "$kind : a missing root adds nothing" (@(_ManagedPathsUnderReparseTargets @((Join-Path $tmp "nope"), "", $null)).Count -eq 0)++ # Deduplicated: two links onto one target must not stack.+ $link2 = Join-Path $tmp "studio-home-2"+ New-Item -ItemType $kind -Path $link2 -Target $target -ErrorAction Stop | Out-Null+ $both = @(_ManagedPathsUnderReparseTargets @($link, $link2))+ Check "$kind : two links onto one target do not duplicate its subtrees" ($both.Count -eq $got.Count)+ }+ finally {+ Remove-Item -LiteralPath $tmp -Recurse -Force -ErrorAction SilentlyContinue+ }}+# An environment that can make neither kind would otherwise pass having asserted nothing.+Check "at least one reparse kind was exercised" ($ran -gt 0)+Write-Host ""if ($failures -gt 0) { Write-Host "$failures check(s) failed" -ForegroundColor Red; exit 1 }Write-Host "All checks passed" -ForegroundColor Green