The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(config-remote): adapt the remote backend to the seam as merged in #134362
Ben Barclaye4374020bd7f
diff --git a/gateway/config_loader.py b/gateway/config_loader.pyindex 26832e61638..e251c24f024 100644--- a/gateway/config_loader.py+++ b/gateway/config_loader.py@@ -552,3 +552,14 @@ def load_yaml_layer(home: Path, gw_data: dict) -> None:apply_plugin_yaml_hooks(yaml_cfg, gateway_platforms, platforms_data, registry,warned=warned, authored=authored, managed_extra=managed_extra, entries=entries)bridge_core_env_settings(yaml_cfg, platforms_data)+++def load_gateway_config_file(gateway_config_file: str):+ """``gateway --config <file>``: a ``GatewayConfig`` from an explicit local YAML file. Refused+ when the config backend has no file tooling (Remote Config: config comes only from the plane)."""+ import hermes_yaml as yaml+ from gateway.config import GatewayConfig+ from hermes_cli.config_backend import require_file_tooling+ require_file_tooling("gateway --config <file>")+ with open(gateway_config_file, encoding="utf-8-sig") as f:+ return GatewayConfig.from_dict(yaml.safe_load(f) or {})diff --git a/gateway/run.py b/gateway/run.pyindex aacf33b94f6..94b141951b6 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -44,7 +44,6 @@ from agent.message_metadata import ABSORBED_MESSAGE_UIDS, MESSAGE_UID, copy_idenfrom agent.turn_context import compression_made_progressfrom agent.session_activity import ActivityProvenance, AwakeIdleMeterfrom hermes_cli.config import _is_ssh_remote_tilde_cwd, cfg_get, config_exists-from hermes_cli.config_backend import require_file_toolingfrom gateway.run_common import _csv_or_list_to_setfrom hermes_cli.fallback_config import pre_agent_fallback_noticefrom gateway.turn_executor import _UnboundedThreadExecutor@@ -5155,10 +5154,8 @@ def main():config = Noneif args.config:- require_file_tooling("gateway --config <file>")- import hermes_yaml as yaml- with open(args.config, encoding="utf-8-sig") as f:- config = GatewayConfig.from_dict(yaml.safe_load(f) or {})+ from gateway.config_loader import load_gateway_config_file+ config = load_gateway_config_file(args.config)# Same boot-time verdict the loaded config gets when the file leaves the flag unset.from hermes_cli.gateway_multiplex_mode import log_multiplex_decision, resolve_multiplex_modelog_multiplex_decision(resolve_multiplex_mode(config))diff --git a/gateway/run_profile_reconcile.py b/gateway/run_profile_reconcile.pyindex db79c2a7d0a..3b13eba5378 100644--- a/gateway/run_profile_reconcile.py+++ b/gateway/run_profile_reconcile.py@@ -33,7 +33,7 @@ from utils import file_cache_versionlogger = logging.getLogger(__name__)_PROFILE_RESCAN_INTERVAL_SECS = 30.0-_PROFILE_SIGNATURE_FILES = ("config.yaml", ".env")+_PROFILE_SIGNATURE_FILES = (".env",) # config.yaml: the config backend's version, below# Bound for one own-gateway liveness probe (``live_gateway_pid_for_home``): the control-socket# read it can end in has no timeout of its own — on Windows the named pipe stalls there until# its peer answers — so the await needs one. A healthy identify answers in milliseconds.@@ -48,10 +48,15 @@ def _stat_signature(path: Path) -> Optional[tuple]:def profile_serve_signature(home: Path) -> tuple:- """Change detector for a served profile's credentials/config: ``file_cache_version`` per file,- hashed every time (``always_digest``): it is compared long after it was taken, and a racy digest- going empty would read as a change and reconnect the profile's adapters."""- sig = []+ """Change detector for a served profile's credentials/config: the config backend's signature+ of its config layer, then ``file_cache_version`` of ``.env``. Each is hashed every time+ (``always_digest``) where it is a file: it is compared long after it was taken, and a racy+ digest going empty would read as a change and reconnect the profile's adapters. A remote layer+ changes with no local file change, so its signature is the backend's version. A config backend+ outage raises ``ConfigBackendUnavailable``; the reconcile cycle contains it and retries."""+ from hermes_cli.config_backend import config_version_or_none, supports_file_tooling+ cfg = Path(home) / "config.yaml"+ sig = [_stat_signature(cfg) if supports_file_tooling() else config_version_or_none(cfg)]for name in _PROFILE_SIGNATURE_FILES:try:sig.append(file_cache_version(Path(home) / name, always_digest=True))diff --git a/hermes_cli/backup.py b/hermes_cli/backup.pyindex bcb2deea56d..2f320944bca 100644--- a/hermes_cli/backup.py+++ b/hermes_cli/backup.py@@ -27,11 +27,12 @@ from hermes_state_holders import read_only_db_urifrom agent.provider_media import GENERATED_SUBDIRfrom hermes_cli.archive_safe import normalize_archive_partsfrom hermes_cli.backup_sqlite import _close_quietly, _safe_copy_db-from hermes_cli.config_backend import require_file_tooling+from hermes_cli.config_backend import require_file_tooling, supports_file_toolingfrom hermes_cli.home_data_layout import PM_RUNTIME_ROOT_DIRS, profile_root_entryfrom hermes_cli.sizefmt import format_bytes as _format_sizefrom hermes_cli.backup_restore import (+ _count_cron_jobs,_count_session_rows,_default_new_file_mode,_detect_prefix,@@ -1675,37 +1676,6 @@ def _restore_quick_snapshot_exclusive(snapshot_id: str, home: Path) -> bool:return restored > 0 and not auth_restore_failed-def _count_cron_jobs(path: Path) -> Optional[int]:- """Return the number of cron jobs stored in ``path``.-- The canonical on-disk shape is ``{"jobs": [...]}`` (see ``cron/jobs.py``).- A legacy bare-list shape (``[...]``) is also honoured.-- Returns:- The job count for any *valid, readable* JSON document, or ``None`` if- the file is missing or cannot be parsed. ``None`` means "unknown" —- callers must not treat it as "zero jobs", because acting on an- unreadable file could mask a real corruption the user needs to see.- """- if not path.is_file():- return None- try:- # utf-8-sig: same dialect as cron/jobs.load_jobs — Windows editors- # may leave a UTF-8 BOM that plain utf-8 json.load rejects. Without- # it a BOM'd jobs.json counts as "unreadable" (None) and the- # post-update cron-loss auto-restore safety net silently disables.- with open(path, "r", encoding="utf-8-sig") as f:- data = json.load(f)- except (OSError, json.JSONDecodeError):- return None- if isinstance(data, dict):- jobs = data.get("jobs", [])- return len(jobs) if isinstance(jobs, list) else None- if isinstance(data, list):- return len(data)- return None--def restore_cron_jobs_if_emptied(snapshot_id: str,hermes_home: Optional[Path] = None,@@ -1907,6 +1877,8 @@ def restore_config_model_settings_if_rewritten("""if not snapshot_id:return None+ if not supports_file_tooling(): # Remote Config: never write a LOCAL snapshot's values to the plane+ return Nonehome = hermes_home or get_hermes_home()live_path = home / "config.yaml"diff --git a/hermes_cli/backup_restore.py b/hermes_cli/backup_restore.pyindex b7eada137f5..c0e262de41a 100644--- a/hermes_cli/backup_restore.py+++ b/hermes_cli/backup_restore.py@@ -676,3 +676,34 @@ def _set_config_path_value(data: dict[str, Any], dotted: tuple[str, ...], value:node[key] = childnode = childnode[dotted[-1]] = value+++def _count_cron_jobs(path: Path) -> Optional[int]:+ """Return the number of cron jobs stored in ``path``.++ The canonical on-disk shape is ``{"jobs": [...]}`` (see ``cron/jobs.py``).+ A legacy bare-list shape (``[...]``) is also honoured.++ Returns:+ The job count for any *valid, readable* JSON document, or ``None`` if+ the file is missing or cannot be parsed. ``None`` means "unknown" —+ callers must not treat it as "zero jobs", because acting on an+ unreadable file could mask a real corruption the user needs to see.+ """+ if not path.is_file():+ return None+ try:+ # utf-8-sig: same dialect as cron/jobs.load_jobs — Windows editors+ # may leave a UTF-8 BOM that plain utf-8 json.load rejects. Without+ # it a BOM'd jobs.json counts as "unreadable" (None) and the+ # post-update cron-loss auto-restore safety net silently disables.+ with open(path, "r", encoding="utf-8-sig") as f:+ data = json.load(f)+ except (OSError, json.JSONDecodeError):+ return None+ if isinstance(data, dict):+ jobs = data.get("jobs", [])+ return len(jobs) if isinstance(jobs, list) else None+ if isinstance(data, list):+ return len(data)+ return Nonediff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex 590b7ca1da0..a321a898915 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -1047,48 +1047,6 @@ def _validate_fallback_model(fb: Any, issues: list[ConfigIssue]) -> None:suffix=" — fallback will be disabled")-def _container_slots() -> dict[str, str]:- """Dotted key -> ``"list"``/``"mapping"`` for every slot the schema fixes to a container:- ``DEFAULT_CONFIG`` (sections included) plus the known-container table for roots it omits."""- slots: dict[str, str] = {}-- def walk(node: dict[str, Any], prefix: str) -> None:- for key, value in node.items():- path = f"{prefix}.{key}" if prefix else key- if isinstance(value, dict):- slots[path] = "mapping"- walk(value, path)- elif isinstance(value, list):- slots[path] = "list"-- walk(DEFAULT_CONFIG, "")- slots.update(_KNOWN_CONTAINER_TYPES)- return slots---def _validate_quoted_containers(config: dict[str, Any], issues: list[ConfigIssue]) -> None:- """A container slot holding ONE quoted string (``enabled: '["a","b"]'``) is skipped by every- isinstance-gated reader while ``config get`` echoes it back, so plugins silently unmount and- exclusions silently lapse (#83308, #105706). Finding only — the file is never rewritten."""- for key, kind in _container_slots().items():- # ``parse_config_string_list`` readers accept the quoted form; nothing is ignored there.- if key in _SCALAR_AS_ONE_ITEM_LIST_KEYS:- continue- value = cfg_get(config, *key.split("."))- if not isinstance(value, str) or not _looks_structured_value(value):- continue- try:- parsed = yaml.safe_load(value)- except yaml.YAMLError:- continue- if isinstance(parsed, (list, dict)):- _issue(issues, "warning",- f"{key} is the quoted string {value!r} — Hermes expects a YAML {kind} here "- "and every reader ignores the string",- f"Run: hermes config set {key} {shlex.quote(value)} (stores a real {kind}), "- "or remove the quotes in config.yaml")--def validate_config_structure(config: Optional[dict[str, Any]] = None) -> list[ConfigIssue]:"""Validate config.yaml structure and return detected issues (accepts a pre-loaded dict).Catches common YAML mistakes that otherwise surface as confusing runtime errors."""@@ -1099,7 +1057,8 @@ def validate_config_structure(config: Optional[dict[str, Any]] = None) -> list[Cfrom hermes_cli.config_home import config_load_issuereturn [config_load_issue(exc)]- from hermes_cli.config_value_checks import _validate_timezone, _validate_voice, _validate_web_backends+ from hermes_cli.config_value_checks import (+ _validate_quoted_containers, _validate_timezone, _validate_voice, _validate_web_backends)issues: list[ConfigIssue] = []_validate_voice(config, issues)_validate_timezone(config, issues)@@ -1181,7 +1140,8 @@ def _persist_migration(config: dict[str, Any]) -> None:persist values that DIFFER from the schema default, plus explicit removals/renames of userdata. Every migration step MUST write through here (``save_config`` with default-strippingON, no ``merge_existing``) so the invariant cannot regress one migration at a time. A migration- is Hermes' own write, never a user turning a feature off."""+ is Hermes' own write, never a user turning a feature off. A backend without file tooling+ migrates in memory on read and never writes back (D12)."""from hermes_cli.observability.shared_metrics_disabled import hermes_applied_writeif not supports_file_tooling():@@ -2923,8 +2883,12 @@ def edit_config():if is_managed():managed_error("edit configuration")return+ if not supports_file_tooling():+ print("`hermes config edit` opens the local config file, and this config backend has none. "+ "Use `hermes config set <key> <value>` instead.", file=sys.stderr)+ returnconfig_path = get_config_path()- if not config_path.exists(): # config-reader: ok — file tooling (edits the local file)+ if not config_path.exists(): # config-reader: ok — file tooling, gated on supports_file_tooling()seed_config_file(config_path)print(f"Created {config_path}")diff --git a/hermes_cli/config_backend.py b/hermes_cli/config_backend.pyindex e2904e6b45b..31429095656 100644--- a/hermes_cli/config_backend.py+++ b/hermes_cli/config_backend.py@@ -1,4 +1,4 @@-"""Where the user config layer lives: the ``ConfigBackend`` seam (config-config design §4.1, D10).+"""Where the user config layer lives: the ``ConfigBackend`` seam (config-config design §4.1, D10/D11).Every read and write of a profile's user ``config.yaml`` goes through the backend returned by:func:`get_config_backend` (``scripts/check_config_yaml_readers.py`` and@@ -28,6 +28,7 @@ from pathlib import Pathfrom typing import Any, Mapping, Optional, Protocol, Union, runtime_checkableCONFIG_FILENAME = "config.yaml"+BACKEND_ENV = "HERMES_CONFIG_BACKEND"PathLike = Union[str, "os.PathLike[str]"]@@ -336,6 +337,16 @@ def _route(config_path: PathLike) -> tuple[ConfigBackend, Path]:return _ExplicitFile(path), path.parent+def local_file_layer(config_path: PathLike) -> tuple[ConfigBackend, Path]:+ """``(backend, home)`` for the LOCAL file at *config_path*, whichever backend is selected.++ Only for PM's dependency runtime: it publishes plugin selections to the local file and+ compare-and-swaps those bytes, and it carries neither the remote backend's client nor the+ plane credential. Everything else goes through :func:`_route`."""+ path = Path(config_path)+ return _ExplicitFile(path), path.parent++def read_config_doc(config_path: PathLike) -> Any:"""Parsed root of a config file (None when empty); raises like ``open`` + ``fast_safe_load``."""backend, home = _route(config_path)@@ -471,8 +482,8 @@ def write_changes(config_path: PathLike, changes: Changes) -> None:"""One :class:`Changes` write. Unlike :func:`write_config_keys`, a ``None`` in ``set`` storesan explicit null (Remote Config: "no value", masking an inherited scalar); the file backendwrites it as YAML null."""- backend, target, is_layer = _route(config_path)- backend.write_changes(target, changes) if is_layer else backend.write_path(target, changes)+ backend, home = _route(config_path)+ backend.write_changes(home, changes)def deployment_env_names() -> frozenset:diff --git a/hermes_cli/config_backups.py b/hermes_cli/config_backups.pyindex a776f4eb297..0fd922aee46 100644--- a/hermes_cli/config_backups.py+++ b/hermes_cli/config_backups.py@@ -46,9 +46,13 @@ def backup_config(config_path: Path, reason: str, *, keep: int = DEFAULT_KEEP) -Skips when the file is missing/empty, or when the newest backup for *reason* already holdsidentical bytes. Never raises: a failed backup must not block the write it precedes.+ Skipped entirely for a config backend without file tooling (no local copies, D2)."""+ from hermes_cli.config_backend import supports_file_tooling+ if not supports_file_tooling():+ return Nonetry:- if not config_path.is_file() or config_path.stat().st_size == 0: # config-reader: ok — file tooling (copies the local file)+ if not config_path.is_file() or config_path.stat().st_size == 0: # config-reader: ok — file tooling, gated abovereturn Noneroot = backups_dir(config_path)root.mkdir(parents=True, exist_ok=True)@@ -56,12 +60,12 @@ def backup_config(config_path: Path, reason: str, *, keep: int = DEFAULT_KEEP) -existing = list_config_backups(config_path, reason)# Not filecmp.cmp: its process-wide cache keys on (size, mtime), so an equal-size edit# within one mtime tick of an earlier comparison is reported identical and never backed up.- if existing and config_path.read_bytes() == existing[0].read_bytes(): # config-reader: ok — file tooling (copies the local file)+ if existing and config_path.read_bytes() == existing[0].read_bytes(): # config-reader: ok — file tooling, gated abovereturn Nonedest = root / f"{config_path.name}.{reason}.{time.strftime('%Y%m%d-%H%M%S')}"if dest.is_symlink() or dest.exists(): # never write through a planted linkreturn None- shutil.copy2(config_path, dest) # config-reader: ok — file tooling (copies the local file)+ shutil.copy2(config_path, dest) # config-reader: ok — file tooling, gated abovefor stale in [dest, *existing][keep:]:stale.unlink(missing_ok=True)return dest@@ -77,6 +81,9 @@ def load_newest_good_backup(config_path: Path) -> Optional[dict]:tried: a backup that fails to parse means the on-disk copy was damaged after the fact, andguessing further back would serve a config the user never saw as current."""+ from hermes_cli.config_backend import supports_file_tooling+ if not supports_file_tooling():+ return Nonenewest = list_config_backups(config_path, "good")[:1]if not newest:return Nonediff --git a/hermes_cli/config_value_checks.py b/hermes_cli/config_value_checks.pyindex 14c5bd5ad83..738e988c684 100644--- a/hermes_cli/config_value_checks.py+++ b/hermes_cli/config_value_checks.py@@ -73,3 +73,50 @@ def _validate_web_backends(config: dict[str, Any], issues: list[ConfigIssue]) ->f"web.{_key} is set to '{_val}', but {note} — ""web_search/web_extract will fail until it is changed","Run 'hermes tools' and pick a different Web Search & Extract provider")+++def _container_slots() -> dict[str, str]:+ """Dotted key -> ``"list"``/``"mapping"`` for every slot the schema fixes to a container:+ ``DEFAULT_CONFIG`` (sections included) plus the known-container table for roots it omits."""+ from hermes_cli.config import _KNOWN_CONTAINER_TYPES, DEFAULT_CONFIG # late: the facade imports this module+ slots: dict[str, str] = {}++ def walk(node: dict[str, Any], prefix: str) -> None:+ for key, value in node.items():+ path = f"{prefix}.{key}" if prefix else key+ if isinstance(value, dict):+ slots[path] = "mapping"+ walk(value, path)+ elif isinstance(value, list):+ slots[path] = "list"++ walk(DEFAULT_CONFIG, "")+ slots.update(_KNOWN_CONTAINER_TYPES)+ return slots+++def _validate_quoted_containers(config: dict[str, Any], issues: list[ConfigIssue]) -> None:+ """A container slot holding ONE quoted string (``enabled: '["a","b"]'``) is skipped by every+ isinstance-gated reader while ``config get`` echoes it back, so plugins silently unmount and+ exclusions silently lapse (#83308, #105706). Finding only — the file is never rewritten."""+ import shlex++ import hermes_yaml as yaml+ from hermes_cli.config import _SCALAR_AS_ONE_ITEM_LIST_KEYS, _looks_structured_value, cfg_get+ for key, kind in _container_slots().items():+ # ``parse_config_string_list`` readers accept the quoted form; nothing is ignored there.+ if key in _SCALAR_AS_ONE_ITEM_LIST_KEYS:+ continue+ value = cfg_get(config, *key.split("."))+ if not isinstance(value, str) or not _looks_structured_value(value):+ continue+ try:+ parsed = yaml.safe_load(value)+ except yaml.YAMLError:+ continue+ if isinstance(parsed, (list, dict)):+ _issue(issues, "warning",+ f"{key} is the quoted string {value!r} — Hermes expects a YAML {kind} here "+ "and every reader ignores the string",+ f"Run: hermes config set {key} {shlex.quote(value)} (stores a real {kind}), "+ "or remove the quotes in config.yaml")diff --git a/hermes_cli/doctor_config.py b/hermes_cli/doctor_config.pyindex 934616ea2e8..ab79fd608f9 100644--- a/hermes_cli/doctor_config.py+++ b/hermes_cli/doctor_config.py@@ -366,7 +366,7 @@ def _check_config_backend(backend, home, f: Finding) -> bool:"""Remote mode (§4.7): report where config comes from instead of the file checks, and flag amanaged /etc/hermes/config.yaml, which remote mode ignores (D18)."""try:- backend.read_user_layer(home)+ backend.read_user_doc(home)check_ok(f"Config backend: {backend.describe(home)}")except SystemExit as exc: # ConfigBackendUnavailable: the plane cannot serve this profilecheck_fail(f"Config backend {backend.name!r} unavailable", str(exc.code or ""))diff --git a/hermes_cli/profile_distribution.py b/hermes_cli/profile_distribution.pyindex 007b2f41964..d488d06fd18 100644--- a/hermes_cli/profile_distribution.py+++ b/hermes_cli/profile_distribution.py@@ -539,6 +539,8 @@ def _copy_dist_payload(staged: Path, target: Path, manifest: DistributionManifesA top-level owned directory, and an owned container (``_is_container``), is merged perauthored root. ``cron/jobs.json`` is special: it is one multi-record runtime store, soshipped definitions merge by job id instead of replacing the file."""+ from hermes_cli.config_backend import require_file_tooling+ require_file_tooling("Profile distribution install")target.mkdir(parents=True, exist_ok=True)entries = list(_owned_entries(staged, manifest))_refuse_symlinked_targets(target, entries)diff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.pyindex dd7716e53b3..40cabdd3015 100644--- a/hermes_cli/profiles.py+++ b/hermes_cli/profiles.py@@ -19,7 +19,6 @@ from typing import Dict, List, Optional, Tuplefrom agent.file_safety import HOME_CREDENTIAL_DIRSfrom hermes_cli.archive_safe import archive_root_dirs, make_targz, normalize_archive_parts, safe_extract_targzfrom hermes_cli import config_backend as _config_backend-from hermes_cli.config_backend import config_exists, config_version, require_file_toolingfrom hermes_cli.profiles_config import _migrate_profile_config_if_outdatedfrom hermes_cli.home_data_layout import PM_RUNTIME_ROOT_DIRSfrom hermes_cli.profiles_remove import _rmtree_make_writable, _rmtree_with_retry, wait_profile_unowned@@ -27,7 +26,8 @@ from hermes_constants import (LOCAL_RUNTIME_ROOT_DIRS, PROFILE_ID_RE, clear_named_profile_deleted, mark_named_profile_deleted,named_profile_has_identity, named_profile_is_deleted, named_profile_is_live,)-from hermes_cli.config_backend import config_cache_version, config_cache_version_or_none, config_exists+from hermes_cli.config_backend import (+ config_cache_version, config_cache_version_or_none, config_exists, require_file_tooling)from hermes_cli.profiles_cache import _PROFILE_FILE_CACHE, _cached_profile_readlogger = logging.getLogger(__name__)diff --git a/hermes_cli/web_routers/analytics.py b/hermes_cli/web_routers/analytics.pyindex ae732bcab7f..253e5bb85ca 100644--- a/hermes_cli/web_routers/analytics.py+++ b/hermes_cli/web_routers/analytics.py@@ -41,11 +41,15 @@ async def get_config_raw(profile: Optional[str] = None):process's own profile, which is wrong under the global profile switcher."""def _run():+ from hermes_cli.config_backend import supports_file_tooling+ if not supports_file_tooling():+ # The raw editor shows the file's bytes; a non-file backend has no file.+ raise HTTPException(status_code=409, detail="This config backend has no raw config file")with _profile_scope(profile):path = get_config_path()- if not path.exists(): # config-reader: ok — file tooling (the local file itself)+ if not path.exists(): # config-reader: ok — file tooling (gated above)return {"yaml": "", "path": str(path)}- return {"yaml": path.read_text(encoding="utf-8-sig"), "path": str(path)} # config-reader: ok — file tooling (the local file itself)+ return {"yaml": path.read_text(encoding="utf-8-sig"), "path": str(path)} # config-reader: ok — file tooling (gated above)return await asyncio.to_thread(_run)diff --git a/hermes_cli/xai_retirement.py b/hermes_cli/xai_retirement.pyindex e7fa6bc0587..43a2837f64c 100644--- a/hermes_cli/xai_retirement.py+++ b/hermes_cli/xai_retirement.py@@ -131,8 +131,11 @@ def apply_migration(Unless ``backup=False`` a copy goes to ``backups/config/`` (reason ``pre-migrate-xai``)."""from ruamel.yaml import YAML # local import — avoid hard dep at module load+ from hermes_cli.config_backend import require_file_tooling+ # A type-literal-preserving rewrite of the file itself; a non-file backend has no file.+ require_file_tooling("The xAI model migration")config_path = Path(config_path)- if not config_path.exists(): # config-reader: ok — file tooling (edits the local file)+ if not config_path.exists(): # config-reader: ok — file tooling, gated on supports_file_tooling()raise FileNotFoundError(config_path)unchanged = ApplyResult(file_path=config_path, backup_path=None, issues_resolved=[], config_changed=False)if not issues:@@ -142,7 +145,7 @@ def apply_migration(yaml = YAML(typ="rt")yaml.width = ROUNDTRIP_YAML_WIDTHyaml.preserve_quotes = True- with config_path.open("r", encoding="utf-8-sig") as fh: # config-reader: ok — file tooling (the local file itself)+ with config_path.open("r", encoding="utf-8-sig") as fh: # config-reader: ok — file tooling (gated above)doc = yaml.load(fh)if doc is None:return unchanged@@ -175,5 +178,5 @@ def apply_migration(# 0640 / container installs; a root-run migration must not flip ownership).buf = io.StringIO()yaml.dump(doc, buf)- atomic_write_text(config_path, buf.getvalue(), preserve_mode=True) # config-reader: ok — file tooling (the local file itself)+ atomic_write_text(config_path, buf.getvalue(), preserve_mode=True) # config-reader: ok — file tooling (gated above)return ApplyResult(file_path=config_path, backup_path=backup_path, issues_resolved=resolved, config_changed=True)diff --git a/plugins/config_backends/remote/backend.py b/plugins/config_backends/remote/backend.pyindex d4524f62d80..9f8afadd807 100644--- a/plugins/config_backends/remote/backend.py+++ b/plugins/config_backends/remote/backend.py@@ -436,6 +436,14 @@ class RemoteBackend:return UserLayer(doc=doc, version=version, locks=locks,provenance=f"remote:{client.base_url()} profile={st.profile}")+ def read_user_doc(self, home: Path) -> Any:+ return self.read_user_layer(home).doc++ def probe_readable(self, home: Path) -> None:+ # Readable once this home's layer is fetched; an unreachable plane raises+ # ConfigBackendUnavailable (never an OSError: there is no local file to retry).+ self._state(home)+def read_user_doc_readonly(self, home: Path) -> Any:st = self._state(home)diff --git a/pm/plugins_state.py b/pm/plugins_state.pyindex d6a4a4d5275..278a12b2ee5 100644--- a/pm/plugins_state.py+++ b/pm/plugins_state.py@@ -22,6 +22,20 @@ def _profiles_root() -> Path:return dependency_home_root() / "profiles"+def _selection_readers(config_path: Path):+ """``(version(path), read(path))`` for a home's selection. PM's dependency runtime reads the+ LOCAL file it publishes to and compare-and-swaps (``pm.publication``): it has neither the+ remote config backend's client nor the plane credential, so a remote deployment never fails+ PM closed there. Every other process reads through the selected config backend."""+ from hermes_cli import config_backend+ from pm.runtime import is_runtime++ if not is_runtime():+ return config_backend.config_version, config_backend.read_config_doc+ backend, home = config_backend.local_file_layer(config_path)+ return (lambda _path: backend.version(home)), (lambda _path: backend.read_user_doc(home))++def read_home_selection(home: Path) -> Optional[dict[str, Any]]:"""The plugin/memory selection a home's config.yaml declares (None: no config yet).@@ -29,9 +43,8 @@ def read_home_selection(home: Path) -> Optional[dict[str, Any]]:An unreadable selection raises rather than shrinking the next dependency generation;empty YAML is an explicit empty configuration, as in the CLI loader."""- from hermes_cli.config_backend import config_version, read_config_doc-config_path = home / "config.yaml"+ config_version, read_config_doc = _selection_readers(config_path)# Stat before the YAML stack: a home without config needs none (PM's own runtime tree has none).# Only a missing file means "no config"; a symlink loop or permission error still refuses.try:diff --git a/tests/gateway/test_profile_serve_signature.py b/tests/gateway/test_profile_serve_signature.pyindex f9da5602e7f..64fad313039 100644--- a/tests/gateway/test_profile_serve_signature.py+++ b/tests/gateway/test_profile_serve_signature.py@@ -20,3 +20,24 @@ def test_profile_serve_signature_changes_on_replacement_with_pinned_mtime(tmp_paos.utime(cfg, ns=(st.st_atime_ns, st.st_mtime_ns))assert (cfg.stat().st_mtime_ns, cfg.stat().st_size) == (st.st_mtime_ns, st.st_size)assert profile_serve_signature(tmp_path) != before+++def test_profile_serve_signature_follows_the_config_backend_version(tmp_path, monkeypatch):+ """Remote Config (#122509): a remote layer changes with no local config.yaml change, so the+ signature must come from the config backend's version, not a stat of the local file."""+ from hermes_cli import config_backend++ class _Backend:+ name = "remote"+ version_now = ("etag-1",)++ def version(self, home):+ return self.version_now++ backend = _Backend()+ monkeypatch.setattr(config_backend, "get_config_backend", lambda: backend)+ before = profile_serve_signature(tmp_path)+ assert profile_serve_signature(tmp_path) == before+ backend.version_now = ("etag-2",)+ assert not (tmp_path / "config.yaml").exists()+ assert profile_serve_signature(tmp_path) != beforediff --git a/tests/hermes_cli/test_backup_remote_config.py b/tests/hermes_cli/test_backup_remote_config.pynew file mode 100644index 00000000000..18735e2ccd1--- /dev/null+++ b/tests/hermes_cli/test_backup_remote_config.py@@ -0,0 +1,23 @@+"""The post-update model/MoA safety net in a Remote Config deployment (#122509)."""+from pathlib import Path+++def test_restore_config_model_settings_is_a_no_op_without_file_tooling(tmp_path: Path, monkeypatch):+ """The snapshot is a LOCAL copy, so the net must never write its values into a backend+ without a config file: that would PATCH stale local values into the plane."""+ from hermes_cli import backup, config_backend+ from hermes_cli.backup import create_quick_snapshot, restore_config_model_settings_if_rewritten++ hermes_home = tmp_path / ".hermes"+ hermes_home.mkdir()+ cfg = hermes_home / "config.yaml"+ cfg.write_text("_config_version: 39\nmodel:\n provider: custom\n default: zamba\n", encoding="utf-8")+ snap_id = create_quick_snapshot(label="pre-update", hermes_home=hermes_home, keep=5)+ assert snap_id+ cfg.write_text("_config_version: 39\nmodel:\n provider: deepseek\n", encoding="utf-8")+ writes = []+ monkeypatch.setattr(backup, "supports_file_tooling", lambda: False)+ monkeypatch.setattr(config_backend, "write_config_document", lambda *a, **k: writes.append(a))+ assert restore_config_model_settings_if_rewritten(snap_id, hermes_home=hermes_home) is None+ assert writes == []+ assert "deepseek" in cfg.read_text(encoding="utf-8")diff --git a/tests/hermes_cli/test_config_backend.py b/tests/hermes_cli/test_config_backend.pyindex 17a2d8bc627..ae3d0644320 100644--- a/tests/hermes_cli/test_config_backend.py+++ b/tests/hermes_cli/test_config_backend.py@@ -12,7 +12,8 @@ REPO = Path(__file__).resolve().parents[2]@pytest.fixture-def home(tmp_path):+def home(tmp_path, monkeypatch):+ monkeypatch.delenv(cb.BACKEND_ENV, raising=False)h = tmp_path / "home"h.mkdir()return h@@ -57,6 +58,52 @@ class TestRouting:assert cb.read_config_doc(other) == {"a": 1}+class TestBootstrapSelector:+ """The one bootstrap (``_ensure_bootstrap_env``) keeps the .env selector rules #134362 had in+ ``_dotenv_backend_override``: the launch home's ``.env`` overrides a stale shell value, an+ explicitly empty value resets to ``file``, an absent key leaves the shell value alone."""++ @pytest.fixture(autouse=True)+ def fresh_bootstrap(self, home, monkeypatch):+ from plugins.config_backends import remote+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.delenv("HERMES_CONFIG_INSTANCE_ID", raising=False)+ monkeypatch.setattr(cb, "_BOOTSTRAPPED", False)+ remote._reset_for_tests()+ yield+ remote._reset_for_tests()++ @pytest.mark.parametrize("shell, dotenv, expected", [+ ("remote", "HERMES_CONFIG_BACKEND=file\n", "file"), # stale shell value, .env says file+ ("remote", "HERMES_CONFIG_BACKEND=\n", "file"), # explicit empty value resets+ (None, "HERMES_CONFIG_BACKEND=remote\n", "remote"), # .env-only remote selects remote+ ("remote", "OTHER=1\n", "remote"), # absent key keeps the shell value+ ])+ def test_dotenv_selector(self, home, monkeypatch, shell, dotenv, expected):+ if shell is None:+ monkeypatch.delenv(cb.BACKEND_ENV, raising=False)+ else:+ monkeypatch.setenv(cb.BACKEND_ENV, shell)+ (home / ".env").write_text(dotenv, encoding="utf-8")+ assert cb.get_config_backend().name == expected++ def test_dotenv_backend_override_is_gone(self):+ # One mechanism: the bootstrap replaces #134362's per-call .env override.+ assert not hasattr(cb, "_dotenv_backend_override")+++class TestRemoteBackendShape:++ def test_remote_backend_is_not_a_file_backend(self):+ # probe_config_readable and every FileBackend-typed path must never treat the remote+ # layer as a local file.+ from plugins.config_backends.remote.backend import RemoteBackend+ assert not issubclass(RemoteBackend, cb.FileBackend)+ for member in ("read_user_doc", "read_user_doc_readonly", "version", "exists",+ "probe_readable", "write_changes"):+ assert callable(getattr(RemoteBackend, member, None)), member++class TestFileBackend:def test_missing(self, home):@@ -207,6 +254,26 @@ class TestPipelinesConsultTheBackend:assert "# hand-tuned" in text and "other-model" in text and "kawaii" in text+class TestFileTooling:++ def test_file_backend_allows_it(self, home):+ cb.require_file_tooling("x")++ def test_backend_without_a_file_refuses_it(self, home, monkeypatch):+ class NoFile(cb.FileBackend):+ name = "nofile"++ def supports_file_tooling(self):+ return False+ monkeypatch.setattr(cb, "get_config_backend", NoFile)+ from hermes_cli.config_backups import backup_config+ (home / "config.yaml").write_text("a: 1\n", encoding="utf-8")+ assert backup_config(home / "config.yaml", "test") is None+ with pytest.raises(cb.ConfigBackendUnavailable, match="Profile clone"):+ from hermes_cli.profiles import _resolve_clone_source+ _resolve_clone_source(None)++class TestReaderGate:def _guard(self):diff --git a/tests/plugins/config_backends/test_remote_backend.py b/tests/plugins/config_backends/test_remote_backend.pyindex 9c49015ddf4..9dcb0915fa4 100644--- a/tests/plugins/config_backends/test_remote_backend.py+++ b/tests/plugins/config_backends/test_remote_backend.py@@ -1296,7 +1296,7 @@ def _absent_section_race(plane, monkeypatch):between our read and our first PATCH (so that PATCH gets a 409)."""from plugins.config_backends.remote import clientplane.profile("default").update(values={"display": {"personality": "concise"}}, version=1)- get_config_backend().read_user_layer(plane.home)+ get_config_backend().read_user_doc(plane.home)real_request = client.requestraced = []diff --git a/tests/pm/test_plugins_state_remote_config.py b/tests/pm/test_plugins_state_remote_config.pynew file mode 100644index 00000000000..de10079f3fd--- /dev/null+++ b/tests/pm/test_plugins_state_remote_config.py@@ -0,0 +1,43 @@+"""PM's dependency runtime in a Remote Config deployment (#122509): the runtime has no remote+backend client and no plane credential, so reading a home's plugin selection there must neither+fail closed nor reach for the plane. It reads the local file PM publishes to and CAS-checks."""+import sys++import pytest++from pm import plugins_state+++def remote_home(tmp_path, monkeypatch):+ from hermes_cli import config_backend+ from plugins.config_backends import remote+ home = tmp_path / "home"+ home.mkdir()+ (home / "config.yaml").write_text("plugins:\n enabled: [alpha]\n", encoding="utf-8")+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setenv(config_backend.BACKEND_ENV, "remote")+ monkeypatch.delenv("HERMES_CONFIG_INSTANCE_ID", raising=False)+ monkeypatch.setattr(config_backend, "_BOOTSTRAPPED", True)+ remote._reset_for_tests()+ yield home+ remote._reset_for_tests()+++def test_pm_runtime_reads_the_local_selection_without_the_plane(remote_home, monkeypatch):+ import pm.runtime+ monkeypatch.setattr(pm.runtime, "is_runtime", lambda: True)+ # The runtime cannot import the remote backend at all.+ for name in [m for m in sys.modules if m.startswith("plugins.config_backends.remote")]:+ monkeypatch.delitem(sys.modules, name)+ monkeypatch.setitem(sys.modules, "plugins.config_backends.remote", None)+ assert plugins_state.read_home_selection(remote_home)["plugins"]["enabled"] == ["alpha"]+ assert plugins_state.read_home_selection(remote_home / "absent") is None+++def test_application_process_reads_the_selection_through_the_backend(remote_home):+ # Control: outside PM's runtime the selected (unconfigured) remote backend is consulted and+ # fails closed rather than serving the local file.+ from hermes_cli.config_backend import ConfigBackendUnavailable+ with pytest.raises(ConfigBackendUnavailable):+ plugins_state.read_home_selection(remote_home)diff --git a/website/docs/developer-guide/config-backend.md b/website/docs/developer-guide/config-backend.mdindex 9fab84e0a4d..4a921560f69 100644--- a/website/docs/developer-guide/config-backend.md+++ b/website/docs/developer-guide/config-backend.md@@ -1,17 +1,15 @@---sidebar_position: 12title: "Config Backend Seam"-description: "Where a profile's user config.yaml is read and written: the ConfigBackend seam, its file backend, and the CI lints that keep every caller on it"+description: "Where a profile's user config.yaml is read and written: the ConfigBackend seam, the file and remote backends, and the CI lints that keep every caller on it"---# Config Backend SeamEvery read, stat, existence check and write of a profile's user `config.yaml` goes through-`hermes_cli/config_backend.py`. `get_config_backend()` returns the backend for every home; today-that is `FileBackend`, the local `config.yaml` with exactly the primitives Hermes used before the-seam (stat signature, `fast_safe_load`, the ruamel round-trip writers). A backend that does not-store the layer as a local file implements the same `ConfigBackend` protocol, and every caller-already reaches it.+`hermes_cli/config_backend.py`. The backend is chosen once per process from+`HERMES_CONFIG_BACKEND`, never from a config value: `file` is the default, and `remote` is+[Remote Config](../user-guide/remote-config.md) (`plugins/config_backends/remote/`).## Helpers@@ -19,17 +17,20 @@ already reaches it.|---|---|| `read_config_doc(path)` | Parsed user layer (raises like `open` + `fast_safe_load`) || `read_config_doc_readonly(path)` | Signature-cached read; never mutate the result |-| `config_version(path)` | Change signature (the file's stat tuple) |-| `config_cache_version(path)` (`config_cache_version_or_none`) | Signature for a cache of the parse: the stat tuple plus a content digest while the later of mtime and ctime is younger than `utils.RACY_MTIME_WINDOW_NS` (`utils.file_cache_version` on the file backend) |-| `config_exists(path)` | Whether the layer exists |-| `probe_config_readable(path)` | Raise `OSError` while the layer cannot be read (no parse) |+| `config_version(path)` | Change signature (the file's stat tuple, or the remote version) |+| `config_cache_version(path)` (`config_cache_version_or_none`) | Signature for a cache of the parse: the stat tuple plus a content digest while the later of mtime and ctime is younger than `utils.RACY_MTIME_WINDOW_NS` (`utils.file_cache_version` on the file backend); the remote version on the remote backend |+| `config_exists(path)` | Whether the layer exists (a remote layer always does) |+| `config_version_or_none(path)` / `version_token(version)` | The version, or None when absent; a number that changes with it (TUI/session `mtime`) |+| `probe_config_readable(path)` | Raise `OSError` while the layer cannot be read (no parse); a remote backend raises `ConfigBackendUnavailable` while the plane cannot serve it || `write_config_document(path, doc)` / `write_config_key(path, key, value)` | Writes; callers normally use `atomic_config_write` / `atomic_config_replace` |+| `supports_file_tooling()` / `require_file_tooling(what)` | Gate for tools that copy, edit or back up the file itself (`config edit`, backup/restore, profile clone) |Only `<home>/config.yaml` is a user layer. Any other file passed to these helpers (an import-source, a fixture) is read and written where it is. A cache of a parse keys on-`config_cache_version`, not `config_version`: on kernels without multigrain timestamps a same-size-in-place rewrite in the tick of a read keeps mtime, ctime, size and inode, so the stat tuple alone-pins the older parse for the life of the process (a rotated `api_key` is the usual casualty).+source, a fixture) is read and written where it is, whichever backend is selected. A cache of a+parse keys on `config_cache_version`, not `config_version`: on kernels without multigrain+timestamps a same-size in-place rewrite in the tick of a read keeps mtime, ctime, size and inode,+so the stat tuple alone pins the older parse for the life of the process (a rotated `api_key` is+the usual casualty).Any other file a cache derives from (`auth.json`, pairing lists, `.env`, token files, the managedoverlay) keys on `utils.file_cache_version(path)`; a signature stored and compared much later (achange detector whose false positive reconnects something, a parse-failure record) passes@@ -52,5 +53,5 @@ as one CAS write, so a lock on any of them refuses all of them.- `scripts/check_config_yaml_writers.py` rejects a direct YAML dump of a config path.- `scripts/check_config_yaml_readers.py` rejects a direct `open` / `read_text` / `stat` /`exists` / YAML load of a config path. A true false positive (another product's config- file, or a tool that copies or edits the local file itself: `config edit`, backups, profile- clone) carries `# config-reader: ok — <why>` on the line.+ file, or file tooling already gated on `supports_file_tooling()`) carries+ `# config-reader: ok — <why>` on the line.diff --git a/website/docs/reference/environment-variables.md b/website/docs/reference/environment-variables.mdindex aba60dadc4e..e805642b719 100644--- a/website/docs/reference/environment-variables.md+++ b/website/docs/reference/environment-variables.md@@ -119,6 +119,7 @@ Hermes reads environment variables from the process environment and, for user-ma| `HERMES_LOCAL_STT_COMMAND` | Optional local speech-to-text command template. Supports `{input_path}`, `{output_dir}`, `{language}`, and `{model}` placeholders || `HERMES_LOCAL_STT_LANGUAGE` | Default language hint for STT. Used by the `local` (faster-whisper) provider, `HERMES_LOCAL_STT_COMMAND`, the local `whisper` CLI fallback (default: `en`), Groq, and xAI when no per-provider `language` is set in `config.yaml` || `HERMES_HOME` | Select the configuration and user-data home. A literal `~` or `$VAR` in the value is expanded (fish does not expand `~` inside `VAR=~/…`), so it never resolves relative to the current directory. Defaults to `~/.hermes` on POSIX and `%LOCALAPPDATA%\hermes` on Windows; the official Docker image uses `/opt/data`. Profile/runtime context can select a more specific home. |+| `HERMES_CONFIG_BACKEND` | Select where the profile's `config.yaml` user layer is read and written. `file` (the default) is the local `config.yaml`; `remote` is [Remote Config](../user-guide/remote-config.md). Any other value, or a remote backend that cannot serve config, stops Hermes at startup with an error instead of falling back to defaults. An explicitly empty value in a `.env` resets a stale shell value to `file`. Read from the launch environment, the launch home's `.env` and the managed `.env`, never from `config.yaml`. See [Config backend](../developer-guide/config-backend.md). || `HERMES_DISABLE_WINDOWS_UTF8` | **Windows only.** Set to `1` to disable the UTF-8 stdio shim (`configure_windows_stdio()`) and fall back to the console's locale code page. Useful for bisecting encoding bugs; rarely the right setting in normal operation || `HERMES_KANBAN_HOME` | Override the shared Hermes root that anchors the kanban board (db + workspaces + worker logs). Falls back to `get_default_hermes_root()` (the parent of any active profile). Useful for tests and unusual deployments || `HERMES_KANBAN_BOARD` | Pin the active kanban board for this process. Takes precedence over `~/.hermes/kanban/current`; the dispatcher injects this into worker subprocess env so workers physically cannot see tasks on other boards. Defaults to `default`. Slug validation: lowercase alphanumerics + hyphens + underscores, 1-64 chars |