The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(profiles): preserve checkpoint history across rename
NanPan8a2c9edac64e
diff --git a/hermes_cli/profile_identity.py b/hermes_cli/profile_identity.pyindex 5b4c536785f..c53db1b2287 100644--- a/hermes_cli/profile_identity.py+++ b/hermes_cli/profile_identity.py@@ -1,11 +1,11 @@-"""Rekey a renamed profile's session/routing identity (#111926), and purge a deleted profile's.+"""Rekey a renamed profile's durable identity (#111926), and purge a deleted profile's (#112727).``rename_profile`` moves ``profiles/<old>/`` to ``profiles/<new>/`` so row DATA travels with the-directory, but the profile name is also baked into keys and values the move never touches:+directory, but several identities are derived from the old name or absolute path and do not:``agent:<old>:*`` session-key namespaces (routing index + the profile's own ``sessions`` rows),-``sessions.profile_name``, ``gateway_heartbeats.profile`` and ``delivery_obligations``. Left alone,-every inbound event on a chat keyed to the old name logs ``Profile 'old' does not exist`` and-falls back to the global home, and renamed sessions drop out of the Desktop sidebar.+``sessions.profile_name``, ``gateway_heartbeats.profile``, ``delivery_obligations``, and checkpoint+project refs/metadata/ledgers keyed by the absolute workdir path. Left alone, routing resolves to a+profile that no longer exists and profile-local `/rollback` history disappears under the new path.The same identity has to be *purged* when a profile is deleted — the mirror image of the rekey,and ``delete_profile`` calls :func:`purge_profile_identity` for it.@@ -17,6 +17,7 @@ control verb and the delete to the delete-only ``purge-profile-identity`` verb.``_unserve_profile()``: that hook fires for every name leaving the served set, and a rename's oldname leaves it exactly like a deleted one, so identity must survive it for the rekey that follows.With no live multiplexer nothing else holds the store and the durable rewrite is safe here.+Checkpoint project state has no live in-memory owner and is rekeyed locally after the directory move."""from __future__ import annotations@@ -26,18 +27,20 @@ from pathlib import Pathdef migrate_profile_identity(old_name: str, new_name: str) -> bool:- """Retry the session/routing identity migration of a rename that already completed.+ """Retry the durable identity migration of a rename that already completed.``rename_profile`` runs the migration itself; this is the standalone retry behind``hermes profile migrate-identity <old> <new>`` for when that attempt failed. The renamecannot simply be repeated — ``profiles/<old>`` is gone — and the identity to migrate is read- from the DB rows that still name *old*, so only the new profile has to exist here.-- A live multiplexer holds the routing index in memory and therefore stays the owner of the- migration (the CLI delegates to its control verb); with no live multiplexer the durable- rewrite is safe because nothing else holds the store. Idempotent: re-running a completed- migration succeeds with nothing left to rekey. Returns True when the identity was migrated,- False when a live gateway would not do it — the caller reports that as a failure.+ from rows/metadata that still name the old profile or old absolute workdir, so only the new+ profile has to exist here.++ A live multiplexer holds the routing index in memory and therefore stays the owner of that+ portion of the migration (the CLI delegates to its control verb); checkpoint identity and,+ with no live multiplexer, session identity are durable-only and safe to rewrite here.+ Idempotent: re-running a completed migration succeeds with nothing left to rekey. Returns True+ when all applicable identity was migrated, False when any durable migration failed or a live+ gateway would not accept the routing migration."""from hermes_cli.profiles import _canon_valid, _live_default_multiplexer, _unknown_profile_error, get_profile_dirold_canon = _canon_valid(old_name)@@ -158,13 +161,37 @@ def _gateway_accepts_profile_identity_verb(root: Path) -> bool:return False+def _migrate_checkpoint_identity(old_canon: str, new_canon: str) -> bool:+ """Rekey checkpoint projects whose absolute workdirs moved with the profile directory."""+ from hermes_cli.profiles import get_profile_dir+ from tools.checkpoint_profile_migration import migrate_profile_checkpoint_projects++ old_dir = get_profile_dir(old_canon)+ new_dir = get_profile_dir(new_canon)+ result = migrate_profile_checkpoint_projects(old_dir, new_dir)+ if result["migrated"]:+ print(f"✓ Checkpoint identity updated: {result['migrated']} project(s)")+ if not result["errors"]:+ return True+ print(+ "⚠ Profile was renamed, but checkpoint identity migration failed for "+ f"{result['errors']} project(s). Retry with:\n"+ f" hermes profile migrate-identity {old_canon} {new_canon}",+ file=sys.stderr,+ )+ return False++def _migrate_profile_identity(old_canon: str, new_canon: str, live_mux: bool) -> bool:"""Rekey renamed-profile identity without racing a live gateway's in-memory routing index.- Returns True when the identity was migrated — by the gateway's control verb, or by this- process's durable rewrite when no gateway holds the store — and False when a live gateway did- not accept it. Never fatal to the rename, which has already happened by this point.+ Returns True when every applicable identity was migrated. Session/routing identity is handled+ by the gateway's control verb when it owns the live store, otherwise by this process; checkpoint+ project identity is always durable-only. Never fatal to the rename, which has already happened+ by this point."""+ checkpoint_migrated = _migrate_checkpoint_identity(old_canon, new_canon)+if live_mux:from hermes_constants import get_default_hermes_rootroot = get_default_hermes_root()@@ -175,7 +202,7 @@ def _migrate_profile_identity(old_canon: str, new_canon: str, live_mux: bool) ->reason = f"{type(exc).__name__}: {exc}"else:if isinstance(answer, dict) and answer.get("ok") is True:- return True+ return checkpoint_migratedreason = _control_answer_failure(answer)if answer is None and _gateway_accepts_profile_identity_verb(root):reason += (" — the gateway is running but does not implement "@@ -191,7 +218,7 @@ def _migrate_profile_identity(old_canon: str, new_canon: str, live_mux: bool) ->from hermes_state_registry import acquire, release_or_closefrom hermes_constants import get_default_hermes_rootroot = get_default_hermes_root()- migrated = True+ migrated = checkpoint_migratedfor db_path in (root / "state.db", get_profile_dir(new_canon) / "state.db"):if not db_path.exists():continuediff --git a/tests/hermes_cli/test_profile_rename_checkpoints.py b/tests/hermes_cli/test_profile_rename_checkpoints.pynew file mode 100644index 00000000000..a887746fb53--- /dev/null+++ b/tests/hermes_cli/test_profile_rename_checkpoints.py@@ -0,0 +1,72 @@+"""Profile rename must preserve profile-local checkpoint history."""++from pathlib import Path+from unittest.mock import patch++import pytest++from hermes_cli.profiles import create_profile, rename_profile+from hermes_constants import reset_hermes_home_override, set_hermes_home_override+from tools.checkpoint_manager import CheckpointManager+++def profile_env(tmp_path, monkeypatch):+ """Isolate profile paths and the process-level Hermes root."""+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ default_home = tmp_path / ".hermes"+ default_home.mkdir(exist_ok=True)+ monkeypatch.setenv("HERMES_HOME", str(default_home))+ return default_home+++def test_rename_preserves_profile_local_checkpoint_history(profile_env):+ """A moved profile keeps rollback history under the moved workspace path.++ Checkpoint refs, project metadata, and the safe-restore ledger are keyed by the+ absolute workdir path. Renaming ``profiles/old`` to ``profiles/new`` moves the+ checkpoint store itself, but it also changes every profile-local workdir key.+ """+ old_dir = create_profile("oldname", no_alias=True)+ workdir = old_dir / "workspace"+ workdir.mkdir()+ (workdir / "pyproject.toml").write_text("[project]\nname = 'rename-checkpoint'\n", encoding="utf-8")+ tracked = workdir / "note.txt"+ tracked.write_text("before\n", encoding="utf-8")++ token = set_hermes_home_override(old_dir)+ try:+ manager = CheckpointManager(enabled=True, max_snapshots=5)+ assert manager.ensure_checkpoint(str(workdir), "before profile rename") is True+ checkpoint_hash = manager.list_checkpoints(str(workdir))[0]["hash"]+ tracked.write_text("after\n", encoding="utf-8")+ manager.record_agent_write(str(tracked))+ finally:+ reset_hermes_home_override(token)++ with patch("hermes_cli.profiles.check_alias_collision", return_value="skip"), \+ patch("hermes_cli.profiles._live_default_multiplexer", return_value=False):+ new_dir = rename_profile("oldname", "newname")++ new_workdir = new_dir / "workspace"+ new_tracked = new_workdir / "note.txt"+ token = set_hermes_home_override(new_dir)+ try:+ manager = CheckpointManager(enabled=True, max_snapshots=5)+ checkpoints = manager.list_checkpoints(str(new_workdir))+ assert [entry["hash"] for entry in checkpoints] == [checkpoint_hash]++ project_paths = {entry["workdir"] for entry in manager.list_all_checkpoints()}+ assert str(new_workdir.resolve()) in project_paths+ assert str(workdir.resolve()) not in project_paths++ plan = manager.safe_restore_plan(str(new_workdir), checkpoint_hash)+ assert plan["success"] is True+ assert plan["restore"] == ["note.txt"]+ assert plan["skipped"] == []++ restored = manager.restore(str(new_workdir), checkpoint_hash, safe=True)+ assert restored["success"] is True+ assert new_tracked.read_text(encoding="utf-8") == "before\n"+ finally:+ reset_hermes_home_override(token)diff --git a/tools/checkpoint_profile_migration.py b/tools/checkpoint_profile_migration.pynew file mode 100644index 00000000000..107c0e3a183--- /dev/null+++ b/tools/checkpoint_profile_migration.py@@ -0,0 +1,192 @@+"""Rekey profile-local checkpoint projects after a named profile directory moves.++The checkpoint store itself lives under ``HERMES_HOME/checkpoints`` and therefore moves with a+renamed profile. Project identity inside that store is different: refs, metadata and the+agent-write ledger are keyed by a hash of the absolute workdir. A profile rename changes that+absolute path for every project beneath the profile home, so those entries must follow the move.+"""++from __future__ import annotations++import json+import logging+import os+import shutil+from pathlib import Path+from typing import Dict++from tools import checkpoint_manager as cm++logger = logging.getLogger(__name__)+++def _rebase_ledger_paths(ledger: Dict, old_workdir: Path, new_workdir: Path) -> Dict:+ """Move absolute ledger keys under ``old_workdir`` to the corresponding new path."""+ rebased = {}+ for raw_path, entry in ledger.items():+ try:+ relative = Path(raw_path).relative_to(old_workdir)+ except (TypeError, ValueError):+ rebased[raw_path] = entry+ else:+ rebased[str(new_workdir / relative)] = entry+ return rebased+++def _temp_json_path(path: Path) -> Path:+ return path.with_name(f".{path.name}.profile-rename-{os.getpid()}.tmp")+++def _write_json_temp(path: Path, data: Dict) -> Path:+ """Write a same-directory temporary JSON file ready for atomic ``replace``."""+ path.parent.mkdir(parents=True, exist_ok=True)+ tmp = _temp_json_path(path)+ tmp.write_text(json.dumps(data), encoding="utf-8")+ return tmp+++def migrate_profile_checkpoint_projects(old_profile_dir: Path, new_profile_dir: Path) -> Dict[str, int]:+ """Rekey live checkpoint projects whose workdirs moved with a profile rename.++ Only workdirs beneath ``old_profile_dir`` are affected. External workdirs keep the same+ absolute path even though their profile-owned checkpoint store moved, so their hash/ref stays+ valid. Target collisions fail closed rather than merging two checkpoint histories.++ The per-project git index is a rebuildable cache: after the new ref and durable metadata are+ installed, the old index is discarded and the next checkpoint seeds a fresh index from the+ migrated ref. The agent-write ledger is durable behavior state and is rebased to the moved+ absolute file paths so safe restore continues to recognize Hermes-authored writes.+ """+ old_root = cm._normalize_path(str(old_profile_dir))+ new_root = cm._normalize_path(str(new_profile_dir))+ base = new_root / "checkpoints"+ store = cm._store_path(base)+ result = {"scanned": 0, "migrated": 0, "errors": 0}+ if not cm._store_has_head(store):+ return result++ git_available = shutil.which("git") is not None+ for meta in cm._list_projects(store):+ result["scanned"] += 1+ raw_workdir = meta.get("workdir")+ old_hash = meta.get("_hash")+ if not raw_workdir or not old_hash:+ continue+ old_workdir = cm._normalize_path(str(raw_workdir))+ try:+ relative = old_workdir.relative_to(old_root)+ except ValueError:+ continue++ new_workdir = cm._normalize_path(str(new_root / relative))+ # A project that was already absent before the profile rename stays stale/orphaned; the+ # rename should not retarget its retention evidence to a path that was never moved.+ if not new_workdir.is_dir():+ continue+ if not git_available:+ result["errors"] += 1+ logger.warning(+ "Cannot migrate checkpoint project %s after profile rename: git not found",+ old_workdir,+ )+ continue++ new_hash = cm._project_hash(str(new_workdir))+ if new_hash == old_hash: # defensive (cryptographic/path identity coincidence)+ continue++ old_ref, new_ref = cm._ref_name(old_hash), cm._ref_name(new_hash)+ old_meta = cm._project_meta_path(store, old_hash)+ new_meta = cm._project_meta_path(store, new_hash)+ old_ledger = cm._ledger_path(store, old_hash)+ new_ledger = cm._ledger_path(store, new_hash)+ old_index = cm._index_path(store, old_hash)++ old_tip = cm._ref_tip(store, str(new_workdir), old_ref)+ new_tip = cm._ref_tip(store, str(new_workdir), new_ref)+ if new_tip or new_meta.exists() or new_ledger.exists():+ result["errors"] += 1+ logger.warning(+ "Cannot migrate checkpoint project %s -> %s after profile rename: "+ "target identity %s already exists",+ old_workdir,+ new_workdir,+ new_hash,+ )+ continue++ serialized_meta = {key: value for key, value in meta.items() if key != "_hash"}+ serialized_meta["workdir"] = str(new_workdir)+ evidence = cm._volume_evidence(new_workdir)+ if evidence:+ serialized_meta.update(evidence)+ else:+ serialized_meta.pop("workdir_parent_dev", None)+ serialized_meta.pop("workdir_parent_ino", None)++ ledger = cm._read_json_dict(old_ledger) if old_ledger.exists() else None+ rebased_ledger = (+ _rebase_ledger_paths(ledger, old_workdir, new_workdir)+ if ledger is not None+ else None+ )++ meta_tmp = ledger_tmp = None+ new_ref_created = False+ installed_meta = installed_ledger = False+ try:+ meta_tmp = _write_json_temp(new_meta, serialized_meta)+ if rebased_ledger is not None:+ ledger_tmp = _write_json_temp(new_ledger, rebased_ledger)++ if old_tip:+ ok, _, err = cm._run_git(["update-ref", new_ref, old_tip], store, str(new_workdir))+ if not ok:+ raise OSError(f"could not create target checkpoint ref: {err}")+ new_ref_created = True++ meta_tmp.replace(new_meta)+ meta_tmp = None+ installed_meta = True+ if ledger_tmp is not None:+ ledger_tmp.replace(new_ledger)+ ledger_tmp = None+ installed_ledger = True+ except Exception as exc:+ result["errors"] += 1+ logger.warning(+ "Cannot migrate checkpoint project %s -> %s after profile rename: %s",+ old_workdir,+ new_workdir,+ exc,+ )+ if meta_tmp is not None:+ cm._unlink_quiet(meta_tmp)+ if ledger_tmp is not None:+ cm._unlink_quiet(ledger_tmp)+ if installed_meta:+ cm._unlink_quiet(new_meta)+ if installed_ledger:+ cm._unlink_quiet(new_ledger)+ if new_ref_created:+ cm._delete_ref(store, new_ref)+ continue++ # Delete the source ref only after the complete target identity exists. If that destructive+ # step fails, roll the target back and leave the source metadata/ledger/index untouched so+ # the standalone migrate-identity command can retry without merging two histories.+ if old_tip and not cm._delete_ref(store, old_ref):+ result["errors"] += 1+ logger.warning("Could not delete source checkpoint ref %s after creating %s", old_ref, new_ref)+ cm._unlink_quiet(new_meta)+ cm._unlink_quiet(new_ledger)+ if new_ref_created:+ cm._delete_ref(store, new_ref)+ continue++ cm._unlink_quiet(old_meta)+ cm._unlink_quiet(old_ledger)+ cm._unlink_quiet(old_index)+ result["migrated"] += 1++ return result