The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge remote-tracking branch 'origin/main' into ethie/pm-clean
ethernet8eb20a50ae41
diff --cc hermes_cli/backup.pyindex 38cf0edc260,51406332486..0808f9ff2b6--- a/hermes_cli/backup.py+++ b/hermes_cli/backup.py@@@ -11,7 -11,8 +11,8 @@@ import tempfilimport threadingimport timeimport zipfile+ import zlib-from contextlib import closing, contextmanager, suppress+from contextlib import contextmanager, suppressfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Tuple@@@ -623,320 -774,241 +635,217 @@@ def _run_backup_locked(args, hermes_roo# --- Import ----def _validate_backup_zip(zf: zipfile.ZipFile) -> tuple[bool, str]:- """Check that a zip looks like a Hermes backup."""- names = zf.namelist()- if not names:- return False, "zip archive is empty"- # Telltale files a hermes home has — at the root or one level deep (zipped directory).- if not any(Path(n).name in {"config.yaml", ".env", "state.db"} for n in names):- return False, "zip does not appear to be a Hermes backup (no config.yaml, .env, or state databases found)"- return True, ""--+ def _find_corrupt_members(zf: zipfile.ZipFile, members: List[str]) -> List[str]:+ """Return ``"<member>: <error>"`` for every member whose data does not decompress or+ fails its CRC, streaming each one in 1 MiB chunks so a multi-GB ``state.db`` is never+ held in memory.- # --- Quick state snapshots (used by /snapshot slash command and hermes backup --quick) ----- # Critical state files (relative to HERMES_HOME) for quick snapshots; everything else is- # regeneratable or managed separately (skills, repo, sessions/). Entries may be files OR- # directories (recursive); missing entries are skipped. Pairing data lives in platform JSON blobs- # outside state.db, so it is listed explicitly — ``hermes update`` snapshots this set (#15733).- _QUICK_STATE_FILES = (- "state.db", "config.yaml", ".env", "auth.json", "cron/jobs.json", "cron/executions.db",- "gateway_state.json", "channel_directory.json", "channel_aliases.json", "processes.json",- "gateway/discord_message_recovery.db", # Discord reconnect replay ledger- # Per-profile user stores, destroyed if the update flow replaces the file and the post-update- # schema-init re-creates an empty one (#52889). Skipped when outside HERMES_HOME.- "projects.db", # per-profile project store- "response_store.db", # gateway conversation history / tool payloads- "memory_store.db", # holographic memory facts/entities- "verification_evidence.db", # agent verification audit trail- "kanban.db", # default board (back-compat <root>/kanban.db)- "kanban/boards", # non-default boards (workspaces/ + attachments/ skipped as regenerable)- # Pairing stores (generic + per-platform JSONs outside state.db)- "pairing", # legacy location (gateway/pairing.py)- "platforms/pairing", # new location (gateway/pairing.py)- "feishu_comment_pairing.json", # Feishu comment subscription pairings- )-- _QUICK_DEFAULT_KEEP = 20--- def _quick_snapshot_root(hermes_home: Optional[Path] = None) -> Path:- home = hermes_home or get_hermes_home()- return home / _QUICK_SNAPSHOTS_DIR--- def _newest_first(root: Path, keep_entry) -> List[Path]:- """Entries of *root* passing ``keep_entry``, newest (by name) first; ``[]`` if *root* is missing."""- if not root.exists():- return []- return sorted(filter(keep_entry, root.iterdir()), key=lambda p: p.name, reverse=True)--- # Kept in sync with ``_QUICK_STATE_FILES`` and ``cron/jobs.py``'s ``JOBS_FILE``.- _CRON_JOBS_REL = "cron/jobs.json"--- # Config paths the update flow must never change (#64160): model routing and the MoA section are- # consumed machine-wide, so an update/repair cycle that rewrites them silently redirects paid- # inference. Dotted paths into raw config.yaml; a single-element tuple protects a whole section.- _PROTECTED_CONFIG_PATHS: Tuple[Tuple[str, ...], ...] = (- ("model", "provider"), ("model", "default"), ("model", "base_url"), ("model", "api_key"),- ("moa",))--- def _prune_oldest(newest_first: List[Path], keep: int, remove, what: str) -> int:- """``remove(path)`` every entry past the first *keep*; return how many succeeded."""- deleted = 0- for p in newest_first[keep:]:- try:- remove(p)- deleted += 1- except OSError as exc:- logger.warning("Failed to prune %s %s: %s", what, p.name, exc)- return deleted--- # --- Shared full-zip backup helper ------ # --- Pre-update / pre-migration auto-backups ----- _PRE_UPDATE_BACKUPS_DIR = "backups"- _PRE_UPDATE_PREFIX = "pre-update-"- _PRE_UPDATE_DEFAULT_KEEP = 5- _PRE_MIGRATION_PREFIX = "pre-migration-"- _PRE_MIGRATION_DEFAULT_KEEP = 5--- def _prune_prefixed_zips(backup_dir: Path, prefix: str, keep: int, what: str) -> int:- """Remove oldest ``<prefix>*.zip`` in *backup_dir* beyond *keep*; return count deleted.-- Only prefix-matched files are touched, so hand-made zips or other backup kinds survive.+ ``is_zipfile()``/``namelist()`` only read the central directory, so an archive with a+ rotten member passes them and the damage surfaces as ``zlib.error``/``BadZipFile`` in+ the middle of the restore, after earlier members already replaced the user's files+ (#121258). Not ``zf.testzip()``: it lets ``zlib.error`` escape and names at most the+ first bad member."""- backups = _newest_first(backup_dir, lambda p: p.is_file() and p.name.startswith(prefix)- and p.suffix.lower() == ".zip")- return _prune_oldest(backups, keep, Path.unlink, what)--- def _create_prefixed_full_backup(- hermes_home: Optional[Path], prefix: str, keep: int, what: str, prune_what: str) -> Optional[Path]:- """Write ``<HERMES_HOME>/backups/<prefix><timestamp>.zip`` and prune older same-prefix zips.- Returns the path, or ``None`` if nothing to back up or the write failed. Never raises."""- hermes_root = hermes_home or get_default_hermes_root()- if not hermes_root.is_dir():- return None- backup_dir = hermes_root / _PRE_UPDATE_BACKUPS_DIR- try:- backup_dir.mkdir(parents=True, exist_ok=True)- except OSError as exc:- logger.warning("Could not create %s backup dir %s: %s", what, backup_dir, exc)- return None- out_path = backup_dir / f"{prefix}{datetime.now().strftime('%Y-%m-%d-%H%M%S')}.zip"- if _write_full_zip_backup(out_path, hermes_root) is None:- return None- _prune_prefixed_zips(backup_dir, prefix, keep, prune_what)- return out_path--- def create_pre_update_backup(- hermes_home: Optional[Path] = None, keep: int = _PRE_UPDATE_DEFAULT_KEEP) -> Optional[Path]:- """Full zip backup to ``backups/pre-update-<timestamp>.zip``, auto-pruned; ``None`` if nothing- was found or the backup failed. Never raises — ``hermes update`` continues anyway."""- return _create_prefixed_full_backup(hermes_home, _PRE_UPDATE_PREFIX, max(keep, 1), "pre-update", "backup")--- def create_pre_migration_backup(- hermes_home: Optional[Path] = None, keep: int = _PRE_MIGRATION_DEFAULT_KEEP) -> Optional[Path]:- """Full zip backup to ``backups/pre-migration-<timestamp>.zip`` before ``hermes claw migrate``- (same dir as update backups so listings/``hermes import`` find it); ``None`` if nothing was- found or the write failed. Never raises."""- return _create_prefixed_full_backup(- hermes_home, _PRE_MIGRATION_PREFIX, max(keep, 0), "pre-migration", "pre-migration backup")--- # ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----- # Names external plugins imported from this module before the Sep 2026 decomposition.- # Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).- # The whole block is removed by reverting the commit that added it.-- def copy_db_and_verify(src: Path, dst: Path) -> bool:- """Like :func:`_safe_copy_db` but verifies the destination after copy.-- Returns True only when the copy succeeded AND the destination is valid- SQLite (header + integrity check). Verification honours the default- size ceiling — a multi-GB destination gets the header + schema probe- rather than a full ``PRAGMA integrity_check`` that would page through- the whole file.- """- if not _safe_copy_db(src, dst):- return False- integrity = verify_sqlite_integrity(dst, run_pragma=True)- if not integrity.get("valid"):+ bad: list[str] = []+ for member in members:try:- dst.unlink(missing_ok=True)- except OSError:- pass- logger.warning("Backup of %s failed integrity verification: %s", src, integrity.get("message"))- return False- return True+ with zf.open(member) as src:+ while src.read(1 << 20): # CRC is checked when the stream hits EOF+ pass+ except (OSError, *_ZIP_MEMBER_READ_ERRORS) as exc:+ bad.append(f"{member}: {exc}")+ return bad+++ def _import_skipped(rel: str) -> bool:+ """True for a HERMES_HOME-relative member the import deliberately does not restore: runtime- state (``_IMPORT_SKIP_NAMES``), an archived SQLite WAL/SHM/journal -- a ``.db`` member is- page-restored into the live file, and a sidecar from a different database image installed- beside it would replay a foreign WAL on next open (current backups never ship these, older or- hand-built archives might)."""- return Path(rel).name in _IMPORT_SKIP_NAMES or rel.endswith(_SQLITE_SIDECAR_SUFFIXES)++ state (``_IMPORT_SKIP_NAMES``), PM-local interpreter/dependency roots, or an archived SQLite++ WAL/SHM/journal. A ``.db`` member is page-restored into the live file, and a sidecar from a++ different image would replay a foreign WAL on next open (older archives may ship these)."""++ try:++ parts = tuple(normalize_archive_parts(rel))++ except ValueError:++ return False # A rejected traversal is still reported by the import itself.++ return (parts[-1] in _IMPORT_SKIP_NAMES or++ profile_root_entry(parts) in PM_RUNTIME_ROOT_DIRS or++ rel.endswith(_SQLITE_SIDECAR_SUFFIXES))- # ---- END PLUGIN-COMPAT ----+ def _import_member_rel(member: str, prefix: str) -> tuple[str, bool]:+ """Classify an archive member exactly as the restore does: return ``(rel, skipped)``.+ ``_external/`` members are home-relative and never skipped; every other member is+ HERMES_HOME-relative after stripping the archive ``prefix``. Shared by the integrity+ pre-flight and ``_import_members`` so the two cannot disagree on what gets restored."""+ if member.startswith(_EXTERNAL_PREFIX):+ return member[len(_EXTERNAL_PREFIX):], False+ rel = member[len(prefix):] if prefix and member.startswith(prefix) else member+ return rel, _import_skipped(rel)- # ---------------------------------------------------------------------------- # Backup- # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- # Import- # ----------------------------------------------------------------------------- def run_import(args) -> None:- """Restore a Hermes backup from a zip file."""-def _detect_prefix(zf: zipfile.ZipFile) -> str:- """Detect if the zip has a common directory prefix wrapping all entries."""- names = [n for n in zf.namelist() if not n.endswith("/")]- first_parts = {Path(n).parts[0] for n in names if len(Path(n).parts) > 1}- if len(first_parts) == 1 and first_parts <= {".hermes", "hermes"}:- return first_parts.pop() + "/"- return ""++def run_import(args) -> Optional[int]:++ """Restore a Hermes backup; return 1 on damaged archives or incomplete restores."""+ zip_path = Path(args.zipfile).expanduser().resolve()+ if not zip_path.is_file():+ print(f"Error: File not found: {zip_path}")+ sys.exit(1)-def _extract_member_atomically(- zf: zipfile.ZipFile, member: str, target: Path, new_file_mode: Optional[int] = None) -> None:- """Restore one zip member onto *target* with no truncation window.+ if not zipfile.is_zipfile(zip_path):+ print(f"Error: Not a valid zip file: {zip_path}")+ sys.exit(1)- ``open(target, "wb")`` would truncate the user's file before any replacement bytes exist.- ``atomic_replace`` (not bare ``os.replace``) resolves a symlinked target first, so a- dotfiles-linked ``config.yaml`` keeps the link (#16743), and falls back to copy/fsync/unlink- on ``EXDEV``/``EBUSY`` for cross-device and bind-mount installs.- """- # Mode is None when the target does not exist: the umask-derived create-mode applies.- mode = _preserve_file_mode(target)- owner = _preserve_file_owner(target)- if mode is None:- mode = new_file_mode- else:- # Deliberately NOT a faithful copy: setuid/setgid are dropped. The bytes come from the- # archive, so carrying elevated bits would hand the zip's author the identity an existing- # setuid file runs as — and ``_external/`` publishes members anywhere under ``$HOME``.- mode &= ~(stat.S_ISUID | stat.S_ISGID)- # Truncate the stem: mkstemp adds ~16 chars and a member near NAME_MAX would otherwise fail.- fd, tmp_name = tempfile.mkstemp(dir=str(target.parent), prefix=f".{target.name[:80]}.", suffix=".partial")- try:- with os.fdopen(fd, "wb") as dst:- if mode is not None:- # Apply the mode BEFORE the replace so the target never transits through mkstemp's- # 0600 and the EXDEV/EBUSY ``copystat`` fallback copies the intended bits.- if hasattr(os, "fchmod"): # Unix-only; Windows takes the path-based chmod- os.fchmod(dst.fileno(), mode)- else:- os.chmod(tmp_name, mode)- # Stream: a multi-gigabyte state.db member must not be held in memory in one piece.- with zf.open(member) as src:- shutil.copyfileobj(src, dst)- dst.flush()- os.fsync(dst.fileno())- real_path = Path(atomic_replace(tmp_name, target))- # Owner first, mode second (as ``atomic_yaml_write``): chown drops setuid/setgid and- # ``mode`` no longer carries them, so neither step can re-elevate the restored file.- _restore_file_owner(real_path, owner)- _restore_file_mode(real_path, mode)- except BaseException:- with suppress(OSError):- os.unlink(tmp_name)- raise+ # The restore target must be the home the command operates under — the+ # same path printed as "Target:" via display_hermes_home(). Resolving+ # through get_default_hermes_root() instead maps a profile home+ # (<root>/profiles/<name>) back to <root>, silently retargeting the+ # restore at the live root while the profile directory stays empty.+ hermes_root = get_hermes_home()+ with zipfile.ZipFile(zip_path, "r") as zf:+ # Validate+ ok, reason = _validate_backup_zip(zf)+ if not ok:+ print(f"Error: {reason}")+ sys.exit(1)-def _count_session_rows(path: Path) -> Optional[Tuple[int, int]]:- """``(sessions, messages)`` in session database *path*; read-only, best effort.+ prefix = _detect_prefix(zf)+ members = [n for n in zf.namelist() if not n.endswith("/")]+ file_count = len(members)- ``None`` means "unknown" (missing, not a Hermes session store, unreadable) — never "zero":- acting on an unreadable database would mask the very loss this count exists to surface.- Same contract as :func:`_count_cron_jobs`.- """- if not path.is_file():- return None- try:- conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True)- except sqlite3.Error:- return None- try:- sessions = conn.execute("SELECT COUNT(*) FROM sessions").fetchone()[0]- messages = conn.execute("SELECT COUNT(*) FROM messages").fetchone()[0]- return int(sessions), int(messages)- except (sqlite3.Error, TypeError, ValueError):- return None- finally:- conn.close()+ print(f"Backup contains {file_count} files")+ print(f"Target: {display_hermes_home()}")+ if prefix:+ print(f"Detected archive prefix: {prefix!r} (will be stripped)")-def _import_db_member(- zf: zipfile.ZipFile, member: str, target: Path, new_file_mode: Optional[int] = None) -> None:- """Publish a SQLite ``.db`` member onto *target* without replacing its inode.+ # Check for existing installation+ has_config = (hermes_root / "config.yaml").exists()+ has_env = (hermes_root / ".env").exists()- A rename-publish over a live database is the #65942 / #90950 corruption class: a gateway,- dashboard, or WebUI holding it open keeps serving the unlinked inode and writing sessions no- other process will see, and a sidecar WAL beside the new file describes the old database —- nothing fails, the sessions are simply gone (#100960). Route the member through the same- ``_safe_restore_db`` page copy ``/snapshot restore`` uses, so the live inode is preserved and- every open connection converges. Raises ``OSError`` when the database could not be- replaced safely, so the caller reports a skipped file instead of a silent success.- """- if not target.exists():- # "Missing" is not "unheld": a gateway or dashboard that had the database open when it- # was unlinked still writes the deleted inode (the ``(deleted)`` fingerprint of #90950).- # Publishing a fresh inode here re-creates the same split brain the branch below exists- # to prevent, so refuse and name the holders instead (#110179).- holders = _foreign_db_holder_pids(target)- if holders:- raise OSError(- f"{target.name} was deleted but is still open in PID(s) "- f"{', '.join(str(pid) for pid in sorted(holders))}; publishing a new file would "- "leave them writing an invisible database. Stop those processes and re-run the import."- )- _extract_member_atomically(zf, member, target, new_file_mode)- return- # The database keeps its own mode/ownership: the bytes come from the archive, the file does not.- mode = _preserve_file_mode(target)- owner = _preserve_file_owner(target)- fd, tmp_name = tempfile.mkstemp(dir=str(target.parent), prefix=f".{target.name[:80]}.", suffix=".dbimport")- try:- with os.fdopen(fd, "wb") as dst:- with zf.open(member) as src: # stream: never hold a multi-GB state.db in memory- shutil.copyfileobj(src, dst)- dst.flush()- os.fsync(dst.fileno())- if not _safe_restore_db(Path(tmp_name), target):- raise OSError(- "live-safe restore refused or failed; the existing database was "- "left untouched. Stop the gateway/dashboard processes holding it "- "open and re-run the import."- )- _restore_file_owner(target, owner)- _restore_file_mode(target, mode)- finally:- with suppress(OSError):- os.unlink(tmp_name)+ if (has_config or has_env) and not args.force:+ print()+ print("Warning: Target directory already has Hermes configuration.")+ print("Importing will overwrite existing files with backup contents.")+ print()+ try:+ answer = input("Continue? [y/N] ").strip().lower()+ except (EOFError, KeyboardInterrupt):+ print("\nAborted.")+ sys.exit(1)+ if answer not in {"y", "yes"}:+ print("Aborted.")+ return+++ # Refuse damaged archives before writing any user files. Runtime and PM-local++ # members skipped below cannot block restoration of the portable data.++ print("\nChecking archive integrity ...")++ corrupt = _find_corrupt_members(zf, [m for m in members if not _import_member_rel(m, prefix)[1]])++ if corrupt:++ _print_capped(f"Error: backup archive is damaged ({len(corrupt)} member(s) fail to "++ f"decompress or fail their CRC); nothing was restored:", corrupt, " ")++ return 1++ # Extract+ print(f"\nImporting {file_count} files ...")+ hermes_root.mkdir(parents=True, exist_ok=True)-def _confirm_import_overwrite(hermes_root: Path) -> bool:- """Prompt before importing over an existing installation; True when import may proceed."""- if not any((hermes_root / m).exists() for m in ("config.yaml", ".env")):- return True- print("\nWarning: Target directory already has Hermes configuration.\n"- "Importing will overwrite existing files with backup contents.\n")- try:- answer = input("Continue? [y/N] ").strip().lower()- except (EOFError, KeyboardInterrupt):- print("\nAborted.")- sys.exit(1)- if answer in {"y", "yes"}:- return True- print("Aborted.")- return False+ errors = []+ restored = 0+ restored_external = 0+ skipped_runtime: list[str] = []+ # (rel, live_counts, imported_counts) for every session database the+ # import replaced with one holding fewer rows. A restore is allowed to+ # do that — it just must not do it silently (issue #100960).+ db_shrunk: list[tuple[str, tuple[int, int], tuple[int, int]]] = []+ home_dir = Path.home().resolve()+ # Resolved once: every member is published via a temp file, and mkstemp+ # would otherwise create newly restored files as 0600.+ new_file_mode = _default_new_file_mode()+ t0 = time.monotonic()+ for member in members:+ # External memory-provider state captured under the reserved+ # ``_external/`` arc prefix restores to its original home-relative+ # location (e.g. ~/.honcho/config.json), NOT under HERMES_HOME.+ if member.startswith(_EXTERNAL_PREFIX):+ ext_rel = member[len(_EXTERNAL_PREFIX):]+ if not ext_rel:+ continue+ target = home_dir / ext_rel+ # Security: the resolved target must stay under the home dir.+ try:+ target.resolve().relative_to(home_dir)+ except ValueError:+ errors.append(f" {member}: path traversal blocked")+ continue+ try:+ target.parent.mkdir(parents=True, exist_ok=True)+ _extract_member_atomically(zf, member, target, new_file_mode)+ # External provider configs commonly hold credentials.+ if target.suffix in {".json", ".env", ".conf"} or target.name in _SECRET_FILE_NAMES:+ try:+ os.chmod(target, 0o600)+ except OSError:+ pass+ restored += 1+ restored_external += 1- except (PermissionError, OSError) as exc:++ except (OSError, *_ZIP_MEMBER_READ_ERRORS) as exc:+ errors.append(f" {member}: {exc}")+ if restored % 500 == 0:+ print(f" {restored}/{file_count} files ...")+ continue-def _import_members(- zf: zipfile.ZipFile, members: List[str], prefix: str, hermes_root: Path, file_count: int-) -> tuple[int, int, list[str], list[str], list[tuple[str, tuple[int, int], tuple[int, int]]]]:- """Publish every member; return ``(restored, restored_external, errors, skipped_runtime, db_shrunk)``.+ # Strip prefix if detected+ if prefix and member.startswith(prefix):+ rel = member[len(prefix):]+ else:+ rel = member- ``db_shrunk`` holds ``(rel, live_counts, imported_counts)`` for every session database the- import replaced with one holding fewer rows — allowed, but never silent (#100960).- """- errors: list[str] = []- skipped_runtime: list[str] = []- db_shrunk: list[tuple[str, tuple[int, int], tuple[int, int]]] = []- restored = restored_external = 0- home_dir = Path.home().resolve()- new_file_mode = default_new_file_mode() # once: every member is published via mkstemp (0600)- for member in members:- # ``_external/`` members restore to their home-relative location (~/.honcho/config.json),- # NOT under HERMES_HOME; provider configs commonly hold credentials, so tighten to 0600.- external = member.startswith(_EXTERNAL_PREFIX)- rel, skipped = _import_member_rel(member, prefix)- if skipped:- skipped_runtime.append(rel)- continue- if external:- target = home_dir / rel- root = home_dir- tighten = target.suffix in {".json", ".env", ".conf"} or target.name in _SECRET_FILE_NAMES- else:- target = hermes_root / rel- root = hermes_root.resolve()- tighten = target.name in _SECRET_FILE_NAMES- if not rel:- continue+ if not rel:+ continue++ try:+ parts = tuple(normalize_archive_parts(rel))+ except ValueError:+ errors.append(f" {rel}: path traversal blocked")+ continue++ # Never overwrite volatile gateway/process runtime state. These are+ # namespaced to the machine/container the backup was taken on;+ # clobbering them (especially gateway_state.json) breaks the gateway+ # reconciler on the target and disconnects hosted instances from the+ # Nous portal. Matched by basename so both the root profile and+ # named profiles (profiles/<name>/gateway_state.json) are covered.+ if parts[-1] in _IMPORT_SKIP_NAMES:+ skipped_runtime.append(rel)+ continue++ # Older archives may contain PM selections pointing at another machine.+ # Match their home-root paths; a plugin's own facts.json is user data.+ if profile_root_entry(parts) in PM_RUNTIME_ROOT_DIRS:+ skipped_runtime.append(rel)+ continue++ # A ``.db`` member is page-restored into the live file below; a+ # WAL/SHM/journal member from the archive describes a different+ # database image, and installing it beside the restored file (over+ # a live sidecar, via os.replace) would replay a foreign WAL on+ # the next open. Current backups never ship these+ # (_EXCLUDED_SUFFIXES); older or hand-built archives might.+ if rel.endswith(_SQLITE_SIDECAR_SUFFIXES):+ skipped_runtime.append(rel)+ continue++ target = hermes_root.joinpath(*parts)++ # Security: reject absolute paths and traversals+ try:+ target.resolve().relative_to(hermes_root.resolve())+ except ValueError:+ errors.append(f" {rel}: path traversal blocked")+ continue- label = member if external else rel- if not _is_within(target, root):- errors.append(f"{label}: path traversal blocked")- else:try:target.parent.mkdir(parents=True, exist_ok=True)if target.suffix == ".db":@@@ -949,224 -1020,302 +858,380 @@@db_shrunk.append((rel, before, after))else:_extract_member_atomically(zf, member, target, new_file_mode)- if tighten:- try:- os.chmod(target, 0o600)- except OSError:- if not external: # external configs are tightened best-effort only- raise+ if target.name in _SECRET_FILE_NAMES:+ os.chmod(target, 0o600)restored += 1- except (PermissionError, OSError) as exc:- restored_external += external+ except (OSError, *_ZIP_MEMBER_READ_ERRORS) as exc:- # _ZIP_MEMBER_READ_ERRORS: the pre-flight in run_import already refused- # archives that fail to decompress; this keeps a member that rots between the two- # passes (archive on failing media) from aborting the rest of the restore.- errors.append(f"{label}: {exc}")+ errors.append(f" {rel}: {exc}")- if restored % 500 == 0:- print(f" {restored}/{file_count} files ...")-- return restored, restored_external, errors, skipped_runtime, db_shrunk+ if restored % 500 == 0:+ print(f" {restored}/{file_count} files ...")+ elapsed = time.monotonic() - t0-def run_import(args) -> Optional[int]:- """Restore a Hermes backup from a zip file.+ # Summary+ print()- print(f"Import complete: {restored} files restored in {elapsed:.1f}s")++ print(f"Import {'incomplete' if errors else 'complete'}: {restored} files restored in {elapsed:.1f}s")+ print(f" Target: {display_hermes_home()}")- Return 1 when the archive is damaged (refused before anything is written) or the restore is- incomplete (some members were not written); None on success or when the overwrite prompt is- declined. A missing, non-zip or invalid archive exits 1 via ``sys.exit``.- """- zip_path = Path(args.zipfile).expanduser().resolve()- if not zip_path.is_file():- print(f"Error: File not found: {zip_path}")- sys.exit(1)- if not zipfile.is_zipfile(zip_path):- print(f"Error: Not a valid zip file: {zip_path}")- sys.exit(1)- # The restore target is the home the command operates under (the printed "Target:");- # ``get_default_hermes_root()`` would silently retarget a profile restore at the live root.- hermes_root = get_hermes_home()- with zipfile.ZipFile(zip_path, "r") as zf:- ok, reason = _validate_backup_zip(zf)- if not ok:- print(f"Error: {reason}")- sys.exit(1)- prefix = _detect_prefix(zf)- members = [n for n in zf.namelist() if not n.endswith("/")]- file_count = len(members)- print(f"Backup contains {file_count} files\nTarget: {display_hermes_home()}")- if prefix:- print(f"Detected archive prefix: {prefix!r} (will be stripped)")- if not args.force and not _confirm_import_overwrite(hermes_root):- return- # Every member is decompressed once here and once again below: a damaged archive- # must be refused while the home is still untouched, not half-way through the restore.- print("\nChecking archive integrity ...")- # Members the restore skips anyway (gateway.pid, WAL sidecars) cannot block it.- corrupt = _find_corrupt_members(zf, [m for m in members if not _import_member_rel(m, prefix)[1]])- if corrupt:- _print_capped(f"Error: backup archive is damaged ({len(corrupt)} member(s) fail to "- f"decompress or fail their CRC); nothing was restored:", corrupt, " ")- return 1- print(f"\nImporting {file_count} files ...")- hermes_root.mkdir(parents=True, exist_ok=True)- t0 = time.monotonic()- restored, restored_external, errors, skipped_runtime, db_shrunk = _import_members(- zf, members, prefix, hermes_root, file_count)- elapsed = time.monotonic() - t0- print(f"\nImport {'incomplete' if errors else 'complete'}: {restored} files restored in {elapsed:.1f}s\n"- f" Target: {display_hermes_home()}")if restored_external:- print(f"\n Restored {restored_external} memory-provider file(s) to "- f"their original location(s) outside {display_hermes_home()}.")+ print(+ f"\n Restored {restored_external} memory-provider file(s) to "+ f"their original location(s) outside {display_hermes_home()}."+ )+if errors:- _print_capped(f"\n Warnings ({len(errors)} files skipped):", errors, " ")+ print(f"\n Warnings ({len(errors)} files skipped):")+ for e in errors[:10]:+ print(e)+ if len(errors) > 10:+ print(f" ... and {len(errors) - 10} more")+if db_shrunk:- # The backup predates work that is now overwritten — say so (#100960: twelve sessions- # disappeared with nothing logged anywhere).+ # The backup predates work that is now overwritten. Say so: the+ # reported incident was twelve sessions disappearing with nothing+ # logged anywhere (issue #100960).print("\n ⚠ Session data replaced by older backup contents:")for rel, before, after in db_shrunk:- print(f" {rel}: {before[0]} session(s) / {before[1]} message(s)"- f" -> {after[0]} / {after[1]}")- print(f" Anything recorded after the backup was taken is not in it. {_snapshot_recovery_hint()}")+ print(+ f" {rel}: {before[0]} session(s) / {before[1]} message(s)"+ f" -> {after[0]} / {after[1]}"+ )+ print(+ " Anything recorded after the backup was taken is not in it. "+ f"{_snapshot_recovery_hint()}"+ )+if skipped_runtime:- _print_capped(f"\n Preserved {len(skipped_runtime)} runtime state "- f"file(s) (kept this machine's, not the backup's):",- sorted(skipped_runtime), " ")- restored_profiles = _restore_profile_wrappers(hermes_root)+ print(+ f"\n Preserved {len(skipped_runtime)} runtime state "+ f"file(s) (kept this machine's, not the backup's):"+ )+ for rel in sorted(skipped_runtime)[:10]:+ print(f" {rel}")+ if len(skipped_runtime) > 10:+ print(f" ... and {len(skipped_runtime) - 10} more")++ # Post-import: restore profile wrapper scripts+ profiles_dir = hermes_root / "profiles"+ restored_profiles = []+ if profiles_dir.is_dir():+ try:+ from hermes_cli.profiles import (+ create_wrapper_script, check_alias_collision,+ _is_wrapper_dir_in_path, _get_wrapper_dir,+ )+ for entry in sorted(profiles_dir.iterdir()):+ if not entry.is_dir():+ continue+ profile_name = entry.name+ # Only create wrappers for directories with config+ if not (entry / "config.yaml").exists() and not (entry / ".env").exists():+ continue+ collision = check_alias_collision(profile_name)+ if collision:+ print(f" Skipped alias '{profile_name}': {collision}")+ restored_profiles.append((profile_name, False))+ else:+ wrapper = create_wrapper_script(profile_name)+ restored_profiles.append((profile_name, wrapper is not None))++ if restored_profiles:+ created = [n for n, ok in restored_profiles if ok]+ skipped = [n for n, ok in restored_profiles if not ok]+ if created:+ print(f"\n Profile aliases restored: {', '.join(created)}")+ if skipped:+ print(f" Profile aliases skipped: {', '.join(skipped)}")+ if not _is_wrapper_dir_in_path():+ print(f"\n Note: {_get_wrapper_dir()} is not in your PATH.")+ print(' Add to your shell config (~/.bashrc or ~/.zshrc):')+ print(' export PATH="$HOME/.local/bin:$PATH"')+ except ImportError:+ # hermes_cli.profiles might not be available (fresh install)+ if any(profiles_dir.iterdir()):+ print("\n Profiles detected but aliases could not be created.")+ print(" Run: hermes profile list (after installing hermes)")++ # Guidanceprint()if not (hermes_root / "hermes-agent").is_dir():- print("Note: The hermes-agent codebase was not included in the backup.\n"- " If this is a fresh install, run: hermes update")+ print("Note: The hermes-agent codebase was not included in the backup.")+ print(" If this is a fresh install, run: hermes update")+if restored_profiles:+ gw_profiles = [n for n, _ in restored_profiles]print("\nTo re-enable gateway services for profiles:")- for pname in restored_profiles:+ for pname in gw_profiles:print(f" hermes -p {pname} gateway install")- _revive_gateway_after_import(hermes_root)++ # Bring the restored install to life: the backup may contain bot+ # tokens and registered cron jobs, but they're inert without a+ # gateway process. Install/start the service automatically (a+ # platform-less gateway is a supported mode, so this is safe even+ # for backups with no messaging config). Best-effort and prompt-free;+ # failures print a manual fallback and never fail the import.+ native_default = _get_platform_default_hermes_home()+ default_has_install = any(+ (native_default / marker).exists()+ for marker in ("config.yaml", ".env", "state.db")+ )+ # A restore into a sandbox or profile home must not silently install+ # a second gateway pointed at it — on the default service name that+ # would shadow or hijack the machine's primary install. Only revive+ # the service automatically when the restore landed in the default+ # home, or when no other install exists on this machine.+ if hermes_root != native_default and default_has_install:+ print(+ "\nRestored into a non-default home; leaving the gateway service "+ "alone to avoid clashing with the install at "+ f"{native_default}."+ )+ print("To start a gateway for this home, run: hermes gateway install")+ else:+ try:+ from hermes_cli.gateway import ensure_gateway_service, _is_service_running++ if not _is_service_running():+ print()+ ensure_gateway_service(context="import")+ except Exception:+ print("\nStart the gateway to activate cron jobs and messaging:")+ print(" hermes gateway install")++ if errors:- # A refused state.db leaves the old sessions in place; exit 0 would let scripts and- # the dashboard's "done" badge treat that as a full restore.+ print(f"Import incomplete: {len(errors)} file(s) were not restored (see Warnings above). "+ "Fix the cause and re-run the import.")+ return 1print("Done. Your Hermes configuration has been restored.")-def _restore_profile_wrappers(hermes_root: Path) -> List[str]:- """Re-create shell wrapper scripts for restored named profiles; return the profile names seen."""- profiles_dir = hermes_root / "profiles"- restored_profiles: list[tuple[str, bool]] = []- if not profiles_dir.is_dir():- return []- try:- from hermes_cli.profiles import (- create_wrapper_script, check_alias_collision, _is_wrapper_dir_in_path, _get_wrapper_dir)- for entry in sorted(profiles_dir.iterdir()):- if not entry.is_dir() or not any((entry / m).exists() for m in ("config.yaml", ".env")):- continue # only profiles with config get wrappers- profile_name = entry.name- collision = check_alias_collision(profile_name)- if collision:- print(f" Skipped alias '{profile_name}': {collision}")- restored_profiles.append(- (profile_name, not collision and create_wrapper_script(profile_name) is not None))- if restored_profiles:- created = [n for n, ok in restored_profiles if ok]- skipped = [n for n, ok in restored_profiles if not ok]- if created:- print(f"\n Profile aliases restored: {', '.join(created)}")- if skipped:- print(f" Profile aliases skipped: {', '.join(skipped)}")- if not _is_wrapper_dir_in_path():- print(f"\n Note: {_get_wrapper_dir()} is not in your PATH.\n"- " Add to your shell config (~/.bashrc or ~/.zshrc):\n"- ' export PATH="$HOME/.local/bin:$PATH"')- except ImportError: # hermes_cli.profiles unavailable (fresh install)- if any(profiles_dir.iterdir()):- print("\n Profiles detected but aliases could not be created.\n"- " Run: hermes profile list (after installing hermes)")- return [n for n, _ in restored_profiles]---def _revive_gateway_after_import(hermes_root: Path) -> None:- """Install/start the gateway service after a restore, best-effort and prompt-free.-- Bot tokens and cron jobs are inert without a gateway (a platform-less gateway is supported, so- this is safe for any backup); failures print a manual fallback, never fail the import. Only- revived when the restore landed in the default home or no other install exists: a sandbox or- profile restore must not install a second gateway on the default service name.- """- native_default = _get_platform_default_hermes_home()- if hermes_root != native_default and any(- (native_default / marker).exists() for marker in ("config.yaml", ".env", "state.db")):- print("\nRestored into a non-default home; leaving the gateway service alone to avoid clashing "- f"with the install at {native_default}.\n"- "To start a gateway for this home, run: hermes gateway install")- return- try:- from hermes_cli.gateway import ensure_gateway_service, _is_service_running- if not _is_service_running():- print()- ensure_gateway_service(context="import")- except Exception:- print("\nStart the gateway to activate cron jobs and messaging:\n hermes gateway install")-++ # --- Quick state snapshots (used by /snapshot slash command and hermes backup --quick) ---++ # Critical state files (relative to HERMES_HOME) for quick snapshots; everything else is+ # regeneratable or managed separately (skills, repo, sessions/). Entries may be files OR+ # directories (recursive); missing entries are skipped. Pairing data lives in platform JSON blobs+ # outside state.db, so it is listed explicitly — ``hermes update`` snapshots this set (#15733).+ _QUICK_STATE_FILES = (+ "state.db", "config.yaml", ".env", "auth.json", "cron/jobs.json", "cron/executions.db",+ "gateway_state.json", "channel_directory.json", "channel_aliases.json", "processes.json",+ "gateway/discord_message_recovery.db", # Discord reconnect replay ledger+ # Per-profile user stores, destroyed if the update flow replaces the file and the post-update+ # schema-init re-creates an empty one (#52889). Skipped when outside HERMES_HOME.+ "projects.db", # per-profile project store+ "response_store.db", # gateway conversation history / tool payloads+ "memory_store.db", # holographic memory facts/entities+ "verification_evidence.db", # agent verification audit trail+ "kanban.db", # default board (back-compat <root>/kanban.db)+ "kanban/boards", # non-default boards (workspaces/ + attachments/ skipped as regenerable)+ # Pairing stores (generic + per-platform JSONs outside state.db)+ "pairing", # legacy location (gateway/pairing.py)+ "platforms/pairing", # new location (gateway/pairing.py)+ "feishu_comment_pairing.json", # Feishu comment subscription pairings+ )++ _QUICK_DEFAULT_KEEP = 20+++ def _quick_snapshot_root(hermes_home: Optional[Path] = None) -> Path:+ home = hermes_home or get_hermes_home()+ return home / _QUICK_SNAPSHOTS_DIR++-def create_quick_snapshot(- label: Optional[str] = None, hermes_home: Optional[Path] = None, keep: Optional[int] = None,- max_file_size: Optional[int] = None) -> Optional[str]:- """Create one atomic quick snapshot while holding the shared backup slot."""- home = hermes_home or get_hermes_home()- with _backup_operation_lock(home):- return _create_quick_snapshot_locked(label, home, keep, max_file_size)-++def _newest_first(root: Path, keep_entry) -> List[Path]:++ """Entries of *root* passing ``keep_entry``, newest (by name) first; ``[]`` if *root* is missing."""++ if not root.exists():++ return []++ return sorted(filter(keep_entry, root.iterdir()), key=lambda p: p.name, reverse=True)+-def _quick_snapshot_candidates(home: Path):- """Yield ``(src, rel_posix, in_dir)`` for every regular file a quick snapshot captures; heavy- regenerable per-board subtrees (workspaces, attachments) are skipped."""- for rel in _QUICK_STATE_FILES:- src = home / rel- if src.is_dir():- for sub in filter(Path.is_file, src.rglob("*")):- sub_rel = sub.relative_to(home).as_posix()- if "/workspaces/" in f"/{sub_rel}/" or "/attachments/" in f"/{sub_rel}/":- continue- yield sub, sub_rel, True- elif src.is_file():- yield src, rel, False+++# Kept in sync with ``_QUICK_STATE_FILES`` and ``cron/jobs.py``'s ``JOBS_FILE``.++_CRON_JOBS_REL = "cron/jobs.json"+-def _copy_quick_snapshot_files(- home: Path, staging_dir: Path, max_file_size: Optional[int]-) -> tuple[Dict[str, int], list[str], list[str]]:- """Copy every quick-snapshot candidate into *staging_dir*.+- Returns ``(manifest {rel: size}, failed_dbs, oversized_skipped)``. The last two are snapshot- incompleteness (#68805): the caller must suppress pruning so the older snapshot that may hold- the only recoverable DB survives.- """- manifest: Dict[str, int] = {}- failed_dbs: list[str] = []- oversized_skipped: list[str] = []- for src, rel, in_dir in _quick_snapshot_candidates(home):- if max_file_size is not None:- try:- size = src.stat().st_size- except OSError:- size = None- if size is not None and size > max_file_size:- print(f" ⚠ Snapshot: skipping {rel} "- f"({_format_size(size)} exceeds {_format_size(max_file_size)} limit)")- logger.warning("Quick snapshot skipped %s: %d bytes exceeds %d byte limit", rel, size, max_file_size)- if src.suffix == ".db":- oversized_skipped.append(rel)- continue- dst = staging_dir / rel- dst.parent.mkdir(parents=True, exist_ok=True)- try:- # SQLite DBs go through the WAL-safe backup() path (the gateway may hold the WAL open).- if src.suffix == ".db":- if not _safe_copy_db(src, dst):- failed_dbs.append(rel)- print(f" ⚠ Snapshot: SQLite safe copy FAILED for {rel} — file may be locked or corrupted")- if is_zeroed_sqlite_file(src):- nuls = " of NULs?" if in_dir else ""- print(f" ⚠ Snapshot: {rel} looks ZEROED "- f"(no SQLite header; {src.stat().st_size} bytes{nuls})")- continue- else:- shutil.copy2(src, dst)- manifest[rel] = dst.stat().st_size- except (OSError, PermissionError) as exc:- logger.warning("Could not snapshot %s: %s", rel, exc)- return manifest, failed_dbs, oversized_skipped++# Config paths the update flow must never change (#64160): model routing and the MoA section are++# consumed machine-wide, so an update/repair cycle that rewrites them silently redirects paid++# inference. Dotted paths into raw config.yaml; a single-element tuple protects a whole section.++_PROTECTED_CONFIG_PATHS: Tuple[Tuple[str, ...], ...] = (++ ("model", "provider"), ("model", "default"), ("model", "base_url"), ("model", "api_key"),++ ("moa",))++-def _secure_quick_snapshot_tree(root: Path, snapshot_dir: Path) -> None:- """Make a staged quick snapshot owner-only before it is published.++def _prune_oldest(newest_first: List[Path], keep: int, remove, what: str) -> int:++ """``remove(path)`` every entry past the first *keep*; return how many succeeded."""++ deleted = 0++ for p in newest_first[keep:]:++ try:++ remove(p)++ deleted += 1++ except OSError as exc:++ logger.warning("Failed to prune %s %s: %s", what, p.name, exc)++ return deleted++++++# --- Shared full-zip backup helper ---++++++# --- Pre-update / pre-migration auto-backups ---++++_PRE_UPDATE_BACKUPS_DIR = "backups"++_PRE_UPDATE_PREFIX = "pre-update-"++_PRE_UPDATE_DEFAULT_KEEP = 5++_PRE_MIGRATION_PREFIX = "pre-migration-"++_PRE_MIGRATION_DEFAULT_KEEP = 5+- The staging directory is private from creation, so copied source modes can- be normalized safely before the final atomic rename exposes the snapshot.- Permission failures are intentionally fatal: publishing a readable- recovery bundle is worse than reporting a failed snapshot.++++def _prune_prefixed_zips(backup_dir: Path, prefix: str, keep: int, what: str) -> int:++ """Remove oldest ``<prefix>*.zip`` in *backup_dir* beyond *keep*; return count deleted.++++ Only prefix-matched files are touched, so hand-made zips or other backup kinds survive.+ """- if os.name == "nt":- return- os.chmod(root, 0o700)- os.chmod(snapshot_dir, 0o700)- for path in snapshot_dir.rglob("*"):- if path.is_dir():- os.chmod(path, 0o700)- elif path.is_file():- os.chmod(path, 0o600)++ backups = _newest_first(backup_dir, lambda p: p.is_file() and p.name.startswith(prefix)++ and p.suffix.lower() == ".zip")++ return _prune_oldest(backups, keep, Path.unlink, what)++-def _create_quick_snapshot_locked(- label: Optional[str], home: Path, keep: Optional[int], max_file_size: Optional[int]++def _create_prefixed_full_backup(++ hermes_home: Optional[Path], prefix: str, keep: int, what: str, prune_what: str) -> Optional[Path]:++ """Write ``<HERMES_HOME>/backups/<prefix><timestamp>.zip`` and prune older same-prefix zips.++ Returns the path, or ``None`` if nothing to back up or the write failed. Never raises."""++ hermes_root = hermes_home or get_default_hermes_root()++ if not hermes_root.is_dir():++ return None++ backup_dir = hermes_root / _PRE_UPDATE_BACKUPS_DIR++ try:++ backup_dir.mkdir(parents=True, exist_ok=True)++ except OSError as exc:++ logger.warning("Could not create %s backup dir %s: %s", what, backup_dir, exc)++ return None++ out_path = backup_dir / f"{prefix}{datetime.now().strftime('%Y-%m-%d-%H%M%S')}.zip"++ if _write_full_zip_backup(out_path, hermes_root) is None:++ return None++ _prune_prefixed_zips(backup_dir, prefix, keep, prune_what)++ return out_path++++++def create_pre_update_backup(++ hermes_home: Optional[Path] = None, keep: int = _PRE_UPDATE_DEFAULT_KEEP) -> Optional[Path]:++ """Full zip backup to ``backups/pre-update-<timestamp>.zip``, auto-pruned; ``None`` if nothing++ was found or the backup failed. Never raises — ``hermes update`` continues anyway."""++ return _create_prefixed_full_backup(hermes_home, _PRE_UPDATE_PREFIX, max(keep, 1), "pre-update", "backup")++++++def create_pre_migration_backup(++ hermes_home: Optional[Path] = None, keep: int = _PRE_MIGRATION_DEFAULT_KEEP) -> Optional[Path]:++ """Full zip backup to ``backups/pre-migration-<timestamp>.zip`` before ``hermes claw migrate``++ (same dir as update backups so listings/``hermes import`` find it); ``None`` if nothing was++ found or the write failed. Never raises."""++ return _create_prefixed_full_backup(++ hermes_home, _PRE_MIGRATION_PREFIX, max(keep, 0), "pre-migration", "pre-migration backup")++++++# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----++# Names external plugins imported from this module before the Sep 2026 decomposition.++# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).++# The whole block is removed by reverting the commit that added it.++++def copy_db_and_verify(src: Path, dst: Path) -> bool:++ """Like :func:`_safe_copy_db` but verifies the destination after copy.++++ Returns True only when the copy succeeded AND the destination is valid++ SQLite (header + integrity check). Verification honours the default++ size ceiling — a multi-GB destination gets the header + schema probe++ rather than a full ``PRAGMA integrity_check`` that would page through++ the whole file.++ """++ if not _safe_copy_db(src, dst):++ return False++ integrity = verify_sqlite_integrity(dst, run_pragma=True)++ if not integrity.get("valid"):++ try:++ dst.unlink(missing_ok=True)++ except OSError:++ pass++ logger.warning("Backup of %s failed integrity verification: %s", src, integrity.get("message"))++ return False++ return True++++++# ---- END PLUGIN-COMPAT ----+++++# ---------------------------------------------------------------------------+# Quick state snapshots (used by /snapshot slash command and hermes backup --quick)+# ---------------------------------------------------------------------------++def create_quick_snapshot(+ label: Optional[str] = None,+ hermes_home: Optional[Path] = None,+ keep: Optional[int] = None,+ max_file_size: Optional[int] = None,) -> Optional[str]:- """Copy the quick-snapshot set to a timestamped dir under state-snapshots/ and prune old ones.+ """Create one atomic quick snapshot while holding the shared backup slot."""+ home = hermes_home or get_hermes_home()+ with _backup_operation_lock(home):+ return _create_quick_snapshot_locked(+ label=label,+ hermes_home=home,+ keep=keep,+ max_file_size=max_file_size,+ )+- ``max_file_size`` skips (with a warning) larger files: the pre-update snapshot uses it so a- multi-GB ``state.db`` never stalls ``hermes update`` while the small files are always captured.+def _create_quick_snapshot_locked(+ label: Optional[str] = None,+ hermes_home: Optional[Path] = None,+ keep: Optional[int] = None,+ max_file_size: Optional[int] = None,+) -> Optional[str]:+ """Create a quick state snapshot of critical files.++ Copies STATE_FILES to a timestamped directory under state-snapshots/.+ Auto-prunes old snapshots beyond the keep limit.++ Args:+ max_file_size: When set, individual files larger than this many bytes+ are skipped (with a printed warning) instead of copied. Used by+ the pre-update safety snapshot so a multi-GB ``state.db`` can+ never stall ``hermes update`` or silently eat disk — the small+ pairing/cron/config files the snapshot exists to protect are+ always captured. ``None`` (default) copies everything, which+ preserves manual ``/snapshot`` and ``hermes backup --quick``+ behavior.++ Returns:+ Snapshot ID (timestamp-based), or None if no files found."""+ home = hermes_home or get_hermes_home()root = _quick_snapshot_root(home)++ def _too_large(path: Path, rel_name: str) -> bool:+ """True (and warn) when ``path`` exceeds the max_file_size cap."""+ if max_file_size is None:+ return False+ try:+ size = path.stat().st_size+ except OSError:+ return False+ if size <= max_file_size:+ return False+ print(+ f" ⚠ Snapshot: skipping {rel_name} "+ f"({_format_size(size)} exceeds {_format_size(max_file_size)} limit)"+ )+ logger.warning(+ "Quick snapshot skipped %s: %d bytes exceeds %d byte limit",+ rel_name,+ size,+ max_file_size,+ )+ return True+ts = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")base_snap_id = f"{ts}-{label}" if label else ts- snap_id, suffix = base_snap_id, 2+ snap_id = base_snap_id+ suffix = 2while (root / snap_id).exists():snap_id = f"{base_snap_id}-{suffix}"suffix += 1diff --cc tests/e2e/core/_pm_dependencies.pyindex 00000000000,00000000000..87bea0eaf56new file mode 100644--- /dev/null+++ b/tests/e2e/core/_pm_dependencies.py@@@ -1,0 -1,0 +1,29 @@@++"""Select prepared test dependencies for subprocesses with isolated E2E homes."""++++from __future__ import annotations++++import json++import shutil++import sys++from pathlib import Path++++from pm.environments import install_key, site_packages++++++def select_test_dependencies(hermes_home: Path, checkout: Path) -> None:++ """Point sandbox PM facts at the real test venv instead of bootstrapping a second one."""++ test_venv = Path(sys.prefix)++ if not (test_venv / "pyvenv.cfg").is_file():++ return # Nix/system Python has no prepared venv to select.++ selected = site_packages(test_venv)++ assert selected.is_dir(), f"test interpreter lacks site-packages: {test_venv}"++ state = hermes_home / "installs" / install_key(checkout)++ environment = state / "environments" / "e2e-test" / "venv"++ environment.mkdir(parents=True)++ shutil.copyfile(test_venv / "pyvenv.cfg", environment / "pyvenv.cfg")++ target = environment / selected.relative_to(test_venv)++ target.parent.mkdir(parents=True)++ target.symlink_to(selected, target_is_directory=True)++ (state / "facts.json").write_text(json.dumps({"packages": {"venv": {++ "environment": str(environment),++ }}}), encoding="utf-8")diff --cc tests/e2e/core/dashboard/_helpers.pyindex bb3c164bf4d,04c860d8055..aa92d0ce3c4--- a/tests/e2e/core/dashboard/_helpers.py+++ b/tests/e2e/core/dashboard/_helpers.py@@@ -186,32 -184,6 +185,12 @@@ def write_profile_home(p: Profile, extr(p.home / ".env").write_text(f"{PROVIDER_KEY_ENV}={p.provider_key}\n", encoding="utf-8")+def _select_test_dependencies(sb: Sandbox) -> None:- """Boot real entrypoints against the PM test venv, not a checkout's unrelated .venv.-- Bootstrap selects dependencies from HOME's PM facts even when the invoking Python is- already the test interpreter. Keep that selection in the sandbox, backed by the actual- test environment rather than syncing into either the sandbox or the developer's HOME.- """- from pm.environments import install_key, site_packages-- test_venv = Path(sys.prefix)- if not (test_venv / "pyvenv.cfg").is_file():- return # Nix/system Python has no venv to redirect; bootstrap keeps its own imports.- selected = site_packages(test_venv)- assert selected.is_dir(), f"test interpreter lacks site-packages: {test_venv}"- state = sb.hermes_home / "installs" / install_key(REPO_ROOT)- environment = state / "environments" / "dashboard-test" / "venv"- environment.mkdir(parents=True)- shutil.copyfile(test_venv / "pyvenv.cfg", environment / "pyvenv.cfg")- target = environment / selected.relative_to(test_venv)- target.parent.mkdir(parents=True)- target.symlink_to(selected, target_is_directory=True)- (state / "facts.json").write_text(json.dumps({"packages": {"venv": {- "environment": str(environment),- }}}), encoding="utf-8")++ from tests.e2e.core._pm_dependencies import select_test_dependencies++++ select_test_dependencies(sb.hermes_home, REPO_ROOT)++def make_sandbox(root: Path, names: tuple[str, ...] = ("default",),responder: Callable[[Profile], Any] | None = None) -> Sandbox:"""Launch profile at HOME/.hermes, the rest under profiles/<name>; each owns a started providerdiff --cc tests/e2e/core/mcp_plugins/_helpers.pyindex ff1ea41d863,887c3bcb089..f987de34aa8--- a/tests/e2e/core/mcp_plugins/_helpers.py+++ b/tests/e2e/core/mcp_plugins/_helpers.py@@@ -120,31 -119,6 +119,12 @@@ class E2EHomeself.config_path.write_text(yaml.safe_dump(cfg, sort_keys=False), encoding="utf-8")+def _select_test_dependencies(eh: E2EHome) -> None:- """Select the prepared test dependencies inside this fake HOME, not the real install.-- PM's startup selection reads facts from the child's HOME. Without these facts- each fresh MCP home can bootstrap its own full runtime under CI contention.- """- from pm.environments import install_key, site_packages-- test_venv = Path(sys.prefix)- if not (test_venv / "pyvenv.cfg").is_file():- return # System Python has no prepared venv to select.- selected = site_packages(test_venv)- assert selected.is_dir(), f"test interpreter lacks site-packages: {test_venv}"- state = eh.hermes_home / "installs" / install_key(REPO_ROOT)- environment = state / "environments" / "mcp-test" / "venv"- environment.mkdir(parents=True)- shutil.copyfile(test_venv / "pyvenv.cfg", environment / "pyvenv.cfg")- target = environment / selected.relative_to(test_venv)- target.parent.mkdir(parents=True)- target.symlink_to(selected, target_is_directory=True)- (state / "facts.json").write_text(json.dumps({"packages": {"venv": {- "environment": str(environment),- }}}), encoding="utf-8")++ from tests.e2e.core._pm_dependencies import select_test_dependencies++++ select_test_dependencies(eh.hermes_home, REPO_ROOT)++def build_home(root: Path, base_url: str, *, mcp_servers: dict[str, dict] | None = None,extra: dict[str, Any] | None = None) -> E2EHome:home = root / "home"diff --cc tests/e2e/core/providers/_catalog_helpers.pyindex 00000000000,5d6cb1de5b0..c9640b62387mode 000000,100644..100644--- a/tests/e2e/core/providers/_catalog_helpers.py+++ b/tests/e2e/core/providers/_catalog_helpers.py@@@ -1,0 -1,379 +1,381 @@@+ """Shared harness for the provider-catalog E2E matrix.++ The provider list is NEVER hardcoded: :func:`discover_catalog` runs the real plugin discovery+ (``providers.list_providers()``) in a clean child interpreter, so a new plugin under+ ``plugins/model-providers/`` joins every matrix automatically. Each row is driven through the+ real ``python -m hermes_cli.main`` in a hermetic HOME against+ :class:`tests.fakes.providers.catalog_fake.CatalogFake`, redirected the way the product documents+ (``model.provider`` + ``model.base_url`` in config.yaml; ``/anthropic`` path for the Anthropic+ Messages dialect). Every other provider's key is present as a decoy, and all non-loopback egress+ goes through the fake's sentinel proxy, so a credential sent to the wrong host is observable.+ """++ from __future__ import annotations++ import contextlib+ import hashlib+ import json+ import os+ import sqlite3+ import subprocess+ import sys+ import tempfile+ import time+ from concurrent.futures import ThreadPoolExecutor+ from dataclasses import dataclass, field+ from pathlib import Path+ from typing import Any+ from urllib.parse import urlsplit++ import pytest-import yaml++import hermes_yaml as yaml++ from tests.e2e.core._pending_fixes import known_failure++from tests.e2e.core._pm_dependencies import select_test_dependencies+ from tests.fakes.providers.catalog_fake import USAGE_IN, USAGE_OUT, CatalogFake, Recorded++ REPO_ROOT = Path(__file__).resolve().parents[4]+ # Hard bound per child. A row that talks to its vendor host instead of the fake ends on its own:+ # the sentinel refuses the CONNECT at once and ``auto_recovery_cycles: 0`` (see ``write_home``)+ # stops the retry ladder (xai: 7 refused CONNECTs, rc 2 after ~18 s). No earlier wall-clock+ # "vendor CONNECT then silence" kill: healthy rows CONNECT their own vendor host during startup+ # (deepinfra's catalog fetch) and then do seconds of CPU-bound init before the first inference,+ # which a loaded CI runner stretches past any fixed grace (it killed a healthy deepinfra turn).+ TURN_TIMEOUT = 75.0+ SHARDS = 3+ FINAL = "CATALOG-TURN-COMPLETE"++ # Wire dialect the fake must see for each transport the runtime can resolve. A transport missing+ # here FAILS the matrix row (teach CatalogFake the dialect); it never becomes a skip.+ DIALECT_OF_API_MODE = {"chat_completions": "chat", "anthropic_messages": "anthropic", "codex_responses": "responses"}+ # Header that must carry the key, per dialect (Anthropic Messages = x-api-key; OpenAI wire = Bearer).+ AUTH_HEADER_OF_DIALECT = {"chat": "authorization", "responses": "authorization", "anthropic": "x-api-key"}+ # Where the documented base-URL override points, per dialect (Anthropic needs a ``/anthropic``+ # path: the product only trusts an Anthropic-protocol override that looks like one).+ URL_SUFFIX_OF_DIALECT = {"chat": "/v1", "responses": "/v1", "anthropic": "/anthropic"}+ # Inference endpoint appended to the configured base URL, per dialect (the Anthropic SDK appends+ # ``/v1/messages`` to an unversioned base; the OpenAI SDK appends to a ``/v1`` base).+ ENDPOINT_OF_DIALECT = {"chat": "/chat/completions", "responses": "/responses", "anthropic": "/v1/messages"}++ # The ONLY reasons a discovered provider may leave the matrix: auth types whose transport cannot+ # be pointed at a loopback HTTP fake by config/env alone, and named keyless providers.+ UNREDIRECTABLE_AUTH = {+ "aws_sdk": "AWS SigV4 via boto3 default chain; no HTTP fake for bedrock-runtime in this lane",+ "vertex": "Google ADC/OAuth2 token minting is required before any request",+ "external_process": "speaks ACP to a local vendor CLI subprocess, not HTTP",+ "copilot": "the GitHub token exchange URL is hardcoded (api.github.com/copilot_internal/v2/token)",+ "oauth_device_code": "login + refresh covered by test_catalog_oauth.py",+ "oauth_external": "login + refresh covered by test_catalog_oauth.py (where redirectable)",+ }+ KEYLESS_PROVIDERS = {+ "custom": "user-defined endpoint keyed by config api_key; covered by test_chat_custom_endpoint.py",+ }+ # Hosts a hermetic run may reach without carrying any vendor credential.+ CREDENTIAL_FREE_HOSTS = frozenset({"models.dev:443"})++ _SECRET_SUFFIXES = ("_API_KEY", "_TOKEN", "_SECRET", "_ACCESS_KEY", "_KEY")+ _PASSTHROUGH = frozenset({"PATH", "LANG", "LANGUAGE", "USER", "LOGNAME", "SHELL", "TMPDIR", "TZ"})+++ class CatalogGap(AssertionError):+ """Raised ONLY by a gated final assertion, so ``known_failure(raises=CatalogGap)`` can never+ swallow a harness failure (timeout, boot crash, precondition assert)."""+++ def gate(ok: bool, message: str) -> None:+ if not ok:+ raise CatalogGap(message)+++ @dataclass(frozen=True)+ class Known:+ """An open bug, gated on its OWN observed signature (a regex on the gated message)."""++ pattern: str+ reason: str+ cells: frozenset[str] = frozenset()+++ def known_gate(known: Known | None) -> contextlib.AbstractContextManager:+ return known_failure(known.pattern, known.reason, raises=CatalogGap) if known else contextlib.nullcontext()+++ @dataclass(frozen=True)+ class Row:+ name: str+ api_mode: str+ auth_type: str+ key_env: str | None+ base_url: str+ aliases: tuple[str, ...]+ supports_model_listing: bool+ # The declared transport is mandated by the provider's OWN host (e.g. a Responses-native+ # endpoint); at a foreign base URL the product speaks plain chat completions instead.+ host_mandated: bool = False++ @property+ def dialect(self) -> str | None:+ return DIALECT_OF_API_MODE.get(self.api_mode)++ def skip_reason(self) -> str | None:+ if self.auth_type in UNREDIRECTABLE_AUTH:+ return f"{self.name}: {UNREDIRECTABLE_AUTH[self.auth_type]}"+ if self.name in KEYLESS_PROVIDERS:+ return f"{self.name}: {KEYLESS_PROVIDERS[self.name]}"+ return None++ @property+ def base_path(self) -> str:+ """Path of the base URL every file configures for this row on its loopback fake."""+ return f"/{self.name}{URL_SUFFIX_OF_DIALECT[self.dialect or 'chat']}"++ def routes(self) -> dict[str, str]:+ """Exact path -> dialect the fake answers for this row; everything else is a 404."""+ assert self.dialect, f"{self.name}: transport {self.api_mode!r} has no loopback dialect"+ p = self.base_path+ out = {p + ENDPOINT_OF_DIALECT[self.dialect]: self.dialect}+ if self.dialect == "responses" or self.host_mandated:+ out[p + ENDPOINT_OF_DIALECT["chat"]] = "chat"+ # Listing: ``/models`` under the configured base; under the Anthropic override also the+ # Anthropic API's own ``/v1/models`` (the SDK's versioned path).+ out[p + "/models"] = "listing"+ if self.dialect == "anthropic":+ out[p + "/v1/models"] = "listing"+ return out++ def listing_routes(self) -> set[str]:+ return {p for p, d in self.routes().items() if d == "listing"}++ def vendor_host(self) -> str:+ return f"{urlsplit(self.base_url).hostname}:443" if self.base_url.startswith("https://") else ""+++ _CATALOG: list[Row] | None = None++ _DISCOVER = """+ import json, providers+ from hermes_cli.providers import host_mandated_api_mode+ out = []+ for p in providers.list_providers():+ key = next((e for e in p.env_vars if not e.endswith("_BASE_URL")), None)+ out.append(dict(name=p.name, api_mode=p.api_mode, auth_type=p.auth_type, key_env=key,+ base_url=p.base_url, aliases=list(p.aliases),+ supports_model_listing=bool(p.supports_model_listing),+ host_mandated=host_mandated_api_mode(p.base_url) is not None))+ print("CATALOG=" + json.dumps(out))+ """+++ def discover_catalog() -> list[Row]:+ """Real plugin discovery in a clean child (no user plugins, no credentials)."""+ global _CATALOG+ if _CATALOG is None:+ with tempfile.TemporaryDirectory(prefix="catalog-discover-") as d:+ env = {k: v for k, v in os.environ.items() if k in _PASSTHROUGH}+ env.update(HOME=d, HERMES_HOME=str(Path(d) / ".hermes"), PYTHONPATH=str(REPO_ROOT))+ proc = subprocess.run([sys.executable, "-c", _DISCOVER], env=env, capture_output=True,+ text=True, timeout=120, cwd=str(REPO_ROOT))+ line = next((ln for ln in proc.stdout.splitlines() if ln.startswith("CATALOG=")), None)+ assert line, f"provider discovery failed: {proc.stderr[-2000:]}"+ _CATALOG = sorted((Row(**{**r, "aliases": tuple(r["aliases"])}) for r in json.loads(line[8:])),+ key=lambda r: r.name)+ return _CATALOG+++ def shard_of(name: str, shards: int = SHARDS) -> int:+ return int(hashlib.sha256(name.encode()).hexdigest()[:8], 16) % shards+++ def decoy_keys(catalog: list[Row]) -> dict[str, str]:+ """One distinct fake secret per credential env var any provider declares."""+ return {r.key_env: f"sk-cat-{r.key_env.lower()}" for r in catalog if r.key_env}+++ def hermetic_env(home: Path, extra: dict[str, str]) -> dict[str, str]:+ env = {k: v for k, v in os.environ.items()+ if (k in _PASSTHROUGH or k.startswith("LC_")) and not k.endswith(_SECRET_SUFFIXES)}+ env.update({+ "HOME": str(home), "HERMES_HOME": str(home / ".hermes"), "PYTHONPATH": str(REPO_ROOT),+ "PYTHONUNBUFFERED": "1", "NO_COLOR": "1", "TERM": "dumb",+ # The child's HOME is tmp_path; this is the state-db guard's documented child escape hatch.+ "HERMES_STATE_DB_GUARD_BYPASS": "1",+ })+ env.update(extra)+ return env+++ def write_home(root: Path, model: dict[str, Any], extra_cfg: dict[str, Any] | None = None) -> Path:+ home = root / "home"+ (home / ".hermes").mkdir(parents=True, exist_ok=True)+ cfg = {"model": {"default": "catalog-model-a", "context_length": 128000, **model},+ # auto_recovery_cycles: 0 — the documented post-exhaustion ladder (15/30/60/60/60 s) would+ # otherwise park a transport-failed turn for minutes; one bounded attempt is the contract here.+ "agent": {"api_max_retries": 1, "auto_recovery_cycles": 0}, "updates": {"check": False},+ **(extra_cfg or {})}+ (home / ".hermes" / "config.yaml").write_text(yaml.safe_dump(cfg, sort_keys=False), encoding="utf-8")++ select_test_dependencies(home / ".hermes", REPO_ROOT)+ return home+++ def run_hermes(home: Path, cwd: Path, env_extra: dict[str, str], *args: str,+ timeout: float = TURN_TIMEOUT) -> subprocess.CompletedProcess:+ """Run the real CLI; a child that outlives ``timeout`` is killed (rc -9, reason in stderr)."""+ with tempfile.TemporaryFile("w+", encoding="utf-8") as out, tempfile.TemporaryFile("w+", encoding="utf-8") as err:+ proc = subprocess.Popen([sys.executable, "-m", "hermes_cli.main", *args], cwd=cwd,+ env=hermetic_env(home, env_extra), stdout=out, stderr=err, text=True,+ stdin=subprocess.DEVNULL)+ try:+ rc, why = proc.wait(timeout=timeout), ""+ except subprocess.TimeoutExpired:+ proc.kill()+ proc.wait()+ rc, why = -9, f"\nTIMEOUT after {timeout}s"+ out.seek(0)+ err.seek(0)+ return subprocess.CompletedProcess(proc.args, rc, out.read(), err.read() + why)+++ def session_usage(home: Path) -> dict[str, Any] | None:+ db = home / ".hermes" / "state.db"+ if not db.exists():+ return None+ con = sqlite3.connect(f"file:{db}?mode=ro", uri=True)+ try:+ con.row_factory = sqlite3.Row+ row = con.execute("SELECT input_tokens, output_tokens, estimated_cost_usd, cost_status "+ "FROM sessions ORDER BY started_at DESC LIMIT 1").fetchone()+ return dict(row) if row else None+ finally:+ con.close()+++ def credential_values(rec: Recorded, secrets: set[str]) -> dict[str, str]:+ """header -> the secret it carries, for every header carrying any known secret."""+ return {h: s for h, v in rec.headers.items() for s in secrets if s in v}+++ @dataclass+ class TurnResult:+ row: Row+ rc: int+ stdout: str+ stderr: str+ requests: list[Recorded]+ egress: list[str]+ own_key: str+ secrets: set[str]+ usage: dict[str, Any] | None+ canary: str+ wall_s: float+ cells: dict[str, bool] = field(default_factory=dict)++ def signature(self) -> str:+ """Observed facts a KNOWN bug's pattern keys on (one line, first in every gated message)."""+ n = sum(1 for r in self.requests if r.method == "POST")+ return f"fake_inference={n} egress={self.egress}"++ def detail(self) -> str:+ reqs = [f"{r.method} {r.path} [{r.dialect}] creds={credential_values(r, self.secrets)}" for r in self.requests]+ return (f"rc={self.rc} wall={self.wall_s}s\n usage={self.usage}\n"+ f" requests={reqs}\n stdout={self.stdout[-600:]!r}\n stderr={self.stderr[-1200:]!r}")+++ def drive_turn(row: Row, root: Path, catalog: list[Row]) -> TurnResult:+ """One oneshot turn with one tool round trip for ``row`` against its own fake."""+ project = root / "project"+ project.mkdir(parents=True, exist_ok=True)+ canary = f"CANARY-{row.name}-{os.urandom(4).hex()}"+ (project / "canary.txt").write_text(canary + "\n", encoding="utf-8")+ keys = decoy_keys(catalog)+ started = time.monotonic()+ with CatalogFake(tool_args={"path": str(project / "canary.txt")}, final_text=FINAL, routes=row.routes()) as fake:+ home = write_home(root, {"provider": row.name, "base_url": fake.origin + row.base_path})+ proc = run_hermes(home, project, {**keys, **fake.proxy_env()}, "-z", "Read canary.txt and report.")+ requests = list(fake.requests)+ egress = fake.egress_hosts()+ return TurnResult(row=row, rc=proc.returncode, stdout=proc.stdout, stderr=proc.stderr, requests=requests,+ egress=egress, own_key=keys[row.key_env or ""], secrets=set(keys.values()),+ usage=session_usage(home), canary=canary, wall_s=round(time.monotonic() - started, 1))+++ def provider_hosts(catalog: list[Row]) -> set[str]:+ """``host:443`` of every provider's canonical HTTPS endpoint (the egress sentinel's CONNECT form)."""+ return {r.vendor_host() for r in catalog} - {""}+++ def evaluate(t: TurnResult, catalog: list[Row]) -> dict[str, bool]:+ """Every invariant of one row. Relationship checks only — never literals of today's output."""+ inference = [r for r in t.requests if r.method == "POST"]+ # A transport mandated by the provider's own host may fall back to chat at a foreign URL.+ expected = {t.row.dialect} | ({"chat"} if t.row.host_mandated else set())+ main = [r for r in inference if isinstance(r.body, dict) and r.body.get("tools")]+ answered = [r for r in main if r.dialect != "unknown"]+ foreign = t.secrets - {t.own_key}+ foreign_hosts = provider_hosts([r for r in catalog if r.name != t.row.name]) - provider_hosts([t.row])+ return {+ "turn_completed": t.rc == 0 and FINAL in t.stdout,+ # The fake answers ONLY the exact configured base path + dialect endpoint (else 404,+ # dialect "unknown"), so a mangled path under the right prefix is red here.+ "reached_own_endpoint": bool(inference) and all(r.dialect != "unknown" for r in inference),+ "dialect_matches_transport": bool(main) and all(r.dialect in expected for r in main),+ "tool_round_trip": any(t.canary in json.dumps(r.body) for r in main),+ "own_key_in_auth_header": bool(inference) and all(+ t.own_key in r.headers.get(AUTH_HEADER_OF_DIALECT.get(r.dialect, "authorization"), "") for r in inference),+ "no_foreign_key_on_wire": not any(s in v for r in t.requests for v in r.headers.values() for s in foreign),+ # Egress sentinel: nothing may leave for ANOTHER provider's host (CONNECT target).+ "no_egress_to_foreign_provider_hosts": not [h for h in t.egress if h in foreign_hosts],+ # The session row charges exactly what the fake reported for every main-turn call it+ # answered (auxiliary title calls are not charged to the session row).+ "usage_matches_wire": bool(answered) and bool(t.usage)+ and t.usage["input_tokens"] == USAGE_IN * len(answered) and t.usage["output_tokens"] == USAGE_OUT * len(answered),+ # Unknown pricing (a model no catalog prices) must be explicit, never a silent $0 estimate.+ # (usage_matches_wire owns absence; this cell judges only a row that exists.)+ "cost_not_silent_zero": not t.usage or not (+ (t.usage.get("estimated_cost_usd") in (0, 0.0)) and t.usage.get("cost_status") not in (None, "unknown")),+ }+++ # --- matrix shards ------------------------------------------------------------------------------++ # Open bugs per provider row: the listed cells may be red ONLY while the gated message carries the+ # bug's own signature; any other red cell fails the row, and a fixed bug simply passes.+ MATRIX_KNOWN: dict[str, Known] = {+ "xai": Known(+ pattern=r"fake_inference=0 egress=\[[^\]]*'api\.x\.ai:443'",+ reason="#121347 xai ignores model.base_url; request + key go to api.x.ai",+ cells=frozenset({"turn_completed", "reached_own_endpoint", "dialect_matches_transport", "tool_round_trip",+ "own_key_in_auth_header", "usage_matches_wire"})),+ }+++ def shard_rows(shard: int) -> list[Row]:+ return [r for r in discover_catalog() if shard_of(r.name) == shard]+++ def shard_params(shard: int) -> list:+ """Every discovered row of the shard; only explicit auth types / keyless names skip."""+ return [pytest.param(r, id=r.name, marks=[pytest.mark.skip(reason=r.skip_reason())] if r.skip_reason() else [])+ for r in shard_rows(shard)]+++ def drive_shard(shard: int, tmp_path_factory: pytest.TempPathFactory) -> dict[str, TurnResult]:+ """Every runnable row of the shard driven concurrently (own home, fake and process each)."""+ catalog = discover_catalog()+ runnable = [r for r in shard_rows(shard) if r.skip_reason() is None and r.dialect]+ roots = {r.name: Path(tmp_path_factory.mktemp(f"cat-{r.name}")) for r in runnable}+ with ThreadPoolExecutor(max_workers=8, thread_name_prefix="catalog") as pool:+ futs = {r.name: pool.submit(drive_turn, r, roots[r.name], catalog) for r in runnable}+ return {name: f.result() for name, f in futs.items()}+++ def check_row(row: Row, turns: dict[str, TurnResult]) -> None:+ assert row.dialect, (f"{row.name}: transport {row.api_mode!r} has no loopback dialect in CatalogFake — "+ f"add it to DIALECT_OF_API_MODE (a provider may not leave the matrix as a skip)")+ t = turns[row.name]+ cells = evaluate(t, discover_catalog())+ failed = sorted(c for c, ok in cells.items() if not ok)+ known = MATRIX_KNOWN.get(row.name)+ unlisted = [c for c in failed if not known or c not in known.cells]+ assert not unlisted, f"{row.name} ({row.api_mode}/{row.auth_type}): cells red: {unlisted}\n{t.signature()}\n{t.detail()}"+ with known_gate(known):+ gate(not failed, f"{t.signature()}\n{row.name}: cells red: {failed}\n{t.detail()}")diff --cc tests/e2e/core/windows/test_state_db_guard.pyindex af762dc633b,e57312deea6..dbe26f84ef1--- a/tests/e2e/core/windows/test_state_db_guard.py+++ b/tests/e2e/core/windows/test_state_db_guard.py@@@ -28,13 -27,8 +27,8 @@@ from tests.e2e.core.windows._helpers im)from tests.fakes.fake_llm_provider import FakeLLMServer-pytestmark = [pytest.mark.windows_only, pytest.mark.integration, pytest.mark.live_system_guard_bypass]+pytestmark = [pytest.mark.platforms("windows"), pytest.mark.integration, pytest.mark.live_system_guard_bypass]- KNOWN: dict[str, str] = {- "foreign_holder": "#120205 foreign_state_db_holders() returns [] on Windows; the write-guard never refuses",- }--def _running(home) -> bool:try:state = json.loads((home.hermes_home / "gateway_state.json").read_text(encoding="utf-8"))diff --cc tests/hermes_cli/test_backup.pyindex 25401dde684,cef3e8eaeab..47c00dc16d1--- a/tests/hermes_cli/test_backup.py+++ b/tests/hermes_cli/test_backup.py@@@ -553,6 -554,161 +554,180 @@@ class TestImportassert (hermes_home / "config.yaml").read_text() == "model: test\n"+ @staticmethod+ def _corrupt_member(zip_path: Path, name: str, damage: str) -> None:+ """Damage *name*'s data in place, leaving ``is_zipfile``/``namelist`` happy.++ ``deflate``: reserved block type 3 (``zlib.error``); ``stored``: one payload byte+ flipped (``Bad CRC-32``); ``bzip2``: block CRC flipped (``OSError`` Invalid data+ stream); ``truncated``: the central directory's compressed size halved, so the+ deflate stream is cut short (``Bad CRC-32``). A real archive cannot make the read hit+ physical EOF (``EOFError``): zipfile refuses overlapping entries first, so that case+ -- media going bad under the archive -- is covered by the rot-after-pre-flight test.+ """+ with zipfile.ZipFile(zip_path) as zf:+ info = zf.getinfo(name)+ data_offset = info.header_offset + 30 + len(info.filename) + len(info.extra)+ raw = bytearray(zip_path.read_bytes())+ if damage == "truncated":+ # Central record = local header fields shifted by 2 ("version made by"); the CRC keeps+ # the match unique. compress_size sits at +20 in the central record.+ local = raw[info.header_offset + 4:info.header_offset + 26]+ entry = raw.index(local, info.header_offset + 26) - 6+ struct.pack_into("<I", raw, entry + 20, info.compress_size // 2)+ elif damage == "deflate":+ raw[data_offset] |= 0b110+ else:+ raw[data_offset + (10 if damage == "bzip2" else 0)] ^= 0xFF+ zip_path.write_bytes(bytes(raw))++ def _home_for_corrupt_import(self, tmp_path, monkeypatch) -> Path:+ hermes_home = tmp_path / ".hermes"+ hermes_home.mkdir()+ (hermes_home / "config.yaml").write_text("model: live\n")+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ return hermes_home++ @pytest.mark.parametrize("damage, compression", [+ ("deflate", zipfile.ZIP_DEFLATED),+ ("stored", zipfile.ZIP_STORED),+ ("bzip2", zipfile.ZIP_BZIP2),+ ("truncated", zipfile.ZIP_DEFLATED),+ ])+ def test_import_refuses_damaged_archive_before_touching_home(+ self, tmp_path, monkeypatch, capsys, damage, compression+ ):+ """#121258: members that fail to decompress, fail their CRC or are cut short must all be+ found BEFORE the first file is replaced -- not surface as a traceback half-way through+ -- listed (capped) in one run, and the command must exit 1 without "restored" wording."""+ hermes_home = self._home_for_corrupt_import(tmp_path, monkeypatch)+ zip_path = tmp_path / "backup.zip"+ names = [f"skills/s{i}/SKILL.md" for i in range(12)]+ with zipfile.ZipFile(zip_path, "w", compression=compression) as zf:+ zf.writestr("config.yaml", "model: restored\n")+ for name in names:+ zf.writestr(name, f"# {name}\n" * 20)+ zf.writestr("sessions/after.json", '{"restored": true}')+ for name in names:+ self._corrupt_member(zip_path, name, damage)+ assert zipfile.is_zipfile(zip_path)++ from hermes_cli.backup import run_import+ from hermes_cli.main import cmd_import++ assert run_import(Namespace(zipfile=str(zip_path), force=True)) == 1+ out = capsys.readouterr().out+ assert "backup archive is damaged (12 member(s)" in out+ assert sum(1 for line in out.splitlines() if line.strip().startswith("skills/s")) == 10+ assert "... and 2 more" in out+ assert "Importing" not in out+ assert "restored" not in out.replace("nothing was restored", "")+ # The home is exactly as it was.+ assert (hermes_home / "config.yaml").read_text() == "model: live\n"+ assert sorted(p.name for p in hermes_home.iterdir()) == ["config.yaml"]+ assert cmd_import(Namespace(zipfile=str(zip_path), force=True)) == 1+++ def test_import_ignores_damaged_pm_runtime_but_keeps_portable_data(++ self, tmp_path, monkeypatch++ ):++ """Machine-local interpreter/dependency state is not a reason to refuse a backup."""++ hermes_home = self._home_for_corrupt_import(tmp_path, monkeypatch)++ zip_path = tmp_path / "backup.zip"++ with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as zf:++ zf.writestr("config.yaml", "model: restored\n")++ zf.writestr("profiles/coder/installs/python.zip", "machine-specific\n" * 20)++ zf.writestr("skills/demo/SKILL.md", "# portable\n")++ self._corrupt_member(zip_path, "profiles/coder/installs/python.zip", "deflate")++++ from hermes_cli.backup import run_import++++ assert run_import(Namespace(zipfile=str(zip_path), force=True)) is None++ assert (hermes_home / "config.yaml").read_text() == "model: restored\n"++ assert (hermes_home / "skills/demo/SKILL.md").read_text() == "# portable\n"++ assert not (hermes_home / "profiles/coder/installs").exists()+++ def test_import_skips_member_that_rots_after_preflight_and_reports_incomplete(+ self, tmp_path, monkeypatch, capsys+ ):+ """A member that passes the integrity pass but fails while being written (media going+ bad under the archive) warns, leaves the damaged target absent, restores the rest and+ exits 1 -- rather than escaping as a traceback. A damaged member the restore skips+ anyway (runtime ``gateway.pid``) does not make the pre-flight refuse the archive."""+ hermes_home = self._home_for_corrupt_import(tmp_path, monkeypatch)+ zip_path = tmp_path / "backup.zip"+ with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as zf:+ zf.writestr("config.yaml", "model: restored\n")+ zf.writestr("damaged.json", '{"will": "fail"}')+ zf.writestr("gateway.pid", "12345\n" * 20)+ zf.writestr("sessions/after.json", '{"restored": true}')+ self._corrupt_member(zip_path, "gateway.pid", "deflate")++ import hermes_cli.backup as backup_mod++ real_extract = backup_mod._extract_member_atomically++ def flaky_extract(zf, member, target, new_file_mode=None):+ if member == "damaged.json":+ raise EOFError("Compressed file ended before the end-of-stream marker was reached")+ return real_extract(zf, member, target, new_file_mode)++ monkeypatch.setattr(backup_mod, "_extract_member_atomically", flaky_extract)++ assert backup_mod.run_import(Namespace(zipfile=str(zip_path), force=True)) == 1++ out = capsys.readouterr().out+ assert "damaged (" not in out+ assert (hermes_home / "config.yaml").read_text() == "model: restored\n"+ assert not (hermes_home / "damaged.json").exists()+ assert not (hermes_home / "gateway.pid").exists()+ assert not list(hermes_home.glob(".damaged.json.*.partial"))+ assert (hermes_home / "sessions" / "after.json").read_text() == '{"restored": true}'+ assert "Warnings (1 files skipped):" in out+ assert "Import incomplete" in out+ assert "has been restored" not in out++ def test_skipped_member_reports_incomplete_and_exits_1(self, tmp_path, monkeypatch, capsys):+ """A member that could not be written is a partial restore: the CLI must not print+ "restored" or exit 0, or a script and the dashboard's "done" badge carry on over it.+ Runtime files the import deliberately keeps are not failures."""+ hermes_home = tmp_path / ".hermes"+ locked = hermes_home / "skills" / "demo"+ locked.mkdir(parents=True)+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))+ monkeypatch.setattr(Path, "home", lambda: tmp_path)++ zip_path = tmp_path / "backup.zip"+ self._make_backup_zip(zip_path, {+ "config.yaml": "model: test\n",+ "gateway.pid": "123\n",+ "skills/demo/SKILL.md": "# demo\n",+ })+ args = Namespace(zipfile=str(zip_path), force=True)++ from hermes_cli.backup import run_import+ from hermes_cli.main import cmd_import++ locked.chmod(0o555)+ try:+ if os.access(locked, os.W_OK):+ pytest.skip("root or Windows: chmod 0555 does not make the directory read-only")+ assert run_import(args) == 1+ out = capsys.readouterr().out+ assert "Import incomplete" in out+ assert "Import complete" not in out+ assert "skills/demo/SKILL.md" in out+ assert "has been restored" not in out+ assert cmd_import(args) == 1+ finally:+ locked.chmod(0o755)++ capsys.readouterr()+ assert cmd_import(args) is None+ out = capsys.readouterr().out+ assert "Preserved 1 runtime state file(s)" in out+ assert "Done. Your Hermes configuration has been restored." in out+@@@ -2318,18 -2488,13 +2498,20 @@@ class TestImportLiveSessionDatabase):"""A refused live-safe restore is a warning, not a counted success."""import hermes_cli.backup as backup_mod+ # _import_db_member (the run_import .db publish path) lives in+ # hermes_cli.backup_restore and resolves _safe_restore_db there.+ import hermes_cli.backup_restore as backup_restore_modhome, live_db, zip_path = self._prepare(tmp_path, monkeypatch)- monkeypatch.setattr(backup_mod, "_safe_restore_db", lambda src, dst: False)+ monkeypatch.setattr(backup_restore_mod, "_safe_restore_db", lambda src, dst: False)- backup_mod.run_import(Namespace(zipfile=str(zip_path), force=True))+ assert backup_mod.run_import(Namespace(zipfile=str(zip_path), force=True)) == 1- assert "has been restored" not in capsys.readouterr().out+ out = capsys.readouterr().out+ assert "files skipped" in out+ assert "state.db" in out++ assert "has been restored" not in out++# The pre-import database is still the one on disk.assert _count_rows(live_db) == (3, 12)diff --cc tests/hermes_cli/test_sessions_set_journal_mode.pyindex 25166737148,f578a9b1e4f..fd95682fe61--- a/tests/hermes_cli/test_sessions_set_journal_mode.py+++ b/tests/hermes_cli/test_sessions_set_journal_mode.py@@@ -53,40 -52,50 +52,50 @@@ def test_set_journal_mode_refuses_while_wal_store(db)monkeypatch.setattr("hermes_state.DEFAULT_DB_PATH", db)holder = subprocess.Popen(- [sys.executable, "-c",- f"import sqlite3, time; c = sqlite3.connect({str(db)!r}); c.execute('SELECT 1'); time.sleep(60)"],- stdin=subprocess.DEVNULL,+ [+ sys.executable, "-c",+ (- "import os,sqlite3,sys,time; "++ "import os,sqlite3,sys; "+ "c=sqlite3.connect(sys.argv[1]); c.execute('SELECT 1'); "- "print(f'held:{os.getpid()}', flush=True); time.sleep(60)"++ "print(f'held:{os.getpid()}', flush=True); sys.stdin.readline()"+ ),+ str(db),+ ],++ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ text=True,)try:- deadline = time.monotonic() + 10- while time.monotonic() < deadline and not (tmp_path / "state.db-shm").exists():- time.sleep(0.05)- assert cmd_sessions(_args("delete", force=False)) == 1+ marker, pid_text = holder.stdout.readline().strip().split(":", 1)+ assert marker == "held"+ sqlite_pid = int(pid_text)+ # --force never waives a process the scan actually found.+ assert cmd_sessions(_args("delete", force=force)) == 1finally:-- holder.kill()-- holder.wait()++ holder.communicate(input="\n", timeout=30)out = capsys.readouterr().out- assert f"pid {holder.pid}" in out+ assert f"pid {sqlite_pid}" in outassert db.read_bytes()[18:20] == b"\x02\x02", "a refused switch must leave the file untouched"+ # A failed scan (pid <= 0 sentinel) is refused too, and is the ONLY thing --force waives.+ monkeypatch.setattr("hermes_state_holders.foreign_state_db_holders", lambda path: [(-1, "scan failed")])+ assert cmd_sessions(_args("delete", force=force)) == (0 if force else 1)+ assert db.read_bytes()[18:20] == (b"\x01\x01" if force else b"\x02\x02")+ assert ("scan: scan failed" in capsys.readouterr().out) is not force- @pytest.mark.parametrize("target,current,platform,cross_vm,force,expected", [- # Windows has no holder scan (foreign_state_db_holders returns []): an empty list must never read- # as "nobody holds it", so the gate refuses instead of issuing a silent all-clear.- ("delete", "wal", "win32", False, False, "no holder scan"),- ("delete", "wal", "win32", False, True, None),- ("delete", "wal", "linux", False, False, None),- # WAL shared memory corrupts on virtiofs/9p, so ENABLING it there is refused, --force or not.- ("wal", "delete", "linux", True, False, "cross-VM filesystems"),- ("wal", "delete", "win32", True, True, "cross-VM filesystems"),- ("delete", "wal", "linux", True, False, None),++ @pytest.mark.parametrize("target,current,cross_vm,expected", [+ ("delete", "wal", False, None),+ # WAL shared memory corrupts on virtiofs/9p, so ENABLING it there is refused.+ ("wal", "delete", True, "cross-VM filesystems"),+ ("delete", "wal", True, None),# A garbage or unrecognised header is reported, never handed to sqlite3 for a raw traceback.- ("delete", "not-a-database", "linux", False, False, "not a Hermes SQLite store"),- ("delete", "unknown(3/3)", "linux", False, True, "not a Hermes SQLite store"),+ ("delete", "not-a-database", False, "not a Hermes SQLite store"),+ ("delete", "unknown(3/3)", False, "not a Hermes SQLite store"),])- def test_refusal_admission_invariants(target, current, platform, cross_vm, force, expected):- reason = _refusal(target, current, platform, on_cross_vm_fs=cross_vm, force=force)+ def test_refusal_admission_invariants(target, current, cross_vm, expected):+ reason = _refusal(target, current, on_cross_vm_fs=cross_vm)if expected is None:assert reason is Noneelse:diff --cc tests/hermes_state/test_state_db_holders.pyindex df85beb901f,fbd7ef07399..eaece06ae17--- a/tests/hermes_state/test_state_db_holders.py+++ b/tests/hermes_state/test_state_db_holders.py@@@ -56,6 -45,58 +56,58 @@@ def test_foreign_holder_uses_device_andmonkeypatch.setattr(hermes_state_holders.os, "stat", _stat)- assert hermes_state_holders.foreign_state_db_holders(db_path) == [- (222, str(alias_path))- ]+ assert hermes_state_holders.foreign_state_db_holders(db_path) == (+ [(222, str(alias_path))] if identity == "alias" else []+ )+++ def test_windows_restart_manager_scan_sizes_then_excludes_self(monkeypatch, tmp_path):+ """The rstrtmgr lane sizes on ERROR_MORE_DATA, drops our own pid, and fails closed."""+ import ctypes++ db_path = tmp_path / "state.db"+ db_path.touch()+ (tmp_path / "state.db-wal").touch()+ calls = []++ class _Fn:+ def __init__(self, impl):+ self.impl = impl++ def __call__(self, *args):+ return self.impl(*args)++ def start(session, _flags, _key):+ session._obj.value = 7+ return 0++ def register(_session, count, names, *_rest):+ calls.append(("register", count, sorted(names)))+ return 0++ def get_list(_session, needed, count, apps, _reasons):+ needed._obj.value = 2+ if apps is None:+ return 234 # ERROR_MORE_DATA: sizing call+ apps[0].process.pid = os.getpid()+ apps[1].process.pid = 4242+ count._obj.value = 2+ return 0++ class _Api:+ RmStartSession = _Fn(start)+ RmRegisterResources = _Fn(register)+ RmGetList = _Fn(get_list)+ RmEndSession = _Fn(lambda _session: calls.append("end") or 0)++ monkeypatch.setattr(ctypes, "WinDLL", lambda *a, **k: _Api(), raising=False)++ holders = hermes_state_holders._windows_restart_manager_holders(db_path)++ assert [pid for pid, _ in holders] == [4242]+ assert calls[0] == ("register", 2, sorted(str(p) for p in (db_path, tmp_path / "state.db-wal")))+ assert calls[-1] == "end"++ _Api.RmStartSession = _Fn(lambda *_args: 5)+ with pytest.raises(OSError):+ hermes_state_holders._windows_restart_manager_holders(db_path)diff --cc tests/hermes_state/test_state_db_holders_windows_live.pyindex 00000000000,b03817c97a8..c0b5dcd0c94mode 000000,100644..100644--- a/tests/hermes_state/test_state_db_holders_windows_live.py+++ b/tests/hermes_state/test_state_db_holders_windows_live.py@@@ -1,0 -1,89 +1,88 @@@+ """Live Windows proof for #120205: structural maintenance sees a real foreign SQLite holder."""++ import sqlite3+ import subprocess+ import sys++ import pytest++ from hermes_state_holders import foreign_state_db_holders, held_store_refusal+-pytestmark = pytest.mark.windows_only++pytestmark = pytest.mark.platforms("windows")+++ def test_restart_manager_finds_real_foreign_state_db_holder(tmp_path):+ db = tmp_path / "state.db"+ conn = sqlite3.connect(db)+ conn.execute("CREATE TABLE t(x)")+ conn.commit()+ conn.close()++ holder = subprocess.Popen(+ [+ sys.executable,+ "-c",+ (+ "import os,sqlite3,sys; "+ "c=sqlite3.connect(sys.argv[1]); "+ "c.execute('SELECT count(*) FROM t').fetchone(); "+ "print(f'held:{os.getpid()}', flush=True); sys.stdin.readline()"+ ),+ str(db),+ ],+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ text=True,+ )+ try:+ marker, pid_text = holder.stdout.readline().strip().split(":", 1)+ assert marker == "held"+ sqlite_pid = int(pid_text)++ holders = foreign_state_db_holders(db)+ assert any(pid == sqlite_pid for pid, _ in holders), holders+ refusal = held_store_refusal(db, command="optimize-storage")+ assert refusal is not None and f"PID {sqlite_pid}" in refusal+ finally:+ holder.stdin.write("\n")+ holder.stdin.flush()+ holder.wait(timeout=30)++ assert foreign_state_db_holders(db) == []++ @pytest.mark.parametrize("suffix", ["-wal", "-shm"])+ def test_restart_manager_finds_foreign_sqlite_sidecar_holder(tmp_path, suffix):+ """A foreign sidecar-only handle is still a holder of this SQLite resource family."""+ db = tmp_path / "state.db"+ db.touch()+ sidecar = tmp_path / f"state.db{suffix}"+ sidecar.write_bytes(b"sidecar sentinel")++ holder = subprocess.Popen(+ [+ sys.executable,+ "-c",+ (+ "import os,sys; "+ "f=open(sys.argv[1], 'rb'); "+ "print(f'held:{os.getpid()}', flush=True); sys.stdin.readline()"+ ),+ str(sidecar),+ ],+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ text=True,+ )+ try:+ marker, pid_text = holder.stdout.readline().strip().split(":", 1)+ assert marker == "held"+ holder_pid = int(pid_text)++ holders = foreign_state_db_holders(db)+ assert any(pid == holder_pid for pid, _ in holders), holders+ finally:+ holder.stdin.write("\n")+ holder.stdin.flush()+ holder.wait(timeout=30)++ assert foreign_state_db_holders(db) == []-