The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(config): remote config backend (HERMES_CONFIG_BACKEND=remote)
Ben Barclay69d037b34976
diff --git a/cli.py b/cli.pyindex 450160cc885..b0b717d13a8 100644--- a/cli.py+++ b/cli.py@@ -1049,6 +1049,9 @@ class HermesCLI(CLIInitMixin, CLITuiRuntimeMixin, CLIProcessNotificationsMixin,if not config_exists(config_path):config_path = Path(__file__).parent / 'cli-config.yaml'config_status = _t("cli.config.loaded") if config_exists(config_path) else _t("cli.config.not_found")+ from hermes_cli.config_backend import get_config_backend+ if not get_config_backend().supports_file_tooling(): # no local file: name where config comes from+ config_path, config_status = get_config_backend().describe(_hermes_home), ""# ``api_key`` may be a callable bearer provider (Entra ID, Vertex OAuth, key_cmd, ...):# label it by its tagged source and never invoke it (that would mint a token just to maskdiff --git a/docker/stage2-hook.sh b/docker/stage2-hook.shindex c3404961bca..78a1cad77b0 100755--- a/docker/stage2-hook.sh+++ b/docker/stage2-hook.sh@@ -640,7 +640,17 @@ fi# config-schema migrations that `hermes update` runs for non-Docker installs,# after first-boot seeding and before supervised gateway services start.# Set HERMES_SKIP_CONFIG_MIGRATION=1 for controlled/manual migrations.-if [ -f "$HERMES_HOME/config.yaml" ]; then+# Remote config mode (HERMES_CONFIG_BACKEND=remote, in the container env or $HERMES_HOME/.env) has+# no local config to migrate: the agent migrates the fetched document in memory and never writes+# it back, so a leftover config.yaml must not be migrated or treated as live.+_remote_config_mode=0+if [ "${HERMES_CONFIG_BACKEND:-}" = "remote" ] \+ || grep -Eqs '^[[:space:]]*(export[[:space:]]+)?HERMES_CONFIG_BACKEND=["'"'"']?remote["'"'"']?[[:space:]]*$' "$HERMES_HOME/.env"; then+ _remote_config_mode=1+fi+if [ "$_remote_config_mode" = "1" ]; then+ echo "[stage2] HERMES_CONFIG_BACKEND=remote: skipping docker_config_migrate.py"+elif [ -f "$HERMES_HOME/config.yaml" ]; thens6-setuidgid hermes "$INSTALL_DIR/.venv/bin/python" "$INSTALL_DIR/scripts/docker_config_migrate.py" \|| echo "[stage2] Warning: docker_config_migrate.py failed; continuing"fidiff --git a/gateway/run.py b/gateway/run.pyindex 6ee7a7dc87d..6efb375623c 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -5154,6 +5154,8 @@ def main():config = Noneif args.config:+ from hermes_cli.config_backend import require_file_tooling+ require_file_tooling("gateway --config <file>")import hermes_yaml as yamlwith open(args.config, encoding="utf-8-sig") as f:config = GatewayConfig.from_dict(yaml.safe_load(f) or {})diff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex d6c2bc5c482..2d6493235a7 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -47,8 +47,8 @@ from hermes_constants import get_hermes_home, get_process_hermes_homefrom utils import atomic_replace, fast_safe_load, file_cache_version, file_signature, mkstemp_besidefrom hermes_cli.config_issues import ConfigIssue, _issuefrom hermes_cli.config_backend import (- config_cache_version, config_exists, config_version, probe_config_readable, read_config_doc,- write_config_document)+ ConfigWriteError, config_cache_version, config_exists, config_version, get_config_backend,+ probe_config_readable, read_config_doc, supports_file_tooling, write_config_document)from hermes_cli.config_read_errors import (_CONFIG_PARSE_FAILURES, _FIX_PERMS, _FIX_YAML, FailedConfigRead, _backups_dir_display,_refuse_failed_read, _refuse_overwrite, _warn_config_parse_failure, _yaml_error_details,@@ -1183,6 +1183,9 @@ def _persist_migration(config: dict[str, Any]) -> None:is Hermes' own write, never a user turning a feature off."""from hermes_cli.observability.shared_metrics_disabled import hermes_applied_write+ if not supports_file_tooling():+ get_config_backend().apply_in_memory(get_config_path().parent, config)+ returnwith hermes_applied_write():save_config(config)@@ -3272,6 +3275,11 @@ def _exit_if_key_managed(key: str, action: str) -> None:f"Cannot {action} '{key}': it is managed by your administrator ({_managed_source('config.yaml')}) "f"and cannot be changed. Contact your administrator to modify it.", file=sys.stderr)sys.exit(1)+ level = get_config_backend().locked(get_config_path().parent, key) # remote locks, prefix-aware (D7)+ if level:+ print(f"Cannot {action} '{key}': it is locked by the {level} level of Remote Config and cannot be "+ "changed from this agent.", file=sys.stderr)+ sys.exit(1)def _touch_skin_file(key: str, value: Any) -> None:@@ -3743,7 +3751,11 @@ def config_command(args):subcmd = getattr(args, 'config_command', None)handler = _CONFIG_SUBCOMMANDS.get(subcmd)if handler is not None:- handler(args)+ try:+ handler(args)+ except ConfigWriteError as exc: # a backend refusal (a remote lock, a secret literal): nothing changed+ print(f"Error: {exc}", file=sys.stderr)+ sys.exit(1)returnprint(f"Unknown config command: {subcmd}")print()diff --git a/hermes_cli/config_backend.py b/hermes_cli/config_backend.pyindex 22834e361f0..7a2a80e9eb5 100644--- a/hermes_cli/config_backend.py+++ b/hermes_cli/config_backend.py@@ -6,11 +6,12 @@ Every read and write of a profile's user ``config.yaml`` goes through the backenthe hermes home (profile): one multiplexed process serves N profiles, and every config cachealready keys on the config path, so a backend keeps per-home state.-:class:`FileBackend` is the only backend and is today's behaviour byte for byte:+:class:`FileBackend` (the default) is today's behaviour byte for byte:the version is the ``file_signature`` stat tuple, reads are ``open`` + ``fast_safe_load`` and raiseexactly what those raise (``FileNotFoundError`` for an absent file, ``OSError``, YAML errors), andwrites are the ruamel round-trip writers in ``utils``. Callers keep their own error handling, so a-backend whose layer always exists simply never takes the "no file" branches.+backend whose layer always exists simply never takes the "no file" branches. The remote backend+(``HERMES_CONFIG_BACKEND=remote``) lives in ``plugins/config_backends/remote/``.The managed scope (``/etc/hermes``) is NOT a backend concern: it stays an overlay applied on top ofwhatever user layer the backend returns.@@ -69,6 +70,68 @@ class ConfigBackend(Protocol):def write_changes(self, home: Path, changes: Changes) -> None: ...+ def locked(self, home: Path, dotted: str) -> Optional[str]:+ """The level that locks ``dotted`` (prefix-aware), or None."""+ ...++ def supports_file_tooling(self) -> bool:+ """Whether tools that copy/edit/back up the config FILE (profile clone, backup/restore,+ ``config edit``, last-known-good backups, ``migrate_config`` write-back) may run."""+ ...++ def honors_managed_config(self) -> bool:+ """Whether the managed ``/etc/hermes/config.yaml`` overlay applies (D18: not in remote mode)."""+ ...++ def boot(self, home: Path) -> None:+ """Called once per ``load_hermes_dotenv`` after the ``.env`` loads and before the first+ config read (design §4.4): a backend that fetches config does it here, failing closed."""+ ...++ def protected_env_names(self) -> frozenset:+ """Env names no external secret source may supply (the plane credential, D32)."""+ ...++ def apply_in_memory(self, home: Path, doc: dict) -> None:+ """Replace the user layer in memory only (in-memory migration, D12). Only called for a+ backend without file tooling; nothing is sent or written."""+ ...++ def describe(self, home: Path) -> str:+ """One line naming where the user layer comes from and its state (status line, doctor)."""+ ...+++class ConfigBackendUnavailable(SystemExit):+ """The selected backend cannot serve config. A ``SystemExit`` on purpose: many config readers+ fail open with ``except Exception`` → defaults, and serving defaults instead of the selected+ backend's config is exactly the silent failure this must not become."""+++class ConfigWriteError(RuntimeError):+ """A config write the backend refused or could not complete; nothing was changed. ``code`` is+ a machine code (the plane's ``error`` for a remote refusal)."""++ def __init__(self, message: str, *, code: str = "config_write_failed") -> None:+ super().__init__(message)+ self.code = code+++class ConfigLockedError(ConfigWriteError):+ """The write touches a path locked by an upper level (D7, D10)."""++ def __init__(self, path: str, locked_by: str, message: Optional[str] = None) -> None:+ super().__init__(message or f"{path} is locked by the {locked_by} level", code="config_key_locked")+ self.path = path+ self.locked_by = locked_by+++class ConfigValueError(ConfigWriteError):+ """A value the backend cannot store (a YAML-only type, a secret literal); nothing was sent."""++ def __init__(self, message: str, *, code: str = "config_value_invalid") -> None:+ super().__init__(message, code=code)+class FileBackend:"""The user layer is ``<home>/config.yaml`` on local disk."""@@ -133,13 +196,46 @@ class FileBackend:def write_changes(self, home: Path, changes: Changes) -> None:self.write_path(self.config_path(home), changes)+ def locked(self, home: Path, dotted: str) -> Optional[str]:+ return None # a local file has no levels; the managed scope is a separate overlay++ def supports_file_tooling(self) -> bool:+ return True++ def honors_managed_config(self) -> bool:+ return True++ def boot(self, home: Path) -> None:+ return None++ def protected_env_names(self) -> frozenset:+ return frozenset()++ def apply_in_memory(self, home: Path, doc: dict) -> None:+ raise NotImplementedError("the file backend persists migrations to config.yaml")++ def describe(self, home: Path) -> str:+ return str(self.config_path(home))+_FILE_BACKEND = FileBackend()def get_config_backend() -> ConfigBackend:- """The backend serving every home's user layer: the file backend, the only one there is."""- return _FILE_BACKEND+ """The backend selected by ``HERMES_CONFIG_BACKEND`` (default ``file``).++ Read from the environment on every call, before any config read, so no config value can+ select it (D11). Raises :class:`ConfigBackendUnavailable` for a backend this build lacks.+ """+ kind = os.environ.get(BACKEND_ENV, "").strip().lower() or "file"+ if kind == "file":+ return _FILE_BACKEND+ if kind == "remote":+ # Imported directly, never through the general plugin loader (which reads config, D11).+ from plugins.config_backends.remote import get_remote_backend+ return get_remote_backend()+ raise ConfigBackendUnavailable(+ f"{BACKEND_ENV}={kind!r} is not a config backend (expected 'file' or 'remote').")class _ExplicitFile(FileBackend):diff --git a/hermes_cli/doctor_config.py b/hermes_cli/doctor_config.pyindex 041e9fe7113..934616ea2e8 100644--- a/hermes_cli/doctor_config.py+++ b/hermes_cli/doctor_config.py@@ -338,11 +338,15 @@ def _validate_auxiliary_config(config_path, issues: list) -> None:@doctor_check()def _check_config_file(should_fix: bool, f: Finding) -> None:"""config.yaml presence (project cli-config.yaml as fallback); model/provider validation."""- from hermes_cli.config_backend import config_exists+ from hermes_cli.config_backend import config_exists, get_config_backendfrom hermes_cli.doctor import HERMES_HOME, PROJECT_ROOT, _DHHconfig_path = HERMES_HOME / 'config.yaml'+ backend = get_config_backend()+ if not backend.supports_file_tooling() and not _check_config_backend(backend, HERMES_HOME, f):+ returnif config_exists(config_path):- check_ok(f"{_DHH}/config.yaml exists")+ if backend.supports_file_tooling():+ check_ok(f"{_DHH}/config.yaml exists")with warn_on_error("Could not validate model/provider config"):_validate_model_config(config_path, f.issues)with warn_on_error("Could not validate auxiliary task routing"):@@ -358,6 +362,24 @@ def _check_config_file(should_fix: bool, f: Finding) -> None:check_warn("config.yaml not found", "(using defaults)")+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 a+ managed /etc/hermes/config.yaml, which remote mode ignores (D18)."""+ try:+ backend.read_user_layer(home)+ check_ok(f"Config backend: {backend.describe(home)}")+ except SystemExit as exc: # ConfigBackendUnavailable: the plane cannot serve this profile+ check_fail(f"Config backend {backend.name!r} unavailable", str(exc.code or ""))+ f.issues.append(f"Config backend {backend.name!r} cannot serve config for {home}")+ return False+ from plugins.config_backends.remote.backend import managed_config_file+ managed = managed_config_file() if backend.name == "remote" else None+ if managed is not None:+ check_warn(f"{managed} exists but is ignored in remote config mode", "(remove it)")+ f.issues.append(f"Remove {managed}: remote config mode takes config and locks only from Remote Config")+ return True++def _drift_config_version(f: Finding, should_fix: bool, config_path) -> None:from hermes_cli.config import check_config_version, migrate_configcurrent_ver, latest_ver = check_config_version()diff --git a/hermes_cli/env_loader.py b/hermes_cli/env_loader.pyindex 36c0e694dfb..01f5eebe998 100644--- a/hermes_cli/env_loader.py+++ b/hermes_cli/env_loader.py@@ -591,6 +591,14 @@ def load_hermes_dotenv(if os.environ.get(name) != value:os.environ[name] = value+ # The config backend is selected here — after the .env files, before the first config.yaml read+ # (``_apply_external_secret_sources`` reads ``secrets:``) — so an unavailable backend stops the+ # process before any reader could fall back to defaults (config-config design §4.4, D11/D32). A+ # remote backend fetches this home's config here, failing closed; the file backend does nothing.+ from hermes_cli.config_backend import get_config_backend++ get_config_backend().boot(home_path)+# External sources are skipped for the updater (dotenv + managed env still load): ``update`` must not# import optional secret-manager libs (Bitwarden → cryptography → _rust.pyd) into the process replacing# that env on Windows, and a fresh retry after a deferred dependency install would otherwise make the@@ -693,6 +701,26 @@ 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) -> None:+ """D32: the config backend's own credential (which plane, which agent, which token) must never+ come 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."""+ from hermes_cli.config_backend import ConfigBackendUnavailable, get_config_backend++ protected = get_config_backend().protected_env_names()+ if not protected:+ return+ supplied = set(report.provenance)+ for src in report.sources:+ supplied.update(getattr(src, "skipped_existing", ()) or ())+ clash = sorted(supplied & protected)+ if clash:+ raise ConfigBackendUnavailable(+ f"A secrets: source supplies {', '.join(clash)}, which the {get_config_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.")++def _apply_external_secret_sources(home_path: Path) -> None:"""Pull secrets from every enabled external source into env — AFTER dotenv (sources need .env bootstraptokens), BEFORE Hermes reads credentials; failures never block startup. Precedence/conflicts/provenance@@ -746,6 +774,7 @@ def _apply_external_secret_sources(home_path: Path) -> None:if not report.sources: # no source enabled: keep retrying cheaply so flipping one on takes effectreturn+ _refuse_protected_env_from_sources(report)# A real fetch attempt happened (success OR error): mark the home so the 3-5 import-time calls per# startup don't re-fetch / re-print (error retries are opt-in via reset_secret_source_cache()).diff --git a/hermes_cli/managed_scope.py b/hermes_cli/managed_scope.pyindex e47edea25f1..78d03f4b2fe 100644--- a/hermes_cli/managed_scope.py+++ b/hermes_cli/managed_scope.py@@ -105,7 +105,12 @@ def _load_managed_file(name: str, cache: dict[str, tuple], parse) -> dict:def load_managed_config() -> dict:- """Parsed managed config.yaml, or {} when absent/malformed (fail-open)."""+ """Parsed managed config.yaml, or {} when absent/malformed (fail-open). Always {} under a config+ backend that takes config and locks from elsewhere (remote mode, D18; boot warns about the file)."""+ from hermes_cli.config_backend import get_config_backend++ if not get_config_backend().honors_managed_config():+ return {}return _load_managed_file("config.yaml", _CONFIG_CACHE, lambda p: fast_safe_load(p.read_text(encoding="utf-8-sig")) or {})diff --git a/hermes_cli/plugins_cmd.py b/hermes_cli/plugins_cmd.pyindex a57c74acb86..82055e85679 100644--- a/hermes_cli/plugins_cmd.py+++ b/hermes_cli/plugins_cmd.py@@ -882,11 +882,11 @@ def _discover_all_plugins() -> list:in ``PluginManager.discover_and_load`` order: bundled, user, then entry points — which neverdisplace a directory plugin of the same key (see ``PluginManager._discover_and_load_inner``)."""seen: dict = {}- # memory/, context_engine/, computer_use/ and model-providers/ load through dedicated registries, not the- # PluginManager opt-in surface, so listing them as toggleable plugins would mislead.+ # memory/, context_engine/, computer_use/, model-providers/ and config_backends/ load through dedicated+ # paths, not the PluginManager opt-in surface, so listing them as toggleable plugins would mislead.from hermes_cli.plugins import discover_entrypoint_manifests, get_bundled_plugins_dirfor base, source, skip in (- (get_bundled_plugins_dir(), "bundled", {"memory", "context_engine", "computer_use", "model-providers"}),+ (get_bundled_plugins_dir(), "bundled", {"memory", "context_engine", "computer_use", "model-providers", "config_backends"}),(_plugins_dir(), "user", set()),):_scan_level(base, source, skip, "", 0, seen)diff --git a/hermes_cli/plugins_discovery.py b/hermes_cli/plugins_discovery.pyindex ffa552531b6..852e667d2d3 100644--- a/hermes_cli/plugins_discovery.py+++ b/hermes_cli/plugins_discovery.py@@ -205,7 +205,7 @@ def collect_directory_manifests() -> list[PluginManifest]:repo_plugins = _origin.get_bundled_plugins_dir()logger.debug("Scanning bundled plugins: %s", repo_plugins)_scan("bundled (top-level)", repo_plugins, "bundled",- {"memory", "context_engine", "model-providers", "cron_providers", "computer_use"})+ {"memory", "context_engine", "model-providers", "cron_providers", "computer_use", "config_backends"})user_dir = get_hermes_home() / "plugins"logger.debug("Scanning user plugins: %s", user_dir)_scan("user", user_dir, "user")diff --git a/plugins/config_backends/__init__.py b/plugins/config_backends/__init__.pynew file mode 100644index 00000000000..d6159f4004d--- /dev/null+++ b/plugins/config_backends/__init__.py@@ -0,0 +1,4 @@+"""Config backends (``HERMES_CONFIG_BACKEND``). Selected by ``hermes_cli.config_backend``+directly from the environment, never discovered through the general plugin loader: that loader+reads config.yaml, and the backend is what serves config.yaml (D11). User plugins cannot supply a+config backend."""diff --git a/plugins/config_backends/remote/__init__.py b/plugins/config_backends/remote/__init__.pynew file mode 100644index 00000000000..7ecf128cb0d--- /dev/null+++ b/plugins/config_backends/remote/__init__.py@@ -0,0 +1,32 @@+"""Remote config backend: ``HERMES_CONFIG_BACKEND=remote`` serves each profile's config from the+config plane (config-config) instead of ``config.yaml``. See ``backend.py``."""+from __future__ import annotations++import threading+from typing import Optional++from .backend import RemoteBackend++_BACKEND: Optional[RemoteBackend] = None+_LOCK = threading.Lock()+++def get_remote_backend() -> RemoteBackend:+ """The process-wide instance (one poller and one in-memory layer per profile home)."""+ global _BACKEND+ if _BACKEND is None:+ with _LOCK:+ if _BACKEND is None:+ _BACKEND = RemoteBackend()+ return _BACKEND+++def _reset_for_tests() -> None:+ global _BACKEND+ with _LOCK:+ if _BACKEND is not None:+ _BACKEND._stop.set()+ _BACKEND = None+++__all__ = ["RemoteBackend", "get_remote_backend"]diff --git a/plugins/config_backends/remote/backend.py b/plugins/config_backends/remote/backend.pynew file mode 100644index 00000000000..cc8b5ef3716--- /dev/null+++ b/plugins/config_backends/remote/backend.py@@ -0,0 +1,487 @@+"""The remote config backend (config-config design §4, contract.md §11, §15).++The user layer of each profile home is the effective document the config plane resolves for+(this instance, that profile). It lives in memory only: fetched at boot (fail closed, D2), kept+fresh by a per-process ETag poller (D9), and written back as key-level changes on the profile+level with CAS (D10). Nothing is read from or written to a local ``config.yaml``.+"""+from __future__ import annotations++import copy+import logging+import os+import random+import sys+import threading+import time+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any, Dict, List, Optional, Tuple++from hermes_cli.config_backend import (+ Changes, ConfigBackendUnavailable, ConfigLockedError, ConfigValueError, ConfigWriteError, UserLayer)++from . import client+from .credentials import PLANE_CREDENTIAL_ENV_NAMES, PlaneCredentialError+from .diff import diff, encode_changes, strip_locked, write_check+from .paths import Path as KeyPath+from .paths import PathError, decode, encode, from_dotted+from .values import secret_literal_path, to_wire++logger = logging.getLogger(__name__)++POLL_ENV = "HERMES_CONFIG_REMOTE_POLL_SECONDS"+DEFAULT_POLL_SECONDS = 300.0+MIN_POLL_SECONDS = 30.0 # contract §11.3: lower values are clamped+BOOT_RETRY_DELAYS = (10.0, 20.0) # contract §11.4: attempts at t = 0, ~10 s, ~30 s+MAX_RETRY_WAIT = 20.0+++def poll_interval() -> float:+ try:+ value = float(os.environ.get(POLL_ENV, "") or DEFAULT_POLL_SECONDS)+ except ValueError:+ value = DEFAULT_POLL_SECONDS+ return max(value, MIN_POLL_SECONDS)+++def _latest_config_version() -> int:+ from hermes_cli.config_defaults import DEFAULT_CONFIG+ version = DEFAULT_CONFIG.get("_config_version")+ return version if isinstance(version, int) else 1+++class _FetchFailed(Exception):+ def __init__(self, detail: str, *, retryable: bool, retry_after: Optional[float] = None,+ status: Optional[int] = None) -> None:+ super().__init__(detail)+ self.retryable = retryable+ self.retry_after = retry_after+ self.status = status+++@dataclass+class _ProfileState:+ home: Path+ profile: str+ server_config: Dict[str, Any] = field(default_factory=dict) # EffectiveResponse.config, as sent+ doc: Dict[str, Any] = field(default_factory=dict) # what readers get (+ _config_version, migrated)+ etag: str = ""+ profile_version: int = 0+ locks: List[Tuple[KeyPath, str]] = field(default_factory=list)+ provenance: Dict[str, str] = field(default_factory=dict)+ changed_ns: int = 0+ gen: int = 0+ postprocessed: bool = False+ in_postprocess: bool = False+ fetched_at: float = 0.0+ last_error: Optional[str] = None+ next_poll: float = 0.0+ lock: threading.RLock = field(default_factory=threading.RLock)+++def _effective_ok(body: Dict[str, Any]) -> bool:+ return (isinstance(body.get("config"), dict) and isinstance(body.get("profileVersion"), int)+ and isinstance(body.get("locks"), list))+++class RemoteBackend:+ name = "remote"++ def __init__(self) -> None:+ self._states: Dict[str, _ProfileState] = {}+ self._fetch_locks: Dict[str, threading.Lock] = {}+ self._lock = threading.Lock()+ self._poller: Optional[threading.Thread] = None+ self._poller_pid: Optional[int] = None+ self._stop = threading.Event()+ self._managed_warned = False+ self._unknown_warned: set = set()++ # --- homes and state --------------------------------------------------------------------++ @staticmethod+ def _key(home: Path) -> str:+ from hermes_constants import hermes_home_key+ return hermes_home_key(home)++ @staticmethod+ def _profile_for(home: Path) -> str:+ from hermes_constants import PROFILE_ID_RE, profile_name_for_home+ name = profile_name_for_home(home)+ if not name or not PROFILE_ID_RE.match(name):+ raise ConfigBackendUnavailable(+ f"Remote Config: {home} is not a Hermes profile home, so it has no remote config "+ "(HERMES_CONFIG_BACKEND=remote serves profile homes only).")+ return name++ def _state(self, home: Path) -> _ProfileState:+ key = self._key(home)+ st = self._states.get(key)+ if st is not None:+ return st+ with self._lock:+ fetch_lock = self._fetch_locks.setdefault(key, threading.Lock())+ with fetch_lock:+ st = self._states.get(key)+ if st is None:+ st = self._initial_fetch(Path(home))+ self._states[key] = st+ self._ensure_poller()+ return st++ def _initial_fetch(self, home: Path) -> _ProfileState:+ """Boot fetch with bounded retry (contract §11.4); fails closed (D2)."""+ profile = self._profile_for(home)+ if not client.instance_id():+ raise ConfigBackendUnavailable(+ f"Remote Config: {client.INSTANCE_ENV} is not set, so Hermes cannot identify this agent "+ "to the config plane. Hermes does not start without its remote config.")+ st = _ProfileState(home=home, profile=profile)+ delays = list(BOOT_RETRY_DELAYS)+ while True:+ try:+ self._fetch_into(st, conditional=False)+ return st+ except _FetchFailed as exc:+ if exc.retryable and delays:+ wait = min(max(exc.retry_after or 0.0, delays.pop(0)), MAX_RETRY_WAIT)+ logger.warning("Remote Config: fetch for profile %r failed (%s); retrying in %.0fs",+ profile, exc, wait)+ time.sleep(wait)+ continue+ raise ConfigBackendUnavailable(+ f"Remote Config: cannot load the config for profile {profile!r} from "+ f"{client.base_url()}: {exc}. Hermes does not start without its remote config "+ "(HERMES_CONFIG_BACKEND=remote has no local fallback).") from exc++ def _fetch_into(self, st: _ProfileState, *, conditional: bool) -> bool:+ """GET ``/self`` into ``st``; True when the document changed. Raises :class:`_FetchFailed`."""+ try:+ resp = client.request("GET", st.home, st.profile, etag=st.etag if conditional else None)+ except PlaneCredentialError as exc:+ raise _FetchFailed(str(exc), retryable=exc.retryable) from exc+ except client.TransportError as exc:+ raise _FetchFailed(str(exc), retryable=True) from exc+ if resp.status == 304 and conditional:+ st.fetched_at, st.last_error = time.time(), None+ return False+ if resp.status == 200 and _effective_ok(resp.body):+ with st.lock:+ self._install(st, resp.body, resp.etag)+ return True+ if resp.status == 200:+ raise _FetchFailed("the plane returned a malformed response", retryable=True)+ retryable = resp.status >= 500 or resp.status == 429+ raise _FetchFailed(f"HTTP {resp.status} {resp.error}: {resp.message}", retryable=retryable,+ retry_after=resp.retry_after, status=resp.status)++ def _install(self, st: _ProfileState, body: Dict[str, Any], etag: Optional[str]) -> None:+ config = body["config"]+ doc = copy.deepcopy(config)+ doc.pop("_config_version", None) # reserved on the wire (§3.6); never expected here+ # R6: the in-memory schema version is the oldest writer's; migrations run in memory (D12).+ writer_versions: List[int] = [+ lv["writerConfigVersion"] for lv in body.get("levels") or []+ if isinstance(lv, dict) and isinstance(lv.get("writerConfigVersion"), int)]+ doc["_config_version"] = min(writer_versions) if writer_versions else _latest_config_version()+ locks: List[Tuple[KeyPath, str]] = []+ for entry in body.get("locks") or []:+ try:+ locks.append((decode(entry["path"]), str(entry["level"])))+ except (KeyError, TypeError, PathError):+ logger.warning("Remote Config: ignoring malformed lock entry %r", entry)+ st.server_config = config+ st.doc = doc+ st.etag = etag or str(body.get("etag") or "")+ st.profile_version = int(body["profileVersion"])+ st.locks = locks+ st.provenance = dict(body.get("provenance") or {})+ st.changed_ns = time.time_ns()+ st.gen += 1+ st.postprocessed = False+ st.fetched_at, st.last_error = time.time(), None+ st.next_poll = time.monotonic() + poll_interval() * random.uniform(0.9, 1.1)++ def _postprocess(self, st: _ProfileState) -> None:+ """First read after a change: warn on unknown keys and migrate in memory (D12). Runs on a+ read, not at fetch, because both need ``hermes_cli.config``, which may still be importing+ when the boot fetch runs."""+ if st.postprocessed or st.in_postprocess:+ return+ with st.lock:+ if st.postprocessed or st.in_postprocess:+ return+ st.in_postprocess = True+ try:+ from hermes_cli.config import _known_top_level_keys+ from hermes_cli.config_migrations import SUPPORT_FLOOR_VERSION, run_migrations+ except ImportError:+ st.in_postprocess = False+ return # still importing; the next read retries+ try:+ for key in sorted(set(st.doc) - _known_top_level_keys() - {"_config_version"}):+ if key not in self._unknown_warned:+ self._unknown_warned.add(key)+ logger.warning("Remote Config: unknown config key %r is ignored by this Hermes version", key)+ current, latest = int(st.doc.get("_config_version") or 0), _latest_config_version()+ if SUPPORT_FLOOR_VERSION <= current < latest:+ self._migrate_in_memory(st, current, run_migrations)+ elif current < SUPPORT_FLOOR_VERSION:+ logger.warning("Remote Config: profile %r was written by config version %d, below the "+ "migration floor %d; not migrated", st.profile, current, SUPPORT_FLOOR_VERSION)+ st.postprocessed = True+ finally:+ st.in_postprocess = False++ def _migrate_in_memory(self, st: _ProfileState, current: int, run_migrations) -> None:+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override+ token = set_hermes_home_override(st.home)+ try:+ run_migrations(current, {"env_added": [], "config_added": [], "warnings": []}, True)+ finally:+ reset_hermes_home_override(token)+ doc = copy.deepcopy(st.doc)+ doc["_config_version"] = _latest_config_version()+ self.apply_in_memory(st.home, doc)+ logger.info("Remote Config: migrated profile %r in memory from config version %d", st.profile, current)++ # --- ConfigBackend: reads ---------------------------------------------------------------++ def read_user_layer(self, home: Path) -> UserLayer:+ st = self._state(home)+ self._postprocess(st)+ return UserLayer(doc=copy.deepcopy(st.doc), version=self._version_of(st),+ locks={encode(p): level for p, level in st.locks},+ provenance=f"remote:{client.base_url()} profile={st.profile}")++ def read_user_doc_readonly(self, home: Path) -> Any:+ st = self._state(home)+ self._postprocess(st)+ return st.doc++ @staticmethod+ def _version_of(st: _ProfileState) -> Tuple[Any, ...]:+ # Leads with a nanosecond timestamp like the file backend's st_mtime_ns (the TUI's config+ # watcher reads element 0 as a time); the etag and local generation make it exact.+ return (st.changed_ns, st.etag, st.gen)++ def version(self, home: Path) -> Tuple[Any, ...]:+ return self._version_of(self._state(home))++ def exists(self, home: Path) -> bool:+ return True # the plane always resolves a document (an absent level is empty, contract R4)++ def locked(self, home: Path, dotted: str) -> Optional[str]:+ path = from_dotted(dotted)+ for lock, level in self._state(home).locks:+ if len(lock) <= len(path) and tuple(path[:len(lock)]) == lock:+ return level+ return None++ # --- ConfigBackend: writes --------------------------------------------------------------++ def write_changes(self, home: Path, changes: Changes) -> None:+ st = self._state(home)+ with st.lock:+ for attempt in (1, 2):+ built = self._build_patch(st, changes)+ if built is None:+ return+ body, unsets = built+ try:+ resp = client.request("PATCH", st.home, st.profile, body=body)+ except (PlaneCredentialError, client.TransportError) as exc:+ raise ConfigWriteError(f"Remote Config write failed: {exc}", code="config_plane_unreachable") from exc+ if resp.status == 200 and _effective_ok(resp.body):+ self._install(st, resp.body, resp.etag)+ self._warn_inherited(st, unsets)+ return+ if resp.status == 409 and attempt == 1:+ try: # contract §15.3: re-read, re-diff, retry once+ self._fetch_into(st, conditional=False)+ except _FetchFailed as exc:+ raise ConfigWriteError(f"Remote Config write conflict and re-read failed: {exc}",+ code="config_version_conflict") from exc+ continue+ raise self._write_error(resp)++ def _build_patch(self, st: _ProfileState, changes: Changes) -> Optional[Tuple[Dict[str, Any], List[KeyPath]]]:+ """The PATCH body for ``changes`` against the last read (§15.2), or None for no change."""+ base = copy.deepcopy(st.server_config)+ if changes.document is not None:+ new = to_wire(copy.deepcopy(changes.document))+ if not isinstance(new, dict):+ raise ConfigValueError("the config document must be a mapping")+ else:+ new = copy.deepcopy(base)+ for key, value in changes.set.items():+ path = from_dotted(key)+ _set_path(new, path, to_wire(value, path))+ for key in changes.unset:+ _pop_path(new, from_dotted(key))+ base.pop("_config_version", None)+ new.pop("_config_version", None)++ if changes.document is not None:+ base, new, dropped = strip_locked(base, new, st.locks)+ 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)+ sets, unsets = diff(base, new)+ refused = write_check(sets, unsets, st.locks)+ if refused is not None:+ raise ConfigLockedError(encode(refused[0]), refused[1],+ f"{encode(refused[0])} is locked by the {refused[1]} level of Remote Config")+ for p, v in sets.items():+ bad = secret_literal_path(p, v)+ if bad is not None:+ raise ConfigValueError(+ f"{encode(bad)} is a secret-shaped key: Remote Config stores only a ${{VAR}} reference "+ "there, never the secret itself. Put the value in .env and set a ${VAR} reference.",+ code="config_secret_literal")+ if not sets and not unsets:+ return None+ set_body, unset_body = encode_changes(sets, unsets)+ body: Dict[str, Any] = {"expectedVersion": st.profile_version,+ "writerConfigVersion": _latest_config_version()}+ if set_body:+ body["set"] = set_body+ if unset_body:+ body["unset"] = unset_body+ return body, unsets++ @staticmethod+ def _write_error(resp: client.Response) -> ConfigWriteError:+ if resp.status == 403 and resp.error == "config_key_locked":+ return ConfigLockedError(str(resp.body.get("path") or ""), str(resp.body.get("lockedBy") or "upper"),+ f"Remote Config refused the write: {resp.message}")+ if resp.status == 400 and resp.error == "config_secret_literal":+ return ConfigValueError(f"Remote Config refused the write: {resp.message}", code=resp.error)+ return ConfigWriteError(f"Remote Config refused the write ({resp.status} {resp.error}): {resp.message}",+ code=resp.error)++ @staticmethod+ def _warn_inherited(st: _ProfileState, unsets: List[KeyPath]) -> None:+ """R5: removing a key at the profile level cannot remove a value an upper level supplies."""+ for p in unsets:+ node: Any = st.server_config+ for seg in p:+ if not isinstance(node, dict) or seg not in node:+ break+ node = node[seg]+ else:+ logger.warning("Remote Config: %s is still set by an upper level; removing it from this "+ "profile cannot remove an inherited value (set it to null for 'no value')",+ encode(p))++ def apply_in_memory(self, home: Path, doc: dict) -> None:+ st = self._state(home)+ with st.lock:+ st.doc = copy.deepcopy(doc)+ st.changed_ns = time.time_ns()+ st.gen += 1++ # --- ConfigBackend: capabilities and boot -----------------------------------------------++ def supports_file_tooling(self) -> bool:+ return False++ def honors_managed_config(self) -> bool:+ return False++ def protected_env_names(self) -> frozenset:+ return PLANE_CREDENTIAL_ENV_NAMES++ def boot(self, home: Path) -> None:+ """Design §4.4 steps 2-4: fetch this home's layer (fail closed) and flag a managed file."""+ self._state(home)+ if not self._managed_warned:+ self._managed_warned = True+ path = managed_config_file()+ if path is not None:+ msg = (f"WARNING: {path} exists but is IGNORED: HERMES_CONFIG_BACKEND=remote takes config "+ "and locks only from Remote Config (D18). Remove the file.")+ logger.warning(msg)+ print(msg, file=sys.stderr)++ def describe(self, home: Path) -> str:+ st = self._states.get(self._key(home))+ head = f"Remote Config {client.base_url()} (instance {client.instance_id() or '<unset>'})"+ if st is None:+ return f"{head}: profile not fetched yet"+ age = int(time.time() - st.fetched_at) if st.fetched_at else -1+ tail = f", last poll failed: {st.last_error}" if st.last_error else ""+ return (f"{head}: profile {st.profile!r}, profile level v{st.profile_version}, "+ f"{len(st.locks)} lock(s), fetched {age}s ago{tail}")++ # --- poller (D9) ------------------------------------------------------------------------++ def _ensure_poller(self) -> None:+ with self._lock:+ if self._poller is not None and self._poller.is_alive() and self._poller_pid == os.getpid():+ return+ self._poller_pid = os.getpid() # a forked child re-arms its own thread+ self._poller = threading.Thread(target=self._poll_loop, name="remote-config-poll", daemon=True)+ self._poller.start()++ def _poll_loop(self) -> None:+ while not self._stop.is_set():+ now = time.monotonic()+ states = list(self._states.values())+ due = [st for st in states if st.next_poll <= now]+ for st in due:+ self.poll_one(st)+ wake = min((st.next_poll for st in self._states.values()), default=now + poll_interval())+ self._stop.wait(max(1.0, wake - time.monotonic()))++ def poll_one(self, st: _ProfileState) -> bool:+ """One conditional GET (contract §11.3). Never raises and never exits: an error keeps the+ in-memory document and is retried next tick."""+ try:+ changed = self._fetch_into(st, conditional=True)+ except _FetchFailed as exc:+ st.last_error = str(exc)+ # contract §11.3: a refused credential needs an operator; anything else is a blip.+ level = logging.ERROR if exc.status in (401, 403) else logging.WARNING+ logger.log(level, "Remote Config: poll for profile %r failed (%s); keeping the loaded config",+ st.profile, exc)+ changed = False+ except Exception as exc: # noqa: BLE001 — the poller thread must survive anything+ st.last_error = str(exc)+ logger.warning("Remote Config: poll for profile %r failed", st.profile, exc_info=True)+ changed = False+ st.next_poll = time.monotonic() + poll_interval() * random.uniform(0.9, 1.1)+ if changed:+ logger.info("Remote Config: profile %r changed (profile level v%d)", st.profile, st.profile_version)+ return changed++ def poll_all(self) -> None:+ for st in list(self._states.values()):+ self.poll_one(st)+++def managed_config_file() -> Optional[Path]:+ from hermes_cli import managed_scope+ managed_dir = managed_scope.get_managed_dir()+ path = managed_dir / "config.yaml" if managed_dir else None+ if path is None:+ return None+ return path if path.exists() else None # config-reader: ok — existence only, to warn it is ignored (D18)+++def _set_path(doc: Dict[str, Any], path: KeyPath, 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: KeyPath) -> None:+ node: Any = doc+ for seg in path[:-1]:+ node = node.get(seg) if isinstance(node, dict) else None+ if isinstance(node, dict):+ node.pop(path[-1], None)diff --git a/plugins/config_backends/remote/client.py b/plugins/config_backends/remote/client.pynew file mode 100644index 00000000000..c95e78cf48c--- /dev/null+++ b/plugins/config_backends/remote/client.py@@ -0,0 +1,96 @@+"""HTTP client for the agent routes of the config plane (contract.md §7.1, §7.2).++Plain HTTP (D9), stdlib only: it runs inside ``load_hermes_dotenv`` before most of Hermes is+imported. Every request re-resolves the bearer (contract §10.2).+"""+from __future__ import annotations++import json+import os+import urllib.error+import urllib.parse+import urllib.request+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Dict, Optional++from .credentials import plane_token++DEFAULT_URL = "https://config-config.nousresearch.com"+URL_ENV = "HERMES_CONFIG_REMOTE_URL"+INSTANCE_ENV = "HERMES_CONFIG_INSTANCE_ID"+_HTTP_TIMEOUT_S = 15.0+++@dataclass(frozen=True)+class Response:+ status: int+ body: Dict[str, Any]+ etag: Optional[str]+ retry_after: Optional[float]++ @property+ def error(self) -> str:+ return str(self.body.get("error") or f"http_{self.status}")++ @property+ def message(self) -> str:+ return str(self.body.get("message") or f"HTTP {self.status}")+++class TransportError(RuntimeError):+ """The request never produced an HTTP response (DNS, connect, TLS, timeout)."""+++def base_url() -> str:+ return (os.environ.get(URL_ENV, "").strip() or DEFAULT_URL).rstrip("/")+++def instance_id() -> str:+ return os.environ.get(INSTANCE_ENV, "").strip()+++def _parse_body(raw: bytes) -> Dict[str, Any]:+ if not raw:+ return {}+ try:+ data = json.loads(raw.decode("utf-8"))+ except ValueError:+ return {}+ return data if isinstance(data, dict) else {}+++def _retry_after(value: Optional[str]) -> Optional[float]:+ try:+ return float(value) if value else None+ except ValueError:+ return None+++def request(method: str, home: Path, profile: str, *, etag: Optional[str] = None,+ body: Optional[Dict[str, Any]] = None) -> Response:+ """One call to ``/v1/config/self?profile=<profile>`` as ``home``'s agent."""+ url = f"{base_url()}/v1/config/self?{urllib.parse.urlencode({'profile': profile})}"+ headers = {+ "Authorization": f"Bearer {plane_token(home)}",+ "X-Hermes-Instance-Id": instance_id(),+ "Accept": "application/json",+ }+ data = None+ if body is not None:+ data = json.dumps(body, separators=(",", ":"), ensure_ascii=False).encode("utf-8")+ headers["Content-Type"] = "application/json"+ if etag:+ headers["If-None-Match"] = etag+ req = urllib.request.Request(url, data=data, method=method, headers=headers)+ try:+ with urllib.request.urlopen(req, timeout=_HTTP_TIMEOUT_S) as resp:+ return Response(resp.status, _parse_body(resp.read()), resp.headers.get("ETag"),+ _retry_after(resp.headers.get("Retry-After")))+ except urllib.error.HTTPError as exc: # every non-2xx, including 304+ with exc:+ raw = exc.read() if exc.fp is not None else b""+ return Response(exc.code, _parse_body(raw), exc.headers.get("ETag") if exc.headers else None,+ _retry_after(exc.headers.get("Retry-After") if exc.headers else None))+ except (urllib.error.URLError, OSError, TimeoutError) as exc:+ raise TransportError(f"{method} {url}: {getattr(exc, 'reason', exc)}") from excdiff --git a/plugins/config_backends/remote/credentials.py b/plugins/config_backends/remote/credentials.pynew file mode 100644index 00000000000..ec088a40c7b--- /dev/null+++ b/plugins/config_backends/remote/credentials.py@@ -0,0 +1,112 @@+"""The plane credential (design §4.4 step 2, D26, D31, D32).++Cloud: the Nous access token from the profile's ``auth.json`` (``resolve_nous_access_token``).+On-prem: an IdP workload token from the OAuth2 client-credentials grant, configured by+``GATEWAY_RELAY_IDP_*`` values in ``.env``. Never from config.yaml (the config is what this token+fetches) and never from a secret source: :data:`PLANE_CREDENTIAL_ENV_NAMES` lists every env name+that decides which token is sent where, and boot refuses a secret source that supplies one.+"""+from __future__ import annotations++import json+import os+import threading+import time+import urllib.parse+import urllib.request+from pathlib import Path+from typing import Dict, Tuple++IDP_ENV_PREFIX = "GATEWAY_RELAY_IDP_"+_IDP_KEYS = ("token_url", "client_id", "client_secret", "scope")++PLANE_CREDENTIAL_ENV_NAMES = frozenset({+ # which backend, which plane, which agent record+ "HERMES_CONFIG_BACKEND", "HERMES_CONFIG_REMOTE_URL", "HERMES_CONFIG_INSTANCE_ID",+ # on-prem workload identity+ *(IDP_ENV_PREFIX + k.upper() for k in _IDP_KEYS),+ # Cloud: where auth.json lives and where its refresh token is sent+ "HERMES_SHARED_AUTH_DIR", "HERMES_PORTAL_BASE_URL", "NOUS_PORTAL_BASE_URL",+})++_HTTP_TIMEOUT_S = 15.0+++class PlaneCredentialError(RuntimeError):+ """No plane credential could be obtained. ``retryable`` is False for a missing or partial+ configuration (retrying cannot help)."""++ def __init__(self, message: str, *, retryable: bool) -> None:+ super().__init__(message)+ self.retryable = retryable+++_IDP_CACHE: Dict[Tuple[str, str, str], Tuple[float, str]] = {}+_IDP_LOCK = threading.Lock()+++def _idp_env() -> Dict[str, str]:+ return {k: os.environ.get(IDP_ENV_PREFIX + k.upper(), "").strip() for k in _IDP_KEYS}+++def credential_kind() -> str:+ return "idp" if _idp_env()["token_url"] else "nous"+++def plane_token(home: Path) -> str:+ """A fresh bearer for ``home``'s requests (re-resolved per request, contract §10.2)."""+ return _idp_token() if credential_kind() == "idp" else _nous_token(home)+++def _nous_token(home: Path) -> str:+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override++ try:+ from hermes_cli.auth import resolve_nous_access_token+ except Exception as exc: # noqa: BLE001 — an import failure is a broken install, not transient+ raise PlaneCredentialError(f"cannot load the Nous auth module: {exc}", retryable=False) from exc+ token = set_hermes_home_override(home) # auth.json is per profile home+ try:+ return resolve_nous_access_token()+ except Exception as exc: # noqa: BLE001 — AuthError and network errors alike+ # A missing login or a revoked session needs a human; a refresh that hit the network can retry.+ fatal = bool(getattr(exc, "relogin_required", False)) or getattr(exc, "code", None) == "nous_auth_missing"+ raise PlaneCredentialError(+ f"no Nous access token for {home} (auth.json): {exc}", retryable=not fatal) from exc+ finally:+ reset_hermes_home_override(token)+++def _idp_token() -> str:+ env = _idp_env()+ token_url, client_id, client_secret, scope = (env[k] for k in _IDP_KEYS)+ if not client_id or not client_secret:+ raise PlaneCredentialError(+ f"{IDP_ENV_PREFIX}TOKEN_URL is set but {IDP_ENV_PREFIX}CLIENT_ID / {IDP_ENV_PREFIX}CLIENT_SECRET "+ "are not: Remote Config needs the OAuth2 client-credentials grant (both values in .env).",+ retryable=False)+ key = (token_url, client_id, scope)+ now = time.monotonic()+ with _IDP_LOCK:+ cached = _IDP_CACHE.get(key)+ if cached is not None and cached[0] > now:+ return cached[1]+ form = {"grant_type": "client_credentials", "client_id": client_id, "client_secret": client_secret}+ if scope:+ form["scope"] = scope+ req = urllib.request.Request(+ token_url, data=urllib.parse.urlencode(form).encode(), method="POST",+ headers={"Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json"})+ try:+ with urllib.request.urlopen(req, timeout=_HTTP_TIMEOUT_S) as resp:+ payload = json.loads(resp.read().decode() or "{}")+ except Exception as exc: # noqa: BLE001 — HTTP and network errors alike; the message has no secret+ raise PlaneCredentialError(f"IdP token request to {token_url} failed: {exc}", retryable=True) from exc+ access_token = payload.get("access_token") if isinstance(payload, dict) else None+ if not isinstance(access_token, str) or not access_token:+ raise PlaneCredentialError("IdP client-credentials response had no access_token", retryable=True)+ expires_in = payload.get("expires_in")+ ttl = float(expires_in) if isinstance(expires_in, int | float) and expires_in > 0 else 60.0+ with _IDP_LOCK:+ _IDP_CACHE[key] = (now + max(ttl - 30.0, 0.0), access_token)+ return access_tokendiff --git a/plugins/config_backends/remote/diff.py b/plugins/config_backends/remote/diff.pynew file mode 100644index 00000000000..60a8d250382--- /dev/null+++ b/plugins/config_backends/remote/diff.py@@ -0,0 +1,114 @@+"""Remote write computation (contract.md §6.4, §15.2).++Pure functions over JSON-shaped documents; no I/O. The plane runs the authoritative write check;+the agent runs the same check before sending so a locked write fails with a clear message and+nothing goes on the wire.+"""+from __future__ import annotations++import copy+from typing import Any, Dict, Iterator, List, Optional, Sequence, Tuple++from .paths import Path, covers, encode++Locks = Sequence[Tuple[Path, str]]+++def json_equal(a: Any, b: Any) -> bool:+ """Structural JSON equality: numbers by value, but ``True`` is not ``1``."""+ if isinstance(a, bool) or isinstance(b, bool):+ return type(a) is type(b) and a == b+ if isinstance(a, int | float) and isinstance(b, int | float):+ return a == b+ if isinstance(a, dict) and isinstance(b, dict):+ return a.keys() == b.keys() and all(json_equal(a[k], b[k]) for k in a)+ if isinstance(a, list) and isinstance(b, list):+ return len(a) == len(b) and all(json_equal(x, y) for x, y in zip(a, b))+ return type(a) is type(b) and a == b+++def diff(base: Dict[str, Any], new: Dict[str, Any], prefix: Path = ()) -> Tuple[Dict[Path, Any], List[Path]]:+ """``(set, unset)`` turning ``base`` into ``new`` (§15.2 step 5). A changed list is one+ whole-list ``set`` (D8); a key equal to its base value is not sent."""+ sets: Dict[Path, Any] = {}+ unsets: List[Path] = []+ for key, value in new.items():+ p = prefix + (key,)+ if key not in base:+ sets[p] = value+ elif isinstance(base[key], dict) and isinstance(value, dict):+ s, u = diff(base[key], value, p)+ sets.update(s)+ unsets.extend(u)+ elif not json_equal(base[key], value):+ sets[p] = value+ unsets.extend(prefix + (key,) for key in base if key not in new)+ return sets, unsets+++def _pop_path(doc: Dict[str, Any], path: Path) -> bool:+ node: Any = doc+ for seg in path[:-1]:+ if not isinstance(node, dict) or not isinstance(node.get(seg), dict):+ return False+ node = node[seg]+ if isinstance(node, dict) and path[-1] in node:+ del node[path[-1]]+ return True+ return False+++def _get_path(doc: Dict[str, Any], path: Path) -> Tuple[bool, Any]:+ node: Any = doc+ for seg in path:+ if not isinstance(node, dict) or seg not in node:+ return False, None+ node = node[seg]+ return True, node+++def strip_locked(base: Dict[str, Any], new: Dict[str, Any], locks: Locks) -> Tuple[Dict[str, Any], Dict[str, Any], List[Path]]:+ """Drop every locked path from BOTH documents (§15.2 step 1), so a bulk write neither sets+ nor unsets a key it may not touch. Returns the copies and the locked paths whose new value+ differed from the effective one (the ones the caller tried to change)."""+ base, new = copy.deepcopy(base), copy.deepcopy(new)+ changed: List[Path] = []+ for lock, _level in locks:+ in_base, base_val = _get_path(base, lock)+ in_new, new_val = _get_path(new, lock)+ if in_base != in_new or (in_new and not json_equal(base_val, new_val)):+ changed.append(lock)+ _pop_path(base, lock)+ _pop_path(new, lock)+ return base, new, changed+++def _touched(path: Path, value: Any) -> Iterator[Tuple[Path, Any]]:+ """``(touched path, value written there)`` for ``set path = value`` (§6.4 rule 2): the path+ itself and every path inside ``value``, descending through objects only."""+ yield path, value+ if isinstance(value, dict):+ for k, v in value.items():+ yield from _touched(path + (k,), v)+++def write_check(sets: Dict[Path, Any], unsets: Sequence[Path], locks: Locks) -> Optional[Tuple[Path, str]]:+ """The ``(lock path, level)`` that refuses this write (§6.4 rules 1-3), or None."""+ for p in unsets:+ for lock, level in locks:+ if covers(lock, p):+ return lock, level+ for p, v in sets.items():+ for t, tv in _touched(p, v):+ for lock, level in locks:+ if covers(lock, t):+ return lock, level+ # R7: a non-object written at a strict ancestor of a lock would replace the+ # locked subtree through deep merge.+ if len(t) < len(lock) and covers(t, lock) and not isinstance(tv, dict):+ return lock, level+ return None+++def encode_changes(sets: Dict[Path, Any], unsets: Sequence[Path]) -> Tuple[Dict[str, Any], List[str]]:+ return {encode(p): v for p, v in sets.items()}, [encode(p) for p in unsets]diff --git a/plugins/config_backends/remote/paths.py b/plugins/config_backends/remote/paths.pynew file mode 100644index 00000000000..c476a7e4748--- /dev/null+++ b/plugins/config_backends/remote/paths.py@@ -0,0 +1,89 @@+"""Dotted-path grammar of the config plane wire contract (contract.md §3).++A path is a list of mapping keys. On the wire it is one string: each segment escapes ``\\`` as+``\\\\`` and ``.`` as ``\\.``, and segments are joined with ``.``. Coverage (lock matching) is+segment-wise, never a string prefix (§3.4).+"""+from __future__ import annotations++from typing import Iterable, List, Optional, Sequence, Tuple++Path = Tuple[str, ...]+++class PathError(ValueError):+ """An encoded path that does not parse (§3.3)."""+++def encode(segments: Sequence[str]) -> str:+ return ".".join(s.replace("\\", "\\\\").replace(".", "\\.") for s in segments)+++def decode(encoded: str) -> Path:+ segments: List[str] = []+ current: List[str] = []+ i = 0+ while i < len(encoded):+ ch = encoded[i]+ if ch == "\\":+ if i + 1 >= len(encoded) or encoded[i + 1] not in "\\.":+ raise PathError(f"invalid escape in config path {encoded!r}")+ current.append(encoded[i + 1])+ i += 2+ continue+ if ch == ".":+ if not current:+ raise PathError(f"empty segment in config path {encoded!r}")+ segments.append("".join(current))+ current = []+ else:+ current.append(ch)+ i += 1+ if not current:+ raise PathError(f"empty segment in config path {encoded!r}")+ segments.append("".join(current))+ validate(segments, encoded)+ return tuple(segments)+++MAX_SEGMENTS = 32+MAX_SEGMENT_BYTES = 256+MAX_ENCODED_BYTES = 2048+++def validate(segments: Sequence[str], encoded: Optional[str] = None) -> None:+ """§3.1 segment and path limits (the plane rejects violations with ``config_path_invalid``)."""+ shown = encoded if encoded is not None else encode(segments)+ if not 1 <= len(segments) <= MAX_SEGMENTS:+ raise PathError(f"config path {shown!r} must have 1-{MAX_SEGMENTS} segments")+ if len((encoded if encoded is not None else encode(segments)).encode("utf-8")) > MAX_ENCODED_BYTES:+ raise PathError(f"config path is longer than {MAX_ENCODED_BYTES} bytes")+ for seg in segments:+ if not 1 <= len(seg.encode("utf-8")) <= MAX_SEGMENT_BYTES:+ raise PathError(f"config path {shown!r}: a segment must be 1-{MAX_SEGMENT_BYTES} bytes")+ if any(ord(c) < 0x20 or ord(c) == 0x7F for c in seg):+ raise PathError(f"config path {shown!r}: control character in a segment")+ if seg == "__proto__":+ raise PathError(f"reserved segment '__proto__' in config path {shown!r}")+++def covers(lock: Sequence[str], path: Sequence[str]) -> bool:+ """``lock`` covers ``path`` when it is a segment-wise prefix of it (equal counts)."""+ return len(lock) <= len(path) and tuple(path[:len(lock)]) == tuple(lock)+++def covering_lock(locks: Iterable[Tuple[Path, str]], path: Sequence[str]) -> Optional[Tuple[Path, str]]:+ """The first ``(lock, level)`` whose lock covers ``path``, or None."""+ for lock, level in locks:+ if covers(lock, path):+ return lock, level+ return None+++def from_dotted(dotted: str) -> Path:+ """A dotted key as the CLI and in-tree callers spell it. Those callers never escape, so a key+ that does not parse as an encoded path is split on every ``.`` (today's behaviour)."""+ try:+ return decode(dotted)+ except PathError:+ return tuple(dotted.split("."))diff --git a/plugins/config_backends/remote/plugin.yaml b/plugins/config_backends/remote/plugin.yamlnew file mode 100644index 00000000000..584428d6a28--- /dev/null+++ b/plugins/config_backends/remote/plugin.yaml@@ -0,0 +1,9 @@+name: remote+description: >-+ Remote Config — serves each profile's config from the config-config plane+ (the agent's effective document for this instance and profile) instead of+ config.yaml: fetched at boot (fail closed), refreshed by an ETag poller,+ written back as key-level changes with compare-and-swap. Selected only by+ HERMES_CONFIG_BACKEND=remote in the environment; never loaded as a general plugin.+version: 1.0.0+author: Nous Researchdiff --git a/plugins/config_backends/remote/values.py b/plugins/config_backends/remote/values.pynew file mode 100644index 00000000000..9bdad3bf906--- /dev/null+++ b/plugins/config_backends/remote/values.py@@ -0,0 +1,133 @@+"""Client-side value rules of the config plane wire contract.++- :func:`to_wire` — YAML-derived Python values → JSON values (contract.md §4.1, §4.2). Runs on the+ whole new user-layer document BEFORE the diff, so a conversion never shows up as a change (§4.3).+- :func:`secret_literal_path` — the secret-shaped-key rule (§14, D17), driven by the vendored+ ``config-secret-keys.json`` fixture so the agent and the plane use one list. The plane re-checks+ every write; this check exists so a literal is never sent.+"""+from __future__ import annotations++import datetime+import json+import logging+import math+import re+from functools import lru_cache+from pathlib import Path as _FsPath+from typing import Any, Dict, Iterator, Optional, Sequence, Tuple++from hermes_cli.config_backend import ConfigValueError++from .paths import Path, encode++logger = logging.getLogger(__name__)++MAX_SAFE_INTEGER = 2**53 - 1+VENDOR_DIR = _FsPath(__file__).resolve().parent / "vendor"+SECRET_KEYS_FIXTURE = VENDOR_DIR / "conformance" / "config-secret-keys.json"+++def to_wire(value: Any, path: Path = ()) -> Any:+ """``value`` converted per §4.1/§4.2; raises :class:`ConfigValueError` naming the path."""+ if value is None or isinstance(value, (str, bool)):+ return value+ if isinstance(value, int):+ if -MAX_SAFE_INTEGER <= value <= MAX_SAFE_INTEGER:+ return value+ logger.warning("config path %s: integer %d is outside ±(2^53-1); sent as a decimal string",+ encode(path) or "<root>", value)+ return str(value)+ if isinstance(value, float):+ if math.isnan(value) or math.isinf(value):+ raise ConfigValueError(f"{encode(path) or '<root>'}: NaN/Infinity cannot be stored in Remote Config")+ return value+ if isinstance(value, datetime.datetime | datetime.date):+ return value.isoformat()+ if isinstance(value, list | tuple):+ return [to_wire(v, path) for v in value]+ if isinstance(value, dict):+ out: Dict[str, Any] = {}+ for k, v in value.items():+ key = _wire_key(k, path)+ if key in out:+ raise ConfigValueError(+ f"{encode(path + (key,))}: two keys become the same string key {key!r}")+ out[key] = to_wire(v, path + (key,))+ return out+ raise ConfigValueError(+ f"{encode(path) or '<root>'}: a {type(value).__name__} value cannot be stored in Remote Config")+++def _wire_key(key: Any, path: Path) -> str:+ if isinstance(key, str):+ return key+ if isinstance(key, int) and not isinstance(key, bool):+ return str(key)+ raise ConfigValueError(+ f"{encode(path) or '<root>'}: a {type(key).__name__} mapping key ({key!r}) cannot be stored "+ "in Remote Config; quote it in YAML")+++# --- secret-shaped keys (§14) -----------------------------------------------------------------++@lru_cache(maxsize=1)+def _secret_rules() -> Dict[str, Any]:+ data = json.loads(SECRET_KEYS_FIXTURE.read_text(encoding="utf-8"))+ return {+ "secret_keys": frozenset(data["secretKeys"]),+ "secret_suffixes": tuple(data["secretKeySuffixes"]),+ "non_secret_suffixes": tuple(data["nonSecretKeySuffixes"]),+ "env_keys": frozenset(data["envConfigKeys"]),+ "env_suffixes": tuple(data["envConfigKeySuffixes"]),+ "env_prefixes": tuple(data["envConfigKeyPrefixes"]),+ # fullmatch: Python's ``$`` also matches before a trailing newline, so ``re.match`` with the+ # fixture pattern would accept ``"${X}\n"`` (a fixture vector the plane rejects).+ "placeholder": re.compile(data["placeholderPattern"]),+ "non_secret_paths": frozenset(tuple(p) for p in data["nonSecretPaths"]),+ }+++def _is_env_config_key(key: str, rules: Dict[str, Any]) -> bool:+ if "." in key:+ return False+ up = key.upper()+ return up in rules["env_keys"] or up.endswith(rules["env_suffixes"]) or up.startswith(rules["env_prefixes"])+++def is_secret_path(segments: Sequence[str]) -> bool:+ """§14.2 on decoded segments (list indices already dropped)."""+ rules = _secret_rules()+ if tuple(segments) in rules["non_secret_paths"]:+ return False+ last = segments[-1]+ leaf = last.lower().replace("-", "_")+ if len(segments) == 1 and _is_env_config_key(last, rules):+ return not leaf.endswith(rules["non_secret_suffixes"])+ return leaf in rules["secret_keys"] or leaf.endswith(rules["secret_suffixes"])+++def _walk(value: Any, path: Path) -> Iterator[Tuple[Path, Any]]:+ yield path, value+ if isinstance(value, dict):+ for k, v in value.items():+ yield from _walk(v, path + (str(k),))+ elif isinstance(value, list):+ for v in value: # list elements inherit the list's path (§14.3)+ yield from _walk(v, path)+++def secret_literal_path(path: Path, value: Any) -> Optional[Path]:+ """The first path under ``set path = value`` that holds a secret literal (§14.3), or None."""+ placeholder = _secret_rules()["placeholder"]+ for node_path, node in _walk(value, path):+ if not node_path or not is_secret_path(node_path):+ continue+ if isinstance(node, bool) or node is None:+ continue+ if isinstance(node, str) and (node == "" or placeholder.fullmatch(node)):+ continue+ if isinstance(node, str | int | float):+ return node_path+ return None+diff --git a/plugins/config_backends/remote/vendor/SOURCE.json b/plugins/config_backends/remote/vendor/SOURCE.jsonnew file mode 100644index 00000000000..401d0c2ca29--- /dev/null+++ b/plugins/config_backends/remote/vendor/SOURCE.json@@ -0,0 +1 @@+{ "repo": "NousResearch/gateway-gateway", "commit": "9151149d7f4c823dc113908e339dbcc9194fb3a7", "fixtureDigest": "e7e92b9b356c509b58b3e64f859922aff1c9cdd97924d53b756e4113de06c0af", "contractDigest": "314e100330af2d71be87238c1cf3aa8a40aedc0f4de58a9c4fadc808f68750ed" }diff --git a/plugins/config_backends/remote/vendor/conformance/config-fixtures.sha256 b/plugins/config_backends/remote/vendor/conformance/config-fixtures.sha256new file mode 100644index 00000000000..ce88811f205--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-fixtures.sha256@@ -0,0 +1,37 @@+862935270118746a681034f7f648e08eca8e1bc05d8a0031347f190194b9e7ec conformance/config-paths.json+ed39824af3a8b0bfc5cee40dece792c103ffce22af0975b0631446e8478296a6 conformance/config-resolution/chain-order-with-group.json+0d756100bf5606ad53c015dd62af004b718ccea32fcbc93aae452da95effafa9 conformance/config-resolution/chain-order-without-group.json+bda3fe88df3f1f2c6c753c9d473af1646f6267f12e547763697d580a0d979461 conformance/config-resolution/default-unlocked-every-level-may-write.json+d5ddf1647da71b401731709cc8928f456478319e784ce4d0ff41c4f17e52c77b conformance/config-resolution/defaults-merge-under-effective.json+f416555059a6861d2f35617ff8d871c475c5163eb75a09a421fbd08fc09912e0 conformance/config-resolution/dotted-key-segment.json+af6323842077f1a3edfb5dded390edd293bf44494edd34de2fd3a8d6348da01d conformance/config-resolution/empty-mapping-is-a-leaf.json+107ae6910f6cf6836a6c756252df0f2ebc3d92c68ec9f4151710c469b9766de7 conformance/config-resolution/global-lock-binds-every-level.json+5288e40c737db0ef68fa0310f4b75f2e88194b33579b75e50dcabae8aa05882e conformance/config-resolution/group-absent-level-skipped.json+d299ff9222cec91803a8bd73711f28f9c966866d15257a85aae717d2ac1847c7 conformance/config-resolution/group-present-lock-binds-principal.json+222f3dd6271620ebebad071711d9935552f018a5aec423e10bbcbed729a9d384 conformance/config-resolution/list-replaces-whole-list.json+407dd86d6a68bdac0e43cc1d60c590d76e8797af63acd394435de2a286411862 conformance/config-resolution/lock-coverage-is-segment-wise.json+5c4a8944350cadbd73e4a8c253df55aff806c2f607323805d333378da9b8702b conformance/config-resolution/lock-does-not-restrict-its-own-level.json+d6e3d04d111288e3457838a32df4f80d21202c32d47535d6e16a752cd821e584 conformance/config-resolution/lock-freezes-inherited-value-with-no-value-at-locking-level.json+5529f4ae98d9e89db9344c7c39c64239b1e71767ed5aa3da3794a1b3c8215a80 conformance/config-resolution/lock-on-absent-value-freezes-absence.json+d9fb020409a233e84fc5269bb2d0ac2d01c26fcc57f3d89062c66587876a5e5e conformance/config-resolution/lock-under-upper-locked-prefix-rejected.json+98d916571bfe7ce8a736e9ae5b54edaa8f390d6a35dad03831bb1f4b5ef3b804 conformance/config-resolution/lower-level-adds-lock-on-unlocked-path.json+3bf3119103e676a4aa94df1ee7ae101050ea4628112504a610b89efee87ba9d0 conformance/config-resolution/lower-overrides-upper-and-sets-unset-keys.json+a8875dd38ae1e48ac9fc593410463dc4eb386510a95c59e95152bcaf98704817 conformance/config-resolution/mappings-merge-key-by-key-across-levels.json+d5304c09003d5ff03706f70f0de69d07e463197dd575ede2853a4492c3ba242e conformance/config-resolution/non-mapping-replaces-mapping-and-back.json+6cdf96a39e936de149a849fa5dfc53d15bfc42b62ece79fd8ee84a250e217698 conformance/config-resolution/null-over-empty-mapping-supplies-nothing.json+0e564cb6d4b26bd2e51980029eec16c943d1a5800d1c50f1dc01aa660a58f8bd conformance/config-resolution/null-over-mapping-ignored.json+ec63a4ccf71eca9dcd82358fb58f7e4ad8b8ceb625f79573f1b962b76709d863 conformance/config-resolution/null-over-scalar-and-list-sets-no-value.json+d260e809eaac3b5eb613d52dd673ed33aea555ee01cdb4394e34c6cd807b8220 conformance/config-resolution/profile-level-below-agent.json+a0c1b0ced559af53fe4e96d5f7fc9ad6d1ecba2c815731df460724670a705f44 conformance/config-resolution/r7-ancestor-non-mapping-stripped-and-rejected.json+ab4349c16774a5cb0a12c8dbc32a78e52cc19cb2d5abdde2f1609ac6427184a1 conformance/config-resolution/r7-inner-value-at-ancestor-stripped-and-rejected.json+a31d9988699bc603a43cf69aa2601ddabf77497c6808da00834923b2b466f868 conformance/config-resolution/r9-redundant-lower-lock-dropped.json+40591acc6009cd02abc38494d7e2903a285ec676836f093780fdac083e282b24 conformance/config-resolution/secret-literal-rejected.json+0ab9be76bccf97a92c48968d6c1b2f3fa73b2332762979f06234db00047e37e9 conformance/config-resolution/secret-placeholder-accepted.json+996789f521ad9dc1571030726e6d4bf7e44ed2a41a7dd3f48d0b8e8c2c88c445 conformance/config-resolution/section-lock-covers-later-sub-keys.json+411963bbb58acbb80151c584fcb2d0e988b1b5b52ba44d73e76bad42e08a7be2 conformance/config-resolution/set-value-touching-locked-sub-path.json+752aca2fc558097938d9f5fa8cea0ee2fdd0867213b2fb46966d8933b73a5d5b conformance/config-resolution/tenant-section-lock-freezes-inherited.json+c09d99b625d71f79c9cf91ad18399d47c11880a7cad4b1fb7777f17082ca2d8e conformance/config-resolution/unset-restores-upper-value.json+8403d14b9b8fca04cb8593d5908f632108021d0e21886aaa37591ade49a03cd3 conformance/config-resolution/unset-under-lock-rejected-ancestor-unset-accepted.json+4f67f51030c565c0561d9acef42df5358dddcabb9abcf1c538b6de2a070b0efd conformance/config-resolution/upper-lock-cannot-be-removed-or-narrowed.json+599e7baca83923546c04bf6af792e0e6d0d8062b9afc3defaa09a08bf6074ce6 conformance/config-resolution/write-accept-reject-per-level.json+743239d0b299c5348e2d2925c31f66db448bad38c6ea6bf6ba2528c39e37e192 conformance/config-secret-keys.jsondiff --git a/plugins/config_backends/remote/vendor/conformance/config-paths.json b/plugins/config_backends/remote/vendor/conformance/config-paths.jsonnew file mode 100644index 00000000000..0a333112969--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-paths.json@@ -0,0 +1,136 @@+{+ "fixtureVersion": 1,+ "valid": [+ {+ "segments": [+ "terminal",+ "timeout"+ ],+ "encoded": "terminal.timeout"+ },+ {+ "segments": [+ "monitoring",+ "gateway_health_export",+ "resource_attributes",+ "service.name"+ ],+ "encoded": "monitoring.gateway_health_export.resource_attributes.service\\.name"+ },+ {+ "segments": [+ "x",+ "a\\b"+ ],+ "encoded": "x.a\\\\b"+ },+ {+ "segments": [+ "mcp_servers",+ "github",+ "env",+ "GITHUB_TOKEN"+ ],+ "encoded": "mcp_servers.github.env.GITHUB_TOKEN"+ },+ {+ "segments": [+ "platforms",+ "discord",+ "extra",+ "channel_prompts",+ "1180000000000000001"+ ],+ "encoded": "platforms.discord.extra.channel_prompts.1180000000000000001"+ },+ {+ "segments": [+ "mcp_servers",+ "x",+ "headers",+ "X-API-Key"+ ],+ "encoded": "mcp_servers.x.headers.X-API-Key"+ },+ {+ "segments": [+ "a."+ ],+ "encoded": "a\\."+ },+ {+ "segments": [+ "\\."+ ],+ "encoded": "\\\\\\."+ },+ {+ "segments": [+ "display",+ "personalities",+ "ペルソナ"+ ],+ "encoded": "display.personalities.ペルソナ"+ },+ {+ "segments": [+ "k",+ "with space"+ ],+ "encoded": "k.with space"+ }+ ],+ "invalid": [+ "",+ ".a",+ "a.",+ "a..b",+ "a\\",+ "a\\x",+ "__proto__.x",+ ".",+ "\\",+ "a.__proto__",+ "a\u0001b",+ "a.b",+ "s.s.s.s.s.s.s.s.s.s.s.s.s.s.s.s.s.s.s.s.s.s.s.s.s.s.s.s.s.s.s.s.s",+ "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"+ ],+ "covers": [+ {+ "lock": "terminal",+ "path": "terminal.timeout",+ "covers": true+ },+ {+ "lock": "terminal",+ "path": "terminal",+ "covers": true+ },+ {+ "lock": "terminal",+ "path": "terminal_extra",+ "covers": false+ },+ {+ "lock": "a\\.b",+ "path": "a.b",+ "covers": false+ },+ {+ "lock": "a",+ "path": "a\\.b",+ "covers": false+ },+ {+ "lock": "terminal.timeout",+ "path": "terminal",+ "covers": false+ },+ {+ "lock": "a\\.b",+ "path": "a\\.b.c",+ "covers": true+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/chain-order-with-group.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/chain-order-with-group.jsonnew file mode 100644index 00000000000..09e8aa6e256--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/chain-order-with-group.json@@ -0,0 +1,95 @@+{+ "fixtureVersion": 1,+ "name": "chain-order-with-group",+ "description": "Proves rule-0, rule-2: With a mapped group the group level sits between tenant and principal.",+ "levels": [+ {+ "kind": "global",+ "values": {+ "a": "g",+ "b": "g",+ "c": "g",+ "d": "g",+ "e": "g",+ "f": "g"+ },+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {+ "b": "t",+ "c": "t",+ "d": "t",+ "e": "t",+ "f": "t"+ },+ "locks": []+ },+ {+ "kind": "group",+ "groupId": "g-support",+ "values": {+ "c": "gr",+ "d": "gr",+ "e": "gr",+ "f": "gr"+ },+ "locks": []+ },+ {+ "kind": "principal",+ "values": {+ "d": "p",+ "e": "p",+ "f": "p"+ },+ "locks": []+ },+ {+ "kind": "agent",+ "values": {+ "e": "a",+ "f": "a"+ },+ "locks": []+ },+ {+ "kind": "profile",+ "values": {+ "f": "pr"+ },+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "a": "g",+ "b": "t",+ "c": "gr",+ "d": "p",+ "e": "a",+ "f": "pr"+ },+ "provenance": {+ "a": "global",+ "b": "tenant",+ "c": "group",+ "d": "principal",+ "e": "agent",+ "f": "profile"+ },+ "locks": []+ },+ "writes": [+ {+ "by": "principal",+ "op": "set",+ "path": "c",+ "value": "x",+ "expect": {+ "result": "accept"+ }+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/chain-order-without-group.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/chain-order-without-group.jsonnew file mode 100644index 00000000000..51cd44497e8--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/chain-order-without-group.json@@ -0,0 +1,80 @@+{+ "fixtureVersion": 1,+ "name": "chain-order-without-group",+ "description": "Proves rule-0, rule-2: With no mapped group the chain is global, tenant, principal, agent, profile; each lower level overrides the one above it.",+ "levels": [+ {+ "kind": "global",+ "values": {+ "a": "g",+ "b": "g",+ "c": "g",+ "d": "g",+ "e": "g"+ },+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {+ "b": "t",+ "c": "t",+ "d": "t",+ "e": "t"+ },+ "locks": []+ },+ {+ "kind": "principal",+ "values": {+ "c": "p",+ "d": "p",+ "e": "p"+ },+ "locks": []+ },+ {+ "kind": "agent",+ "values": {+ "d": "a",+ "e": "a"+ },+ "locks": []+ },+ {+ "kind": "profile",+ "values": {+ "e": "pr"+ },+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "a": "g",+ "b": "t",+ "c": "p",+ "d": "a",+ "e": "pr"+ },+ "provenance": {+ "a": "global",+ "b": "tenant",+ "c": "principal",+ "d": "agent",+ "e": "profile"+ },+ "locks": []+ },+ "writes": [+ {+ "by": "profile",+ "op": "set",+ "path": "e",+ "value": "x",+ "expect": {+ "result": "accept"+ }+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/default-unlocked-every-level-may-write.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/default-unlocked-every-level-may-write.jsonnew file mode 100644index 00000000000..68582c49ef2--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/default-unlocked-every-level-may-write.json@@ -0,0 +1,105 @@+{+ "fixtureVersion": 1,+ "name": "default-unlocked-every-level-may-write",+ "description": "Proves rule-1: With no locks anywhere every level may set, unset, lock and unlock any path.",+ "levels": [+ {+ "kind": "global",+ "values": {+ "x": {+ "y": 0+ }+ },+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {},+ "locks": []+ },+ {+ "kind": "group",+ "groupId": "g-support",+ "values": {},+ "locks": []+ },+ {+ "kind": "principal",+ "values": {},+ "locks": []+ },+ {+ "kind": "agent",+ "values": {},+ "locks": []+ },+ {+ "kind": "profile",+ "values": {},+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "x": {+ "y": 0+ }+ },+ "provenance": {+ "x.y": "global"+ },+ "locks": []+ },+ "writes": [+ {+ "by": "tenant",+ "op": "set",+ "path": "x.y",+ "value": 1,+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "group",+ "op": "unset",+ "path": "x",+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "principal",+ "op": "lock",+ "path": "x",+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "agent",+ "op": "unlock",+ "path": "x",+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "x.y",+ "value": 2,+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "profile",+ "op": "unset",+ "path": "x.y",+ "expect": {+ "result": "accept"+ }+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/defaults-merge-under-effective.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/defaults-merge-under-effective.jsonnew file mode 100644index 00000000000..93e6b7d3bdd--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/defaults-merge-under-effective.json@@ -0,0 +1,107 @@+{+ "fixtureVersion": 1,+ "name": "defaults-merge-under-effective",+ "description": "Proves rule-5: The agent's DEFAULT_CONFIG step deep-merges the effective document over defaults: mappings merge, lists replace, null over a default scalar stays null.",+ "levels": [+ {+ "kind": "global",+ "values": {+ "terminal": {+ "backend": "docker",+ "docker_volumes": [+ "/a"+ ]+ },+ "display": {+ "skin": null+ }+ },+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {},+ "locks": []+ },+ {+ "kind": "principal",+ "values": {},+ "locks": []+ },+ {+ "kind": "agent",+ "values": {},+ "locks": []+ },+ {+ "kind": "profile",+ "values": {},+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "terminal": {+ "backend": "docker",+ "docker_volumes": [+ "/a"+ ]+ },+ "display": {+ "skin": null+ }+ },+ "provenance": {+ "terminal.backend": "global",+ "terminal.docker_volumes": "global",+ "display.skin": "global"+ },+ "locks": []+ },+ "writes": [+ {+ "by": "profile",+ "op": "set",+ "path": "display.skin",+ "value": "ares",+ "expect": {+ "result": "accept"+ }+ }+ ],+ "defaultsMerge": {+ "defaults": {+ "terminal": {+ "backend": "local",+ "timeout": 60,+ "docker_volumes": [+ "/x",+ "/y"+ ]+ },+ "display": {+ "skin": "default",+ "compact": false+ },+ "model": {+ "default": ""+ }+ },+ "expect": {+ "terminal": {+ "backend": "docker",+ "timeout": 60,+ "docker_volumes": [+ "/a"+ ]+ },+ "display": {+ "skin": null,+ "compact": false+ },+ "model": {+ "default": ""+ }+ }+ }+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/dotted-key-segment.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/dotted-key-segment.jsonnew file mode 100644index 00000000000..4507ddd45d5--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/dotted-key-segment.json@@ -0,0 +1,120 @@+{+ "fixtureVersion": 1,+ "name": "dotted-key-segment",+ "description": "Proves path-grammar, rule-3: A key that contains dots is one escaped segment (service\\.name) in locks, provenance and writes; the unescaped form names a different path.",+ "levels": [+ {+ "kind": "global",+ "values": {+ "monitoring": {+ "gateway_health_export": {+ "resource_attributes": {+ "service.name": "hermes",+ "deployment.environment.name": "prod"+ }+ }+ }+ },+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {},+ "locks": [+ "monitoring.gateway_health_export.resource_attributes.service\\.name"+ ]+ },+ {+ "kind": "principal",+ "values": {},+ "locks": []+ },+ {+ "kind": "agent",+ "values": {},+ "locks": []+ },+ {+ "kind": "profile",+ "values": {+ "monitoring": {+ "gateway_health_export": {+ "resource_attributes": {+ "service.name": "acme",+ "deployment.environment.name": "staging"+ }+ }+ }+ },+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "monitoring": {+ "gateway_health_export": {+ "resource_attributes": {+ "service.name": "hermes",+ "deployment.environment.name": "staging"+ }+ }+ }+ },+ "provenance": {+ "monitoring.gateway_health_export.resource_attributes.service\\.name": "global",+ "monitoring.gateway_health_export.resource_attributes.deployment\\.environment\\.name": "profile"+ },+ "locks": [+ {+ "path": "monitoring.gateway_health_export.resource_attributes.service\\.name",+ "level": "tenant"+ }+ ]+ },+ "writes": [+ {+ "by": "profile",+ "op": "set",+ "path": "monitoring.gateway_health_export.resource_attributes.service\\.name",+ "value": "acme-2",+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "monitoring.gateway_health_export.resource_attributes.service\\.name",+ "lockedBy": "tenant"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "monitoring.gateway_health_export.resource_attributes.service.name",+ "value": "acme-3",+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "monitoring.gateway_health_export.resource_attributes",+ "value": {+ "service.name": "acme-4"+ },+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "monitoring.gateway_health_export.resource_attributes.service\\.name",+ "lockedBy": "tenant"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "monitoring.gateway_health_export.resource_attributes.deployment\\.environment\\.name",+ "value": "dev",+ "expect": {+ "result": "accept"+ }+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/empty-mapping-is-a-leaf.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/empty-mapping-is-a-leaf.jsonnew file mode 100644index 00000000000..f0d0862b68a--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/empty-mapping-is-a-leaf.json@@ -0,0 +1,84 @@+{+ "fixtureVersion": 1,+ "name": "empty-mapping-is-a-leaf",+ "description": "Proves r8, rule-5: An empty mapping is a leaf for provenance; merged over a non-empty mapping it changes nothing, over a scalar it replaces it.",+ "levels": [+ {+ "kind": "global",+ "values": {+ "a": {+ "x": 1+ },+ "b": 5+ },+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {},+ "locks": []+ },+ {+ "kind": "principal",+ "values": {},+ "locks": []+ },+ {+ "kind": "agent",+ "values": {+ "c": {}+ },+ "locks": []+ },+ {+ "kind": "profile",+ "values": {+ "a": {},+ "b": {}+ },+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "a": {+ "x": 1+ },+ "b": {},+ "c": {}+ },+ "provenance": {+ "a.x": "global",+ "b": "profile",+ "c": "agent"+ },+ "locks": []+ },+ "writes": [+ {+ "by": "profile",+ "op": "set",+ "path": "b",+ "value": {},+ "expect": {+ "result": "accept"+ }+ }+ ],+ "defaultsMerge": {+ "defaults": {+ "b": {+ "y": 2+ }+ },+ "expect": {+ "b": {+ "y": 2+ },+ "a": {+ "x": 1+ },+ "c": {}+ }+ }+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/global-lock-binds-every-level.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/global-lock-binds-every-level.jsonnew file mode 100644index 00000000000..8e6ea515a46--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/global-lock-binds-every-level.json@@ -0,0 +1,174 @@+{+ "fixtureVersion": 1,+ "name": "global-lock-binds-every-level",+ "description": "Proves rule-3, r7: A Global lock binds every stored level; siblings of the locked leaf stay writable; a scalar at its parent is refused.",+ "levels": [+ {+ "kind": "global",+ "values": {+ "web": {+ "use_gateway": true,+ "backend": "firecrawl"+ }+ },+ "locks": [+ "web.use_gateway"+ ]+ },+ {+ "kind": "tenant",+ "values": {+ "web": {+ "use_gateway": false,+ "backend": "exa"+ }+ },+ "locks": []+ },+ {+ "kind": "group",+ "groupId": "g-support",+ "values": {+ "web": {+ "use_gateway": false+ }+ },+ "locks": []+ },+ {+ "kind": "principal",+ "values": {},+ "locks": []+ },+ {+ "kind": "agent",+ "values": {+ "web": {+ "use_gateway": false+ }+ },+ "locks": []+ },+ {+ "kind": "profile",+ "values": {+ "web": {+ "backend": "tavily"+ }+ },+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "web": {+ "use_gateway": true,+ "backend": "tavily"+ }+ },+ "provenance": {+ "web.use_gateway": "global",+ "web.backend": "profile"+ },+ "locks": [+ {+ "path": "web.use_gateway",+ "level": "global"+ }+ ]+ },+ "writes": [+ {+ "by": "tenant",+ "op": "set",+ "path": "web.use_gateway",+ "value": false,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "web.use_gateway",+ "lockedBy": "global"+ }+ },+ {+ "by": "group",+ "op": "set",+ "path": "web.use_gateway",+ "value": false,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "web.use_gateway",+ "lockedBy": "global"+ }+ },+ {+ "by": "principal",+ "op": "set",+ "path": "web.use_gateway",+ "value": false,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "web.use_gateway",+ "lockedBy": "global"+ }+ },+ {+ "by": "agent",+ "op": "set",+ "path": "web.use_gateway",+ "value": false,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "web.use_gateway",+ "lockedBy": "global"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "web.use_gateway",+ "value": false,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "web.use_gateway",+ "lockedBy": "global"+ }+ },+ {+ "by": "tenant",+ "op": "set",+ "path": "web.backend",+ "value": "parallel",+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "tenant",+ "op": "set",+ "path": "web",+ "value": {+ "backend": "exa"+ },+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "tenant",+ "op": "set",+ "path": "web",+ "value": false,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "web.use_gateway",+ "lockedBy": "global"+ }+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/group-absent-level-skipped.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/group-absent-level-skipped.jsonnew file mode 100644index 00000000000..77f554bd1dc--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/group-absent-level-skipped.json@@ -0,0 +1,67 @@+{+ "fixtureVersion": 1,+ "name": "group-absent-level-skipped",+ "description": "Proves rule-0: When the owner has no mapped group the group level is skipped: no group values or locks apply.",+ "levels": [+ {+ "kind": "global",+ "values": {},+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {},+ "locks": []+ },+ {+ "kind": "principal",+ "values": {+ "display": {+ "personality": "verbose"+ }+ },+ "locks": []+ },+ {+ "kind": "agent",+ "values": {},+ "locks": []+ },+ {+ "kind": "profile",+ "values": {},+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "display": {+ "personality": "verbose"+ }+ },+ "provenance": {+ "display.personality": "principal"+ },+ "locks": []+ },+ "writes": [+ {+ "by": "principal",+ "op": "set",+ "path": "display.personality",+ "value": "technical",+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "agent",+ "op": "set",+ "path": "display.skin",+ "value": "ares",+ "expect": {+ "result": "accept"+ }+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/group-present-lock-binds-principal.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/group-present-lock-binds-principal.jsonnew file mode 100644index 00000000000..16b3b9acbd7--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/group-present-lock-binds-principal.json@@ -0,0 +1,99 @@+{+ "fixtureVersion": 1,+ "name": "group-present-lock-binds-principal",+ "description": "Proves rule-0, rule-3: When the owner has a mapped group, the group level's values apply and its locks bind principal, agent and profile.",+ "levels": [+ {+ "kind": "global",+ "values": {},+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {},+ "locks": []+ },+ {+ "kind": "group",+ "groupId": "g-support",+ "values": {+ "display": {+ "personality": "concise"+ }+ },+ "locks": [+ "display"+ ]+ },+ {+ "kind": "principal",+ "values": {+ "display": {+ "personality": "verbose"+ }+ },+ "locks": []+ },+ {+ "kind": "agent",+ "values": {},+ "locks": []+ },+ {+ "kind": "profile",+ "values": {},+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "display": {+ "personality": "concise"+ }+ },+ "provenance": {+ "display.personality": "group"+ },+ "locks": [+ {+ "path": "display",+ "level": "group"+ }+ ]+ },+ "writes": [+ {+ "by": "principal",+ "op": "set",+ "path": "display.personality",+ "value": "technical",+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "display",+ "lockedBy": "group"+ }+ },+ {+ "by": "agent",+ "op": "set",+ "path": "display.skin",+ "value": "ares",+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "display",+ "lockedBy": "group"+ }+ },+ {+ "by": "tenant",+ "op": "set",+ "path": "display.personality",+ "value": "kawaii",+ "expect": {+ "result": "accept"+ }+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/list-replaces-whole-list.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/list-replaces-whole-list.jsonnew file mode 100644index 00000000000..bbfe5c343a8--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/list-replaces-whole-list.json@@ -0,0 +1,113 @@+{+ "fixtureVersion": 1,+ "name": "list-replaces-whole-list",+ "description": "Proves rule-5: A lower list replaces the whole upper list (no element merge), including lists of mappings and DEFAULT_CONFIG lists.",+ "levels": [+ {+ "kind": "global",+ "values": {+ "tools": {+ "disabled": [+ "web",+ "browser"+ ]+ },+ "fallback_providers": [+ {+ "provider": "openrouter",+ "model": "a"+ }+ ]+ },+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {+ "tools": {+ "disabled": [+ "tts"+ ]+ }+ },+ "locks": []+ },+ {+ "kind": "principal",+ "values": {},+ "locks": []+ },+ {+ "kind": "agent",+ "values": {},+ "locks": []+ },+ {+ "kind": "profile",+ "values": {+ "fallback_providers": [+ {+ "provider": "nous"+ }+ ]+ },+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "tools": {+ "disabled": [+ "tts"+ ]+ },+ "fallback_providers": [+ {+ "provider": "nous"+ }+ ]+ },+ "provenance": {+ "tools.disabled": "tenant",+ "fallback_providers": "profile"+ },+ "locks": []+ },+ "writes": [+ {+ "by": "profile",+ "op": "set",+ "path": "tools.disabled",+ "value": [],+ "expect": {+ "result": "accept"+ }+ }+ ],+ "defaultsMerge": {+ "defaults": {+ "tools": {+ "disabled": [+ "x",+ "y",+ "z"+ ],+ "extra": 1+ },+ "fallback_providers": []+ },+ "expect": {+ "tools": {+ "disabled": [+ "tts"+ ],+ "extra": 1+ },+ "fallback_providers": [+ {+ "provider": "nous"+ }+ ]+ }+ }+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/lock-coverage-is-segment-wise.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/lock-coverage-is-segment-wise.jsonnew file mode 100644index 00000000000..c4bf2064010--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/lock-coverage-is-segment-wise.json@@ -0,0 +1,100 @@+{+ "fixtureVersion": 1,+ "name": "lock-coverage-is-segment-wise",+ "description": "Proves rule-3, path-grammar: A lock on terminal covers terminal.backend but not terminal_extra: coverage compares segments, never string prefixes.",+ "levels": [+ {+ "kind": "global",+ "values": {+ "terminal": {+ "backend": "local"+ },+ "terminal_extra": {+ "a": 1+ }+ },+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {},+ "locks": [+ "terminal"+ ]+ },+ {+ "kind": "principal",+ "values": {},+ "locks": []+ },+ {+ "kind": "agent",+ "values": {},+ "locks": []+ },+ {+ "kind": "profile",+ "values": {+ "terminal_extra": {+ "a": 2+ },+ "terminal": {+ "backend": "docker"+ }+ },+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "terminal": {+ "backend": "local"+ },+ "terminal_extra": {+ "a": 2+ }+ },+ "provenance": {+ "terminal.backend": "global",+ "terminal_extra.a": "profile"+ },+ "locks": [+ {+ "path": "terminal",+ "level": "tenant"+ }+ ]+ },+ "writes": [+ {+ "by": "profile",+ "op": "set",+ "path": "terminal_extra.a",+ "value": 3,+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "terminal.backend",+ "value": "ssh",+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "terminal",+ "lockedBy": "tenant"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "terminal_extra",+ "value": 5,+ "expect": {+ "result": "accept"+ }+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/lock-does-not-restrict-its-own-level.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/lock-does-not-restrict-its-own-level.jsonnew file mode 100644index 00000000000..0b8ec2ec37f--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/lock-does-not-restrict-its-own-level.json@@ -0,0 +1,107 @@+{+ "fixtureVersion": 1,+ "name": "lock-does-not-restrict-its-own-level",+ "description": "Proves rule-3: A lock binds only the levels below the level that stores it; the locking level may still set, unset, unlock and add locks under it.",+ "levels": [+ {+ "kind": "global",+ "values": {},+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {+ "terminal": {+ "timeout": 180+ }+ },+ "locks": [+ "terminal"+ ]+ },+ {+ "kind": "group",+ "groupId": "g-support",+ "values": {},+ "locks": []+ },+ {+ "kind": "principal",+ "values": {},+ "locks": []+ },+ {+ "kind": "agent",+ "values": {},+ "locks": []+ },+ {+ "kind": "profile",+ "values": {},+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "terminal": {+ "timeout": 180+ }+ },+ "provenance": {+ "terminal.timeout": "tenant"+ },+ "locks": [+ {+ "path": "terminal",+ "level": "tenant"+ }+ ]+ },+ "writes": [+ {+ "by": "tenant",+ "op": "set",+ "path": "terminal.timeout",+ "value": 240,+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "tenant",+ "op": "unset",+ "path": "terminal",+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "tenant",+ "op": "unlock",+ "path": "terminal",+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "tenant",+ "op": "lock",+ "path": "terminal.backend",+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "group",+ "op": "set",+ "path": "terminal.timeout",+ "value": 1,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "terminal",+ "lockedBy": "tenant"+ }+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/lock-freezes-inherited-value-with-no-value-at-locking-level.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/lock-freezes-inherited-value-with-no-value-at-locking-level.jsonnew file mode 100644index 00000000000..c493a522e70--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/lock-freezes-inherited-value-with-no-value-at-locking-level.json@@ -0,0 +1,125 @@+{+ "fixtureVersion": 1,+ "name": "lock-freezes-inherited-value-with-no-value-at-locking-level",+ "description": "Proves rule-3: A tenant lock on a leaf it does not set freezes the global value; lower values under it are ignored and lower writes refused; the tenant itself may still write it.",+ "levels": [+ {+ "kind": "global",+ "values": {+ "terminal": {+ "backend": "local",+ "timeout": 60+ }+ },+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {},+ "locks": [+ "terminal.timeout"+ ]+ },+ {+ "kind": "principal",+ "values": {+ "terminal": {+ "timeout": 5+ }+ },+ "locks": []+ },+ {+ "kind": "agent",+ "values": {},+ "locks": []+ },+ {+ "kind": "profile",+ "values": {+ "terminal": {+ "timeout": 10,+ "backend": "docker"+ }+ },+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "terminal": {+ "backend": "docker",+ "timeout": 60+ }+ },+ "provenance": {+ "terminal.backend": "profile",+ "terminal.timeout": "global"+ },+ "locks": [+ {+ "path": "terminal.timeout",+ "level": "tenant"+ }+ ]+ },+ "writes": [+ {+ "by": "profile",+ "op": "set",+ "path": "terminal.timeout",+ "value": 30,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "terminal.timeout",+ "lockedBy": "tenant"+ }+ },+ {+ "by": "agent",+ "op": "unset",+ "path": "terminal.timeout",+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "terminal.timeout",+ "lockedBy": "tenant"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "terminal.backend",+ "value": "ssh",+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "tenant",+ "op": "set",+ "path": "terminal.timeout",+ "value": 90,+ "expect": {+ "result": "accept"+ }+ }+ ],+ "defaultsMerge": {+ "defaults": {+ "terminal": {+ "backend": "local",+ "timeout": 60,+ "persistent": false+ }+ },+ "expect": {+ "terminal": {+ "backend": "docker",+ "timeout": 60,+ "persistent": false+ }+ }+ }+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/lock-on-absent-value-freezes-absence.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/lock-on-absent-value-freezes-absence.jsonnew file mode 100644index 00000000000..cb2a8aaff86--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/lock-on-absent-value-freezes-absence.json@@ -0,0 +1,108 @@+{+ "fixtureVersion": 1,+ "name": "lock-on-absent-value-freezes-absence",+ "description": "Proves rule-3: A lock on a path no level at or above it sets freezes it to absent: lower values under it are stripped and a mapping emptied by stripping is removed.",+ "levels": [+ {+ "kind": "global",+ "values": {},+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {},+ "locks": [+ "tools.disabled"+ ]+ },+ {+ "kind": "principal",+ "values": {+ "tools": {+ "disabled": [+ "web"+ ]+ }+ },+ "locks": []+ },+ {+ "kind": "agent",+ "values": {},+ "locks": []+ },+ {+ "kind": "profile",+ "values": {+ "tools": {+ "disabled": [+ "tts"+ ],+ "enabled": [+ "x"+ ]+ }+ },+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "tools": {+ "enabled": [+ "x"+ ]+ }+ },+ "provenance": {+ "tools.enabled": "profile"+ },+ "locks": [+ {+ "path": "tools.disabled",+ "level": "tenant"+ }+ ]+ },+ "writes": [+ {+ "by": "profile",+ "op": "set",+ "path": "tools.disabled",+ "value": [],+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "tools.disabled",+ "lockedBy": "tenant"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "tools",+ "value": {+ "enabled": []+ },+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "tools",+ "value": {+ "disabled": [+ "a"+ ]+ },+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "tools.disabled",+ "lockedBy": "tenant"+ }+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/lock-under-upper-locked-prefix-rejected.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/lock-under-upper-locked-prefix-rejected.jsonnew file mode 100644index 00000000000..71693795271--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/lock-under-upper-locked-prefix-rejected.json@@ -0,0 +1,100 @@+{+ "fixtureVersion": 1,+ "name": "lock-under-upper-locked-prefix-rejected",+ "description": "Proves rule-4: A level cannot add a lock equal to or under an upper lock; it may add a lock on a path no upper level has locked.",+ "levels": [+ {+ "kind": "global",+ "values": {+ "web": {+ "backend": "firecrawl",+ "use_gateway": true+ }+ },+ "locks": [+ "web"+ ]+ },+ {+ "kind": "tenant",+ "values": {},+ "locks": []+ },+ {+ "kind": "principal",+ "values": {},+ "locks": []+ },+ {+ "kind": "agent",+ "values": {},+ "locks": []+ },+ {+ "kind": "profile",+ "values": {},+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "web": {+ "backend": "firecrawl",+ "use_gateway": true+ }+ },+ "provenance": {+ "web.backend": "global",+ "web.use_gateway": "global"+ },+ "locks": [+ {+ "path": "web",+ "level": "global"+ }+ ]+ },+ "writes": [+ {+ "by": "tenant",+ "op": "lock",+ "path": "web.backend",+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "web",+ "lockedBy": "global"+ }+ },+ {+ "by": "tenant",+ "op": "lock",+ "path": "web",+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "web",+ "lockedBy": "global"+ }+ },+ {+ "by": "tenant",+ "op": "lock",+ "path": "tts",+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "principal",+ "op": "lock",+ "path": "web.use_gateway",+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "web",+ "lockedBy": "global"+ }+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/lower-level-adds-lock-on-unlocked-path.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/lower-level-adds-lock-on-unlocked-path.jsonnew file mode 100644index 00000000000..1ceb6df33da--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/lower-level-adds-lock-on-unlocked-path.json@@ -0,0 +1,128 @@+{+ "fixtureVersion": 1,+ "name": "lower-level-adds-lock-on-unlocked-path",+ "description": "Proves rule-4, rule-3: A principal lock on a path no upper level locked binds agent and profile, but not the levels above the principal.",+ "levels": [+ {+ "kind": "global",+ "values": {+ "web": {+ "use_gateway": true+ }+ },+ "locks": [+ "web.use_gateway"+ ]+ },+ {+ "kind": "tenant",+ "values": {},+ "locks": []+ },+ {+ "kind": "principal",+ "values": {+ "model": {+ "default": "hermes-4-405b"+ }+ },+ "locks": [+ "model"+ ]+ },+ {+ "kind": "agent",+ "values": {+ "model": {+ "default": "hermes-4-70b"+ }+ },+ "locks": []+ },+ {+ "kind": "profile",+ "values": {+ "model": {+ "provider": "openrouter"+ }+ },+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "web": {+ "use_gateway": true+ },+ "model": {+ "default": "hermes-4-405b"+ }+ },+ "provenance": {+ "web.use_gateway": "global",+ "model.default": "principal"+ },+ "locks": [+ {+ "path": "web.use_gateway",+ "level": "global"+ },+ {+ "path": "model",+ "level": "principal"+ }+ ]+ },+ "writes": [+ {+ "by": "agent",+ "op": "set",+ "path": "model.default",+ "value": "hermes-4-8b",+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "model",+ "lockedBy": "principal"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "model.provider",+ "value": "nous",+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "model",+ "lockedBy": "principal"+ }+ },+ {+ "by": "tenant",+ "op": "set",+ "path": "model.default",+ "value": "hermes-3",+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "principal",+ "op": "set",+ "path": "model.default",+ "value": "hermes-4-70b",+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "principal",+ "op": "lock",+ "path": "model.default",+ "expect": {+ "result": "accept"+ }+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/lower-overrides-upper-and-sets-unset-keys.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/lower-overrides-upper-and-sets-unset-keys.jsonnew file mode 100644index 00000000000..2e71b0ca429--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/lower-overrides-upper-and-sets-unset-keys.json@@ -0,0 +1,72 @@+{+ "fixtureVersion": 1,+ "name": "lower-overrides-upper-and-sets-unset-keys",+ "description": "Proves rule-2: On unlocked keys a lower level overrides an upper value and may set keys no upper level sets.",+ "levels": [+ {+ "kind": "global",+ "values": {+ "model": {+ "default": "hermes-3",+ "provider": "auto"+ }+ },+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {},+ "locks": []+ },+ {+ "kind": "principal",+ "values": {},+ "locks": []+ },+ {+ "kind": "agent",+ "values": {+ "model": {+ "default": "hermes-4-405b"+ }+ },+ "locks": []+ },+ {+ "kind": "profile",+ "values": {+ "model": {+ "default": "hermes-4-70b",+ "base_url": "https://inference.example"+ }+ },+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "model": {+ "default": "hermes-4-70b",+ "provider": "auto",+ "base_url": "https://inference.example"+ }+ },+ "provenance": {+ "model.default": "profile",+ "model.provider": "global",+ "model.base_url": "profile"+ },+ "locks": []+ },+ "writes": [+ {+ "by": "agent",+ "op": "set",+ "path": "model.provider",+ "value": "nous",+ "expect": {+ "result": "accept"+ }+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/mappings-merge-key-by-key-across-levels.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/mappings-merge-key-by-key-across-levels.jsonnew file mode 100644index 00000000000..718de82bd1a--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/mappings-merge-key-by-key-across-levels.json@@ -0,0 +1,100 @@+{+ "fixtureVersion": 1,+ "name": "mappings-merge-key-by-key-across-levels",+ "description": "Proves rule-5, rule-2: Nested mappings merge key by key across every level; each leaf takes the value and provenance of the lowest level that sets it.",+ "levels": [+ {+ "kind": "global",+ "values": {+ "a": {+ "b": {+ "c": 1,+ "d": 2+ },+ "e": 3+ }+ },+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {+ "a": {+ "b": {+ "d": 20+ }+ }+ },+ "locks": []+ },+ {+ "kind": "group",+ "groupId": "g-support",+ "values": {+ "a": {+ "f": 6+ }+ },+ "locks": []+ },+ {+ "kind": "principal",+ "values": {+ "a": {+ "b": {+ "g": 7+ }+ }+ },+ "locks": []+ },+ {+ "kind": "agent",+ "values": {},+ "locks": []+ },+ {+ "kind": "profile",+ "values": {+ "a": {+ "b": {+ "c": 10+ }+ }+ },+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "a": {+ "b": {+ "c": 10,+ "d": 20,+ "g": 7+ },+ "e": 3,+ "f": 6+ }+ },+ "provenance": {+ "a.b.c": "profile",+ "a.b.d": "tenant",+ "a.b.g": "principal",+ "a.e": "global",+ "a.f": "group"+ },+ "locks": []+ },+ "writes": [+ {+ "by": "agent",+ "op": "set",+ "path": "a.b.c",+ "value": 11,+ "expect": {+ "result": "accept"+ }+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/non-mapping-replaces-mapping-and-back.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/non-mapping-replaces-mapping-and-back.jsonnew file mode 100644index 00000000000..d3daead598d--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/non-mapping-replaces-mapping-and-back.json@@ -0,0 +1,79 @@+{+ "fixtureVersion": 1,+ "name": "non-mapping-replaces-mapping-and-back",+ "description": "Proves rule-5, r8: A lower scalar or list replaces an upper mapping, and a lower mapping replaces an upper scalar; provenance of replaced leaves is dropped.",+ "levels": [+ {+ "kind": "global",+ "values": {+ "terminal": {+ "backend": "local"+ },+ "a": 5,+ "display": {+ "personality": "x"+ }+ },+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {},+ "locks": []+ },+ {+ "kind": "principal",+ "values": {+ "display": "off"+ },+ "locks": []+ },+ {+ "kind": "agent",+ "values": {},+ "locks": []+ },+ {+ "kind": "profile",+ "values": {+ "terminal": [+ "x"+ ],+ "a": {+ "b": 1+ }+ },+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "terminal": [+ "x"+ ],+ "a": {+ "b": 1+ },+ "display": "off"+ },+ "provenance": {+ "terminal": "profile",+ "a.b": "profile",+ "display": "principal"+ },+ "locks": []+ },+ "writes": [+ {+ "by": "profile",+ "op": "set",+ "path": "display",+ "value": {+ "personality": "y"+ },+ "expect": {+ "result": "accept"+ }+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/null-over-empty-mapping-supplies-nothing.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/null-over-empty-mapping-supplies-nothing.jsonnew file mode 100644index 00000000000..32a8082c31e--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/null-over-empty-mapping-supplies-nothing.json@@ -0,0 +1,63 @@+{+ "fixtureVersion": 1,+ "name": "null-over-empty-mapping-supplies-nothing",+ "description": "Proves rule-5, r8: null over an empty upper mapping is ignored like null over any mapping, so the empty mapping keeps the provenance of the level that supplied it.",+ "levels": [+ {+ "kind": "global",+ "values": {+ "mcp_servers": {}+ },+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {},+ "locks": []+ },+ {+ "kind": "principal",+ "values": {},+ "locks": []+ },+ {+ "kind": "agent",+ "values": {},+ "locks": []+ },+ {+ "kind": "profile",+ "values": {+ "mcp_servers": null+ },+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "mcp_servers": {}+ },+ "provenance": {+ "mcp_servers": "global"+ },+ "locks": []+ },+ "writes": [+ {+ "by": "profile",+ "op": "unset",+ "path": "mcp_servers",+ "expect": {+ "result": "accept"+ }+ }+ ],+ "defaultsMerge": {+ "defaults": {+ "mcp_servers": {}+ },+ "expect": {+ "mcp_servers": {}+ }+ }+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/null-over-mapping-ignored.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/null-over-mapping-ignored.jsonnew file mode 100644index 00000000000..68f73eff097--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/null-over-mapping-ignored.json@@ -0,0 +1,79 @@+{+ "fixtureVersion": 1,+ "name": "null-over-mapping-ignored",+ "description": "Proves rule-5: null at a lower level over an upper mapping is ignored: the upper mapping and its provenance stay.",+ "levels": [+ {+ "kind": "global",+ "values": {+ "display": {+ "personality": "kawaii",+ "compact": true+ }+ },+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {},+ "locks": []+ },+ {+ "kind": "principal",+ "values": {},+ "locks": []+ },+ {+ "kind": "agent",+ "values": {},+ "locks": []+ },+ {+ "kind": "profile",+ "values": {+ "display": null+ },+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "display": {+ "personality": "kawaii",+ "compact": true+ }+ },+ "provenance": {+ "display.personality": "global",+ "display.compact": "global"+ },+ "locks": []+ },+ "writes": [+ {+ "by": "profile",+ "op": "set",+ "path": "display",+ "value": null,+ "expect": {+ "result": "accept"+ }+ }+ ],+ "defaultsMerge": {+ "defaults": {+ "display": {+ "personality": "",+ "compact": false,+ "skin": "default"+ }+ },+ "expect": {+ "display": {+ "personality": "kawaii",+ "compact": true,+ "skin": "default"+ }+ }+ }+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/null-over-scalar-and-list-sets-no-value.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/null-over-scalar-and-list-sets-no-value.jsonnew file mode 100644index 00000000000..50ebb435bbf--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/null-over-scalar-and-list-sets-no-value.json@@ -0,0 +1,97 @@+{+ "fixtureVersion": 1,+ "name": "null-over-scalar-and-list-sets-no-value",+ "description": "Proves rule-5: null at a lower level over an upper scalar or list sets no value (null); over DEFAULT_CONFIG it stays null.",+ "levels": [+ {+ "kind": "global",+ "values": {+ "model": {+ "default": "hermes-4-405b",+ "provider": "nous"+ },+ "tools": {+ "disabled": [+ "web"+ ]+ }+ },+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {},+ "locks": []+ },+ {+ "kind": "principal",+ "values": {},+ "locks": []+ },+ {+ "kind": "agent",+ "values": {},+ "locks": []+ },+ {+ "kind": "profile",+ "values": {+ "model": {+ "default": null+ },+ "tools": {+ "disabled": null+ }+ },+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "model": {+ "default": null,+ "provider": "nous"+ },+ "tools": {+ "disabled": null+ }+ },+ "provenance": {+ "model.default": "profile",+ "model.provider": "global",+ "tools.disabled": "profile"+ },+ "locks": []+ },+ "writes": [+ {+ "by": "profile",+ "op": "set",+ "path": "model.default",+ "value": null,+ "expect": {+ "result": "accept"+ }+ }+ ],+ "defaultsMerge": {+ "defaults": {+ "model": {+ "default": "",+ "provider": "auto"+ },+ "tools": {+ "disabled": []+ }+ },+ "expect": {+ "model": {+ "default": null,+ "provider": "nous"+ },+ "tools": {+ "disabled": null+ }+ }+ }+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/profile-level-below-agent.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/profile-level-below-agent.jsonnew file mode 100644index 00000000000..2ec34c27a46--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/profile-level-below-agent.json@@ -0,0 +1,94 @@+{+ "fixtureVersion": 1,+ "name": "profile-level-below-agent",+ "description": "Proves rule-0, rule-3: The profile level overrides the agent level on unlocked keys; an agent-level lock binds the profile level.",+ "levels": [+ {+ "kind": "global",+ "values": {},+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {},+ "locks": []+ },+ {+ "kind": "principal",+ "values": {},+ "locks": []+ },+ {+ "kind": "agent",+ "values": {+ "model": {+ "default": "hermes-4-405b"+ },+ "max_concurrent_sessions": 4+ },+ "locks": [+ "max_concurrent_sessions"+ ]+ },+ {+ "kind": "profile",+ "values": {+ "model": {+ "default": "hermes-4-70b"+ },+ "max_concurrent_sessions": 10+ },+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "model": {+ "default": "hermes-4-70b"+ },+ "max_concurrent_sessions": 4+ },+ "provenance": {+ "model.default": "profile",+ "max_concurrent_sessions": "agent"+ },+ "locks": [+ {+ "path": "max_concurrent_sessions",+ "level": "agent"+ }+ ]+ },+ "writes": [+ {+ "by": "profile",+ "op": "set",+ "path": "max_concurrent_sessions",+ "value": 8,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "max_concurrent_sessions",+ "lockedBy": "agent"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "model.default",+ "value": "hermes-4-8b",+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "agent",+ "op": "set",+ "path": "max_concurrent_sessions",+ "value": 2,+ "expect": {+ "result": "accept"+ }+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/r7-ancestor-non-mapping-stripped-and-rejected.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/r7-ancestor-non-mapping-stripped-and-rejected.jsonnew file mode 100644index 00000000000..7b9ef581013--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/r7-ancestor-non-mapping-stripped-and-rejected.json@@ -0,0 +1,142 @@+{+ "fixtureVersion": 1,+ "name": "r7-ancestor-non-mapping-stripped-and-rejected",+ "description": "Proves r7: A lower scalar, null or list at a strict ancestor of a locked path would replace the locked subtree: it is stripped on read and refused on write; a mapping at the ancestor is accepted.",+ "levels": [+ {+ "kind": "global",+ "values": {+ "terminal": {+ "backend": "local"+ }+ },+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {+ "terminal": {+ "timeout": 180+ }+ },+ "locks": [+ "terminal.timeout"+ ]+ },+ {+ "kind": "principal",+ "values": {+ "terminal": "docker"+ },+ "locks": []+ },+ {+ "kind": "agent",+ "values": {+ "terminal": null+ },+ "locks": []+ },+ {+ "kind": "profile",+ "values": {+ "terminal": [+ "x"+ ]+ },+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "terminal": {+ "backend": "local",+ "timeout": 180+ }+ },+ "provenance": {+ "terminal.backend": "global",+ "terminal.timeout": "tenant"+ },+ "locks": [+ {+ "path": "terminal.timeout",+ "level": "tenant"+ }+ ]+ },+ "writes": [+ {+ "by": "profile",+ "op": "set",+ "path": "terminal",+ "value": "docker",+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "terminal.timeout",+ "lockedBy": "tenant"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "terminal",+ "value": null,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "terminal.timeout",+ "lockedBy": "tenant"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "terminal",+ "value": [+ "x"+ ],+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "terminal.timeout",+ "lockedBy": "tenant"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "terminal",+ "value": {+ "backend": "docker"+ },+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "terminal",+ "value": {+ "timeout": 5+ },+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "terminal.timeout",+ "lockedBy": "tenant"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "terminal.backend",+ "value": "ssh",+ "expect": {+ "result": "accept"+ }+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/r7-inner-value-at-ancestor-stripped-and-rejected.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/r7-inner-value-at-ancestor-stripped-and-rejected.jsonnew file mode 100644index 00000000000..70fc3de27fc--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/r7-inner-value-at-ancestor-stripped-and-rejected.json@@ -0,0 +1,128 @@+{+ "fixtureVersion": 1,+ "name": "r7-inner-value-at-ancestor-stripped-and-rejected",+ "description": "Proves r7: An inner non-mapping value of a set at a strict ancestor of a lock is refused; on read it is stripped and a mapping emptied by stripping is removed.",+ "levels": [+ {+ "kind": "global",+ "values": {+ "a": {+ "b": {+ "c": 1+ }+ }+ },+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {},+ "locks": [+ "a.b.c"+ ]+ },+ {+ "kind": "principal",+ "values": {+ "a": {+ "b": 5+ }+ },+ "locks": []+ },+ {+ "kind": "agent",+ "values": {},+ "locks": []+ },+ {+ "kind": "profile",+ "values": {+ "a": {+ "b": {+ "c": 2,+ "d": 3+ }+ }+ },+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "a": {+ "b": {+ "c": 1,+ "d": 3+ }+ }+ },+ "provenance": {+ "a.b.c": "global",+ "a.b.d": "profile"+ },+ "locks": [+ {+ "path": "a.b.c",+ "level": "tenant"+ }+ ]+ },+ "writes": [+ {+ "by": "profile",+ "op": "set",+ "path": "a",+ "value": {+ "b": 5+ },+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "a.b.c",+ "lockedBy": "tenant"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "a",+ "value": {+ "b": [+ 1+ ]+ },+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "a.b.c",+ "lockedBy": "tenant"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "a",+ "value": {+ "b": {+ "d": 4+ }+ },+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "a.b.c.x",+ "value": 1,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "a.b.c",+ "lockedBy": "tenant"+ }+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/r9-redundant-lower-lock-dropped.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/r9-redundant-lower-lock-dropped.jsonnew file mode 100644index 00000000000..2a3db296667--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/r9-redundant-lower-lock-dropped.json@@ -0,0 +1,88 @@+{+ "fixtureVersion": 1,+ "name": "r9-redundant-lower-lock-dropped",+ "description": "Proves r9: A lower lock already covered by an upper lock is omitted from the effective lock list, so lock errors name the upper level.",+ "levels": [+ {+ "kind": "global",+ "values": {},+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {+ "terminal": {+ "timeout": 180+ }+ },+ "locks": [+ "terminal"+ ]+ },+ {+ "kind": "principal",+ "values": {},+ "locks": []+ },+ {+ "kind": "agent",+ "values": {},+ "locks": [+ "model",+ "terminal",+ "terminal.timeout"+ ]+ },+ {+ "kind": "profile",+ "values": {},+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "terminal": {+ "timeout": 180+ }+ },+ "provenance": {+ "terminal.timeout": "tenant"+ },+ "locks": [+ {+ "path": "terminal",+ "level": "tenant"+ },+ {+ "path": "model",+ "level": "agent"+ }+ ]+ },+ "writes": [+ {+ "by": "profile",+ "op": "set",+ "path": "terminal.timeout",+ "value": 5,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "terminal",+ "lockedBy": "tenant"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "model.default",+ "value": "hermes-4-70b",+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "model",+ "lockedBy": "agent"+ }+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/secret-literal-rejected.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/secret-literal-rejected.jsonnew file mode 100644index 00000000000..4bfcc3d1f79--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/secret-literal-rejected.json@@ -0,0 +1,116 @@+{+ "fixtureVersion": 1,+ "name": "secret-literal-rejected",+ "description": "Proves secret: A literal string or number under a secret-shaped key is refused at every level, including inside mappings and lists; ${env:X} is not a placeholder.",+ "levels": [+ {+ "kind": "global",+ "values": {+ "model": {+ "provider": "nous"+ }+ },+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {},+ "locks": []+ },+ {+ "kind": "principal",+ "values": {},+ "locks": []+ },+ {+ "kind": "agent",+ "values": {},+ "locks": []+ },+ {+ "kind": "profile",+ "values": {},+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "model": {+ "provider": "nous"+ }+ },+ "provenance": {+ "model.provider": "global"+ },+ "locks": []+ },+ "writes": [+ {+ "by": "profile",+ "op": "set",+ "path": "model.api_key",+ "value": "literal-value-1",+ "expect": {+ "result": "reject",+ "error": "config_secret_literal"+ }+ },+ {+ "by": "tenant",+ "op": "set",+ "path": "mcp_servers.github.env.GITHUB_TOKEN",+ "value": "literal-value-2",+ "expect": {+ "result": "reject",+ "error": "config_secret_literal"+ }+ },+ {+ "by": "agent",+ "op": "set",+ "path": "fallback_providers",+ "value": [+ {+ "provider": "openrouter",+ "api_key": "literal-value-3"+ }+ ],+ "expect": {+ "result": "reject",+ "error": "config_secret_literal"+ }+ },+ {+ "by": "principal",+ "op": "set",+ "path": "dashboard.basic_auth.password",+ "value": 1234,+ "expect": {+ "result": "reject",+ "error": "config_secret_literal"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "model",+ "value": {+ "api_key": "literal-value-4"+ },+ "expect": {+ "result": "reject",+ "error": "config_secret_literal"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "delegation.api_key",+ "value": "${env:X}",+ "expect": {+ "result": "reject",+ "error": "config_secret_literal"+ }+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/secret-placeholder-accepted.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/secret-placeholder-accepted.jsonnew file mode 100644index 00000000000..6c108471243--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/secret-placeholder-accepted.json@@ -0,0 +1,106 @@+{+ "fixtureVersion": 1,+ "name": "secret-placeholder-accepted",+ "description": "Proves secret: A ${VAR} placeholder, an empty string, null, and non-secret keys (R14 exemptions, token_count, *_URL env keys) are accepted.",+ "levels": [+ {+ "kind": "global",+ "values": {},+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {},+ "locks": []+ },+ {+ "kind": "principal",+ "values": {},+ "locks": []+ },+ {+ "kind": "agent",+ "values": {},+ "locks": []+ },+ {+ "kind": "profile",+ "values": {},+ "locks": []+ }+ ],+ "expect": {+ "effective": {},+ "provenance": {},+ "locks": []+ },+ "writes": [+ {+ "by": "profile",+ "op": "set",+ "path": "model.api_key",+ "value": "${OPENROUTER_API_KEY}",+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "model.api_key",+ "value": "",+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "model.api_key",+ "value": null,+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "voice.record_key",+ "value": "ctrl+b",+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "model.token_count",+ "value": "12",+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "FIRECRAWL_API_URL",+ "value": "https://fc.example",+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "tenant",+ "op": "set",+ "path": "mcp_servers.x",+ "value": {+ "env": {+ "API_KEY": "${API_KEY}"+ }+ },+ "expect": {+ "result": "accept"+ }+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/section-lock-covers-later-sub-keys.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/section-lock-covers-later-sub-keys.jsonnew file mode 100644index 00000000000..55d64c3a6e7--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/section-lock-covers-later-sub-keys.json@@ -0,0 +1,120 @@+{+ "fixtureVersion": 1,+ "name": "section-lock-covers-later-sub-keys",+ "description": "Proves rule-3: A lock on a section covers every sub-key under it, including keys no level had set when the lock was added.",+ "levels": [+ {+ "kind": "global",+ "values": {},+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {+ "tools": {+ "disabled": [+ "web"+ ]+ }+ },+ "locks": [+ "tools"+ ]+ },+ {+ "kind": "principal",+ "values": {+ "tools": {+ "enabled_toolsets": [+ "x"+ ]+ }+ },+ "locks": []+ },+ {+ "kind": "agent",+ "values": {},+ "locks": []+ },+ {+ "kind": "profile",+ "values": {+ "tools": {+ "new_key": {+ "deep": true+ }+ }+ },+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "tools": {+ "disabled": [+ "web"+ ]+ }+ },+ "provenance": {+ "tools.disabled": "tenant"+ },+ "locks": [+ {+ "path": "tools",+ "level": "tenant"+ }+ ]+ },+ "writes": [+ {+ "by": "profile",+ "op": "set",+ "path": "tools.new_key.deep",+ "value": false,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "tools",+ "lockedBy": "tenant"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "tools.enabled_toolsets",+ "value": [+ "y"+ ],+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "tools",+ "lockedBy": "tenant"+ }+ },+ {+ "by": "profile",+ "op": "unset",+ "path": "tools.disabled",+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "tools",+ "lockedBy": "tenant"+ }+ },+ {+ "by": "agent",+ "op": "lock",+ "path": "tools.x",+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "tools",+ "lockedBy": "tenant"+ }+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/set-value-touching-locked-sub-path.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/set-value-touching-locked-sub-path.jsonnew file mode 100644index 00000000000..759b48ae7ee--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/set-value-touching-locked-sub-path.json@@ -0,0 +1,133 @@+{+ "fixtureVersion": 1,+ "name": "set-value-touching-locked-sub-path",+ "description": "Proves rule-3, r7: A set of a mapping is checked at every path inside the value: a key under an upper lock is refused, keys beside it are accepted.",+ "levels": [+ {+ "kind": "global",+ "values": {+ "mcp_servers": {+ "github": {+ "command": "gh-mcp",+ "env": {+ "GITHUB_TOKEN": "${GITHUB_TOKEN}"+ }+ }+ }+ },+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {},+ "locks": [+ "mcp_servers.github.env"+ ]+ },+ {+ "kind": "principal",+ "values": {},+ "locks": []+ },+ {+ "kind": "agent",+ "values": {},+ "locks": []+ },+ {+ "kind": "profile",+ "values": {},+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "mcp_servers": {+ "github": {+ "command": "gh-mcp",+ "env": {+ "GITHUB_TOKEN": "${GITHUB_TOKEN}"+ }+ }+ }+ },+ "provenance": {+ "mcp_servers.github.command": "global",+ "mcp_servers.github.env.GITHUB_TOKEN": "global"+ },+ "locks": [+ {+ "path": "mcp_servers.github.env",+ "level": "tenant"+ }+ ]+ },+ "writes": [+ {+ "by": "profile",+ "op": "set",+ "path": "mcp_servers",+ "value": {+ "github": {+ "env": {+ "DEBUG": "1"+ }+ }+ },+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "mcp_servers.github.env",+ "lockedBy": "tenant"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "mcp_servers",+ "value": {+ "other": {+ "command": "x"+ }+ },+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "mcp_servers.github",+ "value": {+ "command": "gh-mcp-2"+ },+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "mcp_servers.github",+ "value": "off",+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "mcp_servers.github.env",+ "lockedBy": "tenant"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "mcp_servers.github.env.GITHUB_TOKEN",+ "value": "${OTHER_TOKEN}",+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "mcp_servers.github.env",+ "lockedBy": "tenant"+ }+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/tenant-section-lock-freezes-inherited.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/tenant-section-lock-freezes-inherited.jsonnew file mode 100644index 00000000000..f74b100b1d0--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/tenant-section-lock-freezes-inherited.json@@ -0,0 +1,156 @@+{+ "fixtureVersion": 1,+ "name": "tenant-section-lock-freezes-inherited",+ "description": "Proves rule-3, rule-4: A tenant lock on a section freezes the resolved value from levels at or above it and refuses lower writes under it.",+ "levels": [+ {+ "kind": "global",+ "values": {+ "terminal": {+ "backend": "local",+ "timeout": 60+ }+ },+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {+ "terminal": {+ "timeout": 180+ }+ },+ "locks": [+ "terminal"+ ]+ },+ {+ "kind": "group",+ "groupId": "g-support",+ "values": {+ "display": {+ "personality": "concise"+ }+ },+ "locks": []+ },+ {+ "kind": "principal",+ "values": {+ "terminal": {+ "timeout": 5+ }+ },+ "locks": []+ },+ {+ "kind": "agent",+ "values": {+ "terminal": "docker"+ },+ "locks": []+ },+ {+ "kind": "profile",+ "values": {+ "model": {+ "default": "hermes-4-70b"+ }+ },+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "terminal": {+ "backend": "local",+ "timeout": 180+ },+ "display": {+ "personality": "concise"+ },+ "model": {+ "default": "hermes-4-70b"+ }+ },+ "provenance": {+ "terminal.backend": "global",+ "terminal.timeout": "tenant",+ "display.personality": "group",+ "model.default": "profile"+ },+ "locks": [+ {+ "path": "terminal",+ "level": "tenant"+ }+ ]+ },+ "writes": [+ {+ "by": "profile",+ "op": "set",+ "path": "terminal.timeout",+ "value": 30,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "terminal",+ "lockedBy": "tenant"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "model.default",+ "value": "hermes-4-405b",+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "tenant",+ "op": "unset",+ "path": "terminal.timeout",+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "principal",+ "op": "lock",+ "path": "terminal.backend",+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "terminal",+ "lockedBy": "tenant"+ }+ }+ ],+ "defaultsMerge": {+ "defaults": {+ "terminal": {+ "backend": "local",+ "timeout": 60,+ "persistent": false+ },+ "display": {+ "personality": ""+ }+ },+ "expect": {+ "terminal": {+ "backend": "local",+ "timeout": 180,+ "persistent": false+ },+ "display": {+ "personality": "concise"+ },+ "model": {+ "default": "hermes-4-70b"+ }+ }+ }+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/unset-restores-upper-value.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/unset-restores-upper-value.jsonnew file mode 100644index 00000000000..131d91455ff--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/unset-restores-upper-value.json@@ -0,0 +1,83 @@+{+ "fixtureVersion": 1,+ "name": "unset-restores-upper-value",+ "description": "Proves rule-6: After the profile level unsets model.default it stops overriding and the tenant value applies again; unset of an absent key is accepted.",+ "levels": [+ {+ "kind": "global",+ "values": {+ "model": {+ "default": "hermes-3"+ }+ },+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {+ "model": {+ "default": "hermes-4-405b"+ }+ },+ "locks": []+ },+ {+ "kind": "principal",+ "values": {},+ "locks": []+ },+ {+ "kind": "agent",+ "values": {},+ "locks": []+ },+ {+ "kind": "profile",+ "values": {+ "model": {+ "provider": "nous"+ }+ },+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "model": {+ "default": "hermes-4-405b",+ "provider": "nous"+ }+ },+ "provenance": {+ "model.default": "tenant",+ "model.provider": "profile"+ },+ "locks": []+ },+ "writes": [+ {+ "by": "profile",+ "op": "unset",+ "path": "model.default",+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "profile",+ "op": "unset",+ "path": "model.provider",+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "profile",+ "op": "unset",+ "path": "model.not_there",+ "expect": {+ "result": "accept"+ }+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/unset-under-lock-rejected-ancestor-unset-accepted.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/unset-under-lock-rejected-ancestor-unset-accepted.jsonnew file mode 100644index 00000000000..8e3240f8f3a--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/unset-under-lock-rejected-ancestor-unset-accepted.json@@ -0,0 +1,93 @@+{+ "fixtureVersion": 1,+ "name": "unset-under-lock-rejected-ancestor-unset-accepted",+ "description": "Proves rule-6, rule-3: Unset of a locked path by a lower level is refused; unset of an ancestor of the lock only removes the lower level's own subtree and is accepted.",+ "levels": [+ {+ "kind": "global",+ "values": {+ "model": {+ "default": "hermes-4-405b"+ }+ },+ "locks": []+ },+ {+ "kind": "tenant",+ "values": {},+ "locks": [+ "model.default"+ ]+ },+ {+ "kind": "principal",+ "values": {},+ "locks": []+ },+ {+ "kind": "agent",+ "values": {+ "model": {+ "default": "hermes-4-8b",+ "provider": "nous"+ }+ },+ "locks": []+ },+ {+ "kind": "profile",+ "values": {},+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "model": {+ "default": "hermes-4-405b",+ "provider": "nous"+ }+ },+ "provenance": {+ "model.default": "global",+ "model.provider": "agent"+ },+ "locks": [+ {+ "path": "model.default",+ "level": "tenant"+ }+ ]+ },+ "writes": [+ {+ "by": "profile",+ "op": "unset",+ "path": "model.default",+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "model.default",+ "lockedBy": "tenant"+ }+ },+ {+ "by": "agent",+ "op": "unset",+ "path": "model.default",+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "model.default",+ "lockedBy": "tenant"+ }+ },+ {+ "by": "agent",+ "op": "unset",+ "path": "model",+ "expect": {+ "result": "accept"+ }+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/upper-lock-cannot-be-removed-or-narrowed.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/upper-lock-cannot-be-removed-or-narrowed.jsonnew file mode 100644index 00000000000..5ba8f5d0176--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/upper-lock-cannot-be-removed-or-narrowed.json@@ -0,0 +1,139 @@+{+ "fixtureVersion": 1,+ "name": "upper-lock-cannot-be-removed-or-narrowed",+ "description": "Proves rule-4: A lower level cannot unlock an upper lock, nor lock or unlock a path under it; the level that stores the lock may unlock it.",+ "levels": [+ {+ "kind": "global",+ "values": {+ "web": {+ "use_gateway": true+ }+ },+ "locks": [+ "web.use_gateway"+ ]+ },+ {+ "kind": "tenant",+ "values": {},+ "locks": []+ },+ {+ "kind": "group",+ "groupId": "g-support",+ "values": {+ "display": {+ "personality": "concise"+ }+ },+ "locks": [+ "display"+ ]+ },+ {+ "kind": "principal",+ "values": {},+ "locks": []+ },+ {+ "kind": "agent",+ "values": {},+ "locks": []+ },+ {+ "kind": "profile",+ "values": {},+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "web": {+ "use_gateway": true+ },+ "display": {+ "personality": "concise"+ }+ },+ "provenance": {+ "web.use_gateway": "global",+ "display.personality": "group"+ },+ "locks": [+ {+ "path": "web.use_gateway",+ "level": "global"+ },+ {+ "path": "display",+ "level": "group"+ }+ ]+ },+ "writes": [+ {+ "by": "tenant",+ "op": "unlock",+ "path": "web.use_gateway",+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "web.use_gateway",+ "lockedBy": "global"+ }+ },+ {+ "by": "agent",+ "op": "unlock",+ "path": "web.use_gateway",+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "web.use_gateway",+ "lockedBy": "global"+ }+ },+ {+ "by": "principal",+ "op": "unlock",+ "path": "display",+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "display",+ "lockedBy": "group"+ }+ },+ {+ "by": "principal",+ "op": "unlock",+ "path": "display.personality",+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "display",+ "lockedBy": "group"+ }+ },+ {+ "by": "principal",+ "op": "lock",+ "path": "display.personality",+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "display",+ "lockedBy": "group"+ }+ },+ {+ "by": "group",+ "op": "unlock",+ "path": "display",+ "expect": {+ "result": "accept"+ }+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-resolution/write-accept-reject-per-level.json b/plugins/config_backends/remote/vendor/conformance/config-resolution/write-accept-reject-per-level.jsonnew file mode 100644index 00000000000..73852c092dd--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-resolution/write-accept-reject-per-level.json@@ -0,0 +1,376 @@+{+ "fixtureVersion": 1,+ "name": "write-accept-reject-per-level",+ "description": "Proves rule-3, rule-0: Each level holds one lock; a write by level k to a path locked at level j is refused exactly when j is above k.",+ "levels": [+ {+ "kind": "global",+ "values": {+ "k": {+ "global": 0,+ "tenant": 0,+ "group": 0,+ "principal": 0,+ "agent": 0+ }+ },+ "locks": [+ "k.global"+ ]+ },+ {+ "kind": "tenant",+ "values": {},+ "locks": [+ "k.tenant"+ ]+ },+ {+ "kind": "group",+ "groupId": "g-support",+ "values": {},+ "locks": [+ "k.group"+ ]+ },+ {+ "kind": "principal",+ "values": {},+ "locks": [+ "k.principal"+ ]+ },+ {+ "kind": "agent",+ "values": {},+ "locks": [+ "k.agent"+ ]+ },+ {+ "kind": "profile",+ "values": {+ "k": {+ "global": 1,+ "tenant": 1,+ "group": 1,+ "principal": 1,+ "agent": 1+ }+ },+ "locks": []+ }+ ],+ "expect": {+ "effective": {+ "k": {+ "global": 0,+ "tenant": 0,+ "group": 0,+ "principal": 0,+ "agent": 0+ }+ },+ "provenance": {+ "k.global": "global",+ "k.tenant": "global",+ "k.group": "global",+ "k.principal": "global",+ "k.agent": "global"+ },+ "locks": [+ {+ "path": "k.global",+ "level": "global"+ },+ {+ "path": "k.tenant",+ "level": "tenant"+ },+ {+ "path": "k.group",+ "level": "group"+ },+ {+ "path": "k.principal",+ "level": "principal"+ },+ {+ "path": "k.agent",+ "level": "agent"+ }+ ]+ },+ "writes": [+ {+ "by": "tenant",+ "op": "set",+ "path": "k.global",+ "value": 1,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "k.global",+ "lockedBy": "global"+ }+ },+ {+ "by": "tenant",+ "op": "set",+ "path": "k.tenant",+ "value": 1,+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "tenant",+ "op": "set",+ "path": "k.group",+ "value": 1,+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "tenant",+ "op": "set",+ "path": "k.principal",+ "value": 1,+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "tenant",+ "op": "set",+ "path": "k.agent",+ "value": 1,+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "group",+ "op": "set",+ "path": "k.global",+ "value": 1,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "k.global",+ "lockedBy": "global"+ }+ },+ {+ "by": "group",+ "op": "set",+ "path": "k.tenant",+ "value": 1,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "k.tenant",+ "lockedBy": "tenant"+ }+ },+ {+ "by": "group",+ "op": "set",+ "path": "k.group",+ "value": 1,+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "group",+ "op": "set",+ "path": "k.principal",+ "value": 1,+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "group",+ "op": "set",+ "path": "k.agent",+ "value": 1,+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "principal",+ "op": "set",+ "path": "k.global",+ "value": 1,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "k.global",+ "lockedBy": "global"+ }+ },+ {+ "by": "principal",+ "op": "set",+ "path": "k.tenant",+ "value": 1,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "k.tenant",+ "lockedBy": "tenant"+ }+ },+ {+ "by": "principal",+ "op": "set",+ "path": "k.group",+ "value": 1,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "k.group",+ "lockedBy": "group"+ }+ },+ {+ "by": "principal",+ "op": "set",+ "path": "k.principal",+ "value": 1,+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "principal",+ "op": "set",+ "path": "k.agent",+ "value": 1,+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "agent",+ "op": "set",+ "path": "k.global",+ "value": 1,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "k.global",+ "lockedBy": "global"+ }+ },+ {+ "by": "agent",+ "op": "set",+ "path": "k.tenant",+ "value": 1,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "k.tenant",+ "lockedBy": "tenant"+ }+ },+ {+ "by": "agent",+ "op": "set",+ "path": "k.group",+ "value": 1,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "k.group",+ "lockedBy": "group"+ }+ },+ {+ "by": "agent",+ "op": "set",+ "path": "k.principal",+ "value": 1,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "k.principal",+ "lockedBy": "principal"+ }+ },+ {+ "by": "agent",+ "op": "set",+ "path": "k.agent",+ "value": 1,+ "expect": {+ "result": "accept"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "k.global",+ "value": 1,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "k.global",+ "lockedBy": "global"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "k.tenant",+ "value": 1,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "k.tenant",+ "lockedBy": "tenant"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "k.group",+ "value": 1,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "k.group",+ "lockedBy": "group"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "k.principal",+ "value": 1,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "k.principal",+ "lockedBy": "principal"+ }+ },+ {+ "by": "profile",+ "op": "set",+ "path": "k.agent",+ "value": 1,+ "expect": {+ "result": "reject",+ "error": "config_key_locked",+ "path": "k.agent",+ "lockedBy": "agent"+ }+ }+ ]+}diff --git a/plugins/config_backends/remote/vendor/conformance/config-secret-keys.json b/plugins/config_backends/remote/vendor/conformance/config-secret-keys.jsonnew file mode 100644index 00000000000..08e399b41e0--- /dev/null+++ b/plugins/config_backends/remote/vendor/conformance/config-secret-keys.json@@ -0,0 +1,313 @@+{+ "fixtureVersion": 1,+ "source": {+ "repo": "NousResearch/hermes-agent",+ "commit": "f7a861379f",+ "path": "hermes_cli/config.py",+ "symbols": [+ "_ENV_CONFIG_KEYS",+ "_is_env_config_key",+ "_SECRET_CONFIG_KEYS",+ "_SECRET_CONFIG_KEY_SUFFIXES",+ "_NON_SECRET_KEY_SUFFIXES",+ "_ENV_PLACEHOLDER_RE",+ "_is_secret_config_key"+ ]+ },+ "secretKeys": [+ "api_key",+ "apikey",+ "key",+ "token",+ "access_token",+ "refresh_token",+ "id_token",+ "secret",+ "client_secret",+ "password",+ "passwd",+ "authorization",+ "private_key",+ "bearer",+ "jwt"+ ],+ "secretKeySuffixes": [+ "_api_key",+ "_token",+ "_secret",+ "_password",+ "_key",+ "_access_key"+ ],+ "nonSecretKeySuffixes": [+ "_url",+ "_host",+ "_user",+ "_id",+ "_domain",+ "_scheme"+ ],+ "envConfigKeys": [+ "OPENROUTER_API_KEY",+ "OPENAI_API_KEY",+ "ANTHROPIC_API_KEY",+ "VOICE_TOOLS_OPENAI_KEY",+ "EXA_API_KEY",+ "PARALLEL_API_KEY",+ "FIRECRAWL_API_KEY",+ "FIRECRAWL_API_URL",+ "FIRECRAWL_GATEWAY_URL",+ "TOOL_GATEWAY_URL",+ "CONNECTOR_GATEWAY_URL",+ "TOOL_GATEWAY_DOMAIN",+ "TOOL_GATEWAY_SCHEME",+ "TOOL_GATEWAY_USER_TOKEN",+ "TAVILY_API_KEY",+ "PERPLEXITY_API_KEY",+ "API_SERVER_KEY",+ "BROWSERBASE_API_KEY",+ "BROWSERBASE_PROJECT_ID",+ "BROWSER_USE_API_KEY",+ "FAL_KEY",+ "TELEGRAM_BOT_TOKEN",+ "DISCORD_BOT_TOKEN",+ "TERMINAL_SSH_HOST",+ "TERMINAL_SSH_USER",+ "TERMINAL_SSH_KEY",+ "SUDO_PASSWORD",+ "SLACK_BOT_TOKEN",+ "SLACK_APP_TOKEN",+ "GITHUB_TOKEN",+ "HONCHO_API_KEY"+ ],+ "envConfigKeySuffixes": [+ "_API_KEY",+ "_TOKEN",+ "_SECRET"+ ],+ "envConfigKeyPrefixes": [+ "TERMINAL_SSH"+ ],+ "placeholderPattern": "^\\$\\{[A-Za-z_][A-Za-z0-9_]*\\}$",+ "nonSecretPaths": [+ [+ "voice",+ "record_key"+ ],+ [+ "terminal",+ "docker_shared_container_key"+ ],+ [+ "browser",+ "camofox",+ "session_key"+ ]+ ],+ "vectors": [+ {+ "path": "model.api_key",+ "value": "sk-live-abc",+ "expect": "reject"+ },+ {+ "path": "model.api_key",+ "value": "${OPENROUTER_API_KEY}",+ "expect": "accept"+ },+ {+ "path": "model.api_key",+ "value": "",+ "expect": "accept"+ },+ {+ "path": "model.api_key",+ "value": null,+ "expect": "accept"+ },+ {+ "path": "delegation.api_key",+ "value": "${env:X}",+ "expect": "reject"+ },+ {+ "path": "mcp_servers.github.env.GITHUB_TOKEN",+ "value": "ghp_x",+ "expect": "reject"+ },+ {+ "path": "mcp_servers.x.headers.X-API-Key",+ "value": "k",+ "expect": "reject"+ },+ {+ "path": "dashboard.basic_auth.password",+ "value": 1234,+ "expect": "reject"+ },+ {+ "path": "OPENAI_API_KEY",+ "value": "sk-x",+ "expect": "reject"+ },+ {+ "path": "FIRECRAWL_API_URL",+ "value": "https://fc.example",+ "expect": "accept"+ },+ {+ "path": "voice.record_key",+ "value": "ctrl+b",+ "expect": "accept"+ },+ {+ "path": "model.token_count",+ "value": "12",+ "expect": "accept"+ },+ {+ "path": "fallback_providers",+ "value": [+ {+ "provider": "openrouter",+ "api_key": "sk-x"+ }+ ],+ "expect": "reject"+ },+ {+ "path": "terminal.docker_shared_container_key",+ "value": "hermes-shared",+ "expect": "accept"+ },+ {+ "path": "browser.camofox.session_key",+ "value": "sess-1",+ "expect": "accept"+ },+ {+ "path": "voice.record_key.extra",+ "value": "x",+ "expect": "accept"+ },+ {+ "path": "TERMINAL_SSH_HOST",+ "value": "host.example",+ "expect": "accept"+ },+ {+ "path": "TERMINAL_SSH_KEY",+ "value": "literal",+ "expect": "reject"+ },+ {+ "path": "TERMINAL_SSH_PORT",+ "value": 22,+ "expect": "reject"+ },+ {+ "path": "BROWSERBASE_PROJECT_ID",+ "value": "proj-1",+ "expect": "accept"+ },+ {+ "path": "mcp_servers.x.env.BROWSERBASE_PROJECT_ID",+ "value": "proj-1",+ "expect": "accept"+ },+ {+ "path": "mcp_servers.x.env.TOOL_GATEWAY_URL",+ "value": "https://tg.example",+ "expect": "accept"+ },+ {+ "path": "mcp_servers.x.headers.Authorization",+ "value": "literal",+ "expect": "reject"+ },+ {+ "path": "mcp_servers.x.headers.X-Auth-Token",+ "value": "literal",+ "expect": "reject"+ },+ {+ "path": "model.api_key",+ "value": true,+ "expect": "accept"+ },+ {+ "path": "auxiliary.vision.api_key",+ "value": 0,+ "expect": "reject"+ },+ {+ "path": "model.token_count",+ "value": 12,+ "expect": "accept"+ },+ {+ "path": "custom_providers",+ "value": [+ {+ "name": "local",+ "key": "literal"+ }+ ],+ "expect": "reject"+ },+ {+ "path": "providers",+ "value": {+ "openai": {+ "api_key": "${OPENAI_API_KEY}"+ }+ },+ "expect": "accept"+ },+ {+ "path": "providers",+ "value": {+ "openai": {+ "api_key": "literal"+ }+ },+ "expect": "reject"+ },+ {+ "path": "model.api_key",+ "value": "${X}\n",+ "expect": "reject"+ },+ {+ "path": "model.api_key",+ "value": "${1X}",+ "expect": "reject"+ },+ {+ "path": "model.api_key",+ "value": [+ "${A}",+ "${B}"+ ],+ "expect": "accept"+ },+ {+ "path": "model.api_key",+ "value": [+ "${A}",+ "literal"+ ],+ "expect": "reject"+ },+ {+ "path": "a.b\\.api_key",+ "value": "literal",+ "expect": "reject"+ },+ {+ "path": "OPENAI_API_KEY.nested",+ "value": "literal",+ "expect": "accept"+ }+ ]+}diff --git a/pyproject.toml b/pyproject.tomlindex 1d6e774c099..7fda79db4e8 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -709,7 +709,9 @@ gateway = ["assets/**/*"]# Bundled plugin discovery reads these manifests at runtime. Keep them in# sealed wheels with the plugin Python modules; without this declaration the# wheel contains adapters but discovery finds zero bundled plugins.-plugins = ["**/plugin.yaml", "**/plugin.yml"]+# The remote config backend checks its vendored config-plane conformance fixtures (secret-key+# list) at runtime: plugins/config_backends/remote/values.py.+plugins = ["**/plugin.yaml", "**/plugin.yml", "config_backends/remote/vendor/**/*"]# pm/lock.json is the runtime pin table (uv/python/tool versions + sha256s).# Without it a sealed wheel installs the pm package but has no pins to# realize — the pm store would be empty.diff --git a/tests/plugins/config_backends/__init__.py b/tests/plugins/config_backends/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/tests/plugins/config_backends/stub_plane.py b/tests/plugins/config_backends/stub_plane.pynew file mode 100644index 00000000000..86dfca96b58--- /dev/null+++ b/tests/plugins/config_backends/stub_plane.py@@ -0,0 +1,195 @@+"""A contract-faithful stub of the config plane's agent routes (contract.md §7.1, §7.2, §8) plus an+OAuth2 client-credentials token endpoint, for driving the remote backend without gg.++Levels are collapsed to one ``upper`` document (everything above the profile) plus per-profile+``values``; locks are ``upper_locks``. Effective = deep_merge(upper, profile) — enough for the+agent, which never resolves the chain itself (design §2.3).+"""+from __future__ import annotations++import copy+import hashlib+import json+import threading+import urllib.parse+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path+from typing import Any, Dict, List, Optional++from plugins.config_backends.remote.diff import write_check+from plugins.config_backends.remote.paths import decode, encode+from plugins.config_backends.remote.values import secret_literal_path++TOKEN = "plane-token-1"+CLIENT_ID = "agent-client"+CLIENT_SECRET = "agent-secret"+INSTANCE = "inst-0001"+++def deep_merge(base: Dict[str, Any], over: Dict[str, Any]) -> Dict[str, Any]:+ out = copy.deepcopy(base)+ for k, v in over.items():+ if isinstance(out.get(k), dict) and isinstance(v, dict):+ out[k] = deep_merge(out[k], v)+ else:+ out[k] = copy.deepcopy(v)+ return out+++class StubPlane:+ def __init__(self) -> None:+ self.upper: Dict[str, Any] = {}+ self.upper_locks: List[Dict[str, str]] = []+ self.profiles: Dict[str, Dict[str, Any]] = {}+ self.fail_status: Optional[int] = None # every /self request returns this+ self.requests: List[Dict[str, Any]] = []+ self.token_requests = 0+ self.home: Optional[Path] = None # the test's HERMES_HOME, set by the fixture+ self.lock = threading.Lock()+ self._server = ThreadingHTTPServer(("127.0.0.1", 0), self._handler())+ self.url = f"http://127.0.0.1:{self._server.server_address[1]}"+ self._thread = threading.Thread(target=self._server.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True)++ def __enter__(self) -> "StubPlane":+ self._thread.start()+ return self++ def __exit__(self, *exc) -> None:+ self._server.shutdown()+ self._server.server_close()++ # --- model ---++ def profile(self, name: str) -> Dict[str, Any]:+ return self.profiles.setdefault(name, {"values": {}, "version": 0, "writer": None})++ def effective(self, name: str) -> Dict[str, Any]:+ prof = self.profile(name)+ body = {+ "instanceId": INSTANCE, "profile": name,+ "config": deep_merge(self.upper, prof["values"]),+ "locks": copy.deepcopy(self.upper_locks),+ "provenance": {},+ "levels": [{"kind": "tenant", "version": 1, "writerConfigVersion": None},+ {"kind": "profile", "version": prof["version"], "writerConfigVersion": prof["writer"]}],+ "profileVersion": prof["version"], "recordVersion": 1,+ }+ digest = hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()+ body["etag"] = f'"{digest}"'+ return body++ def patches(self) -> List[Dict[str, Any]]:+ return [r for r in self.requests if r["method"] == "PATCH"]++ # --- HTTP ---++ def _handler(self):+ plane = self++ class Handler(BaseHTTPRequestHandler):+ def log_message(self, format, *args) -> None: # noqa: A002 — base signature+ pass++ def _send(self, status: int, body: Optional[Dict[str, Any]] = None, etag: Optional[str] = None):+ raw = json.dumps(body).encode() if body is not None else b""+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(raw)))+ if etag:+ self.send_header("ETag", etag)+ self.end_headers()+ self.wfile.write(raw)++ def _body(self) -> Dict[str, Any]:+ n = int(self.headers.get("Content-Length") or 0)+ return json.loads(self.rfile.read(n) or b"{}")++ def do_POST(self):+ if self.path != "/token":+ return self._send(404, {"error": "not_found"})+ n = int(self.headers.get("Content-Length") or 0)+ form = urllib.parse.parse_qs(self.rfile.read(n).decode())+ plane.token_requests += 1+ if (form.get("grant_type") != ["client_credentials"] or form.get("client_id") != [CLIENT_ID]+ or form.get("client_secret") != [CLIENT_SECRET]):+ return self._send(401, {"error": "invalid_client"})+ return self._send(200, {"access_token": TOKEN, "token_type": "Bearer", "expires_in": 3600})++ def _route(self, method: str):+ parsed = urllib.parse.urlparse(self.path)+ if parsed.path != "/v1/config/self":+ return self._send(404, {"error": "not_found"})+ profile = urllib.parse.parse_qs(parsed.query).get("profile", ["default"])[0]+ body = self._body() if method == "PATCH" else None+ with plane.lock:+ plane.requests.append({+ "method": method, "profile": profile, "body": body,+ "auth": self.headers.get("Authorization"),+ "instance": self.headers.get("X-Hermes-Instance-Id"),+ "if_none_match": self.headers.get("If-None-Match")})+ if plane.fail_status is not None:+ return self._send(plane.fail_status, {"error": "unavailable", "message": "stub outage"})+ if self.headers.get("Authorization") != f"Bearer {TOKEN}":+ return self._send(401, {"error": "unauthorized", "message": "bad token"})+ if self.headers.get("X-Hermes-Instance-Id") != INSTANCE:+ return self._send(403, {"error": "config_agent_unknown", "message": "unknown instance"})+ if method == "GET":+ eff = plane.effective(profile)+ if self.headers.get("If-None-Match") == eff["etag"]:+ return self._send(304, None, eff["etag"])+ return self._send(200, eff, eff["etag"])+ return self._patch(profile, body or {})++ def _patch(self, profile: str, body: Dict[str, Any]):+ prof = plane.profile(profile)+ if body.get("expectedVersion") != prof["version"]:+ return self._send(409, {"error": "config_version_conflict", "message": "stale",+ "currentVersion": prof["version"]})+ sets = {decode(k): v for k, v in (body.get("set") or {}).items()}+ unsets = [decode(k) for k in body.get("unset") or []]+ locks = [(decode(lk["path"]), lk["level"]) for lk in plane.upper_locks]+ refused = write_check(sets, unsets, locks)+ if refused is not None:+ path = encode(refused[0])+ return self._send(403, {"error": "config_key_locked", "path": path, "lockedBy": refused[1],+ "message": f"{path} is locked by {refused[1]}"})+ for p, v in sets.items():+ if secret_literal_path(p, v) is not None:+ return self._send(400, {"error": "config_secret_literal", "message": "secret literal"})+ values = prof["values"]+ for p, v in sets.items():+ node = values+ for seg in p[:-1]:+ if not isinstance(node.get(seg), dict):+ node[seg] = {}+ node = node[seg]+ node[p[-1]] = copy.deepcopy(v)+ for p in unsets:+ node = values+ for seg in p[:-1]:+ node = node.get(seg) if isinstance(node, dict) else None+ if isinstance(node, dict):+ node.pop(p[-1], None)+ prof["version"] += 1+ prof["writer"] = body.get("writerConfigVersion")+ eff = plane.effective(profile)+ return self._send(200, eff, eff["etag"])++ def do_GET(self):+ self._route("GET")++ def do_PATCH(self):+ self._route("PATCH")++ return Handler+++def remote_env(plane: StubPlane) -> Dict[str, str]:+ return {+ "HERMES_CONFIG_BACKEND": "remote",+ "HERMES_CONFIG_REMOTE_URL": plane.url,+ "HERMES_CONFIG_INSTANCE_ID": INSTANCE,+ "GATEWAY_RELAY_IDP_TOKEN_URL": f"{plane.url}/token",+ "GATEWAY_RELAY_IDP_CLIENT_ID": CLIENT_ID,+ "GATEWAY_RELAY_IDP_CLIENT_SECRET": CLIENT_SECRET,+ }diff --git a/tests/plugins/config_backends/test_remote_backend.py b/tests/plugins/config_backends/test_remote_backend.pynew file mode 100644index 00000000000..f200ff7a34c--- /dev/null+++ b/tests/plugins/config_backends/test_remote_backend.py@@ -0,0 +1,450 @@+"""Remote config backend against a contract-faithful stub plane (``stub_plane.py``).++Covers the P4 behaviours: boot fetch fails closed with bounded retry, reads come from the plane and+never from a local config.yaml, writes are key-level diffs with CAS, locks and secret literals are+refused client-side (nothing sent), the poller keeps the in-memory document through an outage,+migrations run in memory only, and the managed config.yaml is ignored.+"""+from __future__ import annotations++import argparse+import json+from pathlib import Path++import pytest++from utils import fast_safe_load++from plugins.config_backends import remote as remote_pkg+from plugins.config_backends.remote import backend as backend_mod+from plugins.config_backends.remote import credentials as cred_mod+from hermes_cli.config_backend import (+ ConfigBackendUnavailable, ConfigLockedError, ConfigValueError, get_config_backend, write_config_key)++from .stub_plane import INSTANCE, TOKEN, StubPlane, remote_env+++def plane(tmp_path, monkeypatch):+ home = Path(tmp_path) / "home"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ with StubPlane() as p:+ for k, v in remote_env(p).items():+ monkeypatch.setenv(k, v)+ monkeypatch.setattr(backend_mod, "BOOT_RETRY_DELAYS", (0.0, 0.0))+ remote_pkg._reset_for_tests()+ cred_mod._IDP_CACHE.clear()+ p.home = home+ yield p+ remote_pkg._reset_for_tests()+ cred_mod._IDP_CACHE.clear()+++def _gets(plane):+ return [r for r in plane.requests if r["method"] == "GET"]+++def _config_cmd(capsys, *argv):+ from hermes_cli.config import config_command+ ns = argparse.Namespace(config_command=argv[0], key=argv[1], value=argv[2] if len(argv) > 2 else None,+ force=False)+ with pytest.raises(SystemExit) as exc:+ config_command(ns)+ return exc.value.code, capsys.readouterr().err+++# --- selection and reads ------------------------------------------------------------------++def test_selected_from_env_and_file_tooling_off(plane):+ backend = get_config_backend()+ assert backend.name == "remote"+ assert backend.supports_file_tooling() is False+ assert backend.honors_managed_config() is False+ assert "GATEWAY_RELAY_IDP_CLIENT_SECRET" in backend.protected_env_names()+++def test_reads_come_from_plane_not_local_file(plane):+ from hermes_cli.config import load_config+ plane.upper = {"model": {"default": "hermes-4", "provider": "nous"}, "terminal": {"timeout": 180}}+ local = plane.home / "config.yaml"+ local.write_text(json.dumps({"model": {"default": "LOCAL"}, "terminal": {"timeout": 1}}))++ cfg = load_config()++ assert cfg["model"]["default"] == "hermes-4"+ assert cfg["terminal"]["timeout"] == 180+ assert "display" in cfg # DEFAULT_CONFIG stays under the remote user layer+ assert fast_safe_load(local.read_text())["model"]["default"] == "LOCAL" # untouched+ gets = _gets(plane)+ assert gets and all(r["auth"] == f"Bearer {TOKEN}" and r["instance"] == INSTANCE for r in gets)+ assert gets[0]["profile"] == "default"+++def test_boot_fetch_runs_inside_load_hermes_dotenv(plane):+ from hermes_cli.env_loader import load_hermes_dotenv+ load_hermes_dotenv(hermes_home=plane.home)+ assert len(_gets(plane)) == 1+ load_hermes_dotenv(hermes_home=plane.home) # idempotent: one fetch per process per profile+ assert len(_gets(plane)) == 1+++# --- fail-closed boot ---------------------------------------------------------------------++def test_boot_retries_then_exits_on_outage(plane):+ from hermes_cli.env_loader import load_hermes_dotenv+ plane.fail_status = 503+ with pytest.raises(ConfigBackendUnavailable) as exc:+ load_hermes_dotenv(hermes_home=plane.home)+ assert len(_gets(plane)) == 3 # attempts at t=0, ~10 s, ~30 s (delays patched to 0)+ assert "does not start" in str(exc.value.code)+ assert isinstance(exc.value, SystemExit)+++def test_boot_does_not_retry_a_refusal(plane, monkeypatch):+ from hermes_cli.env_loader import load_hermes_dotenv+ monkeypatch.setenv("HERMES_CONFIG_INSTANCE_ID", "someone-else")+ with pytest.raises(ConfigBackendUnavailable) as exc:+ load_hermes_dotenv(hermes_home=plane.home)+ assert len(_gets(plane)) == 1+ assert "config_agent_unknown" in str(exc.value.code)+++def test_boot_requires_instance_id(plane, monkeypatch):+ from hermes_cli.config import load_config+ monkeypatch.delenv("HERMES_CONFIG_INSTANCE_ID")+ with pytest.raises(ConfigBackendUnavailable, match="HERMES_CONFIG_INSTANCE_ID"):+ load_config()+ assert plane.requests == []+++def test_bad_idp_credentials_fail_closed(plane, monkeypatch):+ from hermes_cli.config import load_config+ monkeypatch.setenv("GATEWAY_RELAY_IDP_CLIENT_SECRET", "wrong")+ with pytest.raises(ConfigBackendUnavailable, match="IdP token request"):+ load_config()+ assert plane.requests == [] # no /self call without a token+++def test_partial_idp_config_is_not_retried(plane, monkeypatch):+ from hermes_cli.config import load_config+ monkeypatch.delenv("GATEWAY_RELAY_IDP_CLIENT_SECRET")+ with pytest.raises(ConfigBackendUnavailable, match="CLIENT_SECRET"):+ load_config()+ assert plane.token_requests == 0+++def test_secret_source_supplying_plane_credential_refuses_start(plane):+ from types import SimpleNamespace++ from hermes_cli.env_loader import _refuse_protected_env_from_sources+ report = SimpleNamespace(provenance={"GATEWAY_RELAY_IDP_CLIENT_SECRET": object()},+ sources=[SimpleNamespace(skipped_existing=["HERMES_CONFIG_REMOTE_URL"])])+ with pytest.raises(ConfigBackendUnavailable) as exc:+ _refuse_protected_env_from_sources(report)+ assert "GATEWAY_RELAY_IDP_CLIENT_SECRET" in str(exc.value.code)+ assert "HERMES_CONFIG_REMOTE_URL" in str(exc.value.code)+ ok = SimpleNamespace(provenance={"OPENROUTER_API_KEY": object()}, sources=[])+ _refuse_protected_env_from_sources(ok) # unrelated names pass+++def test_boot_refuses_remote_secrets_source_that_maps_plane_credential(plane, monkeypatch):+ """End to end through load_hermes_dotenv: the REMOTE secrets: section drives the sources (D32)."""+ from types import SimpleNamespace++ from agent.secret_sources import registry+ from hermes_cli import env_loader+ plane.upper = {"secrets": {"command": {"enabled": True}}}+ seen = {}++ def fake_apply_all(cfg, home_path, environ=None):+ seen["cfg"] = cfg+ return SimpleNamespace(sources=[SimpleNamespace(skipped_existing=[])], applied_any=True,+ provenance={"HERMES_CONFIG_REMOTE_URL": SimpleNamespace(source="command")})++ monkeypatch.setattr(registry, "apply_all", fake_apply_all)+ monkeypatch.setattr(env_loader, "_APPLIED_HOMES", set())+ with pytest.raises(ConfigBackendUnavailable, match="HERMES_CONFIG_REMOTE_URL"):+ env_loader.load_hermes_dotenv(hermes_home=plane.home)+ assert seen["cfg"] == {"command": {"enabled": True}}+++def test_file_backend_has_no_protected_names(monkeypatch):+ from types import SimpleNamespace++ from hermes_cli.env_loader import _refuse_protected_env_from_sources+ monkeypatch.delenv("HERMES_CONFIG_BACKEND", raising=False)+ _refuse_protected_env_from_sources(+ SimpleNamespace(provenance={"GATEWAY_RELAY_IDP_CLIENT_SECRET": object()}, sources=[]))+++# --- writes -------------------------------------------------------------------------------++def test_config_set_sends_only_the_changed_key(plane):+ from hermes_cli.config import load_config, set_config_value+ plane.upper = {"model": {"default": "hermes-4", "provider": "nous"}, "terminal": {"timeout": 180}}++ set_config_value("display.personality", "pirate")++ patches = plane.patches()+ assert len(patches) == 1+ body = patches[0]["body"]+ assert body["set"] == {"display": {"personality": "pirate"}} # absent from the effective doc+ assert "unset" not in body+ assert body["expectedVersion"] == 0+ assert isinstance(body["writerConfigVersion"], int)+ assert plane.profile("default")["values"] == {"display": {"personality": "pirate"}}+ assert load_config()["display"]["personality"] == "pirate"+ assert not (plane.home / "config.yaml").exists()+++def test_change_under_existing_section_is_a_leaf_set(plane):+ from hermes_cli.config import set_config_value+ plane.upper = {"display": {"personality": "concise", "compact": False}}+ set_config_value("display.personality", "pirate")+ assert plane.patches()[0]["body"]["set"] == {"display.personality": "pirate"}+ assert plane.profile("default")["values"] == {"display": {"personality": "pirate"}}+++def test_write_conflict_rereads_and_retries_once(plane):+ from hermes_cli.config import load_config+ load_config()+ plane.profile("default")["version"] = 5 # another writer moved the profile level+ write_config_key(plane.home / "config.yaml", "display.personality", "pirate")+ patches = plane.patches()+ assert [p["body"]["expectedVersion"] for p in patches] == [0, 5]+ assert plane.profile("default")["version"] == 6+++def test_locked_key_refused_by_config_set_without_sending(plane, capsys):+ plane.upper = {"terminal": {"timeout": 180}}+ plane.upper_locks = [{"path": "terminal", "level": "tenant"}]++ code, err = _config_cmd(capsys, "set", "terminal.timeout", "5")++ assert code == 1+ assert "locked by the tenant level" in err+ assert plane.patches() == []+++def test_locked_key_refused_by_backend_single_key_write(plane):+ plane.upper_locks = [{"path": "terminal", "level": "tenant"}]+ with pytest.raises(ConfigLockedError) as exc:+ write_config_key(plane.home / "config.yaml", "terminal.backend", "local")+ assert (exc.value.path, exc.value.locked_by) == ("terminal", "tenant")+ assert plane.patches() == []+++def test_r7_scalar_over_locked_subtree_refused(plane):+ plane.upper_locks = [{"path": "a.b", "level": "tenant"}]+ with pytest.raises(ConfigLockedError):+ write_config_key(plane.home / "config.yaml", "a", "scalar")+ assert plane.patches() == []+++def test_bulk_save_strips_locked_keys_and_sends_the_rest(plane, capsys):+ from hermes_cli.config import read_raw_config, save_config+ plane.upper = {"terminal": {"timeout": 180}, "model": {"default": "hermes-4"}}+ plane.upper_locks = [{"path": "terminal", "level": "tenant"}]+ doc = read_raw_config()+ doc["terminal"]["timeout"] = 5+ doc["display"] = {"personality": "pirate"}++ save_config(doc)++ patches = plane.patches()+ assert len(patches) == 1+ assert patches[0]["body"]["set"] == {"display": {"personality": "pirate"}}+ assert "terminal.timeout" not in json.dumps(patches[0]["body"])+ assert "locked by Remote Config were not saved: terminal" in capsys.readouterr().err+++def test_secret_literal_refused_client_side(plane, capsys):+ with pytest.raises(ConfigValueError) as exc:+ write_config_key(plane.home / "config.yaml", "mcp_servers.github.env.GITHUB_TOKEN", "ghp_live")+ assert exc.value.code == "config_secret_literal"+ code, err = _config_cmd(capsys, "set", "delegation.api_key", "sk-live-abc")+ assert code == 1 and "secret-shaped" in err+ assert plane.patches() == []+ write_config_key(plane.home / "config.yaml", "delegation.api_key", "${OPENROUTER_API_KEY}")+ assert plane.patches()[-1]["body"]["set"] == {"delegation": {"api_key": "${OPENROUTER_API_KEY}"}}+++def test_unset_of_inherited_key_warns(plane, caplog):+ plane.upper = {"display": {"personality": "concise"}}+ plane.profile("default")["values"] = {"display": {"personality": "pirate"}}+ with caplog.at_level("WARNING"):+ write_config_key(plane.home / "config.yaml", "display.personality", None)+ assert plane.patches()[0]["body"]["unset"] == ["display.personality"]+ assert "still set by an upper level" in caplog.text+++def test_yaml_only_values_are_converted_before_the_diff(plane):+ import datetime+ write_config_key(plane.home / "config.yaml", "x.when", datetime.date(2026, 9, 25))+ write_config_key(plane.home / "config.yaml", "x.big", 2**60)+ sent = [p["body"]["set"] for p in plane.patches()]+ assert sent == [{"x": {"when": "2026-09-25"}}, {"x.big": str(2**60)}]+ with pytest.raises(ConfigValueError, match="NaN"):+ write_config_key(plane.home / "config.yaml", "x.nan", float("nan"))+++# --- poll, outage, versions ---------------------------------------------------------------++def test_poll_picks_up_changes_and_invalidates_caches(plane):+ from hermes_cli.config import load_config+ plane.upper = {"display": {"personality": "concise"}}+ assert load_config()["display"]["personality"] == "concise"+ backend = remote_pkg.get_remote_backend()+ v1 = backend.version(plane.home)++ backend.poll_all() # unchanged → 304+ assert plane.requests[-1]["if_none_match"] and backend.version(plane.home) == v1++ plane.upper = {"display": {"personality": "pirate"}}+ backend.poll_all()+ assert backend.version(plane.home) != v1+ assert load_config()["display"]["personality"] == "pirate"+++def test_outage_while_running_keeps_in_memory_doc(plane):+ from hermes_cli.config import load_config+ plane.upper = {"display": {"personality": "concise"}}+ load_config()+ backend = remote_pkg.get_remote_backend()+ plane.fail_status = 503++ backend.poll_all() # never raises, never exits++ assert load_config()["display"]["personality"] == "concise"+ assert "503" in backend.describe(plane.home)+ plane.fail_status = None+ backend.poll_all()+ assert "last poll failed" not in backend.describe(plane.home)+++def test_poll_refusal_logs_error_but_keeps_running(plane, caplog):+ from hermes_cli.config import load_config+ load_config()+ plane.fail_status = 403+ with caplog.at_level("WARNING"):+ remote_pkg.get_remote_backend().poll_all()+ assert [r.levelname for r in caplog.records if "poll for profile" in r.getMessage()] == ["ERROR"]+ plane.fail_status = 503+ caplog.clear()+ with caplog.at_level("WARNING"):+ remote_pkg.get_remote_backend().poll_all()+ assert [r.levelname for r in caplog.records if "poll for profile" in r.getMessage()] == ["WARNING"]+++def test_poll_interval_floor(monkeypatch):+ monkeypatch.setenv("HERMES_CONFIG_REMOTE_POLL_SECONDS", "1")+ assert backend_mod.poll_interval() == backend_mod.MIN_POLL_SECONDS+ monkeypatch.setenv("HERMES_CONFIG_REMOTE_POLL_SECONDS", "600")+ assert backend_mod.poll_interval() == 600+++def test_named_profile_fetches_its_own_layer(plane):+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override++ from hermes_cli.config import load_config+ work = plane.home / "profiles" / "work"+ work.mkdir(parents=True)+ plane.profile("work")["values"] = {"display": {"personality": "formal"}}+ token = set_hermes_home_override(work)+ try:+ assert load_config()["display"]["personality"] == "formal"+ finally:+ reset_hermes_home_override(token)+ assert {r["profile"] for r in _gets(plane)} == {"work"}+++# --- migrations, unknown keys, managed scope ----------------------------------------------++def test_old_writer_version_migrates_in_memory_only(plane):+ from hermes_cli.config import read_raw_config+ from hermes_cli.config_migrations import SUPPORT_FLOOR_VERSION+ latest = backend_mod._latest_config_version()+ old = max(SUPPORT_FLOOR_VERSION, latest - 1)+ plane.profile("default").update(values={"display": {"personality": "pirate"}}, version=1, writer=old)++ doc = read_raw_config()++ assert doc["_config_version"] == latest+ assert doc["display"]["personality"] == "pirate"+ assert plane.patches() == [] # D12: never written back+ assert not (plane.home / "config.yaml").exists()+++def test_migration_steps_persist_into_memory(plane, monkeypatch):+ """A migration step's ``_persist_migration`` lands in the in-memory layer, not on disk/plane."""+ from hermes_cli import config as config_mod+ from hermes_cli import config_migrations+ 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):+ doc = config_mod.read_raw_config()+ doc["new_key"] = doc.pop("old_key")+ config_mod._persist_migration(doc)++ monkeypatch.setattr(config_migrations, "run_migrations", fake_run_migrations)+ doc = config_mod.read_raw_config()+ assert doc.get("new_key") == 1 and "old_key" not in doc+ assert plane.patches() == []+++def test_unknown_top_level_key_warns_once(plane, caplog):+ from hermes_cli.config import load_config+ plane.upper = {"from_the_future": {"x": 1}}+ with caplog.at_level("WARNING"):+ load_config()+ load_config()+ assert caplog.text.count("unknown config key 'from_the_future'") == 1+++def test_managed_config_yaml_is_ignored_and_flagged(plane, tmp_path, monkeypatch, capsys):+ from hermes_cli import managed_scope+ from hermes_cli.config import load_config+ from hermes_cli.env_loader import load_hermes_dotenv+ managed = tmp_path / "etc-hermes"+ managed.mkdir()+ (managed / "config.yaml").write_text(json.dumps({"display": {"personality": "managed"}}))+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(managed))+ managed_scope._CONFIG_CACHE.clear()+ plane.upper = {"display": {"personality": "remote"}}++ load_hermes_dotenv(hermes_home=plane.home)++ assert "IGNORED" in capsys.readouterr().err+ assert managed_scope.load_managed_config() == {}+ assert load_config()["display"]["personality"] == "remote"+++# --- tooling ------------------------------------------------------------------------------++def test_file_tooling_refused(plane):+ from hermes_cli.config_backend import require_file_tooling+ with pytest.raises(ConfigBackendUnavailable, match="Profile clone"):+ require_file_tooling("Profile clone")+++def test_doctor_reports_backend_status(plane, capsys):+ from hermes_cli.doctor_config import _check_config_backend+ from hermes_cli.doctor_report import Finding+ f = Finding()+ assert _check_config_backend(get_config_backend(), plane.home, f) is True+ assert "Remote Config" in capsys.readouterr().out+ plane.fail_status = 503+ remote_pkg._reset_for_tests()+ f2 = Finding()+ assert _check_config_backend(get_config_backend(), plane.home, f2) is False+ assert f2.issues+++def test_general_plugin_manager_never_loads_config_backends(plane, monkeypatch):+ from hermes_cli.plugins import PluginManager+ monkeypatch.setenv("HERMES_CONFIG_BACKEND", "file")+ mgr = PluginManager()+ mgr.discover_and_load()+ assert not any("config_backends" in key or key == "remote" for key in mgr._plugins)diff --git a/tests/plugins/config_backends/test_remote_conformance.py b/tests/plugins/config_backends/test_remote_conformance.pynew file mode 100644index 00000000000..9c21b0f0265--- /dev/null+++ b/tests/plugins/config_backends/test_remote_conformance.py@@ -0,0 +1,105 @@+"""Vendored config-plane conformance fixtures, run against the agent's client-side rules+(contract.md §13): path grammar, secret-shaped keys, the profile-level write check fed+``expect.locks``, and ``defaultsMerge`` against ``_deep_merge``. The digest test pins the vendored+bytes to the manifest and to ``SOURCE.json``, so an edited fixture fails here, not in production."""+from __future__ import annotations++import hashlib+import json+from pathlib import Path++import pytest++from plugins.config_backends.remote import paths as P+from plugins.config_backends.remote.diff import write_check+from plugins.config_backends.remote.values import secret_literal_path++VENDOR = Path(__file__).resolve().parents[3] / "plugins" / "config_backends" / "remote" / "vendor"+MANIFEST = VENDOR / "conformance" / "config-fixtures.sha256"+RESOLUTION = sorted((VENDOR / "conformance" / "config-resolution").glob("*.json"))+++def _load(name: str):+ return json.loads((VENDOR / "conformance" / name).read_text(encoding="utf-8"))+++def test_vendored_fixtures_match_manifest_and_source():+ source = json.loads((VENDOR / "SOURCE.json").read_text(encoding="utf-8"))+ assert hashlib.sha256(MANIFEST.read_bytes()).hexdigest() == source["fixtureDigest"]+ listed = {}+ for line in MANIFEST.read_text(encoding="utf-8").splitlines():+ digest, rel = line.split(None, 1)+ listed[rel.strip()] = digest+ for rel, digest in listed.items():+ assert hashlib.sha256((VENDOR / rel).read_bytes()).hexdigest() == digest, rel+ on_disk = {str(p.relative_to(VENDOR)) for p in (VENDOR / "conformance").rglob("*.json")}+ assert on_disk == set(listed), "every vendored fixture is in the manifest and vice versa"+ assert len(RESOLUTION) > 0++[email protected]("vector", _load("config-paths.json")["valid"], ids=lambda v: v["encoded"])+def test_valid_paths_round_trip(vector):+ assert P.encode(vector["segments"]) == vector["encoded"]+ assert list(P.decode(vector["encoded"])) == vector["segments"]++[email protected]("encoded", _load("config-paths.json")["invalid"], ids=repr)+def test_invalid_paths_rejected(encoded):+ with pytest.raises(P.PathError):+ P.decode(encoded)++[email protected]("vector", _load("config-paths.json")["covers"],+ ids=lambda v: f"{v['lock']}|{v['path']}")+def test_lock_coverage(vector):+ assert P.covers(P.decode(vector["lock"]), P.decode(vector["path"])) is vector["covers"]++[email protected]("vector", _load("config-secret-keys.json")["vectors"],+ ids=lambda v: f"{v['path']}={v['value']!r}")+def test_secret_key_vectors(vector):+ path = P.decode(vector["path"])+ rejected = secret_literal_path(path, vector["value"]) is not None+ assert rejected is (vector["expect"] == "reject")+++def _profile_writes():+ for f in RESOLUTION:+ fx = json.loads(f.read_text(encoding="utf-8"))+ locks = [(P.decode(lk["path"]), lk["level"]) for lk in fx["expect"].get("locks", [])]+ for i, w in enumerate(fx.get("writes", [])):+ if w.get("by") == "profile" and w.get("op") in {"set", "unset"}:+ yield pytest.param(w, locks, id=f"{f.stem}#{i}")++[email protected]("write,locks", list(_profile_writes()))+def test_profile_write_check(write, locks):+ path = P.decode(write["path"])+ sets = {path: write.get("value")} if write["op"] == "set" else {}+ unsets = [path] if write["op"] == "unset" else []+ refused = write_check(sets, unsets, locks)+ secret = secret_literal_path(path, write.get("value")) if write["op"] == "set" else None+ expect = write["expect"]+ if expect["result"] == "accept":+ assert refused is None and secret is None+ return+ if expect["error"] == "config_key_locked":+ assert refused is not None+ assert P.encode(refused[0]) == expect["path"] and refused[1] == expect["lockedBy"]+ elif expect["error"] == "config_secret_literal":+ assert refused is None and secret is not None+ else: # an error the agent does not pre-check (the plane's own validation)+ pytest.skip(f"server-only error {expect['error']}")+++def _defaults_merges():+ for f in RESOLUTION:+ fx = json.loads(f.read_text(encoding="utf-8"))+ if "defaultsMerge" in fx:+ yield pytest.param(fx["defaultsMerge"], fx["expect"]["effective"], id=f.stem)++[email protected]("merge,effective", list(_defaults_merges()))+def test_defaults_merge_matches_deep_merge(merge, effective):+ from hermes_cli.config import _deep_merge+ assert _deep_merge(merge["defaults"], effective) == merge["expect"]diff --git a/tests/plugins/config_backends/test_remote_multiprocess.py b/tests/plugins/config_backends/test_remote_multiprocess.pynew file mode 100644index 00000000000..7ae0b49904c--- /dev/null+++ b/tests/plugins/config_backends/test_remote_multiprocess.py@@ -0,0 +1,77 @@+"""Every Hermes process type reads and writes through the remote backend with the same credential+(design §4.4 step 6, G3): a CLI ``config set`` in one process is seen by a gateway-boot process+and a TUI-gateway (dashboard) process, each of which fetched on its own at import time."""+from __future__ import annotations++import json+import os+import subprocess+import sys+from pathlib import Path++import pytest++from .stub_plane import INSTANCE, TOKEN, StubPlane, remote_env++REPO = Path(__file__).resolve().parents[3]++READ_SNIPPET = """+import json, sys+import {module}+from hermes_cli.config import load_config+print("RESULT=" + json.dumps(load_config()["display"]["personality"]))+"""+++def _run(args, env, timeout=120):+ return subprocess.run(args, cwd=REPO, env=env, capture_output=True, text=True, timeout=timeout,+ stdin=subprocess.DEVNULL)+++def plane_env(tmp_path):+ home = tmp_path / "home"+ home.mkdir()+ with StubPlane() as plane:+ env = {k: v for k, v in os.environ.items() if k in {"PATH", "HOME", "TMPDIR", "LANG", "TZ",+ "PYTHONHASHSEED", "HERMES_TEST_ISOLATION"}}+ env.update(remote_env(plane), HERMES_HOME=str(home), PYTHONPATH=str(REPO), HERMES_YOLO_MODE="",+ PYTHONDONTWRITEBYTECODE="1")+ plane.upper = {"display": {"personality": "concise"}}+ yield plane, env, home+++def _result(proc):+ assert proc.returncode == 0, proc.stderr[-3000:]+ # tui_gateway.server moves print() to stderr (stdout is its JSON-RPC channel), so read both.+ lines = [ln for ln in (proc.stdout + proc.stderr).splitlines() if ln.startswith("RESULT=")]+ assert lines, proc.stdout[-2000:] + proc.stderr[-2000:]+ return json.loads(lines[-1][len("RESULT="):])+++def test_cli_gateway_and_dashboard_share_the_remote_config(plane_env):+ plane, env, home = plane_env++ cli = _run([sys.executable, "-m", "hermes_cli.main", "config", "set", "display.personality", "pirate"], env)+ assert cli.returncode == 0, cli.stderr[-3000:]+ assert plane.profile("default")["values"] == {"display": {"personality": "pirate"}}++ gateway = _run([sys.executable, "-c", READ_SNIPPET.format(module="gateway.run")], env)+ assert _result(gateway) == "pirate"+ dashboard = _run([sys.executable, "-c", READ_SNIPPET.format(module="tui_gateway.server")], env)+ assert _result(dashboard) == "pirate"++ gets = [r for r in plane.requests if r["method"] == "GET"]+ assert len(gets) >= 3 # each process fetched for itself at boot+ assert {r["auth"] for r in plane.requests} == {f"Bearer {TOKEN}"}+ assert {r["instance"] for r in plane.requests} == {INSTANCE}+ assert not (home / "config.yaml").exists()+++def test_process_exits_non_zero_when_plane_is_down(plane_env, monkeypatch):+ plane, env, home = plane_env+ plane.fail_status = 403 # a refusal is not retried, so this is fast+ proc = _run([sys.executable, "-m", "hermes_cli.main", "config", "get", "display.personality"], env)+ assert proc.returncode != 0+ assert "Hermes does not start without its remote config" in proc.stderr+ assert "concise" not in proc.stdout # no default or cached value was serveddiff --git a/website/docs/user-guide/remote-config.md b/website/docs/user-guide/remote-config.mdnew file mode 100644index 00000000000..fc0787087b5--- /dev/null+++ b/website/docs/user-guide/remote-config.md@@ -0,0 +1,99 @@+---+sidebar_position: 4+title: "Remote Config"+description: "Serve each profile's config from the config plane instead of config.yaml"+---++# Remote Config++**Remote config mode** replaces `config.yaml` with the config plane: each+profile's config is the document the plane resolves for this agent instance+and that profile. The plane layers it from global, tenant, group, owner, and+agent settings, with the profile's own settings last. Administrators can lock+keys at an upper level, and the agent cannot change a locked key.++Remote config is for fleet deployments, for example Hermes Cloud. A single+machine with one user should keep `config.yaml`.++## Turning it on++Set the following in the environment or in `~/.hermes/.env`. A value in+`config.yaml` cannot select the backend, because the backend is what serves+config.++| Variable | Meaning |+|---|---|+| `HERMES_CONFIG_BACKEND=remote` | Use the config plane instead of `config.yaml` (default `file`). |+| `HERMES_CONFIG_INSTANCE_ID` | This agent's id in the plane. Hermes Cloud sets it; on-prem the operator sets it when registering the agent. Required. |+| `HERMES_CONFIG_REMOTE_URL` | The plane's base URL (default `https://config-config.nousresearch.com`). |+| `HERMES_CONFIG_REMOTE_POLL_SECONDS` | How often each process checks for changes (default `300`, minimum `30`). |++The agent authenticates as itself:++- **Hermes Cloud**: the Nous access token in the profile's `auth.json`.+- **On-prem**: an OAuth2 client-credentials token from your identity provider,+ configured in `.env` with `GATEWAY_RELAY_IDP_TOKEN_URL`,+ `GATEWAY_RELAY_IDP_CLIENT_ID`, `GATEWAY_RELAY_IDP_CLIENT_SECRET`, and+ 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+(1Password, Bitwarden, a command) supplies any of them, Hermes refuses to+start.++## What changes++- **Startup fetches config and fails closed.** Every Hermes process (gateway,+ dashboard, CLI, terminal children) fetches its profile's config when it+ loads `.env`. If the plane cannot be reached after about 30 seconds of+ retries, or refuses the agent, the process exits with an error. It never+ falls back to a local file or to defaults.+- **No local config file.** `config.yaml` is neither read nor written, and+ there is no local cache. A running process keeps the config it last fetched+ in memory. If the plane becomes unreachable while Hermes runs, the process+ keeps its in-memory config and retries on the next poll.+- **Changes arrive by polling.** Each process checks for changes every+ `HERMES_CONFIG_REMOTE_POLL_SECONDS`. A change made in the plane reaches a+ running agent within one interval.+- **Writes go to the profile's own level.** `hermes config set`, `/model`,+ the dashboard, and every other config writer send only the keys that changed,+ guarded against concurrent edits. Removing a key removes it from the profile+ level only: if an upper level also sets it, that value still applies, and+ Hermes warns you.+- **Locked keys are refused.** `hermes config set` on a locked key prints which+ level locks it and changes nothing. When a whole document is saved, locked+ keys are left out, 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+ `.env` or a secret source and set the reference:++ ```bash+ hermes config set model.api_key '${OPENROUTER_API_KEY}'+ ```++- **`secrets:` comes from the plane** like any other key, so administrators can+ manage and lock secret-source settings centrally.+- **Schema migrations run in memory.** A document written by an older Hermes is+ migrated when it is read, and the result is not written back.+- **Unknown keys** in the fetched document are ignored with a warning, for+ example a key added by a newer Hermes.++## Managed scope++`/etc/hermes/config.yaml` (see [Managed Scope](./managed-scope.md)) is+**ignored** in remote mode: config and locks come only from the plane. Hermes+warns at startup, and `hermes doctor` flags the file. The managed+`/etc/hermes/.env` still applies.++## Commands that work on the config file++These commands copy or edit `config.yaml` and are refused in remote mode:++- `hermes config edit` (use `hermes config set` instead)+- profile clone and profile distribution install+- `hermes backup`, `hermes import`, and snapshot restore+- `hermes gateway --config <file>`++`hermes doctor` reports the backend instead of the file: the plane URL, the+profile, the profile level's version, the number of locks, and when the config+was last fetched.diff --git a/website/sidebars.ts b/website/sidebars.tsindex 0b6a05597fb..dab078f6da0 100644--- a/website/sidebars.ts+++ b/website/sidebars.ts@@ -37,6 +37,7 @@ const sidebars: SidebarsConfig = {'user-guide/configuration','user-guide/which-file-does-what','user-guide/managed-scope',+ 'user-guide/remote-config','user-guide/configuring-models',{type: 'category',