The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: preflight all restore destinations and preserve import warning parity
Tekniumf1b4f6e33bad
diff --git a/gateway/runtime_ownership.py b/gateway/runtime_ownership.pyindex 58b7ae387ca..ac1103977eb 100644--- a/gateway/runtime_ownership.py+++ b/gateway/runtime_ownership.py@@ -111,7 +111,7 @@ def exclusive_maintenance(homes):"""state = getattr(_maintenance, 'state', None)outermost = state is None or state[0] != os.getpid()- owner = ProfileOwnership() if outermost else state[1]+ owner = state[1] if state is not None and not outermost else ProfileOwnership()previous = set(owner.homes)try:owner.reserve(homes)diff --git a/hermes_cli/backup.py b/hermes_cli/backup.pyindex 6904d0749b0..176d7297c08 100644--- a/hermes_cli/backup.py+++ b/hermes_cli/backup.py@@ -909,7 +909,7 @@ 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]]]]:"""Reserve all affected profiles before publishing even the first config file."""- from gateway.runtime_ownership import OwnershipConflict, exclusive_maintenance+ from gateway.runtime_ownership import exclusive_maintenancehomes = {hermes_root}for member in members:rel = member[len(prefix):] if prefix and member.startswith(prefix) else member@@ -918,11 +918,11 @@ def _import_members(home = hermes_root / parts[0] / parts[1]if _is_within(home, hermes_root.resolve()):homes.add(home)- try:- with exclusive_maintenance(homes):- return _import_members_exclusive(zf, members, prefix, hermes_root, file_count)- except OwnershipConflict as exc:- return 0, 0, [str(exc)], [], []+ target = hermes_root / rel+ if target.suffix == '.db' and _is_within(target, hermes_root.resolve()):+ homes.update([target.absolute().parent, target.resolve().parent])+ with exclusive_maintenance(homes):+ return _import_members_exclusive(zf, members, prefix, hermes_root, file_count)def _import_members_exclusive(@@ -1026,10 +1026,12 @@ def run_import(args) -> None: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)- if not restored and errors:- _print_capped("\nImport refused or failed; no files restored:", errors, " ")+ from gateway.runtime_ownership import OwnershipConflict+ try:+ restored, restored_external, errors, skipped_runtime, db_shrunk = _import_members(+ zf, members, prefix, hermes_root, file_count)+ except OwnershipConflict as exc:+ print(f"\nImport refused; no files restored: {exc}")sys.exit(1)elapsed = time.monotonic() - t0print(f"\nImport complete: {restored} files restored in {elapsed:.1f}s\n Target: {display_hermes_home()}")@@ -1342,29 +1344,36 @@ def _restore_quick_snapshot_exclusive(snapshot_id: str, home: Path) -> bool:with open(manifest_path, encoding="utf-8") as f:meta = json.load(f)snap_res, home_res = snap_dir.resolve(), home.resolve()- restored = 0+ from gateway.runtime_ownership import exclusive_maintenance+ homes = {home}for rel in meta.get("files", {}):- src = snap_dir / reldst = home / rel- if not (_is_within(src, snap_res) and _is_within(dst, home_res)):- logger.error("Manifest path traversal blocked: %s", rel)- continue- if not src.exists():- continue- dst.parent.mkdir(parents=True, exist_ok=True)- try:- if dst.suffix == ".db":- # Through the backup API so live connections see the restored data instead of- # stale pages from a replaced inode (#65942).- if not _safe_restore_db(src, dst):- # Refused (live holder) or failed: destination untouched — a failure, not a restore.- logger.error("Failed to restore %s: live-safe restore refused", rel)- continue- else:- shutil.copy2(src, dst)- restored += 1- except (OSError, PermissionError) as exc:- logger.error("Failed to restore %s: %s", rel, exc)+ if dst.suffix == '.db' and _is_within(dst, home_res):+ homes.update([dst.absolute().parent, dst.resolve().parent])+ with exclusive_maintenance(homes):+ restored = 0+ for rel in meta.get("files", {}):+ src = snap_dir / rel+ dst = home / rel+ if not (_is_within(src, snap_res) and _is_within(dst, home_res)):+ logger.error("Manifest path traversal blocked: %s", rel)+ continue+ if not src.exists():+ continue+ dst.parent.mkdir(parents=True, exist_ok=True)+ try:+ if dst.suffix == ".db":+ # Through the backup API so live connections see the restored data instead of+ # stale pages from a replaced inode (#65942).+ if not _safe_restore_db(src, dst):+ # Refused (live holder) or failed: destination untouched — a failure, not a restore.+ logger.error("Failed to restore %s: live-safe restore refused", rel)+ continue+ else:+ shutil.copy2(src, dst)+ restored += 1+ except (OSError, PermissionError) as exc:+ logger.error("Failed to restore %s: %s", rel, exc)logger.info("Restored %d files from snapshot %s", restored, snapshot_id)return restored > 0diff --git a/tests/hermes_cli/test_runtime_maintenance_exclusion.py b/tests/hermes_cli/test_runtime_maintenance_exclusion.pyindex dea99cb9283..3b067eeba61 100644--- a/tests/hermes_cli/test_runtime_maintenance_exclusion.py+++ b/tests/hermes_cli/test_runtime_maintenance_exclusion.py@@ -52,15 +52,17 @@ def test_restore_refuses_live_authority_without_changing_data(tmp_path):await rpc(ws, 'prompt.submit', session_id=session, input_id='queued', text='FOLLOWER')before = rows()assert dict(before) == {'warm': 'terminal', 'started': 'started', 'queued': 'queued'}+ import hashlib+ bundle = [Path(str(home / 'state.db') + suffix) for suffix in ('', '-wal', '-shm')]+ hashes = {str(p): hashlib.sha256(p.read_bytes()).hexdigest() for p in bundle if p.exists()}restored = restore_quick_snapshot(snapshot, hermes_home=home)+ assert hashes == {str(p): hashlib.sha256(p.read_bytes()).hexdigest() for p in bundle if p.exists()}after = rows()print(json.dumps({'live_restore': restored, 'before': before, 'after': after}), flush=True)assert not restored and after == before# The real daemon still holds the source DB. Separate-output salvage# must not require stopping it or installing recovered runtime work.- import hashlibfrom hermes_cli.session_recovery import recover_session_database- bundle = [Path(str(home / 'state.db') + suffix) for suffix in ('', '-wal', '-shm')]hashes = {str(p): hashlib.sha256(p.read_bytes()).hexdigest() for p in bundle if p.exists()}report = recover_session_database(home / 'state.db', tmp_path / 'salvaged.db')assert report['verified'] and report['source_unchanged'], report@@ -87,6 +89,8 @@ def test_restore_refuses_live_authority_without_changing_data(tmp_path):assert restore_quick_snapshot(snapshot, hermes_home=home)with daemon(root, home, env, barrier=False) as (_, restored_again):assert restored_again['authority_epoch'] > later_epoch+ print(json.dumps({'offline_restore_restart_epochs': [old_epoch, later_epoch, restored_again['authority_epoch']],+ 'restart_instance_changed': restored_again['instance_id'] != restarted['instance_id']}), flush=True)finally:peer.release.set()peer.shutdown()@@ -146,10 +150,11 @@ def test_import_and_startup_exclude_each_other_before_publication(tmp_path, monkowner.reserve([home])try:before = (home / 'config.yaml').read_bytes(), (home / 'state.db').read_bytes()- restore()- assert results[-1][0] == 0 and 'maintenance refused' in results[-1][2][0]- assert before == ((home / 'config.yaml').read_bytes(), (home / 'state.db').read_bytes())import pytest+ from gateway.runtime_ownership import OwnershipConflict+ with pytest.raises(OwnershipConflict, match='maintenance refused'):+ restore()+ assert before == ((home / 'config.yaml').read_bytes(), (home / 'state.db').read_bytes())from argparse import Namespacemonkeypatch.setenv('HERMES_HOME', str(home))def forbidden_revival(*args):