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
Installer: recover from and explain an unreadable llama.cpp cache on Windows (#10533)
Daniel Han06dfb2059ab3
diff --git a/install.ps1 b/install.ps1index 80912891144..fec4f357c91 100644--- a/install.ps1+++ b/install.ps1@@ -3795,16 +3795,99 @@ exit 1param([Parameter(Mandatory = $true)][AllowNull()][AllowEmptyString()][string]$Path)if ([string]::IsNullOrWhiteSpace($Path)) { return "" }- $item = Get-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue- if (-not $item) { return "" }- # Non-filesystem providers do not expose FileSystemInfo attributes.- if ($item -isnot [System.IO.FileSystemInfo]) { return "" }- if (-not ($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint)) { return "" }- $target = $null- try { $target = $item.Target } catch { $target = $null }- # PS 5.1 exposes .Target as a collection; PS 7 as a string.- if ($target) { return " (it is a link to $(@($target) -join ', '))" }- return " (it is a link)"++ # Read attributes through the filesystem API rather than Get-Item. Getting+ # attributes needs only FILE_READ_ATTRIBUTES, which survives the ACLs that+ # deny reading the directory itself, so Get-Item returns nothing in exactly+ # the case this detail is meant to describe and the caller silently loses+ # every hint below.+ $attrs = $null+ try { $attrs = [System.IO.File]::GetAttributes($Path) } catch { $attrs = $null }+ if ($null -eq $attrs) { return "" }++ # Ordered by how much each one changes the fix. takeown/icacls cannot help+ # with any of the first three, so name them before falling back to ACLs.+ # On a directory this attribute only means new descendants are encrypted+ # by default, so listing it never needs the key and a denial there is an+ # ACL. Only a file's own streams are unreadable without the certificate.+ $isDirectory = ([int]$attrs -band [int][System.IO.FileAttributes]::Directory) -ne 0+ if (-not $isDirectory -and ($attrs -band [System.IO.FileAttributes]::Encrypted)) {+ return " (it is EFS-encrypted, so it stays unreadable even elevated unless the encrypting account or its recovery certificate is available)"+ }+ # Offline plus either recall attribute is a cloud placeholder, typically+ # OneDrive Files On-Demand that cannot hydrate.+ # RECALL_ON_OPEN (0x40000) and RECALL_ON_DATA_ACCESS (0x400000) are absent+ # from the FileAttributes enum on Windows PowerShell 5.1, so test the bits.+ $offline = ([int]$attrs -band [int][System.IO.FileAttributes]::Offline) -ne 0+ $recall = ([int]$attrs -band (0x00040000 -bor 0x00400000)) -ne 0+ if ($offline -or $recall) {+ return " (it is a cloud placeholder, e.g. OneDrive Files On-Demand, that cannot be hydrated right now)"+ }+ if ($attrs -band [System.IO.FileAttributes]::ReparsePoint) {+ $target = $null+ try {+ $item = Get-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue+ if ($item -is [System.IO.FileSystemInfo]) { $target = $item.Target }+ } catch { $target = $null }+ # PS 5.1 exposes .Target as a collection; PS 7 as a string.+ if ($target) { return " (it is a link to $(@($target) -join ', '))" }+ return " (it is a link)"+ }+ return ""+ }++ # Which security software could be denying this path, as a possibility.+ #+ # Worth naming because takeown and icacls cannot clear a filter-driver block+ # and elevation does not either, so a user whose antivirus is holding the+ # folder is otherwise sent round the takeown loop for as long as they are+ # willing. Nothing readable from here attributes the specific denial though,+ # so this names the candidate and the log that settles it and never+ # contradicts the ACL advice it follows.+ #+ # Defender's Controlled folder access modes are 0 Disabled, 1 Enabled,+ # 2 AuditMode, 3 BlockDiskModificationOnly, 4 AuditDiskModificationOnly. Only+ # 1 gates file access; 3 and 4 are direct disk-sector writes rather than+ # files, so neither explains a denied folder.+ #+ # When Defender is not it, name whichever antivirus is registered and running+ # instead: third-party suites ship the same feature under their own names+ # (Bitdefender Safe Files and Ransomware Remediation, for instance), and the+ # user cannot act on advice that does not say which product to open.+ #+ # Answers "" whenever it cannot tell, so a machine with no Defender module+ # and no SecurityCenter registration reads the same as one that says no.+ function Get-SecuritySoftwareNote {+ $mode = $null+ try {+ if (Get-Command Get-MpPreference -ErrorAction SilentlyContinue) {+ $mode = [int](Get-MpPreference -ErrorAction Stop).EnableControlledFolderAccess+ }+ } catch { $mode = $null }+ if ($mode -eq 1) {+ return "Controlled folder access is ON here, and it gates writes to protected folders whatever your privileges are, so where it is the cause takeown and icacls will not clear it: Windows Defender Operational events 1123 and 1124 say whether it stopped this path, and Virus & threat protection > Ransomware protection > Allow an app is where to allow Unsloth"+ }+ # SecurityCenter2 is the registration every consumer antivirus makes, and+ # it is absent on Server SKUs, so this stays best-effort. productState+ # packs the running state in 0xF000: 0x1000 on, 0x2000 snoozed, 0 off.+ # A product that is not running cannot be holding the folder and naming it+ # sends the user to the wrong console; a state we cannot read proves+ # nothing either way, so it is kept.+ $others = @()+ try {+ $others = @(Get-CimInstance -Namespace "root/SecurityCenter2" -ClassName AntiVirusProduct -ErrorAction Stop |+ Where-Object { $state = $_.productState -as [uint32]; ($null -eq $state) -or (($state -band 0xF000) -eq 0x1000) } |+ ForEach-Object { [string]$_.displayName } |+ Where-Object { $_ -and $_ -notmatch "Windows Defender" -and $_ -notmatch "Microsoft Defender" })+ } catch { $others = @() }+ if ($others.Count -gt 0) {+ $names = ($others | Select-Object -Unique) -join ", "+ return "$names is running here, and its ransomware or protected-folder feature can deny a path whatever your privileges are. If takeown and icacls do not clear this, look in $names for a block on this folder, and add an exclusion for it and for Unsloth"+ }+ if ($mode -eq 2) {+ return "Controlled folder access is in audit mode, so it is logging rather than blocking and is not the cause here; Windows Defender Operational events 1123 and 1124 name whatever it did stop"+ }+ return ""}# Print guidance; returns the failure reason as its only pipeline output.@@ -3833,6 +3916,10 @@ exit 1substep "takeown /F `"$Path`" /R /D Y" "Yellow"substep "icacls `"$Path`" /reset /T" "Yellow"substep "Antivirus or Controlled folder access can deny this path too; allow or exclude it, then retry" "Yellow"+ # After the generic line, since this one either confirms it or rules it+ # out, and an empty answer must leave the generic advice standing.+ $securitySoftware = Get-SecuritySoftwareNote+ if ($securitySoftware) { substep $securitySoftware "Yellow" }if ($UserSupplied) {return "Access denied reading $Label at $Path. Restore access with takeown/icacls, or point UNSLOTH_LOCAL_LLAMA_CPP_DIR at a readable build, then re-run setup."}@@ -3899,10 +3986,71 @@ exit 1Write-StudioLine ""# A denied custom home cannot be claimed as an Unsloth-managed cache.$homeIsCustom = Test-StudioHomeIsCustom- # Preserve user-supplied wording when either override names this tree.+ # Preserve user-supplied wording when either override names this tree, or+ # names a build inside it: moving or deleting this folder takes that build+ # with it, and the later --with-llama-cpp-dir check then aborts on a path+ # we made disappear.$suppliedDir = if ($WithLlamaCppDir) { $WithLlamaCppDir } else { $env:UNSLOTH_LOCAL_LLAMA_CPP_DIR }- $userSupplied = (-not [string]::IsNullOrWhiteSpace($suppliedDir)) -and- ((Get-CanonicalDir -Path $suppliedDir) -eq (Get-CanonicalDir -Path $dir))+ # Walking the ancestors beats comparing the two canonical strings: an+ # override that does not exist yet cannot be resolved, so a prefix test+ # would compare a resolved path against an unresolved one and miss.+ $userSupplied = $false+ if (-not [string]::IsNullOrWhiteSpace($suppliedDir)) {+ $canonicalDir = [string](Get-CanonicalDir -Path $dir)+ $probe = [string](Get-CanonicalDir -Path $suppliedDir)+ while (-not [string]::IsNullOrWhiteSpace($probe)) {+ if ([string](Get-CanonicalDir -Path $probe) -eq $canonicalDir) {+ $userSupplied = $true+ break+ }+ $parent = ""+ try { $parent = [string](Split-Path -Parent $probe) } catch { $parent = "" }+ if ($parent -eq $probe) { break }+ $probe = $parent+ }+ }++ # Only the default branch below tells the user to delete this folder, so+ # only that case may move it. A user-supplied build is not ours to touch,+ # and an unreadable custom home cannot be confirmed as a managed cache.+ # Renaming needs DELETE on the folder plus write on its parent, neither of+ # which is read access, so this recovers denials that takeown and icacls+ # do not: the folder is a managed cache that setup reinstalls anyway.+ # Setup never makes this a link, so a link here is something the user+ # arranged, pointing at a build we were not told about. Moving it would+ # silently change which tree they run without touching the one they were+ # protecting, so it is left alone and named in the guidance instead.+ $isLink = $false+ try {+ $linkAttrs = [System.IO.File]::GetAttributes($dir)+ $isLink = ([int]$linkAttrs -band [int][System.IO.FileAttributes]::ReparsePoint) -ne 0+ } catch {+ # Unreadable attributes prove nothing, and "proves nothing" must not+ # mean "movable": fall through to the guidance rather than guess.+ $isLink = $true+ }+ if (-not $userSupplied -and -not $homeIsCustom -and -not $isLink) {+ $asideDir = "$dir.denied-$(Get-Date -Format 'yyyyMMddHHmmss')"+ $moved = $false+ try {+ Move-Item -LiteralPath $dir -Destination $asideDir -ErrorAction Stop+ $moved = $true+ } catch {+ # Expected when the denial also covers rename; fall through to guidance.+ }+ if ($moved) {+ step "permissions" "llama.cpp install at $dir could not be read, so it was moved aside" "Yellow"+ substep "Moved to $asideDir; it is a managed cache and setup reinstalls it" "Yellow"+ substep "Delete the moved folder once access is restored, it is no longer used" "Yellow"+ Write-StudioLine ""+ return $null+ }+ # This runs before the install lock, so a second run can have moved+ # the folder in between. Re-probe rather than report a denial for a+ # path that is no longer there and stop an install that can proceed.+ if ((Get-LlamaCppInstallReadState -Path $dir) -ne "Denied") { return $null }+ }+$reason = Write-PathAccessDenied -Path $dir -Label "llama.cpp install" `-UserSupplied:$userSupplied -OwnershipUnverified:$homeIsCustomsubstep "Stopping here, before phase 1: nothing has been downloaded or installed" "Yellow"diff --git a/scripts/sync_shared_ps1_helpers.py b/scripts/sync_shared_ps1_helpers.pynew file mode 100644index 00000000000..ddd2ff64b8c--- /dev/null+++ b/scripts/sync_shared_ps1_helpers.py@@ -0,0 +1,122 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Copy the shared Windows preflight helpers from install.ps1 into studio/setup.ps1.++install.ps1 has to run standalone, before any repo exists, so it cannot dot-source+setup.ps1 and instead carries byte-identical copies of a handful of helpers.+tests/studio/install/test_denied_llama_cpp_preflight.py fails when the two drift.+Editing one and running this keeps them together, rather than hand-copying and+finding out from CI.++Usage:+ python3 scripts/sync_shared_ps1_helpers.py [--check]++--check exits 1 without writing when setup.ps1 is out of date, for use in CI.+"""++from __future__ import annotations++import argparse+import re+import sys+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+INSTALL_PS1 = ROOT / "install.ps1"+SETUP_PS1 = ROOT / "studio" / "setup.ps1"++SHARED_BEGIN = "# ── BEGIN SHARED WITH studio/setup.ps1 ──"+SHARED_END = "# ── END SHARED WITH studio/setup.ps1 ──"+++def function_span(text: str, name: str) -> tuple[int, int]:+ """Half-open character span of a PowerShell function, by balanced braces."""+ match = re.search(rf"(?im)^[ \t]*function[ \t]+{re.escape(name)}\b", text)+ if not match:+ raise SystemExit(f"{name} is not defined")+ start = text.index("{", match.start())+ depth = 0+ for index in range(start, len(text)):+ if text[index] == "{":+ depth += 1+ elif text[index] == "}":+ depth -= 1+ if depth == 0:+ return match.start(), index + 1+ raise SystemExit(f"unbalanced braces in {name}")+++def dedented(source: str) -> str:+ """Drop the common indentation, which is the only difference allowed."""+ lines = source.splitlines()+ body = [line for line in lines if line.strip()]+ indent = min(len(line) - len(line.lstrip(" ")) for line in body)+ return "\n".join(line[indent:] if line.strip() else "" for line in lines)+++def shared_names(install_text: str) -> list[str]:+ """The functions declared inside the shared block, in file order."""+ block = install_text.split(SHARED_BEGIN, 1)[1].split(SHARED_END, 1)[0]+ return re.findall(r"(?m)^[ \t]*function[ \t]+([A-Za-z-]+)", block)+++def leading_comment_start(text: str, start: int) -> int:+ """Index of the contiguous comment block directly above a function."""+ lines = text[:start].splitlines(keepends = True)+ cut = len(lines)+ while cut > 0 and lines[cut - 1].lstrip().startswith("#"):+ cut -= 1+ return sum(len(line) for line in lines[:cut])+++def main() -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("--check", action = "store_true", help = "report drift, write nothing")+ args = parser.parse_args()++ install_text = INSTALL_PS1.read_text(encoding = "utf-8")+ setup_text = SETUP_PS1.read_text(encoding = "utf-8")++ stale: list[str] = []+ previous: str | None = None+ for name in shared_names(install_text):+ start, end = function_span(install_text, name)+ wanted = dedented(install_text[start:end])+ if re.search(rf"(?im)^[ \t]*function[ \t]+{re.escape(name)}\b", setup_text):+ setup_start, setup_end = function_span(setup_text, name)+ if setup_text[setup_start:setup_end] == wanted:+ previous = name+ continue+ stale.append(name)+ setup_text = setup_text[:setup_start] + wanted + setup_text[setup_end:]+ previous = name+ continue+ # New helper. Land it where install.ps1 keeps it, after the one before+ # it, with the comment block that explains it.+ if previous is None:+ raise SystemExit(f"{name} is new and has nothing to follow in setup.ps1")+ # dedented() drops the trailing newline, so the comment would otherwise+ # run into the function keyword and hide the declaration from every+ # reader of this file, this script included.+ comment = dedented(install_text[leading_comment_start(install_text, start) : start])+ comment = comment.rstrip("\n") + "\n"+ _, after = function_span(setup_text, previous)+ setup_text = setup_text[:after] + "\n\n" + comment + wanted + setup_text[after:]+ stale.append(name)+ previous = name++ if not stale:+ print("shared helpers already match")+ return 0+ if args.check:+ print("setup.ps1 is behind install.ps1: " + ", ".join(stale))+ print("run: python3 scripts/sync_shared_ps1_helpers.py")+ return 1+ SETUP_PS1.write_text(setup_text, encoding = "utf-8")+ print("synced into studio/setup.ps1: " + ", ".join(stale))+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/studio/install_node_prebuilt.py b/studio/install_node_prebuilt.pyindex 09625d03389..fa661d12c40 100644--- a/studio/install_node_prebuilt.py+++ b/studio/install_node_prebuilt.py@@ -13,13 +13,14 @@ Archives are verified against sha256 digests pinned in ``node_prebuilt_pins.json(committed in-tree), not a checksum re-fetched from the same origin as the archive.Mirrors ``install_llama_prebuilt.py`` so the setup scripts drive it the same way.-Exit codes: 0 success, 1 error, 2 fallback, 3 busy. A re-run that already matches+Exit codes: 0 success, 1 error, 2 fallback, 3 busy, 4 access denied. A re-run that already matcheslogs "already matches" and returns 0 without downloading (the scripts grep it)."""from __future__ import annotationsimport argparse+import errnoimport hashlibimport jsonimport os@@ -53,6 +54,20 @@ EXIT_SUCCESS = 0EXIT_ERROR = 1EXIT_FALLBACK = 2EXIT_BUSY = 3+# The install directory cannot be written. Separate from EXIT_ERROR because the+# caller's advice for that one is "install Node yourself or check your network",+# which is wrong here and sends people to look at the wrong thing.+EXIT_DENIED = 4+# setup.ps1 reads these back out to diagnose the object that was actually+# refused. The install lock and the .staging root live in the install+# directory's parent, so "delete or rename the Node cache" is the wrong advice+# for half of the denials that reach exit 4, and the directory it names may not+# even exist. Classified here, where the install directory is known, rather than+# re-derived from a path string on the PowerShell side.+DENIED_PATH_MARKER = "denied-path: "+DENIED_SCOPE_MARKER = "denied-scope: "+DENIED_SCOPE_INSTALL_DIR = "install-dir"+DENIED_SCOPE_PARENT = "parent"# Node 24 LTS bundles npm 11, clearing Vite 8's floor (Node ^20.19 || >=22.12, npm >= 11).NODE_MIN_LTS_MAJOR = 24@@ -1201,10 +1216,64 @@ def main(argv: list[str] | None = None) -> int:except PrebuiltFallback as exc:log(f"prebuilt unavailable: {exc}")return EXIT_FALLBACK+ except PermissionError as exc:+ return _report_access_denied(exc, install_dir)+ except OSError as exc:+ # Windows reports the ACL and filter-driver denials that matter here as+ # winerror 5, which does not always arrive as PermissionError.+ if getattr(exc, "winerror", None) == 5 or exc.errno == errno.EACCES:+ return _report_access_denied(exc, install_dir)+ log(f"unexpected error: {exc}")+ return EXIT_ERRORexcept Exception as exc: # noqa: BLE001log(f"unexpected error: {exc}")return EXIT_ERROR+def _report_access_denied(exc: OSError, install_dir: Path) -> int:+ """Log the denial, and say which object was refused so the caller can name it."""+ path = getattr(exc, "filename", None) or ""+ if path:+ log(f"{DENIED_PATH_MARKER}{path}")+ scope = DENIED_SCOPE_INSTALL_DIR if _within(path, install_dir) else DENIED_SCOPE_PARENT+ log(f"{DENIED_SCOPE_MARKER}{scope}")+ log(_access_denied_message(exc))+ return EXIT_DENIED+++def _within(path: str, root: Path) -> bool:+ """Whether path is root or sits under it, by spelling alone.++ Both sides come from the same --install-dir string, so normalizing without+ resolving links keeps them comparable; resolving would need the very access+ that was just denied.+ """+ normalized = os.path.normcase(os.path.abspath(path))+ base = os.path.normcase(os.path.abspath(root))+ return normalized == base or normalized.startswith(base.rstrip(os.sep) + os.sep)+++def _access_denied_message(exc: OSError) -> str:+ """Say that this is a permission problem, and that elevation may not fix it.++ Reported as "unexpected error" before, which the caller then followed with+ "install Node yourself, or check your network". Neither is the fix, and a+ user whose antivirus is holding the folder can spend a long time on the+ second one. Antivirus ransomware protection and Controlled folder access+ both deny regardless of privilege, so running elevated is not the answer+ either.+ """+ path = getattr(exc, "filename", None) or ""+ where = f" writing {path}" if path else ""+ return (+ f"access denied{where}. This is a permissions or security-software block, "+ "not a download problem. Antivirus ransomware protection (Bitdefender Safe Files, "+ "Defender Controlled folder access and the like) denies this whatever your "+ "privileges are, so running elevated may not clear it. Allow or exclude the "+ "Unsloth folder in your antivirus, or delete or rename it (it is a managed cache "+ "and setup reinstalls it), then re-run setup."+ )++if __name__ == "__main__":raise SystemExit(main())diff --git a/studio/setup.ps1 b/studio/setup.ps1index 7c90a7ec987..5ef9627023e 100644--- a/studio/setup.ps1+++ b/studio/setup.ps1@@ -521,16 +521,99 @@ function Get-PathDenialDetail {param([Parameter(Mandatory = $true)][AllowNull()][AllowEmptyString()][string]$Path)if ([string]::IsNullOrWhiteSpace($Path)) { return "" }- $item = Get-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue- if (-not $item) { return "" }- # Non-filesystem providers do not expose FileSystemInfo attributes.- if ($item -isnot [System.IO.FileSystemInfo]) { return "" }- if (-not ($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint)) { return "" }- $target = $null- try { $target = $item.Target } catch { $target = $null }- # PS 5.1 exposes .Target as a collection; PS 7 as a string.- if ($target) { return " (it is a link to $(@($target) -join ', '))" }- return " (it is a link)"++ # Read attributes through the filesystem API rather than Get-Item. Getting+ # attributes needs only FILE_READ_ATTRIBUTES, which survives the ACLs that+ # deny reading the directory itself, so Get-Item returns nothing in exactly+ # the case this detail is meant to describe and the caller silently loses+ # every hint below.+ $attrs = $null+ try { $attrs = [System.IO.File]::GetAttributes($Path) } catch { $attrs = $null }+ if ($null -eq $attrs) { return "" }++ # Ordered by how much each one changes the fix. takeown/icacls cannot help+ # with any of the first three, so name them before falling back to ACLs.+ # On a directory this attribute only means new descendants are encrypted+ # by default, so listing it never needs the key and a denial there is an+ # ACL. Only a file's own streams are unreadable without the certificate.+ $isDirectory = ([int]$attrs -band [int][System.IO.FileAttributes]::Directory) -ne 0+ if (-not $isDirectory -and ($attrs -band [System.IO.FileAttributes]::Encrypted)) {+ return " (it is EFS-encrypted, so it stays unreadable even elevated unless the encrypting account or its recovery certificate is available)"+ }+ # Offline plus either recall attribute is a cloud placeholder, typically+ # OneDrive Files On-Demand that cannot hydrate.+ # RECALL_ON_OPEN (0x40000) and RECALL_ON_DATA_ACCESS (0x400000) are absent+ # from the FileAttributes enum on Windows PowerShell 5.1, so test the bits.+ $offline = ([int]$attrs -band [int][System.IO.FileAttributes]::Offline) -ne 0+ $recall = ([int]$attrs -band (0x00040000 -bor 0x00400000)) -ne 0+ if ($offline -or $recall) {+ return " (it is a cloud placeholder, e.g. OneDrive Files On-Demand, that cannot be hydrated right now)"+ }+ if ($attrs -band [System.IO.FileAttributes]::ReparsePoint) {+ $target = $null+ try {+ $item = Get-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue+ if ($item -is [System.IO.FileSystemInfo]) { $target = $item.Target }+ } catch { $target = $null }+ # PS 5.1 exposes .Target as a collection; PS 7 as a string.+ if ($target) { return " (it is a link to $(@($target) -join ', '))" }+ return " (it is a link)"+ }+ return ""+}++# Which security software could be denying this path, as a possibility.+#+# Worth naming because takeown and icacls cannot clear a filter-driver block+# and elevation does not either, so a user whose antivirus is holding the+# folder is otherwise sent round the takeown loop for as long as they are+# willing. Nothing readable from here attributes the specific denial though,+# so this names the candidate and the log that settles it and never+# contradicts the ACL advice it follows.+#+# Defender's Controlled folder access modes are 0 Disabled, 1 Enabled,+# 2 AuditMode, 3 BlockDiskModificationOnly, 4 AuditDiskModificationOnly. Only+# 1 gates file access; 3 and 4 are direct disk-sector writes rather than+# files, so neither explains a denied folder.+#+# When Defender is not it, name whichever antivirus is registered and running+# instead: third-party suites ship the same feature under their own names+# (Bitdefender Safe Files and Ransomware Remediation, for instance), and the+# user cannot act on advice that does not say which product to open.+#+# Answers "" whenever it cannot tell, so a machine with no Defender module+# and no SecurityCenter registration reads the same as one that says no.+function Get-SecuritySoftwareNote {+ $mode = $null+ try {+ if (Get-Command Get-MpPreference -ErrorAction SilentlyContinue) {+ $mode = [int](Get-MpPreference -ErrorAction Stop).EnableControlledFolderAccess+ }+ } catch { $mode = $null }+ if ($mode -eq 1) {+ return "Controlled folder access is ON here, and it gates writes to protected folders whatever your privileges are, so where it is the cause takeown and icacls will not clear it: Windows Defender Operational events 1123 and 1124 say whether it stopped this path, and Virus & threat protection > Ransomware protection > Allow an app is where to allow Unsloth"+ }+ # SecurityCenter2 is the registration every consumer antivirus makes, and+ # it is absent on Server SKUs, so this stays best-effort. productState+ # packs the running state in 0xF000: 0x1000 on, 0x2000 snoozed, 0 off.+ # A product that is not running cannot be holding the folder and naming it+ # sends the user to the wrong console; a state we cannot read proves+ # nothing either way, so it is kept.+ $others = @()+ try {+ $others = @(Get-CimInstance -Namespace "root/SecurityCenter2" -ClassName AntiVirusProduct -ErrorAction Stop |+ Where-Object { $state = $_.productState -as [uint32]; ($null -eq $state) -or (($state -band 0xF000) -eq 0x1000) } |+ ForEach-Object { [string]$_.displayName } |+ Where-Object { $_ -and $_ -notmatch "Windows Defender" -and $_ -notmatch "Microsoft Defender" })+ } catch { $others = @() }+ if ($others.Count -gt 0) {+ $names = ($others | Select-Object -Unique) -join ", "+ return "$names is running here, and its ransomware or protected-folder feature can deny a path whatever your privileges are. If takeown and icacls do not clear this, look in $names for a block on this folder, and add an exclusion for it and for Unsloth"+ }+ if ($mode -eq 2) {+ return "Controlled folder access is in audit mode, so it is logging rather than blocking and is not the cause here; Windows Defender Operational events 1123 and 1124 name whatever it did stop"+ }+ return ""}# Print guidance; returns the failure reason as its only pipeline output.@@ -559,6 +642,10 @@ function Write-PathAccessDenied {substep "takeown /F `"$Path`" /R /D Y" "Yellow"substep "icacls `"$Path`" /reset /T" "Yellow"substep "Antivirus or Controlled folder access can deny this path too; allow or exclude it, then retry" "Yellow"+ # After the generic line, since this one either confirms it or rules it+ # out, and an empty answer must leave the generic advice standing.+ $securitySoftware = Get-SecuritySoftwareNote+ if ($securitySoftware) { substep $securitySoftware "Yellow" }if ($UserSupplied) {return "Access denied reading $Label at $Path. Restore access with takeown/icacls, or point UNSLOTH_LOCAL_LLAMA_CPP_DIR at a readable build, then re-run setup."}@@ -645,10 +732,71 @@ function Invoke-ManagedLlamaCppPreflight {Write-StudioLine ""# A denied custom home cannot be claimed as an Unsloth-managed cache.$homeIsCustom = Test-StudioHomeIsCustom- # Preserve user-supplied wording when either override names this tree.+ # Preserve user-supplied wording when either override names this tree, or+ # names a build inside it: moving or deleting this folder takes that build+ # with it, and the later --with-llama-cpp-dir check then aborts on a path+ # we made disappear.$suppliedDir = if ($WithLlamaCppDir) { $WithLlamaCppDir } else { $env:UNSLOTH_LOCAL_LLAMA_CPP_DIR }- $userSupplied = (-not [string]::IsNullOrWhiteSpace($suppliedDir)) -and- ((Get-CanonicalDir -Path $suppliedDir) -eq (Get-CanonicalDir -Path $dir))+ # Walking the ancestors beats comparing the two canonical strings: an+ # override that does not exist yet cannot be resolved, so a prefix test+ # would compare a resolved path against an unresolved one and miss.+ $userSupplied = $false+ if (-not [string]::IsNullOrWhiteSpace($suppliedDir)) {+ $canonicalDir = [string](Get-CanonicalDir -Path $dir)+ $probe = [string](Get-CanonicalDir -Path $suppliedDir)+ while (-not [string]::IsNullOrWhiteSpace($probe)) {+ if ([string](Get-CanonicalDir -Path $probe) -eq $canonicalDir) {+ $userSupplied = $true+ break+ }+ $parent = ""+ try { $parent = [string](Split-Path -Parent $probe) } catch { $parent = "" }+ if ($parent -eq $probe) { break }+ $probe = $parent+ }+ }++ # Only the default branch below tells the user to delete this folder, so+ # only that case may move it. A user-supplied build is not ours to touch,+ # and an unreadable custom home cannot be confirmed as a managed cache.+ # Renaming needs DELETE on the folder plus write on its parent, neither of+ # which is read access, so this recovers denials that takeown and icacls+ # do not: the folder is a managed cache that setup reinstalls anyway.+ # Setup never makes this a link, so a link here is something the user+ # arranged, pointing at a build we were not told about. Moving it would+ # silently change which tree they run without touching the one they were+ # protecting, so it is left alone and named in the guidance instead.+ $isLink = $false+ try {+ $linkAttrs = [System.IO.File]::GetAttributes($dir)+ $isLink = ([int]$linkAttrs -band [int][System.IO.FileAttributes]::ReparsePoint) -ne 0+ } catch {+ # Unreadable attributes prove nothing, and "proves nothing" must not+ # mean "movable": fall through to the guidance rather than guess.+ $isLink = $true+ }+ if (-not $userSupplied -and -not $homeIsCustom -and -not $isLink) {+ $asideDir = "$dir.denied-$(Get-Date -Format 'yyyyMMddHHmmss')"+ $moved = $false+ try {+ Move-Item -LiteralPath $dir -Destination $asideDir -ErrorAction Stop+ $moved = $true+ } catch {+ # Expected when the denial also covers rename; fall through to guidance.+ }+ if ($moved) {+ step "permissions" "llama.cpp install at $dir could not be read, so it was moved aside" "Yellow"+ substep "Moved to $asideDir; it is a managed cache and setup reinstalls it" "Yellow"+ substep "Delete the moved folder once access is restored, it is no longer used" "Yellow"+ Write-StudioLine ""+ return $null+ }+ # This runs before the install lock, so a second run can have moved+ # the folder in between. Re-probe rather than report a denial for a+ # path that is no longer there and stop an install that can proceed.+ if ((Get-LlamaCppInstallReadState -Path $dir) -ne "Denied") { return $null }+ }+$reason = Write-PathAccessDenied -Path $dir -Label "llama.cpp install" `-UserSupplied:$userSupplied -OwnershipUnverified:$homeIsCustomsubstep "Stopping here, before phase 1: nothing has been downloaded or installed" "Yellow"@@ -4495,6 +4643,23 @@ if ($NeedNodeForSetup) {Write-StudioLine $nodeOut -ForegroundColor DarkGraystep "node" "install blocked by another active Unsloth install" "Red"Exit-SetupFailure "Node install is blocked by another active Unsloth install" 3+ } elseif ($nodeExit -eq 4) {+ # The Node cache could not be written. The generic advice below sends+ # people to nodejs.org and their router; neither is the fix, and the+ # same guidance the llama.cpp cache gets is the right one.+ Write-StudioLine $nodeOut -ForegroundColor DarkGray+ Write-StudioLine ""+ # The install lock and the .staging root live in $NodeParent, so the+ # refused object is not always $NodeDir, which in that case may not+ # even exist. Deleting it cannot make a parent writable, and the+ # parent holds more than Node, so it is never ours to offer up for+ # deletion either. install_node_prebuilt.py classifies which it was.+ if ($nodeOut -match "denied-scope: parent") {+ Exit-PathAccessDenied -Path $NodeParent -Label "Node install parent directory" `+ -OwnershipUnverified+ } else {+ Exit-PathAccessDenied -Path $NodeDir -Label "Node install"+ }} elseif ($nodeExit -ne 0) {Write-StudioLine $nodeOut -ForegroundColor DarkGrayWrite-StudioLine "[ERROR] Could not install an isolated Node automatically." -ForegroundColor Reddiff --git a/tests/studio/install/test_denied_llama_cpp_preflight.py b/tests/studio/install/test_denied_llama_cpp_preflight.pyindex 2571824407f..9bb3d2ec0ab 100644--- a/tests/studio/install/test_denied_llama_cpp_preflight.py+++ b/tests/studio/install/test_denied_llama_cpp_preflight.py@@ -30,6 +30,7 @@ SHARED_FUNCTIONS = ("Get-PathState","Get-LlamaCppInstallReadState","Get-PathDenialDetail",+ "Get-SecuritySoftwareNote","Write-PathAccessDenied","Get-CanonicalDir","Test-StudioHomeIsCustom",@@ -65,9 +66,10 @@ def _normalized(source: str) -> str:@pytest.mark.parametrize("name", SHARED_FUNCTIONS)def test_installer_copy_matches_setup(name: str) -> None:"""Edit one file, not the other, and this fails naming the function."""- assert _normalized(_function_source(INSTALL_PS1, name)) == _normalized(- _function_source(SETUP_PS1, name)- ), name+ assert (+ _normalized(_function_source(INSTALL_PS1, name))+ == _normalized(_function_source(SETUP_PS1, name))+ ), f"{name} differs between install.ps1 and studio/setup.ps1; run python3 scripts/sync_shared_ps1_helpers.py"def test_every_function_in_the_shared_block_is_compared() -> None:@@ -230,8 +232,11 @@ def test_a_tree_the_user_pointed_at_is_never_called_a_cache_we_own() -> None:"$suppliedDir = if ($WithLlamaCppDir) { $WithLlamaCppDir }"" else { $env:UNSLOTH_LOCAL_LLAMA_CPP_DIR }" in body)- # Compare canonical paths, including denied paths whose spelling differs.- assert "(Get-CanonicalDir -Path $suppliedDir) -eq (Get-CanonicalDir -Path $dir)" in body+ # Compare canonical paths, including denied paths whose spelling differs,+ # and every ancestor of the override: a build supplied from inside the+ # managed tree is the user's too.+ assert "$probe = [string](Get-CanonicalDir -Path $suppliedDir)" in body+ assert "if ([string](Get-CanonicalDir -Path $probe) -eq $canonicalDir) {" in bodyassert "$LocalIsCanonical = ($ResolvedLocal -eq $LlamaCppDir)" in SETUP_PS1assert ("Exit-PathAccessDenied -Path $ResolvedLocal"@@ -311,3 +316,139 @@ def test_setup_sh_reports_a_denied_default_home_cache() -> None:assert '_path_access_denied "$LLAMA_CPP_DIR" "llama.cpp install"' in block# Preserve the custom-home ownership guard's more cautious wording.assert block.index("_assert_studio_owned_or_absent") < block.index("_studio_dir_unreadable")+++def test_the_denial_detail_survives_a_directory_it_cannot_open() -> None:+ """Get-Item returns nothing for a directory whose ACL denies read, which is the+ one case this detail exists for, so the attributes have to come through an API+ that needs only FILE_READ_ATTRIBUTES."""+ for text in (INSTALL_PS1, SETUP_PS1):+ body = _function_source(text, "Get-PathDenialDetail")+ assert "[System.IO.File]::GetAttributes($Path)" in body+ # Get-Item may still run, but only after the attributes are in hand and+ # only to name a link target, which is the one thing it adds.+ assert body.index("GetAttributes($Path)") < body.index("Get-Item -LiteralPath")+ # The three causes elevation cannot fix, each named rather than folded+ # into the takeown and icacls advice that cannot clear them.+ assert "Encrypted" in body+ assert "cloud placeholder" in body+ assert "ReparsePoint" in body+ # Every caller passes a directory, where Encrypted only means new+ # descendants are encrypted by default. Listing never needs the key, so+ # claiming EFS there sends an ordinary ACL denial after a certificate.+ assert body.index("FileAttributes]::Directory") < body.index("FileAttributes]::Encrypted")+ assert "-not $isDirectory" in body+ # RECALL_ON_OPEN and RECALL_ON_DATA_ACCESS are missing from the+ # FileAttributes enum on Windows PowerShell 5.1.+ assert "0x00040000" in body and "0x00400000" in body+++def test_the_security_software_holding_the_folder_is_named() -> None:+ """takeown and icacls cannot clear a filter-driver block, and neither can+ elevation, so the Defender mode that blocks file access, and any third-party+ antivirus registered instead, are called out by name. A user told only that+ "antivirus can deny this" cannot tell which product to open."""+ for text in (INSTALL_PS1, SETUP_PS1):+ body = _function_source(text, "Get-SecuritySoftwareNote")+ # Neither branch correlates the block with this path, so neither may say+ # the ACL repair printed above it is pointless. Controlled folder access+ # gates writes, and a registered antivirus need not be involved at all.+ assert "will not help" not in body+ # A product that is not running cannot be holding the folder, and naming+ # it sends the user to the wrong console: 0xF000 carries the run state.+ assert "productState" in body and "0xF000" in body+ # Name the log that can actually attribute a Defender block.+ assert body.count("1123 and 1124") == 2+ # Absent Defender must read the same as a Defender that says no.+ assert "Get-Command Get-MpPreference -ErrorAction SilentlyContinue" in body+ # Every failure to tell must answer "" rather than guess: no Defender+ # module, no SecurityCenter registration, and a query that throws all+ # read the same as a machine that says no.+ assert "catch { $mode = $null }" in body+ assert "catch { $others = @() }" in body+ assert _normalized(body).rstrip().endswith('return ""\n}')+ # 1 Enabled blocks file access. 3 and 4 are direct disk-sector writes, so+ # they cannot explain a denied folder and must not be reported as if they+ # could. 2 AuditMode logs instead of blocking, so it rules itself out.+ assert "$mode -eq 1" in body+ assert "$mode -eq 2" in body+ assert "$mode -eq 3" not in body and "$mode -eq 4" not in body+ # Third-party suites ship the same feature under their own names, and+ # SecurityCenter2 is the registration all of them make.+ assert "root/SecurityCenter2" in body+ assert "AntiVirusProduct" in body+ # Defender registers there too, and it is covered by the mode check.+ assert "Windows Defender" in body and "Microsoft Defender" in body+ reporter = _function_source(text, "Write-PathAccessDenied")+ assert "Get-SecuritySoftwareNote" in reporter+ # After the generic line, so an empty answer leaves it standing.+ assert reporter.index("Antivirus or Controlled folder access") < reporter.index(+ "$securitySoftware = Get-SecuritySoftwareNote"+ )+++def test_a_denied_cache_is_moved_aside_only_when_it_is_ours_to_move() -> None:+ """Renaming needs DELETE on the folder plus write on its parent, neither of+ which is read access, so it recovers denials takeown and icacls do not. It is+ only allowed for the tree the guidance already tells the user to delete."""+ for text in (INSTALL_PS1, SETUP_PS1):+ body = _function_source(text, "Invoke-ManagedLlamaCppPreflight")+ assert "Move-Item -LiteralPath $dir -Destination $asideDir" in body+ guard = "if (-not $userSupplied -and -not $homeIsCustom -and -not $isLink) {"+ assert guard in body+ # Setup never makes this a link, so a link is the user's own arrangement+ # and moving it would change which tree they run.+ assert body.index("ReparsePoint") < body.index(guard)+ # Unreadable attributes prove nothing, which must not mean movable.+ assert "$isLink = $true" in body+ # A failed move falls through to the guidance rather than stopping.+ assert body.index(guard) < body.index("Write-PathAccessDenied -Path $dir")+ # A build supplied from inside this tree goes with it, and the later+ # --with-llama-cpp-dir check then aborts on a path we made disappear, so+ # containment counts as user-supplied and not just an exact match.+ assert "Split-Path -Parent $probe" in body+ assert body.index("$probe = $parent") < body.index(guard)+ # This runs before the install lock, so a second run can move the folder+ # first; reporting a denial for a path that is gone stops an install+ # that could have carried on.+ reprobe = '(Get-LlamaCppInstallReadState -Path $dir) -ne "Denied"'+ assert body.count(reprobe) == 2+ assert body.rindex(reprobe) < body.index("Write-PathAccessDenied -Path $dir")+++def test_the_shared_helpers_have_a_sync_script() -> None:+ """Hand-copying ten helpers between two files is how they drifted before."""+ script = (ROOT / "scripts" / "sync_shared_ps1_helpers.py").read_text(encoding = "utf-8")+ assert SHARED_BEGIN in script+ assert "--check" in script+++def test_a_denied_node_cache_gets_the_same_guidance_as_the_llama_cache() -> None:+ """The same denial reaches the Node cache, where it used to read "unexpected+ error" and then "install Node yourself, or check your network". Neither is+ the fix, and a user whose antivirus holds the folder can spend a long time on+ the second one."""+ node = (ROOT / "studio" / "install_node_prebuilt.py").read_text(encoding = "utf-8")+ assert "EXIT_DENIED = 4" in node+ assert "except PermissionError as exc:" in node+ # Windows does not always deliver winerror 5 as PermissionError.+ assert 'getattr(exc, "winerror", None) == 5' in node+ assert "errno.EACCES" in node+ assert "import errno" in node+ # The catch-all must stay last, or the classification never runs.+ tail = node[node.rindex("def main(") :]+ assert tail.index("except PermissionError") < tail.index("except Exception as exc:")+ # setup.ps1 turns the new code into the shared guidance rather than the+ # nodejs.org and network advice that follows every other nonzero exit.+ caller = SETUP_PS1.split("install_node_prebuilt.py", 1)[1].split("$env:PATH = ", 1)[0]+ assert "$nodeExit -eq 4" in caller+ assert 'Exit-PathAccessDenied -Path $NodeDir -Label "Node install"' in caller+ assert caller.index("$nodeExit -eq 4") < caller.index("https://nodejs.org/")+ # The install lock and the .staging root live in the parent, so half of the+ # denials that reach exit 4 are not on the cache at all. Deleting the cache+ # cannot make a parent writable, and the parent is never ours to offer up.+ assert 'DENIED_SCOPE_MARKER = "denied-scope: "' in node+ assert 'DENIED_SCOPE_PARENT = "parent"' in node+ assert '$nodeOut -match "denied-scope: parent"' in caller+ assert "Exit-PathAccessDenied -Path $NodeParent" in caller+ assert "-OwnershipUnverified" in callerdiff --git a/tests/studio/install/test_install_node_prebuilt_logic.py b/tests/studio/install/test_install_node_prebuilt_logic.pyindex 060266f42e0..3f278aee2c3 100644--- a/tests/studio/install/test_install_node_prebuilt_logic.py+++ b/tests/studio/install/test_install_node_prebuilt_logic.py@@ -900,6 +900,34 @@ def test_swap_into_place_survives_a_transient_lock(monkeypatch, tmp_path):assert (install_dir / "marker.txt").read_text(encoding = "utf-8") == "node"+def test_a_denial_in_the_cache_is_reported_against_the_cache(capsys, tmp_path):+ install_dir = tmp_path / "node"+ exc = PermissionError(+ 13, "Access is denied", str(install_dir / "UNSLOTH_NODE_PREBUILT_INFO.json")+ )+ assert M._report_access_denied(exc, install_dir) == M.EXIT_DENIED+ logged = "".join(capsys.readouterr())+ assert f"{M.DENIED_PATH_MARKER}{install_dir / 'UNSLOTH_NODE_PREBUILT_INFO.json'}" in logged+ assert f"{M.DENIED_SCOPE_MARKER}{M.DENIED_SCOPE_INSTALL_DIR}" in logged+ assert "not a download problem" in logged+++def test_a_denial_on_the_lock_is_reported_against_the_parent(capsys, tmp_path):+ # The install lock and the .staging root live one level up, so setup.ps1+ # would otherwise tell the user to delete a cache that is not the problem+ # and, when the parent is what is denied, may not even exist.+ install_dir = tmp_path / "node"+ exc = PermissionError(13, "Access is denied", str(M.install_lock_path(install_dir)))+ assert M._report_access_denied(exc, install_dir) == M.EXIT_DENIED+ assert f"{M.DENIED_SCOPE_MARKER}{M.DENIED_SCOPE_PARENT}" in "".join(capsys.readouterr())+++def test_a_denial_without_a_filename_still_exits_denied(capsys, tmp_path):+ assert M._report_access_denied(PermissionError(13, "Access is denied"), tmp_path / "node") == (+ M.EXIT_DENIED+ )+ # Nothing to classify, so the caller keeps its default and is told no lie.+ assert M.DENIED_SCOPE_MARKER not in "".join(capsys.readouterr())# The recorded runtime check: the 110 MB interpreter start it saves per run.def _real_node_tree(root: Path, host) -> None:"""The two files existing_install_matches spawns, as real bytes on disk.diff --git a/tests/studio/test_path_probe_access_denied.ps1 b/tests/studio/test_path_probe_access_denied.ps1index 1550a496f71..55a9363a420 100644--- a/tests/studio/test_path_probe_access_denied.ps1+++ b/tests/studio/test_path_probe_access_denied.ps1@@ -258,6 +258,7 @@ function step { param([string]`$Label, [string]`$Value, [string]`$Color = "Greenfunction substep { param([string]`$Message, [string]`$Color = "DarkGray") Write-Host " `$Message" }function Write-StudioLine { param([string]`$Message, [string]`$ForegroundColor) Write-Host `$Message }function Get-PathDenialDetail { param([string]`$Path) return "" }+function Get-SecuritySoftwareNote { return "" }$exitSetupSrc$writeDeniedSrc$exitDeniedSrc@@ -306,6 +307,7 @@ if ($mirrorSrc.Count -eq $mirrorFns.Count) {$mirrorHarness = @"`$ErrorActionPreference = "Stop"function Get-PathDenialDetail { param([string]`$Path) return "" }+function Get-SecuritySoftwareNote { return "" }$($mirrorSrc -join "`n")`$script:StudioVtOk = `$falseAdd-Content -LiteralPath `$args[0] -Value "REDIRECTED=`$([Console]::IsOutputRedirected)"@@ -454,7 +456,8 @@ if ($assertSrc -and $markSrc) {# return actionable guidance for a real denied tree.$installPath = [System.IO.Path]::Combine($repoRoot, "install.ps1")$preflightFns = @("Test-AccessDeniedError", "Get-PathState", "Get-LlamaCppInstallReadState",- "Get-PathDenialDetail", "Write-PathAccessDenied", "Get-CanonicalDir",+ "Get-PathDenialDetail", "Get-SecuritySoftwareNote",+ "Write-PathAccessDenied", "Get-CanonicalDir","Test-StudioHomeIsCustom", "Get-ManagedLlamaCppDir","Invoke-ManagedLlamaCppPreflight")$preflightSrc = @()@@ -488,11 +491,45 @@ Write-Host "CAN_DENY: `$oldFormTerminated"# Both override forms must switch to user-supplied wording.if (`$args[2] -eq "supplied") { `$WithLlamaCppDir = `$dir }if (`$args[2] -eq "env") { `$env:UNSLOTH_LOCAL_LLAMA_CPP_DIR = `$dir }+# A build supplied from inside the managed tree goes with it when the tree is+# moved or deleted, so the tree is not ours to touch either.+if (`$args[2] -eq "nested") { `$env:UNSLOTH_LOCAL_LLAMA_CPP_DIR = Join-Path `$dir "custom" }+# Renaming needs DELETE on the folder plus write on its parent. Taking either+# away is the denial that the move cannot recover, and the one the guidance is+# still written for.+if (`$args[2] -eq "unmovable") {+ if (`$onWindows) { icacls `$dir /deny "`$env:USERDOMAIN\`${env:USERNAME}:(DE)" *>`$null }+ else { chmod 500 (Split-Path -Parent `$dir) }+}+# A link is the user's own arrangement, so it must be reported rather than moved.+`$linkMade = `$false+if (`$args[2] -eq "link") {+ `$realDir = Join-Path `$env:USERPROFILE ".unsloth\real-llama.cpp"+ New-Item -ItemType Directory -Force -Path `$realDir | Out-Null+ if (`$onWindows) { icacls `$dir /remove:d "`$env:USERDOMAIN\`$env:USERNAME" *>`$null } else { chmod 755 `$dir }+ Remove-Item -Recurse -Force -LiteralPath `$dir -ErrorAction SilentlyContinue+ try {+ New-Item -ItemType SymbolicLink -Path `$dir -Target `$realDir -ErrorAction Stop | Out-Null+ `$linkMade = `$true+ } catch { `$linkMade = `$false }+ if (`$linkMade) {+ if (`$onWindows) { icacls `$realDir /deny "`$env:USERDOMAIN\`${env:USERNAME}:(OI)(CI)(RX)" *>`$null }+ else { chmod 000 `$realDir }+ }+}+Write-Host "LINK_MADE: `$linkMade"`$denied = Invoke-ManagedLlamaCppPreflightWrite-Host "DENIED_VERDICT: `$(if (`$null -eq `$denied) { "continue" } else { "stop" })"Write-Host "DENIED_REASON: `$denied"+# Whether the cache was moved out of the way, and whether anything was left at+# the original path for the next run to trip over again.+`$aside = @(Get-ChildItem -LiteralPath (Split-Path -Parent `$dir) -Force -ErrorAction SilentlyContinue |+ Where-Object { `$_.Name -like "llama.cpp.denied-*" })+Write-Host "ASIDE_COUNT: `$(`$aside.Count)"+Write-Host "ORIGINAL_EXISTS: `$(Test-Path -LiteralPath `$dir)"+if (-not `$onWindows) { chmod 755 (Split-Path -Parent `$dir) }if (`$onWindows) { icacls `$dir /remove:d "`$env:USERDOMAIN\`$env:USERNAME" *>`$null }-else { chmod 755 `$dir }+else { chmod 755 `$dir 2>`$null }"@$preflightFile = Join-Path ([System.IO.Path]::GetTempPath()) ("uns_pre_" + [guid]::NewGuid().ToString("N") + ".ps1")Set-Content -LiteralPath $preflightFile -Value $preflightHarness -Encoding utf8@@ -501,11 +538,15 @@ else { chmod 755 `$dir }# Use one child per mode so command-line counts remain unambiguous.$preflightRuns = @{}$preflightHome = ""+ # Each mode gets its own profile, so the folder a reason must name is the one+ # that mode ran against and not the first mode's.+ $preflightHomes = @{}try {- foreach ($mode in @("managed", "supplied", "env")) {+ foreach ($mode in @("managed", "supplied", "env", "nested", "unmovable", "link")) {$runHome = Join-Path ([System.IO.Path]::GetTempPath()) ("uns_home_" + [guid]::NewGuid().ToString("N"))New-Item -ItemType Directory -Force -Path $runHome | Out-Nullif ($mode -eq "managed") { $preflightHome = $runHome }+ $preflightHomes[$mode] = $runHometry {$preflightRuns[$mode] = & $pwshExe2 -NoProfile -File $preflightFile $runHome $(if ($onWindows) { "win" } else { "posix" }) $mode 2>&1 | Out-String} finally {@@ -524,7 +565,21 @@ else { chmod 755 `$dir }if ($out -notmatch "CAN_DENY: True") {Write-Host " SKIP cannot deny access on this host (running as root/admin?) -- preflight denial checks skipped" -ForegroundColor Yellow} else {- Check "an unreadable llama.cpp cache stops the install" ($out -match "DENIED_VERDICT: stop")+ # A cache we own and can still rename is recovered rather than reported:+ # renaming needs DELETE plus write on the parent, and neither is read+ # access, so this clears denials takeown and icacls cannot.+ Check "a denied cache that can be renamed is moved aside, not reported" (+ $out -match "DENIED_VERDICT: continue")+ Check "the moved cache leaves the original path free for the reinstall" (+ $out -match "ASIDE_COUNT: 1" -and $out -match "ORIGINAL_EXISTS: False")++ # Everything below is the tree the move cannot rescue, which is what the+ # guidance was always written for.+ $out = $preflightRuns["unmovable"]+ $expectedDir = Join-Path $preflightHomes["unmovable"] ".unsloth\llama.cpp"+ Check "an unreadable llama.cpp cache that cannot be moved stops the install" (+ $out -match "DENIED_VERDICT: stop")+ Check "the unmovable cache is not left half-renamed" ($out -match "ASIDE_COUNT: 0")Check "the preflight reason names the folder" ($out -match ("DENIED_REASON: .*" + [regex]::Escape($expectedDir)))Check "the preflight reason says a reinstall will not help" (@@ -536,19 +591,36 @@ else { chmod 755 `$dir }@($out -split "`r?`n" | Where-Object { $_ -match 'icacls .* /reset /T' }).Count -eq 1)Check "the preflight says the download has not happened yet" ($out -match "nothing has been downloaded or installed")++ # A link is the user's own arrangement: moving it would change which tree+ # they run without touching the one they were protecting.+ $linked = $preflightRuns["link"]+ if ($linked -notmatch "LINK_MADE: True") {+ Write-Host " SKIP cannot create a symlink on this host -- link checks skipped" -ForegroundColor Yellow+ } else {+ Check "a denied cache that is a link is never moved aside" (+ $linked -match "ASIDE_COUNT: 0" -and $linked -match "ORIGINAL_EXISTS: True")+ Check "a denied cache that is a link stops the install" (+ $linked -match "DENIED_VERDICT: stop")+ Check "a denied cache that is a link is described as one" ($linked -match "it is a link")+ }# Guidance may print ACL repair commands but must never run them.Check "the preflight does not run takeown or icacls itself" ($out -notmatch "SUCCESS: The file \(or folder\)" -and$out -notmatch "processed file:")- # Overrides may name the managed location itself; never call it disposable.- foreach ($mode in @("supplied", "env")) {+ # Overrides may name the managed location itself, or a build inside it;+ # never call either disposable, and never move the tree out from under+ # one, which the later --with-llama-cpp-dir check would then abort on.+ foreach ($mode in @("supplied", "env", "nested")) {$supplied = $preflightRuns[$mode]Check "a tree the user named ($mode) still stops the install" ($supplied -match "DENIED_VERDICT: stop")Check "a tree the user named ($mode) is not called a cache we own" ($supplied -match "DENIED_REASON: .*point UNSLOTH_LOCAL_LLAMA_CPP_DIR at a readable build" -and$supplied -notmatch "DENIED_REASON: .*Delete or rename")+ Check "a tree the user named ($mode) is left where it is" (+ $supplied -match "ASIDE_COUNT: 0" -and $supplied -match "ORIGINAL_EXISTS: True")}Check "the managed cache is still called one" ($out -match "DENIED_REASON: .*Delete or rename that folder")@@ -636,6 +708,12 @@ try {$entryWho = "$env:USERDOMAIN\$env:USERNAME"if ($onWindows) { icacls $entryLocked /deny "${entryWho}:(OI)(CI)(RX)" *>$null }else { chmod 000 $entryLocked }+ # Block the rename as well, so these keep exercising the guidance path.+ # The recovery has its own coverage in the preflight block above, and a+ # movable tree here would just reinstall and then stop on a trapped+ # expensive operation instead, testing nothing about the denial.+ if ($onWindows) { icacls $entryLocked /deny "${entryWho}:(DE)" *>$null }+ else { chmod 500 (Split-Path -Parent $entryLocked) }$canDenyEntrypoint = $falsetry {try { $null = Test-Path (Join-Path $entryLocked "UNSLOTH_PREBUILT_INFO.json") }