The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(cli): add `hermes codex-runtime migrate [--dry-run] [--json]`
teknium1d09183d8d3ee
diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 581491f0ed9..1c3aef77112 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -392,6 +392,7 @@ from hermes_cli.subcommands.fallback import build_fallback_parserfrom hermes_cli.subcommands.worktree import build_worktree_parserfrom hermes_cli.subcommands.browser import build_browser_parserfrom hermes_cli.subcommands.secrets import build_secrets_parser+from hermes_cli.subcommands.codex_runtime import build_codex_runtime_parserfrom hermes_cli.subcommands.egress import build_egress_parserfrom hermes_cli.subcommands.migrate import build_migrate_parserfrom hermes_cli.subcommands.checkpoints import build_checkpoints_parser@@ -2720,7 +2721,7 @@ def cmd_console(args):# entry would let a plugin command silently fail to parse._BUILTIN_SUBCOMMANDS = frozenset({- "acp", "approvals", "auth", "backup", "bundles", "checkpoints", "claw", "completion",+ "acp", "approvals", "auth", "backup", "bundles", "checkpoints", "claw", "codex-runtime", "completion","computer-use","config", "console", "cron", "curator", "dashboard", "serve", "debug", "doctor","dump", "egress", "fallback", "gateway", "hooks", "import", "import-agent", "insights",@@ -3304,6 +3305,7 @@ def _build_cli_parser():# OUTBOUND egress firewall; ``hermes proxy`` (gateway group) is the INBOUND one.build_egress_parser(subparsers)build_migrate_parser(subparsers)+ build_codex_runtime_parser(subparsers)build_gateway_parser(subparsers, cmd_gateway=cmd_gateway, cmd_proxy=cmd_proxy, cmd_gateway_enroll=cmd_gateway_enroll)diff --git a/hermes_cli/subcommands/codex_runtime.py b/hermes_cli/subcommands/codex_runtime.pynew file mode 100644index 00000000000..6d0adcc3fe8--- /dev/null+++ b/hermes_cli/subcommands/codex_runtime.py@@ -0,0 +1,55 @@+"""``hermes codex-runtime`` — noninteractive counterpart of the ``/codex-runtime`` slash command.++``hermes codex-runtime migrate [--dry-run] [--json]`` runs the same ``~/.codex/config.toml``+migration the slash command triggers when the codex app-server runtime is enabled, on the+selected profile home (``hermes -p NAME codex-runtime migrate``), so automation no longer has to+import ``hermes_cli.codex_runtime_plugin_migration`` directly (issue #79023).+"""++from __future__ import annotations++import argparse+import dataclasses+import json+++def cmd_codex_runtime_migrate(args: argparse.Namespace) -> int:+ """Project Hermes MCP servers (+ codex plugins) into ~/.codex/config.toml; 1 on any error."""+ from hermes_cli.codex_runtime_plugin_migration import migrate+ from hermes_cli.config import load_config++ report = migrate(load_config(), dry_run=args.dry_run)+ if args.json:+ payload = dataclasses.asdict(report)+ payload["target_path"] = str(report.target_path)+ print(json.dumps(payload, indent=2, sort_keys=True))+ else:+ print(report.summary())+ return 1 if report.errors else 0+++def build_codex_runtime_parser(subparsers) -> None:+ """Attach the ``codex-runtime`` subcommand (``migrate`` action) to ``subparsers``."""+ parser = subparsers.add_parser(+ "codex-runtime", help="Manage the optional codex app-server runtime (migrate MCP config)",+ description="Noninteractive counterpart of the /codex-runtime slash command. Toggling the "+ "runtime itself stays in the chat command (`/codex-runtime on|off`); `migrate` "+ "re-projects Hermes' mcp_servers + installed codex plugins into the managed block of "+ "~/.codex/config.toml for the selected profile.")+ actions = parser.add_subparsers(dest="codex_runtime_action")+ migrate_parser = actions.add_parser(+ "migrate", help="Regenerate the hermes-managed block in codex's config.toml",+ description="Idempotent: replaces the managed block, keeps user text verbatim, skips Hermes "+ "servers whose name the user already declares outside the block, validates the result "+ "as TOML before writing atomically.")+ migrate_parser.add_argument(+ "--dry-run", action="store_true", help="Report what would be written without touching config.toml")+ migrate_parser.add_argument(+ "--json", action="store_true", help="Print the migration report as JSON (for automation)")+ migrate_parser.set_defaults(func=cmd_codex_runtime_migrate)++ def _print_help(args): # noqa: ANN001 — bare `hermes codex-runtime` lists the actions+ parser.print_help()+ return 0++ parser.set_defaults(func=_print_help)diff --git a/tests/hermes_cli/test_codex_runtime_plugin_migration.py b/tests/hermes_cli/test_codex_runtime_plugin_migration.pyindex 62284fbd8d9..a0cf19079c4 100644--- a/tests/hermes_cli/test_codex_runtime_plugin_migration.py+++ b/tests/hermes_cli/test_codex_runtime_plugin_migration.py@@ -2,6 +2,7 @@from __future__ import annotations+import argparseimport pytest@@ -420,3 +421,50 @@ class TestHermesHomeLeakGuard:f"HERMES_HOME should not be set when env var is unset, got: "f"{env.get('HERMES_HOME')!r}")+++# ---- same-name user-owned [mcp_servers.X] tables (issue #79023) ----+++class TestSameNameUserMcpTable:+ """Issue #79023: a Hermes server whose name the user already declares outside the managed+ block must not be emitted twice (duplicate table header = TOML codex refuses to load)."""++ def test_user_table_wins_and_output_stays_valid_toml(self, tmp_path):+ import tomllib++ target = tmp_path / "config.toml"+ target.write_text('[mcp_servers.gbrain]\ncommand = "existing-gbrain"\n', encoding="utf-8")+ report = migrate(+ {"mcp_servers": {"gbrain": {"command": "projected-gbrain"}, "other": {"command": "o"}}},+ codex_home=tmp_path, discover_plugins=False, expose_hermes_tools=False,+ default_permission_profile=None)+ text = target.read_text(encoding="utf-8")+ parsed = tomllib.loads(text) # would raise "Cannot declare ... twice" before the fix+ assert text.count("[mcp_servers.gbrain]") == 1+ assert parsed["mcp_servers"]["gbrain"]["command"] == "existing-gbrain"+ assert "other" in parsed["mcp_servers"]+ assert report.preserved_user_servers == ["gbrain"]+ assert report.migrated == ["other"]+ assert "gbrain" in report.summary()++ def test_cli_migrate_dry_run_json_reports_without_writing(self, tmp_path, monkeypatch, capsys):+ """`hermes codex-runtime migrate --dry-run --json` is the supported automation seam."""+ import json++ from hermes_cli.subcommands import codex_runtime as mod++ (tmp_path / ".codex").mkdir()+ target = tmp_path / ".codex" / "config.toml"+ target.write_text('[mcp_servers.gbrain]\ncommand = "existing-gbrain"\n', encoding="utf-8")+ monkeypatch.setattr("pathlib.Path.home", classmethod(lambda cls: tmp_path))+ monkeypatch.setattr(+ "hermes_cli.config.load_config",+ lambda: {"mcp_servers": {"gbrain": {"command": "projected"}, "other": {"command": "o"}}})+ rc = mod.cmd_codex_runtime_migrate(argparse.Namespace(dry_run=True, json=True))+ payload = json.loads(capsys.readouterr().out)+ assert rc == 0+ assert payload["dry_run"] is True and payload["written"] is False+ assert payload["preserved_user_servers"] == ["gbrain"]+ assert payload["target_path"] == str(target)+ assert target.read_text(encoding="utf-8") == '[mcp_servers.gbrain]\ncommand = "existing-gbrain"\n'diff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.mdindex b4f012322cb..6a1c22709ab 100644--- a/website/docs/reference/cli-commands.md+++ b/website/docs/reference/cli-commands.md@@ -56,6 +56,7 @@ hermes [global-options] <command> [subcommand/options]| `hermes peer` | Register peer Hermes gateways on other machines and DM their agents' canonical Bot Chats (`hermes peer dm <peer>[/<agent>] "…"`). The transport behind cross-machine bot-to-bot messaging. || `hermes secrets` | Manage external secret sources (currently Bitwarden Secrets Manager) for pulling API keys at process startup instead of from `~/.hermes/.env`. || `hermes migrate` | Diagnose and (optionally) rewrite `config.yaml` to replace references to retired models or deprecated settings (e.g. `migrate xai`). |+| `hermes codex-runtime` | Noninteractive counterpart of `/codex-runtime`: `migrate [--dry-run] [--json]` regenerates the Hermes-managed block in `~/.codex/config.toml` for the selected profile. See [Codex app-server runtime](../user-guide/features/codex-app-server-runtime.md#running-the-migration-from-a-script). || `hermes status` | Show agent, auth, and platform status. || `hermes cron` | Inspect and tick the cron scheduler. || `hermes pause` / `hermes resume` | Global emergency stop: no new cron fires (built-in ticker, managed-cron webhook, misfire catch-up), kanban dispatch or gateway turns start until resumed; in-flight work is never killed. |@@ -603,6 +604,20 @@ Common flags for migration subcommands:> Not to be confused with `hermes claw migrate` (one-shot import of OpenClaw configuration into Hermes) — `hermes migrate` is the top-level config-rewrite command.+## `hermes codex-runtime`++```bash+hermes codex-runtime migrate [--dry-run] [--json]+```++Runs the `~/.codex/config.toml` migration that `/codex-runtime codex_app_server` triggers, without a chat session: Hermes' `mcp_servers` (plus installed codex plugins and the `default_permissions` default) are projected into the managed block for the selected profile (`hermes -p <name> codex-runtime migrate`). User text outside the block is kept verbatim; a user-owned `[mcp_servers.<name>]` with the same name as a Hermes server is preserved and the Hermes projection for that name skipped (reported as `preserved_user_servers`). The result is validated as TOML before an atomic write; exit code is 1 when the report contains errors.++| Flag | Description |+|------|-------------|+| `--dry-run` | Compute and report the migration without writing `config.toml`. |+| `--json` | Print the full migration report as JSON (`migrated`, `preserved_user_servers`, `skipped_keys_per_server`, `errors`, `target_path`, `written`). |++## `hermes proxy````bashdiff --git a/website/docs/user-guide/features/codex-app-server-runtime.md b/website/docs/user-guide/features/codex-app-server-runtime.mdindex 9c85c018912..a89d2b2040d 100644--- a/website/docs/user-guide/features/codex-app-server-runtime.md+++ b/website/docs/user-guide/features/codex-app-server-runtime.md@@ -299,7 +299,7 @@ default_permissions = ":workspace"# end hermes-agent managed section```-Anything **outside** that block is yours. Re-running migration (via `/codex-runtime codex_app_server` or whenever you toggle the runtime on) replaces the managed block in place but preserves user content above and below it verbatim. This means you can:+Anything **outside** that block is yours. Re-running migration (via `/codex-runtime codex_app_server`, whenever you toggle the runtime on, or `hermes codex-runtime migrate`) replaces the managed block in place but preserves user content above and below it verbatim. This means you can:- Add your own MCP servers Hermes doesn't know about- Override `default_permissions` to `:read-only` if you prefer to be prompted@@ -308,6 +308,19 @@ Anything **outside** that block is yours. Re-running migration (via `/codex-runtAnything you add **inside** the managed block will get clobbered on the next migration. If you need a tweak that requires editing the managed block, file an issue and we'll add the knob.+**Same-name servers.** If your own `[mcp_servers.<name>]` table (outside the block) uses the same name as a server in Hermes' `mcp_servers`, your table wins: Hermes skips its projection for that name instead of emitting a second `[mcp_servers.<name>]` header (which is invalid TOML and would stop codex from starting). The migration report lists such names under "Kept N user-owned MCP server(s)". To let Hermes manage the server, delete your table and re-run the migration. The rendered file is parsed as TOML before it replaces `config.toml`; an unparsable result is reported and the existing file is left untouched.++### Running the migration from a script++```bash+hermes codex-runtime migrate # rewrite the managed block for the active profile+hermes codex-runtime migrate --dry-run # report only, no write+hermes codex-runtime migrate --json # machine-readable report (migrated, preserved_user_servers, errors, …)+hermes -p work codex-runtime migrate # a named profile's mcp_servers+```++This is the same migration `/codex-runtime codex_app_server` runs; it is idempotent, writes atomically, and exits non-zero when the report contains errors.+## Multi-profile / multi-tenant setupsBy default, Hermes points the codex subprocess at `~/.codex/` regardless of which Hermes profile is active. This means `hermes -p work` and `hermes -p personal` share the same Codex auth, plugins, and config. For most users this is the right behavior — it matches what running `codex` CLI directly would do.