param( [Parameter(Mandatory = $true)][string]$ArchivePath, [string]$TargetCodexHome = (Join-Path $env:USERPROFILE ".codex"), [switch]$NoBackup ) $ErrorActionPreference = "Stop" function New-CleanDirectory { param([Parameter(Mandatory = $true)][string]$Path) if (Test-Path -LiteralPath $Path) { Remove-Item -LiteralPath $Path -Recurse -Force } New-Item -ItemType Directory -Path $Path -Force | Out-Null } if (-not (Test-Path -LiteralPath $ArchivePath)) { throw "Archive not found: $ArchivePath" } $extractRoot = Join-Path $env:TEMP ("codex-restore-" + (Get-Date -Format "yyyyMMdd-HHmmss")) New-CleanDirectory -Path $extractRoot try { Expand-Archive -LiteralPath $ArchivePath -DestinationPath $extractRoot -Force $manifestPath = Join-Path $extractRoot "manifest.json" $payloadCodexHome = Join-Path $extractRoot "payload\.codex" if (-not (Test-Path -LiteralPath $manifestPath)) { throw "Invalid archive: manifest.json missing" } if (-not (Test-Path -LiteralPath $payloadCodexHome)) { throw "Invalid archive: payload/.codex missing" } if ((Test-Path -LiteralPath $TargetCodexHome) -and -not $NoBackup) { $backupPath = "$TargetCodexHome.before-import-$(Get-Date -Format 'yyyyMMdd-HHmmss')" Move-Item -LiteralPath $TargetCodexHome -Destination $backupPath Write-Output "Existing Codex config moved to: $backupPath" } elseif (Test-Path -LiteralPath $TargetCodexHome) { Remove-Item -LiteralPath $TargetCodexHome -Recurse -Force } Copy-Item -LiteralPath $payloadCodexHome -Destination $TargetCodexHome -Recurse -Force $payloadRoot = Join-Path $extractRoot "payload" Get-ChildItem -LiteralPath $payloadRoot -Force -File -ErrorAction SilentlyContinue | Where-Object { $_.Name -like ".codex*" } | ForEach-Object { Copy-Item -LiteralPath $_.FullName -Destination (Join-Path $env:USERPROFILE $_.Name) -Force } Write-Output "Codex config restored to: $TargetCodexHome" } finally { if (Test-Path -LiteralPath $extractRoot) { Remove-Item -LiteralPath $extractRoot -Recurse -Force } }