Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)
Python
Install Muse Code natively on Windows (#1598)
Ali Khokhar8d18add09238
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex 349b2eb4..bd595ae8 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -269,7 +269,12 @@ and [scripts/uninstall.ps1](scripts/uninstall.ps1) remove those exact desktopartifacts, the FCC uv tool, and the managed `~/.fcc/` tree from[config/paths.py](src/free_claude_code/config/paths.py); they do not removeuv, Claude Code, Codex, Pi, OpenCode, Cline, Hermes, DeepSeek Harness, Grok-Build, Muse Code, or uv-managed Python runtimes. [scripts/ci.sh](scripts/ci.sh) and+Build, Muse Code, or uv-managed Python runtimes. On native Windows,+[scripts/install-muse.ps1](scripts/install-muse.ps1) owns only FCC's fixed Muse+executable, ownership record, and exact user-PATH entry; its independent+[scripts/uninstall-muse.ps1](scripts/uninstall-muse.ps1) removes only those+managed assets and is never called by FCC's general uninstaller.+[scripts/ci.sh](scripts/ci.sh) and[scripts/ci.ps1](scripts/ci.ps1) mirror [.github/workflows/tests.yml](.github/workflows/tests.yml)for local pre-push verification.@@ -1508,9 +1513,10 @@ installed `fcc-muse` launcher for Muse Code 0.2.1 or newer:`x-should-retry: false`. FCC still owns provider retries and ordered modelfallback inside each repeated request; the launcher does not mutate Muse'spersistent retry settings.-- Meta's official installer currently supports macOS, Linux, and WSL. The- PowerShell installer verifies an existing compatible Muse binary but does not- invent a Windows installation or update path.+- Meta's official installer supports macOS, Linux, and WSL. On native Windows,+ FCC's standalone Muse installer selects and verifies Meta's published Windows+ artifact, then owns its fixed local executable and PATH lifecycle without+ adopting external Muse installations.[cli/managed/](src/free_claude_code/cli/managed/) owns managed Claude Code subprocesses used byDiscord and Telegram messaging. Managed task invocations extend the same proxydiff --git a/README.md b/README.mdindex f29a37a0..3b624f5f 100644--- a/README.md+++ b/README.md@@ -585,6 +585,22 @@ Run `fcc-server --version` to check the installed version without starting FCC.Re-run the matching command from [Install Or Update](#install).+### Muse Code on native Windows++Rerunning FCC's Windows installer with Muse Code selected installs or updates FCC's managed Muse executable. To install or update only Muse Code:++```powershell+& ([scriptblock]::Create((irm "https://raw.githubusercontent.com/Alishahryar1/free-claude-code/main/scripts/install-muse.ps1")))+```++To remove only that managed Muse executable while preserving Muse data and other installations:++```powershell+& ([scriptblock]::Create((irm "https://raw.githubusercontent.com/Alishahryar1/free-claude-code/main/scripts/uninstall-muse.ps1")))+```++FCC's ordinary uninstaller below continues to leave Muse Code installed.+### UninstallStop every running FCC command before uninstalling.diff --git a/pyproject.toml b/pyproject.tomlindex 3d77cd0a..c4743508 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "free-claude-code"-version = "5.15.7"+version = "5.15.8"description = "Local proxy connecting coding agents to OpenAI-compatible AI providers"readme = "README.md"requires-python = ">=3.14.0"diff --git a/scripts/install-muse.ps1 b/scripts/install-muse.ps1new file mode 100644index 00000000..4ba72b2d--- /dev/null+++ b/scripts/install-muse.ps1@@ -0,0 +1,915 @@+[CmdletBinding()]+param(+ [switch] $DryRun,+ [switch] $Help,+ [Parameter(ValueFromRemainingArguments = $true)]+ [object[]] $RemainingArgs = @()+)++Set-StrictMode -Version Latest+$ErrorActionPreference = "Stop"+$ProgressPreference = "SilentlyContinue"++$script:MuseStableChannelUrl = "https://api.meta.ai/muse-code/channels/muse-stable"+$script:MuseOwner = "free-claude-code-muse-installer"+$script:MuseOwnerSchemaVersion = 1+$script:MuseMinimumVersion = [version] "0.2.1"++function Show-MuseInstallerUsage {+ @"+Usage: install-muse.ps1 [options]++Installs or updates FCC's managed native-Windows Muse Code executable.+The managed command is placed in %LOCALAPPDATA%\Programs\Muse Code\bin.++Options:+ -DryRun Print actions without downloading or changing state.+ -Help Show this help text.++To remove only this managed Muse installation, run scripts/uninstall-muse.ps1.+"@+}++function Get-MuseArtifactKey {+ param([Parameter(Mandatory = $true)][string] $Architecture)++ switch ($Architecture.Trim().ToUpperInvariant()) {+ "AMD64" { return "x86_windows" }+ "X64" { return "x86_windows" }+ "X86_64" { return "x86_windows" }+ "ARM64" { return "aarch64_windows" }+ default {+ throw "Muse Code does not provide a supported Windows release for architecture '$Architecture'."+ }+ }+}++function Get-MuseNativeArchitecture {+ return [Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString()+}++function Test-MuseSafeReleaseUrl {+ param([Parameter(Mandatory = $true)][string] $Value)++ if ([string]::IsNullOrWhiteSpace($Value) -or $Value -match '[\x00-\x1F\x7F]') {+ return $false+ }++ $uri = $null+ if (-not [Uri]::TryCreate($Value, [UriKind]::Absolute, [ref] $uri)) {+ return $false+ }++ return (+ $uri.Scheme -eq "https" -and+ $uri.DnsSafeHost -eq "lookaside.facebook.com" -and+ [string]::IsNullOrEmpty($uri.UserInfo) -and+ [string]::IsNullOrEmpty($uri.Fragment) -and+ ($uri.IsDefaultPort -or $uri.Port -eq 443)+ )+}++function Assert-MuseStableChannel {+ param([Parameter(Mandatory = $true)] $Channel)++ if ((-not (Test-MuseObjectProperty -Object $Channel -Name "channel")) -or $Channel.channel -ne "muse-stable") {+ throw "Meta's Muse stable channel response did not identify the muse-stable channel."+ }+ if ((-not (Test-MuseObjectProperty -Object $Channel -Name "state")) -or $Channel.state -ne "public") {+ throw "Meta's Muse stable channel is not public."+ }+ if (+ (-not (Test-MuseObjectProperty -Object $Channel -Name "version")) -or+ ([string] $Channel.version) -notmatch '^\d+\.\d+\.\d+-R\d+(?:\.\d+)?$'+ ) {+ throw "Meta's Muse stable channel returned an invalid release version."+ }+ if (+ (-not (Test-MuseObjectProperty -Object $Channel -Name "manifest_url")) -or+ (-not (Test-MuseSafeReleaseUrl -Value ([string] $Channel.manifest_url)))+ ) {+ throw "Meta's Muse manifest URL must use HTTPS on lookaside.facebook.com."+ }+}++function Test-MusePositiveInteger {+ param($Value)++ $integerTypes = @(+ [byte],+ [sbyte],+ [int16],+ [uint16],+ [int32],+ [uint32],+ [int64],+ [uint64]+ )+ foreach ($integerType in $integerTypes) {+ if ($Value -is $integerType) {+ return ([decimal] $Value) -gt 0+ }+ }+ return $false+}++function Test-MuseObjectProperty {+ param(+ [Parameter(Mandatory = $true)] $Object,+ [Parameter(Mandatory = $true)][string] $Name+ )++ return $null -ne $Object -and $Object.PSObject.Properties.Name -contains $Name+}++function Resolve-MuseArtifact {+ param(+ [Parameter(Mandatory = $true)][string] $Architecture,+ [Parameter(Mandatory = $true)] $Channel,+ [Parameter(Mandatory = $true)] $Manifest+ )++ $artifactKey = Get-MuseArtifactKey -Architecture $Architecture++ Assert-MuseStableChannel -Channel $Channel++ if (+ (-not (Test-MuseObjectProperty -Object $Manifest -Name "version")) -or+ ([string] $Manifest.version) -ne ([string] $Channel.version)+ ) {+ throw "Meta's Muse release manifest version does not match the stable channel."+ }+ if (+ (-not (Test-MuseObjectProperty -Object $Manifest -Name "checksum_algorithm")) -or+ ([string] $Manifest.checksum_algorithm) -cne "sha256"+ ) {+ throw "Meta's Muse release manifest must use sha256 checksums."+ }+ if (-not (Test-MuseObjectProperty -Object $Manifest -Name "artifacts")) {+ throw "Meta's Muse release manifest did not contain artifacts."+ }++ $artifactProperty = $Manifest.artifacts.PSObject.Properties[$artifactKey]+ if ($null -eq $artifactProperty) {+ throw "Meta's Muse release manifest did not contain the '$artifactKey' artifact."+ }+ $artifact = $artifactProperty.Value+ if (+ (-not (Test-MuseObjectProperty -Object $artifact -Name "url")) -or+ (-not (Test-MuseSafeReleaseUrl -Value ([string] $artifact.url)))+ ) {+ throw "Meta's Muse artifact URL must use HTTPS on lookaside.facebook.com."+ }+ if (+ (-not (Test-MuseObjectProperty -Object $artifact -Name "checksum")) -or+ ([string] $artifact.checksum) -cnotmatch '^[0-9a-f]{64}$'+ ) {+ throw "Meta's Muse artifact checksum must be a lowercase SHA-256 value."+ }+ if (+ (-not (Test-MuseObjectProperty -Object $artifact -Name "size")) -or+ (-not (Test-MusePositiveInteger -Value $artifact.size))+ ) {+ throw "Meta's Muse artifact size must be a positive integer."+ }++ return [pscustomobject] @{+ ReleaseVersion = [string] $Channel.version+ ArtifactKey = $artifactKey+ Url = [string] $artifact.url+ Sha256 = [string] $artifact.checksum+ Size = [long] $artifact.size+ }+}++function Read-MuseOwnershipRecord {+ param([Parameter(Mandatory = $true)][string] $RecordPath)++ if (-not (Test-Path -LiteralPath $RecordPath -PathType Leaf)) {+ return $null+ }++ try {+ $record = Get-Content -LiteralPath $RecordPath -Raw | ConvertFrom-Json+ }+ catch {+ throw "The Muse ownership record is malformed; refusing to change the managed directory."+ }++ $expectedFields = @(+ "schema_version",+ "owner",+ "release_version",+ "artifact_key",+ "sha256",+ "size"+ )+ $actualFields = @($record.PSObject.Properties.Name)+ if (+ $actualFields.Count -ne $expectedFields.Count -or+ @($expectedFields | Where-Object { $_ -notin $actualFields }).Count -gt 0 -or+ $record.schema_version -ne $script:MuseOwnerSchemaVersion -or+ $record.owner -ne $script:MuseOwner -or+ ([string] $record.release_version) -notmatch '^\d+\.\d+\.\d+-R\d+(?:\.\d+)?$' -or+ $record.artifact_key -notin @("x86_windows", "aarch64_windows") -or+ ([string] $record.sha256) -cnotmatch '^[0-9a-f]{64}$' -or+ (-not (Test-MusePositiveInteger -Value $record.size))+ ) {+ throw "The Muse ownership record is unsupported or foreign; refusing to change the managed directory."+ }++ return $record+}++function Get-MuseCanonicalPath {+ param([Parameter(Mandatory = $true)][string] $Path)++ if ([string]::IsNullOrWhiteSpace($Path)) {+ return $null+ }+ try {+ $fullPath = [IO.Path]::GetFullPath($Path.Trim())+ $root = [IO.Path]::GetPathRoot($fullPath)+ while (+ $fullPath.Length -gt $root.Length -and+ ($fullPath.EndsWith("\") -or $fullPath.EndsWith("/"))+ ) {+ $fullPath = $fullPath.Substring(0, $fullPath.Length - 1)+ }+ return $fullPath+ }+ catch {+ return $null+ }+}++function Test-MuseEquivalentPath {+ param(+ [string] $Left,+ [string] $Right+ )++ $canonicalLeft = Get-MuseCanonicalPath -Path $Left+ $canonicalRight = Get-MuseCanonicalPath -Path $Right+ return (+ $null -ne $canonicalLeft -and+ $null -ne $canonicalRight -and+ [string]::Equals(+ $canonicalLeft,+ $canonicalRight,+ [StringComparison]::OrdinalIgnoreCase+ )+ )+}++function Add-MusePathValue {+ param(+ [AllowEmptyString()][string] $PathValue,+ [Parameter(Mandatory = $true)][string] $ManagedBin+ )++ $canonicalManagedBin = Get-MuseCanonicalPath -Path $ManagedBin+ if ($null -eq $canonicalManagedBin) {+ throw "The managed Muse bin directory is invalid."+ }+ if ([string]::IsNullOrEmpty($PathValue)) {+ return $canonicalManagedBin+ }++ $entries = @($PathValue -split [regex]::Escape([string] [IO.Path]::PathSeparator))+ $unrelated = @(+ $entries | Where-Object {+ -not (Test-MuseEquivalentPath -Left ([string] $_) -Right $canonicalManagedBin)+ }+ )+ return (@($canonicalManagedBin) + $unrelated) -join [IO.Path]::PathSeparator+}++function Remove-MusePathValue {+ param(+ [AllowEmptyString()][string] $PathValue,+ [Parameter(Mandatory = $true)][string] $ManagedBin+ )++ if ([string]::IsNullOrEmpty($PathValue)) {+ return ""+ }+ $entries = @($PathValue -split [regex]::Escape([string] [IO.Path]::PathSeparator))+ return @(+ $entries | Where-Object {+ -not (Test-MuseEquivalentPath -Left ([string] $_) -Right $ManagedBin)+ }+ ) -join [IO.Path]::PathSeparator+}++function Assert-MuseArtifactIntegrity {+ param(+ [Parameter(Mandatory = $true)][string] $Path,+ [Parameter(Mandatory = $true)][long] $ExpectedSize,+ [Parameter(Mandatory = $true)][string] $ExpectedSha256+ )++ if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {+ throw "The downloaded Muse artifact is missing."+ }+ $actualSize = (Get-Item -LiteralPath $Path).Length+ if ($actualSize -ne $ExpectedSize) {+ throw "The downloaded Muse artifact size did not match the release manifest."+ }+ $stream = [IO.File]::OpenRead($Path)+ $sha256 = [Security.Cryptography.SHA256]::Create()+ try {+ $hashBytes = $sha256.ComputeHash($stream)+ $actualSha256 = ([BitConverter]::ToString($hashBytes) -replace "-", "").ToLowerInvariant()+ }+ finally {+ $sha256.Dispose()+ $stream.Dispose()+ }+ if ($actualSha256 -cne $ExpectedSha256) {+ throw "The downloaded Muse artifact SHA-256 did not match the release manifest."+ }+}++function Get-MuseInstallPaths {+ if ([string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {+ throw "LOCALAPPDATA is not set; cannot locate the managed Muse Code installation."+ }++ $root = Join-Path $env:LOCALAPPDATA "Programs\Muse Code"+ $bin = Join-Path $root "bin"+ return [pscustomobject] @{+ Root = $root+ Bin = $bin+ Executable = Join-Path $bin "muse.exe"+ Record = Join-Path $root ".fcc-muse-install.json"+ }+}++function Get-MuseUserPathValue {+ return [Environment]::GetEnvironmentVariable("Path", "User")+}++function Set-MuseUserPathValue {+ param([AllowEmptyString()][string] $Value)++ [Environment]::SetEnvironmentVariable("Path", $Value, "User")+}++function Resolve-MuseExternalCommand {+ $originalPath = $env:Path+ $userPath = Get-MuseUserPathValue+ try {+ $combined = @(+ $originalPath,+ $userPath+ ) | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }+ $env:Path = $combined -join [IO.Path]::PathSeparator+ $commands = @(Get-Command "muse" -CommandType Application -ErrorAction SilentlyContinue)+ if ($commands.Count -eq 0) {+ return $null+ }+ return $commands[0]+ }+ finally {+ $env:Path = $originalPath+ }+}++function ConvertTo-MuseNativeArgument {+ param([AllowEmptyString()][string] $Argument)++ if ($Argument.Length -gt 0 -and $Argument -notmatch '[\s"]') {+ return $Argument+ }++ $builder = [Text.StringBuilder]::new()+ [void] $builder.Append('"')+ $backslashes = 0+ foreach ($character in $Argument.ToCharArray()) {+ if ([int] $character -eq 92) {+ $backslashes += 1+ continue+ }+ if ([int] $character -eq 34) {+ for ($index = 0; $index -lt (($backslashes * 2) + 1); $index += 1) {+ [void] $builder.Append([char] 92)+ }+ [void] $builder.Append($character)+ $backslashes = 0+ continue+ }+ for ($index = 0; $index -lt $backslashes; $index += 1) {+ [void] $builder.Append([char] 92)+ }+ $backslashes = 0+ [void] $builder.Append($character)+ }+ for ($index = 0; $index -lt ($backslashes * 2); $index += 1) {+ [void] $builder.Append([char] 92)+ }+ [void] $builder.Append('"')+ return $builder.ToString()+}++function Invoke-MuseNativeProcess {+ param(+ [Parameter(Mandatory = $true)][string] $FilePath,+ [string[]] $Arguments = @(),+ [int] $TimeoutMilliseconds = 5000+ )++ $startInfo = [Diagnostics.ProcessStartInfo]::new()+ $startInfo.FileName = $FilePath+ $startInfo.Arguments = ($Arguments | ForEach-Object {+ ConvertTo-MuseNativeArgument -Argument ([string] $_)+ }) -join " "+ $startInfo.UseShellExecute = $false+ $startInfo.CreateNoWindow = $true+ $startInfo.RedirectStandardOutput = $true+ $startInfo.RedirectStandardError = $true++ $process = [Diagnostics.Process]::new()+ $process.StartInfo = $startInfo+ try {+ try {+ if (-not $process.Start()) {+ return [pscustomobject] @{+ Started = $false+ TimedOut = $false+ ExitCode = $null+ Output = ""+ }+ }+ }+ catch {+ return [pscustomobject] @{+ Started = $false+ TimedOut = $false+ ExitCode = $null+ Output = ""+ }+ }++ $stdoutTask = $process.StandardOutput.ReadToEndAsync()+ $stderrTask = $process.StandardError.ReadToEndAsync()+ if (-not $process.WaitForExit($TimeoutMilliseconds)) {+ try {+ $process.Kill()+ $process.WaitForExit()+ }+ catch {+ # The process may have exited between the timeout and the kill.+ }+ return [pscustomobject] @{+ Started = $true+ TimedOut = $true+ ExitCode = $null+ Output = ""+ }+ }++ $process.WaitForExit()+ $stdout = $stdoutTask.GetAwaiter().GetResult()+ $stderr = $stderrTask.GetAwaiter().GetResult()+ return [pscustomobject] @{+ Started = $true+ TimedOut = $false+ ExitCode = $process.ExitCode+ Output = (@($stdout, $stderr) | Where-Object {+ -not [string]::IsNullOrWhiteSpace($_)+ }) -join [Environment]::NewLine+ }+ }+ finally {+ $process.Dispose()+ }+}++function Get-MuseVersionProbe {+ param([Parameter(Mandatory = $true)][string] $Path)++ $result = Invoke-MuseNativeProcess -FilePath $Path -Arguments @("--version")+ if (-not $result.Started) {+ return [pscustomobject] @{+ Compatible = $false+ Version = $null+ Reason = "could not be started"+ }+ }+ if ($result.TimedOut) {+ return [pscustomobject] @{+ Compatible = $false+ Version = $null+ Reason = "timed out"+ }+ }+ if ($result.ExitCode -ne 0) {+ return [pscustomobject] @{+ Compatible = $false+ Version = $null+ Reason = "returned exit code $($result.ExitCode)"+ }+ }+ if ($result.Output -notmatch '(?m)^\s*Muse Code\s+(?<version>\d+\.\d+\.\d+)(?:\s+\([^\r\n]+\))?\s*$') {+ return [pscustomobject] @{+ Compatible = $false+ Version = $null+ Reason = "did not identify itself as Muse Code"+ }+ }++ $version = [version] $Matches["version"]+ if ($version -lt $script:MuseMinimumVersion) {+ return [pscustomobject] @{+ Compatible = $false+ Version = $version+ Reason = "is older than Muse Code $($script:MuseMinimumVersion)"+ }+ }+ return [pscustomobject] @{+ Compatible = $true+ Version = $version+ Reason = ""+ }+}++function Assert-CompatibleMuseBinary {+ param(+ [Parameter(Mandatory = $true)][string] $Path,+ [Parameter(Mandatory = $true)][string] $Context+ )++ $probe = Get-MuseVersionProbe -Path $Path+ if (-not $probe.Compatible) {+ throw "$Context at '$Path' $($probe.Reason)."+ }+}++function Get-MuseReleaseArtifact {+ param([Parameter(Mandatory = $true)][string] $Architecture)++ try {+ $channel = Invoke-RestMethod `+ -Uri $script:MuseStableChannelUrl `+ -Method Get `+ -TimeoutSec 30 `+ -ErrorAction Stop+ }+ catch {+ throw "Could not fetch Meta's public Muse stable channel."+ }+ Assert-MuseStableChannel -Channel $channel++ try {+ $manifest = Invoke-RestMethod `+ -Uri ([string] $channel.manifest_url) `+ -Method Get `+ -TimeoutSec 30 `+ -ErrorAction Stop+ }+ catch {+ throw "Could not fetch Meta's public Muse release manifest."+ }+ return Resolve-MuseArtifact `+ -Architecture $Architecture `+ -Channel $channel `+ -Manifest $manifest+}++function Save-MuseArtifact {+ param(+ [Parameter(Mandatory = $true)][string] $Url,+ [Parameter(Mandatory = $true)][string] $Destination+ )++ Write-Host "+ Download Meta's Muse executable to a temporary file"+ try {+ Invoke-WebRequest `+ -Uri $Url `+ -OutFile $Destination `+ -TimeoutSec 600 `+ -UseBasicParsing `+ -ErrorAction Stop+ }+ catch {+ throw "Could not download Meta's public Muse Windows executable."+ }+}++function New-MuseOwnershipRecord {+ param([Parameter(Mandatory = $true)] $Artifact)++ return [ordered] @{+ schema_version = $script:MuseOwnerSchemaVersion+ owner = $script:MuseOwner+ release_version = $Artifact.ReleaseVersion+ artifact_key = $Artifact.ArtifactKey+ sha256 = $Artifact.Sha256+ size = [long] $Artifact.Size+ }+}++function Write-MuseRecordContent {+ param(+ [Parameter(Mandatory = $true)][string] $RecordPath,+ [Parameter(Mandatory = $true)][string] $Content+ )++ $temporaryPath = "$RecordPath.$([guid]::NewGuid().ToString('N')).tmp"+ $backupPath = "$RecordPath.$([guid]::NewGuid().ToString('N')).backup"+ try {+ [IO.File]::WriteAllText(+ $temporaryPath,+ $Content,+ [Text.UTF8Encoding]::new($false)+ )+ if (Test-Path -LiteralPath $RecordPath -PathType Leaf) {+ [IO.File]::Replace($temporaryPath, $RecordPath, $backupPath)+ Remove-Item -LiteralPath $backupPath -Force -ErrorAction SilentlyContinue+ }+ else {+ [IO.File]::Move($temporaryPath, $RecordPath)+ }+ }+ finally {+ Remove-Item -LiteralPath $temporaryPath -Force -ErrorAction SilentlyContinue+ Remove-Item -LiteralPath $backupPath -Force -ErrorAction SilentlyContinue+ }+}++function Write-MuseOwnershipRecord {+ param(+ [Parameter(Mandatory = $true)][string] $RecordPath,+ [Parameter(Mandatory = $true)] $Artifact+ )++ $content = New-MuseOwnershipRecord -Artifact $Artifact | ConvertTo-Json+ Write-MuseRecordContent -RecordPath $RecordPath -Content $content+}++function Restore-MuseOwnershipRecord {+ param(+ [Parameter(Mandatory = $true)][string] $RecordPath,+ [AllowNull()][string] $PreviousContent+ )++ if ($null -eq $PreviousContent) {+ Remove-Item -LiteralPath $RecordPath -Force -ErrorAction SilentlyContinue+ return+ }+ Write-MuseRecordContent -RecordPath $RecordPath -Content $PreviousContent+}++function Test-MuseRecordMatchesArtifact {+ param(+ [Parameter(Mandatory = $true)] $Record,+ [Parameter(Mandatory = $true)] $Artifact+ )++ return (+ $Record.release_version -eq $Artifact.ReleaseVersion -and+ $Record.artifact_key -eq $Artifact.ArtifactKey -and+ $Record.sha256 -ceq $Artifact.Sha256 -and+ [long] $Record.size -eq [long] $Artifact.Size+ )+}++function Test-MuseManagedArtifactCurrent {+ param(+ [Parameter(Mandatory = $true)] $Paths,+ [Parameter(Mandatory = $true)] $Record,+ [Parameter(Mandatory = $true)] $Artifact+ )++ if (-not (Test-MuseRecordMatchesArtifact -Record $Record -Artifact $Artifact)) {+ return $false+ }+ try {+ Assert-MuseArtifactIntegrity `+ -Path $Paths.Executable `+ -ExpectedSize $Artifact.Size `+ -ExpectedSha256 $Artifact.Sha256+ Assert-CompatibleMuseBinary `+ -Path $Paths.Executable `+ -Context "The managed Muse Code executable"+ return $true+ }+ catch {+ return $false+ }+}++function Publish-MuseExecutable {+ param(+ [Parameter(Mandatory = $true)][string] $CandidatePath,+ [Parameter(Mandatory = $true)][string] $ExecutablePath+ )++ $bin = Split-Path -Parent $ExecutablePath+ $stagingPath = Join-Path $bin (".muse-" + [guid]::NewGuid().ToString("N") + ".staging.exe")+ $backupPath = Join-Path $bin (".muse-" + [guid]::NewGuid().ToString("N") + ".backup.exe")+ $replacementCompleted = $false+ $backupRestored = $false+ try {+ Copy-Item -LiteralPath $CandidatePath -Destination $stagingPath+ if (Test-Path -LiteralPath $ExecutablePath -PathType Leaf) {+ try {+ [IO.File]::Replace($stagingPath, $ExecutablePath, $backupPath)+ $replacementCompleted = $true+ }+ catch {+ $publicationError = $_+ if (Test-Path -LiteralPath $backupPath -PathType Leaf) {+ try {+ Remove-Item -LiteralPath $ExecutablePath -Force -ErrorAction SilentlyContinue+ [IO.File]::Move($backupPath, $ExecutablePath)+ $backupRestored = $true+ }+ catch {+ throw "Muse Code update failed and the previous executable could not be restored. The backup remains at '$backupPath'."+ }+ }+ throw $publicationError+ }+ }+ else {+ [IO.File]::Move($stagingPath, $ExecutablePath)+ $replacementCompleted = $true+ }+ }+ finally {+ Remove-Item -LiteralPath $stagingPath -Force -ErrorAction SilentlyContinue+ if ($replacementCompleted -or $backupRestored) {+ Remove-Item -LiteralPath $backupPath -Force -ErrorAction SilentlyContinue+ }+ }+}++function Update-MusePath {+ param([Parameter(Mandatory = $true)][string] $ManagedBin)++ $currentUserPath = [string] (Get-MuseUserPathValue)+ $newUserPath = Add-MusePathValue `+ -PathValue $currentUserPath `+ -ManagedBin $ManagedBin+ if (-not [string]::Equals($currentUserPath, $newUserPath, [StringComparison]::Ordinal)) {+ Set-MuseUserPathValue -Value $newUserPath+ }+ $env:Path = Add-MusePathValue -PathValue ([string] $env:Path) -ManagedBin $ManagedBin+}++function Remove-EmptyMuseInstallDirectories {+ param([Parameter(Mandatory = $true)] $Paths)++ foreach ($directory in @($Paths.Bin, $Paths.Root)) {+ if (+ (Test-Path -LiteralPath $directory -PathType Container) -and+ @(Get-ChildItem -LiteralPath $directory -Force).Count -eq 0+ ) {+ Remove-Item -LiteralPath $directory -Force -ErrorAction SilentlyContinue+ }+ }+}++function Remove-MuseTemporaryRoot {+ param([Parameter(Mandatory = $true)][string] $Path)++ if (-not (Test-Path -LiteralPath $Path -PathType Container)) {+ return+ }+ $temporaryBase = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd("\", "/")+ $resolvedPath = [IO.Path]::GetFullPath($Path).TrimEnd("\", "/")+ $requiredPrefix = $temporaryBase + [IO.Path]::DirectorySeparatorChar+ $leafName = [IO.Path]::GetFileName($resolvedPath)+ if (+ (-not $resolvedPath.StartsWith($requiredPrefix, [StringComparison]::OrdinalIgnoreCase)) -or+ (-not $leafName.StartsWith("fcc-muse-", [StringComparison]::Ordinal))+ ) {+ throw "Refusing to remove an unexpected Muse temporary directory: $resolvedPath"+ }+ Remove-Item -LiteralPath $resolvedPath -Recurse -Force+}++function Invoke-MuseInstaller {+ $architecture = Get-MuseNativeArchitecture+ [void] (Get-MuseArtifactKey -Architecture $architecture)+ $paths = Get-MuseInstallPaths++ if ($DryRun) {+ Write-Host "Dry run: inspect existing Muse ownership and commands."+ Write-Host "+ GET $script:MuseStableChannelUrl"+ Write-Host "+ verify release metadata, exact artifact size, SHA-256, and Muse version"+ Write-Host "+ install to '$($paths.Executable)' and prepend '$($paths.Bin)' to the user PATH"+ Write-Host "Dry run complete. No changes were made."+ return+ }++ if (+ (Test-Path -LiteralPath $paths.Root) -and+ (-not (Test-Path -LiteralPath $paths.Root -PathType Container))+ ) {+ throw "The managed Muse Code install path exists but is not owned by FCC: '$($paths.Root)'. Move or remove it, then rerun the installer."+ }++ $record = Read-MuseOwnershipRecord -RecordPath $paths.Record+ if ($null -eq $record) {+ if (+ (Test-Path -LiteralPath $paths.Root -PathType Container) -and+ @(Get-ChildItem -LiteralPath $paths.Root -Force).Count -gt 0+ ) {+ throw "The managed Muse Code directory exists but is not owned by FCC: '$($paths.Root)'. Move or remove it, then rerun the installer."+ }++ $externalCommand = Resolve-MuseExternalCommand+ if ($null -ne $externalCommand) {+ $externalPath = [string] $externalCommand.Source+ $probe = Get-MuseVersionProbe -Path $externalPath+ if (-not $probe.Compatible) {+ throw "A conflicting 'muse' command at '$externalPath' $($probe.Reason). Update or remove that command, then rerun the installer."+ }+ Write-Host "Compatible Muse Code already found at '$externalPath'; leaving it unchanged."+ return+ }+ }++ $artifact = Get-MuseReleaseArtifact -Architecture $architecture+ if (+ $null -ne $record -and+ (Test-MuseManagedArtifactCurrent -Paths $paths -Record $record -Artifact $artifact)+ ) {+ Update-MusePath -ManagedBin $paths.Bin+ Assert-CompatibleMuseBinary `+ -Path $paths.Executable `+ -Context "The managed Muse Code executable"+ Write-Host "Muse Code $($artifact.ReleaseVersion) is already current and verified."+ return+ }++ $temporaryRoot = Join-Path ([IO.Path]::GetTempPath()) ("fcc-muse-" + [guid]::NewGuid().ToString("N"))+ $candidatePath = Join-Path $temporaryRoot "muse.exe"+ try {+ New-Item -ItemType Directory -Path $temporaryRoot | Out-Null+ Save-MuseArtifact -Url $artifact.Url -Destination $candidatePath+ Assert-MuseArtifactIntegrity `+ -Path $candidatePath `+ -ExpectedSize $artifact.Size `+ -ExpectedSha256 $artifact.Sha256+ Assert-CompatibleMuseBinary `+ -Path $candidatePath `+ -Context "The downloaded Muse Code executable"++ New-Item -ItemType Directory -Path $paths.Bin -Force | Out-Null+ $previousRecordContent = if (Test-Path -LiteralPath $paths.Record -PathType Leaf) {+ [IO.File]::ReadAllText($paths.Record)+ }+ else {+ $null+ }+ $recordWritten = $false+ try {+ Write-MuseOwnershipRecord -RecordPath $paths.Record -Artifact $artifact+ $recordWritten = $true+ Publish-MuseExecutable `+ -CandidatePath $candidatePath `+ -ExecutablePath $paths.Executable+ }+ catch {+ $publicationError = $_+ if ($recordWritten) {+ try {+ Restore-MuseOwnershipRecord `+ -RecordPath $paths.Record `+ -PreviousContent $previousRecordContent+ }+ catch {+ throw "Muse Code publication failed and the previous ownership record could not be restored."+ }+ }+ Remove-EmptyMuseInstallDirectories -Paths $paths+ throw $publicationError+ }++ Update-MusePath -ManagedBin $paths.Bin+ Assert-CompatibleMuseBinary `+ -Path $paths.Executable `+ -Context "The published Muse Code executable"+ }+ finally {+ Remove-MuseTemporaryRoot -Path $temporaryRoot+ }++ Write-Host "Muse Code $($artifact.ReleaseVersion) was installed and verified at '$($paths.Executable)'."+}++if ($MyInvocation.InvocationName -ne ".") {+ if ($Help) {+ Show-MuseInstallerUsage+ return+ }+ if ($RemainingArgs.Count -gt 0) {+ Show-MuseInstallerUsage+ throw "Unknown option: $($RemainingArgs -join ' ')"+ }+ Invoke-MuseInstaller+}diff --git a/scripts/install.ps1 b/scripts/install.ps1index 2d0bc90c..f4a7b823 100644--- a/scripts/install.ps1+++ b/scripts/install.ps1@@ -26,6 +26,7 @@ $HermesInstallUrl = "https://hermes-agent.nousresearch.com/install.ps1"$DshVersion = "0.1.0-rc.8"$DshPackage = "@deepseek-ai/dsh@$DshVersion"$GrokInstallUrl = "https://x.ai/cli/install.ps1"+$MuseInstallUrl = "https://raw.githubusercontent.com/Alishahryar1/free-claude-code/main/scripts/install-muse.ps1"$AiderInstallUrl = "https://aider.chat/install.ps1"$RtkVersion = "0.44.2"$RtkReleaseBaseUrl = "https://github.com/rtk-ai/rtk/releases/download/v$RtkVersion"@@ -279,6 +280,7 @@ function Add-KnownBinDirectories {if (-not [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {Add-PathEntry (Join-Path $env:LOCALAPPDATA "Programs\OpenAI\Codex\bin")Add-PathEntry (Join-Path $env:LOCALAPPDATA "pi-node\current")+ Add-PathEntry (Join-Path $env:LOCALAPPDATA "Programs\Muse Code\bin")}if (-not [string]::IsNullOrWhiteSpace($env:APPDATA)) {Add-PathEntry (Join-Path $env:APPDATA "npm")@@ -850,13 +852,8 @@ function Ensure-Aider {function Ensure-Muse {$script:MuseAvailable = $false- $command = Get-ApplicationCommand "muse"- if (-not $command) {- Write-Host "Muse Code is not installed. Meta does not currently publish an official Windows installer; fcc-muse will be ready when Muse Code is on PATH."- return- }-- Write-Host "Muse Code already found on PATH; verifying it."+ Invoke-DownloadedPowerShellInstaller -Url $MuseInstallUrl -Name "Muse Code"+ Add-KnownBinDirectoriesConfirm-Application -CommandName "muse" -DisplayName "Muse Code"$script:MuseAvailable = $true}@@ -1029,7 +1026,7 @@ function Ensure-SelectedCodingAgents {}if ($script:InstallMuse) {- Write-Step "Checking for Muse Code"+ Write-Step "Ensuring Muse Code is installed"Ensure-Muse}diff --git a/scripts/uninstall-muse.ps1 b/scripts/uninstall-muse.ps1new file mode 100644index 00000000..8ec3106e--- /dev/null+++ b/scripts/uninstall-muse.ps1@@ -0,0 +1,290 @@+[CmdletBinding()]+param(+ [switch] $DryRun,+ [switch] $Help,+ [Parameter(ValueFromRemainingArguments = $true)]+ [object[]] $RemainingArgs = @()+)++Set-StrictMode -Version Latest+$ErrorActionPreference = "Stop"++$script:MuseOwner = "free-claude-code-muse-installer"+$script:MuseOwnerSchemaVersion = 1++function Show-MuseUninstallerUsage {+ @"+Usage: uninstall-muse.ps1 [options]++Removes only the native-Windows Muse Code executable managed by FCC.+Muse settings, credentials, sessions, logs, caches, and external installations are preserved.++Options:+ -DryRun Print actions without changing state.+ -Help Show this help text.+"@+}++function Get-MuseInstallPaths {+ if ([string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {+ throw "LOCALAPPDATA is not set; cannot locate the managed Muse Code installation."+ }++ $root = Join-Path $env:LOCALAPPDATA "Programs\Muse Code"+ $bin = Join-Path $root "bin"+ return [pscustomobject] @{+ Root = $root+ Bin = $bin+ Executable = Join-Path $bin "muse.exe"+ Record = Join-Path $root ".fcc-muse-install.json"+ }+}++function Test-MusePositiveInteger {+ param($Value)++ $integerTypes = @(+ [byte],+ [sbyte],+ [int16],+ [uint16],+ [int32],+ [uint32],+ [int64],+ [uint64]+ )+ foreach ($integerType in $integerTypes) {+ if ($Value -is $integerType) {+ return ([decimal] $Value) -gt 0+ }+ }+ return $false+}++function Read-MuseOwnershipRecord {+ param([Parameter(Mandatory = $true)][string] $RecordPath)++ if (-not (Test-Path -LiteralPath $RecordPath -PathType Leaf)) {+ return $null+ }++ try {+ $record = Get-Content -LiteralPath $RecordPath -Raw | ConvertFrom-Json+ }+ catch {+ throw "The Muse ownership record is malformed; refusing to change the managed directory."+ }++ $expectedFields = @(+ "schema_version",+ "owner",+ "release_version",+ "artifact_key",+ "sha256",+ "size"+ )+ $actualFields = @($record.PSObject.Properties.Name)+ if (+ $actualFields.Count -ne $expectedFields.Count -or+ @($expectedFields | Where-Object { $_ -notin $actualFields }).Count -gt 0 -or+ $record.schema_version -ne $script:MuseOwnerSchemaVersion -or+ $record.owner -ne $script:MuseOwner -or+ ([string] $record.release_version) -notmatch '^\d+\.\d+\.\d+-R\d+(?:\.\d+)?$' -or+ $record.artifact_key -notin @("x86_windows", "aarch64_windows") -or+ ([string] $record.sha256) -cnotmatch '^[0-9a-f]{64}$' -or+ (-not (Test-MusePositiveInteger -Value $record.size))+ ) {+ throw "The Muse ownership record is unsupported or foreign; refusing to change the managed directory."+ }++ return $record+}++function Get-MuseCanonicalPath {+ param([Parameter(Mandatory = $true)][string] $Path)++ if ([string]::IsNullOrWhiteSpace($Path)) {+ return $null+ }+ try {+ $fullPath = [IO.Path]::GetFullPath($Path.Trim())+ $root = [IO.Path]::GetPathRoot($fullPath)+ while (+ $fullPath.Length -gt $root.Length -and+ ($fullPath.EndsWith("\") -or $fullPath.EndsWith("/"))+ ) {+ $fullPath = $fullPath.Substring(0, $fullPath.Length - 1)+ }+ return $fullPath+ }+ catch {+ return $null+ }+}++function Test-MuseEquivalentPath {+ param(+ [string] $Left,+ [string] $Right+ )++ $canonicalLeft = Get-MuseCanonicalPath -Path $Left+ $canonicalRight = Get-MuseCanonicalPath -Path $Right+ return (+ $null -ne $canonicalLeft -and+ $null -ne $canonicalRight -and+ [string]::Equals(+ $canonicalLeft,+ $canonicalRight,+ [StringComparison]::OrdinalIgnoreCase+ )+ )+}++function Remove-MusePathValue {+ param(+ [AllowEmptyString()][string] $PathValue,+ [Parameter(Mandatory = $true)][string] $ManagedBin+ )++ if ([string]::IsNullOrEmpty($PathValue)) {+ return ""+ }+ $entries = @($PathValue -split [regex]::Escape([string] [IO.Path]::PathSeparator))+ return @(+ $entries | Where-Object {+ -not (Test-MuseEquivalentPath -Left ([string] $_) -Right $ManagedBin)+ }+ ) -join [IO.Path]::PathSeparator+}++function Test-MusePathContains {+ param(+ [AllowEmptyString()][string] $PathValue,+ [Parameter(Mandatory = $true)][string] $ManagedBin+ )++ if ([string]::IsNullOrEmpty($PathValue)) {+ return $false+ }+ return @(+ $PathValue -split [regex]::Escape([string] [IO.Path]::PathSeparator) |+ Where-Object {+ Test-MuseEquivalentPath -Left ([string] $_) -Right $ManagedBin+ }+ ).Count -gt 0+}++function Get-MuseUserPathValue {+ return [Environment]::GetEnvironmentVariable("Path", "User")+}++function Set-MuseUserPathValue {+ param([AllowEmptyString()][string] $Value)++ [Environment]::SetEnvironmentVariable("Path", $Value, "User")+}++function Remove-EmptyMuseDirectory {+ param([Parameter(Mandatory = $true)][string] $Path)++ if (+ (Test-Path -LiteralPath $Path -PathType Container) -and+ @(Get-ChildItem -LiteralPath $Path -Force).Count -eq 0+ ) {+ Remove-Item -LiteralPath $Path -Force+ }+}++function Invoke-MuseUninstaller {+ $paths = Get-MuseInstallPaths+ $rootExists = Test-Path -LiteralPath $paths.Root -PathType Container+ $recordExists = Test-Path -LiteralPath $paths.Record -PathType Leaf++ if (-not $rootExists -and -not $recordExists) {+ Write-Host "No FCC-managed Muse Code installation was found."+ return+ }+ if (-not $recordExists) {+ throw "The Muse Code install root is not owned by FCC; refusing to remove '$($paths.Root)'."+ }++ [void] (Read-MuseOwnershipRecord -RecordPath $paths.Record)++ if ($DryRun) {+ Write-Host "Dry run: remove the FCC-managed executable and installer residue from '$($paths.Bin)'."+ Write-Host "Dry run: remove exact '$($paths.Bin)' entries from the user and current-process PATH."+ Write-Host "Dry run: remove the ownership record '$($paths.Record)' and empty managed directories."+ Write-Host "Dry run complete. No changes were made."+ return+ }++ if (Test-Path -LiteralPath $paths.Executable -PathType Leaf) {+ Remove-Item -LiteralPath $paths.Executable -Force+ }++ if (Test-Path -LiteralPath $paths.Bin -PathType Container) {+ $residue = @(Get-ChildItem -LiteralPath $paths.Bin -Force -File | Where-Object {+ $_.Name -cmatch '^\.muse-[0-9a-f]{32}\.(?:staging|backup)\.exe$'+ })+ foreach ($file in $residue) {+ Remove-Item -LiteralPath $file.FullName -Force+ }+ }++ $recordResidue = @(Get-ChildItem -LiteralPath $paths.Root -Force -File | Where-Object {+ $_.Name -cmatch '^\.fcc-muse-install\.json\.[0-9a-f]{32}\.(?:tmp|backup)$'+ })+ foreach ($file in $recordResidue) {+ Remove-Item -LiteralPath $file.FullName -Force+ }++ if (Test-Path -LiteralPath $paths.Executable -PathType Leaf) {+ throw "The managed Muse Code executable could not be removed."+ }++ $currentUserPath = [string] (Get-MuseUserPathValue)+ $newUserPath = Remove-MusePathValue `+ -PathValue $currentUserPath `+ -ManagedBin $paths.Bin+ if (-not [string]::Equals($currentUserPath, $newUserPath, [StringComparison]::Ordinal)) {+ Set-MuseUserPathValue -Value $newUserPath+ }+ $env:Path = Remove-MusePathValue `+ -PathValue ([string] $env:Path) `+ -ManagedBin $paths.Bin++ if (+ (Test-MusePathContains -PathValue ([string] (Get-MuseUserPathValue)) -ManagedBin $paths.Bin) -or+ (Test-MusePathContains -PathValue ([string] $env:Path) -ManagedBin $paths.Bin)+ ) {+ throw "The managed Muse Code PATH entry could not be removed."+ }++ Remove-Item -LiteralPath $paths.Record -Force+ if (Test-Path -LiteralPath $paths.Record -PathType Leaf) {+ throw "The Muse ownership record could not be removed."+ }++ Remove-EmptyMuseDirectory -Path $paths.Bin+ Remove-EmptyMuseDirectory -Path $paths.Root++ if (Test-Path -LiteralPath $paths.Root -PathType Container) {+ Write-Host "Muse Code was uninstalled; unknown files in '$($paths.Root)' were preserved."+ }+ else {+ Write-Host "The FCC-managed Muse Code installation was removed."+ }+}++if ($MyInvocation.InvocationName -ne ".") {+ if ($Help) {+ Show-MuseUninstallerUsage+ return+ }+ if ($RemainingArgs.Count -gt 0) {+ Show-MuseUninstallerUsage+ throw "Unknown option: $($RemainingArgs -join ' ')"+ }+ Invoke-MuseUninstaller+}diff --git a/src/free_claude_code/cli/launchers/muse.py b/src/free_claude_code/cli/launchers/muse.pyindex bbf152de..4145c582 100644--- a/src/free_claude_code/cli/launchers/muse.py+++ b/src/free_claude_code/cli/launchers/muse.py@@ -27,9 +27,11 @@ from .model_catalog import (_BINARY_NAME = "muse"_DISPLAY_NAME = "Muse Code"_INSTALL_HINT = (- "Install Muse Code on macOS/Linux/WSL with "- "`curl -fsSL https://dev.meta.ai/install.sh | bash`. "- "Meta does not currently publish an official Windows installer."+ "Install Muse Code on native Windows with "+ '`& ([scriptblock]::Create((irm "https://raw.githubusercontent.com/'+ 'Alishahryar1/free-claude-code/main/scripts/install-muse.ps1")))`, '+ "or on macOS/Linux/WSL with "+ "`curl -fsSL https://dev.meta.ai/install.sh | bash`.")_MINIMUM_VERSION = (0, 2, 1)_VERSION_TIMEOUT_SECONDS = 5.0diff --git a/tests/cli/test_muse_launcher.py b/tests/cli/test_muse_launcher.pyindex f135ae54..b7320e22 100644--- a/tests/cli/test_muse_launcher.py+++ b/tests/cli/test_muse_launcher.py@@ -40,6 +40,22 @@ def _models_payload() -> JsonObject:}+def test_muse_install_hint_covers_native_windows_and_posix() -> None:+ from free_claude_code.cli.launchers import muse++ with (+ patch.object(+ muse, "resolve_client_binary", side_effect=SystemExit(1)+ ) as resolve_client_binary,+ pytest.raises(SystemExit),+ ):+ muse.launch([])++ install_hint = resolve_client_binary.call_args.kwargs["install_hint"]+ assert "scripts/install-muse.ps1" in install_hint+ assert "https://dev.meta.ai/install.sh" in install_hint++@pytest.mark.parametrize(("argv", "str_mode", "command_index"),[diff --git a/tests/scripts/test_installers.py b/tests/scripts/test_installers.pyindex 591b9f0a..bf70e9b2 100644--- a/tests/scripts/test_installers.py+++ b/tests/scripts/test_installers.py@@ -1837,6 +1837,20 @@ $bin = if ($env:GROK_BIN_DIR) { $env:GROK_BIN_DIR } else { Join-Path $env:USERPRNew-Item -ItemType Directory -Force -Path $bin | Out-NullCopy-Item (Join-Path $env:FAKE_FIXTURES "grok-command.cmd") (Join-Path $bin "grok.cmd") -ForceAdd-Content -LiteralPath $env:CALL_LOG -Value "grok-install"+""",+ encoding="utf-8",+ )+ (fixtures / "muse-installer.ps1").write_text(+ r"""if ($env:FAIL_STEP -eq "muse-install") { exit 68 }+$existing = Get-Command "muse" -CommandType Application -ErrorAction SilentlyContinue+if ($existing) {+ Add-Content -LiteralPath $env:CALL_LOG -Value "muse-install:external"+ return+}+$bin = Join-Path $env:LOCALAPPDATA "Programs\Muse Code\bin"+New-Item -ItemType Directory -Force -Path $bin | Out-Null+Copy-Item (Join-Path $env:FAKE_FIXTURES "muse-command.cmd") (Join-Path $bin "muse.cmd") -Force+Add-Content -LiteralPath $env:CALL_LOG -Value "muse-install"""",encoding="utf-8",)@@ -1894,6 +1908,7 @@ function Invoke-RestMethod {($env:FAIL_STEP -eq "opencode-download" -and $Uri.Contains("anomalyco/opencode")) -or($env:FAIL_STEP -eq "hermes-download" -and $Uri.Contains("hermes-agent.nousresearch.com")) -or($env:FAIL_STEP -eq "grok-download" -and $Uri.Contains("x.ai/cli")) -or+ ($env:FAIL_STEP -eq "muse-download" -and $Uri.Contains("scripts/install-muse.ps1")) -or($env:FAIL_STEP -eq "aider-download" -and $Uri.Contains("aider.chat")) -or($env:FAIL_STEP -eq "rtk-download" -and $Uri.Contains("rtk-ai/rtk")) -or($env:FAIL_STEP -eq "uv-download" -and $Uri.Contains("astral.sh"))@@ -1915,6 +1930,9 @@ function Invoke-RestMethod {elseif ($Uri.Contains("x.ai/cli")) {$source = Join-Path $env:FAKE_FIXTURES "grok-installer.ps1"}+ elseif ($Uri.Contains("scripts/install-muse.ps1")) {+ $source = Join-Path $env:FAKE_FIXTURES "muse-installer.ps1"+ }elseif ($Uri.Contains("aider.chat")) {$source = Join-Path $env:FAKE_FIXTURES "aider-installer.ps1"}@@ -2023,9 +2041,8 @@ def test_install_ps1_fresh_install_is_verified("dsh:--version")assert calls.index("grok-install") < calls.index("grok:--version")+ assert calls.index("muse-install") < calls.index("muse:--version")assert calls.index("aider-install") < calls.index("aider:--version")- assert "Muse Code is not installed" in result.stdout- assert not any(call.startswith("muse:") for call in calls)assert not any("hermes:setup" in call for call in calls)assert calls.index("uv-install") < calls.index("uv:--version")assert any(@@ -2094,7 +2111,6 @@ def test_install_ps1_discovers_grok_in_custom_bin_directory(("cline", "npm:install -g cline"),("hermes", "hermes-install:True:True"),("grok", "grok-install"),- ("muse", "meta.ai"),("aider", "aider-install"),],)@@ -2116,6 +2132,35 @@ def test_install_ps1_preserves_upstream_managed_harness_without_parsing_version(assert not any(install_call in call for call in calls)+def test_install_ps1_delegates_compatible_external_muse_without_adopting_it(+ powershell_harness: PowerShellHarness,+) -> None:+ powershell_harness.add_client("muse")++ result = powershell_harness.run()++ assert result.returncode == 0, result.stderr+ calls = powershell_harness.calls()+ assert "muse-install:external" in calls+ assert calls.index("muse-install:external") < calls.index("muse:--version")+ managed_root = (+ Path(powershell_harness.env["LOCALAPPDATA"]) / "Programs" / "Muse Code"+ )+ assert not managed_root.exists()++[email protected]("failure", ["muse-download", "muse-install"])+def test_install_ps1_stops_when_muse_install_fails(+ powershell_harness: PowerShellHarness,+ failure: str,+) -> None:+ result = powershell_harness.run(fail_step=failure)++ assert result.returncode != 0+ assert "Free Claude Code is installed and verified." not in result.stdout+ assert not any(call.startswith("uv:") for call in powershell_harness.calls())++@pytest.mark.parametrize("failure", ["grok-download", "grok-install"])def test_install_ps1_stops_when_grok_install_fails(powershell_harness: PowerShellHarness,@@ -2460,13 +2505,21 @@ def test_install_ps1_preserves_valid_existing_tools(powershell_harness.add_client("cline")powershell_harness.add_client("hermes")powershell_harness.add_client("grok")+ powershell_harness.add_client("muse")powershell_harness.add_client("aider")powershell_harness.add_uv(uv_version)result = powershell_harness.run()assert result.returncode == 0, result.stderr- assert not any(call.startswith("download:") for call in powershell_harness.calls())+ download_calls = [+ call for call in powershell_harness.calls() if call.startswith("download:")+ ]+ assert download_calls == [+ "download:https://raw.githubusercontent.com/Alishahryar1/"+ "free-claude-code/main/scripts/install-muse.ps1"+ ]+ assert "muse-install:external" in powershell_harness.calls()assert "leaving it unchanged" in result.stdout@@ -2770,8 +2823,10 @@ def test_installers_use_native_clients_and_single_python_selection() -> None:assert "https://dev.meta.ai/install.sh" in shellassert "https://aider.chat/install.sh" in shellassert "https://aider.chat/install.ps1" in powershell- assert "dev.meta.ai" not in powershell- assert "muse-code/channels" not in powershell+ assert (+ "https://raw.githubusercontent.com/Alishahryar1/free-claude-code/"+ "main/scripts/install-muse.ps1"+ ) in powershelldef test_install_ps1_uses_x64_python_for_windows_arm_compatibility() -> None:diff --git a/tests/scripts/test_muse_windows_lifecycle.py b/tests/scripts/test_muse_windows_lifecycle.pynew file mode 100644index 00000000..a0efd727--- /dev/null+++ b/tests/scripts/test_muse_windows_lifecycle.py@@ -0,0 +1,921 @@+"""Behavior contracts for FCC's standalone native-Windows Muse lifecycle."""++import hashlib+import json+import os+import shutil+import subprocess+from pathlib import Path++import pytest+++def _repo_root() -> Path:+ return Path(__file__).resolve().parents[2]+++def _powershells() -> tuple[str, ...]:+ return tuple(+ executable+ for name in ("powershell", "pwsh")+ if (executable := shutil.which(name)) is not None+ )+++POWERSHELLS = _powershells()+++def _ps_literal(value: str | Path) -> str:+ return "'" + str(value).replace("'", "''") + "'"+++def _run_installer_functions(+ powershell: str, body: str+) -> subprocess.CompletedProcess[str]:+ script_path = _repo_root() / "scripts" / "install-muse.ps1"+ script = f"""$ErrorActionPreference = 'Stop'+. {_ps_literal(script_path)}+{body}+"""+ return subprocess.run(+ [powershell, "-NoProfile", "-Command", script],+ check=False,+ capture_output=True,+ text=True,+ )++[email protected]("powershell", POWERSHELLS)+ ("architecture", "expected"),+ [+ ("AMD64", "x86_windows"),+ ("X64", "x86_windows"),+ ("X86_64", "x86_windows"),+ ("ARM64", "aarch64_windows"),+ ],+)+def test_muse_installer_maps_native_windows_architecture(+ powershell: str, architecture: str, expected: str+) -> None:+ result = _run_installer_functions(+ powershell,+ f"Write-Output (Get-MuseArtifactKey -Architecture {_ps_literal(architecture)})",+ )++ assert result.returncode == 0, result.stderr+ assert result.stdout.strip() == expected++[email protected]("powershell", POWERSHELLS)[email protected]("architecture", ["X86", "ARM", "unknown"])+def test_muse_installer_rejects_unsupported_architecture(+ powershell: str, architecture: str+) -> None:+ result = _run_installer_functions(+ powershell,+ f"Get-MuseArtifactKey -Architecture {_ps_literal(architecture)}",+ )++ assert result.returncode != 0+ assert "supported Windows release" in result.stderr+++def _channel() -> dict[str, object]:+ return {+ "channel": "muse-stable",+ "state": "public",+ "version": "0.2.1-R1215.1",+ "manifest_url": "https://lookaside.facebook.com/muse/releases/0.2.1.json",+ }+++def _manifest() -> dict[str, object]:+ return {+ "version": "0.2.1-R1215.1",+ "checksum_algorithm": "sha256",+ "artifacts": {+ "x86_windows": {+ "url": "https://lookaside.facebook.com/muse/muse-x86-windows.exe",+ "checksum": "a" * 64,+ "size": 123,+ },+ "aarch64_windows": {+ "url": "https://lookaside.facebook.com/muse/muse-aarch64-windows.exe",+ "checksum": "b" * 64,+ "size": 456,+ },+ },+ }+++def _resolve_artifact(+ powershell: str,+ *,+ channel: dict[str, object] | None = None,+ manifest: dict[str, object] | None = None,+ architecture: str = "X64",+) -> subprocess.CompletedProcess[str]:+ channel_json = json.dumps(channel or _channel(), separators=(",", ":"))+ manifest_json = json.dumps(manifest or _manifest(), separators=(",", ":"))+ return _run_installer_functions(+ powershell,+ f"""$channel = ConvertFrom-Json {_ps_literal(channel_json)}+$manifest = ConvertFrom-Json {_ps_literal(manifest_json)}+Resolve-MuseArtifact -Architecture {_ps_literal(architecture)} -Channel $channel -Manifest $manifest |+ ConvertTo-Json -Compress+""",+ )++[email protected]("powershell", POWERSHELLS)+def test_muse_installer_resolves_version_bound_verified_artifact(+ powershell: str,+) -> None:+ result = _resolve_artifact(powershell)++ assert result.returncode == 0, result.stderr+ assert json.loads(result.stdout) == {+ "ReleaseVersion": "0.2.1-R1215.1",+ "ArtifactKey": "x86_windows",+ "Url": "https://lookaside.facebook.com/muse/muse-x86-windows.exe",+ "Sha256": "a" * 64,+ "Size": 123,+ }++[email protected]("powershell", POWERSHELLS)+ ("mutation", "message"),+ [+ (("channel", "channel", "preview"), "stable channel"),+ (("channel", "state", "private"), "public"),+ (("channel", "version", "latest"), "release version"),+ (+ ("channel", "manifest_url", "http://lookaside.facebook.com/muse.json"),+ "HTTPS",+ ),+ (+ ("channel", "manifest_url", "https://example.com/muse.json"),+ "lookaside.facebook.com",+ ),+ (("manifest", "version", "0.2.2-R1"), "does not match"),+ (("manifest", "checksum_algorithm", "sha512"), "sha256"),+ (("artifact", "checksum", "ABC"), "checksum"),+ (("artifact", "size", 0), "size"),+ (("artifact", "url", "https://example.com/muse.exe"), "lookaside.facebook.com"),+ ],+)+def test_muse_installer_rejects_untrusted_release_metadata(+ powershell: str, mutation: tuple[str, str, object], message: str+) -> None:+ channel = _channel()+ manifest = _manifest()+ target, field, value = mutation+ if target == "channel":+ channel[field] = value+ elif target == "manifest":+ manifest[field] = value+ else:+ artifacts = manifest["artifacts"]+ assert isinstance(artifacts, dict)+ artifact = artifacts["x86_windows"]+ assert isinstance(artifact, dict)+ artifact[field] = value++ result = _resolve_artifact(+ powershell,+ channel=channel,+ manifest=manifest,+ )++ assert result.returncode != 0+ assert message.lower() in result.stderr.lower()++[email protected]("powershell", POWERSHELLS)+def test_muse_installer_rejects_missing_architecture_artifact(powershell: str) -> None:+ manifest = _manifest()+ artifacts = manifest["artifacts"]+ assert isinstance(artifacts, dict)+ del artifacts["x86_windows"]++ result = _resolve_artifact(powershell, manifest=manifest)++ assert result.returncode != 0+ assert "x86_windows" in result.stderr++[email protected]("powershell", POWERSHELLS)+def test_muse_installer_validates_owner_record(tmp_path: Path, powershell: str) -> None:+ record_path = tmp_path / ".fcc-muse-install.json"+ record_path.write_text(+ json.dumps(+ {+ "schema_version": 1,+ "owner": "free-claude-code-muse-installer",+ "release_version": "0.2.1-R1215.1",+ "artifact_key": "x86_windows",+ "sha256": "a" * 64,+ "size": 123,+ }+ ),+ encoding="utf-8",+ )+ result = _run_installer_functions(+ powershell,+ f"Read-MuseOwnershipRecord -RecordPath {_ps_literal(record_path)} | ConvertTo-Json -Compress",+ )++ assert result.returncode == 0, result.stderr+ assert json.loads(result.stdout)["owner"] == "free-claude-code-muse-installer"++[email protected]("powershell", POWERSHELLS)+ "record",+ [+ "not-json",+ json.dumps({"schema_version": 1, "owner": "someone-else"}),+ json.dumps(+ {+ "schema_version": 2,+ "owner": "free-claude-code-muse-installer",+ }+ ),+ ],+)+def test_muse_installer_rejects_malformed_or_foreign_owner_record(+ tmp_path: Path, powershell: str, record: str+) -> None:+ record_path = tmp_path / ".fcc-muse-install.json"+ record_path.write_text(record, encoding="utf-8")++ result = _run_installer_functions(+ powershell,+ f"Read-MuseOwnershipRecord -RecordPath {_ps_literal(record_path)}",+ )++ assert result.returncode != 0+ assert "ownership record" in result.stderr.lower()++[email protected]("powershell", POWERSHELLS)+def test_muse_installer_normalizes_managed_path_once_and_preserves_order(+ tmp_path: Path, powershell: str+) -> None:+ managed = tmp_path / "Tools" / "Muse" / "bin"+ first = tmp_path / "One"+ second = tmp_path / "Two"+ path_value = os.pathsep.join(+ (+ str(first),+ str(managed).swapcase() + os.sep,+ str(second),+ str(managed).upper(),+ )+ )+ result = _run_installer_functions(+ powershell,+ f"""$managed = {_ps_literal(managed)}+$path = {_ps_literal(path_value)}+Write-Output (Add-MusePathValue -PathValue $path -ManagedBin $managed)+Write-Output (Remove-MusePathValue -PathValue $path -ManagedBin $managed)+""",+ )++ assert result.returncode == 0, result.stderr+ assert result.stdout.splitlines() == [+ os.pathsep.join((str(managed), str(first), str(second))),+ os.pathsep.join((str(first), str(second))),+ ]++[email protected]("powershell", POWERSHELLS)+def test_muse_installer_checks_exact_artifact_size_and_sha256(+ tmp_path: Path, powershell: str+) -> None:+ artifact = tmp_path / "muse.exe"+ payload = b"verified muse fixture\n"+ artifact.write_bytes(payload)+ checksum = hashlib.sha256(payload).hexdigest()+ command = (+ f"Assert-MuseArtifactIntegrity -Path {_ps_literal(artifact)} "+ f"-ExpectedSize {len(payload)} -ExpectedSha256 {_ps_literal(checksum)}"+ )++ accepted = _run_installer_functions(powershell, command)+ wrong_size = _run_installer_functions(+ powershell,+ command.replace(f"-ExpectedSize {len(payload)}", "-ExpectedSize 1"),+ )+ wrong_hash = _run_installer_functions(+ powershell,+ command.replace(checksum, "f" * 64),+ )++ assert accepted.returncode == 0, accepted.stderr+ assert wrong_size.returncode != 0+ assert "size" in wrong_size.stderr.lower()+ assert wrong_hash.returncode != 0+ assert "sha-256" in wrong_hash.stderr.lower()+++def _managed_paths(local_app_data: Path) -> tuple[Path, Path, Path]:+ root = local_app_data / "Programs" / "Muse Code"+ return root, root / "bin" / "muse.exe", root / ".fcc-muse-install.json"+++def _owner_record(+ payload: bytes,+ *,+ release_version: str = "0.2.1-R1215.1",+) -> dict[str, object]:+ return {+ "schema_version": 1,+ "owner": "free-claude-code-muse-installer",+ "release_version": release_version,+ "artifact_key": "x86_windows",+ "sha256": hashlib.sha256(payload).hexdigest(),+ "size": len(payload),+ }+++def _run_installer_lifecycle(+ tmp_path: Path,+ powershell: str,+ *,+ payload: bytes = b"new verified muse binary",+ release_version: str = "0.2.1-R1215.1",+ external_path: str = "",+ external_compatible: bool = True,+ publish_failure: bool = False,+ dry_run: bool = False,+ install_root_is_file: bool = False,+) -> tuple[subprocess.CompletedProcess[str], Path, Path]:+ local_app_data = tmp_path / "local-app-data"+ if install_root_is_file:+ root, _, _ = _managed_paths(local_app_data)+ root.parent.mkdir(parents=True)+ root.write_bytes(b"unowned file")+ source_artifact = tmp_path / "official-muse.exe"+ source_artifact.write_bytes(payload)+ call_log = tmp_path / "calls.log"+ record = _owner_record(payload, release_version=release_version)+ record_json = json.dumps(record, separators=(",", ":"))+ script_path = _repo_root() / "scripts" / "install-muse.ps1"+ process_path = os.pathsep.join(+ (str(tmp_path / "process-one"), str(tmp_path / "process-two"))+ )+ user_path = os.pathsep.join(+ (str(tmp_path / "user-one"), str(tmp_path / "user-two"))+ )+ script = f"""$ErrorActionPreference = 'Stop'+$env:LOCALAPPDATA = {_ps_literal(local_app_data)}+$env:Path = {_ps_literal(process_path)}+. {_ps_literal(script_path)}+$DryRun = ${str(dry_run).lower()}+$script:TestUserPath = {_ps_literal(user_path)}+function Get-MuseNativeArchitecture {{ return 'X64' }}+function Resolve-MuseExternalCommand {{+ if ({_ps_literal(external_path)} -eq '') {{ return $null }}+ return [pscustomobject] @{{ Source = {_ps_literal(external_path)} }}+}}+function Get-MuseVersionProbe {{+ param([string] $Path)+ $isExternal = $Path -eq {_ps_literal(external_path)} -and {_ps_literal(external_path)} -ne ''+ if ($isExternal -and -not ${str(external_compatible).lower()}) {{+ return [pscustomobject] @{{ Compatible = $false; Version = $null; Reason = 'not Muse Code' }}+ }}+ return [pscustomobject] @{{ Compatible = $true; Version = [version] '0.2.1'; Reason = '' }}+}}+function Get-MuseReleaseArtifact {{+ Add-Content -LiteralPath {_ps_literal(call_log)} -Value 'metadata'+ $record = ConvertFrom-Json {_ps_literal(record_json)}+ return [pscustomobject] @{{+ ReleaseVersion = $record.release_version+ ArtifactKey = $record.artifact_key+ Url = 'https://lookaside.facebook.com/muse/fixture.exe'+ Sha256 = $record.sha256+ Size = [long] $record.size+ }}+}}+function Save-MuseArtifact {{+ param([string] $Url, [string] $Destination)+ Add-Content -LiteralPath {_ps_literal(call_log)} -Value 'download'+ Copy-Item -LiteralPath {_ps_literal(source_artifact)} -Destination $Destination+}}+function Get-MuseUserPathValue {{ return $script:TestUserPath }}+function Set-MuseUserPathValue {{+ param([AllowEmptyString()][string] $Value)+ Add-Content -LiteralPath {_ps_literal(call_log)} -Value 'path-write'+ $script:TestUserPath = $Value+}}+"""+ if publish_failure:+ script += (+ "function Publish-MuseExecutable { throw 'injected publication failure' }\n"+ )+ script += """Invoke-MuseInstaller+[pscustomobject] @{ UserPath = $script:TestUserPath; ProcessPath = $env:Path } |+ ConvertTo-Json -Compress+"""+ result = subprocess.run(+ [powershell, "-NoProfile", "-Command", script],+ check=False,+ capture_output=True,+ text=True,+ )+ return result, local_app_data, call_log++[email protected]("powershell", POWERSHELLS)+def test_muse_installer_preserves_compatible_external_installation(+ tmp_path: Path, powershell: str+) -> None:+ result, local_app_data, call_log = _run_installer_lifecycle(+ tmp_path,+ powershell,+ external_path=r"C:\External Muse\muse.exe",+ )+ root, executable, record_path = _managed_paths(local_app_data)++ assert result.returncode == 0, result.stderr+ assert "leaving it unchanged" in result.stdout+ assert not root.exists()+ assert not executable.exists()+ assert not record_path.exists()+ assert not call_log.exists()++[email protected]("powershell", POWERSHELLS)+def test_muse_installer_rejects_conflicting_external_command_before_fetch(+ tmp_path: Path, powershell: str+) -> None:+ result, local_app_data, call_log = _run_installer_lifecycle(+ tmp_path,+ powershell,+ external_path=r"C:\Unrelated\muse.exe",+ external_compatible=False,+ )++ assert result.returncode != 0+ assert r"C:\Unrelated\muse.exe" in result.stderr+ assert "conflict" in result.stderr.lower()+ assert not local_app_data.exists()+ assert not call_log.exists()++[email protected]("powershell", POWERSHELLS)+def test_muse_installer_rejects_file_at_managed_root_before_fetch(+ tmp_path: Path, powershell: str+) -> None:+ result, local_app_data, call_log = _run_installer_lifecycle(+ tmp_path,+ powershell,+ install_root_is_file=True,+ )+ root, executable, record_path = _managed_paths(local_app_data)++ assert result.returncode != 0+ assert "not owned by FCC" in result.stderr+ assert root.read_bytes() == b"unowned file"+ assert not executable.exists()+ assert not record_path.exists()+ assert not call_log.exists()++[email protected]("powershell", POWERSHELLS)+def test_muse_installer_publishes_verified_binary_record_and_path(+ tmp_path: Path, powershell: str+) -> None:+ payload = b"fresh Muse payload"+ result, local_app_data, call_log = _run_installer_lifecycle(+ tmp_path,+ powershell,+ payload=payload,+ )+ root, executable, record_path = _managed_paths(local_app_data)++ assert result.returncode == 0, result.stderr+ assert executable.read_bytes() == payload+ assert json.loads(record_path.read_text(encoding="utf-8-sig")) == _owner_record(+ payload+ )+ state = json.loads(result.stdout.splitlines()[-1])+ assert state["UserPath"].split(os.pathsep)[0] == str(root / "bin")+ assert state["ProcessPath"].split(os.pathsep)[0] == str(root / "bin")+ assert call_log.read_text(encoding="utf-8").splitlines() == [+ "metadata",+ "download",+ "path-write",+ ]++[email protected]("powershell", POWERSHELLS)+def test_muse_installer_skips_download_only_after_revalidating_current_binary(+ tmp_path: Path, powershell: str+) -> None:+ payload = b"current Muse payload"+ local_app_data = tmp_path / "local-app-data"+ _, executable, record_path = _managed_paths(local_app_data)+ executable.parent.mkdir(parents=True)+ executable.write_bytes(payload)+ record_path.write_text(json.dumps(_owner_record(payload)), encoding="utf-8")++ result, _, call_log = _run_installer_lifecycle(+ tmp_path,+ powershell,+ payload=payload,+ )++ assert result.returncode == 0, result.stderr+ assert "already current and verified" in result.stdout+ assert executable.read_bytes() == payload+ assert call_log.read_text(encoding="utf-8").splitlines() == [+ "metadata",+ "path-write",+ ]++[email protected]("powershell", POWERSHELLS)+def test_muse_installer_repairs_corrupt_managed_binary(+ tmp_path: Path, powershell: str+) -> None:+ payload = b"repaired Muse payload"+ local_app_data = tmp_path / "local-app-data"+ _, executable, record_path = _managed_paths(local_app_data)+ executable.parent.mkdir(parents=True)+ executable.write_bytes(b"corrupt")+ record_path.write_text(json.dumps(_owner_record(payload)), encoding="utf-8")++ result, _, call_log = _run_installer_lifecycle(+ tmp_path,+ powershell,+ payload=payload,+ )++ assert result.returncode == 0, result.stderr+ assert executable.read_bytes() == payload+ assert "download" in call_log.read_text(encoding="utf-8").splitlines()++[email protected]("powershell", POWERSHELLS)+def test_muse_installer_updates_changed_release(+ tmp_path: Path, powershell: str+) -> None:+ old_payload = b"old Muse payload"+ new_payload = b"new Muse payload"+ local_app_data = tmp_path / "local-app-data"+ _, executable, record_path = _managed_paths(local_app_data)+ executable.parent.mkdir(parents=True)+ executable.write_bytes(old_payload)+ record_path.write_text(+ json.dumps(_owner_record(old_payload, release_version="0.2.1-R1")),+ encoding="utf-8",+ )++ result, _, _ = _run_installer_lifecycle(+ tmp_path,+ powershell,+ payload=new_payload,+ release_version="0.2.2-R2",+ )++ assert result.returncode == 0, result.stderr+ assert executable.read_bytes() == new_payload+ assert json.loads(record_path.read_text(encoding="utf-8-sig")) == _owner_record(+ new_payload,+ release_version="0.2.2-R2",+ )++[email protected]("powershell", POWERSHELLS)+def test_muse_installer_failed_update_keeps_previous_binary_and_record(+ tmp_path: Path, powershell: str+) -> None:+ old_payload = b"old working Muse payload"+ new_payload = b"new Muse payload"+ old_record = _owner_record(old_payload, release_version="0.2.1-R1")+ local_app_data = tmp_path / "local-app-data"+ _, executable, record_path = _managed_paths(local_app_data)+ executable.parent.mkdir(parents=True)+ executable.write_bytes(old_payload)+ record_path.write_text(json.dumps(old_record), encoding="utf-8")++ result, _, _ = _run_installer_lifecycle(+ tmp_path,+ powershell,+ payload=new_payload,+ release_version="0.2.2-R2",+ publish_failure=True,+ )++ assert result.returncode != 0+ assert "injected publication failure" in result.stderr+ assert executable.read_bytes() == old_payload+ assert json.loads(record_path.read_text(encoding="utf-8-sig")) == old_record++[email protected]("powershell", POWERSHELLS)+def test_muse_installer_refuses_unowned_managed_directory(+ tmp_path: Path, powershell: str+) -> None:+ local_app_data = tmp_path / "local-app-data"+ root, _, _ = _managed_paths(local_app_data)+ root.mkdir(parents=True)+ (root / "unowned.txt").write_text("keep", encoding="utf-8")++ result, _, call_log = _run_installer_lifecycle(tmp_path, powershell)++ assert result.returncode != 0+ assert "not owned" in result.stderr.lower()+ assert (root / "unowned.txt").read_text(encoding="utf-8") == "keep"+ assert not call_log.exists()++[email protected]("powershell", POWERSHELLS)+def test_muse_installer_dry_run_has_no_network_or_state_mutation(+ tmp_path: Path, powershell: str+) -> None:+ result, local_app_data, call_log = _run_installer_lifecycle(+ tmp_path,+ powershell,+ dry_run=True,+ )++ assert result.returncode == 0, result.stderr+ assert "Dry run" in result.stdout+ assert not local_app_data.exists()+ assert not call_log.exists()++[email protected]("powershell", POWERSHELLS)+def test_muse_native_process_runner_times_out_and_stops_process(+ powershell: str,+) -> None:+ result = _run_installer_functions(+ powershell,+ f"""$result = Invoke-MuseNativeProcess `+ -FilePath {_ps_literal(powershell)} `+ -Arguments @('-NoProfile', '-Command', 'Start-Sleep -Seconds 10') `+ -TimeoutMilliseconds 50+Write-Output ($result | ConvertTo-Json -Compress)+""",+ )++ assert result.returncode == 0, result.stderr+ process_result = json.loads(result.stdout)+ assert process_result["TimedOut"] is True+ assert process_result["ExitCode"] is None++[email protected]("powershell", POWERSHELLS)+ ("started", "timed_out", "exit_code", "output", "compatible", "reason"),+ [+ (False, False, 0, "", False, "could not be started"),+ (True, True, 0, "", False, "timed out"),+ (True, False, 7, "", False, "returned exit code 7"),+ (+ True,+ False,+ 0,+ "another muse 0.2.1",+ False,+ "did not identify itself as Muse Code",+ ),+ (+ True,+ False,+ 0,+ "Muse Code 0.2.0",+ False,+ "is older than Muse Code 0.2.1",+ ),+ (True, False, 0, "Muse Code 0.2.1 (0.2.1-R1215.1)", True, ""),+ ],+)+def test_muse_version_probe_classifies_only_supported_native_binary(+ powershell: str,+ started: bool,+ timed_out: bool,+ exit_code: int,+ output: str,+ compatible: bool,+ reason: str,+) -> None:+ result = _run_installer_functions(+ powershell,+ f"""function Invoke-MuseNativeProcess {{+ return [pscustomobject] @{{+ Started = ${str(started).lower()}+ TimedOut = ${str(timed_out).lower()}+ ExitCode = {exit_code}+ Output = {_ps_literal(output)}+ }}+}}+$probe = Get-MuseVersionProbe -Path {_ps_literal(r"C:\fixture\muse.exe")}+[pscustomobject] @{{ Compatible = $probe.Compatible; Reason = $probe.Reason }} |+ ConvertTo-Json -Compress+""",+ )++ assert result.returncode == 0, result.stderr+ probe = json.loads(result.stdout)+ assert probe == {"Compatible": compatible, "Reason": reason}+++def _run_uninstaller_lifecycle(+ tmp_path: Path,+ powershell: str,+ *,+ dry_run: bool = False,+ user_path: str | None = None,+) -> tuple[subprocess.CompletedProcess[str], Path]:+ local_app_data = tmp_path / "local-app-data"+ root, _, _ = _managed_paths(local_app_data)+ managed_bin = root / "bin"+ path_value = user_path or os.pathsep.join(+ (+ str(tmp_path / "one"),+ str(managed_bin),+ str(tmp_path / "two"),+ str(managed_bin) + os.sep,+ )+ )+ script_path = _repo_root() / "scripts" / "uninstall-muse.ps1"+ script = f"""$ErrorActionPreference = 'Stop'+$env:LOCALAPPDATA = {_ps_literal(local_app_data)}+$env:Path = {_ps_literal(path_value)}+. {_ps_literal(script_path)}+$DryRun = ${str(dry_run).lower()}+$script:TestUserPath = {_ps_literal(path_value)}+function Get-MuseUserPathValue {{ return $script:TestUserPath }}+function Set-MuseUserPathValue {{+ param([AllowEmptyString()][string] $Value)+ $script:TestUserPath = $Value+}}+Invoke-MuseUninstaller+[pscustomobject] @{{ UserPath = $script:TestUserPath; ProcessPath = $env:Path }} |+ ConvertTo-Json -Compress+"""+ result = subprocess.run(+ [powershell, "-NoProfile", "-Command", script],+ check=False,+ capture_output=True,+ text=True,+ )+ return result, local_app_data+++def _create_managed_install(+ local_app_data: Path,+ *,+ unknown_file: bool = False,+ record: dict[str, object] | None = None,+) -> tuple[Path, Path, Path]:+ payload = b"managed Muse binary"+ root, executable, record_path = _managed_paths(local_app_data)+ executable.parent.mkdir(parents=True)+ executable.write_bytes(payload)+ record_path.write_text(+ json.dumps(record or _owner_record(payload)),+ encoding="utf-8",+ )+ residue_id = "0123456789abcdef0123456789abcdef"+ (executable.parent / f".muse-{residue_id}.staging.exe").write_bytes(b"staging")+ (executable.parent / f".muse-{residue_id}.backup.exe").write_bytes(b"backup")+ (root / f".fcc-muse-install.json.{residue_id}.tmp").write_bytes(b"temporary")+ (root / f".fcc-muse-install.json.{residue_id}.backup").write_bytes(b"backup")+ if unknown_file:+ near_match_id = "fedcba9876543210fedcba9876543210"+ (root / "keep.txt").write_text("not installer owned", encoding="utf-8")+ (executable.parent / ".muse-user-notes.staging.exe").write_bytes(b"keep")+ (executable.parent / f".MUSE-{near_match_id}.backup.exe").write_bytes(b"keep")+ (root / ".fcc-muse-install.json.user.tmp").write_bytes(b"keep")+ (root / f".FCC-MUSE-INSTALL.JSON.{near_match_id}.backup").write_bytes(b"keep")+ return root, executable, record_path++[email protected]("powershell", POWERSHELLS)+def test_muse_uninstaller_removes_only_managed_assets_and_exact_path_entries(+ tmp_path: Path, powershell: str+) -> None:+ local_app_data = tmp_path / "local-app-data"+ root, executable, record_path = _create_managed_install(local_app_data)+ muse_state = tmp_path / "muse-state" / "sessions" / "state.json"+ muse_state.parent.mkdir(parents=True)+ muse_state.write_text('{"native":true}', encoding="utf-8")++ result, _ = _run_uninstaller_lifecycle(tmp_path, powershell)++ assert result.returncode == 0, result.stderr+ assert not executable.exists()+ assert not record_path.exists()+ assert not root.exists()+ assert muse_state.read_text(encoding="utf-8") == '{"native":true}'+ state = json.loads(result.stdout.splitlines()[-1])+ expected_path = os.pathsep.join((str(tmp_path / "one"), str(tmp_path / "two")))+ assert state == {+ "UserPath": expected_path,+ "ProcessPath": expected_path,+ }++[email protected]("powershell", POWERSHELLS)+def test_muse_uninstaller_preserves_unknown_files_and_nonempty_root(+ tmp_path: Path, powershell: str+) -> None:+ local_app_data = tmp_path / "local-app-data"+ root, executable, record_path = _create_managed_install(+ local_app_data,+ unknown_file=True,+ )++ result, _ = _run_uninstaller_lifecycle(tmp_path, powershell)++ assert result.returncode == 0, result.stderr+ assert not executable.exists()+ assert not record_path.exists()+ assert (root / "keep.txt").read_text(encoding="utf-8") == "not installer owned"+ assert (root / "bin" / ".muse-user-notes.staging.exe").read_bytes() == b"keep"+ assert (+ root / "bin" / ".MUSE-fedcba9876543210fedcba9876543210.backup.exe"+ ).read_bytes() == b"keep"+ assert (root / ".fcc-muse-install.json.user.tmp").read_bytes() == b"keep"+ assert (+ root / ".FCC-MUSE-INSTALL.JSON.fedcba9876543210fedcba9876543210.backup"+ ).read_bytes() == b"keep"+ assert "unknown files" in result.stdout.lower()++[email protected]("powershell", POWERSHELLS)+def test_muse_uninstaller_refuses_foreign_record_without_mutation(+ tmp_path: Path, powershell: str+) -> None:+ local_app_data = tmp_path / "local-app-data"+ foreign = _owner_record(b"managed Muse binary")+ foreign["owner"] = "another-installer"+ _, executable, record_path = _create_managed_install(+ local_app_data,+ record=foreign,+ )+ before = record_path.read_bytes()++ result, _ = _run_uninstaller_lifecycle(tmp_path, powershell)++ assert result.returncode != 0+ assert "ownership record" in result.stderr.lower()+ assert executable.read_bytes() == b"managed Muse binary"+ assert record_path.read_bytes() == before++[email protected]("powershell", POWERSHELLS)+def test_muse_uninstaller_is_idempotent_when_managed_install_is_absent(+ tmp_path: Path, powershell: str+) -> None:+ result, local_app_data = _run_uninstaller_lifecycle(tmp_path, powershell)++ assert result.returncode == 0, result.stderr+ assert "No FCC-managed Muse Code installation" in result.stdout+ assert not local_app_data.exists()++[email protected]("powershell", POWERSHELLS)+def test_muse_uninstaller_refuses_unowned_root(tmp_path: Path, powershell: str) -> None:+ local_app_data = tmp_path / "local-app-data"+ root, _, _ = _managed_paths(local_app_data)+ root.mkdir(parents=True)+ unknown = root / "keep.txt"+ unknown.write_text("keep", encoding="utf-8")++ result, _ = _run_uninstaller_lifecycle(tmp_path, powershell)++ assert result.returncode != 0+ assert "not owned" in result.stderr.lower()+ assert unknown.read_text(encoding="utf-8") == "keep"++[email protected]("powershell", POWERSHELLS)+def test_muse_uninstaller_dry_run_is_non_mutating(+ tmp_path: Path, powershell: str+) -> None:+ local_app_data = tmp_path / "local-app-data"+ root, executable, record_path = _create_managed_install(local_app_data)+ managed_bin = root / "bin"++ result, _ = _run_uninstaller_lifecycle(+ tmp_path,+ powershell,+ dry_run=True,+ )++ assert result.returncode == 0, result.stderr+ assert "Dry run" in result.stdout+ assert executable.exists()+ assert record_path.exists()+ assert (managed_bin / ".muse-0123456789abcdef0123456789abcdef.staging.exe").exists()+ state = json.loads(result.stdout.splitlines()[-1])+ assert str(managed_bin) in state["UserPath"]+ assert str(managed_bin) in state["ProcessPath"]diff --git a/uv.lock b/uv.lockindex dccd7eee..ea57b199 100644--- a/uv.lock+++ b/uv.lock@@ -607,7 +607,7 @@ wheels = [[[package]]name = "free-claude-code"-version = "5.15.7"+version = "5.15.8"source = { editable = "." }dependencies = [{ name = "aiohttp" },