The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(hermes_cli): table-drive codex config migration translation, extract atomic write
Teknium92945b7b5b01
diff --git a/hermes_cli/codex_runtime_plugin_migration.py b/hermes_cli/codex_runtime_plugin_migration.pyindex 310867762fa..6e5f3829b2a 100644--- a/hermes_cli/codex_runtime_plugin_migration.py+++ b/hermes_cli/codex_runtime_plugin_migration.py@@ -1,5 +1,4 @@-"""Migrate Hermes' MCP server config and Codex's installed curated plugins to the format Codex expects-in ~/.codex/config.toml.+"""Migrate Hermes MCP server config and Codex's installed curated plugins into ~/.codex/config.toml."""from __future__ import annotations@@ -13,14 +12,12 @@ from typing import Any, Optionallogger = logging.getLogger(__name__)-# Marker comments wrapping the managed section so re-runs can detect-# what's ours and what's user-edited. Both must appear or strip is a no-op.+# Marker comments wrapping the managed section so re-runs can detect what's ours and what's+# user-edited. Both must appear or strip is a no-op.MIGRATION_MARKER = ("# managed by hermes-agent — `hermes codex-runtime migrate` regenerates this section")-MIGRATION_END_MARKER = (- "# end hermes-agent managed section"-)+MIGRATION_END_MARKER = "# end hermes-agent managed section"@dataclass@@ -47,179 +44,142 @@ class MigrationReport:lines.append(f"Migrated {len(self.migrated)} MCP server(s):")for name in self.migrated:skipped = self.skipped_keys_per_server.get(name, [])- note = (- f" (skipped: {', '.join(skipped)})" if skipped else ""- )+ note = f" (skipped: {', '.join(skipped)})" if skipped else ""lines.append(f" - {name}{note}")else:lines.append("No MCP servers found in Hermes config.")if self.migrated_plugins:- lines.append(- f"Migrated {len(self.migrated_plugins)} native Codex plugin(s):"- )- for name in self.migrated_plugins:- lines.append(f" - {name}")+ lines.append(f"Migrated {len(self.migrated_plugins)} native Codex plugin(s):")+ lines.extend(f" - {name}" for name in self.migrated_plugins)elif self.plugin_query_error:lines.append(f"Codex plugin discovery skipped: {self.plugin_query_error}")if self.wrote_permissions_default:- lines.append(- f"Wrote default_permissions = "- f"{self.wrote_permissions_default!r}"- )- for err in self.errors:- lines.append(f"⚠ {err}")+ lines.append(f"Wrote default_permissions = {self.wrote_permissions_default!r}")+ lines.extend(f"⚠ {err}" for err in self.errors)return "\n".join(lines)-# Hermes keys that codex's MCP schema doesn't support — dropped during-# migration with a warning. Anything not on the keep list AND not the-# transport keys is added to skipped.+# Hermes MCP keys codex understands (transport stdio/http, timeouts, general). Any other key is+# dropped with a warning: ``sampling`` has no codex equivalent; the rest are unknown Hermes keys._KNOWN_HERMES_KEYS = {- # transport — stdio"command", "args", "env", "cwd",- # transport — http"url", "headers", "transport",- # timeouts"timeout", "connect_timeout",- # general"enabled", "description",}+_KEYS_DROPPED_WITH_WARNING = {"sampling"}++# (hermes key, codex key, skip note) — timeouts are emitted as floats or skipped when non-numeric.+_TIMEOUT_KEYS = (+ ("timeout", "tool_timeout_sec", "timeout (not numeric)"),+ ("connect_timeout", "startup_timeout_sec", "connect_timeout (not numeric)"),+)-# Subset that have a direct codex equivalent.-_KEYS_DROPPED_WITH_WARNING = {- # Hermes' sampling subsection — codex MCP has no equivalent- "sampling",-}+def _str_map(d: dict) -> dict[str, str]:+ """Codex expects string keys and values in env / header tables."""+ return {str(k): str(v) for k, v in d.items()}-def _translate_one_server(- name: str, hermes_cfg: dict-) -> tuple[Optional[dict], list[str]]:- """Translate one Hermes MCP server config to the codex inline-table dict representation. Returns- (codex_entry, skipped_keys).++def _translate_one_server(name: str, hermes_cfg: dict) -> tuple[Optional[dict], list[str]]:+ """Translate one Hermes MCP server config to codex's inline-table dict.++ Returns ``(codex_entry, skipped_keys)``; ``codex_entry`` is None when the config is unusable.+ stdio (``command``) wins over ``url`` when both are set. Hermes' ``transport: sse`` hint is+ informational only — codex auto-negotiates. ``enabled`` is emitted only when explicitly false+ (codex defaults to true)."""if not isinstance(hermes_cfg, dict):return None, []skipped: list[str] = []out: dict[str, Any] = {}-- has_command = bool(hermes_cfg.get("command"))- has_url = bool(hermes_cfg.get("url"))-- if has_command and has_url:- skipped.append("url (both command and url set; preferring stdio)")- has_url = False-- if has_command:- # Stdio transport+ if hermes_cfg.get("command"):+ if hermes_cfg.get("url"):+ skipped.append("url (both command and url set; preferring stdio)")out["command"] = str(hermes_cfg["command"])- args = hermes_cfg.get("args") or []- if args:- out["args"] = [str(a) for a in args]- env = hermes_cfg.get("env") or {}- if env:- # Codex expects string values- out["env"] = {str(k): str(v) for k, v in env.items()}- cwd = hermes_cfg.get("cwd")- if cwd:- out["cwd"] = str(cwd)- elif has_url:- # streamable_http transport (codex covers both http and SSE here)+ if hermes_cfg.get("args"):+ out["args"] = [str(a) for a in hermes_cfg["args"]]+ if hermes_cfg.get("env"):+ out["env"] = _str_map(hermes_cfg["env"])+ if hermes_cfg.get("cwd"):+ out["cwd"] = str(hermes_cfg["cwd"])+ elif hermes_cfg.get("url"):out["url"] = str(hermes_cfg["url"])- headers = hermes_cfg.get("headers") or {}- if headers:- out["http_headers"] = {str(k): str(v) for k, v in headers.items()}- # Hermes' transport: sse hint is informational; codex auto-negotiates+ if hermes_cfg.get("headers"):+ out["http_headers"] = _str_map(hermes_cfg["headers"])if hermes_cfg.get("transport") == "sse":skipped.append("transport=sse (codex auto-negotiates)")else:return None, ["no command or url field"]- # Timeouts- if "timeout" in hermes_cfg:- try:- out["tool_timeout_sec"] = float(hermes_cfg["timeout"])- except (TypeError, ValueError):- skipped.append("timeout (not numeric)")- if "connect_timeout" in hermes_cfg:- try:- out["startup_timeout_sec"] = float(hermes_cfg["connect_timeout"])- except (TypeError, ValueError):- skipped.append("connect_timeout (not numeric)")-- # Enabled flag (codex defaults to true so we only emit when explicitly false)+ for hermes_key, codex_key, note in _TIMEOUT_KEYS:+ if hermes_key in hermes_cfg:+ try:+ out[codex_key] = float(hermes_cfg[hermes_key])+ except (TypeError, ValueError):+ skipped.append(note)if hermes_cfg.get("enabled") is False:out["enabled"] = False- # Detect keys we explicitly drop with warningfor key in hermes_cfg:if key in _KEYS_DROPPED_WITH_WARNING:skipped.append(f"{key} (no codex equivalent)")elif key not in _KNOWN_HERMES_KEYS:skipped.append(f"{key} (unknown Hermes key)")-return out, skipped-def _format_toml_value(value: Any) -> str:- """Minimal TOML value formatter for the value types we emit.+# TOML basic-string escapes. Order matters: backslash first so the others aren't re-escaped.+# Control chars must be \-escaped — a literal one is invalid TOML that codex refuses to load;+# env-var passthrough (HERMES_HOME, PYTHONPATH) could carry one in pathological cases.+_TOML_ESCAPES = (+ ("\\", "\\\\"), ('"', '\\"'), ("\b", "\\b"), ("\t", "\\t"),+ ("\n", "\\n"), ("\f", "\\f"), ("\r", "\\r"),+)- We only emit strings, numbers, booleans, and tables of those — no nested arrays of tables. This- covers everything codex's MCP schema accepts.- """++def _escape_toml_string(value: str) -> str:+ for raw, esc in _TOML_ESCAPES:+ value = value.replace(raw, esc)+ return f'"{value}"'+++def _format_toml_value(value: Any) -> str:+ """Minimal TOML formatter for what we emit: strings, numbers, bools, and flat lists/tables of+ those (everything codex's MCP schema accepts; no nested arrays of tables)."""if isinstance(value, bool):return "true" if value else "false"if isinstance(value, (int, float)):return repr(value)if isinstance(value, str):- # Escape per TOML basic-string rules. Order matters: backslash- # first so the other escapes don't get re-escaped.- # Control characters (newline, tab, etc.) must use \-escapes- # because TOML basic strings don't allow literal control chars- # — passing them through would produce invalid TOML that codex- # would refuse to load. Paths usually don't contain control- # chars but env-var passthrough (HERMES_HOME, PYTHONPATH) could- # in pathological cases.- escaped = (- value- .replace("\\", "\\\\")- .replace('"', '\\"')- .replace("\b", "\\b")- .replace("\t", "\\t")- .replace("\n", "\\n")- .replace("\f", "\\f")- .replace("\r", "\\r")- )- return f'"{escaped}"'+ return _escape_toml_string(value)if isinstance(value, list):- items = ", ".join(_format_toml_value(v) for v in value)- return f"[{items}]"+ return f"[{', '.join(_format_toml_value(v) for v in value)}]"if isinstance(value, dict):- items = ", ".join(- f'{_quote_key(k)} = {_format_toml_value(v)}' for k, v in value.items()- )+ items = ", ".join(f'{_quote_key(k)} = {_format_toml_value(v)}' for k, v in value.items())return "{ " + items + " }" if items else "{}"raise ValueError(f"Unsupported TOML value type: {type(value).__name__}")def _quote_key(key: str) -> str:"""Return key bare-or-quoted depending on whether it's a valid bare key."""- if all(c.isalnum() or c in "-_" for c in key) and key:+ if key and all(c.isalnum() or c in "-_" for c in key):return key- escaped = key.replace("\\", "\\\\").replace('"', '\\"')- return f'"{escaped}"'+ return '"' + key.replace("\\", "\\\\").replace('"', '\\"') + '"'+def render_codex_toml_section(servers: dict[str, dict],plugins: Optional[list[dict]] = None,default_permission_profile: Optional[str] = None,) -> str:- """Render the managed [mcp_servers.<n>] / [plugins.<id>] / [permissions] block for- ~/.codex/config.toml.+ """Render the managed [mcp_servers.<n>] / [plugins.<id>] / default_permissions block.- ``default_permission_profile`` (e.g. "workspace-write", "read-only", "full-access") writes- ``[permissions] default`` so the user is not prompted on every write attempt.+ ``default_permission_profile`` (e.g. "workspace-write", "read-only", "full-access") is written+ as the top-level ``default_permissions`` string so the user is not prompted on every write.+ Built-in profile names start with ":" (":workspace-write", ...) and are normalized to that+ form; the ``[permissions]`` table is for *user-defined* named profiles, not what we want."""out = [MIGRATION_MARKER]if not servers and not plugins and not default_permission_profile:@@ -228,121 +188,76 @@ def render_codex_toml_section(return "\n".join(out) + "\n"if default_permission_profile:- # Codex's config schema: `default_permissions` is a top-level- # string referencing a profile name. Built-in profile names start- # with ":" (":workspace-write", ":read-only", ":full-access"). The- # [permissions] table is for *user-defined* named profiles with- # structured fields — not what we want.- normalized = (- default_permission_profile- if default_permission_profile.startswith(":")- else f":{default_permission_profile}"- )- out.append("")- out.append(f"default_permissions = {_format_toml_value(normalized)}")-- if servers:- for name in sorted(servers.keys()):- cfg = servers[name]- out.append("")- out.append(f"[mcp_servers.{_quote_key(name)}]")- for k, v in cfg.items():- out.append(f"{_quote_key(k)} = {_format_toml_value(v)}")-- if plugins:- for plugin in sorted(plugins, key=lambda p: f"{p.get('name','')}@{p.get('marketplace','')}"):- name = plugin.get("name") or ""- marketplace = plugin.get("marketplace") or "openai-curated"- enabled = bool(plugin.get("enabled", True))- qualified = f"{name}@{marketplace}"- out.append("")- out.append(f'[plugins.{_quote_key(qualified)}]')- out.append(f"enabled = {_format_toml_value(enabled)}")-- out.append("")- out.append(MIGRATION_END_MARKER)+ profile = default_permission_profile+ normalized = profile if profile.startswith(":") else f":{profile}"+ out += ["", f"default_permissions = {_format_toml_value(normalized)}"]+ for name in sorted(servers or ()):+ out += ["", f"[mcp_servers.{_quote_key(name)}]"]+ out += [f"{_quote_key(k)} = {_format_toml_value(v)}" for k, v in servers[name].items()]+ plugin_sort_key = lambda p: f"{p.get('name','')}@{p.get('marketplace','')}" # noqa: E731+ for plugin in sorted(plugins or (), key=plugin_sort_key):+ qualified = f"{plugin.get('name') or ''}@{plugin.get('marketplace') or 'openai-curated'}"+ out += ["", f'[plugins.{_quote_key(qualified)}]',+ f"enabled = {_format_toml_value(bool(plugin.get('enabled', True)))}"]+ out += ["", MIGRATION_END_MARKER]return "\n".join(out) + "\n"def _insert_managed_block_at_top_level(user_text: str, managed_block: str) -> str:- """Insert Hermes' managed Codex TOML block while keeping root keys root-scoped.+ """Insert the managed block before the user's first table header.- TOML has no syntax to return to the document root after a table header. Therefore appending a- root key like `default_permissions = ...` after a user table such as `[features]` actually- creates `features.default_permissions`, which Codex rejects.+ TOML has no syntax to return to the document root after a table header, so appending a root+ key like ``default_permissions = ...`` after a user ``[features]`` table would actually create+ ``features.default_permissions``, which codex rejects."""if not user_text.strip():return managed_blocklines = user_text.splitlines(keepends=True)- first_table_idx: Optional[int] = None- for idx, line in enumerate(lines):- stripped = line.lstrip()- if stripped.startswith("["):- first_table_idx = idx- break-+ first_table_idx = next((i for i, ln in enumerate(lines) if ln.lstrip().startswith("[")), None)if first_table_idx is None:prefix = user_text.rstrip("\n")return f"{prefix}\n\n{managed_block}" if prefix else managed_blockprefix = "".join(lines[:first_table_idx]).rstrip("\n")suffix = "".join(lines[first_table_idx:]).lstrip("\n")- if prefix:- return f"{prefix}\n\n{managed_block}\n{suffix}"- return f"{managed_block}\n{suffix}"+ return f"{prefix}\n\n{managed_block}\n{suffix}" if prefix else f"{managed_block}\n{suffix}"def _strip_unmanaged_plugin_tables(toml_text: str) -> str:"""Remove ``[plugins."<name>@<marketplace>"]`` tables that live OUTSIDE the managed block.- Codex itself writes these tables when the user runs ``codex plugins enable`` directly (i.e.- before Hermes' migrate has ever touched the file). When we later run migrate,- ``_query_codex_plugins()`` reports the same plugins via the live ``plugin/list`` RPC and we re-- emit them inside the managed block.-- We own the ``[plugins.*]`` namespace once migrate has run, so dropping any pre-existing- ``[plugins.*]`` tables is safe: ``plugin/list`` is the source of truth for what's actually- installed.+ Codex writes these when the user runs ``codex plugins enable`` directly, before migrate has+ ever touched the file. Once migrate runs, ``plugin/list`` is the source of truth for what is+ installed and we own the ``[plugins.*]`` namespace, so dropping pre-existing tables is safe —+ and necessary, since re-emitting them inside the managed block would otherwise produce+ duplicate-table-header parse errors on codex's next startup."""- lines = toml_text.splitlines(keepends=True)out: list[str] = []in_plugin_table = False- for line in lines:+ for line in toml_text.splitlines(keepends=True):stripped = line.lstrip()- # Only treat a line as a table header when it has the shape- # ``[...]`` (optionally followed by a comment). Multi-line array- # continuations like ``["nested"],`` also start with ``[`` after- # lstrip but are not headers — without this guard they would- # falsely flip ``in_plugin_table`` to False mid-table and leak+ # Only a real ``[...]`` header flips state: multi-line array continuations like+ # ``["nested"],`` also start with ``[`` but must not end the table early and leak# array fragments into the output.if _looks_like_table_header(stripped):in_plugin_table = stripped.startswith("[plugins.")- if in_plugin_table:- continue- if in_plugin_table:- # Swallow keys/comments/blanks until the next table header.- continue- out.append(line)+ if not in_plugin_table: # swallow keys/comments/blanks until the next table header+ out.append(line)return "".join(out)def _looks_like_table_header(stripped_line: str) -> bool:- """Return True if ``stripped_line`` is a TOML table header.-- A header has the shape ``[name]`` or ``[[name]]`` (array-of-tables), optionally followed by a- comment. The closing ``]`` (or ``]]``) must appear on the same line, and no key-assignment ``=``- can precede it.- """+ """True for ``[name]`` / ``[[name]]`` headers (optional trailing comment); the closing ``]``+ must be on the same line and no ``=`` may precede it (``key = [x]`` is not a header)."""if not stripped_line.startswith("["):return False- # Drop trailing comment so e.g. ``[features] # note`` still matches.head = stripped_line.split("#", 1)[0].rstrip()- if not head.endswith("]"):- return False- # ``key = [x]`` would have an ``=`` before the bracket; a header doesn't.- bracket_idx = head.index("]")- return "=" not in head[: bracket_idx + 1]+ return head.endswith("]") and "=" not in head[: head.index("]") + 1]+++# Section headers an old-format managed block (no end marker) may contain.+_LEGACY_MANAGED_HEADERS = ("[mcp_servers", "[plugins", "[permissions]", "[permissions.")def _strip_existing_managed_block(toml_text: str) -> str:@@ -350,38 +265,24 @@ def _strip_existing_managed_block(toml_text: str) -> str:The managed section spans MIGRATION_MARKER through MIGRATION_END_MARKER inclusive; user textoutside it is preserved verbatim. If the start marker exists without an end marker (older- writers), fall back to swallowing lines until a section that is not [mcp_servers.*]/- [plugins.*]/[permissions]/``default_permissions =``, so prior-version configs still migrate.+ writers), swallow lines until a section that is not [mcp_servers.*]/[plugins.*]/[permissions]+ so prior-version configs still migrate."""- lines = toml_text.splitlines(keepends=True)out: list[str] = []in_managed = False- saw_end_marker = False- for line in lines:- line_stripped_nl = line.rstrip("\n")- if line_stripped_nl == MIGRATION_MARKER:+ for line in toml_text.splitlines(keepends=True):+ bare = line.rstrip("\n")+ if bare == MIGRATION_MARKER:in_managed = True- saw_end_marker = Falsecontinueif in_managed:- if line_stripped_nl == MIGRATION_END_MARKER:+ if bare == MIGRATION_END_MARKER:in_managed = False- saw_end_marker = Truecontinuestripped = line.lstrip()- if not saw_end_marker and stripped.startswith("[") and not (- stripped.startswith("[mcp_servers")- or stripped.startswith("[plugins")- or stripped.startswith("[permissions]")- or stripped.startswith("[permissions.")- ):- # Old-format managed block without end marker: bail back- # to user content as soon as we see a non-managed section.- in_managed = False- out.append(line)+ if not stripped.startswith("[") or stripped.startswith(_LEGACY_MANAGED_HEADERS):continue- # Otherwise swallow the line.- continue+ in_managed = False # legacy block: first non-managed section ends itout.append(line)return "".join(out)@@ -395,6 +296,10 @@ def _query_codex_plugins(Spawns ``codex app-server`` briefly, sends initialize + plugin/list and keeps installed=true.Returns ``(plugins, error)``; any failure (not installed, RPC error, timeout) yields ``([],error)`` and is non-fatal — MCP servers and permissions still write through.++ Plugins codex reports as unavailable (broken install, missing OAuth, removed from marketplace)+ are skipped: we write codex's config.toml directly, so a broken plugin would surface as a+ codex error on the user's first turn. ``enabled`` is carried forward as codex reports it."""try:from agent.transports.codex_app_server import CodexAppServerClient@@ -402,132 +307,106 @@ def _query_codex_plugins(return [], f"transport unavailable: {exc}"try:- with CodexAppServerClient(- codex_home=str(codex_home) if codex_home else None- ) as client:+ with CodexAppServerClient(codex_home=str(codex_home) if codex_home else None) as client:client.initialize(client_name="hermes-migration")resp = client.request("plugin/list", {}, timeout=timeout)except Exception as exc:return [], f"plugin/list query failed: {exc}"- out: list[dict] = []- seen: set[tuple[str, str]] = set()marketplaces = resp.get("marketplaces") or []if not isinstance(marketplaces, list):return [], "plugin/list response missing 'marketplaces'"+ out: list[dict] = []+ seen: set[tuple[str, str]] = set()for marketplace in marketplaces:if not isinstance(marketplace, dict):continuemarket_name = str(marketplace.get("name") or "openai-curated")plugins = marketplace.get("plugins") or []- if not isinstance(plugins, list):- continue- for plugin in plugins:- if not isinstance(plugin, dict):+ for plugin in plugins if isinstance(plugins, list) else ():+ if not isinstance(plugin, dict) or not plugin.get("installed", False):continue- installed = bool(plugin.get("installed", False))- if not installed:- continue- # Skip plugins codex itself reports as unavailable (broken- # install, missing OAuth, removed from marketplace, etc.).- # Cf. openclaw/openclaw#80815 — OpenClaw learned to gate- # migration on app readiness to avoid writing config that- # would fail at activation time. Our migration writes to- # codex's config.toml directly, so a broken plugin would- # surface as a codex error on first use. Skipping it here- # keeps the migrated config clean and the user's first- # codex turn from failing.availability = str(plugin.get("availability") or "").upper()if availability and availability != "AVAILABLE":- logger.debug(- "skipping plugin %s: availability=%s",- plugin.get("name"), availability,- )+ logger.debug("skipping plugin %s: availability=%s", plugin.get("name"),+ availability)continuename = str(plugin.get("name") or "")- if not name:- continue- key = (name, market_name)- if key in seen:+ if not name or (name, market_name) in seen:continue- seen.add(key)- # Carry forward whatever 'enabled' codex reports — defaults to- # true for installed plugins. This is the same shape OpenClaw- # writes when migrating native codex plugins.- out.append({- "name": name,- "marketplace": market_name,- "enabled": bool(plugin.get("enabled", True)),- })+ seen.add((name, market_name))+ out.append({"name": name, "marketplace": market_name,+ "enabled": bool(plugin.get("enabled", True))})return out, None+# pytest tempdir shapes: ``pytest-of-<user>/pytest-<n>/``, macOS ``/private/var/folders/…/T``.+_TEST_TEMPDIR_NEEDLES = ("pytest-of-", "/pytest-", "/tmp/pytest", "/private/var/folders/")++def _looks_like_test_tempdir(path: str) -> bool:"""Heuristic: does ``path`` look like a pytest/transient tempdir?- pytest tempdirs (``pytest-of-<user>/pytest-<n>/``, on macOS under ``/private/var/folders/…/T``)- are reaped between sessions; a HERMES_HOME pointing there burned into ``~/.codex/config.toml``- makes every codex-routed call fail silently once GC'd. Err on refusing: a false positive is far- less harmful than silently bricking codex's tool surface.+ Such dirs are reaped between sessions; a HERMES_HOME pointing there burned into+ ``~/.codex/config.toml`` makes every codex-routed call fail silently once GC'd. Err on+ refusing: a false positive is far less harmful than silently bricking codex's tool surface."""- if not path:- return False- needles = (- "pytest-of-",- "/pytest-",- "/tmp/pytest",- "/private/var/folders/", # macOS tempdir root- )- normalized = path.lower()- return any(needle in normalized for needle in needles)+ return bool(path) and any(needle in path.lower() for needle in _TEST_TEMPDIR_NEEDLES)def _build_hermes_tools_mcp_entry() -> dict:- """Build the codex stdio-transport entry that launches Hermes' own tool surface as an MCP server.- Codex's subprocess will call back into this for browser/web/delegate_task/vision/memory/skills- tools.+ """Build the codex stdio entry that launches Hermes' own tool surface as an MCP server, so the+ codex subprocess can call back for browser/web/delegate_task/vision/memory/skills tools.++ HERMES_HOME passes through IF SET so the subprocess sees the same config/auth/sessions DB as+ the parent CLI. Read from os.environ (not get_hermes_home()) on purpose: when unset, the codex+ subprocess should inherit whatever HERMES_HOME its launcher sets at runtime (systemd unit,+ gateway, kanban dispatcher, custom shell) rather than a migrate-time default burned into+ config.toml, which would pin it to the wrong profile. The pytest-tempdir guard stops a sibling+ test's ``monkeypatch.setenv("HERMES_HOME", tmp_path)`` from leaking a transient dir into the+ user's real config.toml. PYTHONPATH passes through so a worktree-launched hermes finds the+ branch's modules instead of the installed package."""import sysenv: dict[str, str] = {}- # HERMES_HOME passes through IF SET so the MCP subprocess sees the same- # config / auth / sessions DB as the parent CLI. Read from os.environ- # (not get_hermes_home()) on purpose: when the env var is unset we want- # codex's subprocess to inherit whatever HERMES_HOME its launcher sets- # at runtime (systemd unit, gateway, kanban dispatcher, custom shell),- # rather than burning the migrate-time resolved default into config.toml- # — that would override the launcher's HERMES_HOME and pin the subprocess- # to the wrong profile.- #- # The pytest-tempdir guard below catches the issue #26250 Bug C scenario:- # a sibling test's monkeypatch.setenv("HERMES_HOME", tmp_path) would- # otherwise leak a transient pytest tempdir into the user's real- # ~/.codex/config.toml and silently brick codex once the tempdir is GC'd.hermes_home = os.environ.get("HERMES_HOME") or ""- if hermes_home and _looks_like_test_tempdir(hermes_home):- hermes_home = ""- if hermes_home:+ if hermes_home and not _looks_like_test_tempdir(hermes_home):env["HERMES_HOME"] = hermes_home- # PYTHONPATH passes through so a worktree-launched hermes finds the- # branch's modules instead of the installed package.- pythonpath = os.environ.get("PYTHONPATH")- if pythonpath:- env["PYTHONPATH"] = pythonpath+ if os.environ.get("PYTHONPATH"):+ env["PYTHONPATH"] = os.environ["PYTHONPATH"]# Quiet mode + redaction defaults so the MCP wire stays clean.env["HERMES_QUIET"] = "1"env["HERMES_REDACT_SECRETS"] = env.get("HERMES_REDACT_SECRETS", "true")- out: dict[str, Any] = {+ return {"command": sys.executable,"args": ["-m", "agent.transports.hermes_tools_mcp_server"],+ "env": env,+ # Generous timeouts — browser_navigate or delegate_task can take a while.+ "startup_timeout_sec": 30.0,+ "tool_timeout_sec": 600.0,}- if env:- out["env"] = env- # Generous timeouts — browser_navigate or delegate_task can take a- # while; we don't want codex's MCP client to give up too early.- out["startup_timeout_sec"] = 30.0- out["tool_timeout_sec"] = 600.0- return out+++def _write_atomic(target: Path, text: str) -> None:+ """Write via a same-directory temp file + rename (atomic on POSIX, ReplaceFile on Windows) so a+ crash mid-write never leaves a half-written config.toml that codex would refuse to load."""+ import tempfile++ tmp_fd, tmp_path_str = tempfile.mkstemp(prefix=".config.toml.", dir=str(target.parent))+ tmp_path = Path(tmp_path_str)+ try:+ with os.fdopen(tmp_fd, "w", encoding="utf-8") as fh:+ fh.write(text)+ tmp_path.replace(target)+ except Exception:+ try:+ if tmp_path.exists():+ tmp_path.unlink()+ except Exception:+ pass+ raisedef migrate(@@ -541,11 +420,12 @@ def migrate() -> MigrationReport:"""Translate Hermes mcp_servers config + Codex curated plugins into ~/.codex/config.toml.- ``discover_plugins`` spawns the live codex CLI (set False in tests).- ``default_permission_profile`` (default ":workspace"; built-ins carry a leading ":", user- profiles do not; None leaves codex's read-only default) avoids an approval prompt on every- write. ``expose_hermes_tools`` registers Hermes' own tool surface as an MCP server so the codex- subprocess can call back for tools it lacks.+ ``discover_plugins`` spawns the live codex CLI (set False in tests); discovery is best-effort+ and never blocks the migration. ``default_permission_profile`` (default ":workspace"; built-ins+ carry a leading ":", user profiles do not; None leaves codex's read-only default) avoids an+ approval prompt on every write. ``expose_hermes_tools`` registers Hermes' own tool surface+ (agent/transports/hermes_tools_mcp_server.py, launched on demand by codex over stdio) as an MCP+ server so the codex subprocess can call back for tools it lacks."""report = MigrationReport(dry_run=dry_run)codex_home = codex_home or Path.home() / ".codex"@@ -554,64 +434,44 @@ def migrate(hermes_servers = (hermes_config or {}).get("mcp_servers") or {}if not isinstance(hermes_servers, dict):- report.errors.append(- "mcp_servers in Hermes config is not a dict; cannot migrate."- )+ report.errors.append("mcp_servers in Hermes config is not a dict; cannot migrate.")return reporttranslated: dict[str, dict] = {}- for name, cfg in hermes_servers.items():- out, skipped = _translate_one_server(str(name), cfg or {})+ for raw_name, cfg in hermes_servers.items():+ name = str(raw_name)+ out, skipped = _translate_one_server(name, cfg or {})if out is None:- report.errors.append(- f"server {name!r} skipped: {', '.join(skipped) or 'no transport configured'}"- )+ reason = ", ".join(skipped) or "no transport configured"+ report.errors.append(f"server {raw_name!r} skipped: {reason}")continue- translated[str(name)] = out+ translated[name] = outif skipped:- report.skipped_keys_per_server[str(name)] = skipped- report.migrated.append(str(name))+ report.skipped_keys_per_server[name] = skipped+ report.migrated.append(name)- # Discover installed Codex curated plugins. Best-effort — never blocks- # the migration if codex is unreachable or the RPC fails.plugins: list[dict] = []plugin_query_succeeded = Falseif discover_plugins and not dry_run:plugins, plugin_err = _query_codex_plugins(codex_home=codex_home)if plugin_err:report.plugin_query_error = plugin_err- else:- # plugin/list returned authoritatively (even if the list is empty).- # That means we own [plugins.*] for this re-render and can safely- # strip any pre-existing tables outside the managed block.- plugin_query_succeeded = True- for p in plugins:- report.migrated_plugins.append(f"{p['name']}@{p['marketplace']}")-- # Track whether we wrote a default permission profile so the report- # surfaces it to the user.+ # An authoritative plugin/list (even an empty one) means we own [plugins.*] for this+ # re-render and may strip pre-existing tables outside the managed block.+ plugin_query_succeeded = not plugin_err+ report.migrated_plugins += [f"{p['name']}@{p['marketplace']}" for p in plugins]+if default_permission_profile:report.wrote_permissions_default = default_permission_profile-- # Inject Hermes' own tool surface as an MCP server so the spawned- # codex subprocess can call back into Hermes for the tools codex- # doesn't ship with — web_search, browser_*, delegate_task, vision,- # memory, skills, session_search, image_generate, text_to_speech.- # The server itself is agent/transports/hermes_tools_mcp_server.py- # and is launched on demand by codex (stdio MCP).if expose_hermes_tools:translated["hermes-tools"] = _build_hermes_tools_mcp_entry()if "hermes-tools" not in report.migrated:report.migrated.append("hermes-tools")- # Build the new managed blockmanaged_block = render_codex_toml_section(- translated, plugins=plugins,- default_permission_profile=default_permission_profile,+ translated, plugins=plugins, default_permission_profile=default_permission_profile,)-- # Read existing codex config if any, strip the prior managed block,- # append the new one.+ new_text = managed_blockif target.exists():try:existing = target.read_text(encoding="utf-8")@@ -619,44 +479,15 @@ def migrate(report.errors.append(f"could not read {target}: {exc}")return reportwithout_managed = _strip_existing_managed_block(existing)- # Bug B: when plugin/list ran authoritatively, codex's own- # [plugins."<name>@<marketplace>"] tables outside our managed block- # would survive _strip_existing_managed_block and then collide with- # the entries we re-emit inside the managed block — producing- # duplicate-table-header parse errors on codex's next startup. Drop- # those pre-existing tables since plugin/list is the source of truth.if plugin_query_succeeded:without_managed = _strip_unmanaged_plugin_tables(without_managed)new_text = _insert_managed_block_at_top_level(without_managed, managed_block)- else:- new_text = managed_blockif dry_run:return report-try:codex_home.mkdir(parents=True, exist_ok=True)- # Atomic write: write to a temp file in the same directory then- # rename. Same-directory rename is atomic on POSIX and ReplaceFile- # on Windows. Avoids leaving a half-written config.toml that- # codex would refuse to load if we crash mid-write.- import tempfile- tmp_fd, tmp_path_str = tempfile.mkstemp(- prefix=".config.toml.", dir=str(codex_home)- )- tmp_path = Path(tmp_path_str)- try:- with os.fdopen(tmp_fd, "w", encoding="utf-8") as fh:- fh.write(new_text)- tmp_path.replace(target)- except Exception:- # Clean up the temp file if the rename didn't happen.- try:- if tmp_path.exists():- tmp_path.unlink()- except Exception:- pass- raise+ _write_atomic(target, new_text)report.written = Trueexcept Exception as exc:report.errors.append(f"could not write {target}: {exc}")