Files
hermes-agent/hermes_cli/profiles_initialization.py
kshitijk4poor 427b87092c fix(profiles): import and rename publish a name like create, so a racing publish wins cleanly
A name published by another create, import or rename between the exists
check and the move:
- import: shutil.move moved the archive INTO the winner
  (profiles/racer/racer/...) and reported success;
- rename: os.rename raised a raw OSError [Errno 39] Directory not empty.

Both now publish through publish_staging, as create does, and the loser gets
the usual "already exists". Import extracts into a clone_staging_dir sibling
(same filesystem, so the publish is one rename) under _create_lock, so an
in-process create and import of one name no longer share and remove each
other's .<name>.staging-<pid> dir. publish_staging renames through
Path.rename, which is the same call, so the existing interrupt-after-move
seam in the rename tests still applies.

From BearHuddleston's review of #158223 (findings 3 and 4).

Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
2026-11-22 15:50:12 +05:30

110 lines
5.5 KiB
Python

"""Initial profile files, written on the staging tree before publication."""
import contextlib
import errno
import os
import shutil
from pathlib import Path
from typing import Callable, Optional
def clone_staging_dir(profile_dir: Path) -> Path:
"""Fresh ``profiles/.<name>.staging-<pid>`` beside the final dir (same filesystem, so the publish
rename is atomic). A leftover from a crashed create is discarded."""
staging = profile_dir.parent / f".{profile_dir.name}.staging-{os.getpid()}"
profile_dir.parent.mkdir(parents=True, exist_ok=True)
if staging.is_symlink() or staging.is_file():
staging.unlink()
elif staging.is_dir():
shutil.rmtree(staging, ignore_errors=True)
return staging
def publish_staging(staging: Path, profile_dir: Path, exists_error: Callable[[], Exception]) -> None:
"""Rename ``staging`` onto ``profile_dir`` (create, import and rename publish a name this way). A
create, import or rename that also passed the exists check and published first leaves a non-empty
destination: the loser raises ``exists_error()`` (the usual "already exists"), not a raw ENOTEMPTY
(Windows: FileExistsError, or PermissionError while the destination exists). Any other failure stays
raw; what happens to ``staging`` then is the caller's."""
try:
staging.rename(profile_dir)
except OSError as exc:
from hermes_platform.host.facts import os_family
lost = isinstance(exc, FileExistsError) or exc.errno in (errno.ENOTEMPTY, errno.EEXIST) or (
isinstance(exc, PermissionError) and os_family() == "win32" and os.path.exists(profile_dir))
if not lost:
raise
raise exists_error() from exc
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 prepare_imported_tree(staged: Path) -> None:
"""Make an extracted ``hermes profile import`` tree safe to publish; runs on the staging tree."""
from hermes_cli.config_backend import drop_other_access
from hermes_cli.home_data_layout import PM_RUNTIME_ROOT_DIRS
# Remove foreign runtime state before publishing, including file-shaped roots.
# A failed removal must abort import rather than install a stale PM selection.
for child in staged.iterdir():
if child.name in PM_RUNTIME_ROOT_DIRS:
if child.is_dir():
shutil.rmtree(child)
else:
child.unlink()
# Extraction applied each archive member's mode: drop world access on config.yaml and make
# .env owner-only, as a clone and `hermes import` do (#59726).
drop_other_access(staged / "config.yaml")
env = staged / ".env"
if env.is_file() and not env.is_symlink():
os.chmod(env, 0o600)
def finish_profile_layout(profile_dir: Path, *, no_skills: bool, clone_all: bool,
description: Optional[str], soul: Optional[str] = None) -> None:
"""Seed files a fresh profile owns from day one; runs on the staging tree before publish."""
from hermes_cli.profiles import (
_seed_file_if_missing, _PLACEHOLDER_ENV, NO_BUNDLED_SKILLS_MARKER,
_migrate_profile_config_if_outdated, write_profile_meta,
)
if soul is not None:
(profile_dir / "SOUL.md").write_text(soul, encoding="utf-8")
# Seed an empty .env so the profile owns a credentials file from day one. Without it,
# profile-scoped env writes (dashboard Channels/Keys pages, `hermes -p <name> auth add`)
# had no file until first write and the profile silently inherited shell API keys —
# read by users as "the new profile reads the root .env". Skipped when a clone copied one.
_seed_file_if_missing(profile_dir / ".env", _PLACEHOLDER_ENV, 0o600)
# A clone's copy2/copytree carries the source config.yaml's mode, world bits included.
from hermes_cli.config_backend import drop_other_access
drop_other_access(profile_dir / "config.yaml")
# Default SOUL.md to customize immediately (skipped when a clone already provided one).
with contextlib.suppress(Exception): # best-effort — don't fail profile creation over this
from hermes_cli.default_soul import DEFAULT_SOUL_MD
_seed_file_if_missing(profile_dir / "SOUL.md", DEFAULT_SOUL_MD)
# Opt-out marker read by seed_profile_skills() and `hermes update`'s all-profile sync
# (the feature still works via the empty skills/ dir if this fails).
if no_skills:
_seed_file_if_missing(
profile_dir / NO_BUNDLED_SKILLS_MARKER,
"This profile opted out of bundled-skill seeding (`hermes profile create --no-skills`).\n"
"Delete this file to re-enable sync on the next `hermes update`.\n",
)
# Migrate config-only clones now so desktop/status don't warn that a just-created
# profile is v0/outdated; --clone-all snapshots stay byte-for-byte apart from the
# explicit runtime/history stripping above.
if not clone_all:
_migrate_profile_config_if_outdated(profile_dir)
# Description last, so a partial-create failure doesn't strand a description file.
if description and description.strip():
with contextlib.suppress(Exception): # non-fatal — `hermes profile describe` works later
write_profile_meta(profile_dir, description=description.strip(), description_auto=False)