The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(install): make both installers survive their real invocation paths
ethernet1038f8479cae
diff --git a/.github/workflows/bootstrap-installer.yml b/.github/workflows/bootstrap-installer.ymlindex 6598d5b00aa..cb1087431f9 100644--- a/.github/workflows/bootstrap-installer.yml+++ b/.github/workflows/bootstrap-installer.yml@@ -33,10 +33,10 @@ jobs:# checkout can't (git: "shallow update not allowed").fetch-depth: 0- - name: Stage manifest is well-formed protocol v1+ - name: Stage manifest is well-formed protocol v1 (piped, as `curl | bash` runs it)shell: bashrun: |- bash scripts/install.sh --manifest | python3 -c '+ cat scripts/install.sh | bash -s -- --manifest | python3 -c 'import json, sysm = json.load(sys.stdin)assert m["protocol_version"] == 1, mdiff --git a/scripts/install.ps1 b/scripts/install.ps1index e0e4b0b1495..30b5619086e 100644--- a/scripts/install.ps1+++ b/scripts/install.ps1@@ -365,7 +365,14 @@ function Invoke-VerifiedDownload {} catch {$errorType = $_.Exception.GetType().FullNameif ($_.Exception -is [System.Net.WebException]) {+ # Windows PowerShell 5.1: DNS/connect/HTTP failures.if ($_.Exception.Status -in @('TrustFailure', 'SecureChannelFailure')) { throw }+ } elseif ($errorType -eq 'System.Net.Http.HttpRequestException') {+ # pwsh 7: DNS/connect failures. A TLS trust failure arrives+ # with an AuthenticationException inside and is never a routing+ # problem. (Matched by name: 5.1 may not load System.Net.Http.)+ $inner = $_.Exception.InnerException+ if ($inner -and $inner.GetType().FullName -eq 'System.Security.Authentication.AuthenticationException') { throw }} elseif ($errorType -ne 'Microsoft.PowerShell.Commands.HttpResponseException') {throw}@@ -391,7 +398,11 @@ function Invoke-VerifiedDownload {# bytes — no astral-latest, no irm|iex. Returns the uv.exe path.function Get-Uv {$existing = Get-Command uv -ErrorAction SilentlyContinue- if ($existing) { return $existing.Source } # dev shortcut; fetches nothing+ if ($existing) {+ # Developer shortcut: fetches nothing, but only for a new-enough uv.+ if (Test-UvAtLeastPin $existing.Source) { return $existing.Source }+ Log "uv on PATH ($($existing.Source)) is older than the pinned $($script:UvPinVersion) or does not run; staging the pin"+ }$target = "win32-$(Get-WindowsArch)"$pin = $script:UvPinFiles[$target]if (-not $pin) {@@ -419,7 +430,7 @@ function Get-Uv {} finally {Remove-Item -Path $tmpDir -Recurse -Force -ErrorAction SilentlyContinue}- if (-not (& $uvExe --version 2>$null)) { Fail "pinned uv staged but does not run on this host" }+ if (-not (Test-UvAtLeastPin $uvExe)) { Fail "pinned uv staged but does not run on this host" }return $uvExe}@@ -444,8 +455,11 @@ function Get-PinnedGit {$extractDir = Join-Path $tmpDir "unpacked"New-Item -ItemType Directory -Force -Path $extractDir | Out-Null# The pinned artifact is a git-for-windows tar.bz2 (the same one pm- # itself extracts). Windows 10+ ships bsdtar with bzip2 support.- & tar.exe -xf $tarPath -C $extractDir+ # itself extracts). Windows 10+ ships bsdtar with bzip2 support in+ # System32; a GNU tar earlier on PATH (Cygwin/MSYS) reads C:\ as a+ # remote host, so never resolve it from PATH.+ $inboxTar = Join-Path $env:SystemRoot 'System32\tar.exe'+ Invoke-Native { & $inboxTar -xf $tarPath -C $extractDir }if ($LASTEXITCODE) { Fail "failed to extract pinned git archive" }# Layout: Git-<ver>/cmd\git.exe — flatten the single wrapper dir.$inner = @(Get-ChildItem $extractDir)@@ -476,6 +490,29 @@ function Ensure-Git {}function Log([string]$msg) { Write-Host "[hermes] $msg" -ForegroundColor Blue }++# Windows PowerShell 5.1 turns a native command's stderr into an ErrorRecord+# whenever that stream is redirected inside PowerShell (`2>$null`, `2>&1`),+# and under $ErrorActionPreference = "Stop" the record terminates the script+# -- even when the tool exits 0, or the caller meant to tolerate its failure.+# Native calls run through here; the exit code stays in $LASTEXITCODE for the+# caller to judge. (The relaxed preference lives in this function's scope and+# reaches only the block invoked from it.)+function Invoke-Native([scriptblock]$Command) {+ $ErrorActionPreference = 'Continue'+ & $Command+}++# Does the uv at $Path run, and is it at least the pinned version? The+# bootstrap passes flags an older uv lacks (`python install --no-bin` arrived+# in 0.7), and a broken shim can exist without running.+function Test-UvAtLeastPin([string]$Path) {+ $global:LASTEXITCODE = 0+ $out = Invoke-Native { & $Path --version 2>$null }+ if ($LASTEXITCODE -or -not $out) { return $false }+ $have = ("$out".Trim() -split '\s+')[1] -replace '[^0-9.].*$', ''+ try { return ([version]$have -ge [version]$script:UvPinVersion) } catch { return $false }+}function Fail([string]$msg) {Write-Host "[hermes] $msg" -ForegroundColor Red# `exit` unwinds past the stage dispatcher's try/catch, so a -Json caller@@ -513,41 +550,117 @@ function Stage-Prerequisites {}function Stage-Repository {+ # An interrupted clone from an older installer can leave a .git with no+ # initial commit, where stash/checkout abort ("You do not have the initial+ # commit yet", #40998). Move it aside -- never delete it, it may hold+ # something the user wants -- and clone fresh below.+ if (Test-Path (Join-Path $InstallDir ".git")) {+ Invoke-Native { git -C $InstallDir rev-parse --verify HEAD 2>$null } | Out-Null+ if ($LASTEXITCODE) {+ $broken = "$InstallDir.broken-$(Get-Date -Format 'yyyyMMdd-HHmmss')"+ Log "$InstallDir has no commits (interrupted clone); moving it aside to $broken"+ Move-Item -LiteralPath $InstallDir -Destination $broken+ }+ }if (Test-Path (Join-Path $InstallDir ".git")) {Log "updating $InstallDir"- git -C $InstallDir fetch origin $Branch; if ($LASTEXITCODE) { Fail "git fetch failed" }- git -C $InstallDir checkout $Branch; if ($LASTEXITCODE) { Fail "git checkout failed" }- git -C $InstallDir merge --ff-only "origin/$Branch"+ # An explicit HERMES_REPO_URL names the source for reruns too, not+ # just the first clone.+ if ($env:HERMES_REPO_URL) {+ Invoke-Native { git -C $InstallDir remote set-url origin $RepoUrl }+ if ($LASTEXITCODE) { Fail "cannot point origin at $RepoUrl" }+ }+ Invoke-Native { git -C $InstallDir fetch origin $Branch }; if ($LASTEXITCODE) { Fail "git fetch failed" }+ $stamp = (Get-Date -Format 'yyyyMMdd-HHmmss')+ # Park local work BEFORE switching branches: checkout refuses a dirty+ # tree that conflicts, and the reset below would discard it. Work that+ # cannot be parked stops the install -- never overwrite it.+ if (Invoke-Native { git -C $InstallDir status --porcelain }) {+ # An interrupted update can leave unmerged index entries, where+ # stash aborts ("could not write index"). Dropping only the+ # index-level conflict state keeps the working-tree changes for+ # the stash below (#4735).+ if (Invoke-Native { git -C $InstallDir ls-files --unmerged }) {+ Log "clearing unmerged index entries from a previous conflict"+ Invoke-Native { git -C $InstallDir reset -q }+ if ($LASTEXITCODE) { Fail "cannot clear the unmerged index in $InstallDir" }+ }+ Invoke-Native { git -C $InstallDir stash push --include-untracked -m "hermes-install-autostash-$stamp" }+ if ($LASTEXITCODE) { Fail "could not stash local changes in $InstallDir; commit or move them aside, then rerun" }+ Log "local changes stashed as hermes-install-autostash-$stamp"+ }+ Invoke-Native { git -C $InstallDir checkout $Branch }; if ($LASTEXITCODE) { Fail "git checkout failed" }+ Invoke-Native { git -C $InstallDir merge --ff-only "origin/$Branch" }if ($LASTEXITCODE) {# A release cut off the main line, a force-pushed remote, or the# user's own commits cannot fast-forward. Every stage below reads# files only the new tree has (pm/), so an install left on the old# tree cannot finish -- match the remote the way `hermes update`- # does, after parking the old tip and any local work. Mirrors- # scripts/install.sh; this side kept the old tree and then read a- # pm/ file that only the new one has.- $stamp = (Get-Date -Format 'yyyyMMdd-HHmmss')- $prior = (git -C $InstallDir rev-parse --short HEAD 2>$null)+ # does, after parking the old tip. Mirrors scripts/install.sh.+ $prior = (Invoke-Native { git -C $InstallDir rev-parse --short HEAD 2>$null })if (-not $prior) { $prior = 'unknown' }$rescue = "refs/hermes-install-backup/$stamp-$prior"- if (git -C $InstallDir status --porcelain) {- git -C $InstallDir stash push --include-untracked -m "hermes-install-autostash-$stamp"- if ($LASTEXITCODE) { Log "could not stash local changes; they are overwritten below" }- else { Log "local changes stashed as hermes-install-autostash-$stamp" }- }- git -C $InstallDir update-ref $rescue HEAD 2>$null+ Invoke-Native { git -C $InstallDir update-ref $rescue HEAD 2>$null }if ($LASTEXITCODE) { Log "could not back up the previous HEAD" }else { Log "previous HEAD backed up to $rescue" }- git -C $InstallDir reset --hard "origin/$Branch"; if ($LASTEXITCODE) { Fail "git reset failed" }+ Invoke-Native { git -C $InstallDir reset --hard "origin/$Branch" }; if ($LASTEXITCODE) { Fail "git reset failed" }Log "not fast-forwardable; reset to origin/$Branch"}} else {+ # Moving a clone onto an existing directory would nest it, so a+ # pre-existing destination must be empty (taken over) or we refuse:+ # whatever lives there is not ours. Mirrors scripts/install.sh.+ if (Test-Path -LiteralPath $InstallDir) {+ $item = Get-Item -LiteralPath $InstallDir -Force+ $empty = $item.PSIsContainer -and -not $item.LinkType -and -not (Get-ChildItem -LiteralPath $InstallDir -Force | Select-Object -First 1)+ if (-not $empty) {+ Fail "$InstallDir exists and is not a Hermes git checkout. Move it aside, or install elsewhere with -InstallDir <path>."+ }+ Remove-Item -LiteralPath $InstallDir -Force+ }Log "cloning $RepoUrl ($Branch) into $InstallDir"- New-Item -ItemType Directory -Force -Path (Split-Path $InstallDir) | Out-Null- git clone --branch $Branch $RepoUrl $InstallDir; if ($LASTEXITCODE) { Fail "git clone failed" }+ $parent = Split-Path $InstallDir+ New-Item -ItemType Directory -Force -Path $parent | Out-Null+ # Clone into a sibling staging dir and publish only a complete,+ # materialized checkout: a clone that dies half-way must not leave a+ # .git behind that the next rerun would try to update.+ $staged = Join-Path $parent ".hermes-clone-$PID-$(Get-Random)"+ $tree = Join-Path $staged "tree"+ New-Item -ItemType Directory -Force -Path $staged | Out-Null+ try {+ $cloned = $false+ foreach ($attempt in 1..3) {+ Invoke-Native { git clone --branch $Branch $RepoUrl $tree }+ if (-not $LASTEXITCODE) { $cloned = $true; break }+ Remove-Item -LiteralPath $tree -Recurse -Force -ErrorAction SilentlyContinue+ if ($attempt -lt 3) { Start-Sleep -Seconds ($attempt * 5) }+ }+ if (-not $cloned) {+ # Full history, blobs on demand: -Commit, tags and later branch+ # switches all still resolve.+ Log "direct clone failed; trying deferred blob download"+ Invoke-Native { git clone --filter=blob:none --no-checkout --branch $Branch $RepoUrl $tree }+ if (-not $LASTEXITCODE) {+ foreach ($attempt in 1..2) {+ Invoke-Native { git -C $tree reset --hard HEAD }+ if (-not $LASTEXITCODE) { $cloned = $true; break }+ if ($attempt -lt 2) { Start-Sleep -Seconds 5 }+ }+ }+ }+ if (-not $cloned) { Fail "git clone failed; no checkout published" }+ Move-Item -LiteralPath $tree -Destination $InstallDir+ } finally {+ Remove-Item -LiteralPath $staged -Recurse -Force -ErrorAction SilentlyContinue+ }}if ($Commit) {- git -C $InstallDir checkout $Commit; if ($LASTEXITCODE) { Fail "could not pin commit $Commit" }+ # A pin must come from the branch being installed: the complete marker+ # records both, and a commit off that branch would make the next plain+ # rerun "update" onto a different line.+ Invoke-Native { git -C $InstallDir merge-base --is-ancestor $Commit "origin/$Branch" 2>$null }+ if ($LASTEXITCODE) { Fail "commit $Commit is not on branch $Branch" }+ Invoke-Native { git -C $InstallDir checkout $Commit }; if ($LASTEXITCODE) { Fail "could not pin commit $Commit" }}}@@ -570,9 +683,9 @@ function Get-BootstrapPython {$lock = Get-Content (Join-Path $InstallDir "pm\lock.json") -Raw | ConvertFrom-Json$pyPin = $lock.packages.python$pyVersion = if ($pyPin) { ($pyPin.version -split '\+')[0] -replace '^(\d+\.\d+).*', '$1' } else { '3.14' }- & $uv python install --no-bin $pyVersion | Out-Host+ Invoke-Native { & $uv python install --no-bin --no-registry $pyVersion } | Out-Hostif ($LASTEXITCODE) { Fail "bootstrap Python installation failed" }- $bootPy = (& $uv python find --managed-python --no-project $pyVersion) -join "`n"+ $bootPy = (Invoke-Native { & $uv python find --managed-python --no-project $pyVersion }) -join "`n"if ($LASTEXITCODE -or -not $bootPy) { Fail "bootstrap Python lookup failed" }return $bootPy.Trim()}@@ -583,7 +696,7 @@ function Invoke-BootstrapPm {Push-Location $InstallDirtry {# Finish bootstrap uv before PM replaces or cleans its store entry.- & $bootPy -m pm.cli install+ Invoke-Native { & $bootPy -m pm.cli install }if ($LASTEXITCODE) { Fail "pm install failed" }} finally {Pop-Location@@ -606,7 +719,7 @@ function Invoke-SourceCompletion([bool]$Desktop) {if ($Desktop) { $completionArgs += '--desktop' }Push-Location $InstallDirtry {- & $bootPy @completionArgs+ Invoke-Native { & $bootPy @completionArgs }$code = $LASTEXITCODE} finally {Pop-Location@@ -624,7 +737,7 @@ function Publish-UserCommand {$bootPy = Get-BootstrapPythonPush-Location $InstallDirtry {- & $bootPy -I -X utf8 hermes_cli/_launchers.py $binDir+ Invoke-Native { & $bootPy -I -X utf8 hermes_cli/_launchers.py $binDir }$code = $LASTEXITCODE} finally {Pop-Location@@ -680,7 +793,7 @@ function Invoke-InstalledHermes([string[]]$CommandArgs) {. (Join-Path $InstallDir 'scripts/desktop-update/runtime.ps1')$command = @(Get-HermesRuntimeCommand -InstallRoot $InstallDir)$runtimeArgs = @($command | Select-Object -Skip 1) + $CommandArgs- & $command[0] @runtimeArgs+ Invoke-Native { & $command[0] @runtimeArgs }if ($LASTEXITCODE) { Fail "hermes $($CommandArgs -join ' ') failed (exit $LASTEXITCODE)" }}@@ -720,8 +833,7 @@ function Confirm-DesktopArtifact {if (Test-Path $cand) { $desktopExe = $cand; break }}if (-not $desktopExe) {- Fail "desktop build produced no Hermes.exe under $desktopDir-elease\*-unpacked\"+ Fail "desktop build produced no Hermes.exe under $desktopDir\release\*-unpacked"}Log "Desktop ready: $desktopExe"@@ -732,7 +844,7 @@ elease\*-unpacked\"# Best-effort -- never fail an otherwise-good install over ACL.try {$appDir = Split-Path -Parent $desktopExe- & icacls $appDir /grant "*S-1-15-2-2:(OI)(CI)(RX)" /T /C /Q | Out-Null+ Invoke-Native { & icacls $appDir /grant "*S-1-15-2-2:(OI)(CI)(RX)" /T /C /Q } | Out-Nullif ($LASTEXITCODE -eq 0) {Log "Granted AppContainer read access on $appDir"} else {@@ -749,7 +861,7 @@ elease\*-unpacked\"function Stage-Complete {$commit = $Commit- if (-not $commit) { $commit = git -C $InstallDir rev-parse HEAD 2>$null }+ if (-not $commit) { $commit = Invoke-Native { git -C $InstallDir rev-parse HEAD 2>$null } }if ($commit) {$marker = [ordered]@{schemaVersion = 1@@ -814,7 +926,7 @@ function New-DesktopShortcuts {# the old Electron icon until the user manually refreshes / reboots.# Best-effort and silent -- never fail the install over a cosmetic cache.try {- & ie4uinit.exe -show 2>$null+ Invoke-Native { & ie4uinit.exe -show 2>$null }} catch {# ie4uinit may be absent/renamed on some SKUs -- ignore.}@@ -850,6 +962,10 @@ if ($script:IsDotSourced) {# switch is honored, so every contract below sees long-form paths.Initialize-ResolvedPaths+# Keep uv from discovering uv.toml / pyproject.toml config from whatever+# directory or user profile the installer runs under (mirrors install.sh).+$env:UV_NO_CONFIG = "1"+if ($ProtocolVersion) { Write-Output 1; exit 0 }if ($ShowResolvedPaths) {diff --git a/scripts/install.sh b/scripts/install.shindex edceb2541cf..9c9e18cf51f 100755--- a/scripts/install.sh+++ b/scripts/install.sh@@ -109,18 +109,40 @@ uv_bootstrap_target() {esac}+# version_at_least HAVE WANT: dotted numeric comparison; a pre-release or+# build suffix on a component is ignored ("0.12.3-rc1" reads as 0.12.3).+version_at_least() {+ local have="$1" want="$2" h w+ while [ -n "$want" ]; do+ h="${have%%.*}"; h="${h%%[!0-9]*}"+ w="${want%%.*}"; w="${w%%[!0-9]*}"+ [ "${h:-0}" -gt "${w:-0}" ] && return 0+ [ "${h:-0}" -lt "${w:-0}" ] && return 1+ case "$have" in *.*) have="${have#*.}" ;; *) have="" ;; esac+ case "$want" in *.*) want="${want#*.}" ;; *) want="" ;; esac+ done+ return 0+}+# Provision uv for this host from the pinned pm/lock.json artifact. Stages# the EXACT artifact pm itself uses into the same store slot-# (~/.hermes/tools/uv-<version>-<target>/), sha256-verified, so the byte-# authority is pm/lock.json - no astral-latest, no curl|sh.+# (<store>/uv-<version>-<target>/, the store pm's store_root() resolves),+# sha256-verified, so the byte authority is pm/lock.json - no astral-latest,+# no curl|sh.UV_CMD=""ensure_uv() {[ -n "$UV_CMD" ] && return 0- if command -v uv >/dev/null 2>&1; then- # Developer shortcut: an existing uv on PATH is fine to use; this- # branch fetches nothing.- UV_CMD="uv"- return 0+ local _path_uv _path_version+ if _path_uv="$(command -v uv 2>/dev/null)"; then+ # Developer shortcut: a uv on PATH fetches nothing, but only one at+ # least as new as the pin -- the bootstrap passes flags older uv+ # lacks (`python install --no-bin` arrived in 0.7).+ _path_version="$("$_path_uv" --version 2>/dev/null | awk '{print $2}')"+ if [ -n "$_path_version" ] && version_at_least "$_path_version" "$UV_PIN_VERSION"; then+ UV_CMD="$_path_uv"+ return 0+ fi+ log "uv on PATH (${_path_version:-does not run}) is older than the pinned $UV_PIN_VERSION; staging the pin"filocal _targetif ! _target="$(uv_bootstrap_target)"; then@@ -129,7 +151,7 @@ ensure_uv() {if ! uv_bootstrap_pin "$_target"; thenfail "no pinned uv artifact for $_target; install uv manually: https://docs.astral.sh/uv/"fi- local _store="${HERMES_RUNTIME_DIR:-$HOME/.hermes/tools}"+ local _store="${HERMES_RUNTIME_DIR:-$HERMES_HOME/tools}"local _entry="$_store/uv-$UV_PIN_VERSION-$_target"UV_CMD="$_entry/uv"if [ ! -x "$UV_CMD" ]; then@@ -291,25 +313,51 @@ stage_prerequisites() {}stage_repository() {+ # An interrupted clone from an older installer can leave a .git with no+ # initial commit, where stash/checkout abort ("You do not have the+ # initial commit yet", #40998). Move it aside -- never delete it, it may+ # hold something the user wants -- and clone fresh below.+ if [ -d "$INSTALL_DIR/.git" ] && ! git -C "$INSTALL_DIR" rev-parse --verify HEAD >/dev/null 2>&1; then+ local broken+ broken="${INSTALL_DIR}.broken-$(date -u +%Y%m%d-%H%M%S)"+ log "$INSTALL_DIR has no commits (interrupted clone); moving it aside to $broken"+ mv "$INSTALL_DIR" "$broken" || fail "cannot move $INSTALL_DIR aside"+ fiif [ -d "$INSTALL_DIR/.git" ]; thenlog "updating $INSTALL_DIR"+ # An explicit HERMES_REPO_URL names the source for reruns too, not+ # just the first clone.+ if [ -n "${HERMES_REPO_URL:-}" ]; then+ git -C "$INSTALL_DIR" remote set-url origin "$REPO_URL" || fail "cannot point origin at $REPO_URL"+ figit -C "$INSTALL_DIR" fetch origin "$BRANCH" || fail "git fetch failed"+ local stamp prior rescue+ stamp="$(date -u +%Y%m%d-%H%M%S)"+ # Park local work BEFORE switching branches: checkout refuses a dirty+ # tree that conflicts, and the reset below would discard it. Work+ # that cannot be parked stops the install -- never overwrite it.+ if [ -n "$(git -C "$INSTALL_DIR" status --porcelain)" ]; then+ # An interrupted update can leave unmerged index entries, where+ # stash aborts ("could not write index"). Dropping only the+ # index-level conflict state keeps the working-tree changes for+ # the stash below (#4735).+ if [ -n "$(git -C "$INSTALL_DIR" ls-files --unmerged)" ]; then+ log "clearing unmerged index entries from a previous conflict"+ git -C "$INSTALL_DIR" reset -q || fail "cannot clear the unmerged index in $INSTALL_DIR"+ fi+ git -C "$INSTALL_DIR" stash push --include-untracked -m "hermes-install-autostash-$stamp" \+ || fail "could not stash local changes in $INSTALL_DIR; commit or move them aside, then rerun"+ log "local changes stashed as hermes-install-autostash-$stamp"+ figit -C "$INSTALL_DIR" checkout "$BRANCH" || fail "git checkout failed"if ! git -C "$INSTALL_DIR" merge --ff-only "origin/$BRANCH"; then# A release cut off the main line, a force-pushed remote, or the# user's own commits cannot fast-forward. Every stage below reads# files only the new tree has (pm/), so an install left on the old# tree cannot finish -- match the remote the way `hermes update`- # does, after parking the old tip and any local work.- local stamp prior rescue- stamp="$(date -u +%Y%m%d-%H%M%S)"+ # does, after parking the old tip.prior="$(git -C "$INSTALL_DIR" rev-parse --short HEAD 2>/dev/null || echo unknown)"rescue="refs/hermes-install-backup/$stamp-$prior"- if [ -n "$(git -C "$INSTALL_DIR" status --porcelain)" ]; then- git -C "$INSTALL_DIR" stash push --include-untracked -m "hermes-install-autostash-$stamp" \- && log "local changes stashed as hermes-install-autostash-$stamp" \- || log "could not stash local changes; they are overwritten below"- figit -C "$INSTALL_DIR" update-ref "$rescue" HEAD 2>/dev/null \&& log "previous HEAD backed up to $rescue" \|| log "could not back up the previous HEAD"@@ -340,8 +388,11 @@ stage_repository() {[ "$attempt" = 3 ] || sleep "$((attempt * 5))"doneif [ "$cloned" = false ]; then+ # Full history, blobs on demand: --commit, tags and later branch+ # switches all still resolve (a shallow single-branch clone+ # could not check out anything but the tip).log "direct clone failed; trying deferred blob download"- if git clone --depth 1 --single-branch --filter=blob:none --no-checkout \+ if git clone --filter=blob:none --no-checkout \--branch "$BRANCH" "$REPO_URL" "$staged/tree"; thenfor attempt in 1 2; doif git -C "$staged/tree" reset --hard HEAD; then@@ -363,6 +414,11 @@ stage_repository() {rmdir "$staged"fiif [ -n "$INSTALL_COMMIT" ]; then+ # A pin must come from the branch being installed: the complete+ # marker records both, and a commit off that branch would make the+ # next plain rerun "update" onto a different line.+ git -C "$INSTALL_DIR" merge-base --is-ancestor "$INSTALL_COMMIT" "origin/$BRANCH" 2>/dev/null \+ || fail "commit $INSTALL_COMMIT is not on branch $BRANCH"git -C "$INSTALL_DIR" checkout "$INSTALL_COMMIT" || fail "could not pin commit $INSTALL_COMMIT"fi}@@ -464,14 +520,27 @@ stage_config() {log "config prepared in $HERMES_HOME"}+# Interactive stages read the terminal, not stdin: under `curl | bash` stdin+# IS the script. Probe by opening /dev/tty -- a Docker build has the device+# node in its mount namespace but opening it fails (ENXIO).+has_terminal() { (: </dev/tty) 2>/dev/null; }+stage_setup() {if [ "$NON_INTERACTIVE" = true ]; then return 0; fi- "$INSTALL_DIR/.hermes/bin/hermes" setup || fail "setup failed"+ if ! has_terminal; then+ log "setup skipped (no terminal); run 'hermes setup' after install"+ return 0+ fi+ "$INSTALL_DIR/.hermes/bin/hermes" setup </dev/tty || fail "setup failed"}stage_gateway() {if [ "$NON_INTERACTIVE" = true ]; then return 0; fi- "$INSTALL_DIR/.hermes/bin/hermes" gateway install || fail "gateway installation failed"+ if ! has_terminal; then+ log "gateway setup skipped (no terminal); run 'hermes gateway install' after install"+ return 0+ fi+ "$INSTALL_DIR/.hermes/bin/hermes" gateway install </dev/tty || fail "gateway installation failed"}stage_complete() {@@ -515,8 +584,9 @@ run_stage() (# Main. Guarded so the script can be SOURCED for its functions (the# installer-test harness sources it with --manifest, which must define-# the functions and stop before main).-if [ "${BASH_SOURCE[0]}" = "$0" ]; then+# the functions and stop before main). Under `curl | bash` BASH_SOURCE is+# empty, and `set -u` would abort on the bare expansion.+if [ "${BASH_SOURCE[0]:-$0}" = "$0" ]; thenif [ "$WANT_MANIFEST" = true ]; thenemit_manifestexit 0diff --git a/tests/scripts/install/test_install_lockfile_churn.py b/tests/scripts/install/test_install_lockfile_churn.pydeleted file mode 100644index 5af3fe8d1f2..00000000000--- a/tests/scripts/install/test_install_lockfile_churn.py+++ /dev/null@@ -1,120 +0,0 @@-"""Regression: installer update should discard pure npm lockfile churn.--Desktop/bootstrap installs update an existing managed checkout in place. Local-build steps often rewrite tracked ``package-lock.json`` without touching the-matching ``package.json``; treating that churn as a real local edit forces an-autostash and can abort the repository stage before the desktop comes back up.--The installer should discard that generated churn before its stash/checkout-logic, while still preserving intentional package edits where ``package.json``-and ``package-lock.json`` changed together.-"""--from __future__ import annotations--import re-import shutil-import subprocess-from pathlib import Path--import pytest--REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent-INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"--pytestmark = pytest.mark.skipif(- shutil.which("git") is None or shutil.which("bash") is None,- reason="needs git and bash",-)--def _git(cwd: Path, *args: str, check: bool = True) -> subprocess.CompletedProcess:- return subprocess.run(- ["git", "-c", "user.email=t@t", "-c", "user.name=t", *args],- cwd=cwd,- check=check,- capture_output=True,- text=True,- )--def _extract_install_sh_function(name: str) -> str:- text = INSTALL_SH.read_text()- match = re.search(rf"{name}\(\) \{{.*?\n\}}", text, re.DOTALL)- assert match is not None, f"{name}() not found in install.sh"- return match.group(0)--def _extract_install_sh_autostash_block() -> str:- text = INSTALL_SH.read_text()- match = re.search(- r'local autostash_ref="".*?\n fi\n',- text,- re.DOTALL,- )- assert match is not None, "autostash block not found in install.sh"- return match.group(0)-[email protected]_system_guard_bypass-def test_install_sh_discards_runtime_lockfile_churn_before_stash(- tmp_path: Path,-) -> None:- repo = tmp_path / "hermes-agent"- repo.mkdir()- _git(repo, "init")- (repo / "package.json").write_text('{"dependencies":{"a":"1"}}\n')- (repo / "package-lock.json").write_text('{"lock":"old"}\n')- _git(repo, "add", "package.json", "package-lock.json")- _git(repo, "commit", "-m", "init")-- (repo / "package-lock.json").write_text('{"lock":"runtime-churn"}\n')-- script = (- "set -e\n"- 'log_info() { echo "INFO: $*"; }\n'- 'INSTALL_DIR="$PWD"\n'- f"{_extract_install_sh_function('discard_update_lockfile_churn')}\n"- "run() {\n"- f"{_extract_install_sh_autostash_block()}"- "}\n"- "run\n"- )- res = subprocess.run(- ["bash", "-c", script], cwd=repo, capture_output=True, text=True- )-- assert res.returncode == 0, res.stderr- assert "Discarded npm lockfile churn (1 file(s))" in res.stdout- assert _git(repo, "stash", "list").stdout.strip() == ""- assert (repo / "package-lock.json").read_text() == '{"lock":"old"}\n'-[email protected]_system_guard_bypass-def test_install_sh_keeps_root_lockfile_for_dirty_workspace_manifest(- tmp_path: Path,-) -> None:- """The root lockfile spans the npm workspace graph: a dirty workspace manifest- (apps/desktop/package.json) protects it, a manifest outside the graph does not (#112378)."""- repo = tmp_path / "hermes-agent"- (repo / "apps" / "desktop").mkdir(parents=True)- (repo / "vendor" / "foo").mkdir(parents=True)- _git(repo, "init")- (repo / "package.json").write_text('{"workspaces": ["apps/*"]}\n')- (repo / "package-lock.json").write_text('{"lock":"old"}\n')- (repo / "apps" / "desktop" / "package.json").write_text("{}\n")- (repo / "vendor" / "foo" / "package.json").write_text("{}\n")- _git(repo, "add", ".")- _git(repo, "commit", "-m", "init")- script = (- 'log_info() { echo "INFO: $*"; }\n'- 'INSTALL_DIR="$PWD"\n'- f"{_extract_install_sh_function('discard_update_lockfile_churn')}\n"- 'discard_update_lockfile_churn "$PWD"\n'- )-- (repo / "apps" / "desktop" / "package.json").write_text('{"dependencies":{"electron":"41"}}\n')- (repo / "package-lock.json").write_text('{"lock":"workspace-bump"}\n')- subprocess.run(["bash", "-c", script], cwd=repo, check=True, capture_output=True)- assert (repo / "package-lock.json").read_text() == '{"lock":"workspace-bump"}\n'-- _git(repo, "checkout", "--", ".")- (repo / "vendor" / "foo" / "package.json").write_text('{"dependencies":{"x":"1"}}\n')- (repo / "package-lock.json").write_text('{"lock":"churn"}\n')- subprocess.run(["bash", "-c", script], cwd=repo, check=True, capture_output=True)- assert (repo / "package-lock.json").read_text() == '{"lock":"old"}\n'diff --git a/tests/scripts/install/test_install_no_initial_commit.py b/tests/scripts/install/test_install_no_initial_commit.pydeleted file mode 100644index 2ac78ee8180..00000000000--- a/tests/scripts/install/test_install_no_initial_commit.py+++ /dev/null@@ -1,107 +0,0 @@-"""Regression for #40998: installer fails on an interrupted prior clone.--A previous clone that died before its first commit leaves ``$INSTALL_DIR/.git``-present but with no resolvable ``HEAD``. ``git rev-parse --is-inside-work-tree``-and ``git status`` both still succeed there, so the installer treated it as a-valid checkout and tried to *update* it -- but ``git stash``/``git checkout``-abort with "You do not have the initial commit yet", failing the install at the-"Cloning Hermes repository" stage.--Both installers must instead treat a commit-less checkout as broken and-re-clone fresh.-"""--from __future__ import annotations--import re-import shlex-import shutil-import subprocess-from pathlib import Path--import pytest--REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent-INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"--pytestmark = pytest.mark.skipif(- shutil.which("git") is None or shutil.which("bash") is None,- reason="needs git and bash",-)--def _git(cwd: Path, *args: str) -> None:- subprocess.run(- ["git", "-c", "user.email=t@t", "-c", "user.name=t", *args],- cwd=cwd,- check=True,- capture_output=True,- )--def _extract_no_commit_guard() -> str:- """Pull the clone_repo() guard that drops a commit-less checkout."""- text = INSTALL_SH.read_text()- m = re.search(- r'if \[ -d "\$INSTALL_DIR/\.git" \] && ! git -C "\$INSTALL_DIR" '- r"rev-parse --verify HEAD.*?\n fi",- text,- re.DOTALL,- )- assert m is not None, "no-commit guard not found in install.sh clone_repo()"- return m.group(0)--def _run_guard(install_dir: Path) -> None:- block = _extract_no_commit_guard()- script = (- "log_warn() { echo \"WARN: $*\"; }\n"- f"INSTALL_DIR={shlex.quote(str(install_dir))}\n"- f"{block}\n"- )- res = subprocess.run(["bash", "-c", script], capture_output=True, text=True)- assert res.returncode == 0, res.stderr--def test_install_sh_guard_moves_commitless_checkout_aside(tmp_path: Path) -> None:- install_dir = tmp_path / "hermes-agent"- install_dir.mkdir()- _git(install_dir, "init")- (install_dir / "leftover.txt").write_text("partial download") # untracked-- # Sanity: this is exactly the state that breaks `git stash`.- head = subprocess.run(- ["git", "-C", str(install_dir), "rev-parse", "--verify", "HEAD"],- capture_output=True,- )- assert head.returncode != 0-- _run_guard(install_dir)- # The original path is cleared so a fresh clone can proceed, but the- # content is preserved in a backup (never deleted -- review feedback).- assert not install_dir.exists(), "commit-less checkout should be moved aside"- backups = list(install_dir.parent.glob(install_dir.name + ".broken-*"))- assert len(backups) == 1, "broken checkout should be moved to one backup dir"- assert (backups[0] / "leftover.txt").read_text() == "partial download"--def test_install_sh_guard_keeps_repo_with_commits(tmp_path: Path) -> None:- install_dir = tmp_path / "hermes-agent"- install_dir.mkdir()- _git(install_dir, "init")- (install_dir / "f.txt").write_text("real content")- _git(install_dir, "add", "f.txt")- _git(install_dir, "commit", "-m", "init")-- _run_guard(install_dir)- assert install_dir.exists()- assert (install_dir / "f.txt").exists(), "a real checkout must be left intact"- assert not list(install_dir.parent.glob(install_dir.name + ".broken-*")), (- "a healthy checkout must not be moved aside"- )--def test_install_sh_guard_ignores_non_repo_dir(tmp_path: Path) -> None:- install_dir = tmp_path / "hermes-agent"- install_dir.mkdir()- (install_dir / "f.txt").write_text("not a repo")-- _run_guard(install_dir)- # No .git → not our concern; the existing "not a git repository" branch- # still handles it. The guard must leave it untouched.- assert install_dir.exists()- assert (install_dir / "f.txt").exists()diff --git a/tests/scripts/install/test_install_ps1_native_calls.py b/tests/scripts/install/test_install_ps1_native_calls.pynew file mode 100644index 00000000000..92f35617b80--- /dev/null+++ b/tests/scripts/install/test_install_ps1_native_calls.py@@ -0,0 +1,91 @@+"""install.ps1 native calls survive Windows PowerShell 5.1, and reruns keep local work.++Windows PowerShell 5.1 turns a native command's redirected stderr into an+ErrorRecord that terminates a script running under+``$ErrorActionPreference = "Stop"``. These run the real installer under+``powershell.exe`` (5.1) -- dot-sourced for its helpers, or as the real+``-Stage repository -Json`` entry against local git repositories.+"""+import json+import os+from pathlib import Path+import shutil+import subprocess++import pytest++pytestmark = pytest.mark.platforms("windows")+INSTALLER = Path(__file__).resolve().parents[3] / "scripts" / "install.ps1"+++def _powershell() -> str:+ powershell = shutil.which("powershell")+ assert powershell, "Windows PowerShell 5.1 is part of every supported Windows"+ return powershell+++def _dot_sourced(body: str) -> subprocess.CompletedProcess:+ script = f'$ErrorActionPreference = "Stop"; . "{INSTALLER}"; {body}'+ return subprocess.run([_powershell(), "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", script],+ capture_output=True, text=True, timeout=120)+++def test_native_stderr_under_stop_leaves_the_exit_code_to_the_caller():+ result = _dot_sourced('Invoke-Native { cmd /c "echo soft-failure 1>&2 & exit 3" 2>$null }; '+ '"exit=$LASTEXITCODE preference=$ErrorActionPreference"')+ assert result.returncode == 0, result.stdout + result.stderr+ assert "exit=3 preference=Stop" in result.stdout+++def test_path_uv_must_run_and_meet_the_pin(tmp_path):+ for name, body in {"old": "@echo uv 0.6.17", "new": "@echo uv 99.0.0 (abc 2099-01-01)",+ "broken": "@echo boom 1>&2 & exit /b 1"}.items():+ (tmp_path / f"{name}.cmd").write_text(body + "\r\n")+ checks = "; ".join(f'"{n}=$(Test-UvAtLeastPin \'{tmp_path / (n + ".cmd")}\')"' for n in ("old", "new", "broken"))+ result = _dot_sourced(checks)+ assert result.returncode == 0, result.stdout + result.stderr+ assert result.stdout.split() == ["old=False", "new=True", "broken=False"]+++def _git(repo: Path, *args: str) -> str:+ return subprocess.run(["git", "-C", str(repo), "-c", "user.email=t@t", "-c", "user.name=t", *args],+ check=True, capture_output=True, text=True).stdout.strip()+++def _stage(origin: Path, home: Path, *extra: str) -> tuple[subprocess.CompletedProcess, dict]:+ env = dict(os.environ, HERMES_REPO_URL=str(origin), HERMES_HOME=str(home))+ result = subprocess.run([_powershell(), "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(INSTALLER),+ "-Stage", "repository", "-Json", *extra],+ env=env, capture_output=True, text=True, timeout=180)+ frames = [json.loads(line) for line in result.stdout.splitlines() if line.startswith("{")]+ assert len(frames) == 1, result.stdout + result.stderr+ return result, frames[0]+++def test_rerun_parks_local_work_and_pins_only_branch_commits(tmp_path):+ origin = tmp_path / "origin"+ origin.mkdir()+ _git(origin, "init", "-q", "-b", "main")+ (origin / "README").write_text("one")+ _git(origin, "add", "README")+ _git(origin, "commit", "-qm", "one")+ home = tmp_path / "home"+ install = home / "hermes-agent"+ assert _stage(origin, home)[1]["ok"] is True+ (install / "README").write_text("local edit")+ (origin / "README").write_text("two")+ _git(origin, "commit", "-qam", "two")+ _git(origin, "checkout", "-qb", "side")+ (origin / "README").write_text("side")+ _git(origin, "commit", "-qam", "side")+ off_branch = _git(origin, "rev-parse", "HEAD")+ _git(origin, "checkout", "-q", "main")++ result, frame = _stage(origin, home)+ assert frame["ok"] is True, result.stdout + result.stderr+ assert (install / "README").read_text() == "two"+ assert "local edit" in _git(install, "stash", "show", "-p", "stash@{0}")++ result, frame = _stage(origin, home, "-Commit", off_branch)+ assert frame["ok"] is False+ assert "is not on branch main" in frame["reason"]diff --git a/tests/scripts/install/test_install_sh_browser_install.py b/tests/scripts/install/test_install_sh_browser_install.pydeleted file mode 100644index 41e7af0010b..00000000000--- a/tests/scripts/install/test_install_sh_browser_install.py+++ /dev/null@@ -1,121 +0,0 @@-"""Regression tests for install.sh browser setup.--Browser automation is optional. The installer should not leave Hermes-half-installed just because Playwright's managed Chromium download hangs on an-unsupported distribution.-"""--from pathlib import Path--REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent-INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"--# ----------------------------------------------------------------------------# Behavioral tests: source the install.sh helpers in a stubbed shell and assert-# the override retry fires ONLY on a too-new apt release (#35166), and not on a-# host Playwright already supports.-# -----------------------------------------------------------------------------import subprocess--def _run_install_fn(distro: str, version: str, *, native_fails: bool,- arch: str = "x86_64", operator_override: str = "") -> dict:- """Source the relevant functions from install.sh and drive run_playwright_install.-- Stubs `npx` (the install command) to fail/succeed, `uname -m` for arch, and- `log_warn`/`log_info` to no-ops. Returns parsed observations: how many times- the install command ran, and the override value seen on each run.- """- # Extract the functions we need so we don't execute the whole installer.- # run_browser_install_with_timeout delegates to run_with_timeout (#39219),- # so the helper must be pulled in too or the install command never runs.- fn_names = [- "run_browser_install_with_timeout",- "run_with_timeout",- "playwright_host_unrecognized",- "playwright_fallback_platform",- "run_playwright_install",- ]- src = INSTALL_SH.read_text()- import re-- extracted = []- for name in fn_names:- m = re.search(rf"^{re.escape(name)}\(\) \{{.*?^\}}", src, re.MULTILINE | re.DOTALL)- assert m, f"could not extract {name}() from install.sh"- extracted.append(m.group(0))- body = "\n\n".join(extracted)-- native_rc = 1 if native_fails else 0- harness = f"""-set -u-DISTRO={distro!r}-DISTRO_VERSION={version!r}-export PLAYWRIGHT_HOST_PLATFORM_OVERRIDE={operator_override!r}-[ -z "$PLAYWRIGHT_HOST_PLATFORM_OVERRIDE" ] && unset PLAYWRIGHT_HOST_PLATFORM_OVERRIDE--log_warn() {{ :; }}-log_info() {{ :; }}--# Stub `uname -m` for arch control without touching the real binary.-uname() {{ if [ "$1" = "-m" ]; then echo {arch!r}; else command uname "$@"; fi }}--# Stub `timeout`: just run the command, ignoring flags/duration. We only care-# about how the npx stub behaves, not real timeout semantics here.-timeout() {{- while [ $# -gt 0 ]; do- case "$1" in -*|[0-9]*) shift ;; *) break ;; esac- done- "$@"-}}--# Stub the install command. Record each invocation + the override in effect.-npx() {{- echo "RUN override=${{PLAYWRIGHT_HOST_PLATFORM_OVERRIDE:-<none>}}" >>"$RUNLOG"- # First run reflects native_fails; the override retry (if any) succeeds.- if [ -n "${{PLAYWRIGHT_HOST_PLATFORM_OVERRIDE:-}}" ]; then return 0; fi- return {native_rc}-}}--{body}--run_playwright_install 600 npx playwright install --with-deps chromium-echo "FINAL_RC=$?"-"""- import tempfile, os- with tempfile.NamedTemporaryFile("w", suffix=".log", delete=False) as lf:- runlog = lf.name- try:- env = dict(os.environ, RUNLOG=runlog)- proc = subprocess.run(["bash", "-c", harness], capture_output=True,- text=True, env=env)- runs = Path(runlog).read_text().strip().splitlines()- final_rc = None- for line in proc.stdout.splitlines():- if line.startswith("FINAL_RC="):- final_rc = int(line.split("=", 1)[1])- return {"runs": runs, "final_rc": final_rc, "stderr": proc.stderr}- finally:- Path(runlog).unlink(missing_ok=True)--def test_override_retry_fires_on_ubuntu_26() -> None:- """Ubuntu 26.04 (too new) → native fails → retry with ubuntu24.04 override."""- r = _run_install_fn("ubuntu", "26.04", native_fails=True)- assert len(r["runs"]) == 2, r["runs"]- assert "override=<none>" in r["runs"][0]- assert "override=ubuntu24.04-x64" in r["runs"][1]- assert r["final_rc"] == 0--def test_override_retry_fires_on_debian_14() -> None:- """Debian 14 (> 13) is the too-new apt case → retry with override."""- r = _run_install_fn("debian", "14", native_fails=True)- assert len(r["runs"]) == 2, r["runs"]- assert "override=ubuntu24.04-x64" in r["runs"][1]- assert r["final_rc"] == 0--def test_no_retry_when_native_succeeds_on_ubuntu_26() -> None:- """Even on Ubuntu 26.04, a successful native install is never retried."""- r = _run_install_fn("ubuntu", "26.04", native_fails=False)- assert len(r["runs"]) == 1, r["runs"]- assert "override=<none>" in r["runs"][0]- assert r["final_rc"] == 0diff --git a/tests/scripts/install/test_install_sh_node_prerelease.py b/tests/scripts/install/test_install_sh_node_prerelease.pydeleted file mode 100644index 4bc0b3482a8..00000000000--- a/tests/scripts/install/test_install_sh_node_prerelease.py+++ /dev/null@@ -1,93 +0,0 @@-"""The installer must never adopt a pre-release Node.js build.--`nodejs.org/dist/latest-v26.x/` serves `node-v26.8.0-<os>-<arch>.tar.xz` — a-filename that looks like a final release — whose binary reports-`v26.8.0-alpha.0.0.0`. Node publishes a headers tarball only for final-releases, so `process.release.headersUrl` 404s for that build and node-gyp-cannot compile against it.--That is fatal rather than cosmetic: `node-pty` ships prebuilds for darwin and-win32 only, so every Linux install compiles it, and the failure surfaces as an-opaque `[email protected] install: command failed` because the package's-`node scripts/prebuild.js || node-gyp rebuild` fallback swallows gyp's stderr.--These tests drive the real blocks out of `scripts/install.sh` rather than-asserting on a copy, so the guard cannot drift away from the test.-"""--import re-import subprocess-from pathlib import Path--REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent-INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"--def _extract_function(text: str, name: str) -> str:- match = re.search(- rf"^{re.escape(name)}\(\) \{{\n.*?^\}}\n", text, re.M | re.S- )- assert match, (- f"could not locate {name}() in scripts/install.sh — "- "if it was renamed, update this test with it"- )- return match.group(0)--def _node_satisfies_build(version: str) -> bool:- """Run the real node_satisfies_build() against one `node --version` string."""- script = (- _extract_function(INSTALL_SH.read_text(encoding="utf-8"), "node_satisfies_build")- + f'\nnode_satisfies_build "{version}"\n'- )- return subprocess.run(["bash", "-c", script]).returncode == 0--def test_prerelease_node_never_satisfies_the_build_floor() -> None:- """The exact build that breaks node-pty, plus the other pre-release tags."""- assert not _node_satisfies_build("v26.8.0-alpha.0.0.0")- assert not _node_satisfies_build("v24.0.0-rc.1")- assert not _node_satisfies_build("v23.5.0-nightly20260101abcdef")- assert not _node_satisfies_build("v22.22.0-pre")--def test_final_releases_still_satisfy_the_build_floor() -> None:- """The guard must not cost us any version that actually works."""- assert _node_satisfies_build("v22.22.0") # the floor itself- assert _node_satisfies_build("v24.20.0")- assert _node_satisfies_build("v26.8.0") # a real 26 release, once one ships--def test_versions_below_the_floor_are_still_rejected() -> None:- assert not _node_satisfies_build("v22.21.0")- assert not _node_satisfies_build("v20.19.0")- assert not _node_satisfies_build("not-a-version")--def test_install_node_falls_back_to_an_older_release_line(tmp_path: Path) -> None:- """A rejected line must not end the install — the next one is tried.-- install_node_line() cannot be exercised here (it downloads), so it is- stubbed to reject 26 the way a pre-release tarball does and accept 24.- """- body = _extract_function(INSTALL_SH.read_text(encoding="utf-8"), "install_node")- script = f"""-set -e-NODE_VERSION=26-DISTRO=linux-OS=linux-uname() {{ echo x86_64; }}-log_info(){{ :; }}; log_warn(){{ :; }}; log_success(){{ :; }}-install_node_line() {{- echo "$1" >> "$TRIED"- [ "$1" = 24 ]-}}-{body}-install_node-"""- tried = tmp_path / "tried"- result = subprocess.run(- ["bash", "-c", script],- capture_output=True,- text=True,- encoding="utf-8",- errors="replace",- env={"PATH": "/usr/bin:/bin", "TRIED": str(tried)},- )- assert result.returncode == 0, result.stderr- # 26 first, then the previous even (LTS) line; stops once one works.- assert tried.read_text(encoding="utf-8").split() == ["26", "24"]diff --git a/tests/scripts/install/test_install_sh_repository_stage.py b/tests/scripts/install/test_install_sh_repository_stage.pynew file mode 100644index 00000000000..9fee1063e67--- /dev/null+++ b/tests/scripts/install/test_install_sh_repository_stage.py@@ -0,0 +1,173 @@+"""install.sh reruns, pins and invocation modes, driven through the real stage functions.++Each test sources the installer with ``--manifest`` (definitions only) and runs+one stage against real git repositories in ``tmp_path``.+"""+import json+import os+from pathlib import Path+import shlex+import subprocess++import pytest++pytestmark = pytest.mark.platforms("posix")+INSTALL_SH = Path(__file__).resolve().parents[3] / "scripts" / "install.sh"+++def _git(repo: Path, *args: str) -> str:+ return subprocess.run(["git", "-C", str(repo), "-c", "user.email=t@t", "-c", "user.name=t", *args],+ check=True, capture_output=True, text=True).stdout.strip()+++def _origin(path: Path, content: str = "one") -> Path:+ path.mkdir()+ _git(path, "init", "-q", "-b", "main")+ (path / "README").write_text(content)+ _git(path, "add", "README")+ _git(path, "commit", "-qm", content)+ return path+++def _commit(repo: Path, content: str) -> str:+ (repo / "README").write_text(content)+ _git(repo, "commit", "-qam", content)+ return _git(repo, "rev-parse", "HEAD")+++def _run(tmp_path: Path, body: str, *, env: dict | None = None, **kwargs) -> subprocess.CompletedProcess:+ script = f"source {shlex.quote(INSTALL_SH.as_posix())} --manifest\nsleep() {{ :; }}\n{body}\n"+ full_env = dict(os.environ, HOME=tmp_path.as_posix(), HERMES_HOME=(tmp_path / "home").as_posix(),+ HERMES_INSTALL_DIR=(tmp_path / "install").as_posix(), **(env or {}))+ return subprocess.run(["bash", "-c", script], env=full_env, capture_output=True, text=True, timeout=60, **kwargs)+++def _stage(tmp_path: Path, origin: Path, *, commit: str = "", extra_env: dict | None = None,+ prelude: str = "") -> subprocess.CompletedProcess:+ env = {"HERMES_REPO_URL": origin.as_posix(), **(extra_env or {})}+ return _run(tmp_path, f"{prelude}\nINSTALL_COMMIT={shlex.quote(commit)}\nstage_repository", env=env)+++def test_piped_one_liner_runs_the_installer():+ """`curl ... | bash` has an empty BASH_SOURCE; under `set -u` the entry guard must still run main."""+ result = subprocess.run(["bash", "-s", "--", "--manifest"], input=INSTALL_SH.read_bytes(),+ capture_output=True, timeout=30)+ assert result.returncode == 0, result.stderr.decode()+ assert json.loads(result.stdout)["protocol_version"] == 1+++def test_rerun_parks_local_work_before_updating(tmp_path):+ origin = _origin(tmp_path / "origin")+ assert _stage(tmp_path, origin).returncode == 0+ install = tmp_path / "install"+ (install / "README").write_text("local edit")+ _commit(origin, "two")+ result = _stage(tmp_path, origin)+ assert result.returncode == 0, result.stdout + result.stderr+ assert (install / "README").read_text() == "two"+ assert "local edit" in _git(install, "stash", "show", "-p", "stash@{0}")+++def test_rerun_stops_when_local_work_cannot_be_parked(tmp_path):+ origin = _origin(tmp_path / "origin")+ assert _stage(tmp_path, origin).returncode == 0+ install = tmp_path / "install"+ before = _git(install, "rev-parse", "HEAD")+ (install / "README").write_text("local edit")+ _commit(origin, "two")+ failing_stash = 'git() { [ "${3:-}" = stash ] && return 1; command git "$@"; }'+ result = _stage(tmp_path, origin, prelude=failing_stash)+ assert result.returncode != 0+ assert (install / "README").read_text() == "local edit"+ assert _git(install, "rev-parse", "HEAD") == before+++def test_commit_pin_must_come_from_the_installed_branch(tmp_path):+ origin = _origin(tmp_path / "origin")+ on_branch = _git(origin, "rev-parse", "HEAD")+ _commit(origin, "two")+ _git(origin, "checkout", "-qb", "side")+ off_branch = _commit(origin, "side")+ _git(origin, "checkout", "-q", "main")+ refused = _stage(tmp_path, origin, commit=off_branch)+ assert refused.returncode != 0+ assert "is not on branch main" in refused.stdout + refused.stderr+ pinned = _stage(tmp_path, origin, commit=on_branch)+ assert pinned.returncode == 0, pinned.stdout + pinned.stderr+ assert _git(tmp_path / "install", "rev-parse", "HEAD") == on_branch+++def test_commitless_checkout_is_moved_aside_and_recloned(tmp_path):+ origin = _origin(tmp_path / "origin")+ install = tmp_path / "install"+ install.mkdir()+ _git(install, "init", "-q")+ (install / "keep").write_text("user file")+ result = _stage(tmp_path, origin)+ assert result.returncode == 0, result.stdout + result.stderr+ assert (install / "README").read_text() == "one"+ [broken] = tmp_path.glob("install.broken-*")+ assert (broken / "keep").read_text() == "user file"+++def test_unmerged_index_is_cleared_then_stashed(tmp_path):+ origin = _origin(tmp_path / "origin")+ assert _stage(tmp_path, origin).returncode == 0+ install = tmp_path / "install"+ _git(install, "checkout", "-qb", "conflict")+ _commit(install, "theirs")+ _git(install, "checkout", "-q", "main")+ _commit(install, "ours")+ subprocess.run(["git", "-C", str(install), "merge", "conflict"], capture_output=True)+ assert _git(install, "ls-files", "--unmerged")+ _commit(origin, "two")+ result = _stage(tmp_path, origin)+ assert result.returncode == 0, result.stdout + result.stderr+ assert (install / "README").read_text() == "two"+ assert not _git(install, "ls-files", "--unmerged")+++def test_rerun_follows_an_explicit_repo_url(tmp_path):+ first = _origin(tmp_path / "first")+ assert _stage(tmp_path, first).returncode == 0+ moved = tmp_path / "moved"+ subprocess.run(["git", "clone", "-q", str(first), str(moved)], check=True)+ tip = _commit(moved, "moved")+ result = _stage(tmp_path, moved)+ assert result.returncode == 0, result.stdout + result.stderr+ install = tmp_path / "install"+ assert _git(install, "rev-parse", "HEAD") == tip+ assert _git(install, "remote", "get-url", "origin") == moved.as_posix()++[email protected]("reported, accepted", [("0.6.17", False), ("99.0.0", True)])+def test_path_uv_is_used_only_when_at_least_the_pin(tmp_path, reported, accepted):+ bindir = tmp_path / "bin"+ bindir.mkdir()+ fake = bindir / "uv"+ fake.write_text(f"#!/bin/sh\necho 'uv {reported}'\n")+ fake.chmod(0o755)+ # No pinned target: rejecting the PATH uv must surface as a failure to stage one.+ body = 'uv_bootstrap_target() { return 1; }\nensure_uv\necho "UV_CMD=$UV_CMD"'+ result = _run(tmp_path, body, env={"PATH": f"{bindir}:{os.environ['PATH']}"})+ if accepted:+ assert result.returncode == 0, result.stdout + result.stderr+ assert f"UV_CMD={fake}" in result.stdout+ else:+ assert result.returncode != 0+ assert "older than the pinned" in result.stdout + result.stderr+++def test_interactive_stages_skip_without_a_terminal(tmp_path):+ install = tmp_path / "install"+ (install / ".hermes" / "bin").mkdir(parents=True)+ marker = tmp_path / "ran"+ hermes = install / ".hermes" / "bin" / "hermes"+ hermes.write_text(f"#!/bin/sh\ntouch {shlex.quote(marker.as_posix())}\n")+ hermes.chmod(0o755)+ # A new session has no controlling terminal, so opening /dev/tty fails.+ result = _run(tmp_path, "NON_INTERACTIVE=false\nstage_setup\nstage_gateway", start_new_session=True,+ stdin=subprocess.DEVNULL)+ assert result.returncode == 0, result.stdout + result.stderr+ assert not marker.exists()+ assert "no terminal" in result.stdout + result.stderrdiff --git a/tests/scripts/install/test_install_sh_reuse_supported_python.py b/tests/scripts/install/test_install_sh_reuse_supported_python.pyindex f1048484ce7..69b474758e1 100644--- a/tests/scripts/install/test_install_sh_reuse_supported_python.py+++ b/tests/scripts/install/test_install_sh_reuse_supported_python.py@@ -57,9 +57,11 @@ def test_supported_base_python_is_reused_offline(tmp_path: Path, activated: boolenv["VIRTUAL_ENV"] = str(active)env["PATH"] = f"{active / 'bin'}{os.pathsep}{bin_dir}"# Source the real helper, then inspect the selected interpreter, not argv.- script = ('source "$1" --manifest; INSTALL_DIR="$2"; bootstrap_python; '+ # UV_CMD hands discovery the host uv as-is: which uv qualifies is+ # ensure_uv's contract (test_install_sh_repository_stage.py), not this one.+ script = ('source "$1" --manifest; INSTALL_DIR="$2"; UV_CMD="$3"; bootstrap_python; ''"$boot_py" -I -c "import sys; print(sys.prefix == sys.base_prefix)"')- result = subprocess.run([bash, "-c", script, "test", str(INSTALL_SH), str(core)],+ result = subprocess.run([bash, "-c", script, "test", str(INSTALL_SH), str(core), str(bin_dir / "uv")],env=env, cwd=core, capture_output=True, text=True, timeout=30)assert result.returncode == 0, result.stdout + result.stderrassert result.stdout.strip() == "True", result.stdout + result.stderr@@ -81,6 +83,9 @@ def test_bootstrap_failure_has_no_success_frame(tmp_path: Path, failure: str) ->uv = bin_dir / "uv"uv.write_text(f"#!{bash}\n"+ # New enough for the installer's pin check, so the failure under test+ # is the Python one, not a rejected uv.+ 'if [ "$1" = --version ]; then echo "uv 99.0.0"; exit 0; fi\n''if [ "$1 $2" = "python install" ]; then\n'f" : > {shlex.quote(str(attempted))}\n"f" exit {9 if failure == 'install' else 0}\nfi\n"diff --git a/tests/scripts/install/test_install_sh_symlink_stomp.py b/tests/scripts/install/test_install_sh_symlink_stomp.pydeleted file mode 100644index 628c9804351..00000000000--- a/tests/scripts/install/test_install_sh_symlink_stomp.py+++ /dev/null@@ -1,104 +0,0 @@-"""Regression for #21454: re-running install.sh on a symlinked prior install.--Older versions of ``install.sh`` created ``$command_link_dir/hermes`` as a-symlink to the pip-generated entry point at ``$HERMES_BIN`` (i.e.-``venv/bin/hermes``). When ``setup_path()`` later switched to writing a bash-shim with ``cat > "$command_link_dir/hermes" <<EOF``, the redirect followed-the existing symlink and overwrote the pip entry point with the shim. The-shim's ``exec "$HERMES_BIN" "$@"`` then self-recursed and ``hermes`` hung on-every invocation.--These tests pin the fix: ``setup_path()`` must remove ``$command_link_dir/hermes``-before writing through the redirect, so the shim is created as a regular file-in ``command_link_dir`` and the venv entry point is left intact.-"""--from __future__ import annotations--import re-import stat-import subprocess-from pathlib import Path---REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent-INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"---def _extract_setup_path_shim_block() -> str:- """Return the install.sh shim-write block used by setup_path()."""- text = INSTALL_SH.read_text()- match = re.search(- r"(?P<block>mkdir -p \"\$command_link_dir\".*?chmod \+x \"\$command_link_dir/hermes\")",- text,- re.DOTALL,- )- assert match is not None, (- "Could not locate the setup_path shim-write block in scripts/install.sh"- )- return match["block"]---def test_re_running_setup_path_block_preserves_pip_entry_point(tmp_path: Path) -> None:- """Behavioral repro: simulate prior-install symlink + new-install heredoc.-- Layout mirrors a real install:-- tmp/- venv/bin/hermes <- pip entry point (the one we must preserve)- local_bin/hermes <- symlink → ../venv/bin/hermes (old install)-- Then we run the exact shim-write block from setup_path() with- ``HERMES_BIN`` and ``command_link_dir`` pointed at this fixture. The fix- requires that, after the run:-- * ``venv/bin/hermes`` still contains its original pip-script body- * ``local_bin/hermes`` is a regular file (not a symlink) holding the shim- """- venv_bin = tmp_path / "venv" / "bin"- venv_bin.mkdir(parents=True)- pip_entry = venv_bin / "hermes"- pip_marker = "#!/usr/bin/env python\n# pip-generated entry point — must not be overwritten\n"- pip_entry.write_text(pip_marker)- pip_entry.chmod(pip_entry.stat().st_mode | stat.S_IXUSR)-- command_link_dir = tmp_path / "local_bin"- command_link_dir.mkdir()- shim_path = command_link_dir / "hermes"- # Reproduce the prior-install state: shim path is a symlink to the- # pip-generated entry point.- shim_path.symlink_to(pip_entry)- assert shim_path.is_symlink()-- block = _extract_setup_path_shim_block()- # Drive the block with the real env vars setup_path() sets.- script = f'set -e\nHERMES_BIN={pip_entry!s}\ncommand_link_dir={command_link_dir!s}\n{block}\n'- result = subprocess.run(- ["bash", "-c", script],- capture_output=True,- text=True,- cwd=tmp_path,- )- assert result.returncode == 0, (- f"shim-write block failed:\nstdout={result.stdout}\nstderr={result.stderr}"- )-- # The pip entry point must still be the original pip script — not a- # re-written self-recursing bash shim.- assert pip_entry.read_text() == pip_marker, (- "venv/bin/hermes was overwritten by setup_path() — symlink-stomp "- "regression (#21454)."- )-- # The shim path itself must now be a regular file holding the launcher.- assert shim_path.exists()- assert not shim_path.is_symlink(), (- "command_link_dir/hermes must be replaced with a regular file, not "- "left as a symlink — otherwise the next install will stomp again."- )- shim_text = shim_path.read_text()- assert "unset PYTHONPATH" in shim_text- assert "unset PYTHONHOME" in shim_text- assert f'exec "{pip_entry}"' in shim_text- shim_mode = shim_path.stat().st_mode- assert shim_mode & stat.S_IXUSR, "shim must be user-executable"diff --git a/tests/scripts/install/test_install_unmerged_index.py b/tests/scripts/install/test_install_unmerged_index.pydeleted file mode 100644index 99dbde32e03..00000000000--- a/tests/scripts/install/test_install_unmerged_index.py+++ /dev/null@@ -1,121 +0,0 @@-"""Regression: installer fails when the existing checkout has an unmerged index.--A previously interrupted update can leave ``$INSTALL_DIR`` with unmerged index-entries (files in a conflicted, "needs merge" state). In that state the update-path's ``git stash`` aborts with "could not write index" and the following-``git checkout <branch>`` aborts with "you need to resolve your current index-first" -- surfacing to GUI/bootstrap users as ``git checkout main failed-(exit 1)`` and failing the whole install at the repository stage.--The ``hermes update`` Python path already clears the conflict with ``git reset``-before stashing (#4735); both installer scripts must do the same.-"""--from __future__ import annotations--import re-import shutil-import subprocess-from pathlib import Path--import pytest--REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent-INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"--pytestmark = pytest.mark.skipif(- shutil.which("git") is None or shutil.which("bash") is None,- reason="needs git and bash",-)--def _git(cwd: Path, *args: str, check: bool = True) -> subprocess.CompletedProcess:- return subprocess.run(- ["git", "-c", "user.email=t@t", "-c", "user.name=t", *args],- cwd=cwd,- check=check,- capture_output=True,- text=True,- )--def _extract_autostash_block() -> str:- """Pull the autostash if-block from install.sh's update_repo()."""- text = INSTALL_SH.read_text()- m = re.search(- r'local autostash_ref="".*?\n fi\n',- text,- re.DOTALL,- )- assert m is not None, "autostash block not found in install.sh"- return m.group(0)--def _extract_install_sh_function(name: str) -> str:- text = INSTALL_SH.read_text()- match = re.search(rf"{name}\(\) \{{.*?\n\}}", text, re.DOTALL)- assert match is not None, f"{name}() not found in install.sh"- return match.group(0)--def _make_unmerged_repo(repo: Path) -> None:- """Leave ``repo`` with a conflicted (unmerged) index, as an interrupted- update would."""- _git(repo, "init")- (repo / "f.txt").write_text("base\n")- _git(repo, "add", "f.txt")- _git(repo, "commit", "-m", "base")- # Capture the default branch name only after the first commit exists- # (rev-parse on an unborn HEAD errors).- start = _git(repo, "rev-parse", "--abbrev-ref", "HEAD").stdout.strip()-- _git(repo, "checkout", "-b", "feature")- (repo / "f.txt").write_text("feature side\n")- _git(repo, "add", "f.txt")- _git(repo, "commit", "-m", "feature")-- _git(repo, "checkout", start)- (repo / "f.txt").write_text("main side\n")- _git(repo, "add", "f.txt")- _git(repo, "commit", "-m", "mainside")-- # Conflicting merge — exits non-zero and leaves the index unmerged.- _git(repo, "merge", "feature", check=False)-[email protected]_system_guard_bypass # runs against a dedicated throwaway repo-def test_install_sh_clears_unmerged_index_then_stashes(tmp_path: Path) -> None:- repo = tmp_path / "hermes-agent"- repo.mkdir()- _make_unmerged_repo(repo)-- # Sanity: this is exactly the state that breaks `git stash` / `git checkout`.- assert _git(repo, "ls-files", "--unmerged").stdout.strip(), (- "test setup failed to produce an unmerged index"- )-- block = _extract_autostash_block()- script = (- "set -e\n"- 'log_info() { echo "INFO: $*"; }\n'- f'INSTALL_DIR="{repo}"\n'- f"{_extract_install_sh_function('discard_update_lockfile_churn')}\n"- "run() {\n"- f"{block}"- "}\n"- "run\n"- "echo BLOCK_OK\n"- )- res = subprocess.run(- ["bash", "-c", script], cwd=repo, capture_output=True, text=True- )-- # The block must complete (previously `git stash` failed with "could not- # write index" on the unmerged tree).- assert res.returncode == 0, res.stderr- assert "BLOCK_OK" in res.stdout- assert "Clearing unmerged index entries" in res.stdout-- # The conflict state is gone ...- assert _git(repo, "ls-files", "--unmerged").stdout.strip() == "", (- "unmerged entries should have been cleared"- )- # ... and the local changes were preserved in a stash, not discarded.- assert _git(repo, "stash", "list").stdout.strip(), (- "local changes should be preserved in a stash"- )