The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(config,update): replace an unwritable SOUL.md symlink; say when the pre-update snapshot failed
teknium169b63e7407c0
diff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex 524292ad0e9..e44fa5bc430 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -11,7 +11,6 @@ drop_stale_root_modules()import copyimport difflib-import errnoimport jsonimport loggingimport os@@ -25,6 +24,7 @@ import tempfileimport threadingimport timeimport unicodedata+from contextlib import suppressfrom dataclasses import dataclassfrom decimal import Decimal, InvalidOperationfrom pathlib import Path@@ -643,36 +643,6 @@ def _ensure_default_soul_md(home: Path) -> None:"""Seed DEFAULT_SOUL_MD on first run; upgrade a legacy comment-only scaffold in place.A SOUL.md the user actually customized is never touched."""soul_path = home / "SOUL.md"- if soul_path.is_symlink():- try:- soul_path.stat()- except OSError as exc:- # A cyclic link chain is the only failure this branch handles; a dangling link- # (missing target) or an unresolvable mount keeps the existing behaviour below.- if exc.errno == errno.ELOOP:- # ``stat`` refuses a cyclic chain, so the seeding write below would follow the- # link and raise ELOOP — an OSError initialize_home turns into- # HomeInitializationError, leaving the gateway unable to boot (exit-75 relaunch- # loop, #114592). A cyclic link cannot resolve to content: seed the default as a- # regular file IN PLACE OF the link, never through it. A unique temp name keeps- # concurrent boot attempts off one shared path; a failure here leaves the link- # alone instead of killing home initialization.- try:- fd, tmp_name = tempfile.mkstemp(prefix=".SOUL.md.", suffix=".seed", dir=str(home))- except OSError:- return- try:- with os.fdopen(fd, "w", encoding="utf-8") as handle:- handle.write(DEFAULT_SOUL_MD)- os.replace(tmp_name, soul_path)- except OSError:- try:- os.unlink(tmp_name)- except OSError:- pass- return- _secure_file(soul_path)- returnif soul_path.exists():try:existing = soul_path.read_text(encoding="utf-8")@@ -680,7 +650,26 @@ def _ensure_default_soul_md(home: Path) -> None:returnif not is_legacy_template_soul(existing):return- soul_path.write_text(DEFAULT_SOUL_MD, encoding="utf-8")+ try:+ soul_path.write_text(DEFAULT_SOUL_MD, encoding="utf-8")+ except OSError:+ if not soul_path.is_symlink():+ raise+ # A symlink the seed cannot write through — cyclic (``SOUL.md -> SOUL.md``, ELOOP) or+ # dangling into a missing directory (ENOENT) — can never hold an identity file, and the+ # OSError became HomeInitializationError on EVERY boot (launchd exit-75 relaunch storm,+ # #114592). Seed the default IN PLACE OF the link, never through it; mkstemp + replace+ # keeps concurrent gateway boots off one shared path. A working link is never reached+ # here: the write above succeeds through it.+ fd, tmp_name = tempfile.mkstemp(prefix=".SOUL.md.", suffix=".seed", dir=str(home))+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as handle:+ handle.write(DEFAULT_SOUL_MD)+ os.replace(tmp_name, soul_path)+ except OSError:+ with suppress(OSError):+ os.unlink(tmp_name)+ raise_secure_file(soul_path)diff --git a/hermes_cli/update_cmd_maint.py b/hermes_cli/update_cmd_maint.pyindex addfdc36333..8780903cc8a 100644--- a/hermes_cli/update_cmd_maint.py+++ b/hermes_cli/update_cmd_maint.py@@ -778,8 +778,21 @@ def _run_pre_update_backup(args) -> Optional[str]:return Nonesnapshot_id = None- with _best_effort('Pre-update snapshot failed: %s'):+ try:snapshot_id = _run_quick_snapshots()+ except Exception as exc:+ logger.warning("Pre-update snapshot failed: %s", exc)+ snapshot_detail = f" ({exc})"+ else:+ snapshot_detail = ""+ if not snapshot_id:+ # Best-effort by design (8ed599dc054: a broken backup never blocks the update), but a+ # swallowed failure is how a user discovers post-hoc that the receipt says+ # ``ok: false`` and nothing was there to restore (#114592). Say it on stdout, once,+ # before any code moves.+ print(f" ⚠ Pre-update snapshot FAILED — no recovery point was saved{snapshot_detail}.")+ print(" Continuing with update (set updates.pre_update_backup: off to silence this).")+ print()if mode != "full":if snapshot_id:diff --git a/tests/hermes_cli/test_home_init_soul_symlink.py b/tests/hermes_cli/test_home_init_soul_symlink.pyindex f8ec5123032..36412bf498c 100644--- a/tests/hermes_cli/test_home_init_soul_symlink.py+++ b/tests/hermes_cli/test_home_init_soul_symlink.py@@ -1,43 +1,36 @@-"""Regression for #114592: a cyclic SOUL.md symlink must not kill home initialization.+"""Home initialization must survive a SOUL.md symlink the seed cannot write through.-A cyclic SOUL.md link makes ``stat`` fail with ELOOP, so the seeding write followed the-link and raised OSError (errno 40 on Linux, 62 on macOS). ``initialize_home`` turned that-into ``HomeInitializationError``, so every gateway spawn died before boot (exit-75-relaunch storm). The seed now replaces a cyclic link instead of writing through it.--Boundary: only a cyclic chain is replaced — a dangling link or a link that resolves is-left alone, so operator wiring and dangling-link preservation stay out of scope.+A cyclic ``SOUL.md -> SOUL.md`` link (ELOOP) or a link dangling into a missing directory+(ENOENT) made the first-run seed raise OSError, which ``initialize_home`` turned into+``HomeInitializationError`` on every gateway spawn (launchd exit-75 relaunch storm). The seed+now replaces such a link with the default identity file; a link that resolves is operator+wiring and stays a link."""-import os+import pytestfrom hermes_cli.config import DEFAULT_SOUL_MD, _ensure_default_soul_mdfrom hermes_cli.config_home import initialize_home-from hermes_cli.default_soul import _LEGACY_TEMPLATE_SOULS_SUBDIRS = ("cron", "sessions", "logs", "memories")-def _seed_temps(home):- return [p.name for p in home.iterdir() if p.name.startswith(".SOUL.md.")]---def test_initialize_home_survives_self_referential_soul_symlink(tmp_path):- """The reported boot-kill path: a home whose SOUL.md link points at itself."""[email protected]("target", ["SOUL.md", "missing-dir/SOUL.md"], ids=["cyclic", "dangling"])+def test_initialize_home_replaces_unwritable_soul_symlink(tmp_path, target):home = tmp_path / ".hermes"home.mkdir()soul = home / "SOUL.md"- soul.symlink_to(soul)+ soul.symlink_to(home / target)initialize_home(home, _SUBDIRS, set())assert not soul.is_symlink()assert soul.read_text(encoding="utf-8") == DEFAULT_SOUL_MD- assert not _seed_temps(home)+ assert not [p for p in home.iterdir() if p.name.startswith(".SOUL.md.")]def test_soul_symlink_to_customized_file_is_left_alone(tmp_path):- """A resolving link is operator wiring: the link survives, content is untouched."""+ """Control: a resolving link survives and its content is untouched."""home = tmp_path / ".hermes"home.mkdir()target = tmp_path / "shared-identity.md"@@ -50,65 +43,3 @@ def test_soul_symlink_to_customized_file_is_left_alone(tmp_path):assert soul.is_symlink()assert soul.read_text(encoding="utf-8") == "custom identity\n"---def test_soul_symlink_to_legacy_scaffold_keeps_link_and_upgrades_target(tmp_path):- """A resolving link keeps pointing at its target, which is upgraded in place."""- home = tmp_path / ".hermes"- home.mkdir()- target = tmp_path / "shared-scaffold.md"- target.write_text(_LEGACY_TEMPLATE_SOULS[1], encoding="utf-8")- soul = home / "SOUL.md"- soul.symlink_to(target)-- _ensure_default_soul_md(home)-- assert soul.is_symlink()- assert target.read_text(encoding="utf-8") == DEFAULT_SOUL_MD---def test_dangling_soul_symlink_is_not_replaced(tmp_path):- """Boundary: a dangling link is not a cycle — the replacement branch must not touch it."""- home = tmp_path / ".hermes"- home.mkdir()- soul = home / "SOUL.md"- soul.symlink_to(home / "does-not-exist.md")-- _ensure_default_soul_md(home)-- assert soul.is_symlink()---def test_unseedable_cyclic_soul_symlink_still_boots(tmp_path, monkeypatch):- """A home where the seed cannot be committed: initialization must not raise."""- import hermes_cli.config as config_mod-- home = tmp_path / ".hermes"- home.mkdir()- soul = home / "SOUL.md"- soul.symlink_to(soul)-- class _ReadOnlyOS:- def __getattr__(self, name):- return getattr(os, name)-- def replace(self, *args, **kwargs):- raise PermissionError("read-only home")-- monkeypatch.setattr(config_mod, "os", _ReadOnlyOS())-- initialize_home(home, _SUBDIRS, set())-- assert soul.is_symlink()- assert not _seed_temps(home)---def test_missing_soul_md_still_seeds_default(tmp_path):- """Unchanged happy path: first run seeds DEFAULT_SOUL_MD as a regular file."""- home = tmp_path / ".hermes"- home.mkdir()-- initialize_home(home, _SUBDIRS, set())-- assert not (home / "SOUL.md").is_symlink()- assert (home / "SOUL.md").read_text(encoding="utf-8") == DEFAULT_SOUL_MDdiff --git a/tests/hermes_cli/test_state_db_guard.py b/tests/hermes_cli/test_state_db_guard.pyindex 0602b96d7a0..9d8a5d9300d 100644--- a/tests/hermes_cli/test_state_db_guard.py+++ b/tests/hermes_cli/test_state_db_guard.py@@ -142,3 +142,22 @@ class TestPreUpdateBackupIntegrityGuard:assert snap_id is not Noneassert "integrity check FAILED" in outassert "Snapshot copy is valid" in out++ def test_failed_snapshot_is_loud_and_update_continues(self, hermes_home, capsys, monkeypatch):+ """Best-effort by design, but never silent: a snapshot helper that raises (or captures+ nothing) prints a stdout warning and returns None so the receipt records a failed step."""+ from argparse import Namespace++ import hermes_cli.backup as backup_mod+ from hermes_cli.update_cmd import _run_pre_update_backup++ def boom(**kwargs):+ raise PermissionError("state-snapshots is read-only")++ monkeypatch.setattr(backup_mod, "create_quick_snapshot", boom)+ snap_id = _run_pre_update_backup(Namespace(no_backup=False, backup=False))+ out = capsys.readouterr().out+ assert snap_id is None+ assert "Pre-update snapshot FAILED" in out+ assert "state-snapshots is read-only" in out+ assert "Continuing with update" in outdiff --git a/website/docs/getting-started/updating.md b/website/docs/getting-started/updating.mdindex 1205d7c0b2d..57fea5acc05 100644--- a/website/docs/getting-started/updating.md+++ b/website/docs/getting-started/updating.md@@ -34,7 +34,7 @@ This suppresses both cached update notices and passive update-check network requWhen you run `hermes update`, the following steps occur:-1. **Pre-update snapshot** — a lightweight state snapshot is saved by default (covers pairing data, cron jobs, `config.yaml`, `.env`, `auth.json`, and other state files that get modified at runtime; individual files over 1 GiB are skipped so a large sessions DB never slows the update down). Because the code swap and gateway restarts touch every profile, the same snapshot is taken for **every profile** on the install — each into its own `state-snapshots/` directory — and the post-update cron-jobs safety net checks each profile against its own snapshot. Controlled by `updates.pre_update_backup` (`quick` by default, `full` for a zip of all of `HERMES_HOME`, `off` to disable). Recoverable via the snapshot restore flow described under [Snapshots and rollback](../user-guide/checkpoints-and-rollback.md). Quick snapshots are file-loss recovery, not code-rollback insurance — for a coherent point-in-time rollback use `--backup` (full mode).+1. **Pre-update snapshot** — a lightweight state snapshot is saved by default (covers pairing data, cron jobs, `config.yaml`, `.env`, `auth.json`, and other state files that get modified at runtime; individual files over 1 GiB are skipped so a large sessions DB never slows the update down). Because the code swap and gateway restarts touch every profile, the same snapshot is taken for **every profile** on the install — each into its own `state-snapshots/` directory — and the post-update cron-jobs safety net checks each profile against its own snapshot. Controlled by `updates.pre_update_backup` (`quick` by default, `full` for a zip of all of `HERMES_HOME`, `off` to disable). Recoverable via the snapshot restore flow described under [Snapshots and rollback](../user-guide/checkpoints-and-rollback.md). Quick snapshots are file-loss recovery, not code-rollback insurance — for a coherent point-in-time rollback use `--backup` (full mode). The snapshot is best-effort: if it fails, the update prints a `⚠ Pre-update snapshot FAILED` warning and continues, and the receipt records `pre_update_backup` as a failed step (a deliberate `off`/`--no-backup` lands in the receipt's skips with its reason instead).2. **Git pull** — pulls the latest code from the `main` branch and updates submodules3. **Post-pull syntax validation + auto-rollback** — after the pull, Hermes compiles the nine critical files every `hermes` invocation imports at startup. If any fails to parse (e.g. an orphan merge-conflict marker, an accidentally truncated file), Hermes runs `git reset --hard <pre-pull-sha>` to roll the install back so your shell stays bootable. Re-run `hermes update` once the upstream fix lands.After this point the updater re-executes itself on the freshly pulled code (`update.log` shows `=== hermes update continued on the pulled code ===`), so the remaining steps never mix old and new modules in one process. If you see two `hermes update` processes for a moment, that is the hand-off.