The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(hermes_cli): surface fail-closed config write refusals cleanly
kshitijk4poor93a29d110db7
diff --git a/hermes_cli/approval_mode.py b/hermes_cli/approval_mode.pyindex 5e29552a0fd..0bd7d3a314a 100644--- a/hermes_cli/approval_mode.py+++ b/hermes_cli/approval_mode.py@@ -52,8 +52,9 @@ def run_approval_mode_command(requested_mode: Optional[str]) -> ApprovalModeResu)# set_config_value is the canonical managed-scope/write-safety chokepoint.- # It reports managed policy through stderr + SystemExit, so capture that for- # slash-command output instead of terminating the interactive worker.+ # It reports managed policy through stderr + SystemExit, and the fail-closed+ # write guard raises RuntimeError on an unparseable config.yaml; capture both+ # for slash-command output instead of terminating the interactive worker.from hermes_cli.config import set_config_valueoutput = StringIO()diff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex d74d8168d9c..ef939e154bc 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -141,6 +141,12 @@ def _warn_config_parse_failure(f"Keeping the previously loaded config for this process — "f"edits to config.yaml are being IGNORED until the YAML is fixed.")+ elif fallback == "refuse-write":+ msg = (+ f"Failed to parse {config_path}: {exc}. "+ f"REFUSING to write config.yaml so the existing file is preserved. "+ f"Fix the YAML (hermes config edit) and retry."+ )else:msg = (f"Failed to parse {config_path}: {exc}. "@@ -5897,7 +5903,13 @@ def config_command(args):print(" --force: skip the unknown-key notice for unrecognized keys,")print(" and allow a scalar to replace a whole mapping section")sys.exit(1)- set_config_value(key, value, force=force)+ try:+ set_config_value(key, value, force=force)+ except RuntimeError as exc:+ # Fail-closed write guard (unparseable / non-mapping / unreadable+ # config.yaml). Surface a clean CLI error instead of a traceback.+ print(f"✗ {exc}", file=sys.stderr)+ sys.exit(1)elif subcmd == "unset":key = getattr(args, 'key', None)@@ -5909,7 +5921,12 @@ def config_command(args):print(" hermes config unset terminal.backend")print(" hermes config unset OPENROUTER_API_KEY")sys.exit(1)- unset_config_value(key)+ try:+ unset_config_value(key)+ except RuntimeError as exc:+ # Same fail-closed guard surface as `config set` above.+ print(f"✗ {exc}", file=sys.stderr)+ sys.exit(1)elif subcmd == "path":print(get_config_path())diff --git a/hermes_cli/console_engine.py b/hermes_cli/console_engine.pyindex 2728af3ff9b..a2cf380c719 100644--- a/hermes_cli/console_engine.py+++ b/hermes_cli/console_engine.py@@ -72,6 +72,15 @@ def _capture_output(fn: Callable[[], object]) -> str:code = 1else:code = int(exc.code or 0)+ except ConsoleCommandError:+ raise+ except RuntimeError as exc:+ # Fail-closed config write guards raise RuntimeError (e.g.+ # require_readable_config_before_write refusing an unparseable+ # config.yaml). Convert to a console error instead of letting it+ # escape execute() and kill the REPL / websocket session.+ message = str(exc)+ code = 1text = stdout.getvalue() + stderr.getvalue()if code:raise ConsoleCommandError(message.strip() or text.strip() or f"Command exited with status {code}")diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 778181c2eb4..467ab2637a7 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -5892,7 +5892,16 @@ def cmd_config(args):"""Configuration management."""from hermes_cli.config import config_command- config_command(args)+ try:+ config_command(args)+ except RuntimeError as exc:+ # Safety net for the fail-closed config write guard (unparseable /+ # non-mapping / unreadable config.yaml raises RuntimeError from+ # require_readable_config_before_write). set/unset already surface+ # this per-branch; this covers migrate and future write subcommands+ # so no path ends in a raw traceback.+ print(f"✗ {exc}", file=sys.stderr)+ sys.exit(1)def cmd_skin(args):diff --git a/tests/hermes_cli/test_config.py b/tests/hermes_cli/test_config.pyindex 8478f454eb4..807a85c77c6 100644--- a/tests/hermes_cli/test_config.py+++ b/tests/hermes_cli/test_config.py@@ -1691,3 +1691,50 @@ def test_default_config_has_no_duplicate_top_level_keys():if "model" in keys and "kanban" in keys: # the DEFAULT_CONFIG literaldupes = {k for k in keys if keys.count(k) > 1}assert not dupes, f"duplicate DEFAULT_CONFIG keys: {sorted(dupes)}"+++class TestConfigCommandFailClosedSurface:+ """`hermes config set/unset` must exit cleanly (no traceback) when the+ fail-closed write guard refuses an unparseable config.yaml."""++ def _args(self, **kw):+ import argparse++ ns = argparse.Namespace()+ for k, v in kw.items():+ setattr(ns, k, v)+ return ns++ def test_config_command_set_exits_cleanly_on_broken_yaml(self, tmp_path, capsys):+ from hermes_cli.config import config_command++ config_path = tmp_path / "config.yaml"+ original = "model:\n default: keep\nbroken: [unterminated\n"+ config_path.write_text(original, encoding="utf-8")++ with patch.dict(os.environ, {"HERMES_HOME": str(tmp_path)}):+ with pytest.raises(SystemExit) as excinfo:+ config_command(+ self._args(config_command="set", key="model.default",+ value="gpt-4o", force=False)+ )++ assert excinfo.value.code == 1+ err = capsys.readouterr().err+ assert "not valid YAML" in err+ assert config_path.read_text(encoding="utf-8") == original++ def test_config_command_unset_exits_cleanly_on_broken_yaml(self, tmp_path, capsys):+ from hermes_cli.config import config_command++ config_path = tmp_path / "config.yaml"+ original = "model:\n default: keep\nbroken: [unterminated\n"+ config_path.write_text(original, encoding="utf-8")++ with patch.dict(os.environ, {"HERMES_HOME": str(tmp_path)}):+ with pytest.raises(SystemExit) as excinfo:+ config_command(self._args(config_command="unset", key="model.default"))++ assert excinfo.value.code == 1+ assert "not valid YAML" in capsys.readouterr().err+ assert config_path.read_text(encoding="utf-8") == originaldiff --git a/tests/hermes_cli/test_console_engine.py b/tests/hermes_cli/test_console_engine.pyindex 1b56ef8d402..67a7c0c6da4 100644--- a/tests/hermes_cli/test_console_engine.py+++ b/tests/hermes_cli/test_console_engine.py@@ -586,3 +586,22 @@ def test_console_checkpoints_prune_succeeds_without_a_tty(assert "Aborted." not in result.outputassert len(prune_calls) == 1assert prune_calls[0]["orphan_allowlist"] is None+++def test_config_set_on_unparseable_yaml_reports_error_not_crash(tmp_path, monkeypatch):+ """The fail-closed config write guard raises RuntimeError; the console must+ surface it as a command error, not let it escape execute() and kill the+ REPL / dashboard websocket session (regression for PR #71385 follow-up)."""+ config_path = tmp_path / "config.yaml"+ original = "model:\n default: keep\nbroken: [unterminated\n"+ config_path.write_text(original, encoding="utf-8")+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))++ result = HermesConsoleEngine().execute(+ "config set model.default gpt-4o", confirmed=True+ )++ assert result.status == "error"+ assert "not valid YAML" in (result.output or "") or "Failed to parse" in (result.output or "")+ # The broken-but-recoverable file must survive untouched.+ assert config_path.read_text(encoding="utf-8") == original