The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(config): legacy AGENT_BROWSER_* settings survive homes that skip the v52 step
Tekniumc22530827589
diff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex 753503c6499..18d348a668f 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -608,7 +608,7 @@ from hermes_cli.personality import (# because callers and tests import these from hermes_cli.config)from hermes_cli.config_version_stamp import (- check_config_version, note_first_stamp, read_config_version_stamp)+ check_config_version, note_first_stamp, read_config_version_stamp, stamp_missing_config)# ---- Config Migration System ----@@ -1290,8 +1290,8 @@ def migrate_config(interactive: bool = True, quiet: bool = False) -> dict[str, A"""Migrate config to latest version, prompting for new required fields."""results = {"env_added": [], "config_added": [], "warnings": []}- # Validate config.yaml before any migration side effect: sanitize_env_file() rewrites .env,- # which must not happen when the migration will be refused for malformed YAML.+ stamp_missing_config() # a missing config.yaml reads as current below: stamp its legacy browser settings+ # Validate before any side effect: sanitize_env_file() rewrites .env, never for refused (malformed) YAML.stamp, latest_ver = read_config_version_stamp(raise_on_parse_error=True)current_ver = 0 if stamp is None else stampdiff --git a/hermes_cli/config_migrations_browser.py b/hermes_cli/config_migrations_browser.pyindex 66cfcc3e675..25a00dea164 100644--- a/hermes_cli/config_migrations_browser.py+++ b/hermes_cli/config_migrations_browser.py@@ -98,6 +98,54 @@ def _backend_removed_note(backend: Any) -> str:return f"removed browser.backend: {value} — {reason}"+def move_agent_browser_env(home, browser: dict) -> tuple[list[str], list[str]]:+ """Move *home*'s AGENT_BROWSER_* settings into *browser* (its raw ``browser:`` section), never over a+ value that already won over them (:func:`_config_decided`). Returns the ``NAME → browser.key`` moves and+ the notes for a relative profile pinned to an absolute directory, which the user must read."""+ moved, pinned = [], []+ for name, value in _agent_browser_env(home).items():+ key = dict(_AGENT_BROWSER_ENV_KEYS)[name]+ if _config_decided(key, browser.get(key)):+ continue+ new = _browser_value_from_env(key, value)+ if new is None:+ continue+ browser[key] = new+ moved.append(f"{name} → browser.{key}")+ if key == "user_data_dir" and new != value:+ # Resolved against this process's cwd, which need not be where Hermes ran before.+ pinned.append(f"pinned browser.user_data_dir to {new}: {name}={value} was relative to the directory "+ f"Hermes ran in; check that the browser logins are there")+ return moved, pinned+++def agent_browser_env_pending() -> bool:+ """The active home's config.yaml would still take AGENT_BROWSER_* settings from its .env (the v52 move)."""+ from pathlib import Path++ from hermes_cli.config import read_raw_config+ from hermes_constants import get_hermes_home++ config = read_raw_config()+ browser = config.get("browser") if isinstance(config.get("browser"), dict) else {}+ return bool(move_agent_browser_env(Path(get_hermes_home()), dict(browser))[0])+++def adopt_agent_browser_env(home, config: dict) -> list[str]:+ """*config* is about to give *home* its first ``_config_version`` outside a config step, so the v52 step+ will never move this home's AGENT_BROWSER_* settings: move them into *config* now. Once only, because+ every later write carries the stamp. Returns the moves; a pinned profile becomes a startup notice."""+ browser = config.get("browser") if isinstance(config.get("browser"), dict) else {}+ moved, pinned = move_agent_browser_env(home, browser)+ if moved:+ config["browser"] = browser+ if pinned:+ from hermes_cli.left_core_migration import defer_startup_notice+ for note in pinned:+ defer_startup_notice(f"{note[0].upper()}{note[1:]}.")+ return moved++def migrate_to_52(results: dict[str, Any], quiet: bool) -> None:# 51 -> 52: agent-browser and the built-in browser_* tools left Hermes; browser_exec is the only# browser. `browser.backend` chose between the two, so it is dropped (an `off`, the opt-out of@@ -132,22 +180,11 @@ def migrate_to_52(results: dict[str, Any], quiet: bool) -> None:if "extension_control" in browser:browser.pop("extension_control")added.append("removed browser.extension_control")- moved = []- for name, value in _agent_browser_env(Path(get_hermes_home())).items():- key = dict(_AGENT_BROWSER_ENV_KEYS)[name]- if _config_decided(key, browser.get(key)):- continue- new = _browser_value_from_env(key, value)- if new is not None:- browser[key] = new- moved.append(f"{name} → browser.{key}")- if key == "user_data_dir" and new != value:- # Resolved against this process's cwd, which need not be where Hermes ran before.- note = (f"pinned browser.user_data_dir to {new}: {name}={value} was relative to the directory "- f"Hermes ran in; check that the browser logins are there")- added.append(note)- messages.append(f" ✓ {note[0].upper()}{note[1:]}.")- notices.append(f"{note[0].upper()}{note[1:]}.")+ moved, pinned = move_agent_browser_env(Path(get_hermes_home()), browser)+ for note in pinned:+ added.append(note)+ messages.append(f" ✓ {note[0].upper()}{note[1:]}.")+ notices.append(f"{note[0].upper()}{note[1:]}.")if moved:added.append(f"browser: {', '.join(moved)}")messages.append(f" ✓ Moved agent-browser settings from .env to config.yaml: {', '.join(moved)}")diff --git a/hermes_cli/config_version_stamp.py b/hermes_cli/config_version_stamp.pyindex 46e9b569e4c..ab125e6d0a5 100644--- a/hermes_cli/config_version_stamp.py+++ b/hermes_cli/config_version_stamp.py@@ -75,16 +75,38 @@ def check_config_version(*, raise_on_parse_error: bool = False) -> tuple[int, inreturn (0 if stamp is None else stamp), latest-def note_first_stamp(home, on_disk: dict, to_write: dict) -> None:+def note_first_stamp(home, on_disk: dict, to_write: dict) -> list[str]:"""``save_config`` is about to give *home*'s config.yaml (*on_disk*: missing or never stamped) its first- ``_config_version`` outside a migration, so the steps up to that version never see this home. Record- the left-core rows they would have found in use (``left_core_migration.record_core_use``) into- *to_write*, or the stamp would make a home that ran the core feature look newer than the split."""+ ``_config_version`` outside a migration, so the steps up to that version never see this home. Do into+ *to_write* what they would have done with the home's pre-split files: record the left-core rows in use+ (``left_core_migration.record_core_use``), or the stamp would make a home that ran the core feature look+ newer than the split, and move its AGENT_BROWSER_* settings (``config_migrations_browser``), which+ nothing reads any more. Returns those browser moves."""if "_config_version" in on_disk or "_config_version" not in to_write:- return+ return []from agent.safe_worker_policy import worker_config_snapshotif worker_config_snapshot() is not None:- return # a frozen worker never reads the profile's files; its owner migrates the home+ return [] # a frozen worker never reads the profile's files; its owner migrates the home+ from hermes_cli.config_migrations_browser import adopt_agent_browser_envfrom hermes_cli.left_core_migration import LEFT_CORE, record_core_usefor version in sorted({feature.left_at for feature in LEFT_CORE if feature.left_at}):record_core_use(home, to_write, version)+ return adopt_agent_browser_env(home, to_write)+++def stamp_missing_config() -> bool:+ """A missing config.yaml reads as current (:func:`read_config_version_stamp`), so no config step ever+ runs on the home. When its .env still carries AGENT_BROWSER_* settings, create config.yaml with its+ first stamp (:func:`note_first_stamp`) now, before callers trust that shortcut, or the browser those+ settings chose is lost. A home without them stays without a config.yaml. Returns whether one was written."""+ from hermes_cli.config import _secure_file, atomic_config_write, get_config_path, is_managed+ path = get_config_path()+ if path.exists() or is_managed():+ return False+ config = {"_config_version": _coerce_config_version(DEFAULT_CONFIG.get("_config_version", 1)) or 1}+ if not note_first_stamp(path.parent, {}, config):+ return False+ path.parent.mkdir(parents=True, exist_ok=True)+ atomic_config_write(path, config)+ _secure_file(path)+ return Truediff --git a/hermes_cli/post_update.py b/hermes_cli/post_update.pyindex 4bdb20d5465..c4d6f35fb1b 100644--- a/hermes_cli/post_update.py+++ b/hermes_cli/post_update.py@@ -75,13 +75,20 @@ def step_migrate_config() -> dict:SUPPORT_FLOOR_VERSION,support_floor_message,)+ from hermes_cli.config_migrations_browser import agent_browser_env_pending+ from hermes_cli.config_version_stamp import read_config_version_stamp, stamp_missing_config- current_ver, latest_ver = check_config_version()+ stamp_missing_config() # a missing config.yaml reads as current below+ stamp, latest_ver = read_config_version_stamp()+ current_ver = 0 if stamp is None else stampif current_ver >= latest_ver:return {"ok": True, "skipped": "up-to-date"}- if current_ver < SUPPORT_FLOOR_VERSION:+ if current_ver < SUPPORT_FLOOR_VERSION and not (stamp is None and agent_browser_env_pending()):# migrate_config() refuses sub-floor configs and leaves the file- # untouched; warn instead of failing the boot.+ # untouched; warn instead of failing the boot. An unstamped config is+ # left alone too, unless its .env still holds AGENT_BROWSER_* settings+ # nothing reads any more: migrate_config() gives it the legacy-key+ # steps (v52's move among them) and a stamp.logger.warning("config migration skipped: %s", support_floor_message())return {"ok": True, "skipped": "below-support-floor"}diff --git a/scripts/docker_config_migrate.py b/scripts/docker_config_migrate.pyindex ff3ae593e23..2557eb2aa0b 100644--- a/scripts/docker_config_migrate.py+++ b/scripts/docker_config_migrate.py@@ -13,7 +13,7 @@ from hermes_cli.config import (get_env_path,migrate_config,)-from hermes_cli.config_version_stamp import check_config_version, read_config_version_stamp+from hermes_cli.config_version_stamp import check_config_version, read_config_version_stamp, stamp_missing_configfrom hermes_cli.config_backups import backup_config, list_config_backupsfrom hermes_cli.config_migrations import (SUPPORT_FLOOR_VERSION,@@ -50,7 +50,9 @@ def main() -> int:# Strict read: malformed YAML or a non-mapping root is left alone with a warning and the# boot continues, instead of running the backup/migrate dance that migrate_config() would- # refuse anyway.+ # refuse anyway. A missing config.yaml reads as current, so its legacy browser settings get their+ # first stamp before that read.+ stamp_missing_config()try:stamp, latest_ver = read_config_version_stamp(raise_on_parse_error=True)except InvalidUserConfigError as exc:diff --git a/tests/hermes_cli/test_config_browser_env_first_stamp.py b/tests/hermes_cli/test_config_browser_env_first_stamp.pynew file mode 100644index 00000000000..0364d18f094--- /dev/null+++ b/tests/hermes_cli/test_config_browser_env_first_stamp.py@@ -0,0 +1,116 @@+"""AGENT_BROWSER_* settings survive homes that never run the versioned v52 step.++The runtime reads only ``browser.*`` from config.yaml now; the v52 step moves a home's legacy+AGENT_BROWSER_* .env settings there. A home whose config.yaml is missing (reads as current), never+stamped (boot used to skip it as below the support floor) or first stamped by an ordinary save+never reaches that step, so the move happens at its first stamp instead, exactly once.+"""++import hermes_yaml as yaml+import pytest++from hermes_cli.config_defaults import DEFAULT_CONFIG++_AB_ENV = ("AGENT_BROWSER_EXECUTABLE_PATH", "AGENT_BROWSER_PROFILE", "AGENT_BROWSER_ARGS",+ "AGENT_BROWSER_HEADED", "AGENT_BROWSER_ENGINE")+_LEGACY = ("AGENT_BROWSER_ENGINE=lightpanda\nAGENT_BROWSER_PROFILE=/probe/chrome-profile\n"+ "AGENT_BROWSER_HEADED=true\n")+_KEPT = {"engine": "lightpanda", "headed": True, "user_data_dir": "/probe/chrome-profile"}+_LATEST = DEFAULT_CONFIG["_config_version"]++[email protected](autouse=True)+def _clean_env(monkeypatch):+ for name in _AB_ENV:+ monkeypatch.delenv(name, raising=False)+ monkeypatch.delenv("CAMOFOX_URL", raising=False)+++def _home(tmp_path, monkeypatch, config_text):+ """A real HERMES_HOME holding the legacy .env and *config_text* (None: no config.yaml)."""+ home = tmp_path / "home"+ home.mkdir()+ (home / ".env").write_text(_LEGACY, encoding="utf-8")+ if config_text is not None:+ (home / "config.yaml").write_text(config_text, encoding="utf-8")+ monkeypatch.setenv("HERMES_HOME", str(home))+ return home+++def _boot():+ from hermes_cli import post_update+ return post_update.step_migrate_config()+++def _first_save():+ from hermes_cli.config import load_config, save_config+ save_config(load_config())+++def _runtime():+ """What the browser launcher resolves for the active home right now."""+ from tools import browser_session_cloud as session+ session.reset_caches()+ return {"engine": session.get_browser_engine(), "headed": session.is_headed_mode(),+ "user_data_dir": session.user_data_dir()}+++def _stamp(home):+ return yaml.safe_load((home / "config.yaml").read_text(encoding="utf-8")).get("_config_version")+++_CONFIGS = {"missing": None, "unstamped": "{}\n", "v51": "_config_version: 51\n"}++[email protected]("case", list(_CONFIGS))+def test_boot_keeps_the_legacy_browser_settings(tmp_path, monkeypatch, case):+ home = _home(tmp_path, monkeypatch, _CONFIGS[case])+ assert _boot()["ok"]+ assert _runtime() == _KEPT+ assert _stamp(home) == _LATEST++[email protected]("case", ["missing", "unstamped"])+def test_a_save_before_any_migration_keeps_the_legacy_browser_settings(tmp_path, monkeypatch, case):+ """The first save stamps the current version, so no config step will ever see this home."""+ home = _home(tmp_path, monkeypatch, _CONFIGS[case])+ _first_save()+ assert _stamp(home) == _LATEST+ _boot()+ assert _runtime() == _KEPT+++def test_explicit_migration_recovers_a_home_without_config(tmp_path, monkeypatch):+ from hermes_cli.config import migrate_config++ home = _home(tmp_path, monkeypatch, None)+ migrate_config(interactive=False, quiet=True)+ assert _runtime() == _KEPT+ assert _stamp(home) == _LATEST+++def test_the_retained_env_is_converted_once_never_over_later_edits(tmp_path, monkeypatch):+ """.env keeps the AGENT_BROWSER_* lines; the user's later choice must still win for good, even the+ defaults (``engine: auto``, ``headed: false``) that the v52 step lets the env override."""+ from hermes_cli.config import load_config, migrate_config, save_config++ _home(tmp_path, monkeypatch, None)+ _boot()+ config = load_config()+ config["browser"].update(engine="auto", headed=False, user_data_dir="/mine")+ save_config(config)+ _boot()+ migrate_config(interactive=False, quiet=True)+ _first_save()+ assert _runtime() == {"engine": "auto", "headed": False, "user_data_dir": "/mine"}++[email protected]("case", ["missing", "unstamped"])+def test_boot_leaves_a_home_without_legacy_settings_as_it_was(tmp_path, monkeypatch, case):+ home = _home(tmp_path, monkeypatch, _CONFIGS[case])+ (home / ".env").write_text("", encoding="utf-8")+ assert _boot()["ok"]+ if _CONFIGS[case] is None:+ assert not (home / "config.yaml").exists()+ else:+ assert (home / "config.yaml").read_text(encoding="utf-8") == _CONFIGS[case]