Skip to content

The agent that grows with you

docs(update): describe the post-swap hand-off; add its live A/B harness

teknium132d958bcda9a
diff --git a/evals/update_pipeline/post_swap_handoff_ab.sh b/evals/update_pipeline/post_swap_handoff_ab.sh
new file mode 100755
index 00000000000..1e7606d5161
--- /dev/null
+++ b/evals/update_pipeline/post_swap_handoff_ab.sh
@@ -0,0 +1,72 @@
+#!/usr/bin/env bash
+# Live A/B for the post-swap hand-off (hermes_cli/update_handoff.py).
+#
+# Installs a real clone at <installed-sha>, publishes a target commit on its origin that
+# (a) adds a symbol to hermes_logging (purge-protected on the old updater),
+# (b) imports it at module level from hermes_cli/config.py (re-imported by the old updater's
+# config-migration step → stale-symbol ImportError class, #111271/#112604), and
+# (c) tags the completion line from update_cmd_maint.py with which code printed it,
+# then runs `hermes update` from the installed clone and reads the receipt + output.
+#
+# evals/update_pipeline/post_swap_handoff_ab.sh <repo> <installed-sha> <label>
+#
+# Phase A (installed-sha = merge-base): the tail runs in the pre-pull interpreter — old
+# completion line, "Could not check config version". Phase B (head): tag present, no warning.
+# Needs: uv on PATH, a Python for the venv. Runs with a disposable HOME/HERMES_HOME, no npm
+# on PATH (skips Node/web/Desktop work) and --no-gateway-restart (never touches your fleet).
+set -euo pipefail
+REPO=$1; SHA=$2; LABEL=$3
+ROOT=$(mktemp -d /tmp/hermes-post-swap-ab.XXXXXX)
+echo "== [$LABEL] scratch: $ROOT (installed at ${SHA:0:10})"
+git clone -q --bare --shared "$REPO" "$ROOT/origin.git"
+git --git-dir="$ROOT/origin.git" update-ref refs/heads/main "$SHA"
+git clone -q --shared -b main "$ROOT/origin.git" "$ROOT/install"
+
+# Target commit: what the NEXT update pulls.
+git clone -q --shared -b main "$ROOT/origin.git" "$ROOT/author"
+(
+ cd "$ROOT/author"
+ printf '\n\ndef post_swap_probe() -> str:\n """Added by the update under test."""\n return "pulled-code"\n' >> hermes_logging.py
+ python3 - <<'PY'
+import re
+p = "hermes_cli/config.py"; s = open(p).read()
+s = s.replace("import logging\n", "import logging\nfrom hermes_logging import post_swap_probe # noqa: F401 (A/B probe: new symbol on a cached module)\n", 1)
+open(p, "w").write(s)
+p = "hermes_cli/update_cmd_maint.py"; s = open(p).read()
+needle = 'def _update_complete_message('
+i = s.index(needle); j = s.index('\n', s.index('"""', s.index('"""', i) + 3)) + 1 # end of docstring
+s = s[:j] + ' from hermes_logging import post_swap_probe\n print(f" [completion printed by: {post_swap_probe()}]")\n' + s[j:]
+open(p, "w").write(s)
+PY
+ git -c user.name=ab -c [email protected] commit -qam "probe: new hermes_logging symbol used by config.py and the completion line"
+ git push -q origin main
+)
+
+# Venv for the installed clone (deps unchanged between the two commits → the updater skips the sync).
+uv venv -q --python "${HERMES_AB_PYTHON:-3.11}" "$ROOT/install/.venv"
+uv pip install -q --python "$ROOT/install/.venv/bin/python" -e "$ROOT/install"
+
+export HOME="$ROOT/home" HERMES_HOME="$ROOT/home/.hermes"
+mkdir -p "$HERMES_HOME"
+export PATH="$ROOT/install/.venv/bin:/usr/bin:/bin"
+set +e
+( cd "$ROOT/install" && python -m hermes_cli.main update --yes --no-backup --no-gateway-restart ) > "$ROOT/update.out" 2>&1
+CODE=$?
+set -e
+echo "== [$LABEL] exit=$CODE head=$(git -C "$ROOT/install" rev-parse --short HEAD)"
+grep -nE "completion printed by|Could not check config version|Update complete|Code updated|Traceback|Error" "$ROOT/update.out" | head -20 || true
+python3 - "$HERMES_HOME/logs/update_receipts/latest.json" <<'PY'
+import json, sys
+try:
+ r = json.load(open(sys.argv[1]))
+except Exception as exc:
+ print("receipt: NONE", exc); sys.exit(0)
+print("receipt:", r.get("outcome"), "exit", r.get("exit_code"), "pid", r.get("pid"), "post_swap_pid", r.get("post_swap_pid"),
+ "steps", [s["name"] for s in r.get("steps", [])], "stop", (r.get("stop_reason") or "")[:60])
+PY
+if grep -q "completion printed by: pulled-code" "$ROOT/update.out" && ! grep -q "Could not check config version" "$ROOT/update.out"; then
+ echo "VERDICT: [$LABEL] tail ran on the PULLED code"
+else
+ echo "VERDICT: [$LABEL] tail ran in the PRE-PULL interpreter (stale-symbol class reachable)"
+fi
+echo " log: $ROOT/update.out"
diff --git a/hermes_cli/AGENTS.md b/hermes_cli/AGENTS.md
index c543788be5a..142a16e9ef7 100644
--- a/hermes_cli/AGENTS.md
+++ b/hermes_cli/AGENTS.md
@@ -129,15 +129,23 @@ it guards. `plan → snapshot → apply → restart-per-kind → verify → repo
(`latest.json` pointer; steps, skips WITH reasons, restart outcome, plan, fleet snapshot).
Finalization is owned by the `cmd_update` command boundary — early `sys.exit` paths (preflight
refusals, fetch failures) still persist a receipt with the real exit code. A begun-but-unwritten
- receipt is a bug: refused/failed runs are the ones receipts exist for. The receipt writer runs in
- the PRE-pull interpreter after the module purge, so `update_receipt.py` may import only stdlib and
- purge-protected modules (`hermes_constants`) — a `hermes_cli.config` import there re-executed the
- pulled config against a stale `utils` and silently dropped the whole receipt; a write failure
- prints `⚠ Update receipt not written` and logs at WARNING, never debug.
-- **Post-update steps are isolated**: everything after the code swap that runs pulled code in the
- pre-pull process (`_finish_dashboard_update_cleanup`, notices, probes) catches its own failure,
- prints it, and records a failed receipt step — one stale-symbol `AttributeError` must not abort
- the fleet matrix, reconciliation and receipt finalize that follow it.
+ receipt is a bug: refused/failed runs are the ones receipts exist for. The receipt is opened by
+ the pre-swap process and finished by the post-swap child (below): `detach_update_receipt` /
+ `resume_update_receipt` carry it across, so one run still yields exactly one receipt. A write
+ failure prints `⚠ Update receipt not written` and logs at WARNING, never debug.
+- **Nothing runs pulled code in the pre-pull interpreter** (`update_handoff.py`). The process that
+ started `hermes update` imported the PRE-pull tree; once git (or the ZIP swap) has replaced the
+ checkout it stops, writes the hand-off payload (open receipt, pre-update plan, pre-update
+ version/active features, Windows pause token) and re-executes
+ `hermes update <same flags> --post-swap <file>` under the venv interpreter, which imports only the
+ pulled tree and owns the tail (deps, Node/web/Desktop, maintenance, config migration, fleet
+ restart, verification, receipt); the parent relays the exit code. Every "purge `sys.modules`" /
+ "reload this list of modules" / "isolate this one step" fix was a symptom of the old shape and is
+ gone — do not reintroduce one: a phase that needs new code runs in the child, full stop. Mocked
+ updater tests run the tail in-process via the `_inline_post_swap_handoff` autouse fixture
+ (`@pytest.mark.real_post_swap_handoff` opts out). Live A/B:
+ `evals/update_pipeline/post_swap_handoff_ab.sh`. Post-update steps still isolate their own
+ failures (a crashed notice must not abort the fleet matrix and receipt finalize that follow).
Process-scan coordination between updater, serve/dashboard, and gateway is being replaced by a
gateway-owned control socket (#92091); scans are the fallback layer for old/crashed processes — read
diff --git a/hermes_cli/update_abort_recovery.py b/hermes_cli/update_abort_recovery.py
index 8dd22d5c722..2dfdf5cd506 100644
--- a/hermes_cli/update_abort_recovery.py
+++ b/hermes_cli/update_abort_recovery.py
@@ -1,6 +1,5 @@
-"""Fresh-process recovery after the update's in-process restart phase aborts (the fleet restart
-runs in the interpreter that started before ``git pull``). Separate owner from ``update_cmd``: its
-own vocabulary (``verified`` / ``relaunch_attempted`` / ``failed``, serve units, survivors) and
+"""Fresh-process recovery after the update's in-process restart phase aborts. Separate owner
+from ``update_cmd``: its own vocabulary (``verified`` / ``relaunch_attempted`` / ``failed``, serve units, survivors) and
its own fail-closed contract."""
from __future__ import annotations
@@ -149,8 +148,8 @@ def _parse_serve_units(raw_serve, *, recover_serve: bool) -> dict[str, list]:
def _recover_gateway_restart_after_abort(
plan, *, gateway_mode: bool, skip_profiles: set[str] | None = None,
skip_units: set[str] | None = None) -> dict[str, list]:
- """Retry supervised gateway restarts from a clean Python process (the in-process restart ran
- in the pre-``git pull`` interpreter). Only inventory-classified supervisor-owned profiles.
+ """Retry supervised gateway restarts from a clean Python process. Only inventory-classified
+ supervisor-owned profiles.
``skip_units`` names the units the aborted phase already settled, as ``<scope>/<unit>``. The scope is
part of the identity, not decoration: ``hermes-serve.service`` can exist in both the user and the system
diff --git a/hermes_cli/update_cmd_maint.py b/hermes_cli/update_cmd_maint.py
index ba4eeb410e7..537cb223d21 100644
--- a/hermes_cli/update_cmd_maint.py
+++ b/hermes_cli/update_cmd_maint.py
@@ -257,10 +257,10 @@ def _finish_dashboard_update_cleanup(
restart_managed=True, already_restarted_units=already_restarted_units
)
except Exception as exc:
- # Isolated like every sibling post-update step: this runs in the pre-pull interpreter
- # against pulled code, and a symbol gap here (#112604) used to abort the fleet matrix,
- # reconciliation and the inner receipt finalize that follow it. A dashboard/serve left
- # on pre-update code is still caught by the survivor probe → reconciliation (exit 1).
+ # Isolated like every sibling post-update step: a failure here (#112604) used to abort
+ # the fleet matrix, reconciliation and the inner receipt finalize that follow it. A
+ # dashboard/serve left on pre-update code is still caught by the survivor probe →
+ # reconciliation (exit 1).
logger.warning("Post-update dashboard cleanup failed: %s", exc)
_record_update_step("dashboard_cleanup", False, f"{type(exc).__name__}: {exc}")
print()
diff --git a/hermes_cli/update_receipt.py b/hermes_cli/update_receipt.py
index 3aa876ad95a..9a0fd74b7ab 100644
--- a/hermes_cli/update_receipt.py
+++ b/hermes_cli/update_receipt.py
@@ -117,11 +117,9 @@ class UpdateReceipt:
def _receipt_dir() -> Path:
- # ``hermes_constants``, never ``hermes_cli.config``: the receipt is written by the PRE-pull
- # interpreter after the post-pull module purge, so a ``hermes_cli.config`` import here
- # re-executes the pulled config.py against whatever is still cached — an ImportError on a
- # symbol the pull added dropped the whole receipt (#112465, #112558). ``hermes_constants``
- # is protected from the purge and stdlib-only.
+ # ``hermes_constants`` (stdlib-only), never ``hermes_cli.config``: the receipt must be
+ # writable from the refused/failed paths where config loading itself may be what broke
+ # (#112465, #112558).
from hermes_constants import get_hermes_home
return get_hermes_home() / "logs" / "update_receipts"
diff --git a/website/docs/getting-started/updating.md b/website/docs/getting-started/updating.md
index c342759a059..82ee38d05cb 100644
--- a/website/docs/getting-started/updating.md
+++ b/website/docs/getting-started/updating.md
@@ -37,6 +37,7 @@ When you run `hermes update`, the following steps occur:
1. **Pre-update snapshot** — a lightweight state snapshot is saved by default (covers pairing data, cron jobs, `config.yaml`, `.env`, `auth.json`, and other state files that get modified at runtime; individual files over 1 GiB are skipped so a large sessions DB never slows the update down). Because the code swap and gateway restarts touch every profile, the same snapshot is taken for **every profile** on the install — each into its own `state-snapshots/` directory — and the post-update cron-jobs safety net checks each profile against its own snapshot. Controlled by `updates.pre_update_backup` (`quick` by default, `full` for a zip of all of `HERMES_HOME`, `off` to disable). Recoverable via the snapshot restore flow described under [Snapshots and rollback](../user-guide/checkpoints-and-rollback.md). Quick snapshots are file-loss recovery, not code-rollback insurance — for a coherent point-in-time rollback use `--backup` (full mode).
2. **Git pull** — pulls the latest code from the `main` branch and updates submodules
3. **Post-pull syntax validation + auto-rollback** — after the pull, Hermes compiles the nine critical files every `hermes` invocation imports at startup. If any fails to parse (e.g. an orphan merge-conflict marker, an accidentally truncated file), Hermes runs `git reset --hard <pre-pull-sha>` to roll the install back so your shell stays bootable. Re-run `hermes update` once the upstream fix lands.
+ After this point the updater re-executes itself on the freshly pulled code (`update.log` shows `=== hermes update continued on the pulled code ===`), so the remaining steps never mix old and new modules in one process. If you see two `hermes update` processes for a moment, that is the hand-off.
4. **Dependency install** — runs `uv pip install -e ".[all]"` to pick up new or changed dependencies
5. **Config migration** — detects new config options added since your version and prompts you to set them
6. **Desktop rebuild (stage-and-swap)** — if the Hermes Desktop app was built from this checkout, it is rebuilt so the GUI matches the new code. The rebuild packs into a temporary staging directory next to `apps/desktop/release/`, verifies the staged app, and only then renames it over the previous build. A rebuild that fails at any point — corrupt Electron download, missing dependency, disk full — leaves the previous app untouched and launchable; the update reports `⚠ Update partially complete` and `hermes desktop` retries the rebuild.