Skip to content

The agent that grows with you

test(update): add the manual update-rehearsal kit under scripts/update-test

ethernetdab981a3a536
diff --git a/scripts/update-test/HANDOFF.md b/scripts/update-test/HANDOFF.md
new file mode 100644
index 00000000000..46aa292c1ea
--- /dev/null
+++ b/scripts/update-test/HANDOFF.md
@@ -0,0 +1,166 @@
+# Handing this off
+
+This directory is a small kit you give to someone who already runs Hermes, so
+they can point their install at a custom repo/ref, update through the normal
+update path, and put everything back afterwards.
+
+Three files matter to them: `hermes-update-rehearsal.sh` (macOS/Linux),
+`hermes-update-rehearsal.ps1` (Windows), and `PLAN.md` if they want the detail.
+`smoke-test.*` is for you, not them.
+
+---
+
+## 1. What to send
+
+Zip the directory and send it however you like (Discord, email, a gist):
+
+```bash
+cd ~/Documents && zip -r hermes-update-rehearsal.zip hermes-update-rehearsal
+```
+
+```powershell
+Compress-Archive -Path "$HOME\Documents\hermes-update-rehearsal" `
+ -DestinationPath "$HOME\Documents\hermes-update-rehearsal.zip" -Force
+```
+
+Fill these in before you send, because the recipient cannot guess them:
+
+| placeholder | meaning | example |
+|---|---|---|
+| `SOURCE` | repo their update should pull from | `https://github.com/<you>/hermes-agent.git` |
+| `REF` | branch or tag in that repo | `<your-branch>` |
+| `WHY` | one line on what you changed | "the desktop updater rewrite" |
+
+---
+
+## 1b. Or: run straight from a gist
+
+Fewer moving parts than a zip — the recipient needs nothing on disk. Put the two
+scripts in a gist, then use each file's **per-file raw URL**
+(`.../raw/<filename>`), never the gist-wide `/raw/` URL: that concatenates
+every file in the gist into one blob, so you would be piping two scripts into
+one shell.
+
+Pin the revision too, so the recipient runs the exact file you tested instead of
+whatever the gist says later:
+
+**macOS / Linux**
+
+```bash
+curl -fsSL '<RAW_URL>' | bash -s -- pre --source '<SOURCE>' --ref '<REF>'
+```
+
+**Windows**
+
+```powershell
+& ([scriptblock]::Create((irm '<RAW_URL>'))) pre -Source '<SOURCE>' -Ref '<REF>'
+```
+
+`post` is the same command with `pre` replaced by `post`.
+
+Two things worth knowing about this form:
+
+- The PowerShell one is not blocked by `-ExecutionPolicy`. That policy governs
+ files, and this never writes one.
+- Piped in, a script cannot see its own path. The "run this next" line it prints
+ therefore says `hermes-update-rehearsal.sh post --backup-root …` rather than a
+ path, plus a reminder to re-run the same one-liner. That is expected, not a
+ failure.
+
+---
+
+## 2. The message to paste
+
+> I'd like you to test a Hermes change on your install. It's reversible, but
+> please read the first paragraph before you start.
+>
+> **What this does:** it backs up your entire Hermes install, then points your
+> updater at my fork's `<REF>` instead of the official repo, so `hermes update`
+> pulls my code. Nothing is updated until *you* run `hermes update`. When you're
+> done, `post` wipes and puts your backup back.
+>
+> **What it touches:** your whole Hermes install (`HERMES_HOME`), the desktop
+> app's data, the `hermes` commands on your PATH, and one line in your global
+> git config. `post` undoes all of it. If you stop part-way, run `post` anyway —
+> don't just walk away from it.
+>
+> **Before you start:** you need `git`, `tar` and `python3` on your PATH, about
+> as much free disk as your install takes, and ~30 seconds of network. Close the
+> desktop app and any running Hermes sessions first — a running process holds
+> files the updater needs.
+>
+> If you're on Windows and `python3` is the Microsoft Store stub, install a real
+> Python first; the script will tell you if it can't find one.
+>
+> **1. Back up and point it at my code**
+>
+> ```bash
+> ./hermes-update-rehearsal.sh pre --source SOURCE --ref REF
+> ```
+>
+> (Windows: `powershell -ExecutionPolicy Bypass -File hermes-update-rehearsal.ps1 pre -Source SOURCE -Ref REF`)
+>
+> It prints where your backup went and the exact next commands. Read that output
+> — it's the source of truth rather than this message.
+>
+> **Check the block it prints at the top before it does anything.** It looks
+> like this, and it tells you which install it's about to touch:
+>
+> ```
+> === your install ===
+> HERMES_HOME ...
+> install ...
+> desktop data ...
+> backup root ...
+> ```
+>
+> It follows your `HERMES_HOME`. If you run Hermes with a profile (or a
+> non-default home) and that block shows the wrong place, stop, `export` the
+> right `HERMES_HOME`, and run `pre` again. If it's showing the wrong home,
+> `post` would restore the wrong home too.
+>
+> **2. Update and use it**
+>
+> ```bash
+> cd "$HERMES_HOME/hermes-agent" && hermes update
+> ```
+>
+> (If your install isn't in the default place, use your path. `pre` prints it.)
+> Then use Hermes normally for a bit — that's the part I actually need tested.
+> If you use the desktop app, update it from Settings → About → Update now
+> instead, so I get the app's own updater covered too.
+>
+> **3. Put it back**
+>
+> ```bash
+> ./hermes-update-rehearsal.sh post
+> ```
+>
+> Close the app first. It removes the redirect, wipes, restores your backup, and
+> reports how exactly it matched. Keep the backup folder until that looks right.
+>
+> **Send me back:** the output of all three steps, and anything that looked
+> wrong. If `post` says entries didn't match, send me that too — it's the most
+> useful thing you could find.
+
+---
+
+## 3. Before you send it
+
+- [ ] `bash smoke-test.sh` and `smoke-test.ps1` are both green. The kit's
+ restore path runs on someone else's machine; this is the only test it has.
+- [ ] `SOURCE`/`REF` actually contain the code you want tested — the script
+ defaults to the fork's `main`, so if you're testing a branch you must pass
+ `--ref`.
+- [ ] You've said out loud that the recipient's install gets rewritten, even
+ though it's reversible.
+
+## 4. After they run it
+
+- [ ] Confirm they ran `post` — a half-finished run leaves a global git-config
+ redirect behind. If they didn't, the manual undo is:
+ `git config --global --unset-all url.<SOURCE>.insteadOf` plus
+ `rm "$HERMES_HOME/.skip_upstream_prompt"`.
+- [ ] Their "nothing was lost" claim is a self-report. If it matters, have them
+ run `hermes doctor` and open the desktop app once before deleting the
+ backup.
diff --git a/scripts/update-test/PLAN.md b/scripts/update-test/PLAN.md
new file mode 100644
index 00000000000..a1307fab4fc
--- /dev/null
+++ b/scripts/update-test/PLAN.md
@@ -0,0 +1,457 @@
+# Manual update-rehearsal plan
+
+> **This directory lives outside the `hermes-agent` checkout** (it is a
+> hand-off kit for real users, not part of the repo or its CI). Paths written
+> as `tests/install/...` or `hermes_cli/...` are relative to a `hermes-agent`
+> checkout; anything without a directory prefix is a file in this directory.
+
+Goal: prove, on a real machine with a real existing install, that an existing
+user can move to **this branch's code** through each of the update surfaces
+without losing anything — and do it in a way that can later be lifted into the
+`install-e2e` job.
+
+The four proofs:
+
+| # | Proof | Surface |
+|---|---|---|
+| 1 | `install.sh` / `install.ps1` install → `hermes update` | CLI updater |
+| 2 | desktop installer install → the app's own update mechanism | desktop app |
+| 3 | an install **with a plugin installed** (mnemosyne) keeps the plugin | plugin survival |
+| 4 | an install with the **photon sidecar** keeps the sidecar | sidecar survival |
+
+Desktop app **bundles** (`Hermes-Setup.dmg`/`.exe` → packaged `.app`/MSIX and
+electron-updater feeds) are explicitly out of scope. This plan is about source
+installs and the source-install desktop app.
+
+---
+
+## 1. The load-bearing finding: the redirect must be transport-level
+
+"Make the install see my fork's main as canonical **without** seeing it as a
+fork" is not cosmetic. It is required for the update to work at all:
+
+* `hermes update` on a source install resolves its update channel from R2
+ (`hermes-assets.nousresearch.com/releases/channels/<channel>.json`) through
+ `hermes_cli/source_releases.py::resolve_source_target`.
+* That read validates the channel record's `repository` against
+ `source_repository()`, which is derived from
+ **`git config --get remote.origin.url`**.
+* A channel record is bound to `NousResearch/hermes-agent`. If `origin` is
+ literally a fork URL, resolution dies with *"Channel repository does not
+ match this source installation"* / *"Could not resolve the main source
+ channel"* and **no update is applied**.
+
+So the fork code has to arrive over a channel whose *configured* origin URL is
+still the official one. Two independent git readers are involved and they do
+**not** agree about URL rewriting:
+
+| Reader | Used for | `url.<x>.insteadOf` rewriting |
+|---|---|---|
+| `git config --get remote.origin.url` | `source_repository()` → channel resolution | **not** rewritten (raw value) |
+| `git remote get-url origin` | `_get_origin_url()` → `_is_fork()` | **is** rewritten |
+
+(git's `insteadOf` is a transport rewrite: `remote get-url` applies it,
+`config --get` does not.)
+
+Therefore:
+
+* A **`url.<rehearsal-source>.insteadOf <official>`** entry in the tester's
+ **global** git config sends all fetches to the rehearsal source while channel
+ resolution still sees the official repository. The updater's own git calls
+ run with the ambient environment (`update_cmd._git_run` → `_no_prompt_git_kwargs`
+ copies `os.environ`), so global config is honoured. Hermes's *read-only*
+ internal probes (`source_check.source_git_env`) set `GIT_CONFIG_GLOBAL` to
+ `/dev/null`, so the redirect cannot corrupt them — and `config --get` is
+ unaffected anyway.
+* The one side effect is `_is_fork()` returning true (because `remote get-url`
+ is rewritten), which prints an *"Updating from fork"* banner and offers the
+ upstream-sync prompt. The scripts neutralise that with
+ `$HERMES_HOME/.skip_upstream_prompt` (which `_should_skip_upstream_prompt()`
+ honours), and offer an opt-in **git shim** (`--with-git-shim`) that makes
+ `remote get-url origin` report the official URL — the exact trick the CI
+ drivers use (`tests/install/e2e-assets/installer-common.sh::arm_source_redirect`,
+ `tests/install/windows-e2e.ps1::Set-GitRedirect`).
+
+This is why the scripts do not simply repoint `origin`.
+
+### Where the code comes from
+
+Two modes:
+
+* **`--mode local` (default, recommended).** A bare clone of the install's own
+ checkout, `serve.git`, with `main` parked at the target commit; the redirect
+ points at `file://…/serve.git`. No fork mutation, no network, reproducible,
+ and byte-for-byte the mechanism the e2e drivers already use. Advance
+ `serve.git`'s `main` between runs to re-test "an update is available".
+* **`--mode fork`.** The redirect points at the fork over the network and the
+ fork's `main` must already be the code under test. Literal reading of "my
+ fork's main", at the cost of requiring the push and the network.
+
+---
+
+## 2. The scripts
+
+`hermes-update-rehearsal.sh` (macOS/POSIX) and `hermes-update-rehearsal.ps1`
+(Windows) are mirrors of each other and share one subcommand set:
+
+| Subcommand | Does |
+|---|---|
+| `pre` | Snapshot everything below into a timestamped dir outside `$HERMES_HOME`, then fetch the custom repo + ref and point the install's update source at it. Creates nothing else, changes nothing else, and judges nothing. |
+| `post` | Remove the redirect, wipe, and put the backup back. Reports how exact the restore was (informational, never a failure). Destructive; needs `--yes`. |
+| `status` | Print what is prepared and which backup root is in play. Read-only. |
+
+There is no `verify` verb on purpose. This tool is for handing to a real user:
+`pre` reports what it did and prints the next commands, and the user decides
+whether the update worked. A script that graded their install would be wrong
+about as often as it was right, and would invite arguing with it instead of
+looking at Hermes. The assertions live in CI instead — see §8.
+
+`pre` is deliberately the only place network is needed: it clones the rehearsal
+source into `serve.git` inside the backup dir, so the update itself is served
+from local disk.
+
+### What `pre` captures
+
+Everything lands in `~/hermes-update-rehearsal/<UTC timestamp>/` (override with
+`--backup-root`). Keep it off the same volume if you can — the copy is the size
+of the install, and `pre` reports how long it took.
+
+1. **The entire `$HERMES_HOME`** → `hermes-home.tgz`. No excludes: the
+ `hermes-agent/` checkout, the venv/PM store, `node_modules`, `.git` and all
+ runtime state come with it, so a restore is a true rollback rather than a
+ re-download. SQLite sidecars (`-wal`/`-shm`/`-journal`) travel **with** their
+ `db` on purpose: a raw copy of db+wal+shm is a consistent SQLite state, and
+ it is only pairing a *checkpointed* copy with a stale wal that tears
+ (`hermes_cli/backup.py` excludes them because it snapshots via
+ `sqlite3.backup()`; a plain copy does not). Expect the archive to be as large
+ as the install and the copy to take minutes.
+2. **The checkout's git facts** → `checkout.txt` (HEAD, branch, stash count),
+ `remotes.txt` (`name<TAB>url`, from `config --get`, not `remote -v`), and the
+ checkout's local `.git/config`. These are *assertion* inputs for `verify`,
+ not a restore mechanism — the tar already carries `.git`.
+3. **Electron userData** → `electron-userdata.tgz`.
+ `HERMES_DESKTOP_USER_DATA_DIR` when set, else the platform default
+ (`~/Library/Application Support/Hermes`, `%APPDATA%\Hermes`) plus
+ `HERMES_DATA_DIR_SUFFIX`.
+4. **The `hermes` shims on PATH** → `shims/` plus `shims.txt` and
+ `shims-links.txt` (symlink targets preserved). POSIX: `$HOME/.local/bin`,
+ `<root>/bin`, `/usr/local/bin`, and the checkout's `.hermes/bin`. Windows:
+ the checkout's `.hermes\bin`, `<home>\bin` (where `install.ps1` publishes and
+ wires the USER PATH), and `~\.local\bin`.
+5. **The USER PATH value** (Windows) → `user-path-before.txt`, so a restore puts
+ back the `PATH` entry that exposes `<home>\bin`. A blank record is left alone
+ rather than written — an empty value would wipe the user's PATH.
+6. **Global git config** → `gitconfig.bak`, plus the redirect entries `arm`
+ adds, recorded for exact removal.
+7. **Two fingerprints** the update must not move: `fingerprint-before.txt`
+ (curated durable state: `config.yaml`, `.env`, `auth.json`, `state.db`,
+ `memories/`, `skills/`, `cron/`, `plugins/`, `profiles/`, `photon/`,
+ `desktop-plugins/`, `tui-widgets/`, `skins/`, `pets/`, `sessions/`) and
+ `userdata-before.txt`. `state.db` is fingerprinted by **row counts**
+ (`sessions`/`messages`/`usage`/`cron_jobs`), never by bytes — a byte hash of
+ a live SQLite database changes for benign reasons and would make `verify`
+ meaningless.
+8. **Nothing else.** The tool does not seed fixtures, install plugins, or
+ script any user action: everything it protects is whatever the user's own
+ install already has.
+
+The fingerprints exist for one purpose: after `post` restores, it re-computes
+them and tells the user how exact the restore was. They are a *restore-fidelity*
+report, never a verdict on the update.
+
+---
+
+## 3. Preconditions
+
+* A machine you can afford to lose. `tests/install/README.md` says the CI
+ drivers are destructive, and so is this: it will run a real update against a
+ real install, then wipe and restore. A VM or a second user account is better
+ than your daily driver.
+* A **real** install that a user could plausibly have:
+ * installed by `install.sh` / `install.ps1` (`~/.hermes/hermes-agent` or
+ `%LOCALAPPDATA%\hermes\hermes-agent`), on a released tag, not a dev
+ checkout;
+ * the desktop app present (built by `--include-desktop` / `-IncludeDesktop`,
+ or the packaged app) for scenario 2;
+ * a plugin installed for scenario 3 (see below);
+ * the photon sidecar installed for scenario 4.
+* Quiesce first: no gateway, no desktop app, no `hermes` session running. On
+ Windows, `hermes update` refuses to mutate a venv that other processes hold.
+* Network access to `hermes-assets.nousresearch.com` for channel resolution.
+ `preflight` checks it and warns (it cannot be faked without a hosts entry).
+
+### Fixtures for scenarios 3 and 4
+
+* **Plugin (mnemosyne).** Install it the way a user does — `memory.provider`
+ from the mnemosyne distribution's documented path — or, for a cheaper
+ rehearsal, seed the shape CI asserts and the plugin scanner recurses into:
+ `$HERMES_HOME/plugins/mnemosyne-wrapper/{plugin.yaml,mnemosyne-wrapper.json}`
+ plus a symlinked runtime and an externally-owned sidecar witness file
+ outside the home. `tests/install/e2e-assets/verify-plugin-preservation.py seed
+ --home <home> --external <path>` creates exactly that fixture.
+* **Photon sidecar.** `hermes photon install-sidecar` (or just let it install
+ on first use), then confirm `$HERMES_HOME/photon/sidecar/node_modules` and
+ `node_modules/.package-lock.json` exist. If you use `PHOTON_SIDECAR_DIR`, also
+ record that path — it is the override branch of `resolve_sidecar_dir`.
+
+---
+
+## 4. Scenarios
+
+Each scenario is: `pre` → *update normally, the way a user would, and use
+Hermes* → `post`.
+
+### Scenario 1 — source install, `hermes update`
+
+```bash
+./hermes-update-rehearsal.sh pre --ref <branch>
+# user path, from a plain shell:
+cd "$HERMES_HOME/hermes-agent" && hermes update
+# use Hermes, poke at whatever you need, then:
+./hermes-update-rehearsal.sh post
+```
+
+`pre` prints the exact two commands to run — copy them rather than retyping.
+
+Expected `hermes update` output: `→ Update channel: main`, `→ Fetching
+updates...`, `→ Found N new commit(s)`, `✓ Code updated!`, dependency sync,
+then the completion line with the old→new version transition. It may also print
+`⚠ Updating from fork`, because the redirect is a transport-level rewrite that
+`git remote get-url origin` sees but `git config --get` does not. That banner is
+cosmetic: channel resolution (which reads the configured URL) still resolves
+normally, which is the part that matters and the part with no workaround.
+
+### Scenario 2 — the desktop app's update mechanism
+
+Same, but let the **app** drive the update instead of the shell:
+
+1. Launch the installed desktop app as a user does (the packaged/installed
+ entry point, or `hermes desktop`).
+2. Settings → About → **Update now**.
+3. Wait for the app to report completion and relaunch.
+4. Use Hermes, then `post`.
+
+A GUI-launched app inherits the **global git config** — which is exactly why the
+redirect lives there and not in a shell-only `PATH` shim. The
+`.skip_upstream_prompt` marker is a file on disk, so it is inherited either way.
+`post` reports separately whether the desktop app's userData came back
+byte-for-byte, so you can see whether `connection.json` and window state
+survived.
+
+### Scenario 3 — plugin survival
+
+Run scenario 1 or 2 on an install that has a plugin. There is no fixture to
+install: if the plugin is on the install, whatever it wrote under
+`$HERMES_HOME/plugins/**` or `profiles/<name>/plugins/**` is in the backup, and
+`post`'s fingerprint report will show if anything under those trees did not come
+back. (The strict delete/modify contract for plugin trees runs in CI, where the
+baseline is reproducible — see §8.)
+
+### Scenario 4 — photon sidecar survival
+
+Same shape. Everything under `$HERMES_HOME/photon/` is inside the whole-home
+backup, including the sidecar's `node_modules` and its
+`node_modules/.package-lock.json` marker, so `post` restores it and reports
+whether it matched. If `PHOTON_SIDECAR_DIR` points outside the home, that tree
+is outside the backup too — back it up yourself before you start.
+
+---
+
+## 5. The preservation contract (enforced in CI)
+
+The scripts verify nothing. `pre` captures and points; `post` restores and
+reports how exact the restore was. The contract they exist to demonstrate is
+asserted in CI, on every upgrade leg, by
+`e2e-assets/verify-user-state.py` (user state) and
+`e2e-assets/verify-plugin-preservation.py` (plugin trees):
+
+1. `state.db` does not lose rows. Bytes are deliberately **not** compared — a
+ live SQLite file changes for benign reasons, so a byte hash would either
+ always fail or prove nothing.
+2. No deletion or byte change under `.env`, `auth.json`, `gateway_state.json`,
+ `memories/`, `cron/`, `sessions/`, `profiles/`, `photon/`,
+ `desktop-plugins/`, `tui-widgets/`, `skins/`, `pets/`, or
+ `skills/.archive/`. `config.yaml` may be rewritten (additive migration) and
+ the bundled `skills/` tree may be re-synced by the product — both are
+ reported, neither fails.
+3. Plugin trees survive under the separate plugin contract (anything deleted or
+ modified fails; added files are tolerated).
+4. The redirect stayed transport-level: `git config --get remote.origin.url` is
+ still the official URL while `git remote get-url origin` is the redirected
+ one. If the configured URL ever looked like the rehearsal source, channel
+ resolution would fail and the leg would not be testing the real user path.
+5. The user-visible launcher still exists and still runs after the upgrade — and
+ on Windows, `<home>\bin` is still on the USER PATH.
+
+Two things the CI checker does **not** cover, so they stay manual here: the
+desktop app's Electron userData (only meaningful where the app is installed and
+`desktop-smoke.ts` treats that dir as its own sandbox), and
+`PHOTON_SIDECAR_DIR` when it points outside `$HERMES_HOME` (outside the backup,
+by definition).
+
+---
+
+## 6. Undo: `post`
+
+`post` is one verb because the two halves must not be separable: removing the
+redirect and putting the state back have to happen together or the install is
+left in a state neither the user nor the script can reason about. Because the
+backup is the whole home, the restore is a true rollback — the checkout, venv,
+PM store and `node_modules` come back with it, not just the config.
+
+`post` does:
+
+1. Remove the redirect entries from the global git config and restore that file
+ from `gitconfig.bak`.
+2. Delete `$HERMES_HOME/.skip_upstream_prompt`.
+3. Put the Windows USER PATH value back from `user-path-before.txt` (left
+ untouched when the record is blank — an empty record must never wipe PATH),
+ and restore the `hermes` launcher shims.
+4. Stop the desktop app and the gateway.
+5. Delete `$HERMES_HOME`, the Electron userData dir, and the recorded shim files.
+6. Extract `hermes-home.tgz` into `$HERMES_HOME` and `electron-userdata.tgz`
+ into the userData dir.
+7. Restore the shims (files from `shims/`, symlinks from `shims-links.txt`).
+8. Re-fingerprint and compare against the pre-`pre` fingerprints, then report
+ how many entries matched. A non-empty diff is reported plainly and does not
+ fail — it is information for the tester, not a verdict.
+
+Then: open the desktop app once, run `hermes doctor`, confirm the gateway
+starts, and keep the snapshot directory until that passes.
+
+---
+
+## 7. Testing the scripts themselves
+
+Both scripts have a smoke test that builds a synthetic install in a temp tree
+and drives every subcommand for real: `pre` (the whole-home backup, the
+fingerprint, the fetch into `serve.git`, `main` parked at the right commit, the
+two `insteadOf` entries, the marker, and that the redirect is visible to
+`git remote get-url` while `git config --get` still reports the official URL),
+then `post` (redirect gone, marker gone, and every artefact back). The bash one
+also asserts `pre` left the checkout byte-identical, which is the mechanical
+half of "`pre` asserts nothing and changes nothing".
+
+```bash
+bash smoke-test.sh # macOS/Linux
+powershell -ExecutionPolicy Bypass -File smoke-test.ps1
+```
+
+The bash one also runs under git-bash on Windows (it normalises paths with
+`cygpath` and, where GNU tar is in play, needs `TAR_OPTIONS=--force-local` — the
+smoke test sets that itself). Two assertions self-skip on a host that cannot
+create symlinks (Windows without developer mode).
+
+Known tooling traps these hit, worth knowing before you edit either script:
+
+* **`url.<base>.insteadOf` is multi-valued.** Writing it with plain
+ `git config` replaces the existing value, so the second official URL silently
+ drops the first and the redirect covers only one form. Use `--add`, and
+ `--unset-all` to remove.
+* **`file://C:/x` parses as host `C:`.** A drive-letter path needs
+ `file:///C:/x`.
+* **`git remote get-url` applies the rewrite; `git config --get` does not.** Use
+ `config --get` for anything asserting "the remote did not change".
+* **GNU tar reads `C:/x` as `host:path`.** Needs `--force-local` (macOS bsdtar
+ does not, and does not need it).
+* **`cmd | grep -q` under `pipefail` is a SIGPIPE race** — capture, then grep.
+* **Windows PowerShell 5.1 reads a BOM-less `.ps1` as ANSI**, so a UTF-8 em-dash
+ breaks string parsing. `hermes-update-rehearsal.ps1` is ASCII-only for that
+ reason.
+* **A PATH that points into a `WindowsApps` payload cannot be launched by
+ Windows PowerShell** (`Access is denied`). The bundled Hermes app puts its
+ whole toolchain there, so on such a host both the Store `python` alias and the
+ payload `git` are unusable from PowerShell. The Windows script skips those
+ candidates and prefers the install's own venv/PM-store interpreter; a host like
+ that needs a normal `Git\cmd` and a real venv python ahead of the payload on
+ PATH before either script will work.
+* **`state.db` must be compared by row counts, not bytes.** A live SQLite file
+ changes for benign reasons.
+
+---
+
+## 8. What was added to the CI drivers
+
+The assertion layer moved; the harness did not. `wipe`/`restore` and the backup
+tar have no home in CI (the runner is disposable), and `pre`/`post` stay manual.
+What landed:
+
+* `e2e-assets/verify-user-state.py` — the shared, read-only, stdlib-only
+ snapshot/verify checker for the user's own durable state. It has **no** `seed`
+ mode: the state it defends is produced by the product, never written by the
+ harness. `state.db` is compared by row counts. The bundled `skills/` tree is
+ recorded but never judged (the product re-syncs it); `skills/.archive/` is
+ judged. `plugins/**` is deliberately **not** scanned — that contract belongs
+ to `verify-plugin-preservation.py`, and double-owning a tree makes two
+ verifiers disagree later.
+* `e2e-assets/user-state-actions.sh` — produces that state through the ordinary
+ CLI (`hermes chat -q`, `hermes auth add`, `hermes profile create`), probing
+ `--help` for each flag per the harness's "probe, do not assume" rule, and
+ asserting each action actually landed so a leg cannot pass while testing
+ nothing.
+* `e2e-assets/preserve-user-state.sh` — the POSIX/macOS hook pair, called at the
+ same two points as `preserve-plugins.sh` (`before_upgrade` after the install
+ phase's checks, `after_upgrade` right after the post-update checkout
+ assertion and *before* the new-side desktop checkpoint, so the window
+ contains only the upgrade).
+* `tests/install/windows-e2e.ps1` — `Invoke-UserStateActions` in the install
+ phase (reusing `Start-DesktopJourneyMock` so the leg has a genuinely
+ configured provider), `Invoke-UserStateSnapshot` in the update phase
+ immediately before `serve.git`'s `main` advances, and
+ `Invoke-UserStateVerify` + `Assert-UserShims` after `Test-HermesRuns`.
+* Two invariants in both drivers: `Assert-RedirectIsTransportOnly` (configured
+ origin stays official while the transport URL is redirected) and
+ `Assert-UserShims` (the launcher still runs; Windows: `<home>\bin` is still
+ on the USER PATH).
+* `tests/scripts/test_verify_user_state.py` — 16 tests over a real temp
+ filesystem with real sqlite databases. These are the tests that keep the
+ allowlist honest: `config.yaml` rewrites pass, a state.db size change is not
+ loss, row loss is, a bundled-skill rewrite is advisory-only, and `plugins/**`
+ is not judged here at all.
+
+Deliberately **not** done: these scripts live outside the repo, so they cannot be
+wired into `installer-tests.yml` from here. If that is ever wanted, they have to
+move back under `tests/install/manual/` — which also means adding that path to
+`_INSTALLER_PATHS` in `scripts/ci/classify_changes.py` (the lane is
+installer-gated, so it would change which PRs spin up a Windows runner), plus
+pwsh 5.1 / 7 and one `shell: bash` step in
+`.github/workflows/installer-tests.yml`. Keeping them out is why they can stay a
+plain hand-off kit instead of a maintained CI lane.
+
+Also not covered: a real plugin install (`hermes plugins install …`, network) and
+the photon sidecar (`npm ci`) — both need the network and a real package, and
+the risk surface *is* the `node_modules` mirror, which a fixture would not
+exercise honestly. They belong on a low-frequency leg when someone wants them.
+
+---
+
+## 9. Risks and gotchas
+
+* **`hermes update` legitimately writes to `$HERMES_HOME`.** Config migration
+ rewrites `config.yaml` (additively), pre-update backups land in `backups/`
+ and `state-snapshots/`, `state.db` may be re-created and restored, and
+ migrations can touch sibling profile configs. The CI checker treats those as
+ allowed; its snapshot diff is what keeps "allowed" honest.
+* **Desktop app rebuild.** The update rebuilds `apps/desktop`. That is slow and
+ needs Node; a failed build is a real update failure, not a rehearsal artifact.
+* **Windows venv holders.** Any process running from the install's venv blocks
+ the dependency sync (`--force-venv` exists and is a trap). Close the app and
+ the gateway first.
+* **The `.skip_upstream_prompt` marker is our addition, not a user's.** Record
+ it as prepared state so `post` removes it; leaving it behind would suppress a
+ prompt a real fork user should see.
+* **There is deliberately no `git` shim.** An earlier draft put a wrapper `git`
+ on PATH that returned the rewritten remote for one subcommand; it was
+ dropped. A second `git` on PATH is exactly the kind of thing that confuses
+ the *next* thing you debug, and the redirect already makes the update pull
+ the custom source. The `⚠ Updating from fork` banner is the price, and it is
+ cosmetic — the code path that matters reads the configured URL.
+* **R2 channel resolution is network-bound and out of our control.** If
+ `main.json` is unreachable or its `repository`/delivery shape changes,
+ `hermes update` fails before any git work. `pre` cannot pre-empt that — it
+ never talks to the channel — so if the update dies that early, that is the
+ first thing to check.
+* **Nothing is served from the real fork, so nothing needs unwinding there.**
+ `pre` clones `--source`/`--ref` into a bare `serve.git` inside the backup dir
+ and redirects to that, so the update never reads or writes the fork itself.
+ The only repair the fork could ever need is if someone pushed to it by hand.
diff --git a/scripts/update-test/hermes-update-rehearsal.ps1 b/scripts/update-test/hermes-update-rehearsal.ps1
new file mode 100755
index 00000000000..ffb6709664f
--- /dev/null
+++ b/scripts/update-test/hermes-update-rehearsal.ps1
@@ -0,0 +1,781 @@
+<#
+.SYNOPSIS
+ hermes-update-rehearsal.ps1 -- for an EXISTING Hermes install (Windows).
+
+.DESCRIPTION
+ Two steps:
+
+ pre back up everything, then point the install's update source at a
+ custom repo + ref so `hermes update` pulls it. Prints what to do next.
+ post undo all of it: remove the redirect, wipe, and restore the backup.
+
+ 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.
+
+ Read PLAN.md (next to this script) first.
+
+.PARAMETER Command
+ pre | post | status
+
+.PARAMETER Source
+ Repo to pull the update from (default: the rehearsal fork).
+
+.PARAMETER Ref
+ Branch or tag in that repo (default: main).
+
+.PARAMETER BackupRoot
+ Where the backup lives (default: $HOME\hermes-update-rehearsal).
+
+.PARAMETER Yes
+ post: skip the confirmation.
+
+.EXAMPLE
+ ./hermes-update-rehearsal.ps1 pre --source <git-url> --ref <branch>
+ # ... run `hermes update`, use Hermes, test ...
+ ./hermes-update-rehearsal.ps1 post
+
+.NOTES
+ The backup is the ENTIRE HERMES_HOME plus the desktop app's Electron userData,
+ the `hermes` shims on PATH, your USER PATH value, and your global git config.
+ `pre` needs network access to -Source and a usable git on PATH.
+#>
+[CmdletBinding()]
+param(
+ [Parameter(Position = 0)]
+ [ValidateSet('pre', 'post', 'status', 'help')]
+ [string]$Command = 'help',
+
+ [string]$Source = 'https://github.com/ethernet8023/hermes-agent.git',
+ [string]$Ref = 'main',
+ [string]$BackupRoot,
+ [switch]$Yes
+)
+
+$ErrorActionPreference = 'Stop'
+Set-StrictMode -Version 2.0
+
+$OfficialHttps = 'https://github.com/NousResearch/hermes-agent.git'
+$OfficialSsh = '[email protected]:NousResearch/hermes-agent.git'
+
+# The durable state `post` reports on after restoring. Regenerable trees
+# (caches, logs, dependency dirs) are deliberately absent, and `skills/` is
+# reported but never judged: the product syncs the bundled library into it on
+# startup and after every update, so it changes legitimately.
+$DurableTop = @('config.yaml', '.env', 'auth.json', 'state.db', 'gateway_state.json',
+ 'memories', 'skills', 'cron', 'plugins', 'photon', 'desktop-plugins',
+ 'tui-widgets', 'skins', 'pets', 'sessions', 'profiles')
+
+$SkipDirs = @('node_modules', '.venv', 'venv', 'site-packages', '__pycache__', '.git',
+ '.cache', '.tox', '.nox', '.pytest_cache', '.mypy_cache', '.ruff_cache',
+ 'backups', 'state-snapshots', 'checkpoints', 'hermes-agent',
+ 'browser-profiles', 'browser-profile', 'models', 'runtimes', 'node')
+$SkipSuffixes = @('.pyc', '.pyo', '.db-wal', '.db-shm', '.db-journal')
+
+$script:Snap = ''
+$script:Armed = ''
+$script:Tar = $null
+$script:DbCountPy = $null
+$script:LastGitExit = $null
+
+function Say { param([string]$m) Write-Host $m }
+function Ok { param([string]$m) Write-Host " OK $m" }
+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 { }
+ }
+ return $null
+}
+
+# ---------------------------------------------------------------------------
+# paths
+# ---------------------------------------------------------------------------
+
+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_) }
+ }
+ else {
+ $base = if ($env:LOCALAPPDATA) { $env:LOCALAPPDATA } else { Join-Path $userProfile 'AppData\Local' }
+ $home_ = "$(Join-Path $base 'hermes')$suffix"
+ }
+ $parent = Split-Path -Parent $home_
+ if ((Split-Path -Leaf $parent) -ieq 'profiles') { $root = Split-Path -Parent $parent } else { $root = $home_ }
+ $install = Join-Path $home_ 'hermes-agent'
+ if ($env:HERMES_DESKTOP_USER_DATA_DIR) {
+ $ud = $env:HERMES_DESKTOP_USER_DATA_DIR
+ try { $ud = (Resolve-Path -LiteralPath $ud -ErrorAction Stop).Path }
+ catch { $ud = [IO.Path]::GetFullPath($ud) }
+ $userData = $ud
+ $userDataSource = 'env'
+ }
+ else {
+ $appData = if ($env:APPDATA) { $env:APPDATA } else { Join-Path $userProfile 'AppData\Roaming' }
+ $userData = Join-Path $appData "Hermes$suffix"
+ $userDataSource = 'default'
+ }
+ # install.ps1 publishes into <home>\bin and wires the USER PATH to it; the
+ # store/venv launchers live in the checkout's .hermes\bin.
+ $shims = @(
+ (Join-Path $install '.hermes\bin\hermes.exe'), (Join-Path $install '.hermes\bin\hermes.cmd'),
+ (Join-Path $install '.hermes\bin\hermes-acp.exe'), (Join-Path $install '.hermes\bin\hermes-acp.cmd'),
+ (Join-Path $home_ 'bin\hermes.exe'), (Join-Path $home_ 'bin\hermes.cmd'),
+ (Join-Path $home_ 'bin\hermes-acp.exe'), (Join-Path $home_ 'bin\hermes-acp.cmd'),
+ (Join-Path $userProfile '.local\bin\hermes'), (Join-Path $root 'bin\hermes.exe'),
+ (Join-Path $root 'bin\hermes.cmd')
+ )
+ return [pscustomobject]@{
+ Home = $home_; Root = $root; Install = $install
+ UserData = $userData; UserDataOrigin = $userDataSource; Shims = $shims
+ }
+}
+
+function Get-UserPathValue {
+ try { return [Environment]::GetEnvironmentVariable('Path', 'User') } catch { return $null }
+}
+
+function Get-LatestSnapshot {
+ if (-not (Test-Path -LiteralPath $BackupRoot)) { return $null }
+ $dirs = Get-ChildItem -LiteralPath $BackupRoot -Directory -ErrorAction SilentlyContinue | Sort-Object Name
+ if (-not $dirs) { return $null }
+ return $dirs[-1].FullName
+}
+
+function Load-Snapshot {
+ $snap = Get-LatestSnapshot
+ if (-not $snap) { Fail "no backup found under $BackupRoot -- run 'pre' first" }
+ $script:Snap = $snap
+ $script:Armed = Join-Path $snap 'armed'
+ $manifestPath = Join-Path $snap 'manifest.json'
+ if (-not (Test-Path -LiteralPath $manifestPath)) { Fail "$snap is not a rehearsal backup (no manifest.json)" }
+ $manifest = Get-Content -LiteralPath $manifestPath -Raw | ConvertFrom-Json
+ $P = Get-ResolvedPaths
+ if ($manifest.hermes_home -ne $P.Home) {
+ Fail "that backup belongs to HERMES_HOME=$($manifest.hermes_home), not $($P.Home); pass -BackupRoot to pick the right one"
+ }
+ return $manifest
+}
+
+# ---------------------------------------------------------------------------
+# git helpers (stdout only: merging stderr folds git warnings into the value)
+# ---------------------------------------------------------------------------
+
+function Invoke-Git {
+ param($P, [string[]]$GitArgs)
+ $prev = $ErrorActionPreference
+ $ErrorActionPreference = 'Continue'
+ try {
+ $out = & git -C $P.Install @GitArgs 2>$null
+ $script:LastGitExit = $LASTEXITCODE
+ }
+ finally { $ErrorActionPreference = $prev }
+ return (($out | Out-String) -replace "`r", '').Trim()
+}
+
+function Get-GitConfigValue {
+ param($P, [string]$Key)
+ $prev = $ErrorActionPreference
+ $ErrorActionPreference = 'Continue'
+ try {
+ $out = & git -C $P.Install config --get $Key 2>$null
+ if ($LASTEXITCODE -ne 0) { return '' }
+ }
+ finally { $ErrorActionPreference = $prev }
+ return (($out | Out-String) -replace "`r", '').Trim()
+}
+
+function Invoke-GitCmd {
+ param([string[]]$GitArgs)
+ $prev = $ErrorActionPreference
+ $ErrorActionPreference = 'Continue'
+ try { & git @GitArgs 2>$null } finally { $ErrorActionPreference = $prev }
+}
+
+# ---------------------------------------------------------------------------
+# fingerprints (used only to report how exact a restore was)
+# ---------------------------------------------------------------------------
+
+function Find-SqlitePython {
+ param($P)
+ $cands = @(
+ (Join-Path $P.Install 'venv\Scripts\python.exe'),
+ (Join-Path $P.Install '.venv\Scripts\python.exe')
+ )
+ $store = Get-ChildItem -LiteralPath (Join-Path $P.Install '.hermes-runtime\tools') -Directory -ErrorAction SilentlyContinue |
+ Where-Object { $_.Name -like 'python-*' }
+ foreach ($s in $store) { $cands += (Join-Path $s.FullName 'python.exe') }
+ $cands += (Get-Command python.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source)
+ foreach ($c in $cands) {
+ if (-not $c) { continue }
+ # The Store alias resolves to a stub PowerShell cannot launch.
+ if ($c -like '*\Microsoft\WindowsApps\*') { continue }
+ if (Test-Path -LiteralPath $c) {
+ try { & $c -c 'import sqlite3' 2>&1 | Out-Null; if ($LASTEXITCODE -eq 0) { return $c } }
+ catch { }
+ }
+ }
+ return $null
+}
+
+function Get-DbCountsPythonPath {
+ # A temp FILE, not `-c`: a multi-line -c argument gets reshaped by
+ # PowerShell's native-argument handling and fails to parse.
+ if (-not $script:DbCountPy) {
+ $script:DbCountPy = Join-Path ([IO.Path]::GetTempPath()) 'hermes-rehearsal-dbcount.py'
+ @'
+import sqlite3, sys
+try:
+ con = sqlite3.connect("file:" + sys.argv[1].replace("\\", "/") + "?mode=ro", uri=True)
+ tables = {r[0] for r in con.execute("SELECT name FROM sqlite_master WHERE type='table'")}
+ parts = [f"{t}={con.execute('SELECT COUNT(*) FROM ' + t).fetchone()[0]}"
+ for t in sorted(tables & {"sessions", "messages", "usage", "cron_jobs"})]
+ con.close()
+ print(";".join(parts) if parts else "")
+except Exception:
+ print("")
+'@ | Set-Content -LiteralPath $script:DbCountPy -Encoding ASCII
+ }
+ return $script:DbCountPy
+}
+
+function Get-DbCounts {
+ param([string]$Python, [string]$DbPath)
+ if (-not $Python) { return $null }
+ $prog = Get-DbCountsPythonPath
+ try {
+ $out = & $Python $prog $DbPath 2>$null
+ if ($LASTEXITCODE -ne 0) { return $null }
+ }
+ catch { return $null }
+ $text = ($out | Out-String).Trim()
+ if ($text) { return $text }
+ return $null
+}
+
+function Get-RelForward {
+ param([string]$Root, [string]$Path)
+ return $Path.Substring($Root.Length).TrimStart('\', '/').Replace('\', '/')
+}
+
+function Add-TreeEntries {
+ param([string]$Root, [string]$Dir, $Lines, [string]$Python)
+ $stack = New-Object System.Collections.Stack
+ $stack.Push($Dir)
+ while ($stack.Count -gt 0) {
+ $cur = $stack.Pop()
+ $kept = @()
+ foreach ($it in @(Get-ChildItem -LiteralPath $cur -Force -ErrorAction SilentlyContinue)) {
+ $rel = Get-RelForward -Root $Root -Path $it.FullName
+ if ($it.PSIsContainer) {
+ if ($SkipDirs -contains $it.Name) { continue }
+ if ($it.Attributes -band [IO.FileAttributes]::ReparsePoint) {
+ $Lines.Add("link`t$rel`t$($it.Target)") # record, never descend
+ continue
+ }
+ $kept += $it
+ }
+ else {
+ $skip = $false
+ foreach ($sfx in $SkipSuffixes) { if ($it.Name.EndsWith($sfx)) { $skip = $true; break } }
+ if ($skip) { continue }
+ if ($it.Name -eq 'state.db') {
+ $counts = Get-DbCounts -Python $Python -DbPath $it.FullName
+ if ($counts) { $Lines.Add("db`t$counts`t$rel") }
+ else { $Lines.Add("file`t$rel`t$((Get-FileHash -LiteralPath $it.FullName -Algorithm SHA256).Hash.ToLower())") }
+ }
+ else {
+ $Lines.Add("file`t$rel`t$((Get-FileHash -LiteralPath $it.FullName -Algorithm SHA256).Hash.ToLower())")
+ }
+ $kept += $it
+ }
+ }
+ if ($kept.Count -eq 0) { $Lines.Add("dir`t" + (Get-RelForward -Root $Root -Path $cur)) }
+ foreach ($k in $kept) { if ($k.PSIsContainer) { $stack.Push($k.FullName) } }
+ }
+}
+
+function Get-TreeFingerprint {
+ param($P, [string]$Out)
+ $python = Find-SqlitePython $P
+ $lines = New-Object System.Collections.Generic.List[string]
+ foreach ($entry in $DurableTop) {
+ $topPath = Join-Path $P.Home $entry
+ if (-not (Test-Path -LiteralPath $topPath)) { continue }
+ $item = Get-Item -LiteralPath $topPath -Force
+ if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) {
+ $lines.Add("link`t$entry`t$($item.Target)"); continue
+ }
+ if ($item.PSIsContainer) {
+ $lines.Add("dir`t$entry")
+ Add-TreeEntries -Root $P.Home -Dir $topPath -Lines $lines -Python $python
+ }
+ elseif ($item.Name -eq 'state.db') {
+ $counts = Get-DbCounts -Python $python -DbPath $item.FullName
+ if ($counts) { $lines.Add("db`t$counts`t$entry") }
+ else { $lines.Add("file`t$entry`t$((Get-FileHash -LiteralPath $item.FullName -Algorithm SHA256).Hash.ToLower())") }
+ }
+ else {
+ $lines.Add("file`t$entry`t$((Get-FileHash -LiteralPath $item.FullName -Algorithm SHA256).Hash.ToLower())")
+ }
+ }
+ Set-Content -LiteralPath $Out -Value ($lines | Sort-Object) -Encoding utf8
+ Write-Host " $($lines.Count) state entries fingerprinted"
+}
+
+function Get-UserDataFingerprint {
+ param($P, [string]$Out)
+ $lines = New-Object System.Collections.Generic.List[string]
+ if (Test-Path -LiteralPath $P.UserData) {
+ $udSkip = @('Cache', 'Code Cache', 'GPUCache', 'DawnGraphiteCache', 'DawnWebGPUCache',
+ 'ShaderCache', 'Crashpad', 'CachedData', 'blob_storage')
+ $stack = New-Object System.Collections.Stack
+ $stack.Push($P.UserData)
+ while ($stack.Count -gt 0) {
+ $cur = $stack.Pop()
+ foreach ($it in @(Get-ChildItem -LiteralPath $cur -Force -ErrorAction SilentlyContinue)) {
+ $rel = Get-RelForward -Root $P.UserData -Path $it.FullName
+ if ($it.PSIsContainer) {
+ if ($udSkip -contains $it.Name) { continue }
+ if ($it.Attributes -band [IO.FileAttributes]::ReparsePoint) {
+ $lines.Add("link`t$rel`t$($it.Target)"); continue
+ }
+ $stack.Push($it.FullName)
+ }
+ else {
+ $lines.Add("file`t$rel`t$((Get-FileHash -LiteralPath $it.FullName -Algorithm SHA256).Hash.ToLower())")
+ }
+ }
+ }
+ }
+ Set-Content -LiteralPath $Out -Value ($lines | Sort-Object) -Encoding utf8
+ Write-Host " $($lines.Count) desktop-data entries fingerprinted"
+}
+
+# ---------------------------------------------------------------------------
+# pre
+# ---------------------------------------------------------------------------
+
+function Invoke-Pre {
+ $P = Get-ResolvedPaths
+ Step 'your install'
+ Say "HERMES_HOME $($P.Home)"
+ Say "install $($P.Install)"
+ Say "desktop data $($P.UserData) ($($P.UserDataOrigin))"
+ 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" }
+
+ Step 'before we start (nothing here is pass/fail, just read it)'
+ $procs = @(Get-Process -Name 'Hermes', 'hermes' -ErrorAction SilentlyContinue)
+ if ($procs.Count) {
+ Warn 'Hermes looks like it is running -- close the desktop app and the gateway'
+ Warn "before you run 'hermes update', or the dependency sync may fail:"
+ $procs | ForEach-Object { Write-Host " $($_.ProcessName) (pid $($_.Id))" }
+ }
+ else { Ok 'no Hermes processes running' }
+ $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" }
+
+ $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)" }
+ $script:Armed = Join-Path $script:Snap 'armed'
+ New-Item -ItemType Directory -Force -Path (Join-Path $script:Snap 'shims'), $script:Armed | Out-Null
+
+ Step 'copying your entire HERMES_HOME'
+ $started = Get-Date
+ $homeTar = Join-Path $script:Snap 'hermes-home.tgz'
+ # No excludes: checkout, venv, PM store and node_modules come too, so post is
+ # a true rollback rather than a re-download.
+ & $script:Tar -czf $homeTar -C $P.Home .
+ if ($LASTEXITCODE -ne 0) { Fail 'backup failed (tar)' }
+ $elapsed = [int]((Get-Date) - $started).TotalSeconds
+ Ok "hermes-home.tgz ($([math]::Round((Get-Item $homeTar).Length / 1MB, 1)) MB, ${elapsed}s)"
+
+ Step 'recording git facts'
+ $head = Invoke-Git $P @('rev-parse', 'HEAD')
+ $branch = Invoke-Git $P @('branch', '--show-current')
+ Set-Content -LiteralPath (Join-Path $script:Snap 'checkout.txt') -Encoding utf8 -Value @("head`t$head", "branch`t$branch")
+ $remotes = @()
+ foreach ($r in @(& git -C $P.Install remote)) {
+ if (-not $r) { continue }
+ $remotes += "$r`t$(Get-GitConfigValue $P "remote.$r.url")"
+ }
+ Set-Content -LiteralPath (Join-Path $script:Snap 'remotes.txt') -Encoding utf8 -Value $remotes
+ Ok "checkout at $head"
+
+ Step "copying the desktop app's data"
+ if (Test-Path -LiteralPath $P.UserData) {
+ $udTar = Join-Path $script:Snap 'electron-userdata.tgz'
+ & $script:Tar -czf $udTar -C $P.UserData .
+ if ($LASTEXITCODE -ne 0) { Fail 'userData backup failed' }
+ Ok "electron-userdata.tgz ($([math]::Round((Get-Item $udTar).Length / 1KB, 1)) KB)"
+ }
+ else { Warn "no Electron userData at $($P.UserData) (desktop app not installed?)" }
+
+ Step 'copying the hermes shims on your PATH'
+ $shimList = New-Object System.Collections.Generic.List[string]
+ $shimLinks = New-Object System.Collections.Generic.List[string]
+ foreach ($shim in $P.Shims) {
+ if (-not (Test-Path -LiteralPath $shim)) { continue }
+ $shimList.Add($shim)
+ $item = Get-Item -LiteralPath $shim -Force
+ if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) {
+ $shimLinks.Add("$shim`t$($item.Target)")
+ }
+ else {
+ Copy-Item -LiteralPath $shim -Destination (Join-Path (Join-Path $script:Snap 'shims') ($shim -replace '[:\\/]', '_')) -Force
+ }
+ }
+ Set-Content -LiteralPath (Join-Path $script:Snap 'shims.txt') -Encoding utf8 -Value $shimList
+ Set-Content -LiteralPath (Join-Path $script:Snap 'shims-links.txt') -Encoding utf8 -Value $shimLinks
+ if ($shimList.Count) { Ok "$($shimList.Count) shim path(s) recorded" } else { Warn 'no shims found' }
+ Set-Content -LiteralPath (Join-Path $script:Snap 'user-path-before.txt') -Encoding utf8 -Value @(Get-UserPathValue)
+
+ Step 'copying your global git config'
+ $globalCfg = Join-Path $env:USERPROFILE '.gitconfig'
+ if (Test-Path -LiteralPath $globalCfg) {
+ Copy-Item -LiteralPath $globalCfg -Destination (Join-Path $script:Snap 'gitconfig.bak') -Force
+ Ok "saved $globalCfg"
+ }
+ else { Warn 'no global git config yet; we will create one and remove it again in post' }
+
+ Step 'fingerprinting (so post can tell you how exact the restore was)'
+ Get-TreeFingerprint -P $P -Out (Join-Path $script:Snap 'fingerprint-before.txt')
+ Get-UserDataFingerprint -P $P -Out (Join-Path $script:Snap 'userdata-before.txt')
+
+ $manifest = [ordered]@{
+ schema = 2
+ created = (Get-Date).ToUniversalTime().ToString('o')
+ hermes_home = $P.Home
+ hermes_root = $P.Root
+ install_dir = $P.Install
+ userdata_dir = $P.UserData
+ userdata_dir_source = $P.UserDataOrigin
+ rehearsal_source = $Source
+ rehearsal_ref = $Ref
+ env = [ordered]@{
+ HERMES_HOME = $env:HERMES_HOME
+ HERMES_DESKTOP_USER_DATA_DIR = $env:HERMES_DESKTOP_USER_DATA_DIR
+ HERMES_DATA_DIR_SUFFIX = $env:HERMES_DATA_DIR_SUFFIX
+ PHOTON_SIDECAR_DIR = $env:PHOTON_SIDECAR_DIR
+ }
+ checkout = [ordered]@{
+ head = (Invoke-Git $P @('rev-parse', 'HEAD'))
+ branch = (Invoke-Git $P @('branch', '--show-current'))
+ origin = (Get-GitConfigValue $P 'remote.origin.url')
+ upstream = (Get-GitConfigValue $P 'remote.upstream.url')
+ }
+ }
+ $manifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $script:Snap 'manifest.json') -Encoding utf8
+ Ok 'manifest.json'
+
+ # --- point the install at the rehearsal source ---------------------------
+ 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 }
+ $null = Invoke-GitCmd @('clone', '--quiet', '--bare', $Source, $serve)
+ if ($LASTEXITCODE -ne 0) { Fail "could not clone $Source (network? permissions? bad -Source?)" }
+ Ok "cloned the whole repo (-Ref '$Ref' is not a branch/tag name)"
+ }
+ else { Ok "cloned $Ref" }
+ $targetSha = (@(& git -C $serve rev-parse --verify "$Ref^{commit}" 2>$null | Out-String) -replace "`r", '').Trim()
+ # Shape-check: a warning or error line folded into the capture would otherwise
+ # be handed to update-ref as a bogus revision.
+ if ($targetSha -notmatch '^[0-9a-f]{40}$') { Fail "-Ref '$Ref' was not found in $Source" }
+ $null = Invoke-GitCmd @('-C', $serve, 'update-ref', 'refs/heads/main', $targetSha)
+ $null = Invoke-GitCmd @('-C', $serve, 'symbolic-ref', 'HEAD', 'refs/heads/main')
+ $null = Invoke-GitCmd @('-C', $serve, 'config', 'uploadpack.allowAnySHA1InWant', 'true')
+ Ok "the update will land on $targetSha"
+
+ 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 '\\', '/')
+ $armedLines = New-Object System.Collections.Generic.List[string]
+ # REPO-LOCAL, like the POSIX script: the checkout's own config lives inside
+ # the home this kit backs up and post restores, and it cannot be read-only or
+ # ACL-denied (the install could not have written its own repo otherwise).
+ 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" }
+ $armedLines.Add("$fileUrl`t$url`tlocal")
+ }
+ Set-Content -LiteralPath (Join-Path $script:Armed 'armed.txt') -Encoding utf8 -Value $armedLines
+ 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:Armed 'target-sha') -Encoding utf8 -Value @($targetSha)
+ Ok 'official repo URL now resolves to the rehearsal copy'
+ Ok "created $($P.Home)\.skip_upstream_prompt (stops the 'add upstream remote?' prompt)"
+
+ Step 'ready'
+ Say 'your install is unchanged so far -- nothing has been updated yet.'
+ Say ''
+ Say 'continue with the instructions provided'
+ Say "your backup is at $($script:Snap) -- keep it until post has run."
+}
+
+# ---------------------------------------------------------------------------
+# status (read-only)
+# ---------------------------------------------------------------------------
+
+function Invoke-Status {
+ $P = Get-ResolvedPaths
+ Step 'your install'
+ Say "HERMES_HOME $($P.Home)"
+ Say "install $($P.Install)"
+ Say "desktop data $($P.UserData) ($($P.UserDataOrigin))"
+ Say "backup root $BackupRoot"
+ Step 'backup'
+ $snap = Get-LatestSnapshot
+ if (-not $snap) { Say "none -- nothing has been set up yet (run 'pre')"; return }
+ Say "latest $snap"
+ $armed = Join-Path $snap 'armed'
+ $ts = Join-Path $armed 'target-sha'
+ if (Test-Path -LiteralPath $ts) {
+ Say "prepared for $((Get-Content -LiteralPath $ts -Raw).Trim())"
+ $manifest = Get-Content -LiteralPath (Join-Path $snap 'manifest.json') -Raw | ConvertFrom-Json
+ Say "source $($manifest.rehearsal_source) @ $($manifest.rehearsal_ref)"
+ }
+ else { Say 'prepared no' }
+ 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 insteadOf entr(y/ies)"
+ if (Test-Path -LiteralPath (Join-Path $P.Install '.git')) {
+ Say "checkout now $(Invoke-Git $P @('rev-parse', '--short', 'HEAD')) ($(Invoke-Git $P @('branch', '--show-current')))"
+ }
+}
+
+# ---------------------------------------------------------------------------
+# post
+# ---------------------------------------------------------------------------
+
+function Confirm-Action {
+ param([string]$Prompt)
+ if ($Yes) { return }
+ $reply = Read-Host "$Prompt [y/N]"
+ if ($reply -notmatch '^(y|yes)$') { Fail 'aborted -- nothing was changed' }
+}
+
+function Invoke-Unarm {
+ Step 'removing the URL redirect'
+ $armedFile = Join-Path $script:Armed 'armed.txt'
+ if (Test-Path -LiteralPath $armedFile) {
+ foreach ($line in @(Get-Content -LiteralPath $armedFile | Where-Object { $_ })) {
+ $parts = $line -split "`t"
+ $t = $parts[0]
+ if (-not $t) { continue }
+ $scope = if ($parts.Count -ge 3) { $parts[2] } else { 'global' }
+ if ($scope -eq 'local') {
+ $null = Invoke-GitCmd @('-C', $P.Install, 'config', '--local', '--unset-all', "url.$t.insteadOf")
+ }
+ else {
+ $null = Invoke-GitCmd @('config', '--global', '--unset-all', "url.$t.insteadOf")
+ }
+ }
+ # An earlier version of this kit wrote the redirect GLOBALLY; clear that too
+ # so a machine that ran it is not left with a stale redirect.
+ foreach ($t in @(Get-Content -LiteralPath $armedFile | Where-Object { $_ } |
+ ForEach-Object { ($_ -split "`t")[0] } | Sort-Object -Unique)) {
+ $null = Invoke-GitCmd @('config', '--global', '--unset-all', "url.$t.insteadOf")
+ }
+ Ok 'removed our insteadOf entries'
+ }
+ $cfgBackup = Join-Path $script:Snap 'gitconfig.bak'
+ if (Test-Path -LiteralPath $cfgBackup) {
+ Copy-Item -LiteralPath $cfgBackup -Destination (Join-Path $env:USERPROFILE '.gitconfig') -Force
+ Ok 'restored your global git config'
+ }
+ $P = Get-ResolvedPaths
+ $marker = Join-Path $P.Home '.skip_upstream_prompt'
+ if (Test-Path -LiteralPath $marker) { Remove-Item -LiteralPath $marker -Force; Ok 'removed the upstream-prompt marker' }
+}
+
+function Invoke-Post {
+ $manifest = Load-Snapshot
+ $P = Get-ResolvedPaths
+ Step 'this will delete and restore:'
+ Say " $($P.Home) (all of it, including the checkout)"
+ Say " $($P.UserData)"
+ Say " the shim files recorded in $($script:Snap)\shims.txt"
+ Confirm-Action "Put everything back from $($script:Snap)?"
+
+ Invoke-Unarm
+ Step 'stopping Hermes'
+ foreach ($name in @('Hermes', 'hermes')) {
+ Get-Process -Name $name -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
+ }
+ Ok 'asked Hermes to stop (if anything was running)'
+
+ Step 'clearing what the rehearsal touched'
+ 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)" }
+ $shimFile = Join-Path $script:Snap 'shims.txt'
+ if (Test-Path -LiteralPath $shimFile) {
+ foreach ($s in @(Get-Content -LiteralPath $shimFile | Where-Object { $_ })) {
+ if (Test-Path -LiteralPath $s) { Remove-Item -LiteralPath $s -Force -ErrorAction SilentlyContinue }
+ }
+ Ok 'removed the recorded shim files'
+ }
+
+ Step 'restoring your HERMES_HOME'
+ New-Item -ItemType Directory -Force -Path $P.Home | Out-Null
+ & $script:Tar -xzf (Join-Path $script:Snap 'hermes-home.tgz') -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.tgz'
+ if (Test-Path -LiteralPath $udTar) {
+ New-Item -ItemType Directory -Force -Path $P.UserData | Out-Null
+ & $script:Tar -xzf $udTar -C $P.UserData
+ if ($LASTEXITCODE -ne 0) { Fail "userData restore failed (backup intact at $($script:Snap))" }
+ Ok 'restored'
+ }
+ else { Warn 'there was no desktop app data to restore' }
+
+ Step 'restoring the shims'
+ $linkFile = Join-Path $script:Snap 'shims-links.txt'
+ if (Test-Path -LiteralPath $shimFile) {
+ foreach ($s in @(Get-Content -LiteralPath $shimFile | Where-Object { $_ })) {
+ $saved = Join-Path (Join-Path $script:Snap 'shims') ($s -replace '[:\\/]', '_')
+ if (Test-Path -LiteralPath $saved) {
+ New-Item -ItemType Directory -Force -Path (Split-Path -Parent $s) | Out-Null
+ Copy-Item -LiteralPath $saved -Destination $s -Force
+ Ok "restored $s"
+ }
+ elseif ((Test-Path -LiteralPath $linkFile) -and ((Get-Content -LiteralPath $linkFile -Raw) -match [regex]::Escape($s))) {
+ $target = (Get-Content -LiteralPath $linkFile | Where-Object { $_ -like "$s`t*" } | ForEach-Object { ($_ -split "`t", 2)[1] })
+ New-Item -ItemType Directory -Force -Path (Split-Path -Parent $s) | Out-Null
+ if (Test-Path -LiteralPath $s) { Remove-Item -LiteralPath $s -Force }
+ # Symlinks need a privilege (or Developer Mode); a copy is close enough
+ # and must never abort the restore.
+ try {
+ New-Item -ItemType SymbolicLink -Path $s -Target $target -Force -ErrorAction Stop | Out-Null
+ Ok "restored symlink $s"
+ }
+ catch {
+ Copy-Item -LiteralPath $target -Destination $s -Recurse -Force -ErrorAction SilentlyContinue
+ Warn "could not create a symlink at $s (no privilege); restored a copy instead"
+ }
+ }
+ }
+ }
+
+ Step 'putting your USER PATH back'
+ $beforePath = Join-Path $script:Snap 'user-path-before.txt'
+ if (Test-Path -LiteralPath $beforePath) {
+ $old = (Get-Content -LiteralPath $beforePath -Raw)
+ if ($old) { $old = $old.TrimEnd("`r", "`n") } else { $old = '' }
+ if ($old) {
+ [Environment]::SetEnvironmentVariable('Path', $old, 'User')
+ Ok 'restored your USER PATH (open a new shell to pick it up)'
+ }
+ else { Warn 'your USER PATH was recorded empty; leaving it untouched' }
+ }
+
+ Step 'how exact was the restore'
+ $diffCount = 0
+ Get-TreeFingerprint -P $P -Out (Join-Path $script:Snap 'fingerprint-restored.txt') *> $null
+ Get-UserDataFingerprint -P $P -Out (Join-Path $script:Snap 'userdata-restored.txt') *> $null
+
+ function Compare-Files([string]$Before, [string]$After, [string]$Label) {
+ $b = @{}; $a = @{}
+ if (Test-Path -LiteralPath $Before) {
+ foreach ($line in (Get-Content -LiteralPath $Before -ErrorAction SilentlyContinue)) {
+ $parts = $line -split "`t"; if ($parts.Count -ge 2) { $b[$parts[1]] = $line }
+ }
+ }
+ if (Test-Path -LiteralPath $After) {
+ foreach ($line in (Get-Content -LiteralPath $After -ErrorAction SilentlyContinue)) {
+ $parts = $line -split "`t"; if ($parts.Count -ge 2) { $a[$parts[1]] = $line }
+ }
+ }
+ $diff = @($b.Keys | Where-Object { -not $a.ContainsKey($_) -or $b[$_] -ne $a[$_] })
+ if ($diff.Count -eq 0) { Ok "all $($b.Count) $Label entries match your backup"; return 0 }
+ Warn "$($diff.Count) $Label entr(y/ies) differ from the backup:"
+ $diff | ForEach-Object { Write-Host " $_" }
+ return 1
+ }
+ $diffCount += (Compare-Files (Join-Path $script:Snap 'fingerprint-before.txt') (Join-Path $script:Snap 'fingerprint-restored.txt') 'state')
+ $diffCount += (Compare-Files (Join-Path $script:Snap 'userdata-before.txt') (Join-Path $script:Snap 'userdata-restored.txt') 'desktop data')
+
+ Step 'done'
+ Say 'Your install, your data and your git config are back as they were.'
+ Say "Open the desktop app once and run 'hermes doctor' to confirm."
+ Say "Nothing was judged or changed by this script; the backup at $($script:Snap)"
+ Say 'is yours to keep or delete.'
+ if ($diffCount -gt 0) { Say '(The differences above are informational, not a failure.)' }
+}
+
+# ---------------------------------------------------------------------------
+
+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 }
+ 'status' { Invoke-Status }
+ default {
+ # $PSCommandPath is empty when the script was piped in rather than run
+ # from a file, so fall back to a self-contained summary.
+ if ($PSCommandPath) {
+ Get-Help $PSCommandPath -Detailed | Out-String | Write-Host
+ }
+ 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 undo all of it: remove the redirect, wipe, restore the backup'
+ Write-Host ' status print what is prepared (read-only; nothing is touched)'
+ 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'
+ Write-Host ' -BackupRoot DIR where the backup lives'
+ Write-Host ' -Yes post: skip the confirmation'
+ Write-Host ''
+ Write-Host "Run 'pre' first: it reports what it did and prints the next commands."
+ }
+ }
+}
+
+# The db-count program is a temp file; do not leave it behind.
+if ($script:DbCountPy -and (Test-Path -LiteralPath $script:DbCountPy)) {
+ Remove-Item -LiteralPath $script:DbCountPy -Force -ErrorAction SilentlyContinue
+}
diff --git a/scripts/update-test/hermes-update-rehearsal.sh b/scripts/update-test/hermes-update-rehearsal.sh
new file mode 100755
index 00000000000..8629f9a0ae8
--- /dev/null
+++ b/scripts/update-test/hermes-update-rehearsal.sh
@@ -0,0 +1,679 @@
+#!/usr/bin/env bash
+# hermes-update-rehearsal.sh — for an EXISTING Hermes install.
+#
+# Two steps:
+# pre back up everything, then point the install's update source at a
+# custom repo + ref so `hermes update` pulls it. Prints what to do next.
+# post undo all of it: remove the redirect, wipe, and restore the backup.
+#
+# Plus `status`, which only prints. This script never judges your install: it
+# reports what it did and stops. Whether the update worked is for you to see.
+#
+# Read PLAN.md (next to this script) first.
+#
+# ./hermes-update-rehearsal.sh pre --source <git-url> --ref <branch-or-tag>
+# # ... run `hermes update`, use Hermes, test whatever you need ...
+# ./hermes-update-rehearsal.sh post
+#
+# Options:
+# --source URL repo to pull the update from (default: the rehearsal fork)
+# --ref REV branch or tag in that repo (default: main)
+# --backup-root DIR where the backup lives (default ~/hermes-update-rehearsal)
+# --yes post: skip the confirmation
+#
+# The backup is the ENTIRE HERMES_HOME plus the desktop app's Electron userData,
+# the `hermes` shims on PATH, and your global git config. Expect it to be as
+# large as your install and to take a few minutes.
+#
+# Requires: python3, tar, git. `pre` needs network access to --source.
+
+set -euo pipefail
+
+OFFICIAL_HTTPS="https://github.com/NousResearch/hermes-agent.git"
+OFFICIAL_SSH="[email protected]:NousResearch/hermes-agent.git"
+DEFAULT_SOURCE="https://github.com/ethernet8023/hermes-agent.git"
+DEFAULT_REF="main"
+
+SUBCMD=""
+BACKUP_ROOT="${HOME}/hermes-update-rehearsal"
+SOURCE="$DEFAULT_SOURCE"
+REF="$DEFAULT_REF"
+ASSUME_YES=0
+
+say() { printf '%s\n' "$*"; }
+ok() { printf ' OK %s\n' "$*"; }
+warn() { printf ' WARN %s\n' "$*" >&2; }
+die() { printf 'ERROR: %s\n' "$*" >&2; exit 1; }
+step() { printf '\n=== %s ===\n' "$*"; }
+
+usage() {
+ if [ -n "$SELF" ] && [ -r "$SELF" ]; then sed -n '2,26p' "$SELF"; exit 0; fi
+ cat <<'EOF'
+hermes-update-rehearsal.sh -- run against an EXISTING Hermes install.
+
+ pre back up everything, then point the update source at a custom repo+ref
+ post undo all of it: remove the redirect, wipe, restore the backup
+ status print what is prepared (read-only; nothing is touched)
+
+Options:
+ --source URL repo to pull the update from (default: the rehearsal fork)
+ --ref REV branch or tag in that repo (default: main)
+ --backup-root DIR where the backup lives (default ~/hermes-update-rehearsal)
+ --yes post: skip the confirmation
+
+`pre` reports what it did and prints the next commands. It never judges your
+install; whether the update worked is for you to see.
+EOF
+ exit 0
+}
+
+# How to name ourselves in the instructions we print. Piped into a shell
+# (`curl ... | bash -s -- pre`) there is no path to point at and "$0" is just
+# "bash", which would print a command that does not exist.
+SELF="$0"
+case "$(basename "$SELF")" in bash|sh|dash|zsh|-bash|-sh|'') SELF="" ;; esac
+case "$SELF" in /dev/fd/*|/dev/stdin|/proc/self/fd/*) SELF="" ;; esac
+SELF_PIPED=""
+if [ -n "$SELF" ]; then SELF_CMD="$SELF"; else SELF_CMD="hermes-update-rehearsal.sh"; SELF_PIPED=1; fi
+
+while [ "$#" -gt 0 ]; do
+ case "$1" in
+ pre|post|status) SUBCMD="$1"; shift ;;
+ --source) [ "$#" -ge 2 ] || die "--source needs a value"; SOURCE="$2"; shift 2 ;;
+ --ref) [ "$#" -ge 2 ] || die "--ref needs a value"; REF="$2"; shift 2 ;;
+ --backup-root) [ "$#" -ge 2 ] || die "--backup-root needs a value"; BACKUP_ROOT="$2"; shift 2 ;;
+ --yes|-y) ASSUME_YES=1; shift ;;
+ -h|--help) usage ;;
+ *) die "unknown argument: $1" ;;
+ esac
+done
+[ -n "$SUBCMD" ] || usage
+
+# Probe, don't assume: on Windows `python3` is often the Microsoft Store alias
+# stub, which exits non-zero for every real invocation.
+PYTHON=""
+for cand in python3 python; do
+ if command -v "$cand" >/dev/null 2>&1 && "$cand" -c 'pass' >/dev/null 2>&1; then
+ PYTHON="$cand"; break
+ fi
+done
+[ -n "$PYTHON" ] || die "python3 is required (fingerprints)"
+command -v git >/dev/null 2>&1 || die "git is required"
+command -v tar >/dev/null 2>&1 || die "tar is required"
+
+SNAP=""
+ARMED=""
+
+# The durable state `post` reports on after restoring. Regenerable trees
+# (caches, logs, dependency dirs) are deliberately absent, and `skills/` is
+# reported but never judged: the product syncs the bundled library into it on
+# startup and after every update, so it changes legitimately.
+durable_tops() {
+ printf '%s\n' config.yaml .env auth.json state.db gateway_state.json \
+ memories skills cron plugins photon desktop-plugins tui-widgets skins pets \
+ sessions profiles
+}
+
+# ---------------------------------------------------------------------------
+# paths
+# ---------------------------------------------------------------------------
+
+# Under git-bash/cygwin, POSIX paths are not translated for native tools
+# (git.exe, python.exe), so normalise them. On macOS cygpath is absent: no-op.
+native_path() {
+ if command -v cygpath >/dev/null 2>&1; then
+ cygpath -m "$1" 2>/dev/null || printf '%s' "$1"
+ else
+ printf '%s' "$1"
+ fi
+}
+
+resolve_paths() {
+ local suffix="${HERMES_DATA_DIR_SUFFIX:-}"
+ if [ -n "${HERMES_HOME:-}" ]; then
+ HERMES_HOME="$(cd "$HERMES_HOME" 2>/dev/null && pwd || printf '%s' "$HERMES_HOME")"
+ else
+ HERMES_HOME="$HOME/.hermes${suffix}"
+ fi
+ # A profile home sits inside the shared root; both are protected.
+ if [ "$(basename "$(dirname "$HERMES_HOME")")" = "profiles" ]; then
+ HERMES_ROOT="$(dirname "$(dirname "$HERMES_HOME")")"
+ else
+ HERMES_ROOT="$HERMES_HOME"
+ fi
+ INSTALL_DIR="$HERMES_HOME/hermes-agent"
+ if [ -n "${HERMES_DESKTOP_USER_DATA_DIR:-}" ]; then
+ USERDATA_DIR="$HERMES_DESKTOP_USER_DATA_DIR"; USERDATA_SOURCE="env"
+ else
+ USERDATA_DIR="$HOME/Library/Application Support/Hermes${suffix}"; USERDATA_SOURCE="default"
+ fi
+ SHIM_CANDIDATES=(
+ "$INSTALL_DIR/.hermes/bin/hermes" "$INSTALL_DIR/.hermes/bin/hermes-acp"
+ "$INSTALL_DIR/.hermes/bin/hermes-agent"
+ "$HOME/.local/bin/hermes" "$HOME/.local/bin/hermes-acp" "$HOME/.local/bin/hermes-agent"
+ "$HERMES_ROOT/bin/hermes" "$HERMES_ROOT/bin/hermes-acp" "$HERMES_ROOT/bin/hermes-agent"
+ "/usr/local/bin/hermes" "/usr/local/bin/hermes-acp"
+ )
+ BACKUP_ROOT="$(native_path "$BACKUP_ROOT")"
+ HERMES_HOME="$(native_path "$HERMES_HOME")"
+ HERMES_ROOT="$(native_path "$HERMES_ROOT")"
+ INSTALL_DIR="$(native_path "$INSTALL_DIR")"
+ USERDATA_DIR="$(native_path "$USERDATA_DIR")"
+ local i
+ for i in "${!SHIM_CANDIDATES[@]}"; do
+ SHIM_CANDIDATES[i]="$(native_path "${SHIM_CANDIDATES[$i]}")"
+ done
+}
+
+global_git_config_paths() {
+ printf '%s\n' "$HOME/.gitconfig"
+ # git also reads the XDG path, and XDG_CONFIG_HOME DEFAULTS to ~/.config --
+ # checking only when the var is exported misses every XDG-style setup, so the
+ # backup silently captured nothing for those users.
+ printf '%s\n' "${XDG_CONFIG_HOME:-$HOME/.config}/git/config"
+ return 0
+}
+
+first_existing_global_config() {
+ local cfg
+ while IFS= read -r cfg; do
+ [ -f "$cfg" ] && { printf '%s' "$cfg"; return 0; }
+ done < <(global_git_config_paths)
+ return 1
+}
+
+latest_backup_root() {
+ [ -d "$BACKUP_ROOT" ] || return 1
+ local newest
+ newest="$(ls -1d "$BACKUP_ROOT"/*/ 2>/dev/null | sort | tail -1 || true)"
+ [ -n "$newest" ] || return 1
+ printf '%s' "${newest%/}"
+}
+
+load_snapshot() {
+ SNAP="$(latest_backup_root)" || die "no backup found under $BACKUP_ROOT — run 'pre' first"
+ ARMED="$SNAP/armed"
+ [ -f "$SNAP/manifest.json" ] || die "$SNAP is not a rehearsal backup (no manifest.json)"
+ local recorded
+ recorded="$("$PYTHON" -c 'import json,sys;print(json.load(open(sys.argv[1]))["hermes_home"])' "$SNAP/manifest.json")"
+ [ "$recorded" = "$HERMES_HOME" ] \
+ || die "that backup belongs to HERMES_HOME=$recorded, not $HERMES_HOME; pass --backup-root to pick the right one"
+}
+
+# ---------------------------------------------------------------------------
+# fingerprints (used only to report how exact a restore was)
+# ---------------------------------------------------------------------------
+
+fingerprint_home() {
+ local out="$1"
+ REHEARSAL_TOPS="$(durable_tops | tr '\n' ' ')" "$PYTHON" - "$HERMES_HOME" "$out" <<'PY'
+import hashlib, os, sqlite3, sys
+
+root, out = sys.argv[1], sys.argv[2]
+SKIP_DIRS = {"node_modules", ".venv", "venv", "site-packages", "__pycache__", ".git",
+ ".cache", ".tox", ".nox", ".pytest_cache", ".mypy_cache", ".ruff_cache",
+ "backups", "state-snapshots", "checkpoints", "hermes-agent",
+ "browser-profiles", "browser-profile", "models", "runtimes", "node"}
+SKIP_SUF = (".pyc", ".pyo", ".db-wal", ".db-shm", ".db-journal")
+TOP = os.environ.get("REHEARSAL_TOPS", "").split()
+
+def sha(path):
+ h = hashlib.sha256()
+ with open(path, "rb") as fh:
+ for block in iter(lambda: fh.read(1 << 20), b""):
+ h.update(block)
+ return h.hexdigest()
+
+def db_counts(path):
+ """Bytes are meaningless for a live SQLite db; count rows instead."""
+ try:
+ con = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
+ try:
+ tables = {r[0] for r in con.execute(
+ "SELECT name FROM sqlite_master WHERE type='table'")}
+ parts = [f"{t}={con.execute(f'SELECT COUNT(*) FROM {t}').fetchone()[0]}"
+ for t in sorted(tables & {"sessions", "messages", "usage", "cron_jobs"})]
+ return "db\t" + ";".join(parts) if parts else None
+ finally:
+ con.close()
+ except Exception:
+ return None
+
+def render(path, rel):
+ if os.path.islink(path):
+ return f"link\t{rel}\t{os.readlink(path)}"
+ if os.path.isdir(path):
+ return f"dir\t{rel}"
+ if os.path.basename(path) == "state.db":
+ counts = db_counts(path)
+ if counts:
+ return f"{counts}\t{rel}"
+ return f"file\t{rel}\t{sha(path)}"
+
+def walk(base):
+ for cur, dirs, files in os.walk(base):
+ keep = []
+ for name in sorted(dirs):
+ if name in SKIP_DIRS:
+ continue
+ full = os.path.join(cur, name)
+ # os.walk lists a symlink-to-dir in `dirs` and refuses to descend,
+ # so record it here or it vanishes from the fingerprint.
+ if os.path.islink(full):
+ yield full
+ else:
+ keep.append(name)
+ dirs[:] = keep
+ for name in sorted(files):
+ if not name.endswith(SKIP_SUF):
+ yield os.path.join(cur, name)
+ if not files and not dirs:
+ yield cur
+
+lines = []
+for entry in TOP:
+ top = os.path.join(root, entry)
+ if not os.path.lexists(top):
+ continue
+ lines.append(render(top, entry))
+ if os.path.isdir(top) and not os.path.islink(top):
+ for path in walk(top):
+ lines.append(render(path, os.path.relpath(path, root).replace(os.sep, "/")))
+
+with open(out, "w", encoding="utf-8") as fh:
+ fh.write("\n".join(sorted(lines)) + ("\n" if lines else ""))
+print(f"{len(lines)} state entries fingerprinted")
+PY
+}
+
+fingerprint_userdata() {
+ local out="$1"
+ [ -d "$USERDATA_DIR" ] || { : > "$out"; return 0; }
+ "$PYTHON" - "$USERDATA_DIR" "$out" <<'PY'
+import hashlib, os, sys
+
+root, out = sys.argv[1], sys.argv[2]
+SKIP_DIRS = {"Cache", "Code Cache", "GPUCache", "DawnGraphiteCache", "DawnWebGPUCache",
+ "ShaderCache", "Crashpad", "CachedData", "blob_storage"}
+
+def sha(path):
+ h = hashlib.sha256()
+ with open(path, "rb") as fh:
+ for block in iter(lambda: fh.read(1 << 20), b""):
+ h.update(block)
+ return h.hexdigest()
+
+lines = []
+for cur, dirs, files in os.walk(root):
+ dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS)
+ for name in sorted(files):
+ path = os.path.join(cur, name)
+ rel = os.path.relpath(path, root).replace(os.sep, "/")
+ lines.append(f"link\t{rel}\t{os.readlink(path)}" if os.path.islink(path)
+ else f"file\t{rel}\t{sha(path)}")
+
+with open(out, "w", encoding="utf-8") as fh:
+ fh.write("\n".join(sorted(lines)) + ("\n" if lines else ""))
+print(f"{len(lines)} userData entries fingerprinted")
+PY
+}
+
+# ---------------------------------------------------------------------------
+# pre: back up, then point the install at the rehearsal source
+# ---------------------------------------------------------------------------
+
+cmd_pre() {
+ resolve_paths
+ step "your install"
+ say "HERMES_HOME $HERMES_HOME"
+ say "install $INSTALL_DIR"
+ say "desktop data $USERDATA_DIR ($USERDATA_SOURCE)"
+ say "backup to $BACKUP_ROOT"
+ [ -d "$HERMES_HOME" ] || die "no HERMES_HOME at $HERMES_HOME"
+ [ -d "$INSTALL_DIR/.git" ] || die "no git checkout at $INSTALL_DIR — this tool covers source installs"
+
+ step "before we start (nothing here is a pass/fail, just read it)"
+ if command -v pgrep >/dev/null 2>&1; then
+ local procs
+ procs="$(pgrep -fl hermes 2>/dev/null | grep -v 'hermes-update-rehearsal' || true)"
+ if [ -n "$procs" ]; then
+ warn "Hermes looks like it is running — close the desktop app and the gateway"
+ warn "before you run 'hermes update', or the dependency sync may fail:"
+ printf ' %s\n' "$procs"
+ else
+ ok "no Hermes processes running"
+ fi
+ fi
+ local n
+ n="$( { git config --global --get-regexp '^url\.' 2>/dev/null || true; git -C "$INSTALL_DIR" config --local --get-regexp '^url\.' 2>/dev/null || true; } | wc -l | tr -d ' ')"
+ if [ "$n" = 0 ]; then 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"; fi
+
+ SNAP="$BACKUP_ROOT/$(date -u +%Y%m%dT%H%M%SZ)"
+ [ ! -e "$SNAP" ] || die "backup dir already exists: $SNAP"
+ mkdir -p "$SNAP/shims" "$SNAP/armed"
+ ARMED="$SNAP/armed"
+
+ step "copying your entire HERMES_HOME"
+ local started elapsed
+ started="$SECONDS"
+ # 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).
+ tar -czf "$SNAP/hermes-home.tgz" -C "$HERMES_HOME" . || die "backup failed (tar)"
+ elapsed=$((SECONDS - started))
+ ok "hermes-home.tgz ($(du -h "$SNAP/hermes-home.tgz" | cut -f1), ${elapsed}s)"
+
+ step "recording git facts"
+ {
+ printf 'head\t%s\n' "$(git -C "$INSTALL_DIR" rev-parse HEAD)"
+ printf 'branch\t%s\n' "$(git -C "$INSTALL_DIR" branch --show-current || true)"
+ printf 'stashes\t%s\n' "$(git -C "$INSTALL_DIR" stash list | wc -l | tr -d ' ')"
+ } > "$SNAP/checkout.txt"
+ : > "$SNAP/remotes.txt"
+ local remote
+ while IFS= read -r remote; do
+ [ -n "$remote" ] || continue
+ printf '%s\t%s\n' "$remote" "$(git -C "$INSTALL_DIR" config --get "remote.$remote.url")" \
+ >> "$SNAP/remotes.txt"
+ done < <(git -C "$INSTALL_DIR" remote)
+ ok "checkout at $(awk -F'\t' '$1=="head"{print $2}' "$SNAP/checkout.txt")"
+
+ step "copying the desktop app's data"
+ if [ -d "$USERDATA_DIR" ]; then
+ tar -czf "$SNAP/electron-userdata.tgz" -C "$USERDATA_DIR" . || die "userData backup failed"
+ ok "electron-userdata.tgz ($(du -h "$SNAP/electron-userdata.tgz" | cut -f1))"
+ else
+ warn "no Electron userData at $USERDATA_DIR (desktop app not installed?)"
+ fi
+
+ step "copying the hermes shims on your PATH"
+ : > "$SNAP/shims.txt"; : > "$SNAP/shims-links.txt"
+ local shim
+ for shim in "${SHIM_CANDIDATES[@]}"; do
+ [ -e "$shim" ] || [ -L "$shim" ] || continue
+ printf '%s\n' "$shim" >> "$SNAP/shims.txt"
+ if [ -L "$shim" ]; then
+ printf '%s\t%s\n' "$shim" "$(readlink "$shim")" >> "$SNAP/shims-links.txt"
+ else
+ cp -p "$shim" "$SNAP/shims/$(printf '%s' "$shim" | tr '/' '_')" 2>/dev/null || warn "could not copy $shim"
+ fi
+ done
+ if [ -s "$SNAP/shims.txt" ]; then ok "$(wc -l < "$SNAP/shims.txt" | tr -d ' ') shim path(s) recorded"
+ else warn "no shims found on PATH"; fi
+
+ step "copying your global git config"
+ local cfg
+ if cfg="$(first_existing_global_config)"; then
+ cp -p "$cfg" "$SNAP/gitconfig.bak"; ok "saved $cfg"
+ else
+ warn "no global git config yet; we will create one and remove it again in post"
+ fi
+
+ step "fingerprinting (so post can tell you how exact the restore was)"
+ fingerprint_home "$SNAP/fingerprint-before.txt"
+ fingerprint_userdata "$SNAP/userdata-before.txt"
+
+ "$PYTHON" - "$SNAP" "$HERMES_HOME" "$HERMES_ROOT" "$INSTALL_DIR" \
+ "$USERDATA_DIR" "$USERDATA_SOURCE" "$SOURCE" "$REF" <<'PY'
+import datetime, json, os, subprocess, sys
+snap, home, root, install, userdata, src, source, ref = sys.argv[1:9]
+def git(*args):
+ try:
+ return subprocess.run(["git", "-C", install, *args], capture_output=True,
+ text=True, check=False).stdout.strip()
+ except Exception:
+ return ""
+json.dump({
+ "schema": 2,
+ "created": datetime.datetime.now(datetime.timezone.utc).isoformat(),
+ "hermes_home": home,
+ "hermes_root": root,
+ "install_dir": install,
+ "userdata_dir": userdata,
+ "userdata_dir_source": src,
+ "rehearsal_source": source,
+ "rehearsal_ref": ref,
+ "env": {k: os.environ.get(k) for k in
+ ("HERMES_HOME", "HERMES_DESKTOP_USER_DATA_DIR", "HERMES_DATA_DIR_SUFFIX",
+ "PHOTON_SIDECAR_DIR")},
+ "checkout": {"head": git("rev-parse", "HEAD"),
+ "branch": git("branch", "--show-current"),
+ "origin": git("config", "--get", "remote.origin.url"),
+ "upstream": git("config", "--get", "remote.upstream.url")},
+}, open(os.path.join(snap, "manifest.json"), "w", encoding="utf-8"), indent=2, sort_keys=True)
+PY
+ ok "manifest.json"
+
+ # --- point the install at the rehearsal source ---------------------------
+ step "fetching the rehearsal source"
+ say "source $SOURCE"
+ say "ref $REF"
+ local serve="$SNAP/serve.git" target_sha=""
+ rm -rf "$serve"
+ # Prefer a single-branch clone (fast); fall back to a full bare clone so a
+ # raw commit in --ref still resolves.
+ if git clone --quiet --bare --branch "$REF" --single-branch "$SOURCE" "$serve" 2>/dev/null; then
+ ok "cloned $REF"
+ else
+ rm -rf "$serve"
+ git clone --quiet --bare "$SOURCE" "$serve" \
+ || die "could not clone $SOURCE (network? permissions? bad --source?)"
+ ok "cloned the whole repo (--ref '$REF' is not a branch/tag name)"
+ fi
+ target_sha="$(git -C "$serve" rev-parse --verify "${REF}^{commit}" 2>/dev/null || true)"
+ [ -n "$target_sha" ] || die "--ref '$REF' was not found in $SOURCE"
+ git -C "$serve" update-ref refs/heads/main "$target_sha"
+ git -C "$serve" symbolic-ref HEAD refs/heads/main
+ # The updater may ask for an exact SHA instead of a branch tip.
+ git -C "$serve" config uploadpack.allowAnySHA1InWant true
+ ok "the update will land on $target_sha"
+
+ 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.
+ case "$serve" in
+ [A-Za-z]:*) REDIRECT="file:///$serve" ;;
+ *) REDIRECT="file://$serve" ;;
+ esac
+ : > "$ARMED/armed.txt"
+ local url
+ # The redirect belongs in the REPO-LOCAL config: it lives inside the checkout
+ # this kit already owns and backs up, it cannot be root-owned or read-only
+ # (the install could not have written its own repo otherwise), and `post`'s
+ # wipe+restore removes it for free. A writable GLOBAL git config is a
+ # dependency we do not need -- requiring it aborts on any machine whose
+ # ~/.config/git/config is read-only or ACL-denied.
+ for url in "$OFFICIAL_HTTPS" "$OFFICIAL_SSH"; do
+ # --add: the key is multi-valued; a plain write would drop the first URL.
+ git -C "$INSTALL_DIR" config --local --add "url.$REDIRECT.insteadOf" "$url" \
+ || die "could not write the URL redirect into $INSTALL_DIR/.git/config"
+ printf '%s\t%s\t%s\n' "$REDIRECT" "$url" local >> "$ARMED/armed.txt"
+ done
+ mkdir -p "$HERMES_HOME"
+ touch "$HERMES_HOME/.skip_upstream_prompt"
+ printf '%s\n' "$target_sha" > "$ARMED/target-sha"
+ ok "official repo URL now resolves to the rehearsal copy"
+ ok "created $HERMES_HOME/.skip_upstream_prompt (stops the 'add upstream remote?' prompt)"
+
+ step "ready"
+ say "your install is unchanged so far. nothing has been updated yet."
+ say ""
+ say "continue with the instructions provided!"
+ say "your backup is at $SNAP. keep it until post has run."
+}
+
+# ---------------------------------------------------------------------------
+# status (read-only)
+# ---------------------------------------------------------------------------
+
+cmd_status() {
+ resolve_paths
+ step "your install"
+ say "HERMES_HOME $HERMES_HOME"
+ say "install $INSTALL_DIR"
+ say "desktop data $USERDATA_DIR ($USERDATA_SOURCE)"
+ say "backup root $BACKUP_ROOT"
+ step "backup"
+ if ! SNAP="$(latest_backup_root)"; then
+ say "none — nothing has been set up yet (run 'pre')"
+ return 0
+ fi
+ ARMED="$SNAP/armed"
+ say "latest $SNAP"
+ if [ -f "$ARMED/target-sha" ]; then
+ say "prepared for $(cat "$ARMED/target-sha")"
+ say "source $(cat "$SNAP/manifest.json" 2>/dev/null | "$PYTHON" -c 'import json,sys;d=json.load(sys.stdin);print(d.get("rehearsal_source","?"),"@",d.get("rehearsal_ref","?"))' 2>/dev/null || echo '?')"
+ else
+ say "prepared no"
+ fi
+ say "marker $([ -f "$HERMES_HOME/.skip_upstream_prompt" ] && echo present || echo absent)"
+ local n=0
+ while IFS= read -r _; do n=$((n + 1)); done \
+ < <( { git config --global --get-regexp '^url\.' 2>/dev/null || true; git -C "$INSTALL_DIR" config --local --get-regexp '^url\.' 2>/dev/null || true; } )
+ say "git rewrites $n insteadOf entr(y/ies)"
+ if [ -d "$INSTALL_DIR/.git" ]; then
+ say "checkout now $(git -C "$INSTALL_DIR" rev-parse --short HEAD) ($(git -C "$INSTALL_DIR" branch --show-current))"
+ fi
+}
+
+# ---------------------------------------------------------------------------
+# post: undo everything
+# ---------------------------------------------------------------------------
+
+confirm() {
+ [ "$ASSUME_YES" = 1 ] && return 0
+ local prompt="$1 [y/N] " reply=""
+ # Piped into a shell (`curl ... | bash -s -- post`) stdin is THIS SCRIPT, so a
+ # plain `read` hits EOF and aborts every time. Ask the terminal instead.
+ # /dev/tty is still a device node with no controlling terminal, so probe by
+ # OPENING it -- `[ -r /dev/tty ]` passes there and the open then fails.
+ local from_tty=""
+ if from_tty="$( { printf '%s' "$prompt" >/dev/tty && read -r a </dev/tty && printf '%s' "$a"; } 2>/dev/null )"; then
+ reply="$from_tty"
+ else
+ printf '%s' "$prompt"
+ read -r reply || reply=""
+ fi
+ case "$reply" in y|Y|yes|YES) return 0 ;; *) die "aborted — nothing was changed (re-run with --yes to skip this prompt)" ;; esac
+}
+
+unarm() {
+ step "removing the URL redirect"
+ if [ -f "$ARMED/armed.txt" ]; then
+ local scope target
+ while IFS=$'\t' read -r target _url scope; do
+ [ -n "$target" ] || continue
+ case "${scope:-global}" in
+ local) git -C "$INSTALL_DIR" config --local --unset-all "url.$target.insteadOf" 2>/dev/null || true ;;
+ *) git config --global --unset-all "url.$target.insteadOf" 2>/dev/null || true ;;
+ esac
+ done < "$ARMED/armed.txt"
+ # An earlier version of this kit wrote the redirect GLOBALLY; clear that too
+ # so a machine that ran it is not left with a stale redirect.
+ while IFS= read -r target; do
+ [ -n "$target" ] || continue
+ git config --global --unset-all "url.$target.insteadOf" 2>/dev/null || true
+ done < <(cut -f1 "$ARMED/armed.txt" | sort -u)
+ ok "removed our insteadOf entries"
+ fi
+ if [ -f "$SNAP/gitconfig.bak" ]; then
+ local cfg
+ if cfg="$(first_existing_global_config)"; then
+ cp -p "$SNAP/gitconfig.bak" "$cfg" && ok "restored your global git config"
+ fi
+ fi
+ if [ -f "$HERMES_HOME/.skip_upstream_prompt" ]; then
+ rm -f "$HERMES_HOME/.skip_upstream_prompt" && ok "removed the upstream-prompt marker"
+ fi
+}
+
+cmd_post() {
+ resolve_paths
+ load_snapshot
+ step "this will delete and restore:"
+ say " $HERMES_HOME (all of it, including the checkout)"
+ say " $USERDATA_DIR"
+ say " the shim files recorded in $SNAP/shims.txt"
+ confirm "Put everything back from $SNAP?"
+
+ unarm
+ step "stopping Hermes"
+ pkill -f "Hermes.app/Contents/MacOS" 2>/dev/null || true
+ pkill -f "hermes gateway" 2>/dev/null || true
+ ok "asked Hermes to stop (if anything was running)"
+
+ step "clearing what the rehearsal touched"
+ rm -rf "$HERMES_HOME"; ok "removed $HERMES_HOME"
+ rm -rf "$USERDATA_DIR"; ok "removed $USERDATA_DIR"
+ local shim
+ if [ -s "$SNAP/shims.txt" ]; then
+ while IFS= read -r shim; do rm -f "$shim" 2>/dev/null || true; done < "$SNAP/shims.txt"
+ ok "removed the recorded shim files"
+ fi
+
+ step "restoring your HERMES_HOME"
+ mkdir -p "$HERMES_HOME"
+ tar -xzf "$SNAP/hermes-home.tgz" -C "$HERMES_HOME" || die "restore failed — your backup is intact at $SNAP"
+ ok "restored"
+
+ step "restoring the desktop app's data"
+ if [ -f "$SNAP/electron-userdata.tgz" ]; then
+ mkdir -p "$USERDATA_DIR"
+ tar -xzf "$SNAP/electron-userdata.tgz" -C "$USERDATA_DIR" || die "userData restore failed (backup intact at $SNAP)"
+ ok "restored"
+ else
+ warn "there was no desktop app data to restore"
+ fi
+
+ step "restoring the shims"
+ if [ -s "$SNAP/shims.txt" ]; then
+ while IFS= read -r shim; do
+ local saved="$SNAP/shims/$(printf '%s' "$shim" | tr '/' '_')"
+ if [ -f "$saved" ]; then
+ mkdir -p "$(dirname "$shim")"; cp -p "$saved" "$shim"; ok "restored $shim"
+ elif grep -qF "$shim" "$SNAP/shims-links.txt" 2>/dev/null; then
+ local target; target="$(awk -v s="$shim" -F'\t' '$1==s{print $2}' "$SNAP/shims-links.txt")"
+ mkdir -p "$(dirname "$shim")"; rm -f "$shim"; ln -s "$target" "$shim"
+ ok "restored symlink $shim"
+ fi
+ done < "$SNAP/shims.txt"
+ fi
+
+ step "how exact was the restore"
+ fingerprint_home "$SNAP/fingerprint-restored.txt" >/dev/null
+ fingerprint_userdata "$SNAP/userdata-restored.txt" >/dev/null
+ local diffs=0
+ if diff -q "$SNAP/fingerprint-before.txt" "$SNAP/fingerprint-restored.txt" >/dev/null 2>&1; then
+ ok "all $(wc -l < "$SNAP/fingerprint-before.txt" | tr -d ' ') state entries match your backup"
+ else
+ diffs=$((diffs + 1))
+ diff -u "$SNAP/fingerprint-before.txt" "$SNAP/fingerprint-restored.txt" \
+ > "$SNAP/fingerprint-restore.diff" 2>/dev/null || true
+ warn "some state differs from the backup — details in $SNAP/fingerprint-restore.diff"
+ fi
+ if [ -f "$SNAP/userdata-before.txt" ] \
+ && ! diff -q "$SNAP/userdata-before.txt" "$SNAP/userdata-restored.txt" >/dev/null 2>&1; then
+ diffs=$((diffs + 1))
+ diff -u "$SNAP/userdata-before.txt" "$SNAP/userdata-restored.txt" \
+ > "$SNAP/userdata-restore.diff" 2>/dev/null || true
+ warn "some desktop app data differs — details in $SNAP/userdata-restore.diff"
+ else
+ ok "desktop app data matches"
+ fi
+
+ step "done"
+ say "Your install, your data and your git config are back as they were."
+ say "Open the desktop app once and run 'hermes doctor' to confirm."
+ say "Nothing was judged or changed by this script; the backup at $SNAP is"
+ say "yours to keep or delete."
+ [ "$diffs" = 0 ] || say "(The differences reported above are informational — see the diff files.)"
+}
+
+case "$SUBCMD" in
+ pre) cmd_pre ;;
+ post) cmd_post ;;
+ status) cmd_status ;;
+esac
diff --git a/scripts/update-test/smoke-test.ps1 b/scripts/update-test/smoke-test.ps1
new file mode 100755
index 00000000000..56dc4b9a560
--- /dev/null
+++ b/scripts/update-test/smoke-test.ps1
@@ -0,0 +1,257 @@
+<#
+ Smoke test for hermes-update-rehearsal.ps1 (this directory).
+ Builds a synthetic install in a temp tree and drives pre/post/status for real.
+#>
+[CmdletBinding()]
+param()
+$ErrorActionPreference = 'Stop'
+
+$Script = Join-Path $PSScriptRoot 'hermes-update-rehearsal.ps1'
+# A python is needed for the sqlite assertions. Prefer an explicit checkout, then
+# a hermes-agent checkout next to this kit (the usual layout while developing).
+$Checkout = $env:HERMES_REHEARSAL_CHECKOUT
+if (-not $Checkout) {
+ $sibling = Join-Path (Split-Path -Parent $PSScriptRoot) 'hermes-agent'
+ if (Test-Path -LiteralPath $sibling) { $Checkout = $sibling }
+}
+if (-not (Test-Path -LiteralPath $Script)) { throw "missing $Script" }
+
+$PSExe = (Get-Command powershell.exe -ErrorAction SilentlyContinue).Source
+if (-not $PSExe) { $PSExe = (Get-Command pwsh.exe -ErrorAction SilentlyContinue).Source }
+if (-not $PSExe) { throw 'no powershell host found' }
+Write-Host "host: $PSExe"
+
+$errors = $null
+[void][System.Management.Automation.Language.Parser]::ParseFile($Script, [ref]$null, [ref]$errors)
+if ($errors -and $errors.Count) { Write-Host 'SYNTAX ERRORS:'; $errors | ForEach-Object { Write-Host " $_" }; exit 1 }
+Write-Host 'syntax OK'
+
+$RealUserPath = [Environment]::GetEnvironmentVariable('Path', 'User')
+
+function Find-RealPython {
+ $cands = @(
+ (Join-Path $env:USERPROFILE '.hermes\hermes-agent\venv\Scripts\python.exe')
+ )
+ if ($Checkout) {
+ $cands += (Join-Path $Checkout '.venv\Scripts\python.exe')
+ $cands += (Join-Path $Checkout 'venv\Scripts\python.exe')
+ }
+ $wa = Join-Path $env:ProgramFiles 'WindowsApps'
+ if (Test-Path -LiteralPath $wa) {
+ $cands += Get-ChildItem -LiteralPath $wa -Directory -ErrorAction SilentlyContinue |
+ Where-Object { $_.Name -like 'NousResearch.Hermes*' } |
+ ForEach-Object {
+ Get-ChildItem -LiteralPath (Join-Path $_.FullName 'app\resources\agent-payload\tools') -Directory -ErrorAction SilentlyContinue |
+ Where-Object { $_.Name -like 'python-*' } | ForEach-Object { Join-Path $_.FullName 'python.exe' }
+ }
+ }
+ foreach ($root in @($env:LOCALAPPDATA + '\Programs\Python', 'C:\', $env:ProgramFiles)) {
+ $cands += Get-ChildItem -Path (Join-Path $root 'Python*') -Directory -ErrorAction SilentlyContinue |
+ ForEach-Object { Join-Path $_.FullName 'python.exe' }
+ $cands += Get-ChildItem -Path (Join-Path $root 'python*') -Directory -ErrorAction SilentlyContinue |
+ ForEach-Object { Join-Path $_.FullName 'python.exe' }
+ }
+ # PATH and the py launcher too: that is where a CI runner keeps python.
+ $cands += (Get-Command python.exe -All -ErrorAction SilentlyContinue | ForEach-Object { $_.Source })
+ $pyLauncher = (Get-Command py.exe -ErrorAction SilentlyContinue).Source
+ if ($pyLauncher) {
+ try {
+ $fromLauncher = (& $pyLauncher -3 -c 'import sys;print(sys.executable)' 2>$null | Out-String).Trim()
+ if ($fromLauncher) { $cands += $fromLauncher }
+ }
+ catch { }
+ }
+ foreach ($c in $cands) {
+ if (-not $c) { continue }
+ if ($c -like '*\Microsoft\WindowsApps\*') { continue } # Store alias stub
+ if (-not (Test-Path -LiteralPath $c)) { continue }
+ try { & $c -c 'import sqlite3' *> $null; if ($LASTEXITCODE -eq 0) { return $c } }
+ catch { }
+ }
+ return $null
+}
+
+function Find-RealGit {
+ foreach ($c in @("$env:ProgramFiles\Git\cmd\git.exe", "$env:ProgramFiles\Git\bin\git.exe",
+ "${env:ProgramFiles(x86)}\Git\cmd\git.exe")) {
+ if ($c -and (Test-Path -LiteralPath $c)) {
+ try { & $c --version *> $null; if ($LASTEXITCODE -eq 0) { return $c } } catch { }
+ }
+ }
+ return $null
+}
+
+$RealPython = Find-RealPython
+if (-not $RealPython) { throw 'no usable python.exe found; the db-count assertions need one' }
+$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 }
+
+$Root = Join-Path $env:LOCALAPPDATA ("Temp\rehearsal-ps-" + [guid]::NewGuid().ToString('N').Substring(0, 8))
+New-Item -ItemType Directory -Force -Path $Root | Out-Null
+$env:USERPROFILE = Join-Path $Root 'home'
+New-Item -ItemType Directory -Force -Path $env:USERPROFILE | Out-Null
+$env:GIT_CONFIG_GLOBAL = Join-Path $Root 'gitconfig-test'
+Set-Content -LiteralPath $env:GIT_CONFIG_GLOBAL -Value @()
+$env:HERMES_HOME = Join-Path $env:USERPROFILE '.hermes'
+$env:HERMES_DESKTOP_USER_DATA_DIR = Join-Path $Root 'electron-user-data'
+Remove-Item Env:\HERMES_DATA_DIR_SUFFIX -ErrorAction SilentlyContinue
+
+$H = $env:HERMES_HOME
+$Install = Join-Path $H 'hermes-agent'
+$Backups = Join-Path $Root 'backups'
+Write-Host "fixture under $Root"
+
+$pass = 0; $fail = 0
+function Check { param([string]$Msg, [bool]$Ok) if ($Ok) { Write-Host " PASS $Msg"; $script:pass++ } else { Write-Host " FAIL $Msg"; $script:fail++ } }
+
+function Invoke-Rehearsal {
+ param([string[]]$Arguments, [switch]$AllowFailure)
+ # PS 5.1 turns a child's stderr into a TERMINATING error record when EAP is
+ # Stop and stderr is merged; relax it just for the child call.
+ $prev = $ErrorActionPreference
+ $ErrorActionPreference = 'Continue'
+ try {
+ $out = & $PSExe -NoProfile -ExecutionPolicy Bypass -File $Script @Arguments 2>&1
+ $code = $LASTEXITCODE
+ }
+ finally { $ErrorActionPreference = $prev }
+ if (-not $AllowFailure -and $code -ne 0) {
+ Write-Host '--- child output ---'
+ Write-Host (($out | Out-String).Trim())
+ Write-Host '--- end child output ---'
+ }
+ return [pscustomobject]@{ Code = $code; Out = ($out | Out-String) }
+}
+
+function New-Fixture {
+ New-Item -ItemType Directory -Force -Path `
+ (Join-Path $H 'plugins\mnemosyne-wrapper'), (Join-Path $H 'memories'),
+ (Join-Path $H 'skills\foo'), (Join-Path $H 'cron'), (Join-Path $H 'logs'),
+ (Join-Path $H 'photon\sidecar\node_modules'), (Join-Path $Root 'external-mnemosyne') | Out-Null
+ Set-Content -LiteralPath (Join-Path $H 'plugins\mnemosyne-wrapper\plugin.yaml') -Value 'name: mnemosyne-wrapper'
+ Set-Content -LiteralPath (Join-Path $H 'plugins\mnemosyne-wrapper\mnemosyne-wrapper.json') -Value '{"wrapper":true}'
+ Set-Content -LiteralPath (Join-Path $Root 'external-mnemosyne\witness.txt') -Value 'witness'
+ Set-Content -LiteralPath (Join-Path $H 'config.yaml') -Value 'timezone: utc'
+ Set-Content -LiteralPath (Join-Path $H '.env') -Value 'NOUS_API_KEY=xxx'
+ Set-Content -LiteralPath (Join-Path $H 'auth.json') -Value '{"tokens":{}}'
+ Set-Content -LiteralPath (Join-Path $H 'memories\note.md') -Value 'recall'
+ Set-Content -LiteralPath (Join-Path $H 'cron\jobs.json') -Value 'jobs'
+ Set-Content -LiteralPath (Join-Path $H 'photon\sidecar\index.mjs') -Value 'console.log(1)'
+ Set-Content -LiteralPath (Join-Path $H 'photon\sidecar\package.json') -Value '{"name":"sidecar"}'
+ Set-Content -LiteralPath (Join-Path $H 'photon\sidecar\package-lock.json') -Value '{"lockfileVersion":3}'
+ Set-Content -LiteralPath (Join-Path $H 'photon\sidecar\node_modules\.package-lock.json') -Value '{"lockfileVersion":3}'
+
+ # SQL goes through a temp script FILE: a `-c` argument carrying quotes gets
+ # reshaped by PowerShell's native-argument handling and fails to parse.
+ $sqlPy = Join-Path $Root 'exec_sql.py'
+ @'
+import sqlite3, sys
+con = sqlite3.connect(sys.argv[1])
+con.executescript(sys.argv[2])
+con.commit()
+con.close()
+'@ | Set-Content -LiteralPath $sqlPy -Encoding ASCII
+ $script:SqlPy = $sqlPy
+ $script:DbPath = Join-Path $H 'state.db'
+ & $RealPython $sqlPy $script:DbPath "CREATE TABLE sessions(id TEXT); CREATE TABLE messages(id TEXT); INSERT INTO sessions VALUES('s1'); INSERT INTO sessions VALUES('s2');"
+ if ($LASTEXITCODE -ne 0) { throw 'state.db fixture failed' }
+
+ New-Item -ItemType Directory -Force -Path $Install | Out-Null
+ & git -C $Install init -q -b main
+ & git -C $Install config user.email [email protected]
+ & git -C $Install config user.name test
+ Set-Content -LiteralPath (Join-Path $Install 'module_name.py') -Value 'print(1)'
+ & git -C $Install add -A | Out-Null
+ & git -C $Install -c commit.gpgsign=false commit -qm initial | Out-Null
+ & git -C $Install remote add origin https://github.com/NousResearch/hermes-agent.git
+ New-Item -ItemType Directory -Force -Path (Join-Path $Install '.hermes\bin'), (Join-Path $Install '.hermes-runtime\python') | Out-Null
+ 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"
+
+ 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":{}}'
+ Set-Content -LiteralPath (Join-Path $env:HERMES_DESKTOP_USER_DATA_DIR 'connection.json') -Value '{"session":"t"}'
+ Set-Content -LiteralPath (Join-Path $env:HERMES_DESKTOP_USER_DATA_DIR 'Local Storage\leveldb\000001.ldb') -Value 'x'
+ Set-Content -LiteralPath (Join-Path $env:HERMES_DESKTOP_USER_DATA_DIR 'Cache\data.bin') -Value 'junk'
+}
+
+try {
+ New-Fixture
+ $HeadSha = (& git -C $Install rev-parse HEAD | Out-String).Trim()
+ Write-Host "checkout HEAD: $HeadSha"
+
+ Write-Host "`n--- pre (source = the fixture repo, so no network) ---"
+ $statusBefore = (& git -C $Install status --porcelain | Out-String)
+ $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.tgz', 'electron-userdata.tgz', 'fingerprint-before.txt', 'userdata-before.txt', 'manifest.json', 'shims.txt', 'checkout.txt', 'remotes.txt')) {
+ Check "backup artifact $f" (Test-Path -LiteralPath (Join-Path $Snap $f))
+ }
+ $tarList = (& tar.exe -tzf (Join-Path $Snap 'hermes-home.tgz') | 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*$')
+ $fp = Get-Content -LiteralPath (Join-Path $Snap 'fingerprint-before.txt') -Raw
+ Check 'state.db row counts fingerprinted' ($fp -match 'sessions=2')
+
+ 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()
+ Check 'serve.git main is the custom ref' ($served -eq $HeadSha)
+ $cfg = (& git -C $Install config --local --get-regexp 'insteadOf' 2>$null | Out-String)
+ Check 'two insteadOf entries written (repo-local)' ((([regex]::Matches($cfg, 'insteadOf', 'IgnoreCase')).Count) -eq 2)
+ Check 'upstream-prompt marker created' (Test-Path -LiteralPath (Join-Path $H '.skip_upstream_prompt'))
+ $getUrl = (& git -C $Install remote get-url origin | Out-String).Trim()
+ Check 'remote get-url resolves to the rehearsal copy' ($getUrl -match 'serve\.git')
+ $configured = (& git -C $Install config --get remote.origin.url | Out-String).Trim()
+ Check 'config --get remote.origin.url stays official' ($configured -match 'NousResearch')
+
+ Write-Host "`n--- pre changed nothing else ---"
+ Check 'checkout untouched by pre' (((& git -C $Install rev-parse HEAD | Out-String).Trim()) -eq $HeadSha)
+ Check 'pre changed no files in the checkout' (((& git -C $Install status --porcelain | Out-String)) -eq $statusBefore)
+ Check 'pre says it did not update anything' ($r.Out -match 'nothing has been updated yet')
+
+ 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))
+
+ Write-Host "`n--- post ---"
+ $r = Invoke-Rehearsal -Arguments @('post', '-BackupRoot', $Backups, '-Yes')
+ Check 'post exits 0' ($r.Code -eq 0)
+ Check 'config.yaml restored' (Test-Path -LiteralPath (Join-Path $H 'config.yaml'))
+ Check '.env restored' (Test-Path -LiteralPath (Join-Path $H '.env'))
+ Check 'memories restored' (Test-Path -LiteralPath (Join-Path $H 'memories\note.md'))
+ Check 'plugin marker restored' (Test-Path -LiteralPath (Join-Path $H 'plugins\mnemosyne-wrapper\mnemosyne-wrapper.json'))
+ Check 'photon sidecar marker restored' (Test-Path -LiteralPath (Join-Path $H 'photon\sidecar\node_modules\.package-lock.json'))
+ Check 'PM store restored' (Test-Path -LiteralPath (Join-Path $Install '.hermes-runtime\python\interpreter.bin'))
+ Check 'checkout restored' (Test-Path -LiteralPath (Join-Path $Install '.git'))
+ Check 'checkout HEAD restored' (((& git -C $Install rev-parse HEAD | Out-String).Trim()) -eq $HeadSha)
+ Check 'origin remote restored' (((& git -C $Install config --get remote.origin.url | Out-String).Trim()) -eq 'https://github.com/NousResearch/hermes-agent.git')
+ Check 'userData connection.json restored' (Test-Path -LiteralPath (Join-Path $env:HERMES_DESKTOP_USER_DATA_DIR 'connection.json'))
+ $cfg2 = (& git -C $Install config --local --get-regexp 'insteadOf' 2>$null | Out-String)
+ if (-not $cfg2) { $cfg2 = '' }
+ Check 'no stale insteadOf left in the checkout' ((([regex]::Matches($cfg2, 'insteadOf', 'IgnoreCase')).Count) -eq 0)
+ 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 reports an exact state restore' ($r.Out -match 'entries match your backup')
+ if ($r.Out -notmatch 'entries match your backup') {
+ Write-Host '--- report section ---'
+ Write-Host (($r.Out -split "`n" | Select-String -Pattern 'how exact was the restore' -Context 0, 12 | Out-String))
+ }
+}
+finally {
+ # Never leave the real user PATH touched by a test.
+ [Environment]::SetEnvironmentVariable('Path', $RealUserPath, 'User')
+ if ($env:SMOKE_KEEP -eq '1') { Write-Host "root kept: $Root" }
+ else { Remove-Item -LiteralPath $Root -Recurse -Force -ErrorAction SilentlyContinue }
+}
+
+Write-Host "`n=== smoke: $pass passed, $fail failed ==="
+exit ([int]($fail -gt 0))
diff --git a/scripts/update-test/smoke-test.sh b/scripts/update-test/smoke-test.sh
new file mode 100755
index 00000000000..ab87fba53b3
--- /dev/null
+++ b/scripts/update-test/smoke-test.sh
@@ -0,0 +1,146 @@
+#!/usr/bin/env bash
+# Smoke test for hermes-update-rehearsal.sh (this directory).
+# Builds a synthetic install in a temp tree and drives pre/post/status for real.
+# Runs on macOS/Linux directly, and under git-bash on Windows (native paths).
+set -uo pipefail
+
+HERE="$(cd "$(dirname "$0")" && pwd)"
+SCRIPT="$HERE/hermes-update-rehearsal.sh"
+[ -f "$SCRIPT" ] || { echo "missing $SCRIPT"; exit 1; }
+
+echo "--- bash -n ---"
+bash -n "$SCRIPT" && echo "syntax OK" || exit 1
+
+# Native paths, so native git.exe/python.exe can reach the same files bash can.
+if command -v cygpath >/dev/null 2>&1; then ROOT="$(cygpath -m "$(mktemp -d)")"; else ROOT="$(mktemp -d)"; fi
+export HOME="$ROOT/home"; mkdir -p "$HOME"
+export GIT_CONFIG_GLOBAL="$ROOT/gitconfig-test"; : > "$GIT_CONFIG_GLOBAL"
+export HERMES_HOME="$ROOT/home/.hermes"
+export HERMES_DESKTOP_USER_DATA_DIR="$ROOT/electron-user-data"
+if tar --help 2>&1 | grep -q -- '--force-local'; then export TAR_OPTIONS=--force-local; fi
+
+H="$HERMES_HOME"; INSTALL="$H/hermes-agent"
+
+echo "--- fixture under $ROOT ---"
+mkdir -p "$H/plugins/mnemosyne-wrapper" "$H/photon/sidecar/node_modules" "$H/memories"
+mkdir -p "$H/skills/foo" "$H/cron" "$H/logs" "$ROOT/external-mnemosyne"
+printf 'name: mnemosyne-wrapper\n' > "$H/plugins/mnemosyne-wrapper/plugin.yaml"
+printf '{"wrapper":true}\n' > "$H/plugins/mnemosyne-wrapper/mnemosyne-wrapper.json"
+printf 'witness\n' > "$ROOT/external-mnemosyne/witness.txt"
+ln -sfn "$ROOT/external-mnemosyne" "$H/plugins/mnemosyne-wrapper/runtime"
+printf 'timezone: utc\n' > "$H/config.yaml"
+printf 'NOUS_API_KEY=xxx\n' > "$H/.env"
+printf '{"tokens":{}}\n' > "$H/auth.json"
+printf 'recall\n' > "$H/memories/note.md"
+printf 'jobs\n' > "$H/cron/jobs.json"
+printf 'console.log(1)\n' > "$H/photon/sidecar/index.mjs"
+printf '{"name":"sidecar"}\n' > "$H/photon/sidecar/package.json"
+printf '{"lockfileVersion":3}\n' > "$H/photon/sidecar/package-lock.json"
+printf '{"lockfileVersion":3}\n' > "$H/photon/sidecar/node_modules/.package-lock.json"
+
+python - "$H/state.db" <<'PY'
+import sqlite3, sys
+con = sqlite3.connect(sys.argv[1])
+con.execute("CREATE TABLE sessions (id TEXT PRIMARY KEY)")
+con.execute("CREATE TABLE messages (id TEXT)")
+con.executemany("INSERT INTO sessions VALUES (?)", [("s1",), ("s2",)])
+con.commit(); con.close()
+PY
+
+# the install checkout: a real repo on branch `main`, plus untracked runtime
+git init -q -b main "$INSTALL"
+git -C "$INSTALL" config user.email [email protected]
+git -C "$INSTALL" config user.name test
+printf 'print(1)\n' > "$INSTALL/module_name.py"
+git -C "$INSTALL" add -A
+git -C "$INSTALL" -c commit.gpgsign=false commit -qm initial
+git -C "$INSTALL" remote add origin https://github.com/NousResearch/hermes-agent.git
+HEAD_SHA="$(git -C "$INSTALL" rev-parse HEAD)"
+mkdir -p "$INSTALL/.hermes/bin" "$INSTALL/.hermes-runtime/python"
+printf '#!/bin/sh\necho hermes 0.0.0\n' > "$INSTALL/.hermes/bin/hermes"; chmod +x "$INSTALL/.hermes/bin/hermes"
+printf 'big' > "$INSTALL/.hermes-runtime/python/interpreter.bin"
+mkdir -p "$HOME/.local/bin"
+ln -sfn "$INSTALL/.hermes/bin/hermes" "$HOME/.local/bin/hermes"
+SYMLINKS_OK=0
+[ -L "$HOME/.local/bin/hermes" ] && SYMLINKS_OK=1
+echo "host symlink support: $SYMLINKS_OK"
+
+mkdir -p "$HERMES_DESKTOP_USER_DATA_DIR/Local Storage/leveldb" "$HERMES_DESKTOP_USER_DATA_DIR/Cache"
+printf '{"window":{}}\n' > "$HERMES_DESKTOP_USER_DATA_DIR/Preferences"
+printf '{"session":"t"}\n' > "$HERMES_DESKTOP_USER_DATA_DIR/connection.json"
+printf 'x' > "$HERMES_DESKTOP_USER_DATA_DIR/Local Storage/leveldb/000001.ldb"
+printf 'junk' > "$HERMES_DESKTOP_USER_DATA_DIR/Cache/data.bin"
+
+BACKUPS="$ROOT/backups"
+RUN=("$SCRIPT")
+pass=0; fail=0
+check() { if [ "$1" = 0 ]; then echo " PASS $2"; pass=$((pass+1)); else echo " FAIL $2"; fail=$((fail+1)); fi; }
+# `cmd | grep -q` loses to SIGPIPE under pipefail: capture, then grep.
+check_out() { local n="$1" m="$2"; shift 2; local out; out="$("$@" 2>&1 || true)"; grep -q "$n" <<< "$out"; check $? "$m"; }
+
+echo
+echo "--- pre (source = the fixture repo, so no network) ---"
+STATUS_BEFORE="$(git -C "$INSTALL" status --porcelain)"
+"${RUN[@]}" pre --source "$INSTALL" --ref main --backup-root "$BACKUPS" > "$ROOT/pre.log" 2>&1
+check $? "pre exits 0"
+SNAP="$(ls -1d "$BACKUPS"/*/ | head -1)"; SNAP="${SNAP%/}"
+for f in hermes-home.tgz electron-userdata.tgz fingerprint-before.txt userdata-before.txt manifest.json shims.txt checkout.txt remotes.txt; do
+ [ -e "$SNAP/$f" ]; check $? "backup artifact $f"
+done
+TARLIST="$(tar -tzf "$SNAP/hermes-home.tgz" 2>&1 || true)"
+grep -qE '^\./hermes-agent/\.git/config$' <<< "$TARLIST"; check $? "whole home: checkout .git in the tar"
+grep -qE '^\./hermes-agent/\.hermes-runtime/python/interpreter\.bin$' <<< "$TARLIST"; check $? "whole home: PM store in the tar"
+grep -qE '^\./config\.yaml$' <<< "$TARLIST"; check $? "whole home: config.yaml in the tar"
+grep -q 'sessions=2' "$SNAP/fingerprint-before.txt"; check $? "state.db row counts fingerprinted"
+
+echo
+echo "--- pre points the install at the rehearsal copy ---"
+[ "$(git -C "$SNAP/serve.git" rev-parse refs/heads/main)" = "$HEAD_SHA" ]; check $? "serve.git main is the custom ref"
+[ "$(git -C "$INSTALL" config --local --get-regexp 'insteadOf' | wc -l | tr -d ' ')" = 2 ]; check $? "two insteadOf entries written (repo-local)"
+[ -f "$H/.skip_upstream_prompt" ]; check $? "upstream-prompt marker created"
+git -C "$INSTALL" remote get-url origin | grep -q 'serve.git'; check $? "remote get-url resolves to the rehearsal copy"
+git -C "$INSTALL" config --get remote.origin.url | grep -q 'NousResearch'; check $? "config --get remote.origin.url stays official"
+
+echo
+echo "--- pre changed nothing else ---"
+[ "$(git -C "$INSTALL" rev-parse HEAD)" = "$HEAD_SHA" ]; check $? "checkout untouched by pre"
+[ "$(git -C "$INSTALL" status --porcelain)" = "$STATUS_BEFORE" ]; check $? "pre changed no files in the checkout"
+grep -q 'nothing has been updated yet' "$ROOT/pre.log"; check $? "pre says it did not update anything"
+
+echo
+echo "--- status (read-only) ---"
+check_out "$HEAD_SHA" "status reports what it prepared" "${RUN[@]}" status --backup-root "$BACKUPS"
+
+echo
+echo "--- post ---"
+"${RUN[@]}" post --backup-root "$BACKUPS" --yes > "$ROOT/post.log" 2>&1
+check $? "post exits 0"
+[ -f "$H/config.yaml" ]; check $? "config.yaml restored"
+[ -f "$H/.env" ]; check $? ".env restored"
+[ -f "$H/memories/note.md" ]; check $? "memories restored"
+[ -f "$H/plugins/mnemosyne-wrapper/mnemosyne-wrapper.json" ]; check $? "plugin marker restored"
+[ -f "$H/photon/sidecar/node_modules/.package-lock.json" ]; check $? "photon sidecar marker restored"
+[ -f "$INSTALL/.hermes-runtime/python/interpreter.bin" ]; check $? "PM store restored"
+[ -d "$INSTALL/.git" ]; check $? "checkout restored"
+[ "$(git -C "$INSTALL" rev-parse HEAD)" = "$HEAD_SHA" ]; check $? "checkout HEAD restored"
+[ "$(git -C "$INSTALL" config --get remote.origin.url)" = "https://github.com/NousResearch/hermes-agent.git" ]; check $? "origin remote restored"
+[ -f "$HERMES_DESKTOP_USER_DATA_DIR/connection.json" ]; check $? "userData connection.json restored"
+[ "$(git -C "$INSTALL" config --local --get-regexp 'insteadOf' 2>/dev/null | wc -l | tr -d ' ')" = 0 ]; check $? "no stale insteadOf left in the checkout"
+[ ! -f "$H/.skip_upstream_prompt" ]; check $? "upstream-prompt marker removed"
+git -C "$INSTALL" remote get-url origin | grep -q 'NousResearch'; check $? "origin resolves officially again"
+if [ "$SYMLINKS_OK" = 1 ]; then
+ [ -L "$HOME/.local/bin/hermes" ]; check $? "user-bin shim restored as a symlink"
+else
+ echo " SKIP user-bin shim symlink (host cannot create symlinks)"
+fi
+grep -q 'entries match your backup' "$ROOT/post.log"; check $? "post reports an exact state restore"
+if ! grep -q 'entries match your backup' "$ROOT/post.log"; then
+ echo " --- report section of post.log ---"
+ sed -n '/how exact was the restore/,$p' "$ROOT/post.log" | sed 's/^/ /' | head -20
+ [ -e "$SNAP/fingerprint-restore.diff" ] && sed 's/^/ /' "$SNAP/fingerprint-restore.diff" | head -30
+fi
+
+echo
+echo "=== smoke: $pass passed, $fail failed ==="
+if [ "${SMOKE_KEEP:-0}" = 1 ]; then echo "root kept: $ROOT"; else rm -rf "$ROOT"; fi
+exit $(( fail > 0 ))