Skip to content

The agent that grows with you

fix(config-remote): review round 7 — grouped edits are one write, readers see only completed migrations

Ben Barclayf15b518b257b
diff --git a/hermes_cli/config_backend.py b/hermes_cli/config_backend.py
index 6663efc457d..ce20702cd09 100644
--- a/hermes_cli/config_backend.py
+++ b/hermes_cli/config_backend.py
@@ -390,9 +390,19 @@ def write_config_document(config_path: PathLike, document: dict, *, extra_conten
def write_config_key(config_path: PathLike, key_path: str, value: Any) -> None:
"""Set one dotted key (``None`` removes it) — ``atomic_roundtrip_yaml_update`` semantics."""
- backend, home = _route(config_path)
- backend.write_changes(home, Changes(unset=(key_path,)) if value is None else Changes(set={key_path: value}))
+ write_config_keys(config_path, {key_path: value})
+
+
+def write_config_keys(config_path: PathLike, updates: Mapping[str, Any]) -> None:
+ """Set several related dotted keys (``None`` removes one) as ONE write.
+ A remote backend sends them as one CAS PATCH, so a refusal of any of them (a lock, a value
+ check) changes none of them: a grouped edit such as a model switch (default + provider + ...)
+ never lands half-applied. The file backend applies them key by key, as before."""
+ backend, target, is_layer = _route(config_path)
+ changes = Changes(set={k: v for k, v in updates.items() if v is not None},
+ unset=tuple(k for k, v in updates.items() if v is None))
+ backend.write_changes(target, changes) if is_layer else backend.write_path(target, changes)
def deployment_env_names() -> frozenset:
diff --git a/hermes_cli/model_switch.py b/hermes_cli/model_switch.py
index 17a0c701e61..bbcc69c61cf 100644
--- a/hermes_cli/model_switch.py
+++ b/hermes_cli/model_switch.py
@@ -1861,9 +1861,15 @@ def persist_model_selection(result: ModelSwitchResult, config_path: Any = None)
config lock, once one exists, must wrap the same section."""
from pathlib import Path
from hermes_cli.config import _CONFIG_LOCK, atomic_config_replace, get_config_path, read_user_config_raw
+ from hermes_cli.config_backend import supports_file_tooling, write_config_keys
path = Path(config_path) if config_path else get_config_path()
planned_from = read_user_config_raw(path).get("model")
updates = model_selection_config_updates(result, planned_from)
+ if not supports_file_tooling():
+ # No config file (Remote Config): one keyed write, so a lock on any key refuses the whole
+ # switch instead of a document save silently omitting the locked part.
+ write_config_keys(path, {f"model.{key}": value for key, value in updates.items()})
+ return
with _CONFIG_LOCK:
config = read_user_config_raw(path)
model_cfg = config.get("model")
diff --git a/plugins/config_backends/remote/backend.py b/plugins/config_backends/remote/backend.py
index 12b0d4a80ab..3b6781777d9 100644
--- a/plugins/config_backends/remote/backend.py
+++ b/plugins/config_backends/remote/backend.py
@@ -79,8 +79,7 @@ class _ProfileState:
gen: int = 0
installed: int = 0 # bumped by every _install; a GET started before a newer install is stale
base: Optional[Dict[str, Any]] = None # the migrated doc writes diff against (None = server_config)
- postprocessed: bool = False
- in_postprocess: bool = False
+ postprocessed: bool = False # st.doc is the completed migration output of generation `installed`
fetched_at: float = 0.0
last_error: Optional[str] = None
next_poll: float = 0.0
@@ -279,20 +278,38 @@ class RemoteBackend:
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:
+ _MAX_POSTPROCESS = 8 # passes when polls keep installing newer docs mid-migration
+
+ def _completed(self, st: _ProfileState) -> bool:
+ """Bring the published doc to its completed postprocess output; False when that is not
+ possible yet (``hermes_cli.config`` still importing during the boot fetch)."""
+ if _private_for(st) is not None:
+ return True # a migration's own reads use its private copy (never another pass)
+ for _ in range(self._MAX_POSTPROCESS):
+ ready = self._postprocess(st)
+ if not ready:
+ return False
+ with st.lock:
+ if st.postprocessed:
+ return True
+ raise ConfigWriteError("Remote Config: the profile's config kept changing while it was migrated in memory",
+ code="config_version_conflict")
+
+ def _postprocess(self, st: _ProfileState) -> bool:
"""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."""
+ when the boot fetch runs (then False: nothing could be done).
+
+ No single flight: a reader or writer that finds the published doc unmigrated runs its own
+ private pass, even while another thread's pass is in flight, and the first pass to finish
+ publishes. Waiting for the other pass instead could deadlock (a migration reads through
+ hermes_cli.config's _CONFIG_LOCK, which the waiting caller may hold), and returning the
+ unmigrated doc meanwhile would hand that caller legacy settings the migration removes."""
if _private_for(st) is not None:
- return # a migration's own reads: never start another one
- # The flag, not st.lock, guards the work: a migration reads through hermes_cli.config (its
- # _CONFIG_LOCK), and holding st.lock across that could deadlock against a writer that holds
- # _CONFIG_LOCK and waits for st.lock. A concurrent reader meanwhile gets the published
- # (unmigrated) doc, and a concurrent writer diffs against its matching base.
+ return True # a migration's own reads: never start another one
with st.lock:
- if st.postprocessed or st.in_postprocess:
- return
- st.in_postprocess = True
+ if st.postprocessed:
+ return True
# The doc, its schema version and its generation are captured together: a poll may
# install a newer doc at any point after this, and migrating that doc from THIS version
# would run steps its data never needed (and, D12, drop settings it holds on purpose).
@@ -300,25 +317,25 @@ class RemoteBackend:
current = int(st.doc.get("_config_version") or 0)
doc = copy.deepcopy(st.doc)
try:
- try:
- from hermes_cli.config import _known_top_level_keys
- from hermes_cli.config_migrations import SUPPORT_FLOOR_VERSION
- except ImportError:
- return # still importing; the next read retries
- for key in sorted(set(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)
- latest = _latest_config_version()
- if SUPPORT_FLOOR_VERSION <= current < latest:
- self._migrate_in_memory(st, seen, current, doc)
- 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)
- with st.lock:
- st.postprocessed = st.installed == seen # a doc installed meanwhile needs its own pass
- finally:
- st.in_postprocess = False
+ from hermes_cli.config import _known_top_level_keys
+ from hermes_cli.config_migrations import SUPPORT_FLOOR_VERSION
+ except ImportError:
+ return False # still importing; the next read retries
+ for key in sorted(set(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)
+ latest = _latest_config_version()
+ if SUPPORT_FLOOR_VERSION <= current < latest:
+ self._migrate_in_memory(st, seen, current, doc)
+ return True
+ if 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)
+ with st.lock:
+ if st.installed == seen: # a doc installed meanwhile needs its own pass
+ st.postprocessed = True
+ return True
def _run_private(self, st: _ProfileState, doc: Dict[str, Any], current: int) -> Dict[str, Any]:
"""Run the migrations from schema *current* over a private copy of *doc* and return it.
@@ -341,22 +358,24 @@ class RemoteBackend:
"""Migrate doc generation *started* (*doc*, schema version *current*) in memory (D12).
The steps work on a private copy; the result is published with its diff base in one step,
- and only while generation *started* is still the installed one: once a poll or write has
- installed another doc, nothing of this migration lands on it (that doc gets its own pass).
+ and only while generation *started* is still the installed one and no concurrent pass over
+ it has published first: once a poll or write has installed another doc, nothing of this
+ migration lands on it (that doc gets its own pass).
The migrated doc becomes the base later writes diff against: a reader was handed the
migrated doc, so a write that leaves the migration's changes in place must not send them
(D12: never write the migration back)."""
with st.lock:
- if st.installed != started:
- return # replaced before we began
+ if st.installed != started or st.postprocessed:
+ return # replaced, or another pass already published this generation
migrated = self._run_private(st, doc, current)
migrated["_config_version"] = _latest_config_version()
base = copy.deepcopy(migrated)
base.pop("_config_version", None)
with st.lock:
- if st.installed != started:
- return # a poll or write installed a newer doc mid-migration
+ if st.installed != started or st.postprocessed:
+ return # a poll or write installed a newer doc, or a concurrent pass published
self._publish_locked(st, migrated, base)
+ st.postprocessed = True
logger.info("Remote Config: migrated profile %r in memory from config version %d", st.profile, current)
@staticmethod
@@ -368,22 +387,38 @@ class RemoteBackend:
# --- ConfigBackend: reads ---------------------------------------------------------------
+ def _snapshot(self, st: _ProfileState, take):
+ """``take()`` under st.lock once the published doc is completed postprocess output (or
+ this thread's own migration copy). A poll that installs a newer doc between completing
+ and taking sends the caller round again, so no reader ever sees an unmigrated doc."""
+ for _ in range(self._MAX_POSTPROCESS):
+ ready = self._completed(st)
+ with st.lock:
+ if not ready or st.postprocessed or _private_for(st) is not None:
+ return take()
+ raise ConfigWriteError("Remote Config: the profile's config kept changing while it was read",
+ code="config_version_conflict")
+
def read_user_layer(self, home: Path) -> UserLayer:
st = self._state(home)
- self._postprocess(st)
- with st.lock:
+
+ def take():
m = _private_for(st)
- doc = copy.deepcopy(m.doc if m is not None else st.doc)
- version = self._version_of(st)
- locks = {encode(p): level for p, level in st.locks}
+ return (copy.deepcopy(m.doc if m is not None else st.doc), self._version_of(st),
+ {encode(p): level for p, level in st.locks})
+
+ doc, version, locks = self._snapshot(st, take)
return UserLayer(doc=doc, version=version, locks=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)
- m = _private_for(st)
- return m.doc if m is not None else st.doc
+
+ def take():
+ m = _private_for(st)
+ return m.doc if m is not None else st.doc
+
+ return self._snapshot(st, take)
@staticmethod
def _version_of(st: _ProfileState) -> Tuple[Any, ...]:
@@ -425,11 +460,14 @@ class RemoteBackend:
st = self._state(home)
intent: Optional[Tuple[Dict[KeyPath, Any], List[KeyPath]]] = None
for attempt in (1, 2):
- # Diff against the doc readers get, i.e. migrated in memory (D12) — also after the CAS
- # re-read below. Outside st.lock: a migration reads through hermes_cli.config.
- self._postprocess(st)
for _ in range(self._MAX_PREPARE):
+ # Diff against the doc readers get, i.e. migrated in memory (D12) — also after the
+ # CAS re-read below or a poll landing mid-prepare. Outside st.lock: a migration
+ # reads through hermes_cli.config.
+ ready = self._completed(st)
with st.lock:
+ if ready and not st.postprocessed:
+ continue # a poll installed a newer doc since: complete that one first
seen = st.installed
if intent is None:
intent = self._intent(st, changes)
diff --git a/tests/plugins/config_backends/test_remote_grouped_and_migration_reads.py b/tests/plugins/config_backends/test_remote_grouped_and_migration_reads.py
new file mode 100644
index 00000000000..44b05a2852c
--- /dev/null
+++ b/tests/plugins/config_backends/test_remote_grouped_and_migration_reads.py
@@ -0,0 +1,314 @@
+"""Remote config review round 7: grouped edits are one write, and readers see only completed
+in-memory migrations.
+
+1. A grouped edit (a model switch's ``model.*`` keys, the TUI ``/focus`` and ``thinking_mode``
+ setters) is ONE backend write: a lock on any of its keys refuses all of them, so a refused
+ switch never leaves a half-applied route. Unlocked, the whole group lands.
+2. While one reader migrates a legacy profile in memory (D12), a concurrent reader or writer
+ never observes the unmigrated document: it gets completed migration output.
+"""
+from __future__ import annotations
+
+import threading
+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 hermes_cli.config_backend import ConfigLockedError, get_config_backend
+
+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 _tui_server(monkeypatch, home):
+ import hermes_cli.banner as banner
+ monkeypatch.setattr(banner, "prefetch_update_check", lambda: None)
+ from tui_gateway import server
+ monkeypatch.setattr(server, "_hermes_home", home)
+ server._cfg_cache = server._cfg_sig = server._cfg_path = None
+ return server
+
+
+def _switch(model="new-model", provider="new-provider"):
+ from hermes_cli.model_switch import ModelSwitchResult
+ return ModelSwitchResult(success=True, new_model=model, target_provider=provider, provider_changed=True,
+ api_key="", base_url="", api_mode="", is_global=True)
+
+
+# --- 1. grouped edits ----------------------------------------------------------------------
+
+def test_locked_provider_refuses_the_whole_model_switch(plane):
+ """A tenant lock on model.provider alone: the switch raises and model.default stays put."""
+ from hermes_cli.config import read_raw_config
+ from hermes_cli.model_switch import persist_model_selection
+ plane.upper = {"model": {"default": "old-model", "provider": "old-provider"}}
+ plane.upper_locks = [{"path": "model.provider", "level": "tenant"}]
+
+ with pytest.raises(ConfigLockedError):
+ persist_model_selection(_switch(), plane.home / "config.yaml")
+
+ assert plane.patches() == []
+ assert plane.profile("default") == {"values": {}, "version": 0, "writer": None}
+ model = read_raw_config()["model"]
+ assert (model["default"], model["provider"]) == ("old-model", "old-provider")
+
+
+def test_unlocked_model_switch_is_one_patch_and_keeps_siblings(plane):
+ from hermes_cli.model_switch import persist_model_selection
+ plane.profile("default").update(values={"model": {"default": "old-model", "provider": "old-provider",
+ "model_slots": {"fast": "mini"}}}, version=1)
+
+ persist_model_selection(_switch(), plane.home / "config.yaml")
+
+ (patch,) = plane.patches()
+ assert patch["body"]["expectedVersion"] == 1
+ model = plane.profile("default")["values"]["model"]
+ assert (model["default"], model["provider"]) == ("new-model", "new-provider")
+ assert model["model_slots"] == {"fast": "mini"}
+
+
+def test_file_backend_model_switch_still_writes_every_key(tmp_path, monkeypatch):
+ """Control: the file backend keeps its key-by-key round-trip (comments, siblings intact)."""
+ import hermes_yaml as yaml
+ from hermes_cli.model_switch import persist_model_selection
+ monkeypatch.delenv("HERMES_CONFIG_BACKEND", raising=False)
+ remote_pkg._reset_for_tests()
+ cfg = tmp_path / "config.yaml"
+ cfg.write_text("# keep me\nmodel:\n default: old\n provider: old-p\n api_mode: x\n model_slots:\n"
+ " fast: mini\n", encoding="utf-8")
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+
+ persist_model_selection(_switch(), cfg)
+
+ text = cfg.read_text(encoding="utf-8")
+ model = yaml.safe_load(text)["model"]
+ assert "# keep me" in text
+ assert model == {"default": "new-model", "provider": "new-provider", "model_slots": {"fast": "mini"}}
+
+
+def test_tui_focus_on_under_a_partial_lock_changes_nothing(plane, monkeypatch):
+ """/focus on writes focus_saved_tool_progress + tool_progress + focus_view; a lock on
+ focus_view alone refuses all three (no stash or mode left behind), and the session is unchanged."""
+ plane.upper = {"display": {"tool_progress": "verbose", "focus_view": False}}
+ plane.upper_locks = [{"path": "display.focus_view", "level": "tenant"}]
+ monkeypatch.delenv("HERMES_TUI_TOOL_PROGRESS", raising=False)
+ server = _tui_server(monkeypatch, plane.home)
+ session = {"session_key": "k", "tool_progress_mode": "verbose", "focus_view": False}
+ server._sessions["s1"] = session
+ try:
+ answer = server._methods["config.set"](1, {"key": "focus", "value": "on", "session_id": "s1"})
+
+ assert answer["error"]["code"] == 4002 and "locked" in answer["error"]["message"]
+ assert plane.patches() == []
+ assert session == {"session_key": "k", "tool_progress_mode": "verbose", "focus_view": False}
+ display = server._load_cfg_raw()["display"]
+ assert display["tool_progress"] == "verbose" and "focus_saved_tool_progress" not in display
+
+ plane.upper_locks = []
+ backend = get_config_backend()
+ assert backend.poll_one(backend._state(plane.home))
+ answer = server._methods["config.set"](2, {"key": "focus", "value": "on", "session_id": "s1"})
+ finally:
+ server._sessions.pop("s1", None)
+ assert answer["result"]["value"] == "on"
+ assert session["focus_view"] is True and session["tool_progress_mode"] == "off"
+ (patch,) = plane.patches()
+ stored = plane.profile("default")["values"]["display"]
+ assert stored == {"focus_saved_tool_progress": "verbose", "tool_progress": "off", "focus_view": True}
+ assert "unset" not in patch["body"]
+
+
+def test_tui_thinking_mode_under_a_partial_lock_changes_nothing(plane, monkeypatch):
+ plane.upper = {"display": {"thinking_mode": "collapsed", "details_mode": "collapsed"}}
+ plane.upper_locks = [{"path": "display.details_mode", "level": "group"}]
+ server = _tui_server(monkeypatch, plane.home)
+
+ answer = server._methods["config.set"](1, {"key": "thinking_mode", "value": "full"})
+
+ assert answer["error"]["code"] == 4002 and "locked" in answer["error"]["message"]
+ assert plane.patches() == []
+ assert server._load_cfg_raw()["display"]["thinking_mode"] == "collapsed"
+
+ plane.upper_locks = []
+ backend = get_config_backend()
+ assert backend.poll_one(backend._state(plane.home))
+ assert "result" in server._methods["config.set"](2, {"key": "thinking_mode", "value": "full"})
+ assert len(plane.patches()) == 1
+ assert plane.profile("default")["values"]["display"] == {"thinking_mode": "full", "details_mode": "expanded"}
+
+
+# --- 2. readers see only completed migrations -----------------------------------------------
+
+def _legacy_profile(plane):
+ latest = backend_mod._latest_config_version()
+ assert latest > 46
+ plane.profile("default").update(values={"compression": {"threshold_tokens": 256000}}, version=1, writer=46)
+ return latest
+
+
+def _pause_first_migration(backend, monkeypatch, name="migrator"):
+ """Pause the named thread's private migration run after its steps ran, before it publishes."""
+ entered, resume = threading.Event(), threading.Event()
+ real = backend._run_private
+
+ def paused(*args, **kwargs):
+ out = real(*args, **kwargs)
+ if threading.current_thread().name == name:
+ entered.set()
+ assert resume.wait(10), "the migrating thread was never released"
+ return out
+
+ monkeypatch.setattr(backend, "_run_private", paused)
+ return entered, resume
+
+
+def _start(target, name):
+ failures, results = [], []
+
+ def run():
+ try:
+ results.append(target())
+ except BaseException as exc: # noqa: BLE001 — surfaced by the caller
+ failures.append(exc)
+
+ t = threading.Thread(target=run, name=name)
+ t.start()
+ return t, results, failures
+
+
+def test_concurrent_reader_never_sees_the_unmigrated_doc(plane, monkeypatch):
+ from hermes_cli.config_backend import read_config_doc
+ latest = _legacy_profile(plane)
+ backend = get_config_backend()
+ backend._state(plane.home)
+ entered, resume = _pause_first_migration(backend, monkeypatch)
+ cfg = plane.home / "config.yaml"
+
+ migrator, first, failures = _start(lambda: read_config_doc(cfg), "migrator")
+ try:
+ assert entered.wait(10)
+ second = read_config_doc(cfg) # while the first migration is paused, unpublished
+ finally:
+ resume.set()
+ migrator.join(10)
+ assert not migrator.is_alive() and not failures, failures
+
+ for doc in (second, first[0]):
+ assert doc["_config_version"] == latest
+ assert "threshold_tokens" not in (doc.get("compression") or {})
+ assert plane.patches() == []
+
+
+def test_concurrent_readonly_reader_never_sees_the_unmigrated_doc(plane, monkeypatch):
+ from hermes_cli.config_backend import read_config_doc_readonly
+ latest = _legacy_profile(plane)
+ backend = get_config_backend()
+ backend._state(plane.home)
+ entered, resume = _pause_first_migration(backend, monkeypatch)
+ cfg = plane.home / "config.yaml"
+
+ migrator, _, failures = _start(lambda: read_config_doc_readonly(cfg), "migrator")
+ try:
+ assert entered.wait(10)
+ doc = read_config_doc_readonly(cfg)
+ assert doc["_config_version"] == latest and "threshold_tokens" not in (doc.get("compression") or {})
+ finally:
+ resume.set()
+ migrator.join(10)
+ assert not migrator.is_alive() and not failures, failures
+
+
+def test_writer_during_a_migration_sends_only_its_edit(plane, monkeypatch):
+ """Concurrent-writer control: the edit diffs against completed migration output, so the
+ migration's removal is never sent (D12) and the stored legacy value survives."""
+ from hermes_cli.config import read_raw_config, set_config_value
+ from hermes_cli.config_backend import read_config_doc
+ _legacy_profile(plane)
+ backend = get_config_backend()
+ backend._state(plane.home)
+ entered, resume = _pause_first_migration(backend, monkeypatch)
+
+ migrator, _, failures = _start(lambda: read_config_doc(plane.home / "config.yaml"), "migrator")
+ try:
+ assert entered.wait(10)
+ set_config_value("display.personality", "pirate")
+ finally:
+ resume.set()
+ migrator.join(10)
+ assert not migrator.is_alive() and not failures, failures
+
+ (patch,) = plane.patches()
+ assert "unset" not in patch["body"] and "compression" not in str(patch["body"])
+ assert "writerConfigVersion" not in patch["body"] # option 1: the old stamp is kept
+ assert plane.profile("default")["values"]["compression"] == {"threshold_tokens": 256000}
+ later = read_raw_config()
+ assert later["display"]["personality"] == "pirate"
+ assert "threshold_tokens" not in (later.get("compression") or {})
+
+
+def test_poll_installing_a_newer_doc_mid_read_is_migrated_before_it_is_returned(plane, monkeypatch):
+ """A poll installs a fresh legacy doc between a reader completing the old one and taking its
+ snapshot: the reader goes round again and still returns only migrated output."""
+ from hermes_cli.config_backend import read_config_doc
+ latest = _legacy_profile(plane)
+ backend = get_config_backend()
+ st = backend._state(plane.home)
+ real = backend._completed
+ polled = []
+
+ def poll_after_completing(state):
+ ready = real(state)
+ if not polled:
+ polled.append(1)
+ plane.profile("default").update(values={"compression": {"threshold_tokens": 256000},
+ "display": {"personality": "pirate"}}, version=2)
+ assert backend.poll_one(st) and st.postprocessed is False
+ return ready
+
+ monkeypatch.setattr(backend, "_completed", poll_after_completing)
+ doc = read_config_doc(plane.home / "config.yaml")
+ assert polled and doc["_config_version"] == latest
+ assert doc["display"]["personality"] == "pirate" # the newer doc, not the first one
+ assert "threshold_tokens" not in (doc.get("compression") or {})
+
+
+def test_migration_recursion_still_sees_its_private_copy(plane, monkeypatch):
+ """Control: a migration step's own reads get its private copy without starting another pass."""
+ 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)
+ seen = []
+
+ def step(current, results, quiet, **kwargs):
+ doc = config_mod.read_raw_config()
+ seen.append(doc.get("_config_version"))
+ doc.pop("old_key", None)
+ doc["new_key"] = 2
+ config_mod._persist_migration(doc)
+
+ monkeypatch.setattr(config_migrations, "run_migrations", step)
+ doc = config_mod.read_raw_config()
+
+ assert seen == [latest - 1]
+ assert doc["new_key"] == 2 and "old_key" not in doc
+ assert plane.patches() == []
diff --git a/tui_gateway/methods_config_set.py b/tui_gateway/methods_config_set.py
index 696eed56c15..30104da010c 100644
--- a/tui_gateway/methods_config_set.py
+++ b/tui_gateway/methods_config_set.py
@@ -270,14 +270,15 @@ def _set_focus(rid, params, key, value, session):
return _err(rid, 4002, f"unknown focus value: {value} (use on|off|status)")
if action == "status" or target is None:
return _kv(rid, key, "on" if cur_focus else "off", tool_progress=_load_tool_progress_mode())
+ updates = {}
if target:
saved = (cur_focus and d_f.get("focus_saved_tool_progress")) or _load_tool_progress_mode()
- _write_config_key("display.focus_saved_tool_progress", normalize_tool_progress_mode(saved))
+ updates["display.focus_saved_tool_progress"] = normalize_tool_progress_mode(saved)
effective = FOCUS_TOOL_PROGRESS_MODE
else:
effective = normalize_tool_progress_mode(d_f.get("focus_saved_tool_progress") or "all")
- _write_config_key("display.tool_progress", effective)
- _write_config_key("display.focus_view", bool(target))
+ updates.update({"display.tool_progress": effective, "display.focus_view": bool(target)})
+ _write_config_keys(updates) # one write: a refused key leaves focus fully as it was
if session:
session["focus_view"] = bool(target)
session["tool_progress_mode"] = effective
@@ -377,8 +378,8 @@ def _word_setters() -> dict:
sections={section: w for section in _DETAIL_SECTION_NAMES}, details_mode=w)),
# thinking_mode also keeps details_mode aligned (compat bridge).
"thinking_mode": (_word, {"collapsed", "truncated", "full"}, "unknown thinking_mode: {value}", lambda w: (
- _write_config_key("display.thinking_mode", w),
- _write_config_key("display.details_mode", "expanded" if w == "full" else "collapsed"))),
+ _write_config_keys({"display.thinking_mode": w,
+ "display.details_mode": "expanded" if w == "full" else "collapsed"}))),
# 'light'/'dark' pin beats background auto-detection (xterm.js hosts misreport OSC 11).
"theme": (_word, {"auto", "light", "dark"}, "unknown theme value: {value} (use auto|light|dark)",
lambda w: _write_config_key("display.tui_theme", w)),
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index d32368d06ae..9f45a54d44f 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -1362,17 +1362,25 @@ def _write_config_changes(sets: dict, unsets: tuple = ()) -> None:
def _write_config_key(key_path: str, value):
+ _write_config_keys({key_path: value})
+
+
+def _write_config_keys(updates: dict) -> None:
+ """Set related dotted keys together: ONE backend write without a config file (remote), so a
+ refused key changes none of them; one raw round-trip save with the file backend."""
if not supports_file_tooling():
- _write_config_changes({key_path: value})
+ _write_config_changes(updates)
return
# Write-back round-trip: raw read is mandatory — saving the overlaid/expanded view would persist it.
- cfg = current = _load_cfg_raw()
- *parents, leaf = key_path.split(".")
- for key in parents:
- if not isinstance(current.get(key), dict):
- current[key] = {}
- current = current[key]
- current[leaf] = value
+ cfg = _load_cfg_raw()
+ for key_path, value in updates.items():
+ current = cfg
+ *parents, leaf = key_path.split(".")
+ for key in parents:
+ if not isinstance(current.get(key), dict):
+ current[key] = {}
+ current = current[key]
+ current[leaf] = value
_save_cfg(cfg)
diff --git a/website/docs/developer-guide/config-backend.md b/website/docs/developer-guide/config-backend.md
index 158fd4fa42c..9fab84e0a4d 100644
--- a/website/docs/developer-guide/config-backend.md
+++ b/website/docs/developer-guide/config-backend.md
@@ -37,8 +37,15 @@ change detector whose false positive reconnects something, a parse-failure recor
manifest, hook-consent, free-tier and onboarding stamps do). "Recent" is judged on ctime as well as
mtime, because `cp -p` or `rsync --inplace -t` restore an older mtime after writing. A worker bound to
a frozen config snapshot never hashes a `config.yaml`: its key stays stat-only there, so the content
-check never makes such a worker open the profile file. The managed scope (`/etc/hermes`) stays an overlay on top
-of whatever user layer the backend returns.
+check never makes such a worker open the profile file. Caches keyed on `config_cache_version` miss
+when a remote poll installs a new layer, exactly as they do after a local file edit. With the file
+backend, the managed scope (`/etc/hermes`) stays an overlay on top of the user layer. The remote
+backend ignores the managed `config.yaml`: config and locks come only from Remote Config, and
+`hermes doctor` flags the file if it exists. The managed `.env` still applies in both modes.
+
+Related keys that must change together (a model switch's `model.*` keys, the TUI `/focus`
+toggle) go through `write_config_keys(path, {key: value, ...})`. A remote backend sends them
+as one CAS write, so a lock on any of them refuses all of them.
## Lints