The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(config): reader gate tracks every binding form and scans pm/
kshitijk4poorb7cd1f084b4c
diff --git a/hermes_cli/config_backups.py b/hermes_cli/config_backups.pyindex e722fa1cf5f..1649a0dcf1b 100644--- a/hermes_cli/config_backups.py+++ b/hermes_cli/config_backups.py@@ -65,7 +65,7 @@ def backup_config(config_path: Path, reason: str, *, keep: int = DEFAULT_KEEP) -dest = root / f"{config_path.name}.{reason}.{time.strftime('%Y%m%d-%H%M%S')}"if dest.is_symlink() or dest.exists(): # never write through a planted linkreturn None- shutil.copy2(config_path, dest)+ shutil.copy2(config_path, dest) # config-reader: ok — file tooling, gated abovefor stale in [dest, *existing][keep:]:stale.unlink(missing_ok=True)return destdiff --git a/pm/client.py b/pm/client.pyindex b52f8041f88..b79d0c12deb 100644--- a/pm/client.py+++ b/pm/client.py@@ -233,7 +233,7 @@ def sync_venv(extras=None, *, explicit=False, plugins: PluginInput | None = Noneif isinstance(plugins, Selection) and "expected_config" not in plugins.data:from pm.filesystem import file_digestplugins = Selection({**plugins.data,- "expected_config": file_digest(Path(plugins.data["home"]) / "config.yaml") or "missing"})+ "expected_config": file_digest(Path(plugins.data["home"]) / "config.yaml") or "missing"}) # config-reader: ok — pm publication: byte-level compare-and-swap rewrite of the local fileforeign = project_root is not None and Path(project_root).resolve() != paths.repo_root().resolve()if is_runtime() and not foreign:from pm.install import sync_venv as directdiff --git a/pm/plugin_eviction.py b/pm/plugin_eviction.pyindex c73007d44ad..ab3236fcb49 100644--- a/pm/plugin_eviction.py+++ b/pm/plugin_eviction.py@@ -206,7 +206,7 @@ class PluginEviction:self.edits: list[tuple[Path, bytes | None, bytes]] = []for home, changes in by_home.items():path = home / "config.yaml"- previous = read_bytes_or_none(path)+ previous = read_bytes_or_none(path) # config-reader: ok — pm publication: byte-level compare-and-swap rewrite of the local fileyaml = roundtrip_yaml()config = (yaml.load(previous.decode("utf-8-sig")) if previous else None) or {}# read_home_selection already proved plugins is a mapping and the lists are lists.diff --git a/pm/plugins_state.py b/pm/plugins_state.pyindex 21007c09c89..8be64dd5ad3 100644--- a/pm/plugins_state.py+++ b/pm/plugins_state.py@@ -29,20 +29,17 @@ def read_home_selection(home: Path) -> Optional[dict[str, Any]]:An unreadable selection raises rather than shrinking the next dependency generation;empty YAML is an explicit empty configuration, as in the CLI loader."""+ # Missing YAML support is a broken runtime, not an empty plugin selection.+ from ruamel.yaml.error import YAMLError+ from hermes_cli.config_backend import read_config_doc+config_path = home / "config.yaml"try:- text = config_path.read_text(encoding="utf-8-sig")+ config = read_config_doc(config_path)except FileNotFoundError:return Noneexcept (OSError, UnicodeError) as exc:raise ValueError(f"could not read plugin selection: {config_path}") from exc-- # Missing YAML support is a broken runtime, not an empty plugin selection.- import utils- from ruamel.yaml.error import YAMLError-- try:- config = utils.fast_safe_load(text)except YAMLError as exc:raise ValueError(f"could not parse plugin selection: {config_path}") from excif config is None:diff --git a/pm/publication.py b/pm/publication.pyindex b1d5db6defb..0deff0ccf9e 100644--- a/pm/publication.py+++ b/pm/publication.py@@ -46,7 +46,8 @@ def candidate_members(extra_dirs=(), **selection):def selection_snapshot() -> dict[Path, bytes | None]:from pm.plugins_state import dependency_homes- return {home / "config.yaml": read_bytes_or_none(home / "config.yaml") for home in dependency_homes()}+ return {home / "config.yaml": read_bytes_or_none(home / "config.yaml") # config-reader: ok — pm publication: byte-level compare-and-swap rewrite of the local file+ for home in dependency_homes()}def validate_manifest(source: Path) -> dict:@@ -69,7 +70,7 @@ class PluginSelection:if not self.home.is_relative_to(dependency_home_root().resolve()):raise ValueError("config path is outside Hermes state")self.path = self.home / "config.yaml"- self.previous = read_bytes_or_none(self.path)+ self.previous = read_bytes_or_none(self.path) # config-reader: ok — pm publication: byte-level compare-and-swap rewrite of the local fileexpected = selection.get("expected_config")actual = hashlib.sha256(self.previous).hexdigest() if self.previous is not None else "missing"if expected is not None and expected != actual:diff --git a/scripts/check_config_yaml_readers.py b/scripts/check_config_yaml_readers.pyindex 87f51289ba9..24962fc24fa 100644--- a/scripts/check_config_yaml_readers.py+++ b/scripts/check_config_yaml_readers.py@@ -39,7 +39,7 @@ from pathlib import PathROOT = Path(__file__).resolve().parent.parentDEFAULT_TREES = (- "hermes_cli", "agent", "gateway", "tui_gateway", "cron", "plugins", "tools", "acp_adapter",+ "hermes_cli", "agent", "gateway", "tui_gateway", "cron", "plugins", "tools", "acp_adapter", "pm","cli.py", "utils.py", "hermes_constants.py", "hermes_logging.py", "hermes_time.py", "run_agent.py","model_tools.py", "batch_runner.py")# The backend module itself, and the on-disk primitives it wraps.@@ -64,7 +64,9 @@ FUNC_READS = {"exists", "isfile", "open", "getmtime", "getsize", "stat", "load_yaml_file_readonly", "fast_safe_load",# Every PyYAML entry point that parses a stream, not just safe_load."safe_load", "safe_load_all", "full_load", "full_load_all", "unsafe_load", "unsafe_load_all",- "load_all", "compose", "compose_all"}+ "load_all", "compose", "compose_all",+ # Byte reads and file copies of the user layer (pm snapshots/digests, shutil.copy*).+ "read_bytes_or_none", "file_digest", "copy", "copy2", "copyfile"}BYPASS_WRITERS = {"atomic_roundtrip_yaml_update", "atomic_roundtrip_yaml_save", "atomic_write_text"}YAML_HELPER_RE = re.compile(r"(load|read)_yaml|yaml_(load|read)")@@ -109,7 +111,7 @@ class _Scanner:return b"\n".join([b[start - 1][c0:], *b[start:end - 1], b[end - 1][:c1]]).decode("utf-8", "replace")def is_config_path(self, node: ast.AST, names: set[str]) -> bool:- if isinstance(node, ast.Name) and node.id in names:+ if isinstance(node, (ast.Name, ast.Attribute)) and self.seg(node) in names:return Trueif isinstance(node, ast.Call) and _func_name(node.func) in {"Path", "str", "expanduser", "resolve"}:inner = node.args[0] if node.args else (node.func.value if isinstance(node.func, ast.Attribute) else None)@@ -128,17 +130,30 @@ class _Scanner:# Two passes so `a = home / "config.yaml"; b = a` binds b too.for _ in range(2):for node in _scope_nodes(scope):- targets: list = []if isinstance(node, ast.Assign):- targets, value = node.targets, node.value+ pairs = [(t, node.value) for t in node.targets]elif isinstance(node, (ast.AnnAssign, ast.NamedExpr)) and node.value is not None:- targets, value = [node.target], node.value+ pairs = [(node.target, node.value)]+ elif isinstance(node, (ast.For, ast.AsyncFor, ast.comprehension)):+ # `for p in (home / "config.yaml", ...)` binds p to each element.+ elts = node.iter.elts if isinstance(node.iter, (ast.Tuple, ast.List, ast.Set)) else [node.iter]+ pairs = [(node.target, e) for e in elts]else:continue- if self.is_config_path(value, names):- names.update(t.id for t in targets if isinstance(t, ast.Name))+ for target, value in pairs:+ self._bind(target, value, names)return names+ def _bind(self, target: ast.AST, value: ast.AST, names: set[str]) -> None:+ """Add *target* (a name, ``self.attr``, or an unpacked tuple element) when *value* is a config path."""+ if isinstance(target, (ast.Tuple, ast.List)):+ if isinstance(value, (ast.Tuple, ast.List)) and len(value.elts) == len(target.elts):+ for t, v in zip(target.elts, value.elts):+ self._bind(t, v, names)+ return+ if isinstance(target, (ast.Name, ast.Attribute)) and self.is_config_path(value, names):+ names.add(self.seg(target))+def flag(self, node: ast.Call, why: str) -> None:line = self.lines[node.lineno - 1]if SUPPRESS_RE.search(line):@@ -159,6 +174,11 @@ class _Scanner:if name in PATH_METHOD_READS and receiver is not None and self.is_config_path(receiver, names):self.flag(node, f"direct {name}() of a config path ({self.seg(receiver)})")return+ # Unbound form: ``Path.read_text(p)`` / ``Path.exists(p)``.+ if (name in PATH_METHOD_READS and isinstance(receiver, ast.Name) and receiver.id == "Path"+ and first is not None and self.is_config_path(first, names)):+ self.flag(node, f"direct Path.{name}() of a config path ({self.seg(first)})")+ returnis_reader = name in FUNC_READS or YAML_HELPER_RE.search(name) is not Noneif name == "load" and receiver is not None and "yaml" in self.seg(receiver).lower():is_reader = Truediff --git a/tests/hermes_cli/test_config_backend.py b/tests/hermes_cli/test_config_backend.pyindex ca077314a5d..b26cf2a0359 100644--- a/tests/hermes_cli/test_config_backend.py+++ b/tests/hermes_cli/test_config_backend.py@@ -240,6 +240,24 @@ class TestReaderGate:with patch.object(guard, "ROOT", tmp_path):assert len(guard.scan_file(bad)) == 1+ @pytest.mark.parametrize("body", [+ "env_path, p = home / '.env', home / 'config.yaml'\n return p.exists()",+ "self.cfg = home / 'config.yaml'\n return open(self.cfg)",+ "for p in (home / 'config.yaml',):\n p.read_text()",+ "p = home / 'config.yaml'\n return Path.read_text(p)",+ "p = home / 'config.yaml'\n shutil.copy2(p, home / 'bak')",+ "return read_bytes_or_none(home / 'config.yaml')",+ ])+ def test_every_binding_form_is_tracked(self, tmp_path, body):+ # Tuple unpacking, attributes, loop targets, unbound Path methods, copies, byte reads.+ guard = self._guard()+ bad = tmp_path / "pm" / "bad_reader.py"+ bad.parent.mkdir()+ bad.write_text(f"def a(self, home):\n {body}\n", encoding="utf-8")+ with patch.object(guard, "ROOT", tmp_path):+ assert len(guard.scan_file(bad)) == 1+ assert "pm" in guard.DEFAULT_TREES+def test_backend_calls_are_clean(self, tmp_path):guard = self._guard()good = tmp_path / "hermes_cli" / "good_reader.py"diff --git a/tools/send_message_tool.py b/tools/send_message_tool.pyindex 913cae0d4f9..bd078299d82 100644--- a/tools/send_message_tool.py+++ b/tools/send_message_tool.py@@ -336,6 +336,7 @@ def _not_configured_error(platform_name, platform, entry):from gateway.config import _getenvfrom gateway.config_env import _ENV_ENABLE_CREDENTIALSfrom hermes_constants import get_hermes_home+ from hermes_cli.config_backend import config_existshome = get_hermes_home()env_names = list(_ENV_ENABLE_CREDENTIALS.get(platform) or (entry.required_env if entry else ()))names = "/".join(env_names) or "credentials"@@ -349,7 +350,7 @@ def _not_configured_error(platform_name, platform, entry):block = user_config.get("platforms", {}).get(platform_name)except Exception:user_config, block = {}, None- if not config_path.exists():+ if not config_exists(config_path):config_state = "missing"elif not isinstance(block, dict):config_state = f"no platforms.{platform_name} block"