Skip to content

The agent that grows with you

fix(config-remote): an explicit config set is stored even when it equals the inherited value

Teknium714eab92e933
diff --git a/hermes_cli/config.py b/hermes_cli/config.py
index 205557d009e..74af83c9f4a 100644
--- a/hermes_cli/config.py
+++ b/hermes_cli/config.py
@@ -3403,7 +3403,9 @@ def set_config_value(key: str, value: str, force: bool = False):
user_config = _normalize_root_model_keys(user_config)
key = "model.base_url"
print(" (note: 'api_base' is an alias — saved as model.base_url)")
- _write_user_config(config_path, user_config)
+ from hermes_cli.config_backend import pinning_keys
+ with pinning_keys(key): # an explicit set is stored even when it equals the inherited value
+ _write_user_config(config_path, user_config)
# Keep .env in sync: terminal_tool reads TERMINAL_ENV etc. directly from env vars.
env_var = terminal_config_env_var_for_key(key)
diff --git a/hermes_cli/config_backend.py b/hermes_cli/config_backend.py
index 76a142e88a0..622d5f47771 100644
--- a/hermes_cli/config_backend.py
+++ b/hermes_cli/config_backend.py
@@ -523,6 +523,27 @@ def refused_locked_omission_prefixes() -> tuple[str, ...]:
return _REFUSE_LOCKED_OMISSIONS.get()
+# Dotted keys a document save in this context stores at the user layer even when the value equals
+# what an upper level already supplies (an explicit `config set`): the file backend always writes
+# them, and a backend with levels must not drop them as "no change".
+_PINNED_KEYS: contextvars.ContextVar[tuple[str, ...]] = contextvars.ContextVar("config_pinned_keys", default=())
+
+
+def pinning_keys(*keys: str):
+ """Within the block, a document save stores *keys* (dotted) at the user layer even when
+ unchanged from the inherited value. No-op for the file backend (it writes the whole file)."""
+ token = _PINNED_KEYS.set(_PINNED_KEYS.get() + tuple(keys))
+ try:
+ yield
+ finally:
+ _PINNED_KEYS.reset(token)
+
+
+def pinned_keys() -> tuple[str, ...]:
+ return _PINNED_KEYS.get()
+
+
def write_changes(config_path: PathLike, changes: Changes) -> None:
"""One :class:`Changes` write. Unlike :func:`write_config_keys`, a ``None`` in ``set`` stores
an explicit null (Remote Config: "no value", masking an inherited scalar); the file backend
diff --git a/plugins/config_backends/remote/backend.py b/plugins/config_backends/remote/backend.py
index 61e6eacbf2d..0e32f355d6d 100644
--- a/plugins/config_backends/remote/backend.py
+++ b/plugins/config_backends/remote/backend.py
@@ -23,14 +23,14 @@ from typing import Any, Dict, List, Optional, Tuple
from hermes_cli.config_backend import (
Changes, ConfigBackendUnavailable, ConfigLockedError, ConfigValueError, ConfigWriteError, UserLayer,
- refused_locked_omission_prefixes)
+ pinned_keys, refused_locked_omission_prefixes)
from . import client
from .credentials import PLANE_CREDENTIAL_ENV_NAMES, PlaneCredentialError
from .diff import (_get_path, _pop_path, _set_path, apply_intent, diff, encode_changes, intent_diff, json_equal,
strip_locked, write_check)
from .paths import Path as KeyPath
-from .paths import PathError, covers, decode, encode, from_dotted
+from .paths import PathError, covering_lock, covers, decode, encode, from_dotted
from .values import secret_literal_path, to_wire
logger = logging.getLogger(__name__)
@@ -501,7 +501,7 @@ class RemoteBackend:
re-read doc, with the re-read locks; it never replays the caller's whole document, which
would turn every key another writer changed meanwhile into an edit of ours."""
st = self._state(home)
- intent: Optional[tuple[dict[KeyPath, Any], list[KeyPath]]] = None
+ intent: Optional[tuple[dict[KeyPath, Any], list[KeyPath], frozenset]] = None
for attempt in (1, 2):
for _ in range(self._MAX_PREPARE):
# Diff against the doc readers get, i.e. migrated in memory (D12) — also after the
@@ -550,13 +550,20 @@ class RemoteBackend:
base.pop("_config_version", None)
return base
- def _intent(self, st: _ProfileState, changes: Changes) -> tuple[dict[KeyPath, Any], list[KeyPath]]:
+ def _intent(self, st: _ProfileState, changes: Changes
+ ) -> tuple[dict[KeyPath, Any], list[KeyPath], frozenset]:
"""The key-level edit ``changes`` makes to the last read doc (§15.2 steps 1-5).
A document is diffed against the base THIS context read it from (``_READ_BASE``): a poll
landing between the caller's read and its save must not turn every key the poll changed
into an edit of ours, sent with the already-current expectedVersion (no 409 to catch it).
- A keyed set/unset names its own keys, so it applies to the current base."""
+ A keyed set/unset names its own keys, so it applies to the current base.
+
+ The third item is the leaf paths a keyed ``set`` (or, for a document save, a
+ :func:`~hermes_cli.config_backend.pinning_keys` block) names: they are stored at the profile
+ level even when the value equals the inherited one, as the file backend writes them into
+ ``config.yaml``. Otherwise ``config set k v`` with ``v`` equal to the upper level's value
+ would report success, store nothing, and follow the next upper-level change."""
base = self._diff_base(st)
if changes.document is not None:
read = _read_base_for(st) if _private_for(st) is None else None
@@ -588,15 +595,37 @@ class RemoteBackend:
f"{', '.join(sorted(encode(p) for p in dropped))}", file=sys.stderr)
# Leaf-level: a key added under a section the doc lacked stays a key-level edit, so a
# retry after 409 keeps the siblings another writer put in that section meanwhile.
- return intent_diff(base, new)
-
- def _patch_body(self, st: _ProfileState, sets: dict[KeyPath, Any], unsets: list[KeyPath]
+ sets, unsets = intent_diff(base, new)
+ pinned: set[KeyPath] = set()
+ named = list(changes.set) + (list(pinned_keys()) if changes.document is not None else [])
+ for key in named:
+ path = from_dotted(key)
+ found, wire = _get_path(new, path)
+ if not found: # a locked key a document save dropped
+ continue
+ leaves = intent_diff({}, wire, path)[0] if isinstance(wire, dict) and wire else {path: wire}
+ for leaf, leaf_value in leaves.items():
+ sets.setdefault(leaf, leaf_value)
+ pinned.add(leaf)
+ return sets, unsets, frozenset(pinned)
+
+ def _patch_body(self, st: _ProfileState, intent_sets: dict[KeyPath, Any], unsets: list[KeyPath],
+ pinned: frozenset = frozenset()
) -> Optional[tuple[dict[str, Any], dict[KeyPath, Any], list[KeyPath]]]:
- """The PATCH body applying the intent to the current doc, or None when that is no change."""
+ """The PATCH body applying the intent to the current doc, or None when that is no change.
+ A *pinned* key equal to the inherited value is still sent, unless a lock already freezes
+ it (nothing to store, and refusing a no-op pick of the locked value helps nobody)."""
base = self._diff_base(st)
new = copy.deepcopy(base)
- apply_intent(new, sets, unsets)
+ apply_intent(new, intent_sets, unsets)
sets, unsets = diff(base, new)
+ for path in pinned:
+ value = intent_sets[path]
+ if isinstance(value, dict) and not value:
+ continue # "make this a mapping" (apply_intent): sent above when absent, kept when present
+ if path not in sets and covering_lock(st.locks, path) is None \
+ and not any(covers(p, path) for p in sets):
+ sets[path] = copy.deepcopy(value)
refused = write_check(sets, unsets, st.locks)
if refused is not None:
raise ConfigLockedError(encode(refused[0]), refused[1],
diff --git a/tests/plugins/config_backends/test_remote_pinned_sets.py b/tests/plugins/config_backends/test_remote_pinned_sets.py
new file mode 100644
index 00000000000..8517fdcbe8f
--- /dev/null
+++ b/tests/plugins/config_backends/test_remote_pinned_sets.py
@@ -0,0 +1,57 @@
+"""A keyed ``config set`` stores its value at the profile level even when it equals the inherited
+one (the file backend writes every keyed set into config.yaml), and a rotated IdP client secret
+takes effect on the next request instead of after the cached token expires."""
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+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 .stub_plane import 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 test_set_equal_to_inherited_value_is_stored_and_survives_an_upper_change(plane):
+ from hermes_cli.config import set_config_value
+ from hermes_cli.config_backend import read_config_doc
+
+ plane.upper = {"display": {"skin": "ares"}}
+
+ set_config_value("display.skin", "ares")
+
+ assert plane.profile("default")["values"] == {"display": {"skin": "ares"}}
+ plane.upper = {"display": {"skin": "slate"}}
+ remote_pkg._reset_for_tests()
+ assert read_config_doc(plane.home / "config.yaml")["display"]["skin"] == "ares"
+
+
+def test_rotated_idp_client_secret_fetches_a_new_token(plane, monkeypatch):
+ cred_mod.plane_token(plane.home)
+ first = plane.token_requests
+ cred_mod.plane_token(plane.home)
+ assert plane.token_requests == first # same secret: served from the cache
+
+ monkeypatch.setenv("GATEWAY_RELAY_IDP_CLIENT_SECRET", "rotated-secret")
+ with pytest.raises(cred_mod.PlaneCredentialError):
+ cred_mod.plane_token(plane.home) # the stub only accepts the original secret
+ assert plane.token_requests == first + 1