Skip to content

The agent that grows with you

feat(update-test): snapshot with VSS instead of tarring the whole home (Windows)

ethernet86adc51d7cf2
diff --git a/scripts/update-test/HANDOFF.md b/scripts/update-test/HANDOFF.md
index bf2edc04788..d051fafb698 100644
--- a/scripts/update-test/HANDOFF.md
+++ b/scripts/update-test/HANDOFF.md
@@ -10,7 +10,7 @@ instructions:
macos/linux:
`curl -fsSL "sh_url?t=$(date +%s)" | bash -s -- pre`
- windows:
+ windows (open PowerShell with **Run as Administrator** — the backup takes a disk snapshot, which needs admin):
`& ([scriptblock]::Create((irm "ps1_url1" -Headers @{"Cache-Control"="no-cache"}))) pre`
this backs up your entire hermes home and any desktop app settings. _from this point on, nothing you do in hermes will be preserved, until you restore your backup at the end._
@@ -28,7 +28,7 @@ instructions:
macos/linux:
`curl -fsSL "sh_url?t=$(date +%s)" | bash -s -- post --yes`
- windows:
+ windows (again as **Administrator**):
`& ([scriptblock]::Create((irm "ps1_url1" -Headers @{"Cache-Control"="no-cache"}))) post -Yes`
this puts hermes back to exactly how it was beforehand.
diff --git a/scripts/update-test/hermes-update-rehearsal.ps1 b/scripts/update-test/hermes-update-rehearsal.ps1
index dc41e9b98f4..d6accbb18b6 100755
--- a/scripts/update-test/hermes-update-rehearsal.ps1
+++ b/scripts/update-test/hermes-update-rehearsal.ps1
@@ -5,16 +5,24 @@
.DESCRIPTION
Two steps:
- pre back up your ENTIRE HERMES_HOME and the desktop app's Electron userData,
+ pre take a `hermes backup` of your data, snapshot the disk that holds
+ HERMES_HOME and the desktop app's Electron userData (Volume Shadow Copy),
then point the install's update source at a custom repo + ref so
`hermes update` pulls it. Prints what to do next.
- post wipe both trees and put the backup back exactly as it was.
+ post put both trees back exactly as they were at the snapshot.
Plus `status`, which only prints. This script never judges your install: it
reports what it did and stops. Whether the update worked is yours to see.
- The backup is one plain tar per tree with nothing filtered out, and `post`
- restores those tars over empty directories, so every file comes back as it was.
+ The snapshot is copy-on-write, so pre copies nothing and takes seconds. post
+ mirrors the snapshot back over both trees: only files the update changed are
+ copied, and files it added are deleted. HERMES_HOME\cache is left as it is.
+
+ If Windows drops the snapshot (it can when the disk's shadow storage fills),
+ your files are untouched but post cannot roll back; the `hermes backup` zip
+ still holds your config, keys, sessions, memories and skills.
+
+ pre and post need an elevated (Run as Administrator) PowerShell.
.PARAMETER Command
pre | post | status
@@ -58,7 +66,6 @@ $OfficialHttps = 'https://github.com/NousResearch/hermes-agent.git'
$OfficialSsh = '[email protected]:NousResearch/hermes-agent.git'
$script:Snap = ''
-$script:Tar = $null
function Say { param([string]$m) Write-Host $m }
function Ok { param([string]$m) Write-Host " OK $m" }
@@ -66,24 +73,12 @@ function Warn { param([string]$m) Write-Warning " $m" }
function Step { param([string]$m) Write-Host "`n=== $m ===" }
function Fail { param([string]$m) throw "ERROR: $m" }
-function Resolve-Tar {
- # A PATH pointing into a WindowsApps payload (the bundled app's toolchain)
- # yields a tar.exe PowerShell cannot launch, so prefer the real one.
- $cands = @()
- if ($env:SystemRoot) {
- $cands += (Join-Path $env:SystemRoot 'System32\tar.exe')
- $cands += (Join-Path $env:SystemRoot 'Sysnative\tar.exe')
- }
- $onPath = Get-Command tar.exe -ErrorAction SilentlyContinue
- if ($onPath) { $cands += $onPath.Source }
- foreach ($c in $cands) {
- if (-not $c) { continue }
- if ($c -like '*\Microsoft\WindowsApps\*') { continue }
- if (-not (Test-Path -LiteralPath $c)) { continue }
- try { & $c --version *> $null; if ($LASTEXITCODE -eq 0) { return $c } }
- catch { }
+function Assert-Elevated {
+ $id = [Security.Principal.WindowsIdentity]::GetCurrent()
+ $admin = (New-Object Security.Principal.WindowsPrincipal $id).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
+ if (-not $admin) {
+ Fail 'the disk snapshot needs admin rights -- open PowerShell with "Run as Administrator" and run this again (nothing was changed)'
}
- return $null
}
# ---------------------------------------------------------------------------
@@ -93,7 +88,6 @@ function Get-ResolvedPaths {
$suffix = if ($env:HERMES_DATA_DIR_SUFFIX) { $env:HERMES_DATA_DIR_SUFFIX } else { '' }
$userProfile = $env:USERPROFILE
if ($env:HERMES_HOME) {
- # Must tolerate a MISSING home: post resolves paths in order to recreate them.
$home_ = $env:HERMES_HOME
try { $home_ = (Resolve-Path -LiteralPath $home_ -ErrorAction Stop).Path }
catch { $home_ = [IO.Path]::GetFullPath($home_) }
@@ -134,6 +128,7 @@ function Load-Snapshot {
$script:Snap = $snap
$recordedPath = Join-Path $snap 'hermes-home.txt'
if (-not (Test-Path -LiteralPath $recordedPath)) { Fail "$snap is not a rehearsal backup (no hermes-home.txt)" }
+ if (-not (Test-Path -LiteralPath (Join-Path $snap 'shadows.txt'))) { Fail "$snap has no disk snapshot (made by an older version of this script)" }
$P = Get-ResolvedPaths
$recorded = ((Get-Content -LiteralPath $recordedPath -Raw) -replace "`r", '').Trim()
if ($recorded -ne $P.Home) {
@@ -162,36 +157,104 @@ function Invoke-GitCmd {
}
# ---------------------------------------------------------------------------
-# pre
+# Volume Shadow Copy
# ---------------------------------------------------------------------------
+# One snapshot per volume. shadows.txt holds one "volume<TAB>id<TAB>device" line
+# each; post looks every id up again and refuses to touch anything if one is gone.
+
+function Get-VolumeRoot {
+ param([string]$Path)
+ $root = [IO.Path]::GetPathRoot([IO.Path]::GetFullPath($Path))
+ if ($root -notmatch '^[A-Za-z]:\\$') { Fail "$Path is not on a local drive letter; a disk snapshot cannot cover it" }
+ return $root.ToUpperInvariant()
+}
-function Invoke-BackupTar {
- param([string]$TarExe, [string[]]$TarArgs, [string]$Root, [string]$Label)
-
-
- $old = $ErrorActionPreference
+function Get-ShadowStorageMax {
+ param([string]$Volume)
+ $prev = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
- $output = & $TarExe @TarArgs 2>&1
- $ErrorActionPreference = $old
+ try { $out = & vssadmin list shadowstorage "/for=$($Volume.TrimEnd('\'))" 2>$null | Out-String }
+ finally { $ErrorActionPreference = $prev }
+ if ($out -match 'Maximum Shadow Copy Storage space:\s*(.+)') { return $Matches[1].Trim() }
+ return $null
+}
- if ($LASTEXITCODE -eq 0) { return }
+function New-Shadow {
+ param([string]$Volume)
+ $r = (Get-WmiObject -List Win32_ShadowCopy).Create($Volume, 'ClientAccessible')
+ if ($r.ReturnValue -ne 0) { Fail "could not snapshot $Volume (Win32_ShadowCopy.Create returned $($r.ReturnValue))" }
+ $sc = Get-WmiObject Win32_ShadowCopy | Where-Object { $_.ID -eq $r.ShadowID }
+ return [pscustomobject]@{ Volume = $Volume; Id = $sc.ID; Device = $sc.DeviceObject }
+}
- $denied = @($output | Where-Object {
- $_ -match 'Permission denied|Access is denied'
+function Read-Shadows {
+ return @(Get-Content -LiteralPath (Join-Path $script:Snap 'shadows.txt') | Where-Object { $_.Trim() } | ForEach-Object {
+ $f = $_ -split "`t"
+ [pscustomobject]@{ Volume = $f[0]; Id = $f[1]; Device = $f[2] }
})
- if ($denied) {
- $user = "$env:USERDOMAIN\$env:USERNAME"
- Warn "tar could not read $($denied.Count) path(s) under $Root`:"
- $denied | ForEach-Object { Write-Host " $_" }
- Say ''
- Say 'run this in an elevated (Run as Administrator) PowerShell, then re-run pre:'
- Say " icacls `"$Root`" /grant `"$user`:(OI)(CI)F`" /t /c"
- Fail "permission errors backing up $Label -- fix with the command above, then re-run"
+}
+
+function Test-ShadowAlive {
+ param($Shadow)
+ return [bool](Get-WmiObject Win32_ShadowCopy | Where-Object { $_.ID -eq $Shadow.Id })
+}
+
+function Remove-Shadow {
+ param($Shadow)
+ Get-WmiObject Win32_ShadowCopy | Where-Object { $_.ID -eq $Shadow.Id } | ForEach-Object { $_.Delete() }
+}
+
+function Get-MountPath {
+ param($Shadow)
+ return Join-Path $script:Snap ('vss-' + $Shadow.Volume.Substring(0, 1))
+}
+
+function Dismount-Shadow {
+ param([string]$Link)
+ # rmdir WITHOUT /s: removes the link, never what it points at.
+ if (Test-Path -LiteralPath $Link) { cmd /c rmdir "$Link" | Out-Null }
+}
+
+function Mount-Shadow {
+ param($Shadow)
+ $link = Get-MountPath $Shadow
+ Dismount-Shadow $link
+ $null = cmd /c mklink /d "$link" "$($Shadow.Device)\"
+ if ($LASTEXITCODE -ne 0) { Fail "could not mount the snapshot of $($Shadow.Volume) at $link" }
+ return $link
+}
+
+# Mirror one tree from the snapshot over the live tree: copies what differs,
+# deletes what the snapshot does not have. Returns robocopy's summary lines.
+function Invoke-Mirror {
+ param([string]$From, [string]$To, [string[]]$ExcludeDirs = @())
+ $roboArgs = @($From, $To, '/MIR', '/COPY:DAT', '/DCOPY:DAT', '/SL', '/MT:16', '/R:2', '/W:1', '/NP', '/NFL', '/NDL', '/NJH')
+ if ($ExcludeDirs.Count) { $roboArgs += '/XD'; $roboArgs += $ExcludeDirs }
+ $prev = $ErrorActionPreference
+ $ErrorActionPreference = 'Continue'
+ try { $out = & robocopy @roboArgs 2>&1; $code = $LASTEXITCODE }
+ finally { $ErrorActionPreference = $prev }
+ # robocopy: 0-7 = success (bit flags for copied/extra/mismatched), 8+ = failures.
+ if ($code -ge 8) {
+ $out | ForEach-Object { Write-Host " $_" }
+ Fail "restoring $To failed (robocopy exit $code) -- the snapshot is kept; fix the cause and run post again"
}
+ return @($out | Where-Object { $_ -match '^\s*(Total\s+Copied|Dirs\s*:|Files\s*:|Bytes\s*:)' })
+}
+
+# ---------------------------------------------------------------------------
+# pre
+# ---------------------------------------------------------------------------
- # non-permission failure: show what tar said and fail generically
- $output | ForEach-Object { Write-Host " $_" }
- Fail "backup failed (tar) for $Label"
+function Resolve-HermesExe {
+ param($P)
+ foreach ($c in @(
+ (Join-Path $P.Install 'venv\Scripts\hermes.exe'),
+ (Join-Path $P.Home 'bin\hermes.exe'),
+ (Join-Path $P.Home 'bin\hermes.cmd'))) {
+ if (Test-Path -LiteralPath $c) { return $c }
+ }
+ return $null
}
function Invoke-Pre {
@@ -203,6 +266,14 @@ function Invoke-Pre {
Say "backup to $BackupRoot"
if (-not (Test-Path -LiteralPath $P.Home)) { Fail "no HERMES_HOME at $($P.Home)" }
if (-not (Test-Path -LiteralPath (Join-Path $P.Install '.git'))) { Fail "no git checkout at $($P.Install) -- this tool covers source installs" }
+ Assert-Elevated
+ $hermesExe = Resolve-HermesExe $P
+ if (-not $hermesExe) { Fail "no hermes executable found under $($P.Install)\venv\Scripts or $($P.Home)\bin" }
+
+ $volumes = @(Get-VolumeRoot $P.Home)
+ $userDataExists = Test-Path -LiteralPath $P.UserData
+ if ($userDataExists) { $volumes += Get-VolumeRoot $P.UserData }
+ $volumes = @($volumes | Select-Object -Unique)
Step 'before we start (nothing here is pass/fail, just read it)'
$procs = @(Get-Process -Name 'Hermes', 'hermes' -ErrorAction SilentlyContinue)
@@ -215,55 +286,47 @@ function Invoke-Pre {
$n = @(Invoke-GitCmd @('config', '--global', '--get-regexp', '^url\.')).Count
if ($n -eq 0) { Ok 'global git config has no URL rewrites' }
else { Warn "$n existing url.* insteadOf entr(y/ies) in your git config; we add more and remove only ours" }
+ foreach ($v in $volumes) {
+ $max = Get-ShadowStorageMax $v
+ # The snapshot keeps the OLD copy of every block rewritten anywhere on the
+ # disk; once that exceeds this limit Windows deletes the snapshot.
+ if ($max) { Say "snapshot room on $v $max (writing more than this to the disk before post drops the snapshot)" }
+ else { Say "snapshot room on $v not configured yet (Windows sizes it on first use)" }
+ }
$stamp = (Get-Date).ToUniversalTime().ToString('yyyyMMddTHHmmssZ')
$script:Snap = Join-Path $BackupRoot $stamp
if (Test-Path -LiteralPath $script:Snap) { Fail "backup dir already exists: $($script:Snap)" }
New-Item -ItemType Directory -Force -Path $script:Snap | Out-Null
- Step 'backing up your entire HERMES_HOME'
+ Step 'backing up your data (hermes backup)'
+ # Insurance for the case where Windows drops the snapshot: config, keys,
+ # sessions, memories, skills, with SQLite copied consistently. Code, venvs and
+ # models are left out -- those are what a reinstall brings back.
+ $zip = Join-Path $script:Snap 'hermes-backup.zip'
$started = Get-Date
- $homeTar = Join-Path $script:Snap 'hermes-home.tar'
- # No excludes: checkout, venv, PM store and node_modules come too, so post is
- # a true rollback rather than a re-download. SQLite sidecars travel WITH their
- # db on purpose (a raw copy of db+wal+shm is consistent). No -z: the backup
- # root is typically the same internal disk, so gzip costs ~5x the wall time
- # for nothing (measured on an M1).
- Invoke-BackupTar -TarExe $script:Tar -TarArgs @('-cf', $homeTar, '-C', $P.Home, '.') -Root $P.Home -Label 'HERMES_HOME'
+ $prevHome = $env:HERMES_HOME
+ $env:HERMES_HOME = $P.Home
+ $prev = $ErrorActionPreference
+ $ErrorActionPreference = 'Continue'
+ try { $out = & $hermesExe backup -o $zip 2>&1; $code = $LASTEXITCODE }
+ finally { $ErrorActionPreference = $prev; $env:HERMES_HOME = $prevHome }
$elapsed = [int]((Get-Date) - $started).TotalSeconds
- Ok "hermes-home.tar ($([math]::Round((Get-Item $homeTar).Length / 1MB, 1)) MB, ${elapsed}s)"
-
- Step "backing up the desktop app's data"
- if (Test-Path -LiteralPath $P.UserData) {
- $udTar = Join-Path $script:Snap 'electron-userdata.tar'
- Invoke-BackupTar -TarExe $script:Tar -TarArgs @('-cf', $udTar, '-C', $P.UserData, '.') -Root $P.UserData -Label 'Electron userData'
- Ok "electron-userdata.tar ($([math]::Round((Get-Item $udTar).Length / 1KB, 1)) KB)"
+ if ($code -eq 1 -and (Test-Path -LiteralPath $zip)) {
+ $out | ForEach-Object { Write-Host " $_" }
+ Warn "hermes backup finished INCOMPLETE (${elapsed}s): the files listed above are not in $zip"
}
- else { Warn "no Electron userData at $($P.UserData) (desktop app not installed?)" }
-
- Step 'recording what this backup is'
- # Plain text, not JSON: post compares this string byte-for-byte to decide
- # whether the backup belongs to the home it is about to wipe.
- Set-Content -LiteralPath (Join-Path $script:Snap 'hermes-home.txt') -Encoding utf8 -Value @($P.Home)
- $manifest = [ordered]@{
- schema = 3
- created = (Get-Date).ToUniversalTime().ToString('o')
- hermes_home = $P.Home
- install_dir = $P.Install
- userdata_dir = $P.UserData
- userdata_dir_source = $P.UserDataOrigin
- rehearsal_source = $Source
- rehearsal_ref = $Ref
+ elseif ($code -ne 0 -or -not (Test-Path -LiteralPath $zip)) {
+ $out | ForEach-Object { Write-Host " $_" }
+ Fail "hermes backup failed (exit $code) -- nothing else was done"
}
- $manifest | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath (Join-Path $script:Snap 'manifest.json') -Encoding utf8
- Ok "manifest.json (backup of $($P.Home))"
+ else { Ok "hermes-backup.zip ($([math]::Round((Get-Item $zip).Length / 1MB, 1)) MB, ${elapsed}s)" }
- # --- point the install at the rehearsal source ---------------------------
+ # --- fetch before the snapshot, so the snapshot is as late as possible -----
Step 'fetching the rehearsal source'
Say "source $Source"
Say "ref $Ref"
$serve = Join-Path $script:Snap 'serve.git'
- if (Test-Path -LiteralPath $serve) { Remove-Item -LiteralPath $serve -Recurse -Force }
$null = Invoke-GitCmd @('clone', '--quiet', '--bare', '--branch', $Ref, '--single-branch', $Source, $serve)
if ($LASTEXITCODE -ne 0) {
if (Test-Path -LiteralPath $serve) { Remove-Item -LiteralPath $serve -Recurse -Force }
@@ -281,21 +344,46 @@ function Invoke-Pre {
$null = Invoke-GitCmd @('-C', $serve, 'config', 'uploadpack.allowAnySHA1InWant', 'true')
Ok "the update will land on $targetSha"
+ # --- snapshot: the rollback point. Everything after this is undone by post.
+ Step 'snapshotting the disk'
+ $shadowLines = @()
+ foreach ($v in $volumes) {
+ $t0 = Get-Date
+ $s = New-Shadow $v
+ $shadowLines += "$($s.Volume)`t$($s.Id)`t$($s.Device)"
+ Ok "snapshot of $v in $([math]::Round(((Get-Date) - $t0).TotalSeconds, 1))s ($($s.Id))"
+ }
+ Set-Content -LiteralPath (Join-Path $script:Snap 'shadows.txt') -Encoding utf8 -Value $shadowLines
+
+ # Plain text, not JSON: post compares this string byte-for-byte to decide
+ # whether the backup belongs to the home it is about to restore.
+ Set-Content -LiteralPath (Join-Path $script:Snap 'hermes-home.txt') -Encoding utf8 -Value @($P.Home)
+ $manifest = [ordered]@{
+ schema = 4
+ created = (Get-Date).ToUniversalTime().ToString('o')
+ hermes_home = $P.Home
+ install_dir = $P.Install
+ userdata_dir = $P.UserData
+ userdata_dir_source = $P.UserDataOrigin
+ userdata_existed = [bool]$userDataExists
+ rehearsal_source = $Source
+ rehearsal_ref = $Ref
+ }
+ $manifest | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath (Join-Path $script:Snap 'manifest.json') -Encoding utf8
+
Step 'pointing your install at it'
# insteadOf is a TRANSPORT rewrite. Your checkout's origin keeps the official
# URL, which matters: `hermes update` resolves its channel from the archive and
# validates it against `git config --get remote.origin.url`. Repointing origin
# at a fork would make the update fail before any git work.
$fileUrl = 'file:///' + ($serve -replace '\\', '/')
- # REPO-LOCAL, like the POSIX script: the checkout's own config lives inside the
- # home this kit backs up, so post's wipe+restore removes it for free and no
- # writable GLOBAL git config is needed.
+ # REPO-LOCAL: the checkout's config lives inside the snapshotted home, so
+ # post's restore removes the redirect for free.
foreach ($url in @($OfficialHttps, $OfficialSsh)) {
# --add: the key is multi-valued; a plain set would drop the first URL.
$null = Invoke-GitCmd @('-C', $P.Install, 'config', '--local', '--add', "url.$fileUrl.insteadOf", $url)
if ($LASTEXITCODE -ne 0) { Fail "could not write the URL redirect into $($P.Install)\.git\config" }
}
- New-Item -ItemType Directory -Force -Path $P.Home | Out-Null
Set-Content -LiteralPath (Join-Path $P.Home '.skip_upstream_prompt') -Encoding utf8 -Value @()
Set-Content -LiteralPath (Join-Path $script:Snap 'target-sha') -Encoding utf8 -Value @($targetSha)
Ok 'official repo URL now resolves to the rehearsal copy'
@@ -322,6 +410,7 @@ function Invoke-Status {
Step 'backup'
$snap = Get-LatestSnapshot
if (-not $snap) { Say "none -- nothing has been set up yet (run 'pre')"; return }
+ $script:Snap = $snap
Say "latest $snap"
$ts = Join-Path $snap 'target-sha'
if (Test-Path -LiteralPath $ts) {
@@ -330,6 +419,12 @@ function Invoke-Status {
Say "source $($manifest.rehearsal_source) @ $($manifest.rehearsal_ref)"
}
else { Say 'prepared no' }
+ if (Test-Path -LiteralPath (Join-Path $snap 'shadows.txt')) {
+ foreach ($s in Read-Shadows) {
+ Say "snapshot $($s.Volume) $(if (Test-ShadowAlive $s) { 'present' } else { 'GONE -- post cannot roll back' })"
+ }
+ }
+ Say "data backup $(if (Test-Path -LiteralPath (Join-Path $snap 'hermes-backup.zip')) { 'hermes-backup.zip' } else { 'none' })"
Say "marker $(if (Test-Path -LiteralPath (Join-Path $P.Home '.skip_upstream_prompt')) { 'present' } else { 'absent' })"
$n = @(Invoke-GitCmd @('config', '--global', '--get-regexp', '^url\.')).Count
Say "git rewrites $n global insteadOf entr(y/ies)"
@@ -374,11 +469,31 @@ function Remove-StaleGlobalRedirect {
function Invoke-Post {
Load-Snapshot
+ Assert-Elevated
$P = Get-ResolvedPaths
- Step 'this will delete and restore:'
- Say " $($P.Home) (all of it, including the checkout)"
+ $manifest = Get-Content -LiteralPath (Join-Path $script:Snap 'manifest.json') -Raw | ConvertFrom-Json
+ $shadows = Read-Shadows
+
+ # Check EVERY snapshot before touching anything: half a rollback is worse than none.
+ $gone = @($shadows | Where-Object { -not (Test-ShadowAlive $_) })
+ if ($gone.Count) {
+ $zip = Join-Path $script:Snap 'hermes-backup.zip'
+ $gone | ForEach-Object { Warn "the snapshot of $($_.Volume) is gone (Windows deletes snapshots when the disk's shadow storage fills)" }
+ Say ''
+ Say 'Nothing was changed. An exact rollback is no longer possible, but your data is'
+ Say "backed up in $zip. To put your config, keys, sessions, memories and"
+ Say 'skills back, either:'
+ Say " hermes import `"$zip`""
+ Say 'or, if hermes itself no longer starts, extract the zip over your home:'
+ Say " tar -xf `"$zip`" -C `"$($P.Home)`""
+ Say 'then reinstall Hermes to get the program back.'
+ Fail 'the disk snapshot is gone'
+ }
+
+ Step 'this will restore:'
+ Say " $($P.Home) (everything except cache\, including the checkout)"
Say " $($P.UserData)"
- Say " from $($script:Snap)"
+ Say " to how they were at $($script:Snap)"
Confirm-Action "Put everything back from $($script:Snap)?"
Step 'stopping Hermes'
@@ -387,25 +502,37 @@ function Invoke-Post {
}
Ok 'asked Hermes to stop (if anything was running)'
- Step 'clearing both trees'
- if (Test-Path -LiteralPath $P.Home) { Remove-Item -LiteralPath $P.Home -Recurse -Force; Ok "removed $($P.Home)" }
- if (Test-Path -LiteralPath $P.UserData) { Remove-Item -LiteralPath $P.UserData -Recurse -Force; Ok "removed $($P.UserData)" }
-
- Step 'restoring your HERMES_HOME'
- New-Item -ItemType Directory -Force -Path $P.Home | Out-Null
- & $script:Tar -xf (Join-Path $script:Snap 'hermes-home.tar') -C $P.Home
- if ($LASTEXITCODE -ne 0) { Fail "restore failed -- your backup is intact at $($script:Snap)" }
- Ok 'restored'
-
- Step "restoring the desktop app's data"
- $udTar = Join-Path $script:Snap 'electron-userdata.tar'
- if (Test-Path -LiteralPath $udTar) {
- New-Item -ItemType Directory -Force -Path $P.UserData | Out-Null
- & $script:Tar -xf $udTar -C $P.UserData
- if ($LASTEXITCODE -ne 0) { Fail "userData restore failed (backup intact at $($script:Snap))" }
- Ok 'restored'
+ $mounts = @{}
+ try {
+ foreach ($s in $shadows) { $mounts[$s.Volume] = Mount-Shadow $s }
+ $trees = @([pscustomobject]@{ Label = 'HERMES_HOME'; Live = $P.Home; IsHome = $true })
+ $trees += [pscustomobject]@{ Label = "the desktop app's data"; Live = $P.UserData; IsHome = $false }
+ foreach ($t in $trees) {
+ Step "restoring $($t.Label)"
+ $vol = Get-VolumeRoot $t.Live
+ if (-not $t.IsHome -and -not $manifest.userdata_existed) {
+ # There was no desktop data at the snapshot: exact means none now either.
+ if (Test-Path -LiteralPath $t.Live) { Remove-Item -LiteralPath $t.Live -Recurse -Force; Ok "removed $($t.Live) (it did not exist before)" }
+ else { Ok 'nothing to restore (there was no desktop data before)' }
+ continue
+ }
+ if (-not $mounts.ContainsKey($vol)) { Fail "no snapshot recorded for $vol (where $($t.Live) lives)" }
+ $from = Join-Path $mounts[$vol] $t.Live.Substring(3)
+ if (-not (Test-Path -LiteralPath $from)) { Fail "$($t.Live) is not in the snapshot of $vol" }
+ $exclude = @()
+ if ($t.IsHome) { $exclude = @((Join-Path $from 'cache'), (Join-Path $t.Live 'cache')) }
+ $started = Get-Date
+ $summary = Invoke-Mirror -From $from -To $t.Live -ExcludeDirs $exclude
+ Ok "restored in $([int]((Get-Date) - $started).TotalSeconds)s"
+ $summary | ForEach-Object { Write-Host " $($_.Trim())" }
+ }
}
- else { Warn 'there was no desktop app data to restore' }
+ finally {
+ foreach ($link in $mounts.Values) { Dismount-Shadow $link }
+ }
+
+ Step 'removing the disk snapshot'
+ foreach ($s in $shadows) { Remove-Shadow $s; Ok "deleted the snapshot of $($s.Volume)" }
Remove-StaleGlobalRedirect
@@ -420,11 +547,6 @@ function Invoke-Post {
if (-not $BackupRoot) { $BackupRoot = Join-Path $env:USERPROFILE 'hermes-update-rehearsal' }
-if ($Command -ne 'help') {
- $script:Tar = Resolve-Tar
- if (-not $script:Tar) { Fail 'no usable tar.exe found; install the Windows tar or put it on PATH' }
-}
-
switch ($Command) {
'pre' { Invoke-Pre }
'post' { Invoke-Post }
@@ -438,10 +560,12 @@ switch ($Command) {
else {
Write-Host 'hermes-update-rehearsal.ps1 -- run against an EXISTING Hermes install.'
Write-Host ''
- Write-Host ' pre back up everything, then point the update source at a custom repo+ref'
- Write-Host ' post wipe both trees and restore the backup exactly as it was'
+ Write-Host ' pre back up your data, snapshot the disk, point the update source at a custom repo+ref'
+ Write-Host ' post restore both trees exactly as they were at the snapshot'
Write-Host ' status print what is prepared (read-only; nothing is touched)'
Write-Host ''
+ Write-Host 'pre and post need an elevated (Run as Administrator) PowerShell.'
+ Write-Host ''
Write-Host 'Options:'
Write-Host ' -Source URL repo to pull the update from'
Write-Host ' -Ref REV branch or tag in that repo'
diff --git a/scripts/update-test/smoke-test.ps1 b/scripts/update-test/smoke-test.ps1
index 3fde90407e2..e72fd92ec19 100755
--- a/scripts/update-test/smoke-test.ps1
+++ b/scripts/update-test/smoke-test.ps1
@@ -87,8 +87,11 @@ $env:PATH = (Split-Path -Parent $RealPython) + ';' + $env:PATH
Write-Host "python: $RealPython"
$RealGit = Find-RealGit
if ($RealGit) { $env:PATH = (Split-Path -Parent $RealGit) + ';' + $env:PATH; Write-Host "git: $RealGit" }
-# tar lives in System32; put it ahead of any WindowsApps payload on PATH.
-if ($env:SystemRoot) { $env:PATH = (Join-Path $env:SystemRoot 'System32') + ';' + $env:PATH }
+
+$id = [Security.Principal.WindowsIdentity]::GetCurrent()
+if (-not (New-Object Security.Principal.WindowsPrincipal $id).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
+ throw 'run this smoke test elevated: pre/post take a Volume Shadow Copy snapshot'
+}
$Root = Join-Path $env:LOCALAPPDATA ("Temp\rehearsal-ps-" + [guid]::NewGuid().ToString('N').Substring(0, 8))
New-Item -ItemType Directory -Force -Path $Root | Out-Null
@@ -196,7 +199,15 @@ con.close()
Set-Content -LiteralPath (Join-Path $Install '.hermes\bin\hermes.cmd') -Value "@echo off`r`necho hermes 0.0.0"
Set-Content -LiteralPath (Join-Path $Install '.hermes-runtime\python\interpreter.bin') -Value 'big'
New-Item -ItemType Directory -Force -Path (Join-Path $H 'bin') | Out-Null
- Set-Content -LiteralPath (Join-Path $H 'bin\hermes.cmd') -Value "@echo off`r`necho hermes"
+ # A fake launcher that understands `backup -o <zip>`: pre calls it for the data backup.
+ @'
+@echo off
+if /i "%~1"=="backup" if /i "%~2"=="-o" (
+ > "%~3" echo fake-zip
+ exit /b 0
+)
+echo hermes
+'@ | Set-Content -LiteralPath (Join-Path $H 'bin\hermes.cmd') -Encoding ASCII
New-Item -ItemType Directory -Force -Path (Join-Path $env:HERMES_DESKTOP_USER_DATA_DIR 'Local Storage\leveldb'), (Join-Path $env:HERMES_DESKTOP_USER_DATA_DIR 'Cache') | Out-Null
Set-Content -LiteralPath (Join-Path $env:HERMES_DESKTOP_USER_DATA_DIR 'Preferences') -Value '{"window":{}}'
@@ -218,15 +229,12 @@ try {
$r = Invoke-Rehearsal -Arguments @('pre', '-Source', $Install, '-Ref', 'main', '-BackupRoot', $Backups)
Check 'pre exits 0' ($r.Code -eq 0)
$Snap = (Get-ChildItem -LiteralPath $Backups -Directory | Sort-Object Name)[-1].FullName
- foreach ($f in @('hermes-home.tar', 'electron-userdata.tar', 'manifest.json', 'hermes-home.txt', 'target-sha')) {
+ foreach ($f in @('hermes-backup.zip', 'shadows.txt', 'manifest.json', 'hermes-home.txt', 'target-sha')) {
Check "backup artifact $f" (Test-Path -LiteralPath (Join-Path $Snap $f))
}
- $tarList = (& tar.exe -tf (Join-Path $Snap 'hermes-home.tar') | Out-String)
- Check 'whole home: checkout .git in the tar' ($tarList -match '(?m)^\./hermes-agent/\.git/config\s*$')
- Check 'whole home: PM store in the tar' ($tarList -match '(?m)^\./hermes-agent/\.hermes-runtime/python/interpreter\.bin\s*$')
- Check 'whole home: config.yaml in the tar' ($tarList -match '(?m)^\./config\.yaml\s*$')
- $udList = (& tar.exe -tf (Join-Path $Snap 'electron-userdata.tar') | Out-String)
- Check 'whole userData: nothing filtered out of the tar' ($udList -match '(?m)^\./Cache/data\.bin\s*$')
+ $ShadowIds = @(Get-Content -LiteralPath (Join-Path $Snap 'shadows.txt') | Where-Object { $_.Trim() } | ForEach-Object { ($_ -split "`t")[1] })
+ Check 'one snapshot recorded' ($ShadowIds.Count -eq 1)
+ Check 'the recorded snapshot exists' ([bool](Get-WmiObject Win32_ShadowCopy | Where-Object { $ShadowIds -contains $_.ID }))
Write-Host "`n--- pre points the install at the rehearsal copy ---"
$served = (& git -C (Join-Path $Snap 'serve.git') rev-parse refs/heads/main | Out-String).Trim()
@@ -247,6 +255,17 @@ try {
Write-Host "`n--- status (read-only) ---"
$r = Invoke-Rehearsal -Arguments @('status', '-BackupRoot', $Backups)
Check 'status reports what it prepared' ($r.Out -match [regex]::Escape($HeadSha))
+ Check 'status reports the snapshot present' ($r.Out -match 'snapshot\s+\S+ present')
+
+ Write-Host "`n--- simulate an update: modify, add and delete in both trees ---"
+ Set-Content -LiteralPath (Join-Path $H 'config.yaml') -Value 'timezone: changed-by-update'
+ Remove-Item -LiteralPath (Join-Path $H 'memories\note.md')
+ Set-Content -LiteralPath (Join-Path $Install 'added_by_update.py') -Value 'print(2)'
+ New-Item -ItemType Directory -Force -Path (Join-Path $H 'photon\sidecar\node_modules\newdep') | Out-Null
+ Set-Content -LiteralPath (Join-Path $H 'photon\sidecar\node_modules\newdep\index.js') -Value 'x'
+ Set-Content -LiteralPath (Join-Path $env:HERMES_DESKTOP_USER_DATA_DIR 'Preferences') -Value '{"window":{"changed":true}}'
+ Set-Content -LiteralPath (Join-Path $env:HERMES_DESKTOP_USER_DATA_DIR 'new-after-update.json') -Value '{}'
+ Check 'the simulated update changed HERMES_HOME' ((Get-TreeListing $H) -ne $homeBefore)
Write-Host "`n--- post ---"
$r = Invoke-Rehearsal -Arguments @('post', '-BackupRoot', $Backups, '-Yes')
@@ -267,6 +286,8 @@ try {
Check 'upstream-prompt marker removed' (-not (Test-Path -LiteralPath (Join-Path $H '.skip_upstream_prompt')))
Check 'origin resolves officially again' (((& git -C $Install remote get-url origin | Out-String).Trim()) -match 'NousResearch')
Check 'bin shim restored' (Test-Path -LiteralPath (Join-Path $H 'bin\hermes.cmd'))
+ Check 'post deleted the snapshot' (-not (Get-WmiObject Win32_ShadowCopy | Where-Object { $ShadowIds -contains $_.ID }))
+ Check 'post removed its mount link' (-not (Test-Path -LiteralPath (Join-Path $Snap 'vss-C')))
Write-Host "`n--- the acceptance criterion: every file identical before/after ---"
$homeAfter = Get-TreeListing $H
Check 'HERMES_HOME identical to before pre' ($homeAfter -eq $homeBefore)