The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(config-remote): review round 4 — leaf-level CAS intent for new sections, D32 guard on routed secret-source hydration, config-only in-memory migrations, bootstrap completes before other threads select, project .env in the early bootstrap, keyed TUI section/prompt/consent setters
Ben Barclayfd059c01f4d5
diff --git a/hermes_cli/config_backend.py b/hermes_cli/config_backend.pyindex 8bd660065d1..6663efc457d 100644--- a/hermes_cli/config_backend.py+++ b/hermes_cli/config_backend.py@@ -227,8 +227,11 @@ class FileBackend:_FILE_BACKEND = FileBackend()-_BOOTSTRAP_LOCK = threading.Lock()+# Reentrant: publishing the deployment can import modules whose import-time config read selects+# the backend again on the SAME thread (``_BOOTSTRAP_OWNER``); every other thread waits for it.+_BOOTSTRAP_LOCK = threading.RLock()_BOOTSTRAPPED = False+_BOOTSTRAP_OWNER: Optional[int] = Nonedef _bootstrap_names() -> frozenset:@@ -242,18 +245,35 @@ def _ensure_bootstrap_env() -> None:authenticates the backend comes from the process env, the launch home's ``.env`` and themanaged ``.env`` (design §4.4 steps 1-2, D26/D32) — also when the first config read comes before``load_hermes_dotenv`` (``hermes_cli.config`` reads config at import time)."""- global _BOOTSTRAPPED- if _BOOTSTRAPPED:- return- with _BOOTSTRAP_LOCK:- if _BOOTSTRAPPED:- return- _BOOTSTRAPPED = True+ if not _BOOTSTRAPPED:+ _bootstrap(None, None, once=True)+++def bootstrap_deployment(home: Optional[PathLike] = None, project_env: Optional[PathLike] = None) -> None:+ """Publish the deployment from an explicit dotenv load's layers (``load_hermes_dotenv``: its+ home and project ``.env``) before that load's first config read. Runs even when the+ once-per-process bootstrap already ran: an earlier one did not know this load's project file."""+ _bootstrap(Path(home) if home is not None else None,+ Path(project_env) if project_env is not None else None, once=False)+++def _bootstrap(home: Optional[Path], project_env: Optional[Path], *, once: bool) -> None:+ global _BOOTSTRAPPED, _BOOTSTRAP_OWNER+ with _BOOTSTRAP_LOCK: # another thread's bootstrap in progress: wait for it to publish+ if (once and _BOOTSTRAPPED) or _BOOTSTRAP_OWNER == threading.get_ident():+ return # done, or this thread's own bootstrap re-entering (import-time config read)+ _BOOTSTRAP_OWNER = threading.get_ident()try:from hermes_cli.env_loader import apply_config_bootstrap_env- apply_config_bootstrap_env(_bootstrap_names) # names resolved only for a remote deployment+ # names resolved only for a remote deployment+ apply_config_bootstrap_env(_bootstrap_names, home, project_env)except ImportError: # no usable python-dotenv (a bare installer interpreter): no .env loads either- return+ pass+ finally:+ # Complete only once the deployment is published: a concurrent first reader that saw+ # the flag earlier would select (and read) the file backend of a remote deployment.+ _BOOTSTRAP_OWNER = None+ _BOOTSTRAPPED = Truedef get_config_backend() -> ConfigBackend:diff --git a/hermes_cli/config_migrations.py b/hermes_cli/config_migrations.pyindex 973217aae33..a6ac26ab909 100644--- a/hermes_cli/config_migrations.py+++ b/hermes_cli/config_migrations.py@@ -8,6 +8,7 @@ step may only persist values that differ from the schema default (plus removals/from __future__ import annotations+import contextvarsimport copyimport functoolsimport logging@@ -26,6 +27,18 @@ logger = logging.getLogger(__name__)#: non-fatal posture for unparseable configs — and a message tells the user how to proceed.SUPPORT_FLOOR_VERSION = 12+#: True while :func:`run_migrations` runs with ``config_only=True``: the remote config backend's+#: in-memory migrations (D12) and its write-validation simulation. Such a run transforms the config+#: document and nothing else: steps that also touch local files (``.env``, profile ``SOUL.md``,+#: ``logs/``) skip that part, so reading a profile's remote config, or a refused write's check, never+#: changes a file on disk — a sibling profile's least of all.+_CONFIG_ONLY: "contextvars.ContextVar[bool]" = contextvars.ContextVar("config_migrations_config_only", default=False)+++def _local_files_allowed() -> bool:+ """Whether the running step may change files other than the config document itself."""+ return not _CONFIG_ONLY.get()+def support_floor_message() -> str:"""Human-facing explanation shown when a config is below the floor."""@@ -174,6 +187,8 @@ def _migrate_to_12(results: dict[str, Any], quiet: bool) -> None:def _migrate_to_13(results: dict[str, Any], quiet: bool) -> None:# 12 → 13: clear dead LLM_MODEL / OPENAI_MODEL from .env (written by the old setup wizard;# nothing reads them — config.yaml is the sole source of truth).+ if not _local_files_allowed():+ return # .env only_c = _cfg()for dead_var in ("LLM_MODEL", "OPENAI_MODEL"):try:@@ -339,11 +354,12 @@ def _migrate_to_23(results: dict[str, Any], quiet: bool) -> None:_c = _cfg()DEFAULT_CONFIG = _c.DEFAULT_CONFIG- try:- curator_dir = _c.get_hermes_home() / "logs" / "curator"- curator_dir.mkdir(parents=True, exist_ok=True)- except Exception as e:- results["warnings"].append(f"Could not create {curator_dir}: {e}")+ if _local_files_allowed():+ try:+ curator_dir = _c.get_hermes_home() / "logs" / "curator"+ curator_dir.mkdir(parents=True, exist_ok=True)+ except Exception as e:+ results["warnings"].append(f"Could not create {curator_dir}: {e}")config = read_raw_config()@@ -541,6 +557,8 @@ def _migrate_to_41(results: dict[str, Any], quiet: bool) -> None:# 40 → 41: drop the plugin-era "## Messaging other agents" append from every SOUL.md. The# server injects the live Bot Mode section in Bot Chat sessions; the frozen SOUL copy taxed# every other session (~600 tok) and shadowed the live roster in Bot Chat itself.+ if not _local_files_allowed():+ return # SOUL.md files only, across the whole rosterfrom hermes_constants import get_hermes_homefrom tools.bot_mode_probe import _PROTOCOL_HEADING, _hermes_root, _roster, strip_legacy_protocol@@ -680,6 +698,8 @@ def _migrate_to_49(results: dict[str, Any], quiet: bool) -> None:f"({DEFAULT_VERCEL_IMAGE})",)(results, quiet)_c = _cfg()+ if not _local_files_allowed():+ return # the .env mirror is a local fileif (_c.get_env_value_prefer_dotenv("TERMINAL_VERCEL_RUNTIME") or "").strip() == LEGACY_VERCEL_RUNTIME:_c.remove_env_value("TERMINAL_VERCEL_RUNTIME")if not quiet:@@ -878,14 +898,25 @@ STAMP_INDEPENDENT_STEPS = frozenset({46, 50})def run_migrations(- current_ver: int, results: dict[str, Any], quiet: bool, *, unversioned: bool = False) -> None:+ current_ver: int, results: dict[str, Any], quiet: bool, *, unversioned: bool = False,+ config_only: bool = False) -> None:"""Apply every registered migration whose target version exceeds *current_ver* (plus:data:`STAMP_INDEPENDENT_STEPS`); a config with no ``_config_version`` (*unversioned*) getsonly :data:`LEGACY_KEY_STEPS`.*current_ver* is the on-disk schema version captured ONCE before any step runs and does notadvance between steps — each step is gated on the same initial value.++ *config_only* transforms the config document alone (see :data:`_CONFIG_ONLY`)."""+ token = _CONFIG_ONLY.set(config_only)+ try:+ _run_steps(current_ver, results, quiet, unversioned)+ finally:+ _CONFIG_ONLY.reset(token)+++def _run_steps(current_ver: int, results: dict[str, Any], quiet: bool, unversioned: bool) -> None:for target_ver, migration_fn in MIGRATIONS:due = current_ver < target_ver or target_ver in STAMP_INDEPENDENT_STEPSif due and (target_ver in LEGACY_KEY_STEPS or not unversioned):diff --git a/hermes_cli/env_loader.py b/hermes_cli/env_loader.pyindex 984f56970cf..7501d8d8510 100644--- a/hermes_cli/env_loader.py+++ b/hermes_cli/env_loader.py@@ -178,7 +178,9 @@ def hydrate_profile_secret_sources(hermes_home: str | os.PathLike) -> dict[str,"""Resolve one profile's configured sources without mutating ``os.environ``: multiplex gateways routeturns to profiles that never ran the process-global dotenv path, so resolve against a private mappingseeded from that ``.env`` and record the per-home snapshot for ``build_profile_secret_scope()``.- Fail-open / once-per-home like ``_apply_external_secret_sources``; never returns plaintext .env entries."""+ Fail-open / once-per-home like ``_apply_external_secret_sources``; never returns plaintext .env entries.+ The one fail-closed case is D32's: under the remote config backend, a source that supplies a+ protected name raises :class:`ConfigBackendUnavailable` and records nothing for the home."""with _SECRET_SOURCE_CACHE_LOCK:return _hydrate_profile_secret_sources(Path(hermes_home))@@ -220,12 +222,21 @@ def _hydrate_profile_secret_sources(home: Path) -> dict[str, str]:for _name, _value in load_env_file(op_env).items():local_env.setdefault(_name, _value)local_env["HERMES_HOME"] = str(home)+ env_before = dict(local_env)report = apply_all(cfg, home, environ=local_env)except Exception:return {}if not report.sources:return {}+ # D32, as on the process-global path: a source must never supply the config backend's own+ # deployment or plane credential, for a routed profile either (this snapshot feeds that+ # profile's secret scope, which the Portal/plane resolvers read). Checked before anything of+ # this attempt is recorded: the remote backend refuses the profile (raises, nothing cached, so+ # every retry refuses again until the mapping is removed); the file backend drops the selector.+ from hermes_cli.config_backend import get_config_backend++ _refuse_protected_env_from_sources(report, get_config_backend(), env_before, env=local_env, routed_home=home)# Routed profiles have no runtime reset path. Keep a failed source retryable so correcting its# profile-local bootstrap credentials takes effect on the next turn; successful sources from a@@ -439,16 +450,21 @@ def _load_dotenv_with_fallback(_sanitize_loaded_credentials() # httpx encodes headers as ASCII-def _bootstrap_env(home: Path | None = None) -> dict:- """The process env as ``load_hermes_dotenv`` leaves it for the names the home's ``.env`` and the- managed ``.env`` define: both override, managed last, ``${VAR}`` resolved, the loader's parser.- Read-only: nothing is published and no file is rewritten (sanitizing imports hermes_cli.config,- whose import-time config read must not run before the backend is decided)."""- from dotenv.variables import parse_variables-+def _bootstrap_env(home: Path | None = None, project_env: Path | None = None) -> dict:+ """The process env as ``load_hermes_dotenv`` leaves it for the names its dotenv layers define:+ the home's ``.env`` (override), ``.op.env`` (fills gaps, only without a process+ ``OP_SERVICE_ACCOUNT_TOKEN``), the caller's *project_env* (fills gaps when the home has a+ ``.env``, else overrides) and the managed ``.env`` (override, last); ``${VAR}`` resolved, the+ loader's parser. Read-only: nothing is published and no file is rewritten (sanitizing imports+ hermes_cli.config, whose import-time config read must not run before the backend is decided)."""home = Path(home) if home is not None else _process_hermes_home()env = dict(os.environ)- layers = [home / ".env"]+ user_env = home / ".env"+ layers: list[tuple[Path, bool]] = [(user_env, True)]+ if not os.environ.get("OP_SERVICE_ACCOUNT_TOKEN"):+ layers.append((home / ".op.env", False))+ if project_env is not None:+ layers.append((Path(project_env), not user_env.exists()))try:from hermes_cli import managed_scope@@ -456,18 +472,16 @@ def _bootstrap_env(home: Path | None = None) -> dict:except Exception: # noqa: BLE001 — same fail-open as _apply_managed_envmanaged_dir = Noneif managed_dir is not None:- layers.append(managed_dir / ".env")- for path in layers:+ layers.append((managed_dir / ".env", True))+ for path, override in layers:try:assignments = _parse_dotenv_file(path)except OSError:continue- resolved: dict[str, str | None] = {}- for name, value in assignments:- if value is not None:- value = "".join(atom.resolve({**env, **resolved}) for atom in parse_variables(value))- resolved[name] = value- env.update({k: v for k, v in resolved.items() if v is not None})+ resolved = _resolve_dotenv_assignments(assignments, env, override=override)+ for name, value in resolved.items():+ if value is not None and (override or name not in env):+ env[name] = valuereturn env@@ -480,7 +494,7 @@ def selected_config_backend_name(home: Path | None = None) -> str:return (_bootstrap_env(home).get(BACKEND_ENV) or "").strip().lower() or "file"-def apply_config_bootstrap_env(remote_names, home: Path | None = None) -> None:+def apply_config_bootstrap_env(remote_names, home: Path | None = None, project_env: Path | None = None) -> None:"""Publish ``remote_names()`` (the remote backend's deployment and plane credential, D26/D32) from thelaunch home's ``.env`` and the managed ``.env``, with the values ``load_hermes_dotenv`` givesthem. Called before the first config read of a process, which can come before@@ -490,7 +504,7 @@ def apply_config_bootstrap_env(remote_names, home: Path | None = None) -> None:no file defines are left alone; ``load_hermes_dotenv`` later publishes the same values."""from hermes_cli.config_backend import BACKEND_ENV- env = _bootstrap_env(home)+ env = _bootstrap_env(home, project_env)if (env.get(BACKEND_ENV) or "").strip().lower() == "remote":names = remote_names()else:@@ -623,6 +637,13 @@ def load_hermes_dotenv(project_env_path = Path(project_env) if project_env else Noneload_pass = next(_DOTENV_PASSES) # one pass: later layers below see the earlier layers' output+ # Before anything below imports hermes_cli.config (the .env sanitizer does), whose import-time+ # config read selects and boots the backend: publish the deployment and plane credential from+ # THIS load's layers, the project .env included, with the precedence the loads below give them.+ from hermes_cli.config_backend import bootstrap_deployment++ bootstrap_deployment(home_path, project_env_path)+if user_env.exists(): # normalize formatting / strip NULs before parsing_sanitize_env_file_if_needed(user_env)if project_env_path and project_env_path.exists():@@ -767,7 +788,7 @@ def _revoke_secret_source_writes(home_path: Path, *, keep) -> None:_SECRET_SOURCE_WRITES_BY_HOME.pop(home_key, None)-def _refuse_protected_env_from_sources(report, backend=None, environ_before=None, env=None) -> None:+def _refuse_protected_env_from_sources(report, backend=None, environ_before=None, env=None, *, routed_home=None) -> None:"""D32: the config backend's own credential (which plane, which agent, which token) must nevercome from a secret source — a source that could change it could point config at another plane.Exits (the backend is unusable), even when the pre-existing value won.@@ -812,10 +833,12 @@ def _refuse_protected_env_from_sources(report, backend=None, environ_before=Noneprint(f" Secret sources: ignored {BACKEND_ENV} from a secrets: source (the config backend is ""chosen by .env or the process environment only).", file=sys.stderr)return+ outcome = (f"Hermes does not serve profile home {routed_home} with it." if routed_home is not None+ else "Hermes does not start with it.")raise ConfigBackendUnavailable(f"A secrets: source supplies {', '.join(clash)}, which the {backend.name!r} config ""backend uses to reach its config plane. That credential must come from auth.json or .env, never "- "from a secret source; remove the mapping. Hermes does not start with it.")+ f"from a secret source; remove the mapping. {outcome}")def _publish_staged_env(staged: dict, environ_before: dict) -> None:diff --git a/plugins/config_backends/remote/backend.py b/plugins/config_backends/remote/backend.pyindex 52bb214d769..12b0d4a80ab 100644--- a/plugins/config_backends/remote/backend.py+++ b/plugins/config_backends/remote/backend.py@@ -25,7 +25,7 @@ from hermes_cli.config_backend import (from . import clientfrom .credentials import PLANE_CREDENTIAL_ENV_NAMES, PlaneCredentialError-from .diff import _get_path, diff, encode_changes, json_equal, strip_locked, write_check+from .diff import _get_path, apply_intent, diff, encode_changes, intent_diff, json_equal, strip_locked, write_checkfrom .paths import Path as KeyPathfrom .paths import PathError, decode, encode, from_dottedfrom .values import secret_literal_path, to_wire@@ -330,7 +330,8 @@ class RemoteBackend:private_token = _PRIVATE.set(m)home_token = set_hermes_home_override(st.home)try:- run_migrations(current, {"env_added": [], "config_added": [], "warnings": []}, True)+ # config_only: a read (or a refused write's check) must change no local file (D12).+ run_migrations(current, {"env_added": [], "config_added": [], "warnings": []}, True, config_only=True)finally:reset_hermes_home_override(home_token)_PRIVATE.reset(private_token)@@ -488,17 +489,16 @@ class RemoteBackend:if dropped:print(f"Note: {len(dropped)} setting(s) locked by Remote Config were not saved: "f"{', '.join(sorted(encode(p) for p in dropped))}", file=sys.stderr)- return diff(base, new)+ # Leaf-level: a key added under a section the doc lacked stays a key-level edit, so a+ # retry after 409 keeps the siblings another writer put in that section meanwhile.+ return intent_diff(base, new)def _patch_body(self, st: _ProfileState, sets: Dict[KeyPath, Any], unsets: List[KeyPath]) -> Optional[Tuple[Dict[str, Any], Dict[KeyPath, Any], List[KeyPath]]]:"""The PATCH body applying the intent to the current doc, or None when that is no change."""base = self._diff_base(st)new = copy.deepcopy(base)- for p, v in sets.items():- _set_path(new, p, copy.deepcopy(v))- for p in unsets:- _pop_path(new, p)+ apply_intent(new, sets, unsets)sets, unsets = diff(base, new)refused = write_check(sets, unsets, st.locks)if refused is not None:diff --git a/plugins/config_backends/remote/diff.py b/plugins/config_backends/remote/diff.pyindex 60a8d250382..0ccd509f1a6 100644--- a/plugins/config_backends/remote/diff.py+++ b/plugins/config_backends/remote/diff.py@@ -46,6 +46,58 @@ def diff(base: Dict[str, Any], new: Dict[str, Any], prefix: Path = ()) -> Tuple[return sets, unsets+def intent_diff(base: Dict[str, Any], new: Dict[str, Any], prefix: Path = ()) -> Tuple[Dict[Path, Any], List[Path]]:+ """:func:`diff` as a caller's *intent*: the key-level edit a write means, to be re-applied to a+ newer document after a CAS conflict (§15.3). A mapping the base did not hold as a mapping+ (absent, or a scalar) is expanded to its leaves: writing ``terminal.timeout`` into a profile+ with no ``terminal`` section means "set that key", not "replace whatever ``terminal`` holds by+ the time the retry runs" — another writer's ``terminal.persistent`` must survive it. Only an+ empty mapping stays a whole value (there is no leaf to name); :func:`apply_intent` adds it+ without replacing a mapping that appeared meanwhile."""+ sets: Dict[Path, Any] = {}+ unsets: List[Path] = []+ for key, value in new.items():+ p = prefix + (key,)+ old = base.get(key, _ABSENT)+ if isinstance(value, dict) and value and not isinstance(old, dict):+ s, _ = intent_diff({}, value, p)+ sets.update(s)+ elif key not in base:+ sets[p] = value+ elif isinstance(old, dict) and isinstance(value, dict):+ s, u = intent_diff(old, value, p)+ sets.update(s)+ unsets.extend(u)+ elif not json_equal(old, value):+ sets[p] = value+ unsets.extend(prefix + (key,) for key in base if key not in new)+ return sets, unsets+++_ABSENT = object()+++def apply_intent(doc: Dict[str, Any], sets: Dict[Path, Any], unsets: Sequence[Path]) -> None:+ """Apply an :func:`intent_diff` edit to *doc* in place."""+ for p, v in sets.items():+ if isinstance(v, dict) and not v:+ found, cur = _get_path(doc, p)+ if found and isinstance(cur, dict):+ continue # "make this a mapping": a mapping is already there, with its keys+ _set_path(doc, p, copy.deepcopy(v))+ for p in unsets:+ _pop_path(doc, p)+++def _set_path(doc: Dict[str, Any], path: Path, value: Any) -> None:+ node = doc+ for seg in path[:-1]:+ if not isinstance(node.get(seg), dict):+ node[seg] = {}+ node = node[seg]+ node[path[-1]] = value++def _pop_path(doc: Dict[str, Any], path: Path) -> bool:node: Any = docfor seg in path[:-1]:diff --git a/tests/plugins/config_backends/test_remote_backend.py b/tests/plugins/config_backends/test_remote_backend.pyindex 55c3a429a3d..3254bcb480b 100644--- a/tests/plugins/config_backends/test_remote_backend.py+++ b/tests/plugins/config_backends/test_remote_backend.py@@ -396,7 +396,7 @@ def test_migration_steps_persist_into_memory(plane, monkeypatch):latest = backend_mod._latest_config_version()plane.profile("default").update(values={"old_key": 1}, version=1, writer=latest - 1)- def fake_run_migrations(current, results, quiet):+ def fake_run_migrations(current, results, quiet, **kwargs):doc = config_mod.read_raw_config()doc["new_key"] = doc.pop("old_key")config_mod._persist_migration(doc)@@ -1286,3 +1286,371 @@ def test_rpc_refused_by_the_config_backend_still_gets_its_one_answer(plane, monkassert written.wait(10)(frame,) = transport.framesassert frame["id"] == "pooled-1" and "cannot load the config" in frame["error"]["message"]++++# --- review round 4 regressions -----------------------------------------------------------++def _absent_section_race(plane, monkeypatch):+ """Another writer adds ``terminal.persistent`` to a profile with no ``terminal`` section+ between our read and our first PATCH (so that PATCH gets a 409)."""+ from plugins.config_backends.remote import client+ plane.profile("default").update(values={"display": {"personality": "concise"}}, version=1)+ get_config_backend().read_user_layer(plane.home)+ real_request = client.request+ raced = []++ def other_writer_lands_first(method, *args, **kwargs):+ if method == "PATCH" and not raced:+ raced.append(True)+ prof = plane.profile("default")+ prof["values"]["terminal"] = {"persistent": True}+ prof["version"] += 1+ return real_request(method, *args, **kwargs)++ monkeypatch.setattr(client, "request", other_writer_lands_first)++[email protected]("entry", ["set_config_value", "write_config_key"])+def test_cas_retry_keeps_a_sibling_added_to_a_section_the_doc_lacked(plane, monkeypatch, entry):+ """Round 4 #1: our edit adds terminal.timeout to a doc with no terminal section; the 409 retry+ must add that one key to the re-read doc, not replace the section another writer created."""+ from hermes_cli.config import set_config_value+ _absent_section_race(plane, monkeypatch)++ if entry == "set_config_value":+ set_config_value("terminal.timeout", "321")+ else:+ write_config_key(plane.home / "config.yaml", "terminal.timeout", 321)++ assert plane.profile("default")["values"]["terminal"] == {"persistent": True, "timeout": 321}+ first, retry = plane.patches()+ assert retry["body"]["expectedVersion"] == 2+ assert retry["body"]["set"] == {"terminal.timeout": 321} and "unset" not in retry["body"]+++def test_cas_retry_of_a_new_empty_section_keeps_a_concurrent_one(plane, monkeypatch):+ """An empty mapping the edit adds means "make this a mapping": on retry it must not replace+ the mapping (with keys) another writer created meanwhile."""+ _absent_section_race(plane, monkeypatch)+ from hermes_cli.config_backend import Changes+ get_config_backend().write_changes(plane.home, Changes(set={"terminal": {}}))+ assert plane.profile("default")["values"]["terminal"] == {"persistent": True}+ assert len(plane.patches()) == 1 # nothing left to send after the re-read: one PATCH, the 409+++def test_explicit_section_replacement_stays_a_replacement(plane):+ """Control: replacing a present section with a scalar, or unsetting it, is still sent whole."""+ from hermes_cli.config_backend import Changes+ plane.profile("default").update(values={"terminal": {"persistent": True, "timeout": 3}}, version=1)+ backend = get_config_backend()+ backend.write_changes(plane.home, Changes(unset=("terminal",)))+ assert plane.patches()[-1]["body"]["unset"] == ["terminal"]+ assert "terminal" not in plane.profile("default")["values"]+++def _routed_profile(profile_plane, source_env_line):+ named = profile_plane.home / "profiles" / "routed"+ named.mkdir(parents=True)+ (named / ".env").write_text("# synthetic\n")+ profile_plane.profile("routed").update(values={"secrets": {"command": {+ "enabled": True, "override_existing": True,+ "command": f"printf '{source_env_line}\\n'"}}}, version=1)+ return named+++def test_routed_hydration_refuses_a_source_that_supplies_a_protected_name(profile_plane, monkeypatch):+ """Round 4 #2: a routed profile's remote secrets: source supplies HERMES_PORTAL_BASE_URL (where+ auth.json's refresh token is sent). Refused before any snapshot, ownership or scope publication;+ every retry refuses again; the profile hydrates once the mapping is gone."""+ import os++ from hermes_cli import env_loader+ from hermes_cli.web_server_profiles import _config_profile_scope+ monkeypatch.setattr(env_loader, "_APPLIED_HOMES", set())+ monkeypatch.setattr(env_loader, "_SOURCE_SUPPLIED_NAMES", set())+ monkeypatch.delenv("HERMES_PORTAL_BASE_URL", raising=False)+ named = _routed_profile(profile_plane, "HERMES_PORTAL_BASE_URL=http://127.0.0.1:1")++ for _attempt in range(2): # nothing is cached by a refusal: a retry refuses again+ with pytest.raises(ConfigBackendUnavailable, match="HERMES_PORTAL_BASE_URL"):+ with _config_profile_scope("routed"):+ pass+ assert env_loader.get_secret_source_values(named) == {}+ assert str(named.resolve()) not in env_loader._APPLIED_HOMES+ assert "HERMES_PORTAL_BASE_URL" not in env_loader._SOURCE_SUPPLIED_NAMES+ assert "HERMES_PORTAL_BASE_URL" not in os.environ++ profile_plane.profile("routed").update(values={"secrets": {"command": {+ "enabled": True, "override_existing": True, "command": "printf 'SYNTHETIC_KEY=routed-ok\\n'"}}}, version=2)+ backend = get_config_backend()+ assert backend.poll_one(backend._state(named))+ assert env_loader.hydrate_profile_secret_sources(named) == {"SYNTHETIC_KEY": "routed-ok"}+++def test_file_mode_routed_hydration_drops_only_the_selector(monkeypatch, tmp_path, capsys):+ """Control: under the file backend a routed source may not switch the backend either, but its+ other values (a Portal URL included: file mode has no plane credential) still hydrate."""+ from hermes_cli import env_loader+ for name in ("HERMES_CONFIG_BACKEND", "HERMES_CONFIG_REMOTE_URL", "HERMES_CONFIG_INSTANCE_ID"):+ monkeypatch.delenv(name, raising=False)+ monkeypatch.setattr(env_loader, "_APPLIED_HOMES", set())+ home = tmp_path / "routed"+ home.mkdir()+ (home / ".env").write_text("# synthetic\n")+ (home / "config.yaml").write_text(+ "secrets:\n command:\n enabled: true\n override_existing: true\n"+ " command: \"printf 'HERMES_CONFIG_BACKEND=remote\\\\nHERMES_PORTAL_BASE_URL=http://portal.test\\\\n'\"\n")++ values = env_loader.hydrate_profile_secret_sources(home)++ assert values == {"HERMES_PORTAL_BASE_URL": "http://portal.test"}+ assert "ignored HERMES_CONFIG_BACKEND" in capsys.readouterr().err+++_LEGACY_SOUL = "# Beta identity\n\n## Messaging other agents\nKEEP THIS PROFILE SECTION\n"+++def _sibling_with_legacy_soul(home):+ beta = home / "profiles" / "beta"+ beta.mkdir(parents=True)+ (beta / "SOUL.md").write_text(_LEGACY_SOUL)+ return beta / "SOUL.md"+++def test_remote_read_migration_changes_no_local_file(plane):+ """Round 4 #3: reading default's remote config stamped 40 runs the 40->41 step in memory. That+ step's only effect is on profile SOUL.md files; a config read must not rewrite a sibling's."""+ from hermes_cli.config_backend import read_config_doc+ soul = _sibling_with_legacy_soul(plane.home)+ plane.profile("default").update(values={"display": {"personality": "old"}}, writer=40, version=1)++ doc = read_config_doc(plane.home / "config.yaml")++ assert doc["_config_version"] == backend_mod._latest_config_version() # it did migrate+ assert soul.read_text() == _LEGACY_SOUL+ assert plane.patches() == []+++def test_refused_write_validation_changes_no_local_file(plane):+ """Round 4 #3: the config_migration_conflict check simulates the migration of the stored doc;+ a refused edit must leave every local file as it was."""+ from hermes_cli.config import read_raw_config+ plane.profile("default").update(values={}, writer=40, version=1)+ read_raw_config()+ soul = _sibling_with_legacy_soul(plane.home) # created after the read's own migration++ with pytest.raises(ConfigValueError) as exc:+ write_config_key(plane.home / "config.yaml", "compression.threshold_tokens", 256000)++ assert exc.value.code == "config_migration_conflict"+ assert soul.read_text() == _LEGACY_SOUL+ assert plane.patches() == []+++def _home_files(root):+ return {str(p.relative_to(root)): (p.read_bytes() if p.is_file() else None)+ for p in sorted(root.rglob("*"))}++[email protected]("config_only", [True, False])+def test_config_only_migration_ladder_touches_no_file(tmp_path, monkeypatch, config_only):+ """The whole ladder from the support floor, config-only, over a home whose files every+ file-touching step would change (.env dead/legacy values, a legacy SOUL.md section, no logs/):+ the only output is the config document. Control: a file-mode run does change them."""+ from hermes_cli import config as config_mod+ from hermes_cli import config_migrations+ home = tmp_path / "home"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ for name in ("HERMES_CONFIG_BACKEND", "LLM_MODEL", "OPENAI_MODEL", "TERMINAL_VERCEL_RUNTIME"):+ monkeypatch.delenv(name, raising=False)+ from hermes_cli.config_defaults import LEGACY_VERCEL_RUNTIME+ (home / ".env").write_text(f"LLM_MODEL=old-model\nTERMINAL_VERCEL_RUNTIME={LEGACY_VERCEL_RUNTIME}\n")+ (home / "SOUL.md").write_text(_LEGACY_SOUL)+ _sibling_with_legacy_soul(home)+ doc = {"_config_version": config_migrations.SUPPORT_FLOOR_VERSION, "model": {"default": "m"}}+ persisted = []+ monkeypatch.setattr(config_mod, "read_raw_config", lambda: dict(persisted[-1] if persisted else doc))+ monkeypatch.setattr(config_mod, "_persist_migration", lambda cfg: persisted.append(dict(cfg)))+ before = _home_files(home)++ config_migrations.run_migrations(config_migrations.SUPPORT_FLOOR_VERSION,+ {"env_added": [], "config_added": [], "warnings": []}, True,+ config_only=config_only)++ assert persisted # the document itself was migrated either way+ assert (_home_files(home) == before) is config_only++++def test_concurrent_first_reader_waits_for_the_bootstrap(plane, monkeypatch, tmp_path):+ """Round 4 #4: while one thread publishes the deployment from .env, a concurrent first reader+ must wait for it, not select the file backend and read the local config.yaml meanwhile."""+ import threading++ from hermes_cli import config_backend, env_loader+ from hermes_cli.config_backend import read_config_doc+ _drop_process_deployment(plane, monkeypatch, tmp_path)+ (plane.home / ".env").write_text("".join(f"{k}={v}\n" for k, v in remote_env(plane).items()))+ (plane.home / "config.yaml").write_text("display:\n personality: forbidden-local\n")+ plane.profile("default").update(values={"display": {"personality": "remote"}}, version=1)+ monkeypatch.setattr(config_backend, "_BOOTSTRAPPED", False)+ entered, resume = threading.Event(), threading.Event()+ real_apply = env_loader.apply_config_bootstrap_env++ def paused(*args, **kwargs):+ entered.set()+ assert resume.wait(10)+ return real_apply(*args, **kwargs)++ monkeypatch.setattr(env_loader, "apply_config_bootstrap_env", paused)+ results = {}++ def run(name, fn):+ threading.Thread(target=lambda: results.__setitem__(name, fn()), name=name, daemon=True).start()++ run("first", lambda: get_config_backend().name)+ assert entered.wait(10)+ run("concurrent", lambda: read_config_doc(plane.home / "config.yaml")["display"]["personality"])+ import time+ time.sleep(0.3)+ assert "concurrent" not in results # waiting for the bootstrap, not reading the local file+ resume.set()+ deadline = time.monotonic() + 10+ while len(results) < 2 and time.monotonic() < deadline:+ time.sleep(0.02)+ assert results == {"first": "remote", "concurrent": "remote"}+++def test_same_thread_reentry_during_the_bootstrap_does_not_deadlock(monkeypatch):+ """Control: an import-time config read on the bootstrapping thread itself returns at once."""+ from hermes_cli import config_backend, env_loader+ monkeypatch.setattr(config_backend, "_BOOTSTRAPPED", False)+ seen = []++ def reentrant(*args, **kwargs):+ seen.append(config_backend.get_config_backend().name) # would block on a plain Lock++ monkeypatch.setattr(env_loader, "apply_config_bootstrap_env", reentrant)+ monkeypatch.delenv("HERMES_CONFIG_BACKEND", raising=False)+ assert config_backend.get_config_backend().name == "file"+ assert seen == ["file"] and config_backend._BOOTSTRAPPED+++def _fresh_interpreter_boot(tmp_path, env, project_env):+ import os+ import subprocess+ import sys+ code = ("import json\n"+ "from hermes_cli.env_loader import load_hermes_dotenv\n"+ f"load_hermes_dotenv(project_env={str(project_env)!r}, load_external_secrets=False)\n"+ "from hermes_cli.config_backend import get_config_backend\n"+ "from hermes_cli.config import load_config\n"+ "print('RESULT=' + json.dumps([get_config_backend().name, load_config()['display']['personality']]))\n")+ child = {k: v for k, v in os.environ.items() if k in ("PATH", "LANG", "TMPDIR", "SYSTEMROOT")}+ child.update(env, PYTHONPATH=str(Path(__file__).resolve().parents[3]))+ return subprocess.run([sys.executable, "-c", code], env=child, capture_output=True, text=True,+ timeout=120, stdin=subprocess.DEVNULL, cwd=str(tmp_path))+++def test_plane_credential_from_the_project_dotenv_boots(plane, tmp_path):+ """Round 4 #5: user .env selects remote and names the plane and instance; the project .env (a+ supported load_hermes_dotenv layer) holds the IdP credential. A fresh process boots and fetches:+ the early bootstrap sees the project layer before the sanitizer's config import reads config."""+ env = remote_env(plane)+ (plane.home / ".env").write_text("".join(f"{k}={v}\n" for k, v in env.items() if k.startswith("HERMES_CONFIG_")))+ project = tmp_path / "project.env"+ project.write_text("".join(f"{k}={v}\n" for k, v in env.items() if k.startswith("GATEWAY_RELAY_IDP_")))+ (plane.home / "config.yaml").write_text("display:\n personality: forbidden-local\n")+ plane.profile("default").update(values={"display": {"personality": "remote"}}, version=1)++ proc = _fresh_interpreter_boot(tmp_path, {"HERMES_HOME": str(plane.home), "HOME": str(tmp_path)}, project)++ assert proc.returncode == 0, proc.stderr[-3000:]+ line = [ln for ln in proc.stdout.splitlines() if ln.startswith("RESULT=")][-1]+ assert json.loads(line[len("RESULT="):]) == ["remote", "remote"]+ assert _gets(plane)+++def test_bootstrap_keeps_the_dotenv_precedence(tmp_path, monkeypatch):+ """The bootstrap composes the layers as load_hermes_dotenv does: user .env overrides the+ process, the project .env only fills gaps when a user .env exists, managed .env wins last."""+ from hermes_cli.env_loader import _bootstrap_env+ home = tmp_path / "home"+ home.mkdir()+ managed = tmp_path / "managed"+ managed.mkdir()+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(managed))+ monkeypatch.setenv("CC_A", "process")+ monkeypatch.setenv("CC_D", "process")+ monkeypatch.delenv("OP_SERVICE_ACCOUNT_TOKEN", raising=False)+ (home / ".env").write_text("CC_A=user\nCC_B=user\n")+ (home / ".op.env").write_text("CC_B=op\nCC_E=op\n")+ project = tmp_path / "project.env"+ project.write_text("CC_B=project\nCC_C=project\nCC_D=project\n")+ (managed / ".env").write_text("CC_C=managed\n")++ env = _bootstrap_env(home, project)++ assert (env["CC_A"], env["CC_B"], env["CC_C"], env["CC_D"], env["CC_E"]) == (+ "user", "user", "managed", "process", "op")+ (home / ".env").unlink() # no user .env: the project layer overrides the process+ assert _bootstrap_env(home, project)["CC_D"] == "project"+++def test_tui_section_and_prompt_setters_refuse_locked_edits(plane, monkeypatch):+ """Round 4 #6: prompt / reasoning / details_mode / details_mode.<section> under an upper lock+ answer with the lock, send nothing, and leave the session as it was. Unlocked, they write."""+ plane.upper = {"custom_prompt": "tenant-prompt",+ "display": {"show_reasoning": False, "sections": {"thinking": "hidden"}, "details_mode": "collapsed"}}+ plane.upper_locks = [{"path": "custom_prompt", "level": "tenant"}, {"path": "display", "level": "group"}]+ server = _tui_server(monkeypatch, plane.home)+ session = {"show_reasoning": False, "session_key": "k"}+ server._sessions["s1"] = session+ try:+ _locked_then_unlocked_tui_setters(plane, server, session)+ finally:+ server._sessions.pop("s1", None) # never torn down by the TUI fixture after the plane stops+++def _locked_then_unlocked_tui_setters(plane, server, session):+ calls = [("prompt", "synthetic-new-prompt"), ("prompt", "clear"), ("reasoning", "show"),+ ("details_mode", "expanded"), ("details_mode.thinking", "expanded"), ("details_mode.thinking", "")]++ for rid, (key, value) in enumerate(calls):+ answer = server._methods["config.set"](rid, {"key": key, "value": value, "session_id": "s1"})+ assert answer.get("error", {}).get("code") == 4002, (key, value, answer)+ assert "locked" in answer["error"]["message"]+ assert plane.patches() == []+ assert session["show_reasoning"] is False+ raw = server._load_cfg_raw()+ assert raw["custom_prompt"] == "tenant-prompt" and raw["display"]["show_reasoning"] is False++ plane.upper_locks = []+ backend = get_config_backend()+ assert backend.poll_one(backend._state(plane.home))+ for rid, (key, value) in enumerate(calls[:1] + calls[2:5]):+ assert "result" in server._methods["config.set"](100 + rid, {"key": key, "value": value, "session_id": "s1"})+ stored = plane.profile("default")["values"]+ assert stored["custom_prompt"] == "synthetic-new-prompt"+ assert stored["display"]["show_reasoning"] is True and stored["display"]["details_mode"] == "expanded"+ assert stored["display"]["sections"]["thinking"] == "expanded"+ assert session["show_reasoning"] is True+ assert all("unset" not in p["body"] for p in plane.patches())+++def test_tui_shared_metrics_set_refuses_a_locked_consent(plane, monkeypatch):+ """Round 4 #6 (same class): the consent setter is explicit too; a locked answer is refused,+ not saved-minus-the-lock while the consent bookkeeping records it."""+ plane.upper = {"telemetry": {"shared_metrics": {"enabled": False, "send": False}}}+ plane.upper_locks = [{"path": "telemetry.shared_metrics", "level": "tenant"}]+ server = _tui_server(monkeypatch, plane.home)+ recorded = []+ from hermes_cli import setup as setup_mod+ monkeypatch.setattr(setup_mod, "_record_send_consent_change", lambda **kw: recorded.append(kw))++ answer = server._methods["shared_metrics.set"](1, {"enabled": True, "send": True})++ assert answer["error"]["code"] == 4002 and "locked" in answer["error"]["message"]+ assert plane.patches() == [] and recorded == []diff --git a/tui_gateway/methods_config_set.py b/tui_gateway/methods_config_set.pyindex ad8979c983a..696eed56c15 100644--- a/tui_gateway/methods_config_set.py+++ b/tui_gateway/methods_config_set.py@@ -18,7 +18,15 @@ _profile_scoped = _registry.profile_scoped# ── shared helpersdef _write_display_sections(*, sections=None, drop_sections=(), **display_fields) -> None:- """Persist ``display.<field>`` + ``display.sections`` edits via the raw (uncached) write-back."""+ """Persist ``display.<field>`` + ``display.sections`` edits via the raw (uncached) write-back.+ Without a config file (remote backend) they are explicit keyed edits, refused as a whole when+ any key is locked (never the bulk save's silent omission of the locked part)."""+ from hermes_cli.config_backend import supports_file_tooling+ if not supports_file_tooling():+ sets = {f"display.{field}": v for field, v in display_fields.items()}+ sets.update({f"display.sections.{name}": v for name, v in (sections or {}).items()})+ _write_config_changes(sets, tuple(f"display.sections.{name}" for name in drop_sections))+ returncfg = _load_cfg_raw()display = cfg.get("display") if isinstance(cfg.get("display"), dict) else {}cur = display.get("sections") if isinstance(display.get("sections"), dict) else {}@@ -96,10 +104,16 @@ def _stash_pending_model_switch(rid, key, value, session, confirmed, parsed):def _cfgset_guarded(fn):- """Setter whose uncaught exception becomes ``_err(rid, 5001, str(e))``."""+ """Setter whose uncaught exception becomes ``_err(rid, 5001, str(e))``. A config backend's+ refusal (locked key, refused value) passes through to ``config.set``'s 4002 answer, like the+ unguarded setters'."""+ from hermes_cli.config_backend import ConfigWriteError+def setter(rid, params, key, value, session):try:return fn(rid, params, key, value, session)+ except ConfigWriteError:+ raiseexcept Exception as e:return _err(rid, 5001, str(e))return setter@@ -449,6 +463,10 @@ def _set_cwd(rid, params, key, value, session):@_cfgset_guardeddef _set_prompt(rid, params, key, value, session):+ from hermes_cli.config_backend import supports_file_tooling+ if not supports_file_tooling(): # one explicit key: refused when locked, never silently dropped+ _write_config_changes({}, ("custom_prompt",)) if value == "clear" else _write_config_changes({"custom_prompt": value})+ return _kv(rid, key, "" if value == "clear" else value)cfg = _load_cfg_raw() # write-back round-tripif value == "clear":cfg.pop("custom_prompt", None)diff --git a/tui_gateway/methods_shared_metrics.py b/tui_gateway/methods_shared_metrics.pyindex 59459469ef7..c8665137aca 100644--- a/tui_gateway/methods_shared_metrics.py+++ b/tui_gateway/methods_shared_metrics.py@@ -61,11 +61,22 @@ def _(rid, params: dict) -> dict:the setup-completed metric. Answers the stored ``{enabled, send, decided, reask}``."""enabled = params.get("enabled") is Truesend = enabled and params.get("send") is True- from hermes_cli.observability.shared_metrics_consent import set_answer+ from hermes_cli.config_backend import ConfigWriteError, supports_file_tooling+ from hermes_cli.observability.shared_metrics_consent import OFFER_VERSION, set_answertry:- cfg = _load_cfg_raw()- set_answer(cfg, enabled, send)- _save_cfg(cfg)+ if supports_file_tooling():+ cfg = _load_cfg_raw()+ set_answer(cfg, enabled, send)+ _save_cfg(cfg)+ else:+ # Explicit keys: refused as a whole when locked, never saved-minus-the-locked-part+ # while the consent bookkeeping below records the proposed answer.+ _write_config_changes({"telemetry.shared_metrics.enabled": enabled,+ "telemetry.shared_metrics.send": send,+ "telemetry.shared_metrics.offer_version": OFFER_VERSION})+ cfg = _load_cfg_raw()+ except ConfigWriteError as e:+ return _err(rid, 4002, str(e))except Exception as e:return _err(rid, 5096, str(e))from hermes_cli.setup import _record_send_consent_changediff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex b86e15dfd2f..a0f5934fba2 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -1347,15 +1347,23 @@ def _append_model_switch_marker(session: dict | None, *, model: str, provider: slogger.warning("failed to persist model switch marker", exc_info=True)+def _write_config_changes(sets: dict, unsets: tuple = ()) -> None:+ """Explicit keyed edits through a config backend without a file (remote): ONE write that sets+ and unsets exactly these dotted keys and refuses a locked one (ConfigLockedError) instead of+ the bulk save's silent omission, so a setter never reports a refused value as saved. Nothing is+ applied when it raises. The file backend keeps its raw round-trip (callers branch on+ ``supports_file_tooling()``)."""+ from hermes_cli.config_backend import Changes, get_config_backend+ try:+ get_config_backend().write_changes(_active_config_path().parent, Changes(set=dict(sets), unset=tuple(unsets)))+ finally:+ _drop_cfg_cache()++def _write_config_key(key_path: str, value):- from hermes_cli.config_backend import Changes, get_config_backend, supports_file_tooling+ from hermes_cli.config_backend import supports_file_toolingif not supports_file_tooling():- # One explicit key: a keyed write, which refuses a locked key (ConfigLockedError) instead- # of the bulk save's silent omission, so the caller never reports a refused value as saved.- try:- get_config_backend().write_changes(_active_config_path().parent, Changes(set={key_path: value}))- finally:- _drop_cfg_cache()+ _write_config_changes({key_path: value})return# Write-back round-trip: raw read is mandatory — saving the overlaid/expanded view would persist it.cfg = current = _load_cfg_raw()diff --git a/website/docs/user-guide/remote-config.md b/website/docs/user-guide/remote-config.mdindex 20e416bd272..ff1ec75e089 100644--- a/website/docs/user-guide/remote-config.md+++ b/website/docs/user-guide/remote-config.md@@ -37,9 +37,13 @@ The agent authenticates as itself:optionally `GATEWAY_RELAY_IDP_SCOPE`.These values, and the `HERMES_CONFIG_*` variables above, must come from-`auth.json`, `.env`, or the process environment. If a `secrets:` source+`auth.json`, a `.env` file (the profile's, the project `.env` a Hermes command+loads, or the managed one), or the process environment. If a `secrets:` source(1Password, Bitwarden, a command) supplies any of them, Hermes refuses to-start.+start. The same holds for `HERMES_PORTAL_BASE_URL`, `NOUS_PORTAL_BASE_URL` and+`HERMES_SHARED_AUTH_DIR` (they decide where the Cloud token is read and sent).+A multi-profile process (gateway, dashboard) that serves a profile whose+`secrets:` source supplies one of these names refuses to serve that profile.A Hermes process started for another profile (a `hermes -p <name>` worker, aprofile's cron or bot child) keeps the `HERMES_CONFIG_*` deployment of the@@ -70,9 +74,10 @@ exits with an error rather than read a local file.undoing the other one. Removing a key removes it from the profile level only:if an upper level also sets it, that value still applies, and Hermes warnsyou.-- **Locked keys are refused.** `hermes config set` (and a single setting- changed in the TUI or desktop app) on a locked key reports which level locks- it and changes nothing. When a whole document is saved, locked keys are left+- **Locked keys are refused.** `hermes config set` (and any setting changed+ in the TUI or desktop app, including the prompt, reasoning display and+ details-mode settings) on a locked key reports which level locks it and+ changes nothing. When a whole document is saved, locked keys are leftout, and Hermes prints a note listing them.- **Secrets stay out of the plane.** A secret-shaped key such as `api_key`accepts only a `${VAR}` reference, never the secret itself. Put the value in@@ -87,7 +92,10 @@ exits with an error rather than read a local file.- **Schema migrations run in memory.** A document written by an older Hermes ismigrated when it is read, and the result is not written back. A later writefrom a newer Hermes keeps the profile's stored schema version unless that- data is already current, so every later reader still migrates it. For the+ data is already current, so every later reader still migrates it. These+ in-memory migrations change only the config document: steps that also+ tidy local files (removing a retired section from `SOUL.md`, clearing old+ values from `.env`) do not run in remote mode. For thesame reason, setting a value that one of those migrations rewrites (forexample `compression.threshold_tokens: 256000`, an old default, on a profilestored at an older schema) is refused with a message naming the key: it would