The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(vault): a failed clone rolls back only the keychain entry it made
Tekniumd778246c8448
diff --git a/agent/vault_store.py b/agent/vault_store.pyindex b4cd4c03494..dc981d48a21 100644--- a/agent/vault_store.py+++ b/agent/vault_store.py@@ -337,38 +337,34 @@ class VaultStore:# reads would prefer over a working keychain entry. Callers hold the vault lock.atomic_write_bytes(self._key_path, key, mode=0o600, fsync_dir=True)- def own_copied_key(self, published_base: Path) -> None:+ def own_copied_key(self, published_base: Path) -> Optional[dict]:"""A ``--clone-all`` copy carries the source's ``vault.keyref``, which names the SOURCE's entry;the source moving its key to a file deletes that entry. Before the clone is published at``published_base``, give it an entry of its own, so it never depends on another profile.- Raises VaultError when the keychain cannot be read or written: the clone must not be published- sharing the source's entry."""+ Returns the new entry's ref (the caller deletes exactly that entry if publication fails), or+ None when nothing was shared. Raises VaultError when the keychain cannot be read or written:+ the clone must not be published sharing the source's entry."""from agent import vault_keychain as kcref = kc.read_ref(self._keyref_path)if ref is None or self._key_path.exists():- return # key file layout (a vault.key always wins on read): nothing is shared+ return None # key file layout (a vault.key always wins on read): nothing is sharedtry:key = kc.load_key(ref)if not self._decrypts(key):- return # the source's own entry is already gone: the copy is no worse off than it+ return None # the source's own entry is already gone: the copy is no worse off than itmine = kc.new_ref(published_base)kc.store_key(mine, key)except kc.KeychainUnavailable as exc:raise VaultError(f"its key is in the OS keychain, which this session cannot use ({exc}). Clone from a session ""that can reach the keychain, or run `hermes vault key migrate --to file` on the source first.") from exc- kc.save_new_ref(self._keyref_path, mine)-- def discard_copied_key(self, source_base: Path) -> None:- """Undo :meth:`own_copied_key` for a clone that was never published: delete the entry this copy- was given, never one the source's pointer names. Never raises (it runs while unwinding)."""- from agent import vault_keychain as kc-- with suppress(VaultError):- mine, theirs = kc.read_ref(self._keyref_path), kc.read_ref(Path(source_base) / "vault.keyref")- if mine is not None and mine["account"] != (theirs or {}).get("account"):- kc.delete_key(mine)+ try:+ kc.write_ref(self._keyref_path, mine)+ except OSError:+ kc.delete_key(mine) # the staged clone is discarded with this error, a landed pointer included+ raise+ return minedef _adopt(self, ref: dict) -> dict:"""Give a moved vault (profile rename, or a clone made before clones got their own entry atdiff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.pyindex f3cdc359f0a..822b9a3de54 100644--- a/hermes_cli/profiles.py+++ b/hermes_cli/profiles.py@@ -1263,7 +1263,7 @@ def _copytree_keep_junctions(src: Path, dst: Path, ignore, dirs_exist_ok: bool =logger.warning("clone: skipped junction %s -> %s (%s)", link, target, exc)-def _clone_all_into(source_dir: Path, profile_dir: Path, canon: str) -> None:+def _clone_all_into(source_dir: Path, profile_dir: Path, canon: str) -> Optional[dict]:"""--clone-all: full copytree minus infrastructure/history, then strip runtime filesand cloned single-use OAuth grants."""_copytree_keep_junctions(source_dir, profile_dir, _clone_all_copytree_ignore(source_dir))@@ -1289,7 +1289,7 @@ def _clone_all_into(source_dir: Path, profile_dir: Path, canon: str) -> None:)from agent.vault_store import VaultError, VaultStoretry: # a keychain-mode vault's copied pointer names the source's entry: the clone gets its own- VaultStore(profile_dir / "vault").own_copied_key(get_profile_dir(canon) / "vault")+ return VaultStore(profile_dir / "vault").own_copied_key(get_profile_dir(canon) / "vault")except VaultError as exc:raise ValueError(f"Cannot copy the vault from {source_dir}: {exc}") from exc@@ -1446,9 +1446,10 @@ def create_profile(# below has not removed yet.from hermes_cli.profiles_initialization import clone_staging_dir, discard_unpublished_vault_key, finish_profile_layoutstaging = clone_staging_dir(profile_dir)+ clone_key = None # the keychain entry made for this clone's vault, if anytry:if clone_all and source_dir:- _clone_all_into(source_dir, staging, canon)+ clone_key = _clone_all_into(source_dir, staging, canon)else:_bootstrap_profile_dir(staging, source_dir, sync_imports=sync_imports)if source_dir is not None and not clone_channels:@@ -1459,7 +1460,7 @@ def create_profile(finish_profile_layout(staging, no_skills=no_skills, clone_all=clone_all, description=description, soul=soul)os.rename(staging, profile_dir)except BaseException:- discard_unpublished_vault_key(staging, source_dir if clone_all else None)+ discard_unpublished_vault_key(clone_key)shutil.rmtree(staging, ignore_errors=True)raisediff --git a/hermes_cli/profiles_initialization.py b/hermes_cli/profiles_initialization.pyindex 624c6aa84ba..5e109bc0460 100644--- a/hermes_cli/profiles_initialization.py+++ b/hermes_cli/profiles_initialization.py@@ -18,11 +18,12 @@ def clone_staging_dir(profile_dir: Path) -> Path:return staging-def discard_unpublished_vault_key(staging: Path, source_dir: Optional[Path]) -> None:- """A create that fails after a --clone-all copy got its own keychain entry must not leave it behind."""- if source_dir is not None and (staging / "vault").is_dir():- from agent.vault_store import VaultStore- VaultStore(staging / "vault").discard_copied_key(source_dir / "vault")+def discard_unpublished_vault_key(ref: Optional[dict]) -> None:+ """A create that fails after a --clone-all copy got its own keychain entry (``ref``, returned by+ ``VaultStore.own_copied_key``) deletes exactly that entry; never one inferred from the source."""+ if ref is not None:+ from agent.vault_keychain import delete_key+ delete_key(ref)def finish_profile_layout(profile_dir: Path, *, no_skills: bool, clone_all: bool,diff --git a/tests/agent/test_vault_key_storage.py b/tests/agent/test_vault_key_storage.pyindex 8abab17da6c..40981190ea4 100644--- a/tests/agent/test_vault_key_storage.py+++ b/tests/agent/test_vault_key_storage.py@@ -250,6 +250,29 @@ def test_a_clone_that_fails_to_publish_leaves_no_keychain_entry_behind(home, keyassert VaultStore(source / "vault").resolve_secret(item)["password"] == _LOGIN["password"]+def test_a_clone_failing_before_custody_never_deletes_the_source_entry(home, keychain, tmp_path, monkeypatch):+ """Rollback deletes only the entry made for this clone, never one inferred from the source's files+ (here the source vault moves away mid-clone, and the copy still names the source's entry)."""+ from hermes_cli import auth+ from hermes_cli.profiles import create_profile++ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ source = home(".hermes", key_storage="keychain")+ item = _add(VaultStore())+ moved = tmp_path / "moved-vault"++ def fail_mid_copy(profile_dir):+ (source / "vault").rename(moved)+ raise RuntimeError("dummy failure while the copy still names the source's entry")++ monkeypatch.setattr(auth, "strip_cloned_single_use_oauth_grants", fail_mid_copy)+ with pytest.raises(RuntimeError):+ create_profile("vault-clone", clone_from="default", clone_all=True, no_alias=True)+ assert len(keychain.entries) == 1+ assert VaultStore(moved).resolve_secret(item)["password"] == _LOGIN["password"]++def test_migration_whose_pointer_cannot_be_saved_leaves_no_untracked_entry(home, keychain, monkeypatch):from agent import vault_keychain