The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor: move hermes import-agent out of core into the agent-importers plugin
Teknium1342ab855344
diff --git a/hermes_cli/agent_import.py b/hermes_cli/agent_import.pydeleted file mode 100644index ee4683a2bd3..00000000000--- a/hermes_cli/agent_import.py+++ /dev/null@@ -1,665 +0,0 @@-"""hermes import-agent — import Claude Code / Codex CLI setups into Hermes.--Secrets are NEVER imported: credential files are never read, and MCP env vars with secret-looking-names (KEY, TOKEN, SECRET, PASSWORD, ...) are stripped and reported so the user re-adds them via-``hermes setup`` or config.yaml.-"""--from __future__ import annotations--import json-import logging-import re-import shutil-import sys-import time-import tomllib-from pathlib import Path-from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple--import hermes_yaml as yaml--from utils import atomic_write_text, atomic_yaml_write--logger = logging.getLogger(__name__)--# Entry delimiter of the Hermes memory store (memories/MEMORY.md) and the openclaw script.-ENTRY_DELIMITER = "\n§\n"-# Character budget for merged memory files (openclaw script default).-MEMORY_CHAR_LIMIT = 20_000-SUPPORTED_AGENTS = ("claude-code", "codex")-_AGENT_DEFAULT_DIRS = {"claude-code": ".claude", "codex": ".codex"}-_SKILL_CATEGORY = {"claude-code": "claude-code-imports", "codex": "codex-imports"}--# Env var names that look like credentials — never copied into config.yaml.-_SECRET_KEY_RE = re.compile(- r"(?:^|_)(?:API[_-]?KEY|APIKEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?|"- r"AUTH|PRIVATE[_-]?KEY|ACCESS[_-]?KEY)(?:_|$)|KEY$", re.IGNORECASE)---def is_secret_key(key: str) -> bool:- """Return True when an env-var name looks like a credential."""- return bool(_SECRET_KEY_RE.search(key or ""))---def normalize_text(text: str) -> str:- return re.sub(r"\s+", " ", (text or "").strip()).lower()---def read_text(path: Path) -> str:- return path.read_text(encoding="utf-8-sig", errors="replace")---class ConfigReadError(RuntimeError):- """Existing config file present but unreadable/unparseable: the read-modify-write round trip- must be abandoned, else the merged result would replace real settings with only merged keys."""---def load_yaml_file(path: Path) -> dict[str, Any]:- """Load a YAML mapping: absent/empty -> ``{}``; unreadable/unparseable/non-mapping ->- :class:`ConfigReadError` so the caller refuses and leaves the file byte-identical."""- if not path.exists():- return {}- fix_hint = "Fix it with `hermes config edit` (or move it aside), then re-run the import."-- def refusal(detail: str) -> ConfigReadError:- return ConfigReadError(f"Refusing to overwrite {path}: {detail}")-- try:- raw = read_text(path)- except OSError as exc:- raise refusal(f"the existing file cannot be read ({exc}). "- "Fix the file permissions or move it aside first.") from exc- try:- data = yaml.safe_load(raw)- except yaml.YAMLError as exc:- raise refusal(f"the existing file is not valid YAML ({exc}). {fix_hint}") from exc- if data is None: # empty file — a legitimate state with nothing to lose- return {}- if not isinstance(data, dict):- raise refusal(f"expected the existing file to hold a YAML mapping but found "- f"{type(data).__name__}. {fix_hint}")- return data---def dump_yaml_file(path: Path, data: dict[str, Any]) -> None:- """Atomic YAML write; only reached after :func:`load_yaml_file` succeeded on the same path."""- atomic_yaml_write(path, data)---def extract_markdown_entries(text: str) -> list[str]:- """Split markdown into memory entries: headings become context prefixes; bullets and- paragraphs become entries; code blocks and tables are skipped."""- entries: list[str] = []- headings: list[str] = []- paragraph_lines: list[str] = []-- def add_entry(content: str) -> None:- prefix = " > ".join(- h for h in headings- if h and not re.search(r"\b(MEMORY|USER|SOUL|AGENTS|TOOLS|IDENTITY|CLAUDE)\.md\b",- h, re.IGNORECASE))- entries.append(f"{prefix}: {content}" if prefix else content)-- def flush_paragraph() -> None:- block = " ".join(line.strip() for line in paragraph_lines).strip()- paragraph_lines.clear()- if block:- add_entry(block)-- in_code_block = False- for raw_line in (text or "").splitlines():- line = raw_line.rstrip()- stripped = line.strip()- if stripped.startswith("```"):- in_code_block = not in_code_block- flush_paragraph()- continue- if in_code_block:- continue- heading_match = re.match(r"^(#{1,6})\s+(.*\S)\s*$", stripped)- if heading_match:- flush_paragraph()- # Drop deeper (and same-level) headings, then push this one.- headings[len(heading_match.group(1)) - 1:] = [heading_match.group(2).strip()]- continue- bullet_match = re.match(r"^\s*(?:[-*]|\d+\.)\s+(.*\S)\s*$", line)- if bullet_match:- flush_paragraph()- add_entry(bullet_match.group(1).strip())- continue- if not stripped or (stripped.startswith("|") and stripped.endswith("|")):- flush_paragraph() # blank line or table row ends the paragraph- continue- paragraph_lines.append(stripped)-- flush_paragraph()- deduped: list[str] = []- seen = set()- for entry in entries:- normalized = normalize_text(entry)- if normalized and normalized not in seen:- seen.add(normalized)- deduped.append(entry.strip())- return deduped---def parse_existing_memory_entries(path: Path) -> list[str]:- """Parse the DESTINATION memory store (``ENTRY_DELIMITER``-split, as ``MemoryStore`` does).- Do NOT fall back to :func:`extract_markdown_entries`: it drops code blocks/table rows and- splits bullets, and the merged result overwrites the user's store — the loss is permanent."""- if not path.exists():- return []- return [e.strip() for e in read_text(path).split(ENTRY_DELIMITER) if e.strip()]---def merge_entries(existing: Sequence[str], incoming: Sequence[str],- limit: int) -> tuple[list[str], dict[str, int]]:- merged = list(existing)- seen = {normalize_text(e) for e in existing if e.strip()}- stats = {"existing": len(existing), "added": 0, "duplicates": 0, "overflowed": 0}- current_len = len(ENTRY_DELIMITER.join(merged))- for entry in incoming:- normalized = normalize_text(entry)- if not normalized:- continue- if normalized in seen:- stats["duplicates"] += 1- continue- candidate_len = (len(entry) if not merged- else current_len + len(ENTRY_DELIMITER) + len(entry))- if candidate_len > limit:- stats["overflowed"] += 1- continue- merged.append(entry)- seen.add(normalized)- current_len = candidate_len- stats["added"] += 1- return merged, stats---_BASH_RULE_RE = re.compile(r"^Bash\((?P<inner>.*)\)$")---def claude_rule_to_command_pattern(rule: str) -> Optional[str]:- """``Bash(npm run test:*)`` -> ``npm run test*`` (Claude ':*' is a prefix match). Bare ``Bash``- (too broad) and non-Bash rules (Claude-only tools, no allowlist equivalent) return None."""- m = _BASH_RULE_RE.match((rule or "").strip())- inner = m.group("inner").strip() if m else ""- if not inner:- return None- return inner[:-2] + "*" if inner.endswith(":*") else inner---def detect_agents() -> list[str]:- """Return the list of supported agents whose default dirs exist."""- return [a for a in SUPPORTED_AGENTS if (Path.home() / _AGENT_DEFAULT_DIRS[a]).is_dir()]---def sanitize_mcp_env(env: Any) -> tuple[dict[str, str], list[str]]:- """Split an MCP server env dict into (kept, stripped-secret-names)."""- if not isinstance(env, dict):- return {}, []- kept = {str(k): v for k, v in env.items() if not is_secret_key(str(k))}- return kept, [str(k) for k in env if str(k) not in kept]---def _translate_mcp_server(name: str, srv: dict[str, Any]) -> tuple[dict[str, Any], list[str]]:- """Map one Claude/Codex MCP server entry to Hermes shape; returns (server, stripped secret paths)."""- hermes_srv: dict[str, Any] = {}- stripped: list[str] = []- if srv.get("command"):- hermes_srv["command"] = srv["command"]- if srv.get("args"):- hermes_srv["args"] = srv["args"]- env_kept, env_stripped = sanitize_mcp_env(srv.get("env"))- if env_kept:- hermes_srv["env"] = env_kept- stripped.extend(f"mcp_servers.{name}.env.{k}" for k in env_stripped)- if srv.get("cwd"):- hermes_srv["cwd"] = srv["cwd"]- if srv.get("url"):- hermes_srv["url"] = srv["url"]- headers = srv.get("headers")- if isinstance(headers, dict):- kept_headers = {k: v for k, v in headers.items()- if not is_secret_key(str(k)) and "authorization" not in str(k).lower()}- if kept_headers:- hermes_srv["headers"] = kept_headers- stripped.extend(f"mcp_servers.{name}.headers.{k}" for k in headers if k not in kept_headers)- return hermes_srv, stripped---class AgentImporter:- """Detect/parse/map/apply importer for one agent source tree. ``execute=False`` runs the full- 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,- sync_skills: Mapping[str, Optional[str]] | Sequence[str] = ()) -> None:- if agent not in SUPPORTED_AGENTS:- raise ValueError(f"Unsupported agent: {agent!r}")- self.agent = agent- self.source_root = Path(source_root)- self.target_root = Path(target_root)- self.execute = execute- self.overwrite = overwrite- # Skills a previous import-agent run copied (from the sync manifest), name → digest of the copy- # it wrote (None = pre-digest manifest, trusted). --sync refreshes a destination in place only- # while it still matches that digest; a locally edited copy keeps conflict semantics.- self.sync_skills: dict[str, Optional[str]] = (dict(sync_skills) if isinstance(sync_skills, Mapping)- else {name: None for name in sync_skills})- self.items: list[dict[str, Any]] = []- self.stripped_secrets: list[str] = []-- def record(self, kind: str, source, destination, status: str,- reason: str = "", **details) -> None:- self.items.append({"kind": kind, "source": str(source) if source else None,- "destination": str(destination) if destination else None,- "status": status, "reason": reason, **details})-- def load_target_config(self, kind: str, source,- destination: Path) -> Optional[dict[str, Any]]:- """Read the destination config.yaml, or record a refusal and return None. Runs in dry-run- too: ``--dry-run`` must report the refusal, not preview an ``imported`` that destroys it."""- try:- return load_yaml_file(destination)- except ConfigReadError as exc:- self.record(kind, source, destination, "error", str(exc))- return None-- def apply(self, kind: str, source, destination, would: str, action,- details: Optional[dict[str, Any]] = None) -> None:- """Record ``imported`` (reason ``would`` in dry-run); in execute mode run ``action`` first.- ``action`` may add keys to ``details`` (shared by reference) and returns an error string- (recorded as ``error``) or None."""- details = details or {}- error = action() if self.execute else None- self.record(kind, source, destination, "error" if error else "imported",- error or ("" if self.execute else would), **details)-- def build_report(self) -> dict[str, Any]:- summary = {"imported": 0, "skipped": 0, "conflict": 0, "error": 0}- for item in self.items:- summary[item["status"]] = summary.get(item["status"], 0) + 1- report: dict[str, Any] = {"agent": self.agent, "source": str(self.source_root),- "target": str(self.target_root), "dry_run": not self.execute,- "items": self.items, "summary": summary}- if self.stripped_secrets:- report["stripped_secrets"] = sorted(set(self.stripped_secrets))- return report-- def run(self) -> dict[str, Any]:- if not self.source_root.is_dir():- self.record("source", self.source_root, None, "error",- "Source directory does not exist")- else:- {"claude-code": self._run_claude_code, "codex": self._run_codex}[self.agent]()- return self.build_report()-- def _run_claude_code(self) -> None:- settings = self._load_source_mapping(- "settings", self.source_root / "settings.json", json.loads, self._JSON_ERRORS,- record_missing=True, non_mapping_error="settings.json is not a JSON object")- self.import_context_file(self.source_root / "CLAUDE.md", "claude-md")- self._import_permission_rules(settings, "allow")- self._import_permission_rules(settings, "deny")- # mcpServers: ~/.claude.json (preferred; lives NEXT TO ~/.claude/) then settings.json- claude_json = self._load_source_mapping(- "mcp-servers", self.source_root.parent / ".claude.json", json.loads, self._JSON_ERRORS)- servers: dict[str, Any] = {}- for source in (claude_json.get("mcpServers"), settings.get("mcpServers")):- if isinstance(source, dict):- for name, srv in source.items():- servers.setdefault(name, srv)- self.import_mcp_servers(servers, kind="mcp-servers")- self.import_skills(self.source_root / "skills")- commands_dir = self.source_root / "commands"- if commands_dir.is_dir() and any(commands_dir.glob("*.md")):- self.record("slash-commands", commands_dir, None, "skipped",- "Claude slash commands have no direct Hermes equivalent — "- "consider converting them into skills")-- def _run_codex(self) -> None:- config = self._load_source_mapping("config", self.source_root / "config.toml",- tomllib.loads, Exception, record_missing=True)- self.import_context_file(self.source_root / "AGENTS.md", "agents-md")- mcp = config.get("mcp_servers")- self.import_mcp_servers(mcp if isinstance(mcp, dict) else {}, kind="mcp-servers")- memories_dir = self.source_root / "memories"- self._import_markdown_files(- "memories", memories_dir,- sorted(memories_dir.glob("*.md")) if memories_dir.is_dir() else None,- "No memories directory found")- self.import_skills(self.source_root / "skills")-- _JSON_ERRORS = (json.JSONDecodeError, OSError)-- def _load_source_mapping(self, kind: str, path: Path, parse, errors, *,- record_missing: bool = False,- non_mapping_error: str = "") -> dict[str, Any]:- """Parse ``path`` into a mapping; problems become per-item error records and ``{}``."""- if not path.exists():- if record_missing:- self.record(kind, None, None, "skipped", f"No {path.name} found")- return {}- try:- data = parse(read_text(path))- except errors as exc:- self.record(kind, path, None, "error", f"Could not parse {path.name}: {exc}")- return {}- if isinstance(data, dict):- return data- if non_mapping_error:- self.record(kind, path, None, "error", non_mapping_error)- return {}-- def import_context_file(self, source: Path, kind: str) -> None:- """CLAUDE.md / AGENTS.md → memory entries in memories/MEMORY.md."""- self._import_markdown_files(kind, source, [source] if source.exists() else None,- f"No {source.name} found", single_file=True)-- def _import_markdown_files(self, kind: str, source: Path, files: Optional[list[Path]],- missing_reason: str, single_file: bool = False) -> None:- """Extract entries from ``files`` (None = source missing) and merge into memories/MEMORY.md.- An unreadable file records an error; a directory import then still reports "no entries"- when nothing was extracted, while a single-file import stops at the error."""- destination = self.target_root / "memories" / "MEMORY.md"- if files is None:- self.record(kind, None, destination, "skipped", missing_reason)- return- incoming: list[str] = []- failed = False- for md_file in files:- try:- incoming.extend(extract_markdown_entries(read_text(md_file)))- except OSError as exc:- failed = True- self.record(kind, md_file, destination, "error", f"Could not read file: {exc}")- if not incoming:- if not (failed and single_file):- self.record(kind, source, destination, "skipped", "No importable entries found")- return- existing = parse_existing_memory_entries(destination)- merged, stats = merge_entries(existing, incoming, MEMORY_CHAR_LIMIT)- details = {"existing_entries": stats["existing"], "added_entries": stats["added"],- "duplicate_entries": stats["duplicates"],- "overflowed_entries": stats["overflowed"]}- if stats["added"] == 0:- self.record(kind, source, destination, "skipped", "No new entries to import", **details)- return-- def write() -> Optional[str]:- destination.parent.mkdir(parents=True, exist_ok=True)- # Snapshot first (``<name>.bak.<unix_ts>``, as MemoryStore does); never rewrite the- # store when the safety net failed.- step = "back up existing"- try:- if destination.exists():- backup = destination.with_suffix(f"{destination.suffix}.bak.{int(time.time())}")- shutil.copy2(destination, backup)- details["backup"] = str(backup)- step = "write merged"- atomic_write_text(destination, ENTRY_DELIMITER.join(merged) + ("\n" if merged else ""))- except OSError as exc:- return f"Could not {step} memory file: {exc}"- return None-- self.apply(kind, source, destination, "Would merge entries", write, details)-- # (settings key, item kind, config path, dry-run tracks unmapped rules)- _PERMISSION_RULES = {- "allow": ("command-allowlist", ("command_allowlist",), True),- "deny": ("command-denylist", ("approvals", "deny"), False)}-- def _import_permission_rules(self, settings: dict[str, Any], key: str) -> None:- """settings.json permissions.allow/deny → config.yaml command_allowlist / approvals.deny."""- kind, config_path, track_unmapped = self._PERMISSION_RULES[key]- label = f"settings.json permissions.{key}"- destination = self.target_root / "config.yaml"- permissions = settings.get("permissions")- rules = permissions.get(key) if isinstance(permissions, dict) else None- if not isinstance(rules, list) or not rules:- self.record(kind, None, destination, "skipped", f"No permissions.{key} rules found")- return- mapped = [(r, claude_rule_to_command_pattern(r)) for r in rules if isinstance(r, str)]- patterns = sorted(dict.fromkeys(p for _, p in mapped if p))- skipped_rules = [r for r, p in mapped if not p]- unmapped: dict[str, Any] = {"unmapped_rules": skipped_rules} if track_unmapped else {}- if not patterns:- self.record(kind, None, destination, "skipped",- f"No Bash(...) {key} rules to import", **unmapped)- return- if not skipped_rules:- unmapped = {}- config = self.load_target_config(kind, label, destination)- if config is None:- return- # Walk to the list's parent mapping, materializing missing/invalid levels.- parent: dict[str, Any] = config- for part in config_path[:-1]:- child = parent.get(part)- parent[part] = parent = child if isinstance(child, dict) else {}- current = parent.get(config_path[-1], [])- current = current if isinstance(current, list) else []- merged = sorted(dict.fromkeys(list(current) + patterns))- added = [p for p in merged if p not in current]- if not added:- self.record(kind, label, destination, "skipped", "All patterns already present")- return-- def write() -> None:- parent[config_path[-1]] = merged- dump_yaml_file(destination, config)-- self.apply(kind, label, destination, "Would merge patterns", write,- {"added_patterns": added, **unmapped})-- def import_mcp_servers(self, servers: dict[str, Any], kind: str) -> None:- """mcpServers / [mcp_servers.*] → config.yaml mcp_servers."""- destination = self.target_root / "config.yaml"- if not servers:- self.record(kind, None, destination, "skipped", "No MCP servers found")- return- config = self.load_target_config(kind, None, destination)- if config is None:- return- existing = config.get("mcp_servers")- existing = existing if isinstance(existing, dict) else {}- added = 0- for name, srv in servers.items():- if not isinstance(srv, dict):- self.record(kind, name, None, "skipped", "Server entry is not a mapping")- continue- if name in existing and not self.overwrite:- self.record(kind, name, f"mcp_servers.{name}", "conflict",- "MCP server already exists in Hermes config")- continue- hermes_srv, stripped = _translate_mcp_server(name, srv)- self.stripped_secrets.extend(stripped)- if not hermes_srv:- self.record(kind, name, None, "skipped", "Server has neither a command nor a url")- continue- existing[name] = hermes_srv- added += 1- self.record(kind, name, f"config.yaml mcp_servers.{name}", "imported")- if added > 0 and self.execute:- config["mcp_servers"] = existing- dump_yaml_file(destination, config)-- def import_skills(self, source_root: Path) -> None:- """skills/<name>/SKILL.md dirs → HERMES_HOME/skills/<category>/<name>."""- destination_root = self.target_root / "skills" / _SKILL_CATEGORY[self.agent]- if not source_root.is_dir():- self.record("skills", None, destination_root, "skipped", "No skills directory found")- return- skill_dirs = [p for p in sorted(source_root.iterdir())- if p.is_dir() and (p / "SKILL.md").exists()]- if not skill_dirs:- self.record("skills", source_root, destination_root, "skipped",- "No skills with SKILL.md found")- return- from hermes_cli.agent_import_sync import skill_tree_digest- for skill_dir in skill_dirs:- destination = destination_root / skill_dir.name- if destination.exists() and not self.overwrite:- if skill_dir.name not in self.sync_skills:- self.record("skill", skill_dir, destination, "conflict", "Destination skill already exists")- continue- expected = self.sync_skills[skill_dir.name]- if expected is not None and skill_tree_digest(destination) != expected:- self.record("skill", skill_dir, destination, "conflict",- "Imported skill was modified locally — not refreshed")- continue-- def copy(skill_dir=skill_dir, destination=destination) -> None:- destination.parent.mkdir(parents=True, exist_ok=True)- if destination.exists():- shutil.rmtree(destination)- shutil.copytree(skill_dir, destination)-- self.apply("skill", skill_dir, destination, "Would copy skill directory", copy)---def import_agent_command(args) -> None:- """Handle ``hermes import-agent`` (invoked from hermes_cli.main)."""- from hermes_cli.config import get_config_path, load_config, save_config- from hermes_constants import get_hermes_home- 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.overwrite-- if agent is None:- detected = detect_agents()- if not detected:- print()- print_error("No supported agent setup found (~/.claude or ~/.codex).")- print_info("Specify one explicitly: hermes import-agent claude-code --source /path")- return- if len(detected) > 1 and explicit_source is None:- print()- print_info("Multiple agent setups detected: " + ", ".join(detected))- print_info("Pick one: hermes import-agent claude-code or hermes import-agent codex")- return- agent = detected[0]- source_dir = Path(explicit_source or Path.home() / _AGENT_DEFAULT_DIRS[agent])-- print()- print(color("┌─────────────────────────────────────────────────────────┐", Colors.MAGENTA))- print(color("│ ☤ Hermes — Import From Another Agent │", Colors.MAGENTA))- print(color("└─────────────────────────────────────────────────────────┘", Colors.MAGENTA))- if not source_dir.is_dir():- print()- print_error(f"Agent directory not found: {source_dir}")- print_info(f"Specify a custom path: hermes import-agent {agent} --source /path/to/{_AGENT_DEFAULT_DIRS[agent]}")- return- hermes_home = get_hermes_home()- print()- print_header("Import Settings")- print_info(f"Agent: {agent}")- print_info(f"Source: {source_dir}")- print_info(f"Target: {hermes_home}")- print_info(f"Overwrite: {'yes' if overwrite else 'no (skip conflicts)'}")- print_info("Secrets: never imported — run 'hermes setup' for credentials")- # Ensure config.yaml exists before the import tries to merge into it- if not get_config_path().exists():- save_config(load_config())-- def run_import(execute: bool, phase: str) -> Optional[dict[str, Any]]:- """Run the importer; on failure print the error and return None."""- try:- return AgentImporter(agent, source_dir.resolve(), hermes_home.resolve(),- execute=execute, overwrite=overwrite).run()- except Exception as e:- print()- print_error(f"Import{phase} failed: {e}")- logger.debug(f"import-agent{phase} error", exc_info=True)- return None-- # Phase 1: preview (always)- preview = run_import(False, " preview")- if preview is None:- return- summary = preview.get("summary", {})- if summary.get("imported", 0) == 0 and summary.get("conflict", 0) == 0:- print()- print_info(f"Nothing to import from {agent}.")- print_import_report(preview, dry_run=True)- return- print()- print_header(f"Import Preview — {summary.get('imported', 0)} item(s) would be imported")- print_info("No changes have been made yet. Review the list below:")- print_import_report(preview, dry_run=True)- if args.dry_run:- return-- # Phase 2: confirm and execute- print()- if not args.yes:- if not sys.stdin.isatty():- print_info("Non-interactive session — preview only.")- print_info(f"To execute, re-run with: hermes import-agent {agent} --yes")- return- if not prompt_yes_no("Proceed with import?", default=True):- print_info("Import cancelled.")- return- report = run_import(True, "")- if report is None:- return- print_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' "- "to configure providers, or add them to ~/.hermes/.env.")---def print_import_report(report: dict[str, Any], dry_run: bool) -> None:- """Print a formatted per-item import report (claw-migrate style)."""- from hermes_cli.setup import Colors, color, print_header, print_info-- print()- print_header("Dry Run Results" if dry_run else "Import Results")- if dry_run:- print_info("No files were modified. This is a preview of what would happen.")- print()- # (status, colour, group heading, summary label)- groups = (- ("imported", Colors.GREEN, "✓ Would import" if dry_run else "✓ Imported",- "would import" if dry_run else "imported"),- ("conflict", Colors.YELLOW, "⚠ Conflicts (skipped — use --overwrite to force)",- "conflict(s)"),- ("skipped", Colors.DIM, "─ Skipped", "skipped"),- ("error", Colors.RED, "✗ Errors", "error(s)"))- for status, col, label, _ in groups:- group_items = [i for i in report.get("items", []) if i.get("status") == status]- if not group_items:- continue- print(color(f" {label}:", col))- for item in group_items:- tail = ("→ " + str(item.get("destination") or "").replace(str(Path.home()), "~")- if status == "imported" else f" {item.get('reason', '')}")- print(f" {item.get('kind', 'unknown'):<22s} {tail}")- print()- if stripped := report.get("stripped_secrets"):- print(color(" ⚷ Secrets stripped (never imported):", Colors.YELLOW))- for name in stripped:- print(f" {name}")- print_info("Re-add credentials deliberately via 'hermes setup' or ~/.hermes/.env.")- print()- summary = report.get("summary", {})- parts = [f"{summary[k]} {label}" for k, _, _, label in groups if summary.get(k)]- if parts:- print_info(f"Summary: {', '.join(parts)}")diff --git a/hermes_cli/agent_import_sync.py b/hermes_cli/agent_import_sync.pydeleted file mode 100644index 93a87a2bd42..00000000000--- a/hermes_cli/agent_import_sync.py+++ /dev/null@@ -1,192 +0,0 @@-"""``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, Optional--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 skill_tree_digest(skill_dir: Path) -> str:- """Content digest of an installed skill directory (relative path + bytes of every file)."""- digest = hashlib.sha256()- for path in sorted(p for p in Path(skill_dir).rglob("*") if p.is_file()):- try:- digest.update(f"{path.relative_to(skill_dir)}\0{hashlib.sha256(path.read_bytes()).hexdigest()}\0".encode("utf-8", "replace"))- except OSError:- digest.update(b"unreadable\0")- return digest.hexdigest()---def managed_skills(entry: Any) -> dict[str, Optional[str]]:- """``imported_skills`` as ``{name: digest-at-import}`` (a pre-digest list maps to ``None`` = trusted)."""- skills = entry.get("imported_skills") if isinstance(entry, dict) else None- if isinstance(skills, dict):- return dict(skills)- return {name: None for name in skills} if isinstance(skills, list) else {}---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-sig", 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], *, refresh_digest: bool = True) -> None:- """Record/refresh the sync entry for ``agent`` after a real (non-dry-run) import.-- ``imported_skills`` maps every skill this command ever copied for the agent to the digest of- the copy it wrote: a later sync replaces the destination only while it still matches that- digest, so a skill the user edited (or created) under the import category is never clobbered.- ``refresh_digest=False`` keeps the previous source digest so a run with errors is retried.- """- manifest = load_sync_manifest(target_root)- agents = manifest.setdefault("agents", {})- entry = agents.get(agent)- if not isinstance(entry, dict):- entry = {}- skills = managed_skills(entry)- for item in report.get("items", []):- if item.get("kind") == "skill" and item.get("status") == "imported" and item.get("destination"):- skills[Path(item["destination"]).name] = skill_tree_digest(Path(item["destination"]))- entry.update({"source": str(source_root), "overwrite": bool(overwrite),- "last_import": int(time.time()), "imported_skills": dict(sorted(skills.items()))})- if refresh_digest or "digest" not in entry:- entry["digest"] = compute_source_digest(agent, Path(source_root))- 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))- try:- report = AgentImporter(agent_name, source_dir, hermes_home, execute=not dry_run,- overwrite=overwrite, sync_skills=managed_skills(entry)).run()- except Exception as exc:- 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)- had_errors = bool(report.get("summary", {}).get("error"))- if had_errors:- failed += 1- if not dry_run:- try:- # Errors keep the old source digest so the next sync retries the failed items.- update_sync_manifest(agent_name, source_dir, hermes_home, overwrite, report,- refresh_digest=not had_errors)- 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/left_core_migration.py b/hermes_cli/left_core_migration.pyindex 388708777f6..2e7c000562d 100644--- a/hermes_cli/left_core_migration.py+++ b/hermes_cli/left_core_migration.py@@ -182,6 +182,13 @@ def singularity_in_use(home: Path, *, process_env: bool = False) -> bool:return configured.lower() == "singularity"+def agent_imports_in_use(home: Path, *, process_env: bool = False) -> bool:+ """*home* registered a ``hermes import-agent`` source for ``--sync`` (its ``import-sync.json``,+ which scheduled syncs read). A one-shot import leaves no other trace, and installing the plugin+ for every home would add a command nobody asked for; the old spelling names the install."""+ return (home / "import-sync.json").is_file()++@dataclass(frozen=True)class LeftCoreFeature:plugin: str # catalog entry name == installed plugin name@@ -209,8 +216,9 @@ class LeftCoreFeature:# prefixes it shared with the feature's tools (stripped only when the source runs the adapter).enable_env: tuple[str, ...] = ()channel_env_prefixes: tuple[str, ...] = ()- # Top-level command the plugin registers in place of core's ``hermes auth <cli>`` login- # (``hermes <cli> login|status|logout``); :func:`moved_command_hint` points the old spelling at it.+ # Top-level command the plugin registers: in place of core's ``hermes auth <cli>`` login+ # (``hermes <cli> login|status|logout``), or core's own top-level command kept under the same name+ # (``hermes import-agent``). :func:`moved_command_hint` points the old spelling at the plugin.cli: str = ""# Top-level command the plugin registers in place of core's nested ``old_command``# (``hermes mcp serve`` -> ``hermes mcp-serve``); :func:`moved_command_hint` points the old spelling at it.@@ -259,6 +267,11 @@ LEFT_CORE: tuple[LeftCoreFeature, ...] = ("and the container_* limits are unchanged",terminal_backend="singularity",),+ LeftCoreFeature(+ plugin="agent-importers", label="`hermes import-agent`", in_use=agent_imports_in_use,+ unchanged="`hermes import-agent`, its flags and your import-sync.json sync sources are unchanged",+ cli="import-agent",+ ),)def _install_sentence(feature: LeftCoreFeature) -> str:diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex e597ce70aee..beea0a159c6 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -369,7 +369,6 @@ from hermes_cli.subcommands.dump import build_dump_parserfrom hermes_cli.subcommands.debug import build_debug_parserfrom hermes_cli.subcommands.backup import build_backup_parserfrom hermes_cli.subcommands.import_cmd import build_import_cmd_parser-from hermes_cli.subcommands.import_agent import build_import_agent_parserfrom hermes_cli.subcommands.config import build_config_parserfrom hermes_cli.subcommands.skin import build_skin_parserfrom hermes_cli.subcommands.console import build_console_parser@@ -1844,7 +1843,6 @@ cmd_pairing = _forward_command("cmd_pairing", "hermes_cli.pairing", "pairing_comcmd_plugins = _forward_command("cmd_plugins", "hermes_cli.plugins_cmd", "plugins_command")cmd_mcp = _forward_command("cmd_mcp", "hermes_cli.mcp_config", "mcp_command", forward_return=True)cmd_claw = _forward_command("cmd_claw", "hermes_cli.claw", "claw_command")-cmd_import_agent = _forward_command("cmd_import_agent", "hermes_cli.agent_import", "import_agent_command")def cmd_model(args):@@ -2763,7 +2761,7 @@ _BUILTIN_SUBCOMMANDS = frozenset("acp", "approvals", "auth", "backup", "bundles", "checkpoints", "claw", "codex-runtime", "completion","computer-use", "connectors","config", "console", "cron", "curator", "dashboard", "serve", "debug", "doctor",- "dump", "egress", "fallback", "gateway", "hooks", "import", "import-agent", "insights",+ "dump", "egress", "fallback", "gateway", "hooks", "import", "insights","gui", "desktop", "kanban", "login", "logout", "logs", "lsp", "mcp", "memory", "migrate", "moa","journey", "memory-graph", "learning","model", "monitoring", "pairing", "pause", "peer", "pets", "plugins", "portal", "profile",@@ -3352,7 +3350,6 @@ def _build_cli_parser():build_backup_parser(subparsers, cmd_backup=cmd_backup)build_checkpoints_parser(subparsers)build_import_cmd_parser(subparsers, cmd_import=cmd_import)- build_import_agent_parser(subparsers, cmd_import_agent=cmd_import_agent)build_config_parser(subparsers, cmd_config=cmd_config)build_skin_parser(subparsers, cmd_skin=cmd_skin)build_console_parser(subparsers, cmd_console=cmd_console)diff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.pyindex f81e091e64d..08b7eb1057f 100644--- a/hermes_cli/profiles.py+++ b/hermes_cli/profiles.py@@ -1354,8 +1354,8 @@ def _bootstrap_profile_dir(profile_dir: Path, source_dir: Optional[Path],config files, installed skills (the dashboard's "clone from default" must keep bundledAND user-installed skills), and memory/identity files from *source_dir*.- ``sync_imports`` also copies the source's ``import-sync.json`` (the ``hermes import-agent``- manifest) so the clone stays registered against the same external Claude Code / Codex trees+ ``sync_imports`` also copies the source's ``import-sync.json`` (the manifest the agent-importers+ plugin's ``hermes import-agent`` writes) so the clone stays registered against the same external treesand ``hermes -p <clone> import-agent --sync`` keeps pulling from them. The link is to theexternal tree, never to the source profile: both profiles stay independent islands."""profile_dir.mkdir(parents=True, exist_ok=True)@@ -1376,9 +1376,8 @@ def _bootstrap_profile_dir(profile_dir: Path, source_dir: Optional[Path],from hermes_cli.profile_memory_config import active_memory_provider, clone_memory_provider_configclone_memory_provider_config(source_dir, profile_dir,active_memory_provider(_load_yaml_dict(source_dir / "config.yaml")))- if sync_imports:- from hermes_cli.agent_import_sync import SYNC_MANIFEST_NAME # lazy: keeps yaml/utils off the hot startup path- _clone_file(source_dir, profile_dir, SYNC_MANIFEST_NAME)+ if sync_imports: # a plain file at the profile root, written by the agent-importers plugin+ _clone_file(source_dir, profile_dir, "import-sync.json")def create_profile(diff --git a/hermes_cli/subcommands/import_agent.py b/hermes_cli/subcommands/import_agent.pydeleted file mode 100644index 0b2205186bd..00000000000--- a/hermes_cli/subcommands/import_agent.py+++ /dev/null@@ -1,36 +0,0 @@-"""``hermes import-agent`` subcommand parser (logic lives in ``hermes_cli/agent_import.py``)."""--from __future__ import annotations--from typing import Callable--from hermes_cli.subcommands._shared import add_yes_flag---def build_import_agent_parser(subparsers, *, cmd_import_agent: Callable) -> None:- """Attach the ``import-agent`` subcommand to ``subparsers``."""- parser = subparsers.add_parser(- "import-agent", help="Import a Claude Code or Codex CLI setup into Hermes",- description="One-command import of another coding agent's setup into Hermes. "- "Maps CLAUDE.md/AGENTS.md instructions, permission allowlists, MCP "- "servers, skills, and memories into their Hermes equivalents. "- "Always shows a preview before making changes. API keys and "- "credentials are never imported — run 'hermes setup' for those.")- parser.add_argument(- "agent", nargs="?", choices=["claude-code", "codex"],- help="Which agent to import from (default: auto-detect ~/.claude or ~/.codex)")- parser.add_argument(- "--source", help="Path to the agent's config directory (default: ~/.claude or ~/.codex)")- parser.add_argument(- "--dry-run", action="store_true",- help="Preview only — stop after showing what would be imported")- parser.add_argument(- "--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.pydeleted file mode 100644index ec5f4b22b80..00000000000--- a/tests/hermes_cli/test_agent_import.py+++ /dev/null@@ -1,777 +0,0 @@-"""Tests for hermes_cli.agent_import — ``hermes import-agent``.--Covers: source detection, Claude Code and Codex parsing, mapping into the-real Hermes stores (memories/MEMORY.md, config.yaml command_allowlist /-approvals.deny / mcp_servers, skills/), dry-run write-nothing guarantees,-malformed-input skip reports, and the never-import-secrets rule.--Uses the profile_env fixture pattern from tests/hermes_cli/test_profiles.py:-Path.home() and HERMES_HOME are redirected to tmp_path so nothing touches-the real ~/.hermes.-"""--import json-from pathlib import Path--import pytest-import hermes_yaml as yaml--from hermes_cli.agent_import import (- ENTRY_DELIMITER,- AgentImporter,- claude_rule_to_command_pattern,- detect_agents,- extract_markdown_entries,- is_secret_key,- sanitize_mcp_env,-)---# ----------------------------------------------------------------------------# Shared fixture: redirect Path.home() and HERMES_HOME (profile_env pattern)-# -----------------------------------------------------------------------------def profile_env(tmp_path, monkeypatch):- """Isolated environment: Path.home() -> tmp_path, HERMES_HOME -> tmp/.hermes."""- monkeypatch.setattr(Path, "home", lambda: tmp_path)- default_home = tmp_path / ".hermes"- default_home.mkdir(exist_ok=True)- monkeypatch.setenv("HERMES_HOME", str(default_home))- return tmp_path---def hermes_home(profile_env):- return profile_env / ".hermes"---# ----------------------------------------------------------------------------# Fake source trees-# -----------------------------------------------------------------------------CLAUDE_MD = """# Global instructions--## Style-- Always use type hints-- Prefer pathlib over os.path--Run the linter before committing.-"""--AGENTS_MD = """# Codex rules--- Never force-push to main-- Keep commits atomic-"""---def claude_tree(profile_env):- """Build a fake ~/.claude tree (plus sibling ~/.claude.json)."""- root = profile_env / ".claude"- root.mkdir()- (root / "CLAUDE.md").write_text(CLAUDE_MD, encoding="utf-8")- (root / "settings.json").write_text(json.dumps({- "permissions": {- "allow": [- "Bash(npm run build)",- "Bash(npm run test:*)",- "Bash(git diff *)",- "Read(~/.zshrc)", # non-Bash → unmapped- ],- "deny": [- "Bash(rm -rf *)",- "WebFetch", # non-Bash → dropped- ],- },- "mcpServers": {- "settings-server": {"command": "uvx", "args": ["settings-mcp"]},- },- }), encoding="utf-8")- # mcpServers in the sibling ~/.claude.json (Claude's primary MCP store)- (profile_env / ".claude.json").write_text(json.dumps({- "mcpServers": {- "github": {- "command": "npx",- "args": ["-y", "@modelcontextprotocol/server-github"],- "env": {- "GITHUB_TOKEN": "ghp_SECRET123",- "GITHUB_HOST": "github.example.com",- },- },- "remote": {- "url": "https://mcp.example.com/sse",- "headers": {- "Authorization": "Bearer abc123",- "X-Region": "us-east",- },- },- },- }), encoding="utf-8")- # A credentials file that must never be read/imported- (root / ".credentials.json").write_text(- json.dumps({"api_key": "sk-ant-SUPERSECRET"}), encoding="utf-8")- # Skills- skill = root / "skills" / "deploy-helper"- skill.mkdir(parents=True)- (skill / "SKILL.md").write_text(- "---\nname: deploy-helper\n---\n\nDeploy things.\n", encoding="utf-8")- (root / "skills" / "not-a-skill").mkdir() # no SKILL.md → ignored- # Slash commands (reported as skipped)- commands = root / "commands"- commands.mkdir()- (commands / "review.md").write_text("Review this PR", encoding="utf-8")- return root---def codex_tree(profile_env):- """Build a fake ~/.codex tree."""- root = profile_env / ".codex"- root.mkdir()- (root / "AGENTS.md").write_text(AGENTS_MD, encoding="utf-8")- (root / "config.toml").write_text(- 'model = "gpt-5"\n'- 'approval_policy = "on-request"\n'- "\n"- "[mcp_servers.docs]\n"- 'command = "uvx"\n'- 'args = ["docs-mcp"]\n'- "\n"- "[mcp_servers.docs.env]\n"- 'DOCS_API_KEY = "secret-value"\n'- 'DOCS_REGION = "eu"\n',- encoding="utf-8",- )- (root / "auth.json").write_text(- json.dumps({"OPENAI_API_KEY": "sk-SECRET"}), encoding="utf-8")- memories = root / "memories"- memories.mkdir()- (memories / "2026-01-01.md").write_text(- "- User prefers tabs over spaces\n- Project uses PostgreSQL\n",- encoding="utf-8",- )- skill = root / "skills" / "db-migrate"- skill.mkdir(parents=True)- (skill / "SKILL.md").write_text(- "---\nname: db-migrate\n---\n\nMigrate databases.\n", encoding="utf-8")- return root---def snapshot_tree(root: Path) -> dict:- """Map of relative-path -> bytes for every file under root."""- return {- str(p.relative_to(root)): p.read_bytes()- for p in sorted(root.rglob("*")) if p.is_file()- }---def run_import(agent, source, hermes_home, execute, overwrite=False):- return AgentImporter(- agent=agent,- source_root=source,- target_root=hermes_home,- execute=execute,- overwrite=overwrite,- ).run()---# ----------------------------------------------------------------------------# Detection & helpers-# -----------------------------------------------------------------------------class TestDetection:- def test_detects_claude_and_codex(self, claude_tree, codex_tree):- assert detect_agents() == ["claude-code", "codex"]--- def test_unsupported_agent_raises(self, hermes_home, tmp_path):- with pytest.raises(ValueError):- AgentImporter("cursor", tmp_path, hermes_home)---class TestRuleMapping:- def test_bash_rule_plain(self):- assert claude_rule_to_command_pattern("Bash(npm run build)") == "npm run build"--- def test_non_bash_rule_is_none(self):- assert claude_rule_to_command_pattern("Read(~/.zshrc)") is None- assert claude_rule_to_command_pattern("WebFetch") is None---class TestSecretDetection:- @pytest.mark.parametrize("key", [- "GITHUB_TOKEN", "OPENAI_API_KEY", "MY_SECRET", "DB_PASSWORD",- "AWS_ACCESS_KEY", "AUTH_HEADER", "APIKEY",- ])- def test_secret_keys(self, key):- assert is_secret_key(key)-- @pytest.mark.parametrize("key", ["GITHUB_HOST", "REGION", "DEBUG", "PORT"])- def test_non_secret_keys(self, key):- assert not is_secret_key(key)-- def test_sanitize_env_splits(self):- kept, stripped = sanitize_mcp_env(- {"API_TOKEN": "x", "HOST": "h", "MY_KEY": "k"})- assert kept == {"HOST": "h"}- assert sorted(stripped) == ["API_TOKEN", "MY_KEY"]---class TestMarkdownEntries:- def test_extracts_bullets_and_paragraphs(self):- entries = extract_markdown_entries(CLAUDE_MD)- assert any("type hints" in e for e in entries)- assert any("linter" in e for e in entries)---# ----------------------------------------------------------------------------# Dry run writes NOTHING-# -----------------------------------------------------------------------------class TestDryRun:- def test_claude_dry_run_writes_nothing(self, claude_tree, hermes_home):- before = snapshot_tree(hermes_home)- report = run_import("claude-code", claude_tree, hermes_home, execute=False)- assert snapshot_tree(hermes_home) == before- assert report["dry_run"] is True- assert report["summary"]["imported"] > 0--- def test_dry_run_and_real_run_plan_same_items(self, claude_tree, hermes_home):- preview = run_import("claude-code", claude_tree, hermes_home, execute=False)- applied = run_import("claude-code", claude_tree, hermes_home, execute=True)- pk = [(i["kind"], i["status"]) for i in preview["items"]]- ak = [(i["kind"], i["status"]) for i in applied["items"]]- assert pk == ak---# ----------------------------------------------------------------------------# Claude Code real run — every item lands in the right store-# -----------------------------------------------------------------------------class TestClaudeCodeImport:- @pytest.fixture()- def report(self, claude_tree, hermes_home):- return run_import("claude-code", claude_tree, hermes_home, execute=True)--- def test_allowlist_lands_in_config_yaml(self, report, hermes_home):- config = yaml.safe_load((hermes_home / "config.yaml").read_text(encoding="utf-8"))- allow = config["command_allowlist"]- assert "npm run build" in allow- assert "npm run test*" in allow- assert "git diff *" in allow- # non-Bash rules must not leak in- assert not any("Read(" in p for p in allow)----- def test_slash_commands_reported_skipped(self, report):- items = {i["kind"]: i for i in report["items"]}- assert items["slash-commands"]["status"] == "skipped"---# ----------------------------------------------------------------------------# Codex real run-# -----------------------------------------------------------------------------class TestCodexImport:- @pytest.fixture()- def report(self, codex_tree, hermes_home):- return run_import("codex", codex_tree, hermes_home, execute=True)--- def test_mcp_servers_from_config_toml(self, report, hermes_home):- config = yaml.safe_load((hermes_home / "config.yaml").read_text(encoding="utf-8"))- docs = config["mcp_servers"]["docs"]- assert docs["command"] == "uvx"- assert docs["args"] == ["docs-mcp"]- # non-secret env survives, secret is stripped- assert docs["env"] == {"DOCS_REGION": "eu"}-- def test_skill_copied(self, report, hermes_home):- assert (hermes_home / "skills" / "codex-imports" / "db-migrate" / "SKILL.md").exists()---# ----------------------------------------------------------------------------# Secrets are never copied-# -----------------------------------------------------------------------------class TestSecretsNeverImported:- def test_no_secret_values_anywhere_claude(self, claude_tree, hermes_home):- run_import("claude-code", claude_tree, hermes_home, execute=True)- blob = "".join(- p.read_text(encoding="utf-8", errors="replace")- for p in hermes_home.rglob("*") if p.is_file()- )- assert "ghp_SECRET123" not in blob- assert "Bearer abc123" not in blob- assert "sk-ant-SUPERSECRET" not in blob-- def test_no_secret_values_anywhere_codex(self, codex_tree, hermes_home):- run_import("codex", codex_tree, hermes_home, execute=True)- blob = "".join(- p.read_text(encoding="utf-8", errors="replace")- for p in hermes_home.rglob("*") if p.is_file()- )- assert "secret-value" not in blob- assert "sk-SECRET" not in blob-- def test_stripped_secrets_reported(self, claude_tree, hermes_home):- report = run_import("claude-code", claude_tree, hermes_home, execute=True)- stripped = report.get("stripped_secrets", [])- assert "mcp_servers.github.env.GITHUB_TOKEN" in stripped- assert any("Authorization" in s for s in stripped)-- def test_non_secret_header_kept(self, claude_tree, hermes_home):- run_import("claude-code", claude_tree, hermes_home, execute=True)- config = yaml.safe_load((hermes_home / "config.yaml").read_text(encoding="utf-8"))- assert config["mcp_servers"]["remote"]["headers"] == {"X-Region": "us-east"}---# ----------------------------------------------------------------------------# Malformed inputs: per-item skip/error reports, no crashes-# -----------------------------------------------------------------------------class TestMalformedInputs:- def test_bad_settings_json_reports_error(self, profile_env, hermes_home):- root = profile_env / ".claude"- root.mkdir()- (root / "settings.json").write_text("{not json!!", encoding="utf-8")- (root / "CLAUDE.md").write_text("- still importable\n", encoding="utf-8")- report = run_import("claude-code", root, hermes_home, execute=True)- errors = [i for i in report["items"] if i["status"] == "error"]- assert any(i["kind"] == "settings" for i in errors)- # CLAUDE.md still imported despite bad settings.json- assert "still importable" in (- hermes_home / "memories" / "MEMORY.md").read_text(encoding="utf-8")--- def test_empty_tree_all_skipped(self, profile_env, hermes_home):- root = profile_env / ".codex"- root.mkdir()- report = run_import("codex", root, hermes_home, execute=True)- assert report["summary"]["imported"] == 0- assert report["summary"]["error"] == 0---# ----------------------------------------------------------------------------# Merge semantics & conflicts-# -----------------------------------------------------------------------------class TestMergeSemantics:-- def test_existing_mcp_server_conflicts_without_overwrite(- self, claude_tree, hermes_home):- (hermes_home / "config.yaml").write_text(- yaml.safe_dump({"mcp_servers": {"github": {"command": "mine"}}}),- encoding="utf-8")- report = run_import("claude-code", claude_tree, hermes_home, execute=True)- config = yaml.safe_load((hermes_home / "config.yaml").read_text(encoding="utf-8"))- assert config["mcp_servers"]["github"]["command"] == "mine"- assert any(- i["status"] == "conflict" and i["source"] == "github"- for i in report["items"]- )--- def test_existing_skill_conflicts_without_overwrite(- self, claude_tree, hermes_home):- dest = hermes_home / "skills" / "claude-code-imports" / "deploy-helper"- dest.mkdir(parents=True)- (dest / "SKILL.md").write_text("mine\n", encoding="utf-8")- report = run_import("claude-code", claude_tree, hermes_home, execute=True)- assert (dest / "SKILL.md").read_text(encoding="utf-8") == "mine\n"- assert any(- i["kind"] == "skill" and i["status"] == "conflict"- for i in report["items"]- )-- def test_reimport_is_idempotent_for_memory(self, claude_tree, hermes_home):- run_import("claude-code", claude_tree, hermes_home, execute=True)- first = (hermes_home / "memories" / "MEMORY.md").read_text(encoding="utf-8")- report = run_import("claude-code", claude_tree, hermes_home, execute=True)- assert (hermes_home / "memories" / "MEMORY.md").read_text(encoding="utf-8") == first- memory_items = [i for i in report["items"] if i["kind"] == "claude-md"]- assert memory_items[0]["status"] == "skipped"---# ----------------------------------------------------------------------------# The DESTINATION memories/MEMORY.md is a §-delimited store, not a document-# -----------------------------------------------------------------------------# A realistic hand-edited store: one entry, no "§", with a fenced code block-# and a markdown table — exactly the content extract_markdown_entries() drops.-EXISTING_MEMORY = """Homelab runbook. Restart the ingress controller with:--```bash-kubectl -n ingress rollout restart deploy/nginx-```--Escalation ladder:--| Severity | Contact | Window |-|----------|---------|--------|-| SEV1 | on-call | 15m |-| SEV2 | #ops | 4h |--Never page for SEV3.-"""---class TestExistingMemoryStorePreserved:- """An import must not shred the memory store it merges into.-- ``memories/MEMORY.md`` is the entry-delimited store written by- ``MemoryStore._write_file``; a single-entry or hand-edited store contains- no ``§`` delimiter. Parsing it with the *source* markdown extractor drops- code blocks and table rows and splits one entry into fragments, and the- merged result is written straight back over the file.- """-- @pytest.fixture()- def seeded_home(self, hermes_home):- memory = hermes_home / "memories" / "MEMORY.md"- memory.parent.mkdir(parents=True, exist_ok=True)- memory.write_text(EXISTING_MEMORY, encoding="utf-8")- return hermes_home---- def test_import_preserves_existing_entry_verbatim(- self, claude_tree, seeded_home):- path = seeded_home / "memories" / "MEMORY.md"- run_import("claude-code", claude_tree, seeded_home, execute=True)- entries = path.read_text(encoding="utf-8").split(ENTRY_DELIMITER)- # The pre-existing store survives byte-intact as a SINGLE entry ...- assert entries[0] == EXISTING_MEMORY.strip()- # ... including the parts the markdown extractor would have dropped.- assert "kubectl -n ingress rollout restart deploy/nginx" in entries[0]- assert "| SEV1 | on-call | 15m |" in entries[0]- # ... and the imported entries are still appended after it.- assert any("type hints" in e for e in entries[1:])-- def test_import_backs_up_the_previous_store(self, claude_tree, seeded_home):- memories = seeded_home / "memories"- run_import("claude-code", claude_tree, seeded_home, execute=True)- backups = sorted(memories.glob("MEMORY.md.bak.*"))- assert len(backups) == 1- assert backups[0].read_text(encoding="utf-8") == EXISTING_MEMORY---# ----------------------------------------------------------------------------# config.yaml preservation (sibling of the MEMORY.md case above)-# -----------------------------------------------------------------------------EXISTING_CONFIG = """\-model: hermes-4-405b-api_key_env: OPENROUTER_API_KEY-command_allowlist:- - ls *- - cat *-approvals:- deny:- - shutdown *-mcp_servers:- local-notes:- command: uvx- args:- - notes-mcp-telegram:- enabled: true- chat_id: 12345-"""--MALFORMED_CONFIG = """\-model: hermes-4-405b-command_allowlist:- - ls *- - cat *-approvals: [unclosed-"""--CONFIG_WRITING_KINDS = ("command-allowlist", "command-denylist", "mcp-servers")---class TestExistingConfigPreserved:- """An import must not destroy the config.yaml it merges into.-- ``load_yaml_file`` returned ``{}`` for an absent file AND for a present- file it could not read or parse. The three importers below read- config.yaml, merge one section into it, and write the whole mapping back —- so a YAML syntax error or a permission problem meant every existing- setting was replaced by just the merged section, reported as ``imported``.- """-- @pytest.fixture()- def config_path(self, hermes_home):- return hermes_home / "config.yaml"-- @staticmethod- def items_for(report, kind):- return [i for i in report["items"] if i["kind"] == kind]-- # -- present but unreadable: refuse, change nothing ---------------------- def test_malformed_config_is_left_byte_identical(- self, claude_tree, hermes_home, config_path):- config_path.write_text(MALFORMED_CONFIG, encoding="utf-8")- before = config_path.read_bytes()-- run_import("claude-code", claude_tree, hermes_home, execute=True)-- assert config_path.read_bytes() == before-- def test_malformed_config_records_an_error_not_an_import(- self, claude_tree, hermes_home, config_path):- config_path.write_text(MALFORMED_CONFIG, encoding="utf-8")-- report = run_import("claude-code", claude_tree, hermes_home, execute=True)-- for kind in CONFIG_WRITING_KINDS:- items = self.items_for(report, kind)- assert items, f"no {kind} item recorded"- assert [i["status"] for i in items] == ["error"], kind-- def test_unreadable_config_is_left_byte_identical(- self, claude_tree, hermes_home, config_path):- """A permission problem is the other half of the same root cause."""- import os-- if os.name != "posix":- pytest.skip("chmod-based permission denial is POSIX-only")- if getattr(os, "geteuid", lambda: 1)() == 0:- pytest.skip("root bypasses file permissions")- config_path.write_text(EXISTING_CONFIG, encoding="utf-8")- before = config_path.read_bytes()- config_path.chmod(0o000)- try:- report = run_import("claude-code", claude_tree, hermes_home,- execute=True)- statuses = {- i["status"]- for kind in CONFIG_WRITING_KINDS- for i in self.items_for(report, kind)- }- assert statuses == {"error"}- finally:- config_path.chmod(0o600)- assert config_path.read_bytes() == before-- def test_non_mapping_config_is_refused(- self, claude_tree, hermes_home, config_path):- """Valid YAML that is not a mapping was also collapsed to {}."""- config_path.write_text("- just\n- a\n- list\n", encoding="utf-8")- before = config_path.read_bytes()-- report = run_import("claude-code", claude_tree, hermes_home, execute=True)-- assert config_path.read_bytes() == before- assert [i["status"] for i in self.items_for(report, "command-allowlist")] == ["error"]-- def test_dry_run_reports_the_refusal_rather_than_a_preview(- self, claude_tree, hermes_home, config_path):- """--dry-run must not promise an import that would destroy the file."""- config_path.write_text(MALFORMED_CONFIG, encoding="utf-8")-- report = run_import("claude-code", claude_tree, hermes_home, execute=False)-- for kind in CONFIG_WRITING_KINDS:- statuses = [i["status"] for i in self.items_for(report, kind)]- assert statuses == ["error"], kind- assert "imported" not in statuses-- # -- the regression that actually pins the data loss --------------------- def test_import_preserves_every_pre_existing_config_key(- self, claude_tree, hermes_home, config_path):- config_path.write_text(EXISTING_CONFIG, encoding="utf-8")-- run_import("claude-code", claude_tree, hermes_home, execute=True)-- merged = yaml.safe_load(config_path.read_text(encoding="utf-8"))- # Untouched sections survive verbatim.- assert merged["model"] == "hermes-4-405b"- assert merged["api_key_env"] == "OPENROUTER_API_KEY"- assert merged["telegram"] == {"enabled": True, "chat_id": 12345}- # Merged-into sections keep their existing members ...- assert "ls *" in merged["command_allowlist"]- assert "shutdown *" in merged["approvals"]["deny"]- assert "local-notes" in merged["mcp_servers"]- # ... alongside the imported ones.- assert "npm run build" in merged["command_allowlist"]- assert "github" in merged["mcp_servers"]-- def test_absent_config_is_still_created(- self, claude_tree, hermes_home, config_path):- """The guard must not break first-time creation."""- assert not config_path.exists()-- run_import("claude-code", claude_tree, hermes_home, execute=True)-- created = yaml.safe_load(config_path.read_text(encoding="utf-8"))- assert "npm run build" in created["command_allowlist"]-- def test_empty_config_is_treated_as_absent(- self, claude_tree, hermes_home, config_path):- config_path.write_text("", encoding="utf-8")-- run_import("claude-code", claude_tree, hermes_home, execute=True)-- created = yaml.safe_load(config_path.read_text(encoding="utf-8"))- assert "npm run build" in created["command_allowlist"]-- # -- the write itself ---------------------------------------------------- def test_config_write_is_atomic_and_leaves_no_temp_files(- self, claude_tree, hermes_home, config_path):- config_path.write_text(EXISTING_CONFIG, encoding="utf-8")-- run_import("claude-code", claude_tree, hermes_home, execute=True)-- leftovers = [p.name for p in hermes_home.glob(".tmp*")]- assert leftovers == []-- @pytest.mark.require_symlinks- def test_symlinked_config_stays_a_symlink(- self, claude_tree, hermes_home, tmp_path, config_path):- """A non-atomic ``write_text`` would follow it; ``os.replace`` would- clobber it. ``atomic_replace`` keeps the link and writes the target."""- real = tmp_path / "real-config.yaml"- real.write_text(EXISTING_CONFIG, encoding="utf-8")- config_path.symlink_to(real)-- run_import("claude-code", claude_tree, hermes_home, execute=True)-- assert config_path.is_symlink()- assert "npm run build" in real.read_text(encoding="utf-8")-- def test_failed_write_does_not_truncate_the_existing_config(- self, hermes_home, config_path, monkeypatch):- """An interrupted dump leaves the previous file complete."""- from hermes_cli import agent_import-- config_path.write_text(EXISTING_CONFIG, encoding="utf-8")- before = config_path.read_bytes()-- def boom(*_args, **_kwargs):- raise OSError("no space left on device")-- monkeypatch.setattr(agent_import, "atomic_yaml_write", boom)- with pytest.raises(OSError):- agent_import.dump_yaml_file(config_path, {"model": "replacement"})-- assert config_path.read_bytes() == before---# ----------------------------------------------------------------------------# CLI wiring-# -----------------------------------------------------------------------------class TestCliWiring:-- def test_rejects_unknown_agent(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)- with pytest.raises(SystemExit):- parser.parse_args(["import-agent", "cursor"])-- def test_command_dry_run_via_cli_writes_nothing(- self, claude_tree, hermes_home, capsys):- """End-to-end through import_agent_command with --dry-run."""- import types- from hermes_cli.agent_import import import_agent_command-- args = types.SimpleNamespace(- agent="claude-code", source=str(claude_tree), dry_run=True,- overwrite=False, yes=False)- import_agent_command(args)- assert "command-allowlist" in capsys.readouterr().out- # Baseline config.yaml/SOUL.md may be seeded by save_config() before- # the preview runs — but nothing from the IMPORT itself may land:- assert not (hermes_home / "memories" / "MEMORY.md").exists()- assert not (hermes_home / "skills" / "claude-code-imports").exists()- config_text = (hermes_home / "config.yaml").read_text(encoding="utf-8") \- if (hermes_home / "config.yaml").exists() else ""- assert "npm run build" not in config_text- assert "github" not in config_text---# ----------------------------------------------------------------------------# Sync mode (--sync): keep previously imported sources current-# -----------------------------------------------------------------------------class TestSyncManifest:- def _run_command(self, agent, source, dry_run=False, sync=False):- import types- from hermes_cli.agent_import import import_agent_command-- import_agent_command(types.SimpleNamespace(- agent=agent, source=str(source) if source else None,- dry_run=dry_run, overwrite=False, yes=True, sync=sync))-- def test_import_registers_source_and_unchanged_sync_is_noop(- self, claude_tree, hermes_home):- from hermes_cli.agent_import_sync import load_sync_manifest-- self._run_command("claude-code", claude_tree)- entry = load_sync_manifest(hermes_home)["agents"]["claude-code"]- assert entry["source"] == str(claude_tree.resolve())- assert "deploy-helper" in entry["imported_skills"] # name → digest of the copy we wrote- # A token refresh in the credential file is invisible to the digest.- (claude_tree / ".credentials.json").write_text(- json.dumps({"api_key": "rotated-token"}), encoding="utf-8")- before = snapshot_tree(hermes_home)- self._run_command(None, None, sync=True)- assert snapshot_tree(hermes_home) == before-- def test_sync_reimports_changed_source_but_never_clobbers_user_skill(- 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")- (claude_tree / "skills" / "deploy-helper" / "SKILL.md").write_text(- "---\nname: deploy-helper\n---\n\nDeploy v2.\n", encoding="utf-8")- # 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")- (claude_tree / "skills" / "hand-rolled").mkdir()- (claude_tree / "skills" / "hand-rolled" / "SKILL.md").write_text(- "---\nname: hand-rolled\n---\n\nsource content\n", encoding="utf-8")-- self._run_command(None, None, sync=True)-- imports = hermes_home / "skills" / "claude-code-imports"- assert "Freshly added sync rule" in (- hermes_home / "memories" / "MEMORY.md").read_text(encoding="utf-8")- assert "Deploy v2." in (imports / "deploy-helper" / "SKILL.md").read_text(encoding="utf-8")- assert (user_skill / "SKILL.md").read_text(encoding="utf-8") == "user content"-- # An imported skill the user then EDITED locally is no longer Hermes-owned: the next sync- # records a conflict for it instead of overwriting the edit (the docs promise this).- (imports / "deploy-helper" / "SKILL.md").write_text("my local tweaks", encoding="utf-8")- (claude_tree / "skills" / "deploy-helper" / "SKILL.md").write_text(- "---\nname: deploy-helper\n---\n\nDeploy v3.\n", encoding="utf-8")- self._run_command(None, None, sync=True)- assert (imports / "deploy-helper" / "SKILL.md").read_text(encoding="utf-8") == "my local tweaks"-- def test_sync_dry_run_previews_without_writing(self, claude_tree, hermes_home):- from hermes_cli.agent_import_sync 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)- self._run_command(None, None, sync=True, dry_run=True)- assert snapshot_tree(hermes_home) == before- assert load_sync_manifest(hermes_home)["agents"]["claude-code"]["digest"] == old_digestdiff --git a/tests/hermes_cli/test_agent_import_left_core.py b/tests/hermes_cli/test_agent_import_left_core.pynew file mode 100644index 00000000000..185315efe8f--- /dev/null+++ b/tests/hermes_cli/test_agent_import_left_core.py@@ -0,0 +1,59 @@+"""`hermes import-agent` left core for the agent-importers catalog plugin.++Real parser and real config files under a temp HERMES_HOME; the catalog lookup and the install are+stand-ins (the live install is exercised end to end outside the unit suite).+"""++from __future__ import annotations++import sys++import pytest++import hermes_cli.left_core_migration as lcm++[email protected](autouse=True)+def _fresh(monkeypatch):+ monkeypatch.setattr(lcm, "_attempted", set())+ monkeypatch.setattr(lcm, "_undelivered", {})+ import hermes_cli.memory_provider_migration as mpm+ monkeypatch.setattr(mpm, "catalog_source", lambda name: name)+++def test_old_spelling_without_the_plugin_names_the_install(tmp_path, monkeypatch, capsys):+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setattr(sys, "argv", ["hermes", "import-agent", "claude-code", "--dry-run"])+ from hermes_cli.main import _build_cli_parser++ parser, _subparsers = _build_cli_parser()+ with pytest.raises(SystemExit) as exc:+ parser.parse_args(sys.argv[1:])+ err = capsys.readouterr().err+ assert exc.value.code == 2+ assert "moved out of core into the 'agent-importers' plugin, which is not loaded" in err+ assert "hermes plugins install agent-importers" in err+++def test_only_a_home_with_registered_imports_gets_the_plugin(tmp_path):+ """A registered sync source (scheduled `--sync` runs read it) is use; a home that never imported+ is left alone: the old spelling names the install instead."""+ synced, untouched = tmp_path / "synced", tmp_path / "untouched"+ for home in (synced, untouched):+ home.mkdir()+ (home / "config.yaml").write_text("model: test\n", encoding="utf-8")+ (synced / "import-sync.json").write_text('{"version": 1, "agents": {}}', encoding="utf-8")+ calls, said = [], []++ def install(name):+ calls.append(name)+ (synced / "plugins" / name).mkdir(parents=True)+ return {"ok": True}++ assert lcm.migrate_home(untouched, install=install, say=said.append) == []+ assert calls == [] and said == []+ assert lcm.migrate_home(synced, install=install, say=said.append) == ["agent-importers"]+ assert calls == ["agent-importers"]+ assert "✓ `hermes import-agent` moved out of core" in said[0]diff --git a/tests/hermes_cli/test_profiles.py b/tests/hermes_cli/test_profiles.pyindex 740e188d21c..85d4319ff0a 100644--- a/tests/hermes_cli/test_profiles.py+++ b/tests/hermes_cli/test_profiles.py@@ -309,20 +309,18 @@ class TestCreateProfile:def test_clone_sync_imports_carries_manifest_but_never_links_profiles(self, profile_env):"""--sync-imports copies import-sync.json (a pointer at EXTERNAL agent trees) and nothingelse changes: the clone still gets its own config/skills copies, never a live link."""- from hermes_cli.agent_import_sync import SYNC_MANIFEST_NAME, load_sync_manifest-default_home = profile_env / ".hermes"(default_home / "config.yaml").write_text("model: test", encoding="utf-8")manifest = {"version": 1, "agents": {"claude-code": {"source": str(profile_env / ".claude"), "digest": "d", "overwrite": False,"last_import": 1, "imported_skills": ["s1"]}}}- (default_home / SYNC_MANIFEST_NAME).write_text(json.dumps(manifest), encoding="utf-8")+ (default_home / "import-sync.json").write_text(json.dumps(manifest), encoding="utf-8")plain = create_profile("plain", clone_config=True, no_alias=True)- assert not (plain / SYNC_MANIFEST_NAME).exists()+ assert not (plain / "import-sync.json").exists()synced = create_profile("synced", clone_config=True, sync_imports=True, no_alias=True)- assert load_sync_manifest(synced)["agents"] == manifest["agents"]+ assert json.loads((synced / "import-sync.json").read_text(encoding="utf-8")) == manifest# Editing the source afterwards does not reach the clone: still an independent island.(default_home / "config.yaml").write_text("model: changed", encoding="utf-8")assert yaml.safe_load((synced / "config.yaml").read_text(encoding="utf-8-sig"))["model"] == "test"diff --git a/tests/skills/test_openclaw_migration.py b/tests/skills/test_openclaw_migration.pyindex 4c766d39173..7fd75aea16d 100644--- a/tests/skills/test_openclaw_migration.py+++ b/tests/skills/test_openclaw_migration.py@@ -164,8 +164,7 @@ def test_unreadable_config_is_refused_not_overwritten(tmp_path: Path):``load_yaml_file`` returned ``{}`` for an absent file AND for one it couldnot parse; the config-mutating steps read, merge and write the wholemapping back, so a YAML syntax error meant every existing setting was- replaced by just the merged section. Same defect as the ported twin in- ``hermes_cli/agent_import.py``.+ replaced by just the merged section."""mod = load_module()migrator, config_path = _allowlist_migrator(diff --git a/website/docs/guides/migrate-from-openclaw.md b/website/docs/guides/migrate-from-openclaw.mdindex d59080cc876..4b08dc07f04 100644--- a/website/docs/guides/migrate-from-openclaw.md+++ b/website/docs/guides/migrate-from-openclaw.md@@ -9,7 +9,7 @@ description: "Complete guide to migrating your OpenClaw / Clawdbot setup to Herm`hermes claw migrate` imports your OpenClaw (or legacy Clawdbot/Moldbot) setup into Hermes. This guide covers exactly what gets migrated, the config key mappings, and what to verify after migration.:::note-Coming from **Claude Code** or **OpenAI Codex CLI** instead? Use [`hermes import-agent`](../user-guide/import-from-other-agents.md).+Coming from **Claude Code**, **OpenAI Codex CLI** or **Cursor** instead? Use [`hermes import-agent`](../user-guide/import-from-other-agents.md) from the `agent-importers` plugin.::::::tipdiff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.mdindex c5194bc862d..3ce3f89b97f 100644--- a/website/docs/reference/cli-commands.md+++ b/website/docs/reference/cli-commands.md@@ -103,7 +103,7 @@ The install also ships `hermes-agent`, a minimal runner that sends one query and| `hermes sessions` | Browse, export, prune, rename, and delete sessions. || `hermes insights` | Show token/cost/activity analytics. || `hermes claw` | OpenClaw migration helpers. |-| `hermes import-agent` | Import a Claude Code (`~/.claude`) or Codex CLI (`~/.codex`) setup. |+| `hermes import-agent` | Import a Claude Code, Codex CLI or Cursor setup (from the [`agent-importers`](../user-guide/import-from-other-agents.md) plugin). || `hermes dashboard` | Launch the web dashboard for managing config, API keys, and sessions. || `hermes serve` | Start the Hermes backend server (headless; powers the desktop app and remote backends). || `hermes desktop` (alias `gui`) | Build and launch the native Electron desktop app. |@@ -1858,21 +1858,13 @@ hermes claw migrate --source /home/user/old-openclaw## `hermes import-agent````bash-hermes import-agent [claude-code|codex] [options]+hermes plugins install agent-importers # once; the command comes from this official plugin+hermes import-agent [claude-code|codex|cursor] [options]```-Import a **Claude Code** (`~/.claude`) or **OpenAI Codex CLI** (`~/.codex`) setup into Hermes. Maps `CLAUDE.md`/`AGENTS.md` instructions to memory entries, `Bash(...)` permission allow/deny rules to `command_allowlist`/`approvals.deny`, MCP servers to `mcp_servers` in `config.yaml`, and skill directories into `~/.hermes/skills/`. Always previews before applying; API keys and credentials are never imported.+Import a **Claude Code** (`~/.claude`), **OpenAI Codex CLI** (`~/.codex`) or **Cursor** (`~/.cursor`) setup into Hermes: instructions and rules become memory entries, `Bash(...)` permission rules become `command_allowlist`/`approvals.deny`, MCP servers land in `mcp_servers`, and skills are copied. Always previews first; API keys and credentials are never imported. `--sync` re-imports registered sources that changed.-| Option | Description |-| --- | --- |-| `agent` | `claude-code` or `codex` (default: auto-detect). |-| `--source <path>` | Custom source directory (default: `~/.claude` or `~/.codex`). |-| `--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. |--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.+The command moved out of core into the official `agent-importers` plugin; without the plugin, `hermes import-agent` prints the install line. See the **[import guide](../user-guide/import-from-other-agents.md)** for options and mapping tables.## `hermes serve`diff --git a/website/docs/user-guide/features/mcp.md b/website/docs/user-guide/features/mcp.mdindex 27e77ef349d..b8a03dc55f5 100644--- a/website/docs/user-guide/features/mcp.md+++ b/website/docs/user-guide/features/mcp.md@@ -15,7 +15,7 @@ MCP lets Hermes Agent connect to external tool servers so the agent can use toolIf you have ever wanted Hermes to use a tool that already exists somewhere else, MCP is usually the cleanest way to do it.:::tip Coming from Claude Code?-The `mcpServers` block in your `~/.claude.json` maps to `mcp_servers` in Hermes' `config.yaml` — and `hermes import-agent claude-code` migrates it (along with skills and instructions) automatically. See [Import from Other Agents](../import-from-other-agents.md).+The `mcpServers` block in your `~/.claude.json` maps to `mcp_servers` in Hermes' `config.yaml` — and `hermes import-agent claude-code` (from the `agent-importers` plugin) migrates it, along with skills and instructions. See [Import from Other Agents](../import-from-other-agents.md).:::## What MCP gives youdiff --git a/website/docs/user-guide/import-from-other-agents.md b/website/docs/user-guide/import-from-other-agents.mdindex 2814766b9bf..6e5aee4eb84 100644--- a/website/docs/user-guide/import-from-other-agents.md+++ b/website/docs/user-guide/import-from-other-agents.md@@ -1,17 +1,24 @@---sidebar_position: 9title: "Import from Other Agents"-description: "One-command import of a Claude Code (~/.claude) or OpenAI Codex CLI (~/.codex) setup into Hermes — instructions, allowlists, MCP servers, skills, and memories."+description: "One-command import of a Claude Code (~/.claude), OpenAI Codex CLI (~/.codex) or Cursor (~/.cursor) setup into Hermes — instructions, rules, allowlists, MCP servers, skills, and memories."---# Import from Other Agents-`hermes import-agent` imports your existing **Claude Code** or **OpenAI Codex CLI** setup into Hermes with one command. It follows the same preview-first pattern as [`hermes claw migrate`](../guides/migrate-from-openclaw.md): you always see a per-item plan before anything is written, and `--dry-run` never touches disk.+`hermes import-agent` imports your existing **Claude Code**, **OpenAI Codex CLI** or **Cursor** setup into Hermes with one command. It follows the same preview-first pattern as [`hermes claw migrate`](../guides/migrate-from-openclaw.md): you always see a per-item plan before anything is written, and `--dry-run` never touches disk.++The command comes from the official **`agent-importers` plugin** from the [plugin catalog](./features/plugins.md), maintained by Nous Research in [NousResearch/hermes-official-plugins](https://github.com/NousResearch/hermes-official-plugins/tree/main/agent-importers). Install it once per profile:++```bash+hermes plugins install agent-importers+``````bash-hermes import-agent # auto-detect ~/.claude or ~/.codex+hermes import-agent # auto-detect ~/.claude, ~/.codex or ~/.cursorhermes import-agent claude-code # import from ~/.claudehermes import-agent codex # import from ~/.codex+hermes import-agent cursor # import from ~/.cursorhermes import-agent claude-code --dry-run # preview onlyhermes import-agent codex --source /path/to/.codex # custom locationhermes import-agent claude-code --overwrite --yes # replace conflicts, skip prompts@@ -41,9 +48,20 @@ Claude's `Bash(npm run test:*)` prefix rules become `npm run test*` globs. Non-`| `memories/*.md` | Memory entries in `~/.hermes/memories/MEMORY.md` || `skills/<name>/` (dirs with `SKILL.md`) | `~/.hermes/skills/codex-imports/<name>/` |+### Cursor (`~/.cursor`)++| Cursor | Hermes |+|---|---|+| `AGENTS.md` (global instructions) | Memory entries in `~/.hermes/memories/MEMORY.md` |+| `rules/*.md`, `rules/*.mdc` (User Rules) | Memory entries in `~/.hermes/memories/MEMORY.md` |+| `mcp.json` → `mcpServers` | `mcp_servers` in `config.yaml` |+| `skills/**/<name>/` (dirs with `SKILL.md`, category folders allowed) | `~/.hermes/skills/cursor-imports/<name>/` |++`.mdc` frontmatter (`description`, `globs`, `alwaysApply`) is routing metadata for Cursor's rule engine and is stripped; only the rule body is imported. A skill is the folder holding `SKILL.md`, so `skills/shipping/land-it/` imports as `cursor-imports/land-it/`; two skills with the same name in different folders are reported as a conflict.+## What is never imported-**API keys and credentials.** Credential files (`~/.claude/.credentials.json`, `~/.codex/auth.json`) are never read, and MCP server environment variables or headers with secret-looking names (`*_TOKEN`, `*_API_KEY`, `Authorization`, ...) are stripped and listed in the report so you can re-add them deliberately. Run `hermes setup` to configure providers, or add secrets to `~/.hermes/.env`.+**API keys and credentials.** Credential files (`~/.claude/.credentials.json`, `~/.codex/auth.json`, `~/.cursor/cli-config.json`) are never read, and MCP server environment variables or headers with secret-looking names (`*_TOKEN`, `*_API_KEY`, `Authorization`, ...) are stripped and listed in the report so you can re-add them deliberately. Run `hermes setup` to configure providers, or add secrets to `~/.hermes/.env`.## Behavior notes@@ -72,3 +90,10 @@ Sync is prompt-free and cheap: sources whose files are unchanged are skipped byThis mirrors ChatGPT Work's *Settings > Import* automatic updates, adapted to an explicit, inspectable command instead of a background service.The manifest is per profile. A profile created with `hermes profile create <name> --clone --sync-imports` carries it over, so `hermes -p <name> import-agent --sync` keeps pulling from the same external trees (see [Profiles](./profiles.md#keep-a-clones-imported-agent-setups-synced---sync-imports)).++## Upgrading from a version with `import-agent` built in++`hermes import-agent` used to ship inside Hermes core. The command, its flags and the `import-sync.json` manifest are unchanged in the plugin:++- **Profiles with a registered sync source** (an `import-sync.json`, which scheduled `--sync` runs read) get the plugin installed automatically by `hermes update`, or on the first start after updating (this honours `security.allow_lazy_installs`). If you later remove it (`hermes plugins remove agent-importers`), it stays removed.+- **Everyone else** installs it when they next need it: running `hermes import-agent` without the plugin prints the install command.diff --git a/website/docs/user-guide/profiles.md b/website/docs/user-guide/profiles.mdindex c816f6da495..8daaaa56cb4 100644--- a/website/docs/user-guide/profiles.md+++ b/website/docs/user-guide/profiles.md@@ -84,11 +84,11 @@ Copies your current profile's `config.yaml`, `.env`, `SOUL.md`, skills, and the#### Keep a clone's imported agent setups synced (`--sync-imports`)-If the source profile has run [`hermes import-agent`](./import-from-other-agents.md), its `import-sync.json` records which external Claude Code / Codex trees it imported. `--clone` leaves that manifest behind, so the clone gets a one-off copy of those skills and memories and stops there. Add `--sync-imports` to carry the manifest over:+If the source profile has run [`hermes import-agent`](./import-from-other-agents.md) (the `agent-importers` plugin), its `import-sync.json` records which external Claude Code / Codex / Cursor trees it imported. `--clone` leaves that manifest behind, so the clone gets a one-off copy of those skills and memories and stops there. Add `--sync-imports` to carry the manifest over:```bashhermes profile create work --clone --sync-imports-hermes -p work import-agent --sync # pulls changes from the same ~/.claude / ~/.codex+hermes -p work import-agent --sync # pulls changes from the same ~/.claude / ~/.codex / ~/.cursor```This is explicit, opt-in and one-directional, and it links the clone to the **external agent trees only** — never to the source profile. Both profiles stay independent islands: editing the source's `config.yaml`, `SOUL.md` or skills afterwards never reaches the clone. `--clone-all` copies the manifest as part of the full copy.