diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bc75ab5..07241e1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -191,7 +191,8 @@ jobs: grep -Fq 'nix-user-baseline/bin' "$HOME/.config/pc-setup/shell-init.bash" grep -Fq 'wt config shell init bash' "$HOME/.config/pc-setup/shell-init.bash" grep -Fq '.dotfiles/script/agent' "$HOME/.config/pc-setup/shell-init.bash" - grep -Fq 'agent/mimo' "$HOME/.config/pc-setup/shell-init.bash" + ! grep -Fq 'agent/mimo' "$HOME/.config/pc-setup/shell-init.bash" + ! grep -Fq 'claude()' "$HOME/.config/pc-setup/shell-init.bash" # Once Home Manager owns the rc files they are declarative symlinks. # Re-running bootstrap must preserve those links instead of replacing @@ -668,6 +669,88 @@ jobs: throw 'mise-path-ownership.ps1 must print duplicate owners before the plan-only exit.' } + - name: Validate Tailscale fail-closed and User PATH convergence + shell: pwsh + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + + # setup-tailscale.ps1 must fail closed when `tailscale status --json` + # cannot be parsed: the old code treated parse failure as "not + # running" and fell into `tailscale up --auth-key`, re-registering an + # already-enrolled node. And both scripts must decode the native JSON + # as UTF-8, because Windows PowerShell 5.1 uses the OEM code page and + # mojibake breaks ConvertFrom-Json on Japanese Windows. + $setup = Get-Content -LiteralPath ./platforms/windows-11/setup-tailscale.ps1 -Raw + foreach ($needle in 'Invoke-Utf8Native', 'Get-TailscaleStatus', 'UTF8', 'fail closed') { + if (-not $setup.Contains($needle)) { throw "setup-tailscale.ps1 is missing: $needle" } + } + $statusCall = $setup.IndexOf('$status = Get-TailscaleStatus') + $nullGuard = $setup.IndexOf('refusing to touch node registration') + $register = $setup.IndexOf("'up'") + if ($statusCall -lt 0 -or $nullGuard -lt 0 -or $register -lt 0) { + throw 'setup-tailscale.ps1 must read status through Get-TailscaleStatus and guard registration behind the fail-closed check.' + } + if (-not ($statusCall -lt $nullGuard -and $nullGuard -lt $register)) { + throw 'setup-tailscale.ps1 must throw on unknown status BEFORE reaching tailscale up.' + } + + $verify = Get-Content -LiteralPath ./platforms/windows-11/verify.ps1 -Raw + foreach ($needle in 'Invoke-NativeUtf8', 'Microsoft.PowerShell', 'user-path.ps1', 'legacy .cargo\bin') { + if (-not $verify.Contains($needle)) { throw "verify.ps1 is missing: $needle" } + } + + # user-path.ps1 edits HKCU\Environment\Path. Plan mode must be + # read-only; -Apply must back up the unexpanded value first and write + # through the registry with the original value kind preserved. + $up = './platforms/windows-11/user-path.ps1' + $tokens = $null; $parseErrors = $null + [void][System.Management.Automation.Language.Parser]::ParseFile((Resolve-Path $up).Path, [ref]$tokens, [ref]$parseErrors) + if ($parseErrors.Count -gt 0) { throw "user-path.ps1 does not parse: $($parseErrors[0].Message)" } + $upText = Get-Content -LiteralPath $up -Raw + foreach ($needle in 'param(', '[switch]$Apply', '[string]$Restore', 'HKCU', 'user-path-backup', 'DoNotExpandEnvironmentNames', '.cargo\bin', 'mise\shims') { + if (-not $upText.Contains($needle)) { throw "user-path.ps1 is missing: $needle" } + } + $backupIndex = $upText.IndexOf('user-path-backup') + $setValueIndex = $upText.IndexOf("SetValue('Path'") + if ($backupIndex -lt 0 -or $setValueIndex -lt 0 -or $setValueIndex -lt $backupIndex) { + throw 'user-path.ps1 must save the previous User PATH before writing it.' + } + + # Plan mode on the CI runner must not write. + $userKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $false) + try { $before = $userKey.GetValue('Path', '', 'DoNotExpandEnvironmentNames') } finally { $userKey.Close() } + & $up *>&1 | Out-Null + if ($LASTEXITCODE -ne 0) { throw "user-path.ps1 plan mode exited $LASTEXITCODE" } + $userKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $false) + try { $after = $userKey.GetValue('Path', '', 'DoNotExpandEnvironmentNames') } finally { $userKey.Close() } + if ($before -ne $after) { throw 'user-path.ps1 changed the User PATH without -Apply.' } + + # -Apply on the ephemeral runner must converge and be restorable: + # apply, confirm a second plan reports converged, restore the backup, + # confirm the original value is back. + $applyOut = (& $up -Apply *>&1 | Out-String) + if ($LASTEXITCODE -ne 0) { throw "user-path.ps1 -Apply exited $LASTEXITCODE`n$applyOut" } + $backupLine = [regex]::Match($applyOut, 'backup\s+(\S+\.txt)') + if (-not $backupLine.Success) { throw "user-path.ps1 -Apply printed no backup path`n$applyOut" } + $backupFile = $backupLine.Groups[1].Value + $converged = (& $up *>&1 | Out-String) + if ($converged -notmatch 'already converged') { throw "user-path.ps1 did not converge after -Apply`n$converged" } + & $up -Restore $backupFile *>&1 | Out-Null + if ($LASTEXITCODE -ne 0) { throw "user-path.ps1 -Restore exited $LASTEXITCODE" } + $userKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $false) + try { $restored = $userKey.GetValue('Path', '', 'DoNotExpandEnvironmentNames') } finally { $userKey.Close() } + if ($restored -ne $before) { throw 'user-path.ps1 -Restore did not put the original User PATH back.' } + + # bootstrap.ps1 and converge.ps1 must both reach the same script so a + # fresh install and the hourly converge stay on one code path. + $bootstrap = Get-Content -LiteralPath ./bootstrap.ps1 -Raw + if (-not $bootstrap.Contains('user-path.ps1')) { throw 'bootstrap.ps1 must invoke user-path.ps1.' } + $converge = Get-Content -LiteralPath ./platforms/windows-11/converge.ps1 -Raw + if (-not $converge.Contains('user-path.ps1') -or -not $converge.Contains("Invoke-Step 'user-path'")) { + throw 'converge.ps1 must run user-path.ps1 as a named step.' + } + - name: Validate converge survives a step error and always reports shell: pwsh run: | diff --git a/.mise/locks/mise.global/npm-playwright/1.65.1/aube-lock.yaml b/.mise/locks/mise.global/npm-playwright/1.65.1/aube-lock.yaml deleted file mode 100644 index 5c3333a..0000000 --- a/.mise/locks/mise.global/npm-playwright/1.65.1/aube-lock.yaml +++ /dev/null @@ -1,33 +0,0 @@ -lockfileVersion: '9.0' - -settings: - autoInstallPeers: true - excludeLinksFromLockfile: false - -importers: - - .: - dependencies: - playwright: - specifier: 1.65.1 - version: 1.65.1 - -packages: - - playwright-core@1.65.1: - resolution: {integrity: sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==} - engines: {node: '>=20'} - hasBin: true - - playwright@1.65.1: - resolution: {integrity: sha512-vJ1FuoOrNwOKHUIVEvSt3jT1L+wjjDpwhwIstKtfvTh8XIG4FG4bIFuvNdMxi81LGfAhUgUZleVFaOLY4RIUUw==} - engines: {node: '>=20'} - hasBin: true - -snapshots: - - playwright-core@1.65.1: {} - - playwright@1.65.1: - dependencies: - playwright-core: 1.65.1 diff --git a/.mise/locks/mise.global/npm-playwright/1.65.1/package.json b/.mise/locks/mise.global/npm-playwright/1.65.1/package.json deleted file mode 100644 index 7517bf1..0000000 --- a/.mise/locks/mise.global/npm-playwright/1.65.1/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "mise-npm-install", - "private": true, - "dependencies": { - "playwright": "1.65.1" - } -} diff --git a/README.md b/README.md index 04d7f0c..5da0512 100644 --- a/README.md +++ b/README.md @@ -84,11 +84,11 @@ OSに依存しにくい開発CLI/runtimeは一度だけ宣言する。 - Claude Code / Codex / OpenCode / Devin - Worktrunk / Herdr - Open Code Review / npkill / cargo-clean-all -- Google Cloud CLI / AWS CLI -- Supabase CLI - ripgrep / fd / fzf / jq / bat / gdu - ShellCheck / Neovim +AWS CLI / Google Cloud CLI は必要なホストだけに導入する任意機能です。Supabase CLI は各プロジェクトの `mise.toml`、Playwright は各プロジェクトの依存管理で版を指定します。CLIの導入範囲と認証アカウントの範囲は別の判断です。詳細は [ADR-0029](./docs/adr/ADR-0029.md)。 + Open Code Review は npm trust policy を迂回せず、公式 `alibaba/open-code-review` GitHub Release のplatform binaryをmiseから導入する。詳細は [ADR-0007](./docs/adr/ADR-0007.md) を参照。 Vercel CLI は npm の trust policy を通らないため baseline に含めない。必要なマシンは project 側で導入する。詳細は [ADR-0023](./docs/adr/ADR-0023.md) を参照。 diff --git a/bootstrap.ps1 b/bootstrap.ps1 index eb72fa7..f6dd0bc 100644 --- a/bootstrap.ps1 +++ b/bootstrap.ps1 @@ -221,3 +221,24 @@ finally { & (Join-Path $applyDir 'platforms\windows-11\install-apps.ps1') Install-NotionMsix Install-StoreApps + +# User PATH convergence (ADR-0021): drop the legacy .cargo\bin rustup proxy +# entry and guarantee the mise shims entry. HKCU only with a backup; a failure +# must not stop bootstrap — verify.ps1 reports the resulting state. +try { + & (Join-Path $applyDir 'platforms\windows-11\user-path.ps1') -Apply +} +catch { + Write-Warning "User PATH convergence failed: $($_.Exception.Message)" +} + +# Rex is in public beta and its Windows server still requires tester +# enrollment, so a failed install or `rex server install --user` must not stop +# the rest of the machine bootstrap. platforms/windows-11/verify.ps1 reports +# the resulting state. +try { + & (Join-Path $applyDir 'platforms\windows-11\install-rex.ps1') +} +catch { + Write-Warning "Rex could not be installed automatically: $($_.Exception.Message)" +} diff --git a/components/herdr-t3/README.md b/components/herdr-t3/README.md new file mode 100644 index 0000000..6ee5ee9 --- /dev/null +++ b/components/herdr-t3/README.md @@ -0,0 +1,58 @@ +# herdr-t3 stable component + +Managed install of [rebuildup/herdr-t3](https://github.com/rebuildup/herdr-t3) +as a native Electron desktop app for macOS and Windows 11 +(Issue #220, herdr-t3 ADR-0004, pc-setup ADR-0028). The earlier browser/PWA +bridge design is superseded and must not be revived. + +## Layout + +``` +$STATE_DIR/ # ~/.local/share/herdr-t3 or %LOCALAPPDATA%\herdr-t3 + releases// # one self-contained checkout+build per ref + current # text file naming the selected release + previous # release superseded by the last update + current_app # path to the staged .app / built .exe + installed # selected release name + commit + logs/ # build logs +``` + +Only `v*` tags or full commit SHAs are install targets; dev branches and +unreleased release candidates are never selected implicitly. Linux is out +of scope — the herdr TUI keeps its existing operation there. + +## Commands + +| Action | macOS/POSIX | Windows 11 | +| --- | --- | --- | +| install | `install.sh [ref]` | `install.ps1 [-Ref ]` | +| update | `update.sh [ref]` | `update.ps1 [-Ref ]` | +| launch | `launch.sh` | `launch.ps1` | +| verify | `verify.sh [--live]` | `verify.ps1 [-Live]` | +| rollback | `rollback.sh` | `rollback.ps1` | + +macOS stages the built `.app` into `~/Applications` so it behaves like a +normal app (Finder, Spotlight, Launch Services, Dock). Windows keeps the +built `win-unpacked` tree under the release dir and registers a Start Menu +shortcut (`%APPDATA%\Microsoft\Windows\Start Menu\Programs\herdr-t3.lnk`) +that tracks the selected executable. + +`launch` is idempotent: it activates the already-running app. Builds happen +at install/update time only — never at launch. A failed install or update +leaves `current` (and the installed app / shortcut) untouched; `rollback` +flips the pointer back to the previous release dir, which is kept on disk, +and re-stages it. + +`verify --live` additionally checks that the app process is running, the +herdr endpoint is reachable (macOS: `~/.config/herdr/herdr.sock`; Windows: +the named-pipe endpoint `\\.\pipe\`), and — on macOS — +that the app's own `bridge-status.json` reports a fresh successful herdr +snapshot. + +## Integration notes + +- Requires `git`, `mise` (herdr-t3 pins bun+node via `mise.toml`), `bun`, + `curl` (POSIX) / `Invoke-RestMethod` (Windows). +- Windows herdr connectivity goes through the named-pipe endpoint; the app + handles that transparently once herdr-t3#6 lands — until then + `verify.ps1 -Live` on Windows may report `herdr.reachable=false`. diff --git a/components/herdr-t3/install.ps1 b/components/herdr-t3/install.ps1 new file mode 100644 index 0000000..a9a666a --- /dev/null +++ b/components/herdr-t3/install.ps1 @@ -0,0 +1,82 @@ +# herdr-t3 stable install — native Electron app (Windows 11). +# +# Installs a verified release of rebuildup/herdr-t3 into the managed state +# dir as an independent per-ref checkout, builds the app once with +# electron-builder (win-unpacked + NSIS installer), and only then selects +# it. A failed install or update never disturbs the selected release. +# +# Usage: install.ps1 [-Ref ] +param([string]$Ref = "") + +$ErrorActionPreference = "Stop" +$RepoUrl = "https://github.com/rebuildup/herdr-t3.git" +$StateDir = if ($env:HERDR_T3_STATE_DIR) { $env:HERDR_T3_STATE_DIR } else { Join-Path $env:LOCALAPPDATA "herdr-t3" } +$ReleasesDir = Join-Path $StateDir "releases" +$CurrentFile = Join-Path $StateDir "current" +$AppFile = Join-Path $StateDir "current_app" +$LogDir = Join-Path $StateDir "logs" +New-Item -ItemType Directory -Force -Path $ReleasesDir, $LogDir | Out-Null + +function Log($msg) { Write-Host "[herdr-t3] $msg" } +function Die($msg) { Write-Host "[herdr-t3] ERROR: $msg" -ForegroundColor Red; exit 1 } + +if (-not $Ref) { + # Stable release tags only: a prerelease tag like v1.1.0-rc.1 would fail + # the [version] cast below and must never win auto-selection. + $tags = git ls-remote --tags $RepoUrl "refs/tags/v*" | + ForEach-Object { ($_ -split "/")[-1] } | Where-Object { $_ -match '^v\d+\.\d+\.\d+$' } + $Ref = $tags | Sort-Object { [version]($_.TrimStart('v')) } | Select-Object -Last 1 + if (-not $Ref) { Die "no stable v* tag found on $RepoUrl" } +} +if ($Ref -match '^v[0-9]') { + git ls-remote --exit-code --tags $RepoUrl "refs/tags/$Ref" | Out-Null + if ($LASTEXITCODE -ne 0) { Die "tag $Ref not found on $RepoUrl" } +} elseif ($Ref -notmatch '^[0-9a-f]{40}$') { + Die "ref must be a v* tag or a full 40-char SHA (got: $Ref)" +} + +$name = $Ref -replace '[/\\:]', '_' +$target = Join-Path $ReleasesDir $name + +if (-not (Test-Path (Join-Path $target ".git"))) { + Log "cloning $Ref into $target" + git clone --quiet $RepoUrl $target +} else { + git -C $target fetch --quiet --tags origin +} +git -C $target checkout --quiet $Ref +if ($LASTEXITCODE -ne 0) { Die "git checkout $Ref failed in $target" } +$commit = (git -C $target rev-parse HEAD).Trim() +Log "building $name ($commit)" + +Push-Location $target +try { + mise install --locked | Out-Null + if ($LASTEXITCODE -ne 0) { Die "mise install failed" } + bun install --frozen-lockfile | Out-Null + if ($LASTEXITCODE -ne 0) { Die "bun install failed" } + $env:CSC_IDENTITY_AUTO_DISCOVERY = "false" + bun run desktop:pack | Out-Null + if ($LASTEXITCODE -ne 0) { Die "electron-builder failed" } +} finally { Pop-Location } + +$exe = Join-Path $target "release\win-unpacked\herdr-t3.exe" +if (-not (Test-Path $exe)) { Die "built app missing: $exe" } + +. (Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) "shortcut.ps1") + +$prevCurrent = if (Test-Path $CurrentFile) { (Get-Content $CurrentFile -Raw).Trim() } else { $null } +$prevApp = if (Test-Path $AppFile) { (Get-Content $AppFile -Raw).Trim() } else { $null } +$prevShortcut = Get-HerdrT3ShortcutTarget + +try { + Set-Content $CurrentFile $name + Set-Content $AppFile $exe + Set-HerdrT3Shortcut -ExePath $exe +} catch { + if ($null -ne $prevCurrent) { Set-Content $CurrentFile $prevCurrent } else { Remove-Item $CurrentFile -Force -ErrorAction SilentlyContinue } + if ($null -ne $prevApp) { Set-Content $AppFile $prevApp } else { Remove-Item $AppFile -Force -ErrorAction SilentlyContinue } + if ($prevShortcut) { try { Set-HerdrT3Shortcut -ExePath $prevShortcut } catch { } } + Die "shortcut registration failed; previous selection restored" +} +Log "installed $name ($commit); current -> $name ($exe)" diff --git a/components/herdr-t3/install.sh b/components/herdr-t3/install.sh new file mode 100755 index 0000000..690ef7d --- /dev/null +++ b/components/herdr-t3/install.sh @@ -0,0 +1,128 @@ +#!/usr/bin/env bash +# herdr-t3 stable install — native Electron app (macOS). +# +# Builds a verified release of rebuildup/herdr-t3 into the managed state +# dir, then stages the resulting .app into ~/Applications so it behaves +# like a normal macOS app: Finder, Spotlight, Launch Services, Dock. +# `current`/`previous` pointers and per-ref release dirs are unchanged; +# rollback re-stages the previous .app. A failed install or update never +# disturbs the installed stable app. +# +# Usage: install.sh [ref] +# ref: a v* tag or a full commit SHA (default: newest v* tag on origin). +set -euo pipefail + +REPO_URL="https://github.com/rebuildup/herdr-t3.git" +BUNDLE_ID="com.github.rebuildup.herdr-t3" +STATE_DIR="${HERDR_T3_STATE_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/herdr-t3}" +APPS_DIR="${HERDR_T3_APPS_DIR:-$HOME/Applications}" +RELEASES_DIR="$STATE_DIR/releases" +CURRENT_FILE="$STATE_DIR/current" +APP_FILE="$STATE_DIR/current_app" +INSTALLED_FILE="$STATE_DIR/installed" +LOG_DIR="$STATE_DIR/logs" +LSREGISTER="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister" +mkdir -p "$RELEASES_DIR" "$LOG_DIR" "$APPS_DIR" + +log() { printf '[herdr-t3] %s\n' "$*"; } +die() { log "ERROR: $*" >&2; exit 1; } + +bundle_id_of() { # $1 = .app path -> prints CFBundleIdentifier or nothing + /usr/libexec/PlistBuddy -c "Print CFBundleIdentifier" "$1/Contents/Info.plist" 2>/dev/null || true +} + +resolve_ref() { + local ref="${1:-}" + if [[ -z "$ref" ]]; then + # Stable release tags only: sort -V would let a prerelease tag like + # v1.1.0-rc.1 win auto-selection. + ref="$(git ls-remote --tags "$REPO_URL" 'refs/tags/v*' \ + | awk -F/ '{print $3}' | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | sort -V | tail -1)" + [[ -n "$ref" ]] || die "no stable v* tag found on $REPO_URL" + fi + if [[ "$ref" =~ ^v[0-9] ]]; then + git ls-remote --exit-code --tags "$REPO_URL" "refs/tags/$ref" >/dev/null \ + || die "tag $ref not found on $REPO_URL" + elif [[ ! "$ref" =~ ^[0-9a-f]{40}$ ]]; then + die "ref must be a v* tag or a full 40-char SHA (got: $ref)" + fi + printf '%s' "$ref" +} + +# Stage a built .app into the standard apps dir. Refuses to overwrite an +# unrelated app; quits a running herdr-t3 first so the swap is clean. +stage_app() { # $1 = source .app, $2 = destination .app + local src="$1" dst="$2" + [[ -d "$src" ]] || die "source app missing: $src" + if [[ -e "$dst" ]]; then + local existing_id + existing_id="$(bundle_id_of "$dst")" + [[ "$existing_id" == "$BUNDLE_ID" ]] \ + || die "refusing to overwrite unrelated app at $dst (bundle id: ${existing_id:-unknown})" + if pgrep -f "$dst/Contents/MacOS/herdr-t3" >/dev/null 2>&1; then + log "quitting running herdr-t3 before replacing $dst" + osascript -e 'tell application id "com.github.rebuildup.herdr-t3" to quit' >/dev/null 2>&1 || true + for _ in $(seq 1 25); do + pgrep -f "$dst/Contents/MacOS/herdr-t3" >/dev/null 2>&1 || break + sleep 0.2 + done + if pgrep -f "$dst/Contents/MacOS/herdr-t3" >/dev/null 2>&1; then + # Graceful quit failed; SIGTERM is safe — the app owns no herdr + # sessions, panes and agents keep running inside herdr. + pkill -f "$dst/Contents/MacOS/herdr-t3" || true + for _ in $(seq 1 25); do + pgrep -f "$dst/Contents/MacOS/herdr-t3" >/dev/null 2>&1 || break + sleep 0.2 + done + fi + pgrep -f "$dst/Contents/MacOS/herdr-t3" >/dev/null 2>&1 \ + && die "herdr-t3 is still running; quit it and retry" + fi + fi + # Stage beside the destination and swap only after the copy verifies, so a + # failed ditto never leaves ~/Applications without the app. + local staging="$dst.staging-$$" + rm -rf "$staging" + ditto "$src" "$staging" || { rm -rf "$staging"; die "ditto failed staging $src"; } + [[ -x "$staging/Contents/MacOS/herdr-t3" ]] || { rm -rf "$staging"; die "staged app has no executable: $staging"; } + rm -rf "$dst" + mv "$staging" "$dst" + # Register with Launch Services so Finder/Spotlight/`open -a` resolve it, + # and unregister the build artifact so it can never win resolution. + [[ -x "$LSREGISTER" ]] && "$LSREGISTER" -f "$dst" >/dev/null 2>&1 || true + [[ -x "$LSREGISTER" ]] && "$LSREGISTER" -u "$src" >/dev/null 2>&1 || true +} + +ref="$(resolve_ref "${1:-}")" +name="$(printf '%s' "$ref" | tr '/:' '__')" +target="$RELEASES_DIR/$name" + +if [[ ! -d "$target/.git" ]]; then + log "cloning $ref into $target" + git clone --quiet "$REPO_URL" "$target" +else + git -C "$target" fetch --quiet --tags origin +fi + +git -C "$target" checkout --quiet "$ref" +commit="$(git -C "$target" rev-parse HEAD)" +log "building $name ($commit)" + +(cd "$target" \ + && mise install --locked >/dev/null \ + && bun install --frozen-lockfile \ + && CSC_IDENTITY_AUTO_DISCOVERY=false bun run desktop:pack) \ + || die "build failed for $name; installed app left untouched" + +built="$(find "$target/release" -maxdepth 2 -name 'herdr-t3.app' -type d 2>/dev/null | head -1)" +[[ -n "$built" ]] || die "no herdr-t3.app built under $target/release" +[[ "$(bundle_id_of "$built")" == "$BUNDLE_ID" ]] \ + || die "built app has unexpected bundle id: $(bundle_id_of "$built")" + +dst="$APPS_DIR/herdr-t3.app" +stage_app "$built" "$dst" + +printf '%s\n' "$name" > "$CURRENT_FILE" +printf '%s\n' "$dst" > "$APP_FILE" +printf '%s\n%s\n' "$name" "$commit" > "$INSTALLED_FILE" +log "installed $name ($commit) -> $dst" diff --git a/components/herdr-t3/launch.ps1 b/components/herdr-t3/launch.ps1 new file mode 100644 index 0000000..c64f9fe --- /dev/null +++ b/components/herdr-t3/launch.ps1 @@ -0,0 +1,32 @@ +# Launch the stable herdr-t3 desktop app (Windows 11). +# +# Idempotent: if the app is already running it is simply activated. No +# bridge, port or browser is involved — the app embeds the bridge in its +# Main process and connects to herdr directly (native or WSL socket path +# resolved inside the app). +$ErrorActionPreference = "Stop" + +$StateDir = if ($env:HERDR_T3_STATE_DIR) { $env:HERDR_T3_STATE_DIR } else { Join-Path $env:LOCALAPPDATA "herdr-t3" } +$CurrentFile = Join-Path $StateDir "current" +$AppFile = Join-Path $StateDir "current_app" + +function Log($msg) { Write-Host "[herdr-t3] $msg" } +function Die($msg) { Write-Host "[herdr-t3] ERROR: $msg" -ForegroundColor Red; exit 1 } + +if (-not (Test-Path $CurrentFile)) { Die "no install found; run install.ps1 first" } +$name = (Get-Content $CurrentFile -Raw).Trim() +$release = Join-Path $StateDir "releases\$name" +$exe = "" +if (Test-Path $AppFile) { $exe = (Get-Content $AppFile -Raw).Trim() } +if (-not $exe -or -not (Test-Path $exe)) { + $exe = Join-Path $release "release\win-unpacked\herdr-t3.exe" +} +if (-not (Test-Path $exe)) { Die "release $name has no built app; reinstall ($exe)" } + +$running = Get-Process -Name "herdr-t3" -ErrorAction SilentlyContinue +if ($running) { + Log "already running; activating" +} else { + Start-Process $exe +} +Log "launched $name ($exe)" diff --git a/components/herdr-t3/launch.sh b/components/herdr-t3/launch.sh new file mode 100755 index 0000000..ba9d257 --- /dev/null +++ b/components/herdr-t3/launch.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# Launch the stable herdr-t3 app (macOS). +# +# Idempotent: `open` activates the already-running app. The app is a normal +# macOS bundle in ~/Applications — Finder, Spotlight, `open -a herdr-t3`, +# the Dock and this script all reach the same installed copy. No bridge, +# port or browser is involved. +set -euo pipefail + +STATE_DIR="${HERDR_T3_STATE_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/herdr-t3}" +APPS_DIR="${HERDR_T3_APPS_DIR:-$HOME/Applications}" +CURRENT_FILE="$STATE_DIR/current" +APP_FILE="$STATE_DIR/current_app" +BUNDLE_ID="com.github.rebuildup.herdr-t3" + +log() { printf '[herdr-t3] %s\n' "$*"; } +die() { log "ERROR: $*" >&2; exit 1; } + +[[ -f "$CURRENT_FILE" ]] || die "no install found ($CURRENT_FILE missing); run install.sh first" +name="$(cat "$CURRENT_FILE")" +app="$APPS_DIR/herdr-t3.app" +if [[ -f "$APP_FILE" ]]; then + recorded="$(cat "$APP_FILE")" + [[ -d "$recorded" ]] && app="$recorded" +fi +[[ -d "$app" ]] || die "installed app missing: $app (run install.sh)" +[[ -x "$app/Contents/MacOS/herdr-t3" ]] || die "app executable missing: $app" + +# Prefer the recorded installed path; fall back to Launch Services lookup. +if [[ -f "$APP_FILE" && -d "$(cat "$APP_FILE")" ]]; then + open "$(cat "$APP_FILE")" +else + open -a "$BUNDLE_ID" 2>/dev/null || open "$app" +fi +log "launched $name ($app)" diff --git a/components/herdr-t3/rollback.ps1 b/components/herdr-t3/rollback.ps1 new file mode 100644 index 0000000..1ed620a --- /dev/null +++ b/components/herdr-t3/rollback.ps1 @@ -0,0 +1,30 @@ +# Roll back the stable herdr-t3 app to the previously selected release. +# Pointer flip only — no rebuild. Quit and relaunch the app to apply. +$ErrorActionPreference = "Stop" +$StateDir = if ($env:HERDR_T3_STATE_DIR) { $env:HERDR_T3_STATE_DIR } else { Join-Path $env:LOCALAPPDATA "herdr-t3" } +$CurrentFile = Join-Path $StateDir "current" +$PrevFile = Join-Path $StateDir "previous" +$AppFile = Join-Path $StateDir "current_app" + +if (-not (Test-Path $PrevFile)) { Write-Host "[herdr-t3] no previous release recorded" -ForegroundColor Red; exit 1 } +$prev = (Get-Content $PrevFile -Raw).Trim() +$prevExe = Join-Path $StateDir "releases\$prev\release\win-unpacked\herdr-t3.exe" +if (-not (Test-Path $prevExe)) { Write-Host "[herdr-t3] previous release $prev has no built app" -ForegroundColor Red; exit 1 } +$prevCurrent = if (Test-Path $CurrentFile) { (Get-Content $CurrentFile -Raw).Trim() } else { $null } +$prevApp = if (Test-Path $AppFile) { (Get-Content $AppFile -Raw).Trim() } else { $null } + +. (Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) "shortcut.ps1") +$rollbackShortcut = Get-HerdrT3ShortcutTarget + +try { + Set-Content $CurrentFile $prev + Set-Content $AppFile $prevExe + Set-HerdrT3Shortcut -ExePath $prevExe +} catch { + if ($null -ne $prevCurrent) { Set-Content $CurrentFile $prevCurrent } else { Remove-Item $CurrentFile -Force -ErrorAction SilentlyContinue } + if ($null -ne $prevApp) { Set-Content $AppFile $prevApp } else { Remove-Item $AppFile -Force -ErrorAction SilentlyContinue } + if ($rollbackShortcut) { try { Set-HerdrT3Shortcut -ExePath $rollbackShortcut } catch { } } + Write-Host "[herdr-t3] shortcut update failed; previous selection restored" -ForegroundColor Red + exit 1 +} +Write-Host "[herdr-t3] rolled back to $prev ($prevExe); relaunch the app to apply" diff --git a/components/herdr-t3/rollback.sh b/components/herdr-t3/rollback.sh new file mode 100755 index 0000000..40e9d31 --- /dev/null +++ b/components/herdr-t3/rollback.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash +# Roll back the stable herdr-t3 app to the previously selected release. +# Flips the pointers AND re-stages the previous .app into ~/Applications, +# so the next launch (Finder/Spotlight/Dock/open -a) runs the old build. +set -euo pipefail + +BUNDLE_ID="com.github.rebuildup.herdr-t3" +STATE_DIR="${HERDR_T3_STATE_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/herdr-t3}" +APPS_DIR="${HERDR_T3_APPS_DIR:-$HOME/Applications}" +CURRENT_FILE="$STATE_DIR/current" +PREV_FILE="$STATE_DIR/previous" +APP_FILE="$STATE_DIR/current_app" +INSTALLED_FILE="$STATE_DIR/installed" +LSREGISTER="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister" + +log() { printf '[herdr-t3] %s\n' "$*"; } +die() { log "ERROR: $*" >&2; exit 1; } + +[[ -f "$PREV_FILE" ]] || die "no previous release recorded" +prev="$(cat "$PREV_FILE")" +built="$(find "$STATE_DIR/releases/$prev/release" -maxdepth 2 -name 'herdr-t3.app' -type d 2>/dev/null | head -1)" +[[ -n "$built" ]] || die "previous release $prev has no built .app" + +dst="$APPS_DIR/herdr-t3.app" +if [[ -e "$dst" ]]; then + existing_id="$(/usr/libexec/PlistBuddy -c 'Print CFBundleIdentifier' "$dst/Contents/Info.plist" 2>/dev/null || true)" + [[ "$existing_id" == "$BUNDLE_ID" ]] || die "refusing to overwrite unrelated app at $dst" + if pgrep -f "$dst/Contents/MacOS/herdr-t3" >/dev/null 2>&1; then + log "quitting running herdr-t3 before rollback" + osascript -e "tell application id \"$BUNDLE_ID\" to quit" >/dev/null 2>&1 || true + for _ in $(seq 1 25); do + pgrep -f "$dst/Contents/MacOS/herdr-t3" >/dev/null 2>&1 || break + sleep 0.2 + done + if pgrep -f "$dst/Contents/MacOS/herdr-t3" >/dev/null 2>&1; then + pkill -f "$dst/Contents/MacOS/herdr-t3" || true + for _ in $(seq 1 25); do + pgrep -f "$dst/Contents/MacOS/herdr-t3" >/dev/null 2>&1 || break + sleep 0.2 + done + fi + pgrep -f "$dst/Contents/MacOS/herdr-t3" >/dev/null 2>&1 && die "herdr-t3 still running; quit and retry" + fi +fi +# Stage beside the destination and swap only after the copy verifies, so a +# failed ditto never leaves ~/Applications without the app. +staging="$dst.staging-$$" +rm -rf "$staging" +ditto "$built" "$staging" || { rm -rf "$staging"; die "ditto failed staging $built"; } +[[ -x "$staging/Contents/MacOS/herdr-t3" ]] || { rm -rf "$staging"; die "staged app has no executable: $staging"; } +rm -rf "$dst" +mv "$staging" "$dst" +[[ -x "$LSREGISTER" ]] && "$LSREGISTER" -f "$dst" >/dev/null 2>&1 || true +[[ -x "$LSREGISTER" ]] && "$LSREGISTER" -u "$built" >/dev/null 2>&1 || true + +commit="$(git -C "$STATE_DIR/releases/$prev" rev-parse HEAD)" +printf '%s\n' "$prev" > "$CURRENT_FILE" +printf '%s\n' "$dst" > "$APP_FILE" +printf '%s\n%s\n' "$prev" "$commit" > "$INSTALLED_FILE" +log "rolled back to $prev ($commit) -> $dst; relaunch the app to apply" diff --git a/components/herdr-t3/shortcut.ps1 b/components/herdr-t3/shortcut.ps1 new file mode 100644 index 0000000..a138634 --- /dev/null +++ b/components/herdr-t3/shortcut.ps1 @@ -0,0 +1,23 @@ +# Shared Start Menu shortcut management for the stable herdr-t3 app. +# Dot-source this file; it defines Set-/Test-HerdrT3Shortcut only. + +$script:HerdrT3ShortcutPath = Join-Path $env:APPDATA "Microsoft\Windows\Start Menu\Programs\herdr-t3.lnk" + +function Set-HerdrT3Shortcut { + param([Parameter(Mandatory = $true)][string]$ExePath) + if (-not (Test-Path -LiteralPath $ExePath)) { throw "shortcut target missing: $ExePath" } + $shell = New-Object -ComObject WScript.Shell + $shortcut = $shell.CreateShortcut($script:HerdrT3ShortcutPath) + $shortcut.TargetPath = $ExePath + $shortcut.WorkingDirectory = Split-Path -Parent $ExePath + $shortcut.Description = "herdr-t3 — Herdr desktop client" + $icon = Join-Path (Split-Path -Parent $ExePath) "herdr-t3.exe" + if (Test-Path -LiteralPath $icon) { $shortcut.IconLocation = "$icon,0" } + $shortcut.Save() +} + +function Get-HerdrT3ShortcutTarget { + if (-not (Test-Path -LiteralPath $script:HerdrT3ShortcutPath)) { return $null } + $shell = New-Object -ComObject WScript.Shell + return $shell.CreateShortcut($script:HerdrT3ShortcutPath).TargetPath +} diff --git a/components/herdr-t3/update.ps1 b/components/herdr-t3/update.ps1 new file mode 100644 index 0000000..f3c0966 --- /dev/null +++ b/components/herdr-t3/update.ps1 @@ -0,0 +1,21 @@ +# Update the stable herdr-t3 install (Windows 11). +# Selects the newest v* tag (or -Ref), installs it, and records the +# superseded release for rollback. Failed updates keep the current release. +param([string]$Ref = "") + +$ErrorActionPreference = "Stop" +$StateDir = if ($env:HERDR_T3_STATE_DIR) { $env:HERDR_T3_STATE_DIR } else { Join-Path $env:LOCALAPPDATA "herdr-t3" } +$CurrentFile = Join-Path $StateDir "current" +$PrevFile = Join-Path $StateDir "previous" +$Here = Split-Path -Parent $MyInvocation.MyCommand.Path + +$prev = "" +if (Test-Path $CurrentFile) { $prev = (Get-Content $CurrentFile -Raw).Trim() } + +& (Join-Path $Here "install.ps1") -Ref $Ref +if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + +if ($prev) { + $cur = (Get-Content $CurrentFile -Raw).Trim() + if ($cur -ne $prev) { Set-Content -Path $PrevFile -Value "$prev`n" -NoNewline } +} diff --git a/components/herdr-t3/update.sh b/components/herdr-t3/update.sh new file mode 100755 index 0000000..9ad2d91 --- /dev/null +++ b/components/herdr-t3/update.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +# Update the stable herdr-t3 install. +# +# Resolves the newest v* tag (or an explicit ref), installs it via +# install.sh into its own release dir, and flips `current` only after the +# build succeeds. The previously selected release stays on disk, so +# rollback.sh can restore it without a rebuild. A failed update leaves the +# running/selected stable version untouched. +set -euo pipefail + +HERE="$(cd "$(dirname "$0")" && pwd)" +STATE_DIR="${HERDR_T3_STATE_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/herdr-t3}" +CURRENT_FILE="$STATE_DIR/current" + +if [[ -f "$CURRENT_FILE" ]]; then + prev="$(cat "$CURRENT_FILE")" + prev_commit="$(git -C "$STATE_DIR/releases/$prev" rev-parse HEAD 2>/dev/null || echo unknown)" +else + prev=""; prev_commit="" +fi + +"$HERE/install.sh" "${1:-}" + +# Record the superseded release for rollback (only after a successful switch). +if [[ -n "$prev" && -f "$CURRENT_FILE" ]]; then + cur="$(cat "$CURRENT_FILE")" + if [[ "$cur" != "$prev" ]]; then + printf '%s\n' "$prev" > "$STATE_DIR/previous" + printf 'previous=%s (%s)\ncurrent=%s\n' "$prev" "$prev_commit" "$cur" + fi +fi diff --git a/components/herdr-t3/verify.ps1 b/components/herdr-t3/verify.ps1 new file mode 100644 index 0000000..5fe839b --- /dev/null +++ b/components/herdr-t3/verify.ps1 @@ -0,0 +1,47 @@ +# Verify the stable herdr-t3 install (Windows 11). +# +# Checks: current release + built app exist, and with -Live the app process +# is running and the herdr endpoint (socket or named pipe) is reachable. +param([switch]$Live) + +$ErrorActionPreference = "Stop" +$StateDir = if ($env:HERDR_T3_STATE_DIR) { $env:HERDR_T3_STATE_DIR } else { Join-Path $env:LOCALAPPDATA "herdr-t3" } +$CurrentFile = Join-Path $StateDir "current" +$AppFile = Join-Path $StateDir "current_app" + +function Fail($msg) { Write-Host "[herdr-t3] FAIL: $msg" -ForegroundColor Red; exit 1 } + +if (-not (Test-Path $CurrentFile)) { Fail "not installed ($CurrentFile missing)" } +$name = (Get-Content $CurrentFile -Raw).Trim() +$release = Join-Path $StateDir "releases\$name" +if (-not (Test-Path (Join-Path $release ".git"))) { Fail "release dir missing: $release" } +$exe = "" +if (Test-Path $AppFile) { $exe = (Get-Content $AppFile -Raw).Trim() } +if (-not $exe -or -not (Test-Path $exe)) { $exe = Join-Path $release "release\win-unpacked\herdr-t3.exe" } +if (-not (Test-Path $exe)) { Fail "no built app for $name ($exe)" } +$commit = (git -C $release rev-parse HEAD).Trim() +Write-Host "[herdr-t3] installed: $name @ $($commit.Substring(0,12)) -> $exe" + +. (Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) "shortcut.ps1") +$lnk = Get-HerdrT3ShortcutTarget +if (-not $lnk) { Fail "Start Menu shortcut missing ($script:HerdrT3ShortcutPath)" } +if ($lnk -ne $exe) { Fail "Start Menu shortcut points to $lnk, expected $exe" } +Write-Host "[herdr-t3] start menu: $lnk" + +if ($Live) { + if (-not (Get-Process -Name "herdr-t3" -ErrorAction SilentlyContinue)) { Fail "app is not running (run launch.ps1)" } + $sock = if ($env:HERDR_SOCKET) { $env:HERDR_SOCKET } else { Join-Path $env:APPDATA "herdr\herdr.sock" } + # Windows herdr endpoints are named pipes; Directory.Exists cannot see + # them, so probe the pipe with a short connect instead. + $pipeName = [System.IO.Path]::GetFileName($sock) + $pipeUp = $false + try { + $pipeClient = New-Object System.IO.Pipes.NamedPipeClientPipe('.', $pipeName, [System.IO.Pipes.PipeDirection]::InOut) + try { $pipeClient.Connect(1500); $pipeUp = $true } catch { } + finally { $pipeClient.Dispose() } + } catch { } + if (-not (Test-Path $sock) -and -not $pipeUp) { + Fail "herdr endpoint not found: $sock / \\.\pipe\$pipeName (is herdr running?)" + } + Write-Host "[herdr-t3] live: app running, herdr endpoint present: $sock" +} diff --git a/components/herdr-t3/verify.sh b/components/herdr-t3/verify.sh new file mode 100755 index 0000000..d64453e --- /dev/null +++ b/components/herdr-t3/verify.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +# Verify the stable herdr-t3 install (macOS). +# +# Checks: installed app in ~/Applications, bundle id, recorded release +# commit vs the release checkout, the actual launch target, Launch +# Services / Spotlight discovery, and with --live the running process. +set -euo pipefail + +BUNDLE_ID="com.github.rebuildup.herdr-t3" +STATE_DIR="${HERDR_T3_STATE_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/herdr-t3}" +APPS_DIR="${HERDR_T3_APPS_DIR:-$HOME/Applications}" +CURRENT_FILE="$STATE_DIR/current" +APP_FILE="$STATE_DIR/current_app" +INSTALLED_FILE="$STATE_DIR/installed" +LIVE=0; [[ "${1:-}" == "--live" ]] && LIVE=1 + +fail() { echo "[herdr-t3] FAIL: $*" >&2; exit 1; } + +[[ -f "$CURRENT_FILE" ]] || fail "not installed ($CURRENT_FILE missing)" +name="$(cat "$CURRENT_FILE")" +release="$STATE_DIR/releases/$name" +[[ -d "$release/.git" ]] || fail "release dir missing: $release" + +app="$APPS_DIR/herdr-t3.app" +[[ -f "$APP_FILE" ]] && [[ -d "$(cat "$APP_FILE")" ]] && app="$(cat "$APP_FILE")" +[[ -d "$app" ]] || fail "installed app missing: $app" +[[ -x "$app/Contents/MacOS/herdr-t3" ]] || fail "app executable missing: $app" +bid="$(/usr/libexec/PlistBuddy -c 'Print CFBundleIdentifier' "$app/Contents/Info.plist" 2>/dev/null || true)" +[[ "$bid" == "$BUNDLE_ID" ]] || fail "bundle id mismatch: ${bid:-none} != $BUNDLE_ID" +version="$(/usr/libexec/PlistBuddy -c 'Print CFBundleShortVersionString' "$app/Contents/Info.plist" 2>/dev/null || echo unknown)" + +commit="$(git -C "$release" rev-parse HEAD)" +if [[ -f "$INSTALLED_FILE" ]]; then + recorded_commit="$(sed -n 2p "$INSTALLED_FILE")" + [[ "$recorded_commit" == "$commit" ]] || fail "installed commit $recorded_commit != release HEAD $commit" +fi +echo "[herdr-t3] installed: $name @ ${commit:0:12} -> $app (v$version, $bid)" + +# Launch Services / Spotlight discovery (not just file existence). +mdfind "kMDItemCFBundleIdentifier == '$BUNDLE_ID'" 2>/dev/null | grep -Fqx "$app" \ + || fail "Spotlight/Launch Services does not resolve $BUNDLE_ID to $app" +echo "[herdr-t3] launch services: $app" + +if [[ "$LIVE" == "1" ]]; then + # Layer 1: the installed app process is actually running. + pgrep -f "$app/Contents/MacOS/herdr-t3" >/dev/null \ + || fail "app is not running (run launch.sh)" + echo "[herdr-t3] live: app process running ($app)" + # Layer 2: the herdr endpoint the app will use exists. + sock="${HERDR_SOCKET:-$HOME/.config/herdr/herdr.sock}" + [[ -S "$sock" ]] || fail "herdr socket not present: $sock (is herdr running?)" + echo "[herdr-t3] live: herdr socket present: $sock" + # Layer 3: the running app's Main process reports a live herdr snapshot + # via /bridge-status.json — proof the GUI bridge reached herdr, + # not just that a process and a socket exist. + status="$HOME/Library/Application Support/herdr-t3/bridge-status.json" + [[ -f "$status" ]] || fail "no bridge-status.json at $status (app too old or never connected)" + python3 - "$status" <<'PYEOF' || fail "bridge-status.json reports failure or is stale: $(cat "$status" 2>/dev/null)" +import json, sys, time, calendar +d = json.load(open(sys.argv[1])) +age = time.time() - calendar.timegm(time.strptime(d["at"][:19], "%Y-%m-%dT%H:%M:%S")) +assert d.get("ok") is True, d.get("detail") +assert age < 300, f"status is {int(age)}s old" +print(f"[herdr-t3] live: bridge reports '{d['detail']}' via {d['herdr']}") +PYEOF +fi diff --git a/docs/adr/ADR-0006.md b/docs/adr/ADR-0006.md index 5234b7e..2585897 100644 --- a/docs/adr/ADR-0006.md +++ b/docs/adr/ADR-0006.md @@ -55,7 +55,7 @@ The user does not manually reproduce the full APT/Homebrew/WinGet package list. ### 3. Portable development tools use `[tools]` -Tools whose primary identity is a developer CLI/runtime and which mise can install portably belong in `mise.global.toml` `[tools]`. This file is applied as the user's global mise config, while root `mise.toml` owns machine bootstrap orchestration. +Frequently used, cross-project developer CLI/runtime defaults belong in `mise.global.toml` `[tools]`. A CLI being installable by mise is not sufficient grounds to make it mandatory on all hosts; project-scoped and optional-host tools are governed by ADR-0029. This file is applied as the user's global mise config, while root `mise.toml` owns machine bootstrap orchestration. Current baseline includes: @@ -65,12 +65,10 @@ Current baseline includes: - Claude Code / Codex / OpenCode / Devin - Worktrunk / Herdr - Open Code Review / npkill / cargo-clean-all -- Google Cloud CLI / AWS CLI -- Supabase CLI - ripgrep / fd / fzf / jq / bat - ShellCheck / Neovim -Project-specific pinned versions still belong to each project. The pc-setup declarations are machine-wide defaults, not a replacement for project-local toolchain definitions. +Project-specific pinned versions still belong to each project. See [ADR-0029](./ADR-0029.md) for the global / optional-host / project boundary, including identity separation. The pc-setup declarations are machine-wide defaults, not a replacement for project-local toolchain definitions. ### 4. Host packages and applications use `[bootstrap.packages]` diff --git a/docs/adr/ADR-0009.md b/docs/adr/ADR-0009.md index 07e8047..3ec84ac 100644 --- a/docs/adr/ADR-0009.md +++ b/docs/adr/ADR-0009.md @@ -30,10 +30,8 @@ Current Windows foundation includes: - .NET SDK - Visual Studio - Android Studio -- Google Cloud SDK -- AWS CLI -Git and mise themselves remain bootstrap dependencies. +Git and mise themselves remain bootstrap dependencies. AWS CLI and Google Cloud SDK were removed from the mandatory Windows foundation under [ADR-0029](./ADR-0029.md). Their installation is an optional, use-driven host capability, not a prerequisite for all development machines. ### 2. Desktop applications use a shared best-effort inventory diff --git a/docs/adr/ADR-0021.md b/docs/adr/ADR-0021.md index d508af6..bb5446f 100644 --- a/docs/adr/ADR-0021.md +++ b/docs/adr/ADR-0021.md @@ -83,7 +83,11 @@ orphan shim は上の「Rust CLI は mise の cargo backend で宣言する」 - mise 管理のツールは、`mise activate` された shell で mise が先頭に差し込む install dir / shim で解決される。activation が無い経路 (Scheduled Task / IDE / GUI / `pwsh -NoProfile`) では、registry PATH 上の同名 binary が勝つ。 - registry (User/Machine) PATH には mise shim dir だけを mise 由来の最小集合として置く。`%USERPROFILE%\.cargoin` のような mise の data dir 外の Rust home は registry PATH に置かない。 -- 同名の重複 (Program Files / npm global / bun / chocolatey) は、その管理者が自己更新する GUI・vendor 経路を壊しうるため、自動では削除しない。`verify.ps1` は非 activation 経路で mise 外に解決されるものを WARN として列挙する。 +- 同名の重複 (Program Files / npm global / bun / chocolatey) は、その管理者が自己更新する GUI・vendor 経路を壊しうるため、自動では削除しない。`verify.ps1` は Tool ownership で非 activation 経路の mise 外解決を FAIL として報告し、`mise-path-ownership.ps1` が Machine PATH の冗長 entry を除去する。 + +## Addendum (#174, 2026-11-23): User PATH の収束は user-path.ps1 が担う + +「`%USERPROFILE%\.cargo\bin` は User PATH から外す」の実施手段として `platforms/windows-11/user-path.ps1` を追加した。HKCU の User PATH だけを対象に、展開後の完全一致で legacy `.cargo\bin` entry を除去し、`%LOCALAPPDATA%\mise\shims` の存在を保証する。既定は plan のみで、`-Apply` は書き込み前に生値を state dir へ backup し、`-Restore` で復元できる。`bootstrap.ps1` と `converge.ps1` の双方から呼ばれ、`verify.ps1` は未収束を FAIL として報告する。 ## Consequences diff --git a/docs/adr/ADR-0023.md b/docs/adr/ADR-0023.md index 07e9852..904715e 100644 --- a/docs/adr/ADR-0023.md +++ b/docs/adr/ADR-0023.md @@ -68,7 +68,7 @@ Vercel CLI を `mise.global.toml` の machine-global baseline から外す。 - Vercel の npm 公開が trusted-publisher / provenance を一貫して持ち、`trustPolicy=no-downgrade` を通るようになった場合 - Vercel CLI が standalone binary を公式 GitHub Release で配布するようになった場合 -- 日常的に使う machine-global CLI としての需要が戻った場合 +- ADR-0029 の machine-global 採用条件を満たす横断的な需要が確認された場合 ## References diff --git a/docs/adr/ADR-0026.md b/docs/adr/ADR-0026.md new file mode 100644 index 0000000..f42516c --- /dev/null +++ b/docs/adr/ADR-0026.md @@ -0,0 +1,46 @@ +# ADR-0026: Rex は OS 公式導入経路で管理し preview channel を追跡する + +- Status: Accepted +- Date: 2026-11-21 +- Related: Issue #216, rebuildup/dotfiles#207 + +## Context + +Rex (Superlogical) を第二の agent execution runtime の実行基盤として pc-setup の正式管理対象にする。Rex は terminal multiplexer 兼 agent runtime で、client としての Mac app / Windows app と、server としての Linux / Windows / FreeBSD がある。 + +配布経路の調査結果(2026-11-21 時点): + +- `stable` channel は未公開(404)。`preview` / `snapshot` のみ存在し、preview が実質の最新安定候補 +- mise registry に Rex backend は存在しない +- Linux: 公式 `install.sh` が apt/dnf/apk 等の repo を追加するか、`--user` で `~/.local/bin` への user install(sudo 不要)、`--tarball` / `--tarball-file` の選択肢がある +- `rex server install` は Linux で systemd user unit(`rex.socket` / `rex.service`)と lingering を自動設定し、Windows では Service(要 admin)または `--user`(HKCU Run)を選べる +- macOS: beta 期間中は Homebrew cask / pkg installer がなく、公式配布は公証済み DMG のみ +- Windows: app / server は tester enrollment が必要で、beta 期間中は全 tester に開放されていない +- NixOS: 公式 flake(`pkgs.superlogical.com/rex/nix/.tar.gz`)と `rex.nixosModules.default` が存在するが、Linux 向け package は tester package token による認証が必要 + +## Decision + +### 配布 channel + +`preview` channel を追跡する。stable が未公開のため選択肢は preview / snapshot のみで、snapshot は不安定 build のため採用しない。stable が公開された時点で channel 選択を再評価する(後述の Consequences)。 + +version の pin は行わない。pc-setup は継続更新される user tool を snapshot の見た目のために pin しない方針(AGENTS.md §4、ADR-0010)であり、Rex も同じ扱いとする。Linux の `--user` install と macOS DMG install は bootstrap 実行ごとに最新版へ更新され、Windows zip install は install 時に preview release の version と照合して差分があるときだけ再取得する。 + +### OS ごとの導入経路 + +- **Ubuntu/WSL** (`platforms/ubuntu-wsl/install-rex.sh`): 公式 `install.sh` を `--user --channel preview` で実行する。`--user` は sudo なしで `~/.local/bin` のみへ binary を置き、systemd が動いていれば installer 自身が `rex server install` を実行する。script は `rex server install` を明示的に再実行する(公式に再実行安全と明記)。systemd user session がない環境では警告に留め、`rex server start` を手動 fallback とする。apt repo を追加する system install は採用しない。理由は、(1) bootstrap が既に `~/.local/bin` 前提の user scope で完結し、(2) repo install でも自動 update は発生せず結局 script 再実行が必要で、(3) 第三者 repo の管理対象を増やさないため。 +- **macOS** (`platforms/macos/install-rex.sh`): preview の `latest.dmg` を取得し、読み取り専用 mount から app bundle を `/Applications`(書き込めない場合は `~/Applications`)へ `ditto` で配置する。installed bundle の version/build と DMG 内の値が一致すれば copy を skip する。app は自身の local server を内包するため server 設定は不要。 +- **Windows 11** (`platforms/windows-11/install-rex.ps1`): preview の artifact index から windows 向け zip を取得し、SHA-256 を照合して `%LOCALAPPDATA%\Programs\Rex` へ展開する。user PATH への追加と `rex server install --user`(HKCU Run)まで自動化する。Windows Service 化は admin 権限とアカウントパスワード入力を要するため手動境界とする。beta の enrollment 制約があるため、install / server 登録の失敗は bootstrap を止めず、`verify.ps1` も未導入を WARN (pending) として扱う。 +- **NixOS**: desired state に含めない。公式 flake と NixOS module は存在するが tester package token が必須であり、secret を repository / flake / Nix store へ埋め込めない。Rex を使う host は host 側 flake input として token を機密境界(`/etc/nix/netrc` 等)で与えて個別に宣言する。 + +### mise との関係 + +mise registry に Rex backend は存在しないため `mise.global.toml` の `[tools]` へは追加しない。`mise.global.toml` / `mise.global.lock` は変更しない。導入は platform bootstrap(`scripts/apply-platform.sh` / `bootstrap.ps1`)が呼ぶ platform script が担う。 + +## Consequences + +- 各 OS の bootstrap が Rex を冪等に収束させ、`verify` が binary と server 状態を報告する +- preview channel を追跡するため、Rex 側の preview 更新は次回 bootstrap で自動的に取り込まれる。安定版が必要になった場合や preview の品質問題が出た場合は、channel 指定(`--channel`、DMG path、artifact index の channel)を stable/snapshot へ切り替える ADR 改訂が必要 +- `stable` channel 公開時に default install 先を stable へ移すかは別途判断する。`--channel preview` を明示している間は stable 公開後も preview に留まる +- WSL で systemd が無効な構成では server 常駐化は行われず、`rex server start` の手動運用になる。これは verify の WARN で可視化される +- Windows の Service 常駐化と beta enrollment は手動境界として残る。enrollment 完了後に Service 化を自動化するかは実機確認後に再評価する diff --git a/docs/adr/ADR-0027.md b/docs/adr/ADR-0027.md new file mode 100644 index 0000000..1405fe5 --- /dev/null +++ b/docs/adr/ADR-0027.md @@ -0,0 +1,25 @@ +# ADR-0027: herdr-t3 は検証済み ref の独立リリース配置で導入・更新・復旧する + +- Status: Superseded by ADR-0028 +- Date: 2026-11-22 +- Related: Issue #220, rebuildup/herdr-t3#6, rebuildup/herdr-t3 ADR-0004 + +## Context + +herdr-t3 は browser/PWA + ローカル Bun ブリッジ (`127.0.0.1:4737`) として配布され、デスクトップシェルや常駐サービスを持たない (herdr-t3 ADR-0004)。pc-setup は macOS と Windows 11 の双方で、検証済みリリースの導入・更新・起動・verify・ロールバックを再現可能にする必要がある。開発チェックアウト (Vite HMR、port 4738) とは同時運用できなければならない。 + +## Decision + +- 管理 state dir は `~/.local/share/herdr-t3` (Windows は `%LOCALAPPDATA%\herdr-t3`)。配下に `releases//` の ref 別独立 checkout を置き、`current` ファイルが選択中リリースを指す。 +- 導入対象は `v*` タグまたは完全 SHA のみ。dev ブランチや未承認の release 候補は自動選択しない。既定は origin の最新 `v*` タグ。 +- build (`mise install --locked` + `bun install --frozen-lockfile` + `bun run build`) は install/update 時のみ。起動時ビルドは行わない。 +- `current` の切替は build 成功後に限る。失敗時は選択・稼働中リリースを維持する。`previous` に記録した旧リリース dir を残し、rollback は pointer flip のみ (再 build 不要)。 +- launch は冪等: `/api/health` が応答すれば bridge を再利用してブラウザのみ開く。他プロセスが port 4737 を占有する場合は乗っ取らず失敗とする。 +- verify は install 状態 (ref, dist, bun) を必須とし、`--live` で `/api/health` の `ok` / `herdr.reachable` / version・commit を追加判定する。 +- Linux の herdr TUI 運用は変更しない。 + +## Consequences + +- リリースごとに独立 dir を持つため disk 使用量は増えるが、rollback が再 build なしで即時に行える。 +- Windows の named pipe / mirror pane 対応 (herdr-t3#6) が未完の間、Windows での `verify --live` は `herdr.reachable=false` を返しうる。これは既知の制限として Issue #220 の受入で追跡する。 +- 実機 (macOS / Windows 11) での導入→起動→verify→更新→rollback の受入証跡は Issue #220 で管理する。 diff --git a/docs/adr/ADR-0028.md b/docs/adr/ADR-0028.md new file mode 100644 index 0000000..2ed9e7f --- /dev/null +++ b/docs/adr/ADR-0028.md @@ -0,0 +1,44 @@ +# ADR-0028: herdr-t3 は Electron デスクトップアプリとして導入・検証する + +- Status: Accepted +- Date: 2026-11-22 +- Supersedes: ADR-0027 +- Related: Issue #220, rebuildup/herdr-t3#21, rebuildup/herdr-t3 ADR-0005 + +## Context + +herdr-t3 の配布方式が browser/PWA + ローカル Bun ブリッジから Electron +デスクトップアプリ (macOS .app / Windows 11 インストーラ) へ変更された +(herdr-t3 ADR-0005)。pc-setup#220 の install/launch/verify/rollback は +ブラウザ起動を前提としていたため、アプリ本体の導入・起動・検証へ改訂する。 + +## Decision + +- 導入対象は検証済みリリースのデスクトップアプリ成果物 (macOS `.app` / + Windows インストール可能パッケージ) であり、`v*` タグまたは固定 SHA に + 対応する。開発ブランチや未承認 RC は自動導入しない。 +- state dir・`current`/`previous` pointer・更新失敗時の現行維持・ + rollback (pointer flip) の構造は ADR-0027 を踏襲するが、単位は + 「ビルド済みアプリ成果物」とする。 +- 起動は OS の通常導線 (macOS は `.app` を `open`、Windows は + ショートカット/`Start-Process`)。Bun ブリッジやブラウザの別途起動を + 前提にしない。アプリは Main プロセス内に bridge core を持ち herdr + socket へ直接接続する。 +- verify はアプリ成果物の存在・バージョンと、可能ならアプリの + `/api/health` 相当 (IPC health) またはプロセス生存で Herdr 接続可否を + 判定する。実 Herdr への接続受入は herdr-t3#22 の実機証跡で管理する。 +- macOS の署名/notarize と Windows の SmartScreen 警告は、個人利用の + 実配布方式 (unsigned local build 等) に合わせて扱い、ストア配布は + 前提にしない。 +- Linux の herdr TUI 運用は変更しない。 + +## Consequences + +- `components/herdr-t3/` はアプリ成果物モデルへ改訂済み: install は + pin された ref を checkout して `bun run desktop:pack` + (electron-builder) で `.app` / `win-unpacked` を構築し、launch は + 生成物を直接起動する。Bun・ブラウザ・ローカル HTTP サーバーの + 常駐は不要。 +- herdr-t3 側で packaging (electron-builder 設定、アイコン、 + macOS/Windows 成果物レイアウト) が確定してから pc-setup 側の + install/verify 実装を完成させる。 diff --git a/docs/adr/ADR-0029.md b/docs/adr/ADR-0029.md new file mode 100644 index 0000000..344d76e --- /dev/null +++ b/docs/adr/ADR-0029.md @@ -0,0 +1,71 @@ +# ADR-0029: machine-global / optional-host / project-local CLI の所有境界 + +- Status: Accepted +- Date: 2026-11-23 +- Extends: ADR-0006, ADR-0009, ADR-0010 +- Related: ADR-0023 +- Supersedes intent of: 未統合だった旧 PR #201 の ADR 案(番号衝突のため 0029 として採番) + +## Context + +pc-setupのmachine-global baselineには、すべての開発機で使う共通CLIに加えて、 +特定クラウドや個別プロジェクトでだけ使うAWS CLI、Google Cloud CLI、 +Supabase CLI、Playwrightまで含まれていた。 +その結果、使用しない環境へのmandatory install、更新対象の肥大化、 +project tool versionとglobal versionの責任の重複が起きる。 + +CLIのインストール位置、バージョン所有者、認証/権限の境界は独立した概念。 +グローバルCLIが必ずグローバル認証を必要とするわけではなく、 +project-localインストールが資格情報を自動的に隔離するわけでもない。 + +## Decision + +CLIを用途と所有する正本で分類する。 + +1. **Machine-global core:** 複数プロジェクトの共通入口として頻用するCLIとruntime + (mise、gh、Infisical、各種agent、汎用shellツール等)。 + そのバージョンの既定値は `mise.global.toml` と adopted lock が所有する。 + Project側のtoolchain定義はglobal既定値より優先する。 +2. **Optional host capabilities:** AWS CLIとGoogle Cloud CLIのように、 + 実行環境・SDK・利用するクラウドが限定されるツール。 + 必要なホストだけに公式のインストール経路で導入する。 + 単に認証があるから、という理由でプロジェクトへの実行ファイルの複製は要求しない。 +3. **Project-local dependencies:** Supabase CLIやPlaywrightのように、 + プロジェクトのスキーマ、ビルド、テスト、マイグレーションと + バージョン互換性が結びつくCLI。 + Consumerの `mise.toml` / `package.json` / toolchain lock等で版を管理する。 + CLIが必要なリポジトリ自身が宣言し、pc-setupは代わりに配備しない。 + +採用判断はツールごとに利用頻度、バージョン結合度、認証境界、 +再現可能性、全ホストへの配備コストで行う。用途に合わない独自profile frameworkは作らない。 + +## Authentication and rollout boundary + +- Cloudのアカウント/プロジェクトはAWSのnamed profile、gcloudのnamed configuration、 + Supabaseのproject linkなど公式の手段で明示的に選択する。 + 実行時には現在の対象を確認し、本番操作を意図せず実行しない。 +- Credential、token、service key、auth fileはGit/lock/mise configに保存しない。 + Providerのsupported user store、Infisical、workload identity/OIDCなど適切な管理を使う。 +- 宣言除去は「今後bootstrapで必須にしない」という意味。 + 既存のインストール済みCLIや資格情報を自動消去しない。 + 移行後の未使用コピーの掃除は利用確認と別の安全な手順で行う。 +- WindowsのWinGet `Google.CloudSDK` / `Amazon.AWSCLI` もmandatory package setから外す。 + 既存のWindows利用者に削除を要求しない。 +- NixOSのFHS `aws` / `gcloud` / `supabase` command wrapperは残す。 + これはproject-local/tool-on-demandの実行互換のためのlaunch surfaceであり、 + バイナリ導入・認証済み・共通必須を意味しない。 + +## Verification + +- `mise.global.toml` と `mise.global.lock` の対象CLIは不在で、Playwrightの未参照sidecarも不在。 +- Platform bootstrap / verifyの共通必須一覧から対象CLIを除外する。 +- NixOSのcompatibility wrapperとmandatory command checksを混同しない。 +- CLIが必要な個別projectの構成、利用案内、ローカル検証を各projectが所有する。 +- lock採用/配備の仕組み自体(ADR-0010)を変更しない。 +- `scripts/ci.sh` が global config / lock / mandatory host package / orphan sidecar の整合を静的に検査する。 + +## Re-evaluation + +- 任意ホストのツールが日常的な複数プロジェクトの必須基盤になったとき +- Global既定値を使うよりproject-localに固定しない方が安全・再現可能だと示されたとき +- CLI公式配布・認証・mise backendに破壊的な仕様変更があったとき diff --git a/docs/adr/README.md b/docs/adr/README.md index b6d4d46..25ef649 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -27,5 +27,9 @@ | [ADR-0023](./ADR-0023.md) | Accepted | Vercel CLI は machine-global baseline に含めない | | [ADR-0024](./ADR-0024.md) | Accepted | converge の verify 用に launchctl print 1件だけを NOPASSWD で許可する | | [ADR-0025](./ADR-0025.md) | Accepted | Windows のツール所有は mise を唯一の正本とし、実行確認で壊れを検出する | +| [ADR-0026](./ADR-0026.md) | Accepted | Rex は OS 公式導入経路で管理し preview channel を追跡する | +| [ADR-0027](./ADR-0027.md) | Superseded by ADR-0028 | herdr-t3 は検証済み ref の独立リリース配置で導入・更新・復旧する | +| [ADR-0028](./ADR-0028.md) | Accepted | herdr-t3 は Electron デスクトップアプリとして導入・検証する | +| [ADR-0029](./ADR-0029.md) | Accepted | machine-global / optional-host / project-local CLI の所有境界 | 新しい ADR は `ADR-NNNN.md` の連番で追加します。既存 decision を置換する場合は旧 ADR の status と `Superseded by` も更新します。 diff --git a/mise.global.lock b/mise.global.lock index 2371e05..546c1b5 100644 --- a/mise.global.lock +++ b/mise.global.lock @@ -2,23 +2,64 @@ lockfile_version = 3 -[[tools.aws-cli]] -version = "2.42.1" -backend = "aqua:aws/aws-cli" +[[tools.agy]] +version = "1.5.14" +backend = "aqua:google-antigravity/antigravity-cli" specifiers = ["latest"] -[tools.aws-cli."platforms.linux-x64"] -checksum = "sha256:ff2631c32c5db291b099600f404bc493454ec66c125ff4604625da90480c1f47" -url = "https://awscli.amazonaws.com/awscli-exe-linux-x86_64-2.42.1.zip" +[tools.agy."platforms.linux-x64"] +checksum = "sha256:d58386322d2073e96b33f7cc32b4e9ae2db6228f58440369725967b2de48c7b5" +checksum_source = "mise-versions" +url = "https://github.com/google-antigravity/antigravity-cli/releases/download/1.5.14/agy_cli_linux_x64.tar.gz" +url_api = "https://api.github.com/repos/google-antigravity/antigravity-cli/releases/assets/774857841" + +[tools.agy."platforms.linux-x64-baseline"] +checksum = "sha256:d58386322d2073e96b33f7cc32b4e9ae2db6228f58440369725967b2de48c7b5" +checksum_source = "mise-versions" +url = "https://github.com/google-antigravity/antigravity-cli/releases/download/1.5.14/agy_cli_linux_x64.tar.gz" +url_api = "https://api.github.com/repos/google-antigravity/antigravity-cli/releases/assets/774857841" + +[tools.agy."platforms.linux-x64-musl"] +checksum = "sha256:d58386322d2073e96b33f7cc32b4e9ae2db6228f58440369725967b2de48c7b5" +checksum_source = "mise-versions" +url = "https://github.com/google-antigravity/antigravity-cli/releases/download/1.5.14/agy_cli_linux_x64.tar.gz" +url_api = "https://api.github.com/repos/google-antigravity/antigravity-cli/releases/assets/774857841" + +[tools.agy."platforms.linux-x64-musl-baseline"] +checksum = "sha256:d58386322d2073e96b33f7cc32b4e9ae2db6228f58440369725967b2de48c7b5" +checksum_source = "mise-versions" +url = "https://github.com/google-antigravity/antigravity-cli/releases/download/1.5.14/agy_cli_linux_x64.tar.gz" +url_api = "https://api.github.com/repos/google-antigravity/antigravity-cli/releases/assets/774857841" + +[tools.agy."platforms.macos-arm64"] +checksum = "sha256:b01bdd4591e13ddfcb0e049bea74ae9f83e80829adcf64aaa58f5bfb1a425a54" +checksum_source = "mise-versions" +url = "https://github.com/google-antigravity/antigravity-cli/releases/download/1.5.14/agy_cli_mac_arm64.tar.gz" +url_api = "https://api.github.com/repos/google-antigravity/antigravity-cli/releases/assets/774857995" + +[tools.agy."platforms.macos-x64"] +checksum = "sha256:c142141141cbaa93f4e46904b76341e349f3f2b78445f877f39468dfe60dda1e" +checksum_source = "mise-versions" +url = "https://github.com/google-antigravity/antigravity-cli/releases/download/1.5.14/agy_cli_mac_x64.tar.gz" +url_api = "https://api.github.com/repos/google-antigravity/antigravity-cli/releases/assets/774857833" -[tools.aws-cli."platforms.macos-arm64"] -checksum = "sha256:74e38ab8a592b635d7b0ae85e6f33cb1ceba79ce19c112d425cbbf535e607b23" -url = "https://awscli.amazonaws.com/AWSCLIV2-2.42.1.pkg" +[tools.agy."platforms.macos-x64-baseline"] +checksum = "sha256:c142141141cbaa93f4e46904b76341e349f3f2b78445f877f39468dfe60dda1e" +checksum_source = "mise-versions" +url = "https://github.com/google-antigravity/antigravity-cli/releases/download/1.5.14/agy_cli_mac_x64.tar.gz" +url_api = "https://api.github.com/repos/google-antigravity/antigravity-cli/releases/assets/774857833" -[tools.aws-cli."platforms.macos-x64"] -checksum = "sha256:74e38ab8a592b635d7b0ae85e6f33cb1ceba79ce19c112d425cbbf535e607b23" -url = "https://awscli.amazonaws.com/AWSCLIV2-2.42.1.pkg" +[tools.agy."platforms.windows-x64"] +checksum = "sha256:144b37d27595ca1ab6b19b9f365e9ee66fb8cc95c020b541858d8947e02daf3f" +checksum_source = "mise-versions" +url = "https://github.com/google-antigravity/antigravity-cli/releases/download/1.5.14/agy_cli_windows_x64.zip" +url_api = "https://api.github.com/repos/google-antigravity/antigravity-cli/releases/assets/774858003" +[tools.agy."platforms.windows-x64-baseline"] +checksum = "sha256:144b37d27595ca1ab6b19b9f365e9ee66fb8cc95c020b541858d8947e02daf3f" +checksum_source = "mise-versions" +url = "https://github.com/google-antigravity/antigravity-cli/releases/download/1.5.14/agy_cli_windows_x64.zip" +url_api = "https://api.github.com/repos/google-antigravity/antigravity-cli/releases/assets/774858003" [[tools.bat]] version = "0.26.1" backend = "aqua:sharkdp/bat" @@ -264,23 +305,6 @@ checksum_source = "mise-versions" url = "https://github.com/junegunn/fzf/releases/download/v0.75.0/fzf-0.75.0-windows_amd64.zip" url_api = "https://api.github.com/repos/junegunn/fzf/releases/assets/720590885" -[[tools.gcloud]] -version = "594.0.0" -backend = "vfox:jdx/vfox-gcloud" -specifiers = ["latest"] - -[tools.gcloud."platforms.linux-x64"] -checksum = "sha256:dcafb57eefb7254f9fcd34247f09549f3bd7fd7453d28add3b5c961ceb9e6be0" -url = "https://storage.googleapis.com/cloud-sdk-release/google-cloud-sdk-594.0.0-linux-x86_64.tar.gz" - -[tools.gcloud."platforms.macos-arm64"] -checksum = "sha256:fc01d5a31927191c1dfb82bb971ce0f9b73ed0ece16a5f8208e5d88b4c5baa57" -url = "https://storage.googleapis.com/cloud-sdk-release/google-cloud-sdk-594.0.0-darwin-arm.tar.gz" - -[tools.gcloud."platforms.macos-x64"] -checksum = "sha256:4f49dc37063b7b29008b249ae163c86ab338aa3efb506b48c4f4bb969108f517" -url = "https://storage.googleapis.com/cloud-sdk-release/google-cloud-sdk-594.0.0-darwin-x86_64.tar.gz" - [[tools.gdu]] version = "5.39.0" backend = "aqua:dundee/gdu" @@ -565,12 +589,6 @@ aube = { path = ".mise/locks/mise.global/npm-npkill/1.0.0", digest = "sha256:ebd backend = "npm:npkill" specifiers = ["latest"] -[[tools."npm:playwright"]] -version = "1.65.1" -aube = { path = ".mise/locks/mise.global/npm-playwright/1.65.1", digest = "sha256:f87d3323cec54802bd1cae015bbcbb00af6f4192ffe35c191a6ccdad4cd955e0" } -backend = "npm:playwright" -specifiers = ["latest"] - [[tools.oh-my-pi]] version = "19.1.0" backend = "github:can1357/oh-my-pi" @@ -763,35 +781,6 @@ checksum = "sha256:8a4e35ab0b331c85d73567b12f2a444df187f483e5079ceffa6bda1faa2e7 url = "https://github.com/koalaman/shellcheck/releases/download/v0.11.0/shellcheck-v0.11.0.zip" url_api = "https://api.github.com/repos/koalaman/shellcheck/releases/assets/279056944" -[[tools.supabase]] -version = "3.2.0" -backend = "aqua:supabase/cli" -specifiers = ["latest"] - -[tools.supabase."platforms.linux-x64"] -checksum = "sha256:fb88b175a817563505be02c60872060bcb8d5c869a1aa5656eaeb085d4a2f1e4" -url = "https://github.com/supabase/cli/releases/download/v3.2.0/supabase_linux_amd64.tar.gz" -url_api = "https://api.github.com/repos/supabase/cli/releases/assets/755641437" -provenance = "github-attestations" - -[tools.supabase."platforms.macos-arm64"] -checksum = "sha256:c9e27cdaf848f216879df0a354fca96c7e5ac0d1527d934b730ec62ba348b86d" -url = "https://github.com/supabase/cli/releases/download/v3.2.0/supabase_darwin_arm64.tar.gz" -url_api = "https://api.github.com/repos/supabase/cli/releases/assets/755640673" -provenance = "github-attestations" - -[tools.supabase."platforms.macos-x64"] -checksum = "sha256:0b02ac63d6400b3f238a442c3d2aa72d2977b3a5dcd3f2e679095a004733102e" -url = "https://github.com/supabase/cli/releases/download/v3.2.0/supabase_darwin_amd64.tar.gz" -url_api = "https://api.github.com/repos/supabase/cli/releases/assets/755640863" -provenance = "github-attestations" - -[tools.supabase."platforms.windows-x64"] -checksum = "sha256:127618716a054061e961db0ffbcbb87a0c6f0702ed70cd55ea19c339a38b40ed" -url = "https://github.com/supabase/cli/releases/download/v3.2.0/supabase_windows_amd64.tar.gz" -url_api = "https://api.github.com/repos/supabase/cli/releases/assets/755641776" -provenance = "github-attestations" - [[tools.worktrunk]] version = "0.83.0" backend = "packslip:github.com/max-sixty/worktrunk" diff --git a/mise.global.toml b/mise.global.toml index 93ef7bc..ea0a634 100644 --- a/mise.global.toml +++ b/mise.global.toml @@ -26,6 +26,12 @@ gh = "latest" infisical = "latest" claude = "latest" codex = "latest" +# Antigravity CLI (agy): aqua:google-antigravity/antigravity-cli. Auth is +# per-user Google OAuth state under ~/.gemini and the OS keyring, never +# managed here. Over SSH, agy switches to file-based token storage +# (~/.gemini/antigravity-cli/antigravity-oauth-token); the dotfiles `agy` +# wrapper normalizes that split. +agy = "latest" # OpenCode 2 is distributed as @opencode/cli on npm; the legacy `opencode` tool # (aqua:anomalyco/opencode) only tracks the 1.x GitHub releases. "npm:@opencode/cli" = { version = "latest", depends = ["node"], allow_builds = ["@opencode/cli"] } @@ -35,9 +41,6 @@ worktrunk = "latest" # keep the registry entry unchanged. herdr = { version = "latest", os = ["linux", "macos"] } -gcloud = { version = "latest", os = ["linux", "macos"] } -aws-cli = { version = "latest", os = ["linux", "macos"] } -supabase = "latest" # Vercel CLI is deliberately not in the machine-global baseline. Its npm # dependency graph fails mise's default npm supply-chain policy # (trustPolicy=no-downgrade), and exempting it would mean listing dozens of @@ -93,7 +96,6 @@ oh-my-pi = "latest" # Node launcher plus a per-platform native binary as an optional dependency, so # it follows the same npm channel as OpenCode. "npm:devin" = { version = "latest", depends = ["node"] } -"npm:playwright" = "latest" ruby = "4" [tools."github:herdrdev/herdr"] diff --git a/mise.toml b/mise.toml index f89977d..647268c 100644 --- a/mise.toml +++ b/mise.toml @@ -49,8 +49,6 @@ bun = "1.4.2" # Visual Studio is intentionally not installed here: any edition/year is accepted # and platforms/windows-11/verify.ps1 checks the MSVC / Windows SDK capabilities. "winget:Google.AndroidStudio" = { os = "windows" } -"winget:Google.CloudSDK" = { os = "windows" } -"winget:Amazon.AWSCLI" = { os = "windows" } "winget:Tailscale.Tailscale" = { os = "windows" } [bootstrap.repos] diff --git a/plans/macos/README.md b/plans/macos/README.md index 6ec2d2d..7c935e8 100644 --- a/plans/macos/README.md +++ b/plans/macos/README.md @@ -40,10 +40,10 @@ Cross-machine developer CLI/runtime requirements are inherited from root `mise.t - Node.js / Python / pnpm / Bun / Rust - Claude Code / Codex / OpenCode / Devin / Worktrunk / Herdr - Open Code Review / npkill / cargo-clean-all -- Google Cloud CLI / AWS CLI -- Supabase CLI - ripgrep / fd / fzf / jq / bat / gdu / ShellCheck / Neovim +AWS / Google Cloud はホスト任意機能、Supabase / Playwright はプロジェクト依存として管理します([ADR-0029](../../docs/adr/ADR-0029.md))。 + macOS-specific application candidates are recorded separately in `mise.candidate.toml`. These remain candidate application choices until actual continued use justifies promotion into the active macOS package graph. diff --git a/platforms/macos/README.md b/platforms/macos/README.md index 7e3743a..9e8ef29 100644 --- a/platforms/macos/README.md +++ b/platforms/macos/README.md @@ -213,6 +213,17 @@ VM を停止したまま `docker` を実行すると `Cannot connect to the Dock verify は mise 設定の読み込みと OS 条件、`colima` / `docker` / compose / buildx / `ffmpeg`、Docker Context、VM 設定を確認する。VM を起動することはなく、停止中は「作成済みだが停止中」と未構築を区別して報告し、daemon に依存する項目だけを skip する。`--smoke` は VM が起動中のときだけ有効。 +## Rex + +[Rex](https://www.superlogical.com/rex) は agent execution runtime の macOS 側 desired state。beta 期間中は Homebrew cask / pkg installer がなく、公式配布は公証済み DMG のみ。`platforms/macos/install-rex.sh`(`scripts/apply-platform.sh` から bootstrap 時に実行)が preview channel の `latest.dmg` を取得し、`/Applications`(書き込めない場合は `~/Applications`)へ app bundle を配置する。同一 version/build なら copy を skip するため再実行可能。 + +```bash +./platforms/macos/install-rex.sh +ls -d /Applications/Rex*.app "$HOME"/Applications/Rex*.app +``` + +macOS app は自身の local Rex server を内包するため追加の server 設定は不要。agent連携は app 内コマンドパレットまたは `rex skill setup` で行う(手動)。channel / pin 判断は [`ADR-0026`](../../docs/adr/ADR-0026.md) を参照。 + ## Verification ```bash diff --git a/platforms/macos/install-rex.sh b/platforms/macos/install-rex.sh new file mode 100755 index 0000000..232d733 --- /dev/null +++ b/platforms/macos/install-rex.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Install the Rex macOS app (https://www.superlogical.com/rex). +# +# Rex has no Homebrew cask or pkg installer during the beta; the official +# distribution is a notarized DMG. The preview channel's latest.dmg alias is +# the public download URL used by testers. The installer downloads the DMG, +# mounts it read-only at a private mountpoint, and copies the app bundle. It +# re-runs cleanly: when the installed bundle already carries the same version +# and build, the copy is skipped. See docs/adr/ADR-0026.md. + +dmg_url="https://blob.superlogical.com/download/rex-app/preview/latest.dmg" + +log() { + printf '\n==> %s\n' "$*" +} + +warn() { + printf 'WARN %s\n' "$*" >&2 +} + +fail() { + printf 'FAIL %s\n' "$*" >&2 + exit 1 +} + +if [[ "$(uname -s)" != "Darwin" ]]; then + printf 'Rex app install is macOS-only; skipping.\n' + exit 0 +fi + +bundle_value() { + # bundle_value ; prints nothing when absent. + /usr/libexec/PlistBuddy -c "Print :$2" "$1/Contents/Info.plist" 2>/dev/null || true +} + +installed_app="" +for candidate in /Applications/Rex*.app "$HOME/Applications/Rex"*.app; do + if [[ -d "$candidate" ]]; then + installed_app="$candidate" + break + fi +done + +work_dir="$(mktemp -d)" +mount_point="$work_dir/mnt" +mkdir -p "$mount_point" +cleanup() { + hdiutil detach "$mount_point" -quiet >/dev/null 2>&1 || true + rm -rf "$work_dir" +} +trap cleanup EXIT + +log "Downloading Rex preview DMG" +curl -fL --retry 3 -o "$work_dir/Rex.dmg" "$dmg_url" + +log "Mounting DMG" +if ! hdiutil attach -nobrowse -readonly -mountpoint "$mount_point" "$work_dir/Rex.dmg" >/dev/null; then + fail "could not mount $work_dir/Rex.dmg" +fi + +source_app="" +for candidate in "$mount_point"/Rex*.app; do + if [[ -d "$candidate" ]]; then + source_app="$candidate" + break + fi +done + +if [[ -z "$source_app" ]]; then + fail "no Rex*.app found in the mounted DMG" +fi + +source_version="$(bundle_value "$source_app" CFBundleShortVersionString)" +source_build="$(bundle_value "$source_app" CFBundleVersion)" + +if [[ -n "$installed_app" ]]; then + installed_version="$(bundle_value "$installed_app" CFBundleShortVersionString)" + installed_build="$(bundle_value "$installed_app" CFBundleVersion)" + if [[ -n "$source_version" && "$installed_version" == "$source_version" && "$installed_build" == "$source_build" ]]; then + printf 'ok Rex %s (%s) already installed at %s\n' \ + "$installed_version" "$installed_build" "$installed_app" + exit 0 + fi + printf 'updating Rex %s (%s) -> %s (%s)\n' \ + "${installed_version:-unknown}" "${installed_build:-unknown}" \ + "${source_version:-unknown}" "${source_build:-unknown}" +fi + +# Prefer /Applications (the conventional location, writable by admin users +# without sudo); fall back to a per-user Applications folder. +target_dir="/Applications" +if [[ ! -w "$target_dir" ]]; then + target_dir="$HOME/Applications" + mkdir -p "$target_dir" +fi + +target_app="$target_dir/$(basename "$source_app")" + +# A bundle already at the target may live in the other Applications folder; +# remove stale copies so only the managed location remains. +for stale in /Applications/Rex*.app "$HOME/Applications/Rex"*.app; do + if [[ -d "$stale" && "$stale" != "$target_app" ]]; then + warn "removing stale Rex app copy: $stale" + rm -rf "$stale" + fi +done + +log "Installing Rex to $target_app" +if [[ -d "$target_app" ]]; then + rm -rf "$target_app" +fi +ditto "$source_app" "$target_app" + +# Sanity check: warn when the bundle does not contain this Mac's architecture. +main_executable="$(bundle_value "$target_app" CFBundleExecutable)" +if [[ -n "$main_executable" && -f "$target_app/Contents/MacOS/$main_executable" ]]; then + if ! lipo -info "$target_app/Contents/MacOS/$main_executable" 2>/dev/null | grep -q "$(uname -m)"; then + warn "installed Rex executable may not support $(uname -m); check: lipo -info \"$target_app/Contents/MacOS/$main_executable\"" + fi +fi + +printf 'ok Rex %s (%s) installed at %s\n' \ + "${source_version:-unknown}" "${source_build:-unknown}" "$target_app" +printf 'note launch Rex once, then run "rex skill setup" inside it to install agent skills\n' diff --git a/platforms/nixos/README.md b/platforms/nixos/README.md index b6f5000..bf24649 100644 --- a/platforms/nixos/README.md +++ b/platforms/nixos/README.md @@ -82,8 +82,8 @@ Portable user CLI baseline (`mise.global.toml`): - Claude Code / Codex / OpenCode / Devin - Worktrunk / Herdr - Open Code Review / npkill / cargo-clean-all / gdu -- Google Cloud CLI / AWS CLI -- Supabase CLI + +AWS / Google Cloud / Supabase は共通インストール対象外です。`flake.nix` には project-local / optional CLI を実行するための FHS wrapper 名だけ残します。wrapper があることと CLI のインストール済み・認証済みであることは別です([ADR-0029](../../docs/adr/ADR-0029.md))。 Worktrunk の Bash integration も Home Manager で宣言します。 @@ -288,14 +288,18 @@ gh auth status Claude Code 本体は `mise.global.toml` の portable CLI baseline から導入します。 -provider 接続は machine provisioning ではなく `rebuildup/dotfiles` の Infisical runtime integration が所有します。MiMo 利用時は dotfiles の provider entrypoint 経由で起動します。 +provider 接続は machine provisioning ではなく `rebuildup/dotfiles` の Infisical runtime integration が所有します。 ```bash -claude -# equivalent: ~/.dotfiles/script/agent/mimo claude +claude # official native Claude Code login +agent list # configured harness/provider routes +agent claude openrouter # explicit opt-in API route (dotfiles launcher) +agent opencode zen # free OpenCode Zen models +# MiMo は dotfiles の tuned entrypoint が維持: +~/.dotfiles/script/agent/mimo claude ``` -`~/.config/pc-setup/shell-init.bash` は `~/.dotfiles/script/agent` を PATH 先頭に置き、`mimo` entrypoint が存在する場合に `claude` を process-scoped injection へ委譲します。委譲は shell function と、agent 配下の `claude` PATH shim の両方で行うため、function 未定義のシェルでも素の Claude Code に落ちません。provider URL / model / credential は shell には export されません。 +`~/.config/pc-setup/shell-init.bash` は `~/.dotfiles/script/agent`(provider-tuned entrypoint)を PATH に追加するだけで、`claude` を shell function や PATH shim で委譲しません(native CLI のまま)。provider URL / model / credential を shell に export もしません。代替API route は `agent` launcher(`~/.local/bin/agent`、設定は `~/.dotfiles/config/agents.toml`)が process-scoped に注入します。`agent` 本体は dotfiles の `./script/link` が配置します。 ### OpenCode @@ -412,6 +416,10 @@ Infisical CLIはLinuxではOS Secret Serviceを利用し、利用できない環 global profile に全projectの依存を集約しません。 +## Rex + +Rex には公式 flake (`https://pkgs.superlogical.com/rex/nix/.tar.gz`) があり、`rex.nixosModules.default` が shared server / login server を systemd service として構成できる。ただし Linux 向け package は現在 tester package token による認証が必要で、token は secret であり Flake / Nix store / この repository に埋め込めない。そのため machine baseline の desired state には含めず、Rex を使う host は host 側の flake input として `/etc/nix/netrc` 等の機密境界で token を与えて個別に宣言する。判断の記録は [`ADR-0026`](../../docs/adr/ADR-0026.md) を参照してください。 + ## References - NixOS Manual: https://nixos.org/manual/nixos/stable/ diff --git a/platforms/nixos/configure-shell.sh b/platforms/nixos/configure-shell.sh index 83f0ba3..2637284 100755 --- a/platforms/nixos/configure-shell.sh +++ b/platforms/nixos/configure-shell.sh @@ -26,11 +26,9 @@ if [[ -d "$pc_setup_agent_entry" ]]; then *) export PATH="$pc_setup_agent_entry:$PATH" ;; esac fi -if [[ -x "$pc_setup_agent_entry/mimo" ]]; then - claude() { - "$HOME/.dotfiles/script/agent/mimo" claude "$@" - } -fi +# Native 'claude' stays untouched. Opt-in API routes go through the dotfiles +# `agent` launcher: ~/.local/bin/agent, config ~/.dotfiles/config/agents.toml +# (process-scoped Infisical injection, explicit provider per launch). if command -v wt >/dev/null 2>&1; then eval "$(wt config shell init bash)" diff --git a/platforms/nixos/flake.nix b/platforms/nixos/flake.nix index 89c3d05..8ceb0e6 100644 --- a/platforms/nixos/flake.nix +++ b/platforms/nixos/flake.nix @@ -132,6 +132,8 @@ "devin" "wt" "herdr" + # Compatibility launchers for optional host and project-local tools. + # These wrappers do not install CLI binaries or imply credentials. "gcloud" "aws" "supabase" diff --git a/platforms/nixos/verify.sh b/platforms/nixos/verify.sh index c1686a0..b7e02fb 100755 --- a/platforms/nixos/verify.sh +++ b/platforms/nixos/verify.sh @@ -84,9 +84,6 @@ commands=( devin wt herdr - gcloud - aws - supabase npkill ocr cargo-clean-all @@ -114,10 +111,10 @@ fi shell_init_file="$HOME/.config/pc-setup/shell-init.bash" if [[ -r "$shell_init_file" ]] && grep -Fq '.dotfiles/script/agent' "$shell_init_file" && - grep -Fq 'agent/mimo' "$shell_init_file"; then - ok "dotfiles provider entrypoint routing is present in shell init" + ! grep -Eq 'claude\(\)|agent/mimo.*claude' "$shell_init_file"; then + ok "dotfiles agent entrypoints are provisioned and native claude is not overridden" else - fail "dotfiles provider entrypoint routing is missing from $shell_init_file; rerun platforms/nixos/configure-shell.sh" + fail "pc-setup shell init is missing, lost the dotfiles agent PATH entry, or overrides native claude; rerun platforms/nixos/configure-shell.sh" fi if [[ -d "$HOME/.local/state/pc-setup/nix-user-baseline/bin" ]]; then diff --git a/platforms/ubuntu-wsl/README.md b/platforms/ubuntu-wsl/README.md index 8e0bc85..d238ea9 100644 --- a/platforms/ubuntu-wsl/README.md +++ b/platforms/ubuntu-wsl/README.md @@ -61,13 +61,25 @@ Portable developer tools are declared once in `mise.global.toml`, which is linke - Claude Code / Codex / OpenCode / Devin - Worktrunk / Herdr - Open Code Review / npkill / cargo-clean-all -- Google Cloud CLI / AWS CLI -- Supabase CLI - ripgrep / fd / fzf / jq / bat / gdu - ShellCheck / Neovim +AWS / Google Cloud は使うホストの任意機能、Supabase / Playwright は各プロジェクト側のバージョン管理対象です。CLIの有無は共通bootstrapの成否に含めません([ADR-0029](../../docs/adr/ADR-0029.md))。 + The Ubuntu bootstrap does not duplicate installation logic for those tools. +## Rex + +Rex (https://www.superlogical.com/rex) is the second agent execution runtime baseline. mise has no Rex backend, so `platforms/ubuntu-wsl/install-rex.sh` — invoked from `scripts/apply-platform.sh` during bootstrap — installs it through the official installer: + +```bash +curl -fsSL https://pkgs.superlogical.com/rex/install.sh | sh -s -- --user --channel preview +``` + +`--user` needs no sudo and only writes the `rex` binary to `~/.local/bin` plus the server setup. On a systemd-enabled WSL the installer enables the `rex.socket`/`rex.service` user units and lingering, so the server starts at boot and survives logout; the script repeats `rex server install` explicitly because re-running it is safe. Without a systemd user session the script warns and the fallback is a manual `rex server start`. + +Only the `preview` channel is published today; the channel choice and the revisit condition are recorded in `docs/adr/ADR-0026.md`. Re-running the installer upgrades Rex, so each bootstrap also refreshes the preview build. + ## Authentication and dotfiles mise clones `rebuildup/dotfiles` to: diff --git a/platforms/ubuntu-wsl/install-rex.sh b/platforms/ubuntu-wsl/install-rex.sh new file mode 100755 index 0000000..c92439f --- /dev/null +++ b/platforms/ubuntu-wsl/install-rex.sh @@ -0,0 +1,75 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Install Rex (https://www.superlogical.com/rex) for the current user. +# +# The official installer is used with --user so no sudo or third-party apt +# repository is required: the rex binary lands in ~/.local/bin, which is the +# only path the installer writes outside the server setup. When systemd is +# running, the installer itself also runs `rex server install`, which enables +# the rex.socket/rex.service systemd user units and lingering. This script +# repeats that step explicitly so the persistence contract does not depend on +# installer internals; `rex server install` is documented as safe to re-run. +# +# Only the preview channel is published today (stable returns 404), so the +# channel is pinned explicitly. See docs/adr/ADR-0026.md. + +log() { + printf '\n==> %s\n' "$*" +} + +warn() { + printf 'WARN %s\n' "$*" >&2 +} + +if [[ ! -r /etc/os-release ]]; then + warn "cannot detect the distribution; skipping Rex install" + exit 0 +fi + +# shellcheck disable=SC1091 +. /etc/os-release + +case "${ID:-}" in + ubuntu|debian) + ;; + *) + printf 'skipping Rex install on unsupported distribution: %s\n' "${ID:-unknown}" + exit 0 + ;; +esac + +log "Installing Rex (preview channel, user scope)" +curl -fsSL https://pkgs.superlogical.com/rex/install.sh | sh -s -- --user --channel preview + +rex_bin="" +for candidate in "$HOME/.local/bin/rex" "$(command -v rex 2>/dev/null || true)"; do + if [[ -n "$candidate" && -x "$candidate" ]]; then + rex_bin="$candidate" + break + fi +done + +if [[ -z "$rex_bin" ]]; then + printf 'Rex installer finished but the rex binary was not found.\n' >&2 + printf 'Check that ~/.local/bin exists and is on PATH, then rerun.\n' >&2 + exit 1 +fi + +printf 'ok rex -> %s (%s)\n' "$rex_bin" "$("$rex_bin" version | head -n 1)" + +if [[ ":$PATH:" != *":$HOME/.local/bin:"* ]]; then + warn "$HOME/.local/bin is not on PATH in this shell; add it to your shell profile" +fi + +# `rex server install` needs a systemd user session. Without one (for example +# WSL without systemd, or most containers) the documented fallback is a +# per-boot `rex server start`, so this stays a warning rather than a failure. +if command -v systemctl >/dev/null 2>&1 && systemctl --user list-units >/dev/null 2>&1; then + log "Enabling the Rex server at boot (systemd user units)" + if ! "$rex_bin" server install; then + warn "rex server install failed; run it manually: rex server install" + fi +else + warn "no systemd user session detected; start the server manually with: rex server start" +fi diff --git a/platforms/ubuntu-wsl/verify.sh b/platforms/ubuntu-wsl/verify.sh index 37a75be..3b51a55 100755 --- a/platforms/ubuntu-wsl/verify.sh +++ b/platforms/ubuntu-wsl/verify.sh @@ -54,6 +54,7 @@ snapshot() { printf 'worktrunk=%s\n' "$(first_line wt --version)" printf 'claude=%s\n' "$(first_line claude --version)" printf 'opencode=%s\n' "$(first_line opencode --version)" + printf 'rex=%s\n' "$(first_line rex version)" printf 'devin=%s\n' "$(first_line devin --version)" printf 'shellcheck=%s\n' "$(first_line shellcheck --version)" printf 'python=%s\n' "$(first_line python3 --version)" @@ -62,7 +63,7 @@ snapshot() { } if [[ "$SNAPSHOT" -eq 1 ]]; then - required=(git gh rg fd fzf jq bat gdu bun rustc cargo wt claude opencode devin shellcheck python3 cmake clang) + required=(git gh rg fd fzf jq bat gdu bun rustc cargo wt claude opencode rex devin shellcheck python3 cmake clang) for cmd in "${required[@]}"; do if ! command -v "$cmd" >/dev/null 2>&1; then printf 'Cannot create complete snapshot: missing command %s\n' "$cmd" >&2 @@ -149,14 +150,12 @@ commands=( wt herdr pnpm - gcloud - aws - supabase npkill ocr cargo-clean-all claude opencode + rex devin shellcheck python3 @@ -188,6 +187,16 @@ if command -v claude >/dev/null 2>&1; then warn "Claude Code login is interactive; run: claude and confirm the active account" fi +# `--autostart=false` keeps verification side-effect free: without it a +# missing local server would be started just by asking for status. +if command -v rex >/dev/null 2>&1; then + if rex server status --autostart=false >/dev/null 2>&1; then + ok "Rex server is reachable" + else + warn "Rex server is not reachable; run: rex server install (or rex server start without systemd)" + fi +fi + # `--global` alone does not expand [include] directives, so a machine whose # identity lives in ~/.gitconfig.local (included from the managed ~/.gitconfig) # was reported as unconfigured. Measured on the dotfiles layout: diff --git a/platforms/windows-11/README.md b/platforms/windows-11/README.md index 70467cc..4114566 100644 --- a/platforms/windows-11/README.md +++ b/platforms/windows-11/README.md @@ -47,12 +47,12 @@ root `mise.toml` の mandatory Windows package phase には、bootstrap / develo - PowerShell 7 - .NET SDK 10 - Android Studio -- Google Cloud SDK -- AWS CLI - Tailscale これらは fail-fast。Git と mise 自体も bootstrap dependency。 +AWS CLI と Google Cloud SDK は machine-wide mandatory ではありません。利用するホストで任意に導入し、認証先はコマンドごとに明示します(ADR-0029)。既存の認証設定やインストール済みバイナリを bootstrap は削除しません。 + ### Best-effort desktop apps GUI / desktop application は `platforms/windows-11/apps.psd1` が canonical inventory。 @@ -95,8 +95,6 @@ OSごとにWinGet packageを重複宣言せず、`mise.global.toml [tools]` を - Claude Code / Codex / OpenCode / Devin - Worktrunk / Herdr - Open Code Review / npkill / cargo-clean-all -- Google Cloud CLI / AWS CLI -- Supabase CLI - ripgrep / fd / fzf / jq / bat / gdu - ShellCheck / Neovim @@ -131,10 +129,22 @@ pwsh -NoProfile -File platforms/windows-11/powershell-path.ps1 -Apply # 管理 並び順だけを変更し、PATH entry も PowerShell 本体も削除しない。変更前の PATH は `%LOCALAPPDATA%\pc-setup` に保存する。 +`winget:Microsoft.PowerShell` は MSI と MSIX のどちらの package も同じ正本として導入されうる。MSIX の場合 `pwsh` は `%LOCALAPPDATA%\Microsoft\WindowsApps\Microsoft.PowerShell__x64__\pwsh.exe` の per-user 実行エイリアスに解決される。`verify.ps1` は MSI path・MSIX `InstallLocation`・実行エイリアスのいずれにも一致すれば正本として受理する。 + ### Herdr 実機の Herdr は GitHub backend (`github:herdrdev/herdr`、aqua registry より新しい)。Windows だけこの宣言を `mise.global.toml` に置き、Linux/macOS は従来の registry entry のまま。`mise.global.lock` には Windows の GitHub backend entry を追加している。 +### Rex + +Rex (https://www.superlogical.com/rex) は agent execution runtime の Windows 側 desired state。WinGet package は存在しないため、`platforms/windows-11/install-rex.ps1` が preview channel の公式 artifact index (`blob.superlogical.com/api/releases/rex/preview`) から windows 向け zip を取得し、SHA-256 を照合して `%LOCALAPPDATA%\Programs\Rex` へ展開する。管理者権限は不要。 + +- user PATH への追加と `rex server install --user`(HKCU Run によるサインイン時起動)まで自動化する。 +- 常駐 Windows Service 化 (`rex server install`、管理者権限とアカウントパスワード入力が必要) は手動境界とし、自動実行しない。 +- beta 期間中は Windows server が tester enrollment を要求するため、install または server 登録が失敗しても bootstrap は継続する。`verify.ps1` は未導入を FAIL ではなく WARN (pending) として報告する。 + +channel / pin 判断は [`ADR-0026`](../../docs/adr/ADR-0026.md) を参照。 + ## Microsoft Store boundary miseのWinGet managerではStore sourceをこのrepositoryの要件どおり明示できないため、Store product IDをroot PowerShell adapterが扱う。 @@ -170,6 +180,10 @@ infisical login --domain=https://secrets.rebuildup.dev setup script は Infisical から OAuth secret を runtime injectionし、未接続の host だけを persistent / preauthorized node として登録する。既に Tailscale backend が `Running` の host は既存 node identity を維持し、再登録しない。 +`tailscale status --json` の出力は UTF-8 で decode する。Windows PowerShell 5.1 が console の OEM code page で decode すると、日本語 Windows では Health 文字列が文字化けして `ConvertFrom-Json` が失敗するため、status / serve の呼び出しは一時的に UTF-8 へ切り替えて実行する。 + +status が取得・parse できない場合は **fail closed** とし、node 登録 (`tailscale up --auth-key`) へ進まない。状態不明を「未接続」と誤認して既存 node を再登録する経路はない。`BackendState` が判明して `Running` 以外 (`NeedsLogin` / `Stopped` など) の場合だけ登録処理へ進む。 + その後 Tailscale Serve を idempotent に収束させるため、WSL 側の SSH endpoint は従来どおり Windows localhost にだけ bind したままでよい。LAN interfaceへ `2222` / `2223` を直接公開しない。 詳細な authority / recovery boundary は [ADR-0011](../../docs/adr/ADR-0011.md) を参照。 @@ -182,6 +196,17 @@ Windows nativeのsymlink adapterはまだcanonical化していないため、roo 現時点のuser-level agent/dotfiles設定はWSL側をcanonicalとし、Windows native adapter完成後に同じsource of truthを接続する。 +例外として、統一 `agent` ランチャー(rebuildup/dotfiles PR #46)はBun + TypeScriptの単一実装(`script/agent.ts`)でWindows nativeを直接サポートする。symlink不要で、以下で起動できる: + +```powershell +& ~\.dotfiles\script\agent.ps1 check +& ~\.dotfiles\script\agent.ps1 opencode zen -- run "explain this repo" +& ~\.dotfiles\script\agent.ps1 opencode-zen -- run "..." # shortcut form(TOML由来) +& ~\.dotfiles\script\agent.ps1 shortcuts create # ~/.local/bin に最小 .cmd を生成 +``` + +Secret注入は `script/with-secrets.ps1`(`infisical.exe` をWindows nativeで起動)。`config/agents.toml` は全OS共通のsource of truth。引数の忠実な渡し方にはPowerShell 7.3+を推奨(entry scriptが `$PSNativeCommandArgumentPassing = 'Standard'` を設定)。`bun` と `pwsh` はmise bootstrap(`mise.global.toml` / mandatory package)で揃う。 + ## Manual/vendor boundaries 次はpackage presenceだけでは完了しない。 @@ -296,6 +321,21 @@ pwsh -NoProfile -File platforms/windows-11/mise-path-ownership.ps1 -Restore +``` + +- 変更するのは **User PATH (HKCU) のみ**。展開後の完全一致で `.cargo\bin` entry を除去し、mise shims entry が無ければ末尾へ追加する。並び順は変えず、他の entry・ファイル・ディレクトリは触らない。 +- Machine PATH は `mise-path-ownership.ps1` の担当であり、この script は触らない。 +- 書き込み前に展開前の生値を `%LOCALAPPDATA%\pc-setup\user-path-backup\user-path-.txt` に保存する。registry の値 kind (REG_SZ / REG_EXPAND_SZ) は保持する。 +- `bootstrap.ps1` と `converge.ps1` の両方から呼ばれ、再実行は冪等。`verify.ps1` は `.cargo\bin` 残存と shims entry 欠落を FAIL として報告する。 + ### 宣言済みツールの実行確認 `verify.ps1` は `Get-Command` による**解決**だけでなく、宣言済みツールを**実際に起動**して確認する。存在確認では検出できない破損があるため。 diff --git a/platforms/windows-11/converge.ps1 b/platforms/windows-11/converge.ps1 index 04ffe2b..0f5bb5d 100644 --- a/platforms/windows-11/converge.ps1 +++ b/platforms/windows-11/converge.ps1 @@ -205,6 +205,28 @@ function Invoke-MiseApply { } } +# Converges the per-user PATH (ADR-0021): drops the legacy .cargo\bin rustup +# proxy entry and guarantees the mise shims entry. HKCU only, exact-match +# removal, backup before write — user-path.ps1 is idempotent by design. +function Invoke-UserPath { + if (-not $script:DeployOk) { + Add-Step 'user-path' 'skipped' 'deploy checkout not converged in this run' + return + } + $userPath = Join-Path (Join-Path (Join-Path $DeployDir 'platforms') 'windows-11') 'user-path.ps1' + if (-not (Test-Path -LiteralPath $userPath)) { + Add-Step 'user-path' 'skipped' 'no user-path.ps1 in the deploy checkout' + return + } + & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $userPath -Apply *>&1 | ForEach-Object { Write-Log ([string]$_) } + $code = $LASTEXITCODE + if ($code -eq 0) { + Add-Step 'user-path' 'ok' 'User PATH converged' + } else { + Add-Step 'user-path' 'error' ('user-path.ps1 -Apply exited ' + $code + '; see ' + $script:LogFile) + } +} + # Derived from current state, not from a previous run: dsh is pending when # `npm:@deepseek-ai/dsh` is installed on this machine but the deployed # mise.global.toml does not declare it (it exists only in an unmerged PR; ADR-0016). @@ -531,6 +553,7 @@ function Invoke-Main { Invoke-Step 'deploy-sync' { Sync-Deploy } Invoke-Step 'mise-apply' { Invoke-MiseApply } + Invoke-Step 'user-path' { Invoke-UserPath } Invoke-Step 'dsh-declaration' { Test-DshDeclaration } Invoke-Step 'dotfiles-sync' { Invoke-DotfilesSync } Invoke-Step 'devices-sync' { Sync-Devices } diff --git a/platforms/windows-11/install-rex.ps1 b/platforms/windows-11/install-rex.ps1 new file mode 100644 index 0000000..b9341c5 --- /dev/null +++ b/platforms/windows-11/install-rex.ps1 @@ -0,0 +1,135 @@ +[CmdletBinding()] +param() + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +# Install the Rex Windows binary (https://www.superlogical.com/rex) for the +# current user. Rex has no WinGet package; the preview channel JSON at +# blob.superlogical.com is the official artifact index. The user-scope zip is +# extracted under %LOCALAPPDATA%\Programs\Rex (no admin), the directory is +# added to the user PATH, and `rex server install --user` registers the +# HKCU Run entry so the server starts at sign-in. The Windows Service variant +# needs an elevated shell and is a documented manual step instead. +# See docs/adr/ADR-0026.md. + +$ReleasesUrl = 'https://blob.superlogical.com/api/releases/rex/preview' +$InstallRoot = Join-Path $env:LOCALAPPDATA 'Programs\Rex' + +function Write-StepLocal { + param([Parameter(Mandatory)][string]$Message) + Write-Host "`n==> $Message" +} + +function Find-RexExecutable { + param([Parameter(Mandatory)][string]$Root) + if (-not (Test-Path -LiteralPath $Root)) { return $null } + return Get-ChildItem -LiteralPath $Root -Filter 'rex.exe' -Recurse -File -ErrorAction SilentlyContinue | + Select-Object -First 1 -ExpandProperty FullName +} + +function Get-RexVersion { + param([Parameter(Mandatory)][string]$RexExe) + # `rex version` prints "rex " on the first line; --version is not a flag. + $line = (& $RexExe version 2>$null | Select-Object -First 1) + if ($LASTEXITCODE -eq 0 -and $line -match 'rex\s+(\S+)') { return $Matches[1] } + return $null +} + +$architecture = switch ($env:PROCESSOR_ARCHITECTURE) { + 'AMD64' { 'amd64' } + 'ARM64' { 'arm64' } + default { + Write-Warning "Rex Windows install is unsupported on architecture: $env:PROCESSOR_ARCHITECTURE" + return + } +} + +Write-StepLocal "Resolving Rex preview artifacts ($architecture)" +$release = Invoke-RestMethod -Uri $ReleasesUrl -TimeoutSec 30 +$artifact = @($release.artifacts | Where-Object { + $_.os -eq 'windows' -and $_.arch -eq $architecture -and $_.filename -like '*.zip' +}) | Select-Object -First 1 + +if (-not $artifact) { + throw "no windows/$architecture zip artifact in the Rex preview release" +} + +$existingExe = Find-RexExecutable -Root $InstallRoot +$installedVersion = if ($existingExe) { Get-RexVersion -RexExe $existingExe } else { $null } +if ($installedVersion -and $installedVersion -eq $release.version) { + Write-Host "ok Rex $installedVersion already installed ($existingExe)" +} +else { + Write-StepLocal "Installing Rex $($release.version) for $architecture" + $tempDir = Join-Path ([System.IO.Path]::GetTempPath()) "rex-$([guid]::NewGuid())" + New-Item -ItemType Directory -Path $tempDir -Force | Out-Null + try { + $zipPath = Join-Path $tempDir $artifact.filename + Invoke-WebRequest -Uri $artifact.downloadUrl -OutFile $zipPath -TimeoutSec 300 + $hash = (Get-FileHash -LiteralPath $zipPath -Algorithm SHA256).Hash.ToLowerInvariant() + if ($hash -ne $artifact.sha256.ToLowerInvariant()) { + throw "SHA-256 mismatch for $($artifact.filename): expected $($artifact.sha256), got $hash" + } + + $extractDir = Join-Path $tempDir 'extract' + Expand-Archive -LiteralPath $zipPath -DestinationPath $extractDir -Force + + if (Test-Path -LiteralPath $InstallRoot) { + # A running rex.exe locks its directory; stop it first so the + # replace cannot fail halfway and leave a mixed install. + Get-Process -Name 'rex' -ErrorAction SilentlyContinue | + Where-Object { $_.Path -and $_.Path.StartsWith($InstallRoot, [StringComparison]::OrdinalIgnoreCase) } | + Stop-Process -Force -ErrorAction SilentlyContinue + Remove-Item -LiteralPath $InstallRoot -Recurse -Force + } + New-Item -ItemType Directory -Path $InstallRoot -Force | Out-Null + Copy-Item -Path (Join-Path $extractDir '*') -Destination $InstallRoot -Recurse -Force + + $existingExe = Find-RexExecutable -Root $InstallRoot + if (-not $existingExe) { + throw "rex.exe was not found after extracting $($artifact.filename)" + } + + $newVersion = Get-RexVersion -RexExe $existingExe + $reportedVersion = $newVersion + if (-not $reportedVersion) { $reportedVersion = $release.version } + Write-Host "ok Rex $reportedVersion installed -> $existingExe" + } + finally { + Remove-Item -LiteralPath $tempDir -Recurse -Force -ErrorAction SilentlyContinue + } +} + +if (-not $existingExe) { + $existingExe = Find-RexExecutable -Root $InstallRoot +} +if (-not $existingExe) { throw 'rex.exe is missing after install' } +$rexDir = Split-Path -Parent $existingExe + +# Keep the user PATH converged: the install dir must resolve rex.exe in new +# shells. Only append when absent; never reorder or remove existing entries. +$userPath = [Environment]::GetEnvironmentVariable('Path', 'User') +$pathEntries = @($userPath -split ';' | Where-Object { $_ -ne '' }) +if ($pathEntries -notcontains $rexDir) { + [Environment]::SetEnvironmentVariable('Path', (@($pathEntries) + $rexDir) -join ';', 'User') + Write-Host "ok added $rexDir to the user PATH" +} +$env:Path = "$env:Path;$rexDir" + +# HKCU Run registration needs no admin; the elevated Windows Service variant is +# a manual step documented in platforms/windows-11/README.md. During the beta +# the server may still require tester enrollment, so a failure here warns +# instead of failing the whole bootstrap. +try { + & $existingExe server install --user + if ($LASTEXITCODE -ne 0) { + Write-Warning "rex server install --user exited $LASTEXITCODE; the Rex server may require beta enrollment. Run it manually after signing in: rex server install --user" + } + else { + Write-Host 'ok rex server install --user completed' + } +} +catch { + Write-Warning "rex server install --user failed: $($_.Exception.Message). Run it manually after signing in: rex server install --user" +} diff --git a/platforms/windows-11/manual-apps.md b/platforms/windows-11/manual-apps.md index 27c8cce..228e59a 100644 --- a/platforms/windows-11/manual-apps.md +++ b/platforms/windows-11/manual-apps.md @@ -84,3 +84,9 @@ Do not install every optional workload merely to make the machine look "complete Android Studio is declared in root `mise.toml` and installed through the WinGet backend. Android SDK/NDK/JDK versions required by an individual repository should remain project-controlled where possible. Avoid accumulating multiple unrelated global JDK installations. Android Studio's bundled runtime and project-specific requirements should be preferred over an untracked collection of system JDKs. + +## Rex + +Rex has no WinGet package. `platforms/windows-11/install-rex.ps1` installs the preview-channel binary under `%LOCALAPPDATA%\Programs\Rex` without admin rights and registers `rex server install --user` (HKCU Run). During the beta the Windows server requires tester enrollment, so failures are warnings, not bootstrap blockers. + +Manual boundary: the persistent Windows Service (`rex server install`, elevated shell, account password) is not automated. See `platforms/windows-11/README.md` and `docs/adr/ADR-0026.md`. diff --git a/platforms/windows-11/setup-tailscale.ps1 b/platforms/windows-11/setup-tailscale.ps1 index 14556cf..910ae82 100644 --- a/platforms/windows-11/setup-tailscale.ps1 +++ b/platforms/windows-11/setup-tailscale.ps1 @@ -40,6 +40,58 @@ function Invoke-Checked { } } +# `tailscale status --json` emits UTF-8. Windows PowerShell 5.1 on a Japanese +# (or any non-UTF-8) console decodes native output with the OEM code page, so +# the Health strings arrive as mojibake and ConvertFrom-Json fails on +# 'Path 'Health[0]''. Decode as UTF-8 for the duration of the call and restore +# the previous encoding afterwards; a failure to set it must not stop the +# script, because the parse below still fails closed on bad output. +function Invoke-Utf8Native { + param( + [Parameter(Mandatory)][string]$Command, + [Parameter(Mandatory)][string[]]$Arguments + ) + + $previousEncoding = $null + try { + $previousEncoding = [Console]::OutputEncoding + [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 + } + catch { } + + try { + $output = @(& $Command @Arguments 2>$null) + $exitCode = $LASTEXITCODE + } + finally { + if ($null -ne $previousEncoding) { + try { [Console]::OutputEncoding = $previousEncoding } catch { } + } + } + + return [pscustomobject]@{ Output = $output; ExitCode = $exitCode } +} + +# Returns the parsed `tailscale status --json` object, or $null when the state +# cannot be determined. Callers MUST treat $null as "unknown" and fail closed: +# an unparseable status once fell through to the `tailscale up --auth-key` +# path and re-registered a node that was already enrolled. +function Get-TailscaleStatus { + param([Parameter(Mandatory)]$TailscaleCommand) + + $result = Invoke-Utf8Native -Command $TailscaleCommand -Arguments @('status', '--json') + if ($result.ExitCode -ne 0 -or $result.Output.Count -eq 0) { + return $null + } + + try { + return (($result.Output -join [Environment]::NewLine) | ConvertFrom-Json) + } + catch { + return $null + } +} + if ([System.Environment]::OSVersion.Platform -ne [System.PlatformID]::Win32NT) { throw 'This setup targets Windows.' } @@ -107,18 +159,18 @@ if ([string]::IsNullOrWhiteSpace($oauthSecret)) { throw "Required Infisical secret is not injected: $secretName" } -$status = $null -$statusOutput = @(& $tailscale status --json 2>$null) -if ($LASTEXITCODE -eq 0 -and $statusOutput.Count -gt 0) { - try { - $status = ($statusOutput -join [Environment]::NewLine) | ConvertFrom-Json - } - catch { - $status = $null - } +$status = Get-TailscaleStatus -TailscaleCommand $tailscale + +if ($null -eq $status -or $null -eq $status.BackendState) { + # Fail closed: the backend state is unknown, so this script cannot tell a + # fresh machine (NeedsLogin) from an already-enrolled node whose status + # output failed to decode. Re-registering here once replaced a healthy + # node identity; refuse instead and let the operator re-run once the + # status command works. + throw 'tailscale status --json is unavailable or unparseable; refusing to touch node registration (fail closed). Re-run after Tailscale is responsive.' } -if (-not $status -or $status.BackendState -ne 'Running') { +if ($status.BackendState -ne 'Running') { Write-Host 'Registering Windows host with Tailscale' $authKey = "${oauthSecret}?$($config.Tailscale.AuthKeyParameters)" try { @@ -147,9 +199,10 @@ foreach ($mapping in $config.Tailscale.Serve) { ) -Description "Tailscale Serve $($mapping.ListenPort)" } -$serveStatus = @(& $tailscale serve status 2>$null) -join [Environment]::NewLine -if ($LASTEXITCODE -ne 0) { - throw "Tailscale Serve status failed with exit code $LASTEXITCODE" +$serveResult = Invoke-Utf8Native -Command $tailscale -Arguments @('serve', 'status') +$serveStatus = ($serveResult.Output -join [Environment]::NewLine) +if ($serveResult.ExitCode -ne 0) { + throw "Tailscale Serve status failed with exit code $($serveResult.ExitCode)" } foreach ($mapping in $config.Tailscale.Serve) { diff --git a/platforms/windows-11/user-path.ps1 b/platforms/windows-11/user-path.ps1 new file mode 100644 index 0000000..68a949f --- /dev/null +++ b/platforms/windows-11/user-path.ps1 @@ -0,0 +1,172 @@ +# Converges the per-user PATH for the mise-managed Windows baseline. +# +# user-path.ps1 plan: report what would change, change nothing +# user-path.ps1 -Apply write the User PATH (no elevation needed) +# user-path.ps1 -Restore put a saved User PATH back +# +# Why this exists +# ADR-0021 makes mise the single owner of Rust on Windows: rustup's home and +# Cargo home live under the mise data dir, and the legacy +# %USERPROFILE%\.cargo\bin entry must not stay on the registry User PATH — +# on a real machine it sat at the head of User PATH and resolved rustc/cargo +# to the legacy rustup proxies in shells that do not activate mise. mise's +# own shims entry (%LOCALAPPDATA%\mise\shims) is the only mise-sourced entry +# the registry PATH is supposed to carry. +# +# What it changes +# Only the *User* PATH (HKCU), and only by exact expanded-path match: +# - removes every entry that expands to \.cargo\bin +# - appends %LOCALAPPDATA%\mise\shims when it is absent +# Nothing is reordered, no other entry is touched, and no file or +# directory is deleted. Removing the PATH entry leaves the legacy +# directory in place; the proxies simply stop winning resolution. +# +# Safety +# The unexpanded User PATH is saved to +# \user-path-backup\user-path-.txt before any write, +# and -Restore reads exactly that file back. +[CmdletBinding()] +param( + [switch]$Apply, + [string]$Restore, + [string]$StateDir = '' +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +. (Join-Path $PSScriptRoot 'app-detection.ps1') + +$userKeyPath = 'HKCU:\Environment' + +# Legacy Rust proxy home. ADR-0021 keeps the directory itself (inert once +# RUSTUP_HOME/CARGO_HOME point into the mise data dir); only its PATH +# presence is the defect. +$legacyCargoBin = Join-Path $env:USERPROFILE '.cargo\bin' + +$miseShimEntry = '%LOCALAPPDATA%\mise\shims' + +function Split-PathValue { + param([string]$Value) + # Same rule as mise-path-ownership.ps1: empty entries are not meaningful + # and are never introduced. The comma operator keeps an empty result an + # empty array instead of $null. + return , @($Value -split ';' | Where-Object { $_ -and $_.Trim() }) +} + +function Test-LegacyCargoEntry { + param([Parameter(Mandatory)][string]$Entry) + $expanded = [Environment]::ExpandEnvironmentVariables($Entry).Trim().TrimEnd('\') + return ($expanded.Equals($legacyCargoBin.TrimEnd('\'), [StringComparison]::OrdinalIgnoreCase)) +} + +function Test-MiseShimEntry { + param([Parameter(Mandatory)][string]$Entry) + $expanded = [Environment]::ExpandEnvironmentVariables($Entry).Trim().TrimEnd('\') + $expected = [Environment]::ExpandEnvironmentVariables($miseShimEntry).TrimEnd('\') + return ($expanded.Equals($expected, [StringComparison]::OrdinalIgnoreCase)) +} + +if (-not $StateDir) { + $StateDir = Join-Path (Get-PcSetupStateDir) 'user-path-backup' +} + +function Get-UserPathRaw { + $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $false) + try { + if ($key.GetValueNames() -notcontains 'Path') { + # PATH normally exists as REG_EXPAND_SZ; a missing value is + # written back expandable. + return [pscustomobject]@{ Value = ''; Kind = [Microsoft.Win32.RegistryValueKind]::ExpandString } + } + $value = $key.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) + $kind = $key.GetValueKind('Path') + if ($kind -eq [Microsoft.Win32.RegistryValueKind]::Unknown) { + $kind = [Microsoft.Win32.RegistryValueKind]::ExpandString + } + } + finally { $key.Close() } + return [pscustomobject]@{ Value = $value; Kind = $kind } +} + +function Set-UserPathRaw { + param([string]$Value, [Microsoft.Win32.RegistryValueKind]$Kind) + $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true) + try { $key.SetValue('Path', $Value, $Kind) } finally { $key.Close() } +} + +if ($Restore) { + if (-not (Test-Path -LiteralPath $Restore)) { throw "restore file not found: $Restore" } + $saved = (Get-Content -LiteralPath $Restore -Raw).TrimEnd("`r", "`n") + $current = Get-UserPathRaw + New-Item -ItemType Directory -Force -Path $StateDir | Out-Null + $pre = Join-Path $StateDir ("user-path-{0}.txt" -f (Get-Date -Format 'yyyyMMdd-HHmmss')) + Set-Content -LiteralPath $pre -Value $current.Value -Encoding utf8 -NoNewline + Set-UserPathRaw -Value $saved -Kind $current.Kind + Write-Host "restored User PATH from $Restore" + Write-Host "previous value saved to $pre" + exit 0 +} + +$current = Get-UserPathRaw +$entries = Split-PathValue -Value $current.Value +$removals = @($entries | Where-Object { Test-LegacyCargoEntry -Entry $_ }) +$shimPresent = @($entries | Where-Object { Test-MiseShimEntry -Entry $_ }).Count -gt 0 + +Write-Host "User PATH entries: $($entries.Count)" +foreach ($entry in $removals) { + Write-Host (" remove {0} (expands to {1}; legacy rustup proxy home, ADR-0021)" -f $entry, $legacyCargoBin) +} +if ($removals.Count -eq 0) { + Write-Host ' (no legacy .cargo\bin entry)' +} +if ($shimPresent) { + Write-Host " keep $miseShimEntry (already present)" +} +else { + Write-Host " add $miseShimEntry (mise shims; appended, order of existing entries unchanged)" +} + +if (-not $Apply) { + $changes = $removals.Count + $(if ($shimPresent) { 0 } else { 1 }) + if ($changes -eq 0) { + Write-Host 'ok User PATH already converged' + } + else { + Write-Host "plan only; re-run with -Apply to change $changes entr$(if ($changes -eq 1) { 'y' } else { 'ies' })." + } + exit 0 +} + +$kept = @($entries | Where-Object { -not (Test-LegacyCargoEntry -Entry $_) }) +if (-not $shimPresent) { + # A REG_SZ User PATH is never environment-expanded at runtime, so the + # shim entry must be stored pre-expanded there; REG_EXPAND_SZ keeps the + # portable %LOCALAPPDATA% form. + $shimEntry = if ($current.Kind -eq [Microsoft.Win32.RegistryValueKind]::String) { + [Environment]::ExpandEnvironmentVariables($miseShimEntry) + } else { $miseShimEntry } + $kept += $shimEntry +} +$newValue = ($kept -join ';') + +if ($newValue -eq $current.Value) { + Write-Host 'ok User PATH already converged' + exit 0 +} + +New-Item -ItemType Directory -Force -Path $StateDir | Out-Null +$backup = Join-Path $StateDir ("user-path-{0}.txt" -f (Get-Date -Format 'yyyyMMdd-HHmmss')) +Set-Content -LiteralPath $backup -Value $current.Value -Encoding utf8 -NoNewline +Write-Host "backup $backup" +Write-Host "restore pwsh -NoProfile -File $PSCommandPath -Restore `"$backup`"" + +Set-UserPathRaw -Value $newValue -Kind $current.Kind +# Broadcast the change so new processes pick it up; existing shells keep +# their snapshot (same rule as mise-path-ownership.ps1). +[Environment]::SetEnvironmentVariable('PC_SETUP_PATH_TOUCH', '1', 'User') +[Environment]::SetEnvironmentVariable('PC_SETUP_PATH_TOUCH', $null, 'User') + +Write-Host ('applied; removed {0} entr{1}, mise shims {2}. Open a new shell.' -f ` + $removals.Count, $(if ($removals.Count -eq 1) { 'y' } else { 'ies' }), ` + $(if ($shimPresent) { 'already present' } else { 'added' })) diff --git a/platforms/windows-11/verify.ps1 b/platforms/windows-11/verify.ps1 index c04b647..f152ab9 100644 --- a/platforms/windows-11/verify.ps1 +++ b/platforms/windows-11/verify.ps1 @@ -60,6 +60,36 @@ function Resolve-TailscaleCommand { return $null } +# `tailscale status --json` is UTF-8. Windows PowerShell 5.1 decodes native +# output with the console OEM code page, so on a Japanese Windows the Health +# strings arrive as mojibake and ConvertFrom-Json fails even though the JSON +# is valid. Decode as UTF-8 for the call and restore the previous encoding. +function Invoke-NativeUtf8 { + param( + [Parameter(Mandatory)]$Command, + [Parameter(Mandatory)][string[]]$Arguments + ) + + $previousEncoding = $null + try { + $previousEncoding = [Console]::OutputEncoding + [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 + } + catch { } + + try { + $output = @(& $Command @Arguments 2>$null) + $exitCode = $LASTEXITCODE + } + finally { + if ($null -ne $previousEncoding) { + try { [Console]::OutputEncoding = $previousEncoding } catch { } + } + } + + return [pscustomobject]@{ Output = $output; ExitCode = $exitCode } +} + if ([System.Environment]::OSVersion.Platform -ne [System.PlatformID]::Win32NT) { throw 'This verification targets Windows.' } Write-Host "pc-setup Windows 11 verification`n" @@ -276,14 +306,42 @@ else { Write-Host "`nPowerShell (WinGet-managed Microsoft.PowerShell is canonical)" $pwshCommand = Get-Command pwsh -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 $pwshX64 = Join-Path $env:ProgramFiles 'PowerShell\7\pwsh.exe' -if (-not (Test-Path -LiteralPath $pwshX64)) { - Write-Fail "PowerShell 7 x64 not found at $pwshX64" +# winget:Microsoft.PowerShell installs either the MSI (Program Files) or the +# MSIX package; both are the same canonical PowerShell 7. The MSIX resolves +# through the per-user app execution alias +# (%LOCALAPPDATA%\Microsoft\WindowsApps\Microsoft.PowerShell__x64__\pwsh.exe) +# and its InstallLocation under WindowsApps, so accept every shape the package +# can produce instead of requiring the MSI path only. +$pwshCanonicalPaths = New-Object System.Collections.Generic.List[string] +if (Test-Path -LiteralPath $pwshX64) { $pwshCanonicalPaths.Add($pwshX64) } +foreach ($pwshPackage in @(Get-AppxPackage -Name 'Microsoft.PowerShell' -ErrorAction SilentlyContinue)) { + if ($pwshPackage.InstallLocation) { + $candidate = Join-Path $pwshPackage.InstallLocation 'pwsh.exe' + if (Test-Path -LiteralPath $candidate) { $pwshCanonicalPaths.Add($candidate) } + } } -elseif ($pwshCommand -and ($pwshCommand.Source -ne $pwshX64)) { - Write-WarnLocal "pwsh resolves to $($pwshCommand.Source), not the x64 install. Nothing was removed; run platforms/windows-11/powershell-path.ps1 (plan) and -Apply from an elevated shell, or call $pwshX64 explicitly." +$pwshResolved = if ($pwshCommand) { [string]$pwshCommand.Source } else { $null } +$pwshIsCanonical = $false +if ($pwshResolved) { + foreach ($candidate in $pwshCanonicalPaths) { + if ($pwshResolved.Equals($candidate, [StringComparison]::OrdinalIgnoreCase)) { $pwshIsCanonical = $true; break } + } + if (-not $pwshIsCanonical -and $pwshResolved -match '\\Microsoft\.PowerShell_[^\\]+\\pwsh\.exe$') { + # Per-user execution-alias path of an installed MSIX package. + $pwshIsCanonical = $true + } +} +if ($pwshCanonicalPaths.Count -eq 0) { + Write-Fail "PowerShell 7 not found (neither the MSI at $pwshX64 nor a Microsoft.PowerShell MSIX package)" +} +elseif (-not $pwshResolved) { + Write-Fail 'pwsh does not resolve on PATH' +} +elseif (-not $pwshIsCanonical) { + Write-WarnLocal "pwsh resolves to $pwshResolved, not a canonical PowerShell 7 install ($($pwshCanonicalPaths -join ', ')). Nothing was removed; run platforms/windows-11/powershell-path.ps1 (plan) and -Apply from an elevated shell, or call a canonical pwsh.exe explicitly." } else { - Write-Ok "pwsh -> $pwshX64" + Write-Ok "pwsh -> $pwshResolved" } Write-Host "`nRust (mise manages Rust on Windows; rustup runs underneath)" @@ -332,6 +390,37 @@ else { } } +Write-Host "`nUser PATH (ADR-0021: mise shims only, no legacy Rust proxy home)" +# Read the unexpanded registry value so %USERPROFILE% / %LOCALAPPDATA% style +# entries compare correctly; [Environment]::GetEnvironmentVariable('Path','User') +# would already be expanded and could hide a literal-vs-expanded difference. +$userPathKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $false) +try { + $userPathValue = $userPathKey.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) +} +finally { $userPathKey.Close() } +$userPathEntries = @($userPathValue -split ';' | Where-Object { $_ -and $_.Trim() }) +$legacyCargoBin = (Join-Path $env:USERPROFILE '.cargo\bin').TrimEnd('\') +$legacyEntries = @($userPathEntries | Where-Object { + ([Environment]::ExpandEnvironmentVariables($_).Trim().TrimEnd('\')) -ieq $legacyCargoBin +}) +$miseShimExpected = [Environment]::ExpandEnvironmentVariables('%LOCALAPPDATA%\mise\shims').TrimEnd('\') +$shimEntries = @($userPathEntries | Where-Object { + ([Environment]::ExpandEnvironmentVariables($_).Trim().TrimEnd('\')) -ieq $miseShimExpected +}) +if ($legacyEntries.Count -gt 0) { + Write-Fail "User PATH still resolves rustc/cargo through the legacy rustup proxy home: $($legacyEntries -join ', '); run platforms/windows-11/user-path.ps1 -Apply" +} +else { + Write-Ok 'User PATH has no legacy .cargo\bin entry' +} +if ($shimEntries.Count -gt 0) { + Write-Ok "User PATH carries the mise shims entry ($($shimEntries -join ', '))" +} +else { + Write-Fail "User PATH has no mise shims entry ($miseShimExpected); run platforms/windows-11/user-path.ps1 -Apply" +} + Write-Host "`nTailscale / WSL SSH" $tailscaleConfig = Import-PowerShellDataFile -LiteralPath (Join-Path $ScriptDir 'tailscale.psd1') $tailscale = Resolve-TailscaleCommand @@ -342,8 +431,9 @@ else { Write-Ok 'Tailscale command available' $tailscaleVerdict = 'manual' - $statusOutput = @(& $tailscale status --json 2>$null) - if ($LASTEXITCODE -ne 0 -or $statusOutput.Count -eq 0) { + $statusResult = Invoke-NativeUtf8 -Command $tailscale -Arguments @('status', '--json') + $statusOutput = $statusResult.Output + if ($statusResult.ExitCode -ne 0 -or $statusOutput.Count -eq 0) { Write-Fail 'Tailscale status unavailable' } else { @@ -364,8 +454,9 @@ else { } } - $serveStatus = @(& $tailscale serve status 2>$null) -join [Environment]::NewLine - if ($LASTEXITCODE -ne 0) { + $serveResult = Invoke-NativeUtf8 -Command $tailscale -Arguments @('serve', 'status') + $serveStatus = ($serveResult.Output -join [Environment]::NewLine) + if ($serveResult.ExitCode -ne 0) { if ($tailscaleVerdict -eq 'ok') { Write-Fail 'Tailscale Serve status unavailable' } else { Write-WarnLocal 'Tailscale Serve status unavailable (backend is not Running; pending manual step)' } } else { @@ -383,12 +474,41 @@ else { } } +Write-Host "`nRex" +# Rex is in public beta and its Windows server still requires tester +# enrollment, so a missing install is a warning (pending boundary), not a +# failure. When the binary is present, version and server reachability are +# still checked. +$rexExe = Get-Command rex -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 +if (-not $rexExe) { + $rexExePath = Join-Path $env:LOCALAPPDATA 'Programs\Rex' + $rexExe = Get-ChildItem -LiteralPath $rexExePath -Filter 'rex.exe' -Recurse -File -ErrorAction SilentlyContinue | + Select-Object -First 1 + if ($rexExe) { $rexExe = $rexExe.FullName } +} +if (-not $rexExe) { + Write-WarnLocal 'rex not installed (beta enrollment may be required); run platforms/windows-11/install-rex.ps1' +} +else { + $rexPath = if ($rexExe -is [string]) { $rexExe } else { $rexExe.Source } + $versionOutput = @(& $rexPath version 2>$null | Select-Object -First 1) + if ($LASTEXITCODE -eq 0 -and $versionOutput) { Write-Ok "rex -> $($versionOutput -join ' ')" } else { Write-WarnLocal "rex version check failed for $rexPath" } + + $statusOutput = @(& $rexPath server status --autostart=false 2>$null) + if ($LASTEXITCODE -eq 0) { + Write-Ok 'Rex server is reachable' + } + else { + Write-WarnLocal 'Rex server is not reachable; the Windows server may require beta enrollment. Run `rex server install --user` after signing in.' + } +} + Write-Host "`nCommand capabilities" foreach ($commandName in @( 'git','gh','infisical','pwsh','code','node','python','pnpm','bun','rustc','cargo', 'rg','fd','fzf','jq','bat','gdu','shellcheck','nvim', 'claude','codex','opencode','devin','wt','herdr', - 'gcloud','aws','supabase','npkill','ocr','cargo-clean-all','dotnet' + 'npkill','ocr','cargo-clean-all','dotnet' )) { Test-CommandPresent -Name $commandName } Write-Host "`nmise-managed commands resolve to mise (no shadowing copy earlier in PATH)" @@ -608,7 +728,6 @@ foreach ($n in $Names) { @{ key = 'npm:devin'; command = 'devin'; args = @('--version') }, @{ key = 'npm:@earendil-works/pi-coding-agent'; command = 'pi'; args = @('--version') }, @{ key = 'npm:@deepseek-ai/dsh'; command = 'dsh'; args = @('--version') }, - @{ key = 'npm:playwright'; command = 'playwright'; args = @('--version') }, @{ key = 'npm:npkill'; command = 'npkill'; args = @('--version') }, @{ key = 'worktrunk'; command = 'wt'; args = @('--version') }, @{ key = 'oh-my-pi'; command = 'omp'; args = @('--version') }, diff --git a/scripts/apply-platform.sh b/scripts/apply-platform.sh index 86c0fdf..ddd67c3 100755 --- a/scripts/apply-platform.sh +++ b/scripts/apply-platform.sh @@ -8,8 +8,10 @@ case "$(uname -s)" in bash "$repo_root/platforms/macos/install-keyboard.sh" bash "$repo_root/platforms/macos/kanata/install-kanata.sh" bash "$repo_root/platforms/macos/containers/install.sh" + bash "$repo_root/platforms/macos/install-rex.sh" ;; Linux) + bash "$repo_root/platforms/ubuntu-wsl/install-rex.sh" ;; *) ;; diff --git a/scripts/ci.sh b/scripts/ci.sh index e196f8c..a09a94a 100755 --- a/scripts/ci.sh +++ b/scripts/ci.sh @@ -45,6 +45,36 @@ for path in (Path("mise.toml"), Path("mise.global.toml")): tomllib.load(fh) PY +printf 'Checking CLI ownership scope contract...\n' +python3 - <<'PY' +import tomllib +from pathlib import Path + +with Path("mise.global.toml").open("rb") as fh: + global_config = tomllib.load(fh) +with Path("mise.global.lock").open("rb") as fh: + global_lock = tomllib.load(fh) +with Path("mise.toml").open("rb") as fh: + bootstrap = tomllib.load(fh) + +project_or_optional = {"aws-cli", "gcloud", "supabase", "npm:playwright"} +for label, tools in ( + ("mise.global.toml", global_config.get("tools", {})), + ("mise.global.lock", global_lock.get("tools", {})), +): + unwanted = project_or_optional.intersection(tools) + if unwanted: + raise SystemExit(f"{label} contains project/optional CLI: {sorted(unwanted)}") + +packages = bootstrap.get("bootstrap", {}).get("packages", {}) +for package in ("winget:Google.CloudSDK", "winget:Amazon.AWSCLI"): + if package in packages: + raise SystemExit(f"optional cloud CLI is a mandatory host package: {package}") + +if Path(".mise/locks/mise.global/npm-playwright").exists(): + raise SystemExit("orphaned global Playwright dependency sidecar") +PY + printf 'Checking machine-wide mise package scope...\n' python3 - <<'PY' import tomllib