The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Inspired by ChatGPT Work: keep imported agent setups in sync (`hermes import-agent --sync`)
Teknium6fcd011c0158
diff --git a/hermes_cli/agent_import.py b/hermes_cli/agent_import.pyindex 1cd6978c7bb..1fa985a7e6f 100644--- a/hermes_cli/agent_import.py+++ b/hermes_cli/agent_import.py@@ -235,7 +235,8 @@ class AgentImporter:plan without touching disk; every item is recorded as imported/skipped/conflict/error."""def __init__(self, agent: str, source_root: Path, target_root: Path,- execute: bool = False, overwrite: bool = False) -> None:+ execute: bool = False, overwrite: bool = False,+ sync_skills: Sequence[str] = ()) -> None:if agent not in SUPPORTED_AGENTS:raise ValueError(f"Unsupported agent: {agent!r}")self.agent = agent@@ -243,6 +244,9 @@ class AgentImporter:self.target_root = Path(target_root)self.execute = executeself.overwrite = overwrite+ # Skills a previous import-agent run copied (from the sync manifest): Hermes owns those+ # destinations, so --sync refreshes them in place; anything else keeps conflict semantics.+ self.sync_skills = frozenset(sync_skills)self.items: List[Dict[str, Any]] = []self.stripped_secrets: List[str] = []@@ -495,7 +499,8 @@ class AgentImporter:returnfor skill_dir in skill_dirs:destination = destination_root / skill_dir.name- if destination.exists() and not self.overwrite:+ may_replace = self.overwrite or skill_dir.name in self.sync_skills+ if destination.exists() and not may_replace:self.record("skill", skill_dir, destination, "conflict","Destination skill already exists")continue@@ -516,6 +521,11 @@ def import_agent_command(args) -> None:from hermes_cli.setup import (Colors, color, print_header, print_info, print_success,print_error, prompt_yes_no)+ if getattr(args, "sync", False):+ from hermes_cli.agent_import_sync import sync_imported_agents+ sync_imported_agents(args)+ return+agent, explicit_source, overwrite = args.agent, args.source, args.overwriteif agent is None:@@ -596,6 +606,13 @@ def import_agent_command(args) -> None:if report is None:returnprint_import_report(report, dry_run=False)+ from hermes_cli.agent_import_sync import update_sync_manifest+ try:+ update_sync_manifest(agent, source_dir.resolve(), hermes_home.resolve(), overwrite, report)+ print_info("Source registered for sync — re-run 'hermes import-agent --sync' "+ "any time to pull in changes.")+ except OSError as exc:+ logger.warning("Could not update import sync manifest: %s", exc)print()print_success("Import complete.")print_info("API keys and credentials were NOT imported — run 'hermes setup' "diff --git a/hermes_cli/agent_import_sync.py b/hermes_cli/agent_import_sync.pynew file mode 100644index 00000000000..d022f697428--- /dev/null+++ b/hermes_cli/agent_import_sync.py@@ -0,0 +1,172 @@+"""``hermes import-agent --sync`` — keep previously imported Claude Code / Codex setups current.++Every successful ``hermes import-agent`` run records its source in ``HERMES_HOME/import-sync.json``+(the sync manifest); ``--sync`` re-imports every registered source whose files changed since the+last run. Change detection is a content digest over exactly the files the importer reads, so an+unchanged source is a cheap no-op and credential files (never read by the importer) can never+trigger a sync. Sync runs prompt-free — it only re-applies sources the user already imported once.+"""++from __future__ import annotations++import hashlib+import json+import logging+import time+from pathlib import Path+from typing import Any, Dict, Iterator, List++from utils import atomic_write_text++logger = logging.getLogger(__name__)++SYNC_MANIFEST_NAME = "import-sync.json"+# Credential stores that live inside the source trees; never part of the digest.+_CREDENTIAL_FILENAMES = frozenset({".credentials.json", "auth.json", "credentials.json"})+++def sync_manifest_path(target_root: Path) -> Path:+ return Path(target_root) / SYNC_MANIFEST_NAME+++def _iter_sync_files(agent: str, source_root: Path) -> Iterator[Path]:+ """Yield the source files whose content determines the sync digest — exactly what+ :class:`~hermes_cli.agent_import.AgentImporter` reads for ``agent``."""+ if agent == "claude-code":+ # ~/.claude.json lives NEXT TO ~/.claude/ (see AgentImporter._run_claude_code)+ paths = [source_root / "CLAUDE.md", source_root / "settings.json",+ source_root.parent / ".claude.json"]+ else:+ paths = [source_root / "AGENTS.md", source_root / "config.toml"]+ paths.extend(sorted((source_root / "memories").glob("*.md")))+ paths.extend(p for p in sorted((source_root / "skills").rglob("*")) if p.is_file())+ for path in paths:+ if path.name not in _CREDENTIAL_FILENAMES and path.is_file():+ yield path+++def compute_source_digest(agent: str, source_root: Path) -> str:+ """Content digest of everything the importer would read from ``source_root``."""+ source_root = Path(source_root)+ digest = hashlib.sha256()+ for path in _iter_sync_files(agent, source_root):+ try:+ rel = str(path.relative_to(source_root))+ except ValueError:+ rel = f"../{path.name}"+ try:+ content_hash = hashlib.sha256(path.read_bytes()).hexdigest()+ except OSError:+ content_hash = "unreadable"+ digest.update(f"{rel}\0{content_hash}\0".encode("utf-8", "replace"))+ return digest.hexdigest()+++def load_sync_manifest(target_root: Path) -> Dict[str, Any]:+ """Read the manifest; a missing, unreadable or malformed file yields an empty manifest."""+ path = sync_manifest_path(target_root)+ if not path.exists():+ return {"version": 1, "agents": {}}+ try:+ data = json.loads(path.read_text(encoding="utf-8", errors="replace"))+ except (json.JSONDecodeError, OSError):+ logger.warning("Unreadable %s — starting a fresh sync manifest", path)+ return {"version": 1, "agents": {}}+ if not isinstance(data, dict) or not isinstance(data.get("agents"), dict):+ return {"version": 1, "agents": {}}+ return data+++def save_sync_manifest(target_root: Path, manifest: Dict[str, Any]) -> None:+ atomic_write_text(sync_manifest_path(target_root),+ json.dumps(manifest, indent=2, sort_keys=True) + "\n")+++def update_sync_manifest(agent: str, source_root: Path, target_root: Path,+ overwrite: bool, report: Dict[str, Any]) -> None:+ """Record/refresh the sync entry for ``agent`` after a real (non-dry-run) import.++ ``imported_skills`` accumulates every skill name this command ever copied for the agent:+ those destinations are Hermes-owned and may be refreshed in place by a later sync, while+ skills the user created under the import category keep normal conflict semantics.+ """+ manifest = load_sync_manifest(target_root)+ agents = manifest.setdefault("agents", {})+ entry = agents.get(agent)+ if not isinstance(entry, dict):+ entry = {}+ previous = entry.get("imported_skills")+ skills = set(previous) if isinstance(previous, list) else set()+ skills.update(Path(item["destination"]).name for item in report.get("items", [])+ if item.get("kind") == "skill" and item.get("status") == "imported"+ and item.get("destination"))+ entry.update({"source": str(source_root), "overwrite": bool(overwrite),+ "digest": compute_source_digest(agent, Path(source_root)),+ "last_import": int(time.time()), "imported_skills": sorted(skills)})+ agents[agent] = entry+ save_sync_manifest(target_root, manifest)+++def sync_imported_agents(args) -> None:+ """Handle ``hermes import-agent --sync``: re-import every registered source whose digest+ changed. Prompt-free (cron-friendly); ``--dry-run`` previews without touching the manifest."""+ from hermes_cli.agent_import import AgentImporter, print_import_report+ from hermes_cli.setup import print_error, print_header, print_info, print_success+ from hermes_constants import get_hermes_home++ dry_run = bool(getattr(args, "dry_run", False))+ hermes_home = get_hermes_home().resolve()+ agents: Dict[str, Any] = load_sync_manifest(hermes_home).get("agents", {})+ if not agents:+ print()+ print_info("No import sources registered yet.")+ print_info("Run 'hermes import-agent' first — successful imports are "+ "registered for sync automatically.")+ return++ print()+ print_header("Import Sync")+ synced = unchanged = failed = 0+ for agent_name in sorted(agents):+ entry = agents[agent_name]+ if not isinstance(entry, dict) or not entry.get("source"):+ continue+ source_dir = Path(entry["source"])+ if not source_dir.is_dir():+ print_info(f"{agent_name}: source {source_dir} no longer exists — skipped")+ continue+ if compute_source_digest(agent_name, source_dir) == entry.get("digest"):+ print_info(f"{agent_name}: unchanged since last import")+ unchanged += 1+ continue+ print_info(f"{agent_name}: changes detected in {source_dir}"+ + (" (dry run)" if dry_run else " — re-importing"))+ overwrite = bool(entry.get("overwrite", False))+ sync_skills: List[str] = entry.get("imported_skills") or []+ try:+ report = AgentImporter(agent_name, source_dir, hermes_home, execute=not dry_run,+ overwrite=overwrite,+ sync_skills=sync_skills if isinstance(sync_skills, list) else ()+ ).run()+ except Exception as exc: # noqa: BLE001 — keep syncing the other sources+ print_error(f"{agent_name}: sync failed: {exc}")+ logger.debug("import-agent sync error", exc_info=True)+ failed += 1+ continue+ print_import_report(report, dry_run=dry_run)+ if report.get("summary", {}).get("error"):+ failed += 1+ if not dry_run:+ try:+ update_sync_manifest(agent_name, source_dir, hermes_home, overwrite, report)+ except OSError as exc:+ logger.warning("Could not update import sync manifest: %s", exc)+ synced += 1++ print()+ if synced == 0 and failed == 0:+ print_success(f"All {unchanged} source(s) already up to date.")+ return+ parts = [f"{synced} synced"] + [f"{n} {label}" for n, label in+ ((unchanged, "unchanged"), (failed, "failed")) if n]+ print_success("Sync complete: " + ", ".join(parts) + ".")diff --git a/hermes_cli/subcommands/import_agent.py b/hermes_cli/subcommands/import_agent.pyindex b6b27ef07d3..0b2205186bd 100644--- a/hermes_cli/subcommands/import_agent.py+++ b/hermes_cli/subcommands/import_agent.py@@ -28,4 +28,9 @@ def build_import_agent_parser(subparsers, *, cmd_import_agent: Callable) -> None"--overwrite", action="store_true",help="Overwrite existing Hermes items on name conflicts (default: skip)")add_yes_flag(parser, "Skip confirmation prompts")+ parser.add_argument(+ "--sync", action="store_true",+ help="Re-import every previously imported source whose files changed since the last "+ "import (registered in HERMES_HOME/import-sync.json). Runs without prompts; "+ "combine with --dry-run to preview.")parser.set_defaults(func=cmd_import_agent)diff --git a/tests/hermes_cli/test_agent_import.py b/tests/hermes_cli/test_agent_import.pyindex d00ae59f3ad..db2bcfb1d11 100644--- a/tests/hermes_cli/test_agent_import.py+++ b/tests/hermes_cli/test_agent_import.py@@ -727,3 +727,148 @@ class TestCliWiring:if (hermes_home / "config.yaml").exists() else ""assert "npm run build" not in config_textassert "github" not in config_text+++# ---------------------------------------------------------------------------+# Sync mode (--sync): ChatGPT Work-inspired "keep imported work in sync"+# ---------------------------------------------------------------------------++class TestSyncManifest:+ def _run_command(self, agent, source, dry_run=False, sync=False,+ overwrite=False):+ import types+ from hermes_cli.agent_import import import_agent_command++ args = types.SimpleNamespace(+ agent=agent, source=str(source) if source else None,+ dry_run=dry_run, overwrite=overwrite, yes=True, sync=sync)+ import_agent_command(args)++ def test_successful_import_registers_source(self, claude_tree, hermes_home):+ from hermes_cli.agent_import import load_sync_manifest++ self._run_command("claude-code", claude_tree)+ manifest = load_sync_manifest(hermes_home)+ entry = manifest["agents"]["claude-code"]+ assert entry["source"] == str(claude_tree.resolve())+ assert entry["digest"]+ assert "deploy-helper" in entry["imported_skills"]++ def test_dry_run_does_not_register(self, claude_tree, hermes_home):+ from hermes_cli.agent_import import sync_manifest_path++ self._run_command("claude-code", claude_tree, dry_run=True)+ assert not sync_manifest_path(hermes_home).exists()++ def test_sync_without_manifest_is_a_noop(self, hermes_home, capsys):+ self._run_command(None, None, sync=True)+ assert "No import sources registered" in capsys.readouterr().out++ def test_sync_unchanged_source_writes_nothing(+ self, claude_tree, hermes_home, capsys):+ self._run_command("claude-code", claude_tree)+ before = snapshot_tree(hermes_home)+ capsys.readouterr()+ self._run_command(None, None, sync=True)+ out = capsys.readouterr().out+ assert "unchanged since last import" in out+ assert snapshot_tree(hermes_home) == before++ def test_sync_picks_up_new_memory_entries(self, claude_tree, hermes_home):+ self._run_command("claude-code", claude_tree)+ (claude_tree / "CLAUDE.md").write_text(+ CLAUDE_MD + "\n- Freshly added sync rule\n", encoding="utf-8")+ self._run_command(None, None, sync=True)+ memory = (hermes_home / "memories" / "MEMORY.md").read_text(+ encoding="utf-8")+ assert "Freshly added sync rule" in memory++ def test_sync_refreshes_previously_imported_skill_in_place(+ self, claude_tree, hermes_home):+ self._run_command("claude-code", claude_tree)+ (claude_tree / "skills" / "deploy-helper" / "SKILL.md").write_text(+ "---\nname: deploy-helper\n---\n\nDeploy v2.\n", encoding="utf-8")+ self._run_command(None, None, sync=True)+ imported = (hermes_home / "skills" / "claude-code-imports" /+ "deploy-helper" / "SKILL.md").read_text(encoding="utf-8")+ assert "Deploy v2." in imported++ def test_sync_does_not_replace_user_owned_skill(+ self, claude_tree, hermes_home):+ """A destination skill import-agent did NOT create keeps conflict+ semantics on sync — the user's copy is never clobbered."""+ self._run_command("claude-code", claude_tree)+ # A NEW source skill whose destination the user created themselves.+ user_skill = (hermes_home / "skills" / "claude-code-imports" /+ "hand-rolled")+ user_skill.mkdir(parents=True)+ (user_skill / "SKILL.md").write_text("user content", encoding="utf-8")+ source_skill = claude_tree / "skills" / "hand-rolled"+ source_skill.mkdir()+ (source_skill / "SKILL.md").write_text(+ "---\nname: hand-rolled\n---\n\nsource content\n", encoding="utf-8")+ self._run_command(None, None, sync=True)+ assert (user_skill / "SKILL.md").read_text(+ encoding="utf-8") == "user content"++ def test_sync_dry_run_previews_without_writing(+ self, claude_tree, hermes_home, capsys):+ from hermes_cli.agent_import import load_sync_manifest++ self._run_command("claude-code", claude_tree)+ old_digest = load_sync_manifest(hermes_home)["agents"]["claude-code"]["digest"]+ (claude_tree / "CLAUDE.md").write_text(+ CLAUDE_MD + "\n- Dry sync entry\n", encoding="utf-8")+ before = snapshot_tree(hermes_home)+ capsys.readouterr()+ self._run_command(None, None, sync=True, dry_run=True)+ out = capsys.readouterr().out+ assert "changes detected" in out+ assert snapshot_tree(hermes_home) == before+ assert load_sync_manifest(+ hermes_home)["agents"]["claude-code"]["digest"] == old_digest++ def test_sync_skips_vanished_source(self, claude_tree, hermes_home, capsys):+ import shutil as _shutil++ self._run_command("claude-code", claude_tree)+ _shutil.rmtree(claude_tree)+ capsys.readouterr()+ self._run_command(None, None, sync=True)+ assert "no longer exists" in capsys.readouterr().out++ def test_corrupt_manifest_recovers(self, claude_tree, hermes_home):+ from hermes_cli.agent_import import load_sync_manifest, sync_manifest_path++ sync_manifest_path(hermes_home).write_text("{not json", encoding="utf-8")+ assert load_sync_manifest(hermes_home) == {"version": 1, "agents": {}}+ # And a real import repairs it:+ self._run_command("claude-code", claude_tree)+ assert "claude-code" in load_sync_manifest(hermes_home)["agents"]++ def test_credential_files_do_not_affect_digest(self, claude_tree):+ from hermes_cli.agent_import import compute_source_digest++ before = compute_source_digest("claude-code", claude_tree)+ (claude_tree / ".credentials.json").write_text(+ json.dumps({"api_key": "rotated-token"}), encoding="utf-8")+ assert compute_source_digest("claude-code", claude_tree) == before++ def test_codex_digest_tracks_memories(self, codex_tree):+ from hermes_cli.agent_import import compute_source_digest++ before = compute_source_digest("codex", codex_tree)+ (codex_tree / "memories" / "2026-02-01.md").write_text(+ "- Another memory\n", encoding="utf-8")+ assert compute_source_digest("codex", codex_tree) != before++ def test_parser_accepts_sync_flag(self):+ import argparse+ from hermes_cli.subcommands.import_agent import build_import_agent_parser++ parser = argparse.ArgumentParser()+ subparsers = parser.add_subparsers(dest="command")+ build_import_agent_parser(subparsers, cmd_import_agent=lambda a: None)+ args = parser.parse_args(["import-agent", "--sync", "--dry-run"])+ assert args.sync is True+ assert args.dry_run is Truediff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.mdindex 14cce22769d..5e8b567d985 100644--- a/website/docs/reference/cli-commands.md+++ b/website/docs/reference/cli-commands.md@@ -1722,8 +1722,9 @@ Import a **Claude Code** (`~/.claude`) or **OpenAI Codex CLI** (`~/.codex`) setu| `--dry-run` | Preview only — write nothing. || `--overwrite` | Replace conflicting MCP servers / skills (default: skip). || `--yes`, `-y` | Skip confirmation prompts. |+| `--sync` | Re-import every previously imported source whose files changed since the last import. Prompt-free; combine with `--dry-run` to preview. |-See the **[import guide](../user-guide/import-from-other-agents.md)** for the full mapping tables.+Every successful import registers its source in `~/.hermes/import-sync.json`; `hermes import-agent --sync` then re-imports any registered source whose files changed (a cron-friendly way to keep an imported Claude Code / Codex setup current). See the **[import guide](../user-guide/import-from-other-agents.md)** for the full mapping tables.## `hermes serve`diff --git a/website/docs/user-guide/import-from-other-agents.md b/website/docs/user-guide/import-from-other-agents.mdindex 53f8d7b2304..38807261ca5 100644--- a/website/docs/user-guide/import-from-other-agents.md+++ b/website/docs/user-guide/import-from-other-agents.md@@ -52,3 +52,21 @@ Claude's `Bash(npm run test:*)` prefix rules become `npm run test*` globs. Non-`- **Conflicts are skipped by default.** An MCP server or skill that already exists in Hermes is reported as a conflict; pass `--overwrite` to replace it.- **Malformed files don't abort the run.** A broken `settings.json` or `config.toml` becomes a per-item error in the report while everything else still imports.- Coming from OpenClaw instead? Use [`hermes claw migrate`](../guides/migrate-from-openclaw.md).++## Keeping imports in sync++Every successful import registers its source (and the digest of everything it read) in `~/.hermes/import-sync.json`. When the other agent's setup changes later — new skills, edited `CLAUDE.md`/`AGENTS.md`, added MCP servers — pull the changes in with:++```bash+hermes import-agent --sync # re-import every changed source+hermes import-agent --sync --dry-run # preview what a sync would do+```++Sync is prompt-free and cheap: sources whose files are unchanged are skipped by digest comparison, so it is safe to run on a schedule (e.g. a daily [cron job](features/cron.md)). Rules:++- **Memory and config merges stay deduplicating** — a sync never duplicates entries or patterns you already have.+- **Skills previously imported by `import-agent` are refreshed in place** when the source copy changes.+- **Skills you created or modified under the import category yourself are never clobbered** — they keep normal conflict semantics (use `--overwrite` on a manual run to force).+- **Credential files never trigger a sync** — token refreshes in `~/.claude/.credentials.json` or `~/.codex/auth.json` are ignored by the digest, and secrets are still stripped from anything imported.++This mirrors ChatGPT Work's *Settings > Import* automatic updates, adapted to an explicit, inspectable command instead of a background service.