Skip to content

The agent that grows with you

test(install-e2e): assert the user's own state survives an upgrade

ethernetbf499370bd8e
diff --git a/tests/install/README.md b/tests/install/README.md
index 99a26180711..2e3fad2e810 100644
--- a/tests/install/README.md
+++ b/tests/install/README.md
@@ -210,6 +210,53 @@ contract and not exercised.
stable-to-stable when BOTH the install ref and the target ref are release
tags. The workflow matrix itself is unchanged.
+## Manual update rehearsals
+
+There is no `manual/` directory in this repo. The rehearsal scripts — `pre`
+(back up the whole `HERMES_HOME`, the desktop app's Electron userData, the
+`hermes` shims on PATH and the global git config, then point the install's
+update source at a custom repo + ref) and `post` (undo all of it and report how
+exact the restore was) — are a hand-off kit for someone with a *real* install,
+kept outside this checkout on purpose: they are not part of the repo and not
+wired into any lane here.
+
+What *is* in the repo is the assertion layer they exist to demonstrate. The
+user-state preservation checks below run on every upgrade leg; the manual kit
+only reproduces the same upgrade on a machine you care about, where a backup
+and a restore are the only honest way to do it.
+
+## User-state preservation
+
+Alongside the plugin-tree contract below, every upgrade leg also carries a
+**user-state** contract: an upgrade may add state, may rewrite `config.yaml`
+(additive config migration) and the bundled `skills/` tree (the product
+re-syncs it), but it may not delete or modify the user's own durable state —
+`.env`, `auth.json`, `state.db`, `gateway_state.json`, `memories/`, `cron/`,
+`sessions/`, `profiles/`, `photon/`, `desktop-plugins/`, `tui-widgets/`,
+`skins/`, `pets/`, `skills/.archive/` — and `state.db` may not lose rows.
+
+- `e2e-assets/verify-user-state.py` is the shared, stdlib-only, read-only
+ verifier. It records row counts for `state.db` rather than bytes (a live
+ SQLite file changes for benign reasons), and it has **no** `seed` mode on
+ purpose: the state it defends must be produced by the product through the
+ ordinary user path, never hand-written by the harness.
+- `e2e-assets/user-state-actions.sh` produces that state with real commands —
+ `hermes chat -q` (a real turn → `sessions/` + `state.db` rows),
+ `hermes auth add` (→ `auth.json`), `hermes profile create`
+ (→ `profiles/<name>/`) — after probing `--help` for each flag, per the
+ harness's "probe, do not assume" rule. Each action asserts it actually landed,
+ so a leg can never "pass" while testing nothing.
+- `e2e-assets/preserve-user-state.sh` is the POSIX/macOS hook pair
+ (snapshot before the upgrade, verify after). Windows calls the same Python
+ `snapshot`/`verify` from `windows-e2e.ps1`'s phases, alongside its existing
+ plugin hooks.
+- Two more invariants ride along: the redirect must stay transport-level
+ (`config --get remote.origin.url` stays official while `remote get-url` is
+ rewritten), and the user-visible launcher must still exist and run after the
+ upgrade.
+- Unit tests live at `tests/scripts/test_verify_user_state.py` and exercise the
+ verifier against a real temp filesystem with real sqlite databases.
+
## Artifacts
Each leg uploads its logs as an artifact. Every leg also records the screen for its whole run: the composite action `.github/actions/e2e-screen-record` records with the OS's capture backend (x11grab on linux, gdigrab on windows, avfoundation on macos), and fails the leg if the recording is missing or has zero frames. ffmpeg itself comes from the PM toolchain — jobs pass `packages: ffmpeg` to `actions/setup-pm`, which installs the locked, sha256-pinned build (native per-OS, including win32-arm64) and puts it on `PATH`; the action only verifies it is there. Linux runners have no display, so the action starts `Xvfb :99` first and exports `DISPLAY` for every later step — the app under test and the recorder share that display. The windows GUI leg also uploads screenshots and the update result file. Get them with `gh run download <run-id>`.
diff --git a/tests/install/e2e-assets/preserve-user-state.sh b/tests/install/e2e-assets/preserve-user-state.sh
new file mode 100644
index 00000000000..ce77efecad5
--- /dev/null
+++ b/tests/install/e2e-assets/preserve-user-state.sh
@@ -0,0 +1,71 @@
+#!/usr/bin/env bash
+# Shared user-state preservation hooks for the install E2E drivers
+# (POSIX + macOS + Windows-via-bash). Sourced by installer-script-e2e.sh and
+# scripts under tests/install/.
+#
+# The contract under test: a tagged upgrade must not delete or modify the
+# user's OWN durable state — config.yaml (additive rewrites only), .env,
+# auth.json, state.db (row counts may not shrink), gateway_state.json,
+# memories/, cron/, sessions/, profiles/, photon/, desktop-plugins/,
+# tui-widgets/, skins/, pets/, and skills/.archive/. Additions are fine; an
+# upgrade may add files, it may not take yours away or alter them.
+#
+# Everything this verifies is produced by the PRODUCT through the ordinary user
+# path (see user-state-actions.sh) — never seeded by the harness. Asserting over
+# fixtures we wrote ourselves would only prove the harness can write files.
+#
+# Not owned here, by design:
+# plugins/** -> preserve-plugins.sh / verify-plugin-preservation.py
+# config migration -> config.yaml and state.db are reported, not judged
+# (their real contract is the row-count check)
+# skills/ bulk -> re-synced from the bundled library by the product
+#
+# State flow (called by the driver):
+# user_state_before_upgrade snapshot -> $USER_STATE_SNAPSHOT
+# user_state_after_upgrade verify (exit 1 on violation)
+#
+# Requires: HERMES_HOME set (the leg's isolated home), WORK_ROOT, LOG_DIR,
+# REPO_ROOT. Verifier: tests/install/e2e-assets/verify-user-state.py
+# (stdlib-only; runs under python3 or $HERMES_E2E_PYTHON).
+
+USER_STATE_SNAPSHOT="$WORK_ROOT/user-state-snapshot.json"
+USER_STATE_REPORT="$LOG_DIR/user-state-report.json"
+USER_STATE_VERIFIER="$REPO_ROOT/tests/install/e2e-assets/verify-user-state.py"
+
+_user_state_python() {
+ if [ -n "${HERMES_E2E_PYTHON:-}" ]; then
+ printf '%s' "$HERMES_E2E_PYTHON"
+ else
+ printf 'python3'
+ fi
+}
+
+user_state_before_upgrade() {
+ step "user state: snapshotting what the user already has"
+ [ -f "$USER_STATE_VERIFIER" ] || fail "user-state verifier missing at $USER_STATE_VERIFIER"
+ [ ! -e "$USER_STATE_SNAPSHOT" ] || fail "refusing to overwrite an existing user-state snapshot"
+ local py rc=0
+ py="$(_user_state_python)"
+ "$py" "$USER_STATE_VERIFIER" snapshot --home "$HERMES_HOME" --out "$USER_STATE_SNAPSHOT" \
+ 2>&1 | ts_prefix > "$LOG_DIR/user-state-snapshot.log" || rc=$?
+ log_group "user-state snapshot transcript" "$LOG_DIR/user-state-snapshot.log"
+ # 3 = inconclusive (nothing to protect). That is a broken leg, not a pass:
+ # an empty contract would make the post-upgrade verify meaningless.
+ [ "$rc" -eq 0 ] || fail "user-state snapshot failed (exit $rc); see $LOG_DIR/user-state-snapshot.log"
+ ok "user-state snapshot at $USER_STATE_SNAPSHOT"
+}
+
+user_state_after_upgrade() {
+ step "user state: verifying the upgrade did not take anything away"
+ [ -f "$USER_STATE_SNAPSHOT" ] \
+ || fail "no pre-upgrade user-state snapshot; cannot claim preservation"
+ local py rc=0
+ py="$(_user_state_python)"
+ "$py" "$USER_STATE_VERIFIER" verify --home "$HERMES_HOME" \
+ --snapshot "$USER_STATE_SNAPSHOT" --report "$USER_STATE_REPORT" \
+ > "$LOG_DIR/user-state-verify.log" 2>&1 || rc=$?
+ log_group "user-state verify transcript" "$LOG_DIR/user-state-verify.log"
+ [ "$rc" -eq 0 ] \
+ || fail "the upgrade changed the user's own state; report at $USER_STATE_REPORT"
+ ok "user state survived: $(grep -o 'user-state preservation OK.*' "$LOG_DIR/user-state-verify.log" | head -1)"
+}
diff --git a/tests/install/e2e-assets/user-state-actions.sh b/tests/install/e2e-assets/user-state-actions.sh
new file mode 100644
index 00000000000..a423125385e
--- /dev/null
+++ b/tests/install/e2e-assets/user-state-actions.sh
@@ -0,0 +1,89 @@
+#!/usr/bin/env bash
+# Produce the user state that preserve-user-state.sh verifies — through the
+# ORDINARY user surface, never by writing files ourselves.
+#
+# Why this exists: an upgrade-preservation check over fixtures the harness wrote
+# proves only that the harness can write files. Everything here is a real
+# command a user would run, against the leg's real installed CLI, with a real
+# (mocked-inference) provider configured:
+#
+# hermes chat -q ... a real turn -> sessions/ transcripts + state.db rows
+# hermes auth add ... a pooled credential -> auth.json
+# hermes profile create .. a second profile -> profiles/<name>/**
+#
+# The assertions below are about OUR fixture production, not about the upgrade:
+# if an action silently produces nothing, the leg would "pass" the preservation
+# check while testing nothing, so each action proves it landed.
+#
+# Requires: hermes command, HERMES_HOME, ok/fail helpers. Sourced by the driver.
+
+# Probe, do not assume (the harness's rule for old refs): use a flag only if the
+# installed CLI advertises it.
+_user_state_help_has() {
+ local hermes="$1" flag="$2"
+ "$hermes" chat --help 2>&1 | grep -qF -- "$flag"
+}
+
+_user_state_db_sessions() {
+ local py out
+ py="$(_user_state_python)"
+ out="$("$py" - "$HERMES_HOME/state.db" <<'PY' 2>/dev/null || true
+import sqlite3, sys
+try:
+ con = sqlite3.connect(f"file:{sys.argv[1]}?mode=ro", uri=True)
+ print(con.execute("SELECT COUNT(*) FROM sessions").fetchone()[0])
+except Exception:
+ print(-1)
+PY
+)"
+ printf '%s' "${out:--1}"
+}
+
+user_state_produce() {
+ local hermes="$1"
+ step "user state: producing it through the ordinary CLI"
+
+ # --- a real turn ---------------------------------------------------------
+ local before after
+ before="$(_user_state_db_sessions)"
+ if _user_state_help_has "$hermes" "--quiet" || _user_state_help_has "$hermes" "-q"; then
+ local rc=0
+ HERMES_DISABLE_LAZY_INSTALLS=1 "$hermes" chat -q "Reply with the single word: ok" \
+ > "$LOG_DIR/user-state-chat.log" 2>&1 || rc=$?
+ log_group "first real chat turn" "$LOG_DIR/user-state-chat.log"
+ [ "$rc" -eq 0 ] || fail "the first chat turn failed (exit $rc); see $LOG_DIR/user-state-chat.log"
+ else
+ # No one-shot flag on this ref: a piped prompt would need a PTY. Record the
+ # gap loudly rather than pretending the leg covered sessions.
+ fail "the installed CLI has no one-shot chat flag; this leg cannot produce a session through the user path"
+ fi
+ after="$(_user_state_db_sessions)"
+ if [ "${before:-0}" -ge 0 ] && [ "${after:-0}" -gt "${before:-0}" ]; then
+ ok "a real turn created a session (state.db sessions $before -> $after)"
+ else
+ fail "the chat turn produced no session row (state.db sessions $before -> $after)"
+ fi
+
+ # --- a pooled credential -------------------------------------------------
+ if [ ! -f "$HERMES_HOME/auth.json" ]; then
+ HERMES_DISABLE_LAZY_INSTALLS=1 \
+ "$hermes" auth add mock --type api-key --api-key "e2e-preservation-not-a-real-key" \
+ > "$LOG_DIR/user-state-auth.log" 2>&1 \
+ || fail "hermes auth add failed; see $LOG_DIR/user-state-auth.log"
+ [ -s "$HERMES_HOME/auth.json" ] || fail "hermes auth add produced no auth.json"
+ ok "a pooled credential exists (auth.json)"
+ else
+ ok "auth.json already present"
+ fi
+
+ # --- a second profile ----------------------------------------------------
+ if [ ! -d "$HERMES_HOME/profiles/e2e-second" ]; then
+ HERMES_DISABLE_LAZY_INSTALLS=1 \
+ "$hermes" profile create e2e-second > "$LOG_DIR/user-state-profile.log" 2>&1 \
+ || fail "hermes profile create failed; see $LOG_DIR/user-state-profile.log"
+ [ -d "$HERMES_HOME/profiles/e2e-second" ] || fail "hermes profile create produced no profile dir"
+ ok "a second profile exists (profiles/e2e-second)"
+ else
+ ok "the second profile already exists"
+ fi
+}
\ No newline at end of file
diff --git a/tests/install/e2e-assets/verify-user-state.py b/tests/install/e2e-assets/verify-user-state.py
new file mode 100644
index 00000000000..50deed32885
--- /dev/null
+++ b/tests/install/e2e-assets/verify-user-state.py
@@ -0,0 +1,420 @@
+#!/usr/bin/env python3
+"""User-state upgrade-preservation verifier (Hermes install/update E2E hook).
+
+Answers the question the install/update E2E legs only answered indirectly:
+after an upgrade, is the user's *own* state still there?
+
+Standalone and stdlib-only. Both modes are read-only against the home; nothing
+is ever created, deleted or written under it. There is deliberately NO `seed`
+mode: the state this verifies must be produced by the product through the
+ordinary user path (a real chat turn, `hermes auth add`, `hermes profile
+create`), never hand-written by the harness. Assertions over fixtures we wrote
+ourselves would only prove the harness can write files.
+
+ snapshot walk the durable state of a HERMES_HOME and record, per entry —
+ kind (file/dir/symlink), byte size + sha256 for regular files, link
+ target, and, for every state.db, its ROW COUNTS — into JSON.
+ verify re-walk and diff against a snapshot. FAILS (exit 1) on any deleted
+ or modified entry. New entries are reported but tolerated: an
+ upgrade may add files, it may not take yours away or alter them.
+
+Two things are deliberately NOT failed on:
+
+* ``config.yaml`` (root and per-profile) is rewritten by config migration. The
+ rewrite is additive by design, so it is reported, never judged.
+* ``skills/**`` is seeded and re-synced from the bundled library at startup and
+ after every update (``tools.skills_sync.sync_skills``). It changes on an
+ ordinary release, so it is advisory-only. The exception is
+ ``skills/.archive/**``, which holds restorable *user* skills and therefore
+ is judged like everything else.
+
+Ownership: the ``plugins/**`` trees belong to verify-plugin-preservation.py —
+that contract (nothing deleted or modified, additions tolerated) is already
+enforced separately, so this tool does not double-own them.
+
+Unreadable paths are a hard error (exit 2), never a silent skip: a scanner that
+cannot see a file cannot defend it. An empty snapshot is refused as
+inconclusive (exit 3) rather than reported as a pass.
+
+Usage:
+ python verify-user-state.py snapshot --home <HERMES_HOME> --out snap.json
+ python verify-user-state.py verify --home <HERMES_HOME> --snapshot snap.json [--report r.json]
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import os
+import sqlite3
+import stat
+import sys
+from pathlib import Path
+
+SCHEMA_VERSION = 1
+PROFILES_DIR = "profiles"
+PLUGIN_ROOT = "plugins"
+SKILLS_ROOT = "skills"
+SKILL_ARCHIVE = ".archive"
+CHUNK = 1 << 20
+
+# Top-level files whose content must survive verbatim.
+JUDGED_FILES = ("config.yaml", ".env", "auth.json", "state.db", "gateway_state.json")
+# Trees that must survive: every entry under them is judged.
+JUDGED_ROOTS = ("memories", "cron", "sessions", "profiles", "photon",
+ "desktop-plugins", "tui-widgets", "skins", "pets",
+ "skills/" + SKILL_ARCHIVE)
+# Trees recorded for the report but never judged (see the module docstring).
+ADVISORY_ROOTS = (SKILLS_ROOT,)
+# state.db tables whose row counts stand in for "the user's data is still here".
+# Counting rows rather than hashing bytes: a live SQLite file changes for
+# benign reasons (WAL checkpoint, migration, a later turn).
+COUNTED_TABLES = ("sessions", "messages", "usage", "cron_jobs")
+
+
+class ScanError(Exception):
+ pass
+
+
+def _sha256_file(path: str) -> str:
+ digest = hashlib.sha256()
+ with open(path, "rb") as handle:
+ while True:
+ block = handle.read(CHUNK)
+ if not block:
+ break
+ digest.update(block)
+ return digest.hexdigest()
+
+
+def _is_link(path: str) -> bool:
+ """True for symlinks everywhere, and for NTFS junctions on Windows
+ (st.islink() is False for junctions, but readlink() works)."""
+ if os.path.islink(path):
+ return True
+ st = os.lstat(path)
+ reparse = getattr(st, "st_file_attributes", 0)
+ return bool(reparse & stat.FILE_ATTRIBUTE_REPARSE_POINT)
+
+
+def _lexists(path: str) -> bool:
+ """Exists including dangling symlinks/junctions (os.path.exists resolves)."""
+ try:
+ os.lstat(path)
+ return True
+ except FileNotFoundError:
+ return False
+ except OSError:
+ return False
+
+
+def _db_counts(path: str) -> dict | None:
+ """Row counts for COUNTED_TABLES present in the db, or None if unreadable."""
+ try:
+ con = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
+ except sqlite3.Error:
+ return None
+ try:
+ names = {row[0] for row in con.execute(
+ "SELECT name FROM sqlite_master WHERE type='table'")}
+ counts = {}
+ for table in COUNTED_TABLES:
+ if table in names:
+ counts[table] = con.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]
+ return counts
+ except sqlite3.Error:
+ return None
+ finally:
+ con.close()
+
+
+def _owns_plugins(rel: str, *, profiles: bool) -> bool:
+ """plugins/** belongs to verify-plugin-preservation.py, at both roots."""
+ parts = rel.split("/")
+ if not profiles:
+ return parts[0] == PLUGIN_ROOT
+ # profiles/<name>/plugins/...
+ return len(parts) >= 3 and parts[2] == PLUGIN_ROOT
+
+
+def _is_bundled_skill(rel: str, *, profiles: bool) -> bool:
+ """skills/** except skills/.archive/**, at both roots (see module docstring)."""
+ parts = rel.split("/")
+ if not profiles:
+ return parts[0] == SKILLS_ROOT and not (
+ len(parts) > 1 and parts[1] == SKILL_ARCHIVE)
+ if len(parts) >= 3 and parts[2] == SKILLS_ROOT:
+ return not (len(parts) > 3 and parts[3] == SKILL_ARCHIVE)
+ return False
+
+
+def _entry_record(abs_path: str) -> dict:
+ if _is_link(abs_path):
+ record: dict = {"kind": "symlink", "target": os.readlink(abs_path)}
+ record["target_resolves"] = os.path.exists(os.path.realpath(abs_path))
+ return record
+ if os.path.isdir(abs_path):
+ return {"kind": "dir"}
+ if os.path.isfile(abs_path):
+ st = os.lstat(abs_path)
+ record = {"kind": "file", "size": st.st_size}
+ if os.path.basename(abs_path) == "state.db":
+ counts = _db_counts(abs_path)
+ if counts is not None:
+ # Row counts, not bytes: a byte hash of a live db is noise.
+ record["rows"] = counts
+ else:
+ record["sha256"] = _sha256_file(abs_path)
+ else:
+ record["sha256"] = _sha256_file(abs_path)
+ return record
+ return {"kind": "other"}
+
+
+def _walk_root(home: str, root_rel: str, *, profiles: bool, judged: bool):
+ """Yield (rel_path, abs_path) for every entry under a root, pruning the
+ trees owned elsewhere (plugins) and, for advisory roots, the judged
+ skills/.archive subtree."""
+ root_abs = os.path.join(home, root_rel.replace("/", os.sep))
+ if not _lexists(root_abs):
+ return
+ yield root_rel, root_abs
+ # Top-level entries include plain FILES (config.yaml, state.db): only a real
+ # directory can be descended, and a symlink must never be followed.
+ if _is_link(root_abs) or not os.path.isdir(root_abs):
+ return
+ stack = [root_abs]
+ while stack:
+ current = stack.pop()
+ try:
+ names = sorted(os.listdir(current))
+ except OSError as exc:
+ raise ScanError(f"unreadable under {home}: {exc}") from exc
+ for name in names:
+ abs_path = os.path.join(current, name)
+ rel = os.path.relpath(abs_path, home).replace(os.sep, "/")
+ if judged:
+ if _owns_plugins(rel, profiles=profiles):
+ continue
+ else:
+ # Advisory walk of skills/: skip .archive, which is judged.
+ if not _owns_plugins(rel, profiles=profiles) and _is_bundled_skill(rel, profiles=profiles):
+ pass
+ elif rel.split("/")[-1] == SKILL_ARCHIVE or "/" + SKILL_ARCHIVE + "/" in rel:
+ continue
+ if _is_link(abs_path):
+ yield rel, abs_path
+ continue
+ if os.path.isdir(abs_path):
+ yield rel, abs_path
+ stack.append(abs_path)
+ else:
+ yield rel, abs_path
+
+
+def snapshot_home(home: str, profiles_dir: str | None = None) -> dict:
+ home = os.path.abspath(home)
+ entries: dict[str, dict] = {}
+ advisory: dict[str, dict] = {}
+
+ targets: list[tuple[str, bool, bool]] = [] # (rel, profiles_style, judged)
+ for name in JUDGED_FILES:
+ targets.append((name, False, True))
+ for name in JUDGED_ROOTS:
+ targets.append((name, name.split("/")[0] == PROFILES_DIR, True))
+ for name in ADVISORY_ROOTS:
+ targets.append((name, False, False))
+
+ for rel_root, profiles, judged in targets:
+ sink = entries if judged else advisory
+ for rel, abs_path in _walk_root(home, rel_root, profiles=profiles, judged=judged):
+ sink[rel] = _entry_record(abs_path)
+
+ # Profiles may live somewhere else entirely (a test harness override).
+ if profiles_dir and os.path.abspath(profiles_dir) != os.path.join(home, PROFILES_DIR):
+ override_abs = os.path.abspath(profiles_dir)
+ if _lexists(override_abs):
+ entries["profiles"] = {"kind": "dir"}
+ for name in sorted(os.listdir(override_abs)):
+ abs_path = os.path.join(override_abs, name)
+ rel = f"{PROFILES_DIR}/{name}"
+ entries[rel] = _entry_record(abs_path)
+ if os.path.isdir(abs_path) and not _is_link(abs_path):
+ for sub_rel, sub_abs in _walk_root(
+ override_abs, name, profiles=True, judged=True):
+ if sub_rel == name:
+ continue
+ entries[f"{PROFILES_DIR}/{sub_rel}"] = _entry_record(sub_abs)
+
+ return {
+ "schema": SCHEMA_VERSION,
+ "home": home,
+ "entries": entries,
+ "advisory": advisory,
+ }
+
+
+def _diff(before: dict, after: dict) -> dict:
+ return {
+ "deleted": sorted(set(before) - set(after)),
+ "added": sorted(set(after) - set(before)),
+ "modified": {key: {"before": before[key], "after": after[key]}
+ for key in sorted(set(before) & set(after))
+ if before[key] != after[key]},
+ }
+
+
+def _modification_allowed(rel: str) -> bool:
+ """Entries whose *bytes* may legitimately change during an upgrade.
+
+ config.yaml is rewritten by config migration: additive, by design.
+ state.db is a live SQLite file — its size moves whenever rows are written,
+ so its real contract is the row-count check below, not byte equality.
+ """
+ name = rel.rsplit("/", 1)[-1]
+ return name in ("config.yaml", "state.db")
+
+
+def _rows_shrank(rel: str, before: dict, after: dict) -> bool:
+ if rel.rsplit("/", 1)[-1] != "state.db":
+ return False
+ old, new = before.get("rows"), after.get("rows")
+ if not isinstance(old, dict) or not isinstance(new, dict):
+ return False
+ return any(isinstance(old.get(k), int) and isinstance(new.get(k), int)
+ and new[k] < old[k] for k in old)
+
+
+def verify_home(home: str, snap: dict) -> dict:
+ home = os.path.abspath(home)
+ fresh = snapshot_home(home, snap.get("_profiles_dir"))
+ judged = _diff(snap["entries"], fresh["entries"])
+ advisory = _diff(snap.get("advisory", {}), fresh["advisory"])
+
+ failing_modified = {k: v for k, v in judged["modified"].items()
+ if not _modification_allowed(k)}
+ shrank = sorted(k for k, v in judged["modified"].items()
+ if _rows_shrank(k, v["before"], v["after"]))
+ tolerated_modified = sorted(set(judged["modified"]) - set(failing_modified))
+
+ return {
+ "schema": SCHEMA_VERSION,
+ "home": home,
+ "counts": {
+ "before": len(snap["entries"]),
+ "after": len(fresh["entries"]),
+ "deleted": len(judged["deleted"]),
+ "modified": len(failing_modified),
+ "added": len(judged["added"]),
+ "tolerated_modified": len(tolerated_modified),
+ "advisory_changed": len(advisory["deleted"]) + len(advisory["modified"])
+ + len(advisory["added"]),
+ },
+ "deleted": judged["deleted"],
+ "modified": failing_modified,
+ "added": judged["added"],
+ "tolerated_modified": tolerated_modified,
+ "rows_shrank": shrank,
+ "advisory": advisory,
+ "ok": not judged["deleted"] and not failing_modified and not shrank,
+ }
+
+
+def _render(report: dict) -> str:
+ lines = []
+ counts = report["counts"]
+ lines.append(
+ f"user state: {counts['before']} -> {counts['after']} entries "
+ f"({counts['deleted']} deleted, {counts['modified']} modified, "
+ f"{counts['added']} added, {counts['tolerated_modified']} tolerated, "
+ f"{counts['advisory_changed']} advisory)")
+ for label, key in (("DELETED", "deleted"), ("MODIFIED", "modified")):
+ for rel in report[key]:
+ lines.append(f" {label} {rel}")
+ for rel in report["rows_shrank"]:
+ lines.append(f" ROWS SHRANK {rel}")
+ for rel in report["tolerated_modified"]:
+ lines.append(f" tolerated (config rewrite) {rel}")
+ advisory = report["advisory"]
+ for label, key in (("advisory deleted", "deleted"), ("advisory modified", "modified")):
+ for rel in advisory[key]:
+ lines.append(f" {label} (skills sync) {rel}")
+ return "\n".join(lines)
+
+
+def main(argv: list[str] | None = None) -> int:
+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ sub = ap.add_subparsers(dest="mode", required=True)
+
+ p_snap = sub.add_parser("snapshot", help="record durable user state to JSON")
+ p_snap.add_argument("--home", required=True)
+ p_snap.add_argument("--out", required=True)
+ p_snap.add_argument("--profiles-dir",
+ help="override the profiles root (default <home>/profiles)")
+
+ p_ver = sub.add_parser("verify", help="compare current state to a snapshot")
+ p_ver.add_argument("--home", required=True)
+ p_ver.add_argument("--snapshot", required=True)
+ p_ver.add_argument("--report")
+ p_ver.add_argument("--profiles-dir")
+
+ args = ap.parse_args(argv)
+
+ if not os.path.isdir(os.path.abspath(args.home)):
+ print(f"error: --home is not a directory: {args.home}", file=sys.stderr)
+ return 2
+
+ if args.mode == "snapshot":
+ try:
+ snap = snapshot_home(args.home, args.profiles_dir)
+ except (OSError, ScanError) as exc:
+ print(f"snapshot failed: {exc}", file=sys.stderr)
+ return 2
+ if not snap["entries"]:
+ print("snapshot INCONCLUSIVE: zero judged entries — was this home "
+ "ever used? Refusing to record an empty contract.",
+ file=sys.stderr)
+ return 3
+ if args.profiles_dir:
+ snap["_profiles_dir"] = args.profiles_dir
+ with open(args.out, "w", encoding="utf-8") as handle:
+ json.dump(snap, handle, indent=2, sort_keys=True)
+ print(f"snapshot: {len(snap['entries'])} judged entries "
+ f"({len(snap['advisory'])} advisory) -> {args.out}")
+ return 0
+
+ with open(args.snapshot, "r", encoding="utf-8") as handle:
+ snap = json.load(handle)
+ if args.profiles_dir:
+ snap["_profiles_dir"] = args.profiles_dir
+ try:
+ report = verify_home(args.home, snap)
+ except (OSError, ScanError) as exc:
+ print(f"verify failed: {exc}", file=sys.stderr)
+ return 2
+
+ rendered = json.dumps(report, indent=2, sort_keys=True)
+ if args.report:
+ with open(args.report, "w", encoding="utf-8") as handle:
+ handle.write(rendered)
+
+ if not snap.get("entries"):
+ print("USER-STATE PRESERVATION INCONCLUSIVE: the snapshot is empty; "
+ "refusing to claim preservation over zero recorded entries.",
+ file=sys.stderr)
+ return 3
+
+ if report["ok"]:
+ print("user-state preservation OK: " + _render(report))
+ return 0
+ print(_render(report), file=sys.stderr)
+ counts = report["counts"]
+ print("USER-STATE PRESERVATION FAILED: "
+ f"{counts['deleted']} deleted, {counts['modified']} modified, "
+ f"{len(report['rows_shrank'])} with fewer rows", file=sys.stderr)
+ return 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/install/installer-script-e2e.sh b/tests/install/installer-script-e2e.sh
index 74c60e867b2..038cbccc956 100755
--- a/tests/install/installer-script-e2e.sh
+++ b/tests/install/installer-script-e2e.sh
@@ -102,6 +102,12 @@ fail() { printf 'E2E ASSERTION FAILED: %s\n' "$*" >&2; exit 1; }
source "$(dirname "$0")/e2e-assets/ts-prefix.sh" 2>/dev/null || ts_prefix() { cat; }
# shellcheck source=../e2e-assets/preserve-plugins.sh
source "$(dirname "$0")/e2e-assets/preserve-plugins.sh"
+# shellcheck source=../e2e-assets/preserve-user-state.sh
+source "$(dirname "$0")/e2e-assets/preserve-user-state.sh"
+# shellcheck source=../e2e-assets/user-state-actions.sh
+source "$(dirname "$0")/e2e-assets/user-state-actions.sh"
+# shellcheck source=../e2e-assets/mock-provider.sh
+source "$(dirname "$0")/e2e-assets/mock-provider.sh"
# shellcheck source=e2e-assets/source-driver.sh
source "$(dirname "$0")/e2e-assets/source-driver.sh"
# shellcheck source=e2e-assets/installer-common.sh
@@ -217,6 +223,43 @@ desktop_checkpoint() { # phase, expected commit, selected method
--desktop "$EXPECT_DESKTOP" --method "$3"
}
+# The redirect must stay at TRANSPORT level. `hermes update` resolves its
+# update channel from the release archive and validates the record against
+# `git config --get remote.origin.url`; if the configured URL ever looked like
+# the rehearsal source, channel resolution would fail outright and the leg
+# would be testing a fork install instead of the real user path.
+assert_redirect_is_transport_only() {
+ local official='https://github.com/NousResearch/hermes-agent.git'
+ local configured observed
+ configured="$(git -C "$INSTALL_DIR" config --get remote.origin.url)"
+ [ "$configured" = "$official" ] \
+ || fail "origin is configured as '$configured', not the official URL — the redirect is not transport-only"
+ observed="$(git -C "$INSTALL_DIR" remote get-url origin)"
+ case "$observed" in
+ file://*|*serve.git*) ;;
+ *) fail "origin transport '$observed' is not redirected to the staged repo" ;;
+ esac
+ ok "redirect is transport-only (configured: $configured, transport: $observed)"
+}
+
+# The user-visible launcher must survive the upgrade and still run. A launcher
+# left pointing at a vanished tree is exactly the "update lost something" shape
+# a checkout-hash assertion cannot see.
+assert_user_shims() {
+ local hermes user_shim
+ hermes="$(source_hermes "$INSTALL_DIR")" || fail "no usable launcher after the upgrade"
+ [ -x "$hermes" ] || fail "launcher is not executable: $hermes"
+ user_shim="$HOME/.local/bin/hermes"
+ if [ -e "$user_shim" ] || [ -L "$user_shim" ]; then
+ HERMES_DISABLE_LAZY_INSTALLS=1 PYTHONDONTWRITEBYTECODE=1 \
+ "$user_shim" --version > "$LOG_DIR/version-path-shim.log" 2>&1 \
+ || fail "the PATH shim stopped working after the upgrade: $user_shim"
+ ok "PATH shim still runs: $user_shim"
+ else
+ ok "no PATH shim at $user_shim (nothing to check there)"
+ fi
+}
+
# --- install OLD ---------------------------------------------------------------
step "installing OLD ($INSTALL_REF) via its own scripts/install.sh ($INSTALL_METHOD)"
@@ -231,6 +274,21 @@ else
assert_checkout "$OLD_SHA" OLD
fi
desktop_checkpoint old "$OLD_SHA" "$INSTALL_METHOD"
+
+# A real, chat-capable provider. An existing user HAS one configured, and the
+# durability check below needs a real turn — not a file we wrote ourselves.
+if [ -z "${HERMES_E2E_MOCK_URL:-}" ]; then
+ PATH="$(dirname "$HERMES_E2E_NODE"):$PATH" mock_start "$WORK_ROOT"
+ trap mock_stop EXIT
+fi
+
+# Produce the user's own state through the ordinary CLI, then snapshot what
+# must survive. Done as late as possible before the update so the window
+# verify() covers contains only the upgrade.
+HERMES="$(source_hermes "$INSTALL_DIR")" || fail "no installed command to drive"
+source_build_env user_state_produce "$HERMES"
+user_state_before_upgrade
+assert_redirect_is_transport_only
preserve_before_upgrade
# --- update OLD -> HEAD ----------------------------------------------------------
@@ -334,6 +392,8 @@ ls -la "$INSTALL_DIR/venv/bin" > "$ildest/venv-bin-ls.txt" 2>/dev/null || true
ok "collected install-side logs to $ildest"
assert_checkout "$TARGET_SHA" "$TARGET_LABEL"
+assert_user_shims
+user_state_after_upgrade
preserve_after_upgrade
desktop_checkpoint new "$TARGET_SHA" "$UPDATE_METHOD"
diff --git a/tests/install/windows-e2e.ps1 b/tests/install/windows-e2e.ps1
index b745fa89e38..a978a6f7f5e 100644
--- a/tests/install/windows-e2e.ps1
+++ b/tests/install/windows-e2e.ps1
@@ -922,6 +922,155 @@ function Invoke-PreserveVerify {
Write-Host " plugins/** and profile plugin trees survived the upgrade intact"
}
+# ----------------------------------------------------------------------------
+# User-state preservation: the user's OWN durable state, produced through the
+# ordinary CLI (never seeded by us), snapshotted before the upgrade and
+# verified after it. Complements the plugin-tree contract above, which owns
+# plugins/** only.
+# ----------------------------------------------------------------------------
+
+function Get-UserStateSessionCount {
+ # A real chat turn must actually create a session; if it silently does not,
+ # the preservation check below would be testing nothing.
+ $probe = Join-Path $WorkRoot 'user-state-session-count.py'
+ if (-not (Test-Path -LiteralPath $probe)) {
+ @'
+import sqlite3, sys
+try:
+ con = sqlite3.connect("file:" + sys.argv[1].replace("\\", "/") + "?mode=ro", uri=True)
+ print(con.execute("SELECT COUNT(*) FROM sessions").fetchone()[0])
+except Exception:
+ print(-1)
+'@ | Set-Content -LiteralPath $probe -Encoding ASCII
+ }
+ $prevEap = $ErrorActionPreference; $ErrorActionPreference = 'Continue'
+ try { $value = (& python $probe (Join-Path $HermesHome 'state.db') 2>$null | Out-String).Trim() }
+ finally { $ErrorActionPreference = $prevEap }
+ if ($value -match '^-?\d+$') { return [int]$value }
+ return -1
+}
+
+function Invoke-UserStateActions {
+ # Everything here is a command a user would run against the real installed
+ # CLI with a real (mocked-inference) provider configured.
+ $hermes = Get-SourceHermes $InstallDir
+ if (-not $script:ChatMock) {
+ # Same mock + config writer the desktop chat checkpoints use, so the
+ # leg has a genuinely configured provider rather than a dummy key.
+ $script:ChatMock = Start-DesktopJourneyMock $DriverNode $AssetsDir $WorkRoot $HermesHome $ProofRoot
+ }
+ $prevLazy = $env:HERMES_DISABLE_LAZY_INSTALLS
+ $prevEap = $ErrorActionPreference
+ try {
+ $env:HERMES_DISABLE_LAZY_INSTALLS = '1'
+ $ErrorActionPreference = 'Continue'
+
+ # Probe, do not assume (the harness rule for old refs).
+ $chatHelp = (& $hermes chat --help 2>&1 | Out-String)
+ if (-not ($chatHelp -match '(^|\s)-q(\s|,|$)' -or $chatHelp -match '--quiet')) {
+ throw 'the installed CLI has no one-shot chat flag; this leg cannot produce a session through the user path'
+ }
+ $before = Get-UserStateSessionCount
+ $log = Join-Path $WorkRoot 'logs\user-state-chat.log'
+ & $hermes chat -q "Reply with the single word: ok" 2>&1 | Add-TsPrefix | Out-File -Encoding UTF8 $log
+ $chatExit = $LASTEXITCODE
+ Write-LogGroup 'first real chat turn' $log
+ if ($chatExit -ne 0) { throw "the first chat turn failed (exit $chatExit); see $log" }
+ $after = Get-UserStateSessionCount
+ if (-not ($before -ge 0 -and $after -gt $before)) {
+ throw "the chat turn produced no session row (state.db sessions $before -> $after)"
+ }
+ Write-Host " a real turn created a session (state.db sessions $before -> $after)"
+
+ if (-not (Test-Path -LiteralPath (Join-Path $HermesHome 'auth.json'))) {
+ & $hermes auth add mock --type api-key --api-key 'e2e-preservation-not-a-real-key' 2>&1 |
+ Out-File -Encoding UTF8 (Join-Path $WorkRoot 'logs\user-state-auth.log')
+ if ($LASTEXITCODE -ne 0) { throw 'hermes auth add failed' }
+ if (-not (Test-Path -LiteralPath (Join-Path $HermesHome 'auth.json'))) {
+ throw 'hermes auth add produced no auth.json'
+ }
+ Write-Host ' a pooled credential exists (auth.json)'
+ }
+
+ if (-not (Test-Path -LiteralPath (Join-Path $HermesHome 'profiles\e2e-second'))) {
+ & $hermes profile create e2e-second 2>&1 |
+ Out-File -Encoding UTF8 (Join-Path $WorkRoot 'logs\user-state-profile.log')
+ if ($LASTEXITCODE -ne 0) { throw 'hermes profile create failed' }
+ if (-not (Test-Path -LiteralPath (Join-Path $HermesHome 'profiles\e2e-second'))) {
+ throw 'hermes profile create produced no profile dir'
+ }
+ Write-Host ' a second profile exists (profiles/e2e-second)'
+ }
+ }
+ finally {
+ $env:HERMES_DISABLE_LAZY_INSTALLS = $prevLazy
+ $ErrorActionPreference = $prevEap
+ }
+}
+
+function Invoke-UserStateSnapshot {
+ $snap = Join-Path $WorkRoot 'user-state-snapshot.json'
+ if (Test-Path -LiteralPath $snap) { throw 'refusing to overwrite an existing user-state snapshot' }
+ & python (Join-Path $AssetsDir 'verify-user-state.py') snapshot --home $HermesHome --out $snap
+ if ($LASTEXITCODE -ne 0) { throw "user-state snapshot failed (exit $LASTEXITCODE)" }
+ Write-Host " pre-upgrade user-state snapshot: $snap"
+}
+
+function Invoke-UserStateVerify {
+ $snap = Join-Path $WorkRoot 'user-state-snapshot.json'
+ if (-not (Test-Path -LiteralPath $snap)) {
+ throw 'no pre-upgrade user-state snapshot; cannot claim preservation'
+ }
+ $report = Join-Path $WorkRoot 'logs\user-state-report.json'
+ $prevEap = $ErrorActionPreference; $ErrorActionPreference = 'Continue'
+ try {
+ & python (Join-Path $AssetsDir 'verify-user-state.py') verify --home $HermesHome `
+ --snapshot $snap --report $report
+ $code = $LASTEXITCODE
+ }
+ finally { $ErrorActionPreference = $prevEap }
+ if ($code -ne 0) {
+ throw "the upgrade changed the user's own state (exit $code); report at $report"
+ }
+ Write-Host " the user's own durable state survived the upgrade"
+}
+
+function Assert-RedirectIsTransportOnly {
+ # The redirect must stay at TRANSPORT level: `hermes update` resolves its
+ # channel from the release archive and validates the record against
+ # `git config --get remote.origin.url`. If the configured URL ever looked
+ # like the rehearsal source, channel resolution would fail and this leg
+ # would be testing a fork install rather than the real user path.
+ $official = 'https://github.com/NousResearch/hermes-agent.git'
+ $configured = (Invoke-Git @('-C', $InstallDir, 'config', '--get', 'remote.origin.url') | Out-String).Trim()
+ Assert-True ($configured -eq $official) "origin stays configured as the official URL (got '$configured')"
+ $observed = (Invoke-Git @('-C', $InstallDir, 'remote', 'get-url', 'origin') | Out-String).Trim()
+ Assert-True ($observed -match 'serve\.git|^file://') "origin transport is redirected to the staged repo (got '$observed')"
+}
+
+function Assert-UserShims {
+ # A launcher left pointing at a vanished tree is the "update lost
+ # something" shape a checkout-hash assertion cannot see.
+ $hermes = Get-SourceHermes $InstallDir
+ Assert-True (Test-Path -LiteralPath $hermes) "a usable launcher still exists after the upgrade ($hermes)"
+ $userShim = Join-Path $HermesHome 'bin\hermes.exe'
+ if (-not (Test-Path -LiteralPath $userShim)) { $userShim = Join-Path $HermesHome 'bin\hermes.cmd' }
+ if (Test-Path -LiteralPath $userShim) {
+ $prevEap = $ErrorActionPreference; $ErrorActionPreference = 'Continue'
+ try {
+ & $userShim --version 2>&1 | Out-Null
+ $shimExit = $LASTEXITCODE
+ }
+ finally { $ErrorActionPreference = $prevEap }
+ Assert-True ($shimExit -eq 0) "the $HermesHome\bin launcher still runs after the upgrade"
+ }
+ $userPath = [Environment]::GetEnvironmentVariable('Path', 'User')
+ if ($userPath) {
+ Assert-True ($userPath -like "*$(Join-Path $HermesHome 'bin')*") `
+ "the USER PATH still exposes $(Join-Path $HermesHome 'bin')"
+ }
+}
+
function Invoke-PhaseInstall {
# Dispatch on the install axis. Each arm ends with the same contract:
# checkout at OLD, hermes runs, and state carries how OLD landed so any
@@ -955,6 +1104,8 @@ function Invoke-PhaseInstall {
if ($InstallMethod -ne 'desktop-installer@latest') {
Invoke-DesktopCheckpoint 'old' $state.old $InstallMethod
}
+ Assert-RedirectIsTransportOnly
+ Invoke-UserStateActions
}
function Invoke-PhaseUpdate {
@@ -973,6 +1124,9 @@ function Invoke-PhaseUpdate {
# helper used to own this step.
# Snapshot every plugin tree BEFORE the upgrade moves anything.
Invoke-PreserveSnapshot
+ # ... and the user's own durable state, produced by the install phase
+ # through the ordinary CLI.
+ Invoke-UserStateSnapshot
Invoke-Git @("-C", $ServeRepo, "update-ref", "refs/heads/main", $state.current) | Out-Null
Write-Host " serve.git main advanced to $($state.current)"
@@ -1019,7 +1173,9 @@ function Invoke-PhaseUpdate {
Assert-True ((Get-InstalledHead) -eq $state.current) "checkout landed on HEAD"
Test-HermesRuns "post-update"
+ Assert-UserShims
Invoke-PreserveVerify
+ Invoke-UserStateVerify
if ($Route -notin @('open-app-update', 'desktop-installer@latest')) {
Invoke-DesktopCheckpoint 'new' $state.current $Route
}
diff --git a/tests/scripts/test_verify_user_state.py b/tests/scripts/test_verify_user_state.py
new file mode 100644
index 00000000000..95bc3de97f1
--- /dev/null
+++ b/tests/scripts/test_verify_user_state.py
@@ -0,0 +1,244 @@
+"""Unit tests for the user-state upgrade-preservation verifier.
+
+tests/install/e2e-assets/verify-user-state.py is the standalone hook the
+install/update E2E drivers call around a real upgrade. These tests exercise it
+against a real temp HERMES_HOME (real files, real sqlite databases) — no
+source-reading, no filesystem mocks.
+
+The contract under test: an upgrade may ADD state and may rewrite config.yaml
+(config migration) and the bundled skills tree (skills sync), but it may not
+delete or modify the user's own durable state, and it may not shrink state.db.
+plugins/** is deliberately not owned here — verify-plugin-preservation.py owns
+it — so this tool must not fail on it.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+import os
+import sqlite3
+import subprocess
+import sys
+
+import pytest
+
+_HERE = os.path.dirname(os.path.abspath(__file__))
+VERIFIER = os.path.join(_HERE, "..", "install", "e2e-assets", "verify-user-state.py")
+
+_spec = importlib.util.spec_from_file_location("verify_user_state", VERIFIER)
+vus = importlib.util.module_from_spec(_spec)
+_spec.loader.exec_module(vus)
+
+
+def _make_db(path, sessions=2, messages=3):
+ con = sqlite3.connect(str(path))
+ con.execute("CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY)")
+ con.execute("CREATE TABLE IF NOT EXISTS messages (id TEXT)")
+ con.executemany("INSERT OR REPLACE INTO sessions VALUES (?)",
+ [(f"s{i}",) for i in range(sessions)])
+ con.executemany("INSERT INTO messages VALUES (?)",
+ [(f"m{i}",) for i in range(messages)])
+ con.commit()
+ con.close()
+
+
+def _home(tmp_path):
+ home = tmp_path / "home"
+ for rel in ("memories", "cron", "sessions", "skills/foo", "skills/.archive/mine",
+ "plugins/demo", "photon/sidecar", "profiles/work"):
+ (home / rel).mkdir(parents=True, exist_ok=True)
+ (home / "config.yaml").write_text("timezone: utc\n", encoding="utf-8")
+ (home / ".env").write_text("NOUS_API_KEY=xxx\n", encoding="utf-8")
+ (home / "auth.json").write_text('{"tokens":{}}\n', encoding="utf-8")
+ (home / "memories" / "note.md").write_text("remember\n", encoding="utf-8")
+ (home / "cron" / "jobs.json").write_text('{"jobs":[]}\n', encoding="utf-8")
+ (home / "sessions" / "2026.jsonl").write_text('{"t":1}\n', encoding="utf-8")
+ (home / "skills" / "foo" / "SKILL.md").write_text("bundled\n", encoding="utf-8")
+ (home / "skills" / ".archive" / "mine" / "SKILL.md").write_text("mine\n", encoding="utf-8")
+ (home / "plugins" / "demo" / "plugin.yaml").write_text("name: demo\n", encoding="utf-8")
+ (home / "photon" / "sidecar" / "package-lock.json").write_text("{}\n", encoding="utf-8")
+ (home / "profiles" / "work" / "config.yaml").write_text("x: 1\n", encoding="utf-8")
+ _make_db(home / "state.db")
+ return home
+
+
+def _snapshot(home):
+ return vus.snapshot_home(str(home))
+
+
+def _verify(home, snap):
+ return vus.verify_home(str(home), snap)
+
+
+# --- shape ------------------------------------------------------------------
+
+def test_snapshot_records_rows_not_bytes_for_state_db(tmp_path):
+ home = _home(tmp_path)
+ snap = _snapshot(home)
+ record = snap["entries"]["state.db"]
+ assert record["kind"] == "file"
+ assert record["rows"] == {"sessions": 2, "messages": 3}
+ assert "sha256" not in record, "a live db must be judged by rows, not bytes"
+
+
+def test_snapshot_is_read_only(tmp_path):
+ home = _home(tmp_path)
+ before = sorted(os.path.relpath(os.path.join(dp, n), home)
+ for dp, _, ns in os.walk(home) for n in ns)
+ snap = _snapshot(home)
+ after = sorted(os.path.relpath(os.path.join(dp, n), home)
+ for dp, _, ns in os.walk(home) for n in ns)
+ assert before == after
+ assert snap["entries"], "a used home must produce judged entries"
+
+
+def test_plugins_and_bundled_skills_are_not_judged(tmp_path):
+ home = _home(tmp_path)
+ snap = _snapshot(home)
+ assert not [k for k in snap["entries"] if k.startswith("plugins/")], \
+ "plugins/** is owned by verify-plugin-preservation.py"
+ assert "skills/foo/SKILL.md" in snap["advisory"]
+ assert "skills/foo/SKILL.md" not in snap["entries"]
+ assert "skills/.archive/mine/SKILL.md" in snap["entries"], \
+ "the curator's archive holds USER skills and is judged"
+
+
+# --- the contract -----------------------------------------------------------
+
+def test_verify_passes_when_nothing_changed(tmp_path):
+ home = _home(tmp_path)
+ report = _verify(home, _snapshot(home))
+ assert report["ok"] is True
+ assert report["deleted"] == [] and report["modified"] == {}
+
+
+def test_tolerates_added_files(tmp_path):
+ home = _home(tmp_path)
+ snap = _snapshot(home)
+ (home / "memories" / "another.md").write_text("new\n", encoding="utf-8")
+ report = _verify(home, snap)
+ assert report["ok"] is True, "an upgrade may add files"
+ assert "memories/another.md" in report["added"]
+
+
+def test_fails_when_a_user_file_is_deleted(tmp_path):
+ home = _home(tmp_path)
+ snap = _snapshot(home)
+ (home / "memories" / "note.md").unlink()
+ report = _verify(home, snap)
+ assert report["ok"] is False
+ assert "memories/note.md" in report["deleted"]
+
+
+def test_fails_when_env_is_modified(tmp_path):
+ home = _home(tmp_path)
+ snap = _snapshot(home)
+ (home / ".env").write_text("CLOBBERED=1\n", encoding="utf-8")
+ report = _verify(home, snap)
+ assert report["ok"] is False
+ assert ".env" in report["modified"]
+
+
+def test_tolerates_config_yaml_rewrite(tmp_path):
+ home = _home(tmp_path)
+ snap = _snapshot(home)
+ (home / "config.yaml").write_text("timezone: utc\nnew_key: 1\n", encoding="utf-8")
+ (home / "profiles" / "work" / "config.yaml").write_text("x: 1\ny: 2\n", encoding="utf-8")
+ report = _verify(home, snap)
+ assert report["ok"] is True, "config migration rewrites config.yaml additively"
+ assert sorted(report["tolerated_modified"]) == sorted(
+ ["config.yaml", "profiles/work/config.yaml"])
+
+
+def test_fails_when_state_db_loses_rows(tmp_path):
+ home = _home(tmp_path)
+ snap = _snapshot(home)
+ con = sqlite3.connect(str(home / "state.db"))
+ con.execute("DELETE FROM sessions WHERE id='s1'")
+ con.commit()
+ con.close()
+ report = _verify(home, snap)
+ assert report["ok"] is False
+ assert report["rows_shrank"] == ["state.db"]
+
+
+def test_tolerates_state_db_growth(tmp_path):
+ home = _home(tmp_path)
+ snap = _snapshot(home)
+ con = sqlite3.connect(str(home / "state.db"))
+ con.execute("INSERT INTO sessions VALUES ('s9')")
+ con.commit()
+ con.close()
+ report = _verify(home, snap)
+ assert report["ok"] is True, "a later turn adds rows; that is not loss"
+
+
+def test_bundled_skill_resync_is_advisory_only(tmp_path):
+ home = _home(tmp_path)
+ snap = _snapshot(home)
+ # A release adds a bundled skill and updates an existing one.
+ (home / "skills" / "bar").mkdir()
+ (home / "skills" / "bar" / "SKILL.md").write_text("new bundled\n", encoding="utf-8")
+ (home / "skills" / "foo" / "SKILL.md").write_text("updated bundled\n", encoding="utf-8")
+ report = _verify(home, snap)
+ assert report["ok"] is True, "skills sync rewrites the bundled tree by design"
+ assert "skills/foo/SKILL.md" in report["advisory"]["modified"]
+
+
+def test_fails_when_archived_user_skill_is_lost(tmp_path):
+ home = _home(tmp_path)
+ snap = _snapshot(home)
+ (home / "skills" / ".archive" / "mine" / "SKILL.md").unlink()
+ report = _verify(home, snap)
+ assert report["ok"] is False
+ assert "skills/.archive/mine/SKILL.md" in report["deleted"]
+
+
+def test_fails_when_a_profile_directory_disappears(tmp_path):
+ home = _home(tmp_path)
+ snap = _snapshot(home)
+ (home / "profiles" / "work" / "config.yaml").unlink()
+ report = _verify(home, snap)
+ assert report["ok"] is False
+ assert "profiles/work/config.yaml" in report["deleted"]
+
+
+# --- CLI contract -----------------------------------------------------------
+
+def _run(args):
+ return subprocess.run([sys.executable, VERIFIER, *args],
+ capture_output=True, text=True)
+
+
+def test_cli_snapshot_then_verify_round_trip(tmp_path):
+ home = _home(tmp_path)
+ snap = tmp_path / "snap.json"
+ report = tmp_path / "report.json"
+ first = _run(["snapshot", "--home", str(home), "--out", str(snap)])
+ assert first.returncode == 0, first.stderr
+ assert snap.exists()
+ ok = _run(["verify", "--home", str(home), "--snapshot", str(snap),
+ "--report", str(report)])
+ assert ok.returncode == 0, ok.stderr
+ assert json.loads(report.read_text(encoding="utf-8"))["ok"] is True
+
+ (home / "memories" / "note.md").unlink()
+ bad = _run(["verify", "--home", str(home), "--snapshot", str(snap)])
+ assert bad.returncode == 1
+ assert "USER-STATE PRESERVATION FAILED" in bad.stderr
+
+
+def test_cli_refuses_an_empty_snapshot_as_inconclusive(tmp_path):
+ empty = tmp_path / "empty"
+ empty.mkdir()
+ snap = tmp_path / "snap.json"
+ result = _run(["snapshot", "--home", str(empty), "--out", str(snap)])
+ assert result.returncode == 3
+ assert "INCONCLUSIVE" in result.stderr
+
+
+def test_cli_rejects_a_missing_home(tmp_path):
+ result = _run(["snapshot", "--home", str(tmp_path / "nope"),
+ "--out", str(tmp_path / "s.json")])
+ assert result.returncode == 2