The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor: OpenClaw migration leaves core too; first-time setup offers the agent-importers plugin
Tekniumd7db4d109dd5
diff --git a/README.es.md b/README.es.mdindex 17ba71aa033..42bd5413f9e 100644--- a/README.es.md+++ b/README.es.md@@ -158,6 +158,7 @@ Si vienes de OpenClaw, Hermes puede importar automáticamente tu configuración,**En cualquier momento después de instalar:**```bash+hermes plugins install agent-importers # una vez: OpenClaw, Claude Code, Codex y Cursorhermes claw migrate # Migración interactiva (preset completo)hermes claw migrate --dry-run # Vista previa de qué se migraríahermes claw migrate --preset user-data # Migrar sin secretosdiff --git a/README.md b/README.mdindex 53e5cd95082..1f5cfb9b49f 100644--- a/README.md+++ b/README.md@@ -114,7 +114,6 @@ hermes config set # Set individual config valueshermes config get # Print individual config valueshermes gateway # Start the messaging gateway (Telegram, Discord, etc.)hermes setup # Run the full setup wizard (configures everything at once)-hermes claw migrate # Migrate from OpenClaw (if coming from OpenClaw)hermes update # Update to the latest versionhermes doctor # Diagnose any issues```@@ -186,33 +185,34 @@ All documentation lives at **[hermes-agent.nousresearch.com/docs](https://hermes----## Migrating from OpenClaw+## Migrating from OpenClaw or another agent-If you're coming from OpenClaw, Hermes can automatically import your settings, memories, skills, and API keys.+If you're coming from OpenClaw, Claude Code, Codex CLI or Cursor, Hermes can import your settings, memories and skills (and, for OpenClaw, API keys when you ask for them).-**During first-time setup:** The setup wizard (`hermes setup`) automatically detects `~/.openclaw` and offers to migrate before configuration begins.+**During setup:** `hermes setup` asks whether to import from another agent, pre-selects the ones it finds (`~/.openclaw`, `~/.claude`, `~/.codex`, `~/.cursor`), installs the official `agent-importers` plugin and runs the import with a preview first.**Anytime after install:**```bash-hermes claw migrate # Interactive migration (full preset)-hermes claw migrate --dry-run # Preview what would be migrated-hermes claw migrate --preset user-data # Migrate without secrets-hermes claw migrate --overwrite # Overwrite existing conflicts+hermes plugins install agent-importers # once per profile+hermes import-agent openclaw # interactive migration (full preset)+hermes import-agent openclaw --dry-run # preview what would be migrated+hermes import-agent openclaw --migrate-secrets # also bring allowlisted API keys+hermes import-agent claude-code # or codex / cursor```-What gets imported:+What gets imported from OpenClaw:- **SOUL.md** — persona file- **Memories** — MEMORY.md and USER.md entries- **Skills** — user-created skills → `~/.hermes/skills/openclaw-imports/`- **Command allowlist** — approval patterns- **Messaging settings** — platform configs, allowed users, working directory-- **API keys** — allowlisted secrets (Telegram, OpenRouter, OpenAI, Anthropic, ElevenLabs)+- **API keys** — allowlisted secrets (Telegram, OpenRouter, OpenAI, Anthropic, ElevenLabs), only with `--migrate-secrets`- **TTS assets** — workspace audio files- **Workspace instructions** — AGENTS.md (with `--workspace-target`)-See `hermes claw migrate --help` for all options, or use the `openclaw-migration` skill for an interactive agent-guided migration with dry-run previews.+`hermes claw migrate` still works as the older spelling. See the [OpenClaw migration guide](https://hermes-agent.nousresearch.com/docs/guides/migrate-from-openclaw) and [Import from Other Agents](https://hermes-agent.nousresearch.com/docs/user-guide/import-from-other-agents).---diff --git a/README.ur-pk.md b/README.ur-pk.mdindex 1cf357a1a7d..e003533115b 100644--- a/README.ur-pk.md+++ b/README.ur-pk.md@@ -187,6 +187,7 @@ hermes setup --portal<div dir="ltr">```bash+hermes plugins install agent-importers # ایک بار: OpenClaw، Claude Code، Codex اور Cursorhermes claw migrate # انٹرایکٹو مائیگریشن (مکمل پری سیٹ)hermes claw migrate --dry-run # جائزہ لیں کہ کیا کیا مائیگریٹ ہوگاhermes claw migrate --preset user-data # حساس معلومات (secrets) کے بغیر مائیگریٹ کریںdiff --git a/README.zh-CN.md b/README.zh-CN.mdindex 44c22e1ec1f..21bbe2bf598 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -144,6 +144,7 @@ Hermes 有两种入口:用 `hermes` 启动终端 UI,或运行网关从 Teleg**安装后任意时间:**```bash+hermes plugins install agent-importers # 一次即可:支持 OpenClaw、Claude Code、Codex 和 Cursorhermes claw migrate # 交互式迁移(完整预设)hermes claw migrate --dry-run # 预览将要迁移的内容hermes claw migrate --preset user-data # 仅迁移用户数据,不含密钥diff --git a/agent/onboarding.py b/agent/onboarding.pyindex a2a02219cad..97246666109 100644--- a/agent/onboarding.py+++ b/agent/onboarding.py@@ -95,7 +95,8 @@ def openclaw_residue_hint_cli() -> str:"""Banner shown the first time Hermes finds ``~/.openclaw/``: migrate first, cleanup (which breaks OpenClaw) after."""return ("A legacy OpenClaw directory was detected at ~/.openclaw/.\n"- "To port your config, memory, and skills over to Hermes, run `hermes claw migrate`.\n"+ "To port your config, memory, and skills over to Hermes, run `hermes import-agent openclaw` "+ "(from the agent-importers plugin: `hermes plugins install agent-importers`).\n""If you've already migrated and want to archive the old directory, run `hermes claw cleanup` ""(renames it to ~/.openclaw.pre-migration — OpenClaw will stop working after this).\n""This tip only shows once."diff --git a/evals/gateway/session_time_persistence_controls.py b/evals/gateway/session_time_persistence_controls.pyindex e70099d449b..30d21ac7b65 100644--- a/evals/gateway/session_time_persistence_controls.py+++ b/evals/gateway/session_time_persistence_controls.py@@ -1,6 +1,5 @@"""Isolated production-library controls; no transport/provider calls."""import contextlib-import importlib.utilimport ioimport jsonimport os@@ -98,21 +97,6 @@ assert fenced.session_id != suspended.session_idresults["historical_expiry_fence_preserved"] = Truestore._db.close()-spec = importlib.util.spec_from_file_location("migration_probe", repo / "optional-skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py")-module = importlib.util.module_from_spec(spec)-sys.modules[spec.name] = module-spec.loader.exec_module(module)-source_dir = home / "migration-source"-target = home / "migration-target"-source_dir.mkdir()-target.mkdir()-(target / "config.yaml").write_text("memory: {}\n", encoding="utf-8")-before = (target / "config.yaml").read_bytes()-migrator = module.Migrator(source_dir, target, True, None, False, False, home / "archive-output")-migrator.migrate_session_config({"session": {"reset": {"mode": "daily", "atHour": 3}, "identityLinks": {"test": "identity"}}})-assert (target / "config.yaml").read_bytes() == before-assert json.loads((migrator.archive_dir / "session-config.json").read_text(encoding="utf-8")) == {"identityLinks": {"test": "identity"}}-results["migration_timers_ignored_advanced_archived"] = Truefrom contextlib import redirect_stdoutfrom io import StringIOfrom hermes_cli.cli_info_mixin import CLIInfoMixindiff --git a/hermes_cli/backup.py b/hermes_cli/backup.pyindex 606729fc67a..d50dbee9dac 100644--- a/hermes_cli/backup.py+++ b/hermes_cli/backup.py@@ -1217,10 +1217,10 @@ def create_pre_update_backup(def create_pre_migration_backup(hermes_home: Optional[Path] = None, keep: int = _PRE_MIGRATION_DEFAULT_KEEP) -> Optional[Path]:- """Full zip backup to ``backups/pre-migration-<timestamp>.zip`` before ``hermes claw migrate``- (same dir as update backups so listings/``hermes import`` find it); ``None`` if nothing was- found, the write failed, or it was incomplete (salvage kept as ``*.incomplete.zip``). Never- raises."""+ """Full zip backup to ``backups/pre-migration-<timestamp>.zip`` before a plugin's agent import+ (``hermes import-agent openclaw``), so its name and signature are API; same dir as update backups+ so ``hermes import`` finds it. ``None`` if nothing was found, the write failed, or it was+ incomplete (salvage kept as ``*.incomplete.zip``). Never raises."""return _create_prefixed_full_backup(hermes_home, _PRE_MIGRATION_PREFIX, max(keep, 0), "pre-migration", "pre-migration backup")diff --git a/hermes_cli/claw.py b/hermes_cli/claw.pydeleted file mode 100644index 0815d7e5524..00000000000--- a/hermes_cli/claw.py+++ /dev/null@@ -1,531 +0,0 @@-"""hermes claw — OpenClaw migration commands."""--import contextlib-import importlib.util-import itertools-import logging-import subprocess-import sys-from datetime import datetime-from pathlib import Path-from types import SimpleNamespace-from typing import Callable, Optional--from hermes_cli.config import get_hermes_home, get_config_path, load_config, save_config-from hermes_constants import get_optional_skills_dir-from hermes_cli.setup import (Colors, color, print_header, print_info, print_success, print_error,- print_warning, prompt_yes_no)--logger = logging.getLogger(__name__)--PROJECT_ROOT = Path(__file__).parent.parent.resolve()--_SCRIPT_REL = Path("migration", "openclaw-migration", "scripts", "openclaw_to_hermes.py")-_OPENCLAW_SCRIPT = get_optional_skills_dir(PROJECT_ROOT / "optional-skills") / _SCRIPT_REL-# Fallback: user may have installed the skill from the Hub-_OPENCLAW_SCRIPT_INSTALLED = get_hermes_home() / "skills" / _SCRIPT_REL--# Known OpenClaw directory names (current + legacy)-_OPENCLAW_DIR_NAMES = (".openclaw", ".clawdbot", ".moltbot")-# pgrep -f ERE anchored on a node interpreter as argv[0] (``node /usr/local/bin/openclaw gateway``).-_OPENCLAW_NODE_CMDLINE_RE = r"^(\S*/)?node(js)?\s.*(openclaw|clawd)"--# `hermes claw migrate` flags/defaults. Secrets are never included implicitly: --migrate-secrets-# is required even under --preset full (OpenClaw's two-phase posture); no silent API-key import.-_MIGRATE_ARG_DEFAULTS = (- ("source", None), ("dry_run", False), ("preset", "full"), ("overwrite", False),- ("migrate_secrets", False), ("workspace_target", None), ("skill_conflict", "skip"),- ("no_backup", False), ("yes", False))--# (status, heading, color, default reason) — printed in this order after migrated items.-_REPORT_REASON_GROUPS = (- ("conflict", " ⚠ Conflicts (skipped — use --overwrite to force):", Colors.YELLOW,- "already exists"),- ("skipped", " ─ Skipped:", Colors.DIM, ""),- ("error", " ✗ Errors:", Colors.RED, "unknown error"))-# Summary-line counters after the migrated count: (summary key, label).-_SUMMARY_COUNT_LABELS = (("conflict", "conflict(s)"), ("skipped", "skipped"), ("error", "error(s)"))--# A subdir with any of these files is a workspace; the labelled subset is listed by cleanup.-_WORKSPACE_MARKERS = ("todo.json", "SOUL.md", "MEMORY.md", "USER.md")-_WORKSPACE_ITEM_LABELS = (- ("todo.json", "todo.json", Path.exists), ("sessions", "sessions/", Path.is_dir),- ("SOUL.md", "SOUL.md", Path.exists), ("MEMORY.md", "MEMORY.md", Path.exists))---def _print_banner(title: str) -> None:- """Print the magenta boxed banner shared by the claw subcommands."""- print()- rule = "─" * 57- for line in (f"┌{rule}┐", f"│ ☤ Hermes — {title:<35s}│", f"└{rule}┘"):- print(color(line, Colors.MAGENTA))---def _info(*lines: str) -> None:- """print_info each line; an empty string prints a bare blank line instead."""- for line in lines:- print_info(line) if line else print()---def _error_block(headline: str, *lines: str, debug: Optional[str] = None) -> None:- """Print a blank line, an error headline, then info lines; ``debug`` logs the traceback."""- print()- print_error(headline)- _info(*lines)- if debug:- logger.debug(debug, exc_info=True)---def _confirm(auto_yes: bool, question: str, *, default: bool, declined: str,- non_tty: Optional[tuple[str, ...]] = None) -> Optional[bool]:- """Ask to proceed unless --yes; print ``declined`` and return False on an explicit no. With- ``non_tty`` set, a non-interactive stdin prints those lines and returns None (not a refusal)."""- if auto_yes:- return True- if non_tty is not None and not sys.stdin.isatty():- _info(*non_tty)- return None- answer = prompt_yes_no(question, default=default)- if not answer:- print_info(declined)- return answer---def _warn_running(auto_yes: bool, headline: str, running: list[str], lines: tuple[str, ...],- question: str, declined: str, non_tty: Optional[tuple[str, ...]] = None):- """Print the 'still running' block (headline, `* detail` per process, advice) then _confirm."""- _error_block(headline, *(f" * {detail}" for detail in running), *lines)- print()- return _confirm(auto_yes, question, default=False, declined=declined, non_tty=non_tty)---def _detect_openclaw_processes() -> list[str]:- """Detect running OpenClaw processes and services."""- found: list[str] = []- if sys.platform == "win32":- # bounded_probe_run: plain subprocess.run(timeout=...) can hang forever on Windows when a- # conhost.exe descendant holds duplicated pipe handles — a hang is not an exception.- # See #87134.- from hermes_cli._subprocess_compat import bounded_probe_run- try:- for exe in ("openclaw.exe", "clawd.exe"):- result = bounded_probe_run(["tasklist", "/FI", f"IMAGENAME eq {exe}"], timeout=5)- if result is not None and exe in (result.stdout or "").lower():- found.append(f"process: {exe}")- # Node.js-hosted OpenClaw — tasklist doesn't show command lines, so use PowerShell.- ps_cmd = (- 'Get-CimInstance Win32_Process -Filter "Name = \'node.exe\'" | '- 'Where-Object { $_.CommandLine -match "openclaw|clawd" } | '- 'Select-Object -First 1 ProcessId')- result = bounded_probe_run(["powershell", "-NoProfile", "-Command", ps_cmd], timeout=5)- pid = (result.stdout or "").strip() if result is not None else ""- if pid:- found.append(f"node.exe process with openclaw in command line (PID {pid})")- except Exception:- pass- return found- result = _posix_probe(["systemctl", "--user", "is-active", "openclaw-gateway.service"], 5)- if result is not None and result.stdout.strip() == "active":- found.append("systemd service: openclaw-gateway.service")- # Never a bare ``pgrep -f openclaw``: it matches ANY argv containing the word (an editor on- # ~/.openclaw/config.json, ``tail -f openclaw.log``) and aborted cleanup on idle hosts (#12648).- # Mirror the Windows branch: exact binary names, plus node processes whose script mentions it.- pids: list[str] = []- # ``-x`` matches the 15-char comm: the gateway sets process.title="openclaw-gateway", which- # the kernel truncates to "openclaw-gatewa".- for probe in (["pgrep", "-x", "openclaw"], ["pgrep", "-x", "openclaw-gatewa"], ["pgrep", "-x", "clawd"],- ["pgrep", "-f", _OPENCLAW_NODE_CMDLINE_RE]):- result = _posix_probe(probe, 3)- if result is not None and result.returncode == 0:- pids.extend(result.stdout.split())- if pids:- found.append(f"openclaw process(es) (PIDs: {', '.join(dict.fromkeys(pids))})")- return found---def _posix_probe(cmd: list[str], timeout: int):- try:- return subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8',- errors='replace', timeout=timeout, check=False)- except (FileNotFoundError, subprocess.TimeoutExpired):- return None---def _warn_if_openclaw_running(auto_yes: bool) -> None:- """Warn if OpenClaw is still running: Telegram/Discord/Slack allow one session per bot token."""- running = _detect_openclaw_processes()- if running and _warn_running(- auto_yes, "OpenClaw appears to be running:", running,- ("Messaging platforms (Telegram, Discord, Slack) only allow one "- "active session per bot token. If you continue, both OpenClaw and "- "Hermes may try to use the same token, causing disconnects.",- "Recommendation: stop OpenClaw before migrating."),- "Continue anyway?", declined="Migration cancelled. Stop OpenClaw and try again.",- non_tty=("Non-interactive session — continuing to preview only.",),- ) is False:- sys.exit(0)---def _warn_if_gateway_running(auto_yes: bool) -> None:- """Warn if the HOST gateway has connected platforms for this profile (token conflicts, e.g.- Telegram 409).-- Multiplex-only: one host process serves N profiles, so a SERVED profile owns no ``gateway.pid``.- Gating on ``get_running_pid()`` made this destructive-action warning silently vanish for exactly- those profiles — the liveness ladder answers for the served case too.- """- from gateway.status import (- profile_platforms_from_multiplexer, read_runtime_status, resolve_gateway_liveness)- liveness = resolve_gateway_liveness(use_cache=False)- platforms: dict = {}- if liveness.running:- profile = None- with contextlib.suppress(Exception):- from hermes_cli.profiles import get_active_profile_name- profile = get_active_profile_name()- if liveness.source == "multiplexer" and profile and profile != "default":- # Served profile: its platforms live under `<profile>:<platform>` in the host record.- platforms = profile_platforms_from_multiplexer(liveness.runtime, profile)- else:- platforms = (liveness.runtime or read_runtime_status() or {}).get("platforms") or {}- connected = [name for name, info in platforms.items()- if isinstance(info, dict) and info.get("state") == "connected"]- if connected and _warn_running(- auto_yes, "Hermes gateway is running with active connections: " + ", ".join(connected), [],- ("Migrating bot tokens while the gateway is active will cause "- "conflicts (Telegram, Discord, and Slack only allow one active "- "session per token).",- "Recommendation: stop the host gateway first with 'hermes gateway stop'."),- "Continue anyway?", declined="Migration cancelled. Stop the gateway and try again.",- ) is False:- sys.exit(0)---def _find_migration_script() -> Path | None:- """Find the openclaw_to_hermes.py script in known locations."""- return next((c for c in (_OPENCLAW_SCRIPT, _OPENCLAW_SCRIPT_INSTALLED) if c.exists()), None)---def _load_migration_module(script_path: Path):- """Dynamically load the migration script as a module."""- spec = importlib.util.spec_from_file_location("openclaw_to_hermes", script_path)- if spec is None or spec.loader is None:- return None- # Register in sys.modules so @dataclass can resolve the module (Python 3.11+ requires this).- mod = sys.modules[spec.name] = importlib.util.module_from_spec(spec)- try:- spec.loader.exec_module(mod)- except Exception:- sys.modules.pop(spec.name, None)- raise- return mod---def _find_openclaw_dirs() -> list[Path]:- """Find all OpenClaw directories on disk."""- return [d for d in (Path.home() / name for name in _OPENCLAW_DIR_NAMES) if d.is_dir()]---def _scan_workspace_state(source_dir: Path) -> list[tuple[Path, str]]:- """List state files in an OpenClaw directory root, then in its workspace-like subdirs."""- candidates = [(source_dir / name, "Root") for name in ("todo.json", "sessions", "logs")]- try:- children = sorted(source_dir.iterdir())- except OSError:- children = []- candidates += [(child / name, "Workspace") for child in children- if child.is_dir() and not child.name.startswith(".")- for name in ("todo.json", "sessions", "logs", "memory")]- return [(p, f"{scope} {'directory' if p.is_dir() else 'file'}: "- f"{p.relative_to(source_dir).as_posix()}") for p, scope in candidates if p.exists()]---def _archive_directory(source_dir: Path, dry_run: bool = False) -> Path:- """Rename an OpenClaw directory to .pre-migration (date-stamped, then numbered, if taken)."""- base = f"{source_dir.name}.pre-migration"- stamped = f"{base}-{datetime.now().strftime('%Y%m%d')}"- names = itertools.chain((base, stamped), (f"{stamped}-{n}" for n in itertools.count(2)))- archive_path = next(p for p in (source_dir.parent / n for n in names) if not p.exists())- if not dry_run:- source_dir.rename(archive_path)- return archive_path---def claw_command(args):- """Route hermes claw subcommands."""- action = getattr(args, "claw_action", None)- if action == "migrate":- _cmd_migrate(args)- elif action in {"cleanup", "clean"}:- _cmd_cleanup(args)- else:- print("Usage: hermes claw <command> [options]\n\nCommands:\n"- " migrate Migrate settings from OpenClaw to Hermes\n"- " cleanup Archive leftover OpenClaw directories after migration\n\n"- "Run 'hermes claw <command> --help' for options.")---def _cmd_migrate(args):- """Run the OpenClaw → Hermes migration: preflight, preview, confirm, back up, apply."""- opts = SimpleNamespace(**{k: getattr(args, k, d) for k, d in _MIGRATE_ARG_DEFAULTS})- # Explicit --source, else first existing of current + legacy names; default to ~/.openclaw.- opts.source_dir = (Path(opts.source) if opts.source- else next(iter(_find_openclaw_dirs()), Path.home() / ".openclaw"))- _print_banner("OpenClaw Migration")- if not opts.source_dir.is_dir():- return _error_block(- f"OpenClaw directory not found: {opts.source_dir}",- "Make sure your OpenClaw installation is at the expected path.",- "You can specify a custom path: hermes claw migrate --source /path/to/.openclaw")- script_path = _find_migration_script()- if not script_path:- return _error_block(- "Migration script not found.", "Expected at one of:", f" {_OPENCLAW_SCRIPT}",- f" {_OPENCLAW_SCRIPT_INSTALLED}",- "Make sure the openclaw-migration skill is installed.")- opts.hermes_home = get_hermes_home()- print()- print_header("Migration Settings")- _info(f"Source: {opts.source_dir}", f"Target: {opts.hermes_home}",- f"Preset: {opts.preset}",- f"Overwrite: {'yes' if opts.overwrite else 'no (skip conflicts)'}",- f"Secrets: {'yes (allowlisted only)' if opts.migrate_secrets else 'no'}",- *([f"Skill conflicts: {opts.skill_conflict}"] if opts.skill_conflict != "skip" else []),- *([f"Workspace: {opts.workspace_target}"] if opts.workspace_target else []))- print()- # Migrating tokens while OpenClaw or the gateway is active causes conflicts (e.g. Telegram 409).- _warn_if_openclaw_running(opts.yes)- _warn_if_gateway_running(opts.yes)- # Ensure config.yaml exists before migration tries to read it- if not get_config_path().exists():- save_config(load_config())- run_migrator = _load_migrator(script_path, opts)- if run_migrator is None or not _preview_migration(run_migrator, opts):- return- print()- if _confirm(opts.yes, "Proceed with migration?", default=True, declined="Migration cancelled.",- non_tty=("Non-interactive session — preview only.",- "To execute, re-run with: hermes claw migrate --yes")):- _apply_migration(run_migrator, opts)- # Source directory is left untouched — archiving is `hermes claw cleanup`'s job.---def _load_migrator(script_path: Path, opts: SimpleNamespace) -> Optional[Callable[[bool], dict]]:- """Load the migration script; return ``run(execute) -> report`` or None (error printed)."""- try:- mod = _load_migration_module(script_path)- except Exception as e:- return _error_block(f"Could not load migration script: {e}",- debug="OpenClaw migration error")- if mod is None:- return print_error("Could not load migration script.")- selected = mod.resolve_selected_options(None, None, preset=opts.preset)- ws_target = Path(opts.workspace_target).resolve() if opts.workspace_target else None- return lambda execute: mod.Migrator(- source_root=opts.source_dir.resolve(), target_root=opts.hermes_home.resolve(),- execute=execute, workspace_target=ws_target, overwrite=opts.overwrite,- migrate_secrets=opts.migrate_secrets, output_dir=None, selected_options=selected,- preset_name=opts.preset, skill_conflict_mode=opts.skill_conflict).migrate()---def _preview_migration(run_migrator: Callable[[bool], dict], opts: SimpleNamespace) -> bool:- """Always preview first; return True only if the run should proceed to apply."""- try:- preview_report = run_migrator(False)- except Exception as e:- _error_block(f"Migration preview failed: {e}", debug="OpenClaw migration preview error")- return False- summary = preview_report.get("summary", {})- count, conflicts = summary.get("migrated", 0), summary.get("conflict", 0)- # "Nothing to migrate" means nothing migrated AND nothing blocked by conflicts. With- # conflicts, still show the plan and surface the --overwrite guidance instead of bailing.- print()- if count == 0 and conflicts == 0:- print_info("Nothing to migrate from OpenClaw.")- else:- what = (f"{count} item(s) would be imported" if count > 0- else f"{conflicts} conflict(s), nothing would be imported")- print_header(f"Migration Preview — {what}")- print_info("No changes have been made yet. Review the list below:")- _print_migration_report(preview_report, dry_run=True)- if opts.dry_run or (count == 0 and conflicts == 0):- return False- # Modelled on OpenClaw's assertConflictFreePlan(): apply is a safe no-op on conflicts unless- # the user opts in to overwriting — otherwise "yes, proceed" would silently skip every- # conflicting item.- if conflicts > 0 and not opts.overwrite:- _error_block(- f"Plan has {conflicts} conflict(s). Refusing to apply.",- "Each conflict is an item whose target already exists in ~/.hermes/. "- "Re-run with --overwrite to replace conflicting targets (item-level "- "backups are written to the migration report directory).",- "Or re-run with --dry-run to review the full plan.")- return False- return True---def _apply_migration(run_migrator: Callable[[bool], dict], opts: SimpleNamespace) -> None:- """Take a pre-migration backup (unless --no-backup), execute, and print the report. The backup- shares the pre-update backup's implementation (exclusions, SQLite safe-copy, zip) so it is- restorable with `hermes import`: one restore point before any mutation, pruned to the last 5."""- backup_archive: Optional[Path] = None- if not opts.no_backup:- try:- from hermes_cli.backup import create_pre_migration_backup- from hermes_cli.sizefmt import format_bytes as _format_size- backup_archive = create_pre_migration_backup(hermes_home=opts.hermes_home)- if backup_archive:- print()- print_success(f"Pre-migration backup: {backup_archive} "- f"({_format_size(backup_archive.stat().st_size)})")- print_info(f"Restore with: hermes import {backup_archive.name}")- else:- print()- print_warning("Pre-migration backup was not created (nothing to back up, the write "- "failed, or it was incomplete); if incomplete, a partial "- "pre-migration-*.incomplete.zip may exist in the backups dir.")- except Exception as e:- return _error_block(- f"Could not create pre-migration backup: {e}",- "Re-run with --no-backup to skip, or free up disk space under the Hermes home.",- debug="Pre-migration backup error")- try:- report = run_migrator(True)- except Exception as e:- _error_block(f"Migration failed: {e}", debug="OpenClaw migration error")- if backup_archive:- _info(f"A pre-migration backup is available at: {backup_archive}",- f"Restore with: hermes import {backup_archive.name}")- return- _print_migration_report(report, dry_run=False)---def _cmd_cleanup(args):- """Offer to rename leftover OpenClaw directories to .pre-migration to free disk space."""- dry_run, auto_yes = getattr(args, "dry_run", False), getattr(args, "yes", False)- _print_banner("OpenClaw Cleanup")- source = getattr(args, "source", None)- dirs_to_check = [Path(source)] if source else _find_openclaw_dirs()- if not dirs_to_check:- print()- return print_success("No OpenClaw directories found. Nothing to clean up.")- # Archiving while the service is active makes it recreate an empty skeleton directory.- # See #8502.- running = _detect_openclaw_processes()- if running and not _warn_running(- auto_yes, "OpenClaw appears to be still running:", running,- ("Archiving .openclaw/ while the service is active may cause it to "- "immediately recreate an empty skeleton directory, destroying your config.",- "Stop OpenClaw first: systemctl --user stop openclaw-gateway.service"),- "Proceed anyway?",- declined="Aborted. Stop OpenClaw first, then re-run: hermes claw cleanup",- non_tty=("Non-interactive session — aborting. Stop OpenClaw and re-run.",)):- return- total_archived = 0- for source_dir in dirs_to_check:- _describe_openclaw_dir(source_dir)- if dry_run:- archive_path = _archive_directory(source_dir, dry_run=True)- print_info(f"Would archive: {source_dir} → {archive_path}")- elif _confirm(auto_yes, f"Archive {source_dir}?", default=True, declined="Skipped.",- non_tty=(f"Non-interactive session — would archive: {source_dir}",- "To execute, re-run with: hermes claw cleanup --yes")):- try:- archive_path = _archive_directory(source_dir)- print_success(f"Archived: {source_dir} → {archive_path}")- total_archived += 1- except OSError as e:- print_error(f"Could not archive: {e}")- print_info(f"Try manually: mv {source_dir} {source_dir}.pre-migration")- print()- word = "directory" if (len(dirs_to_check) if dry_run else total_archived) == 1 else "directories"- if dry_run:- _info(f"Dry run complete. {len(dirs_to_check)} {word} would be archived.",- "Run without --dry-run to archive them.")- elif total_archived:- print_success(f"Cleaned up {total_archived} OpenClaw {word}.")- print_info("Directories were renamed, not deleted. You can undo by renaming them back.")- else:- print_info("No directories were archived.")---def _describe_openclaw_dir(source_dir: Path) -> None:- """Print the workspace directories (first 5) and state files (first 8) of one OpenClaw dir."""- print()- print_header(f"Found: {source_dir}")- state_files = _scan_workspace_state(source_dir)- try:- workspace_dirs = [d for d in source_dir.iterdir() if d.is_dir()- and not d.name.startswith(".")- and any((d / n).exists() for n in _WORKSPACE_MARKERS)]- except OSError:- workspace_dirs = []- if workspace_dirs:- print_info(f"Workspace directories: {len(workspace_dirs)}")- _print_rows([f"{ws.name}/ ({', '.join(_workspace_items(ws)) or 'empty'})"- for ws in workspace_dirs], 5)- if state_files:- print()- print(color(f" {len(state_files)} state file(s) found:", Colors.YELLOW))- _print_rows([desc for _path, desc in state_files], 8)- print()---def _workspace_items(ws: Path) -> list[str]:- return [lbl for n, lbl, chk in _WORKSPACE_ITEM_LABELS if chk(ws / n)]---def _print_rows(rows: list[str], shown: int) -> None:- """Print the first ``shown`` rows indented, then a '... and N more' trailer if truncated."""- for row in rows[:shown]:- print(f" {row}")- if len(rows) > shown:- print(f" ... and {len(rows) - shown} more")---def _print_migration_report(report: dict, dry_run: bool):- """Print a formatted migration report."""- summary, items = report.get("summary", {}), report.get("items", [])- migrated = summary.get("migrated", 0)- print()- print_header("Dry Run Results" if dry_run else "Migration Results")- if dry_run:- print_info("No files were modified. This is a preview of what would happen.")- print()- migrated_heading = f" ✓ {'Would migrate' if dry_run else 'Migrated'}:"- for status, heading, heading_color, default_reason in (- ("migrated", migrated_heading, Colors.GREEN, None), *_REPORT_REASON_GROUPS):- rows = []- for item in (i for i in items if i.get("status") == status):- kind, dest = item.get("kind", "unknown"), item.get("destination", "")- if default_reason is not None: # conflict / skipped / error rows show a reason- rows.append(f"{kind:<22s} {item.get('reason', default_reason)}")- else:- rows.append(f"{kind:<22s} → {str(dest).replace(str(Path.home()), '~')}" if dest- else kind)- if rows:- print(color(heading, heading_color))- _print_rows(rows, len(rows))- print()- counts = [(migrated, "would migrate" if dry_run else "migrated")] + [- (summary.get(k, 0), label) for k, label in _SUMMARY_COUNT_LABELS]- parts = [f"{count} {label}" for count, label in counts if count]- print_info(f"Summary: {', '.join(parts)}" if parts else "Nothing to migrate.")- if report.get("output_dir"):- print_info(f"Full report saved to: {report['output_dir']}")- if dry_run:- _info("", "To execute the migration, run without --dry-run:",- f" hermes claw migrate --preset {report.get('preset', 'full')}")- elif migrated:- print()- print_success("Migration complete!")- # Warn if API keys were skipped (migrate_secrets not enabled)- if any(i.get("kind") == "provider-keys" and i.get("status") == "skipped" for i in items):- print()- for line in (- " ⚠ API keys were NOT migrated (secrets migration is disabled by default).",- " Your OPENROUTER_API_KEY and other provider keys must be added manually."):- print(color(line, Colors.YELLOW))- _info("", "To migrate API keys, re-run with:",- " hermes claw migrate --migrate-secrets", "", "Or add your key manually:",- " hermes config set OPENROUTER_API_KEY sk-or-v1-...")diff --git a/hermes_cli/left_core_migration.py b/hermes_cli/left_core_migration.pyindex 2e7c000562d..9ab1147b618 100644--- a/hermes_cli/left_core_migration.py+++ b/hermes_cli/left_core_migration.py@@ -224,6 +224,9 @@ class LeftCoreFeature:# (``hermes mcp serve`` -> ``hermes mcp-serve``); :func:`moved_command_hint` points the old spelling at it.command: str = ""old_command: str = ""+ # Other top-level commands core shipped that the same plugin now registers (``hermes claw``, the+ # OpenClaw migration's spelling before ``hermes import-agent openclaw``); hinted like *cli*.+ old_cli: tuple[str, ...] = ()# Key of the bundled plugin core shipped (``observability/langfuse``). It stays an alias of the# catalog plugin in ``plugins.enabled`` / ``plugins.disabled`` (the loader's gate, an# administrator's pinned list) and for every `hermes plugins <verb>` (:func:`legacy_plugin_alias`).@@ -270,7 +273,7 @@ LEFT_CORE: tuple[LeftCoreFeature, ...] = (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",+ cli="import-agent", old_cli=("claw",),),)@@ -308,8 +311,8 @@ def legacy_plugin_keys(plugin: str) -> set[str]:def moved_command_hint(prog: str, value: str, action: str = "") -> str:"""For a command a left-core plugin took over: ``hermes auth [<action>] <cli>`` (core's old loginspelling), core's old nested spelling (``hermes mcp serve``), or the plugin's own ``hermes <cli>`` /- ``hermes <command>`` while the plugin is not loaded, the line saying where it went and how to get it- for the active home, else ``""``."""+ ``hermes <command>`` / ``hermes <old_cli>`` while the plugin is not loaded, the line saying where it+ went and how to get it for the active home, else ``""``."""from hermes_constants import get_hermes_homehome = Path(get_hermes_home())moved = next((f for f in LEFT_CORE if f.old_command and f.old_command == f"{prog} {value}"), None)@@ -321,7 +324,7 @@ def moved_command_hint(prog: str, value: str, action: str = "") -> str:if prog == "hermes auth":feature = next((f for f in LEFT_CORE if f.cli and f.cli == value), None)elif prog == "hermes":- feature = next((f for f in LEFT_CORE if value and value in (f.cli, f.command)), None)+ feature = next((f for f in LEFT_CORE if value and value in (f.cli, f.command, *f.old_cli)), None)else:feature = Noneif feature is None:@@ -335,7 +338,8 @@ def moved_command_hint(prog: str, value: str, action: str = "") -> str:old = " ".join(p for p in ("hermes auth", action, value) if p)return (f"{feature.label} moved out of core into the '{feature.plugin}' plugin: `{old}` is now "f"`hermes {value} {action or 'login'}`.{get}")- return f"{feature.label} moved out of core into the '{feature.plugin}' plugin, which is not loaded.{get}"+ label = f"`hermes {value}`" if value in feature.old_cli else feature.label+ return f"{label} moved out of core into the '{feature.plugin}' plugin, which is not loaded.{get}"def moved_plugin_hint(name: str) -> str:diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex beea0a159c6..baaea1738b7 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -389,7 +389,6 @@ from hermes_cli.subcommands.pairing import build_pairing_parserfrom hermes_cli.subcommands.plugins import build_plugins_parserfrom hermes_cli.subcommands.mcp import build_mcp_parserfrom hermes_cli.subcommands.connectors import build_connectors_parser-from hermes_cli.subcommands.claw import build_claw_parserfrom hermes_cli.subcommands.vault import build_vault_parserfrom hermes_cli.subcommands.moa import build_moa_parserfrom hermes_cli.subcommands.fallback import build_fallback_parser@@ -1842,7 +1841,6 @@ cmd_prompt_size = _forward_command("cmd_prompt_size", "hermes_cli.prompt_size",cmd_pairing = _forward_command("cmd_pairing", "hermes_cli.pairing", "pairing_command")cmd_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")def cmd_model(args):@@ -2758,7 +2756,7 @@ def cmd_console(args):# entry would let a plugin command silently fail to parse._BUILTIN_SUBCOMMANDS = frozenset({- "acp", "approvals", "auth", "backup", "bundles", "checkpoints", "claw", "codex-runtime", "completion",+ "acp", "approvals", "auth", "backup", "bundles", "checkpoints", "codex-runtime", "completion","computer-use", "connectors","config", "console", "cron", "curator", "dashboard", "serve", "debug", "doctor","dump", "egress", "fallback", "gateway", "hooks", "import", "insights",@@ -3372,7 +3370,6 @@ def _build_cli_parser():build_insights_parser(subparsers, cmd_insights=cmd_insights)build_usage_parser(subparsers)build_monitoring_parser(subparsers, cmd_monitoring=cmd_monitoring)- build_claw_parser(subparsers, cmd_claw=cmd_claw)build_vault_parser(subparsers)build_update_parser(subparsers, cmd_update=cmd_update)build_uninstall_parser(subparsers, cmd_uninstall=cmd_uninstall)diff --git a/hermes_cli/setup.py b/hermes_cli/setup.pyindex 0d2bc4cfa56..43990ff1eac 100644--- a/hermes_cli/setup.py+++ b/hermes_cli/setup.py@@ -577,7 +577,8 @@ from hermes_cli.setup_tts import setup_ttsfrom hermes_cli.setup_terminal import setup_terminal_backendfrom hermes_cli.setup_platforms import setup_gatewayfrom hermes_cli.setup_summary import _print_setup_summary-from hermes_cli.setup_migration import _offer_openclaw_migration, _skip_configured_section+from hermes_cli.setup_migration import _skip_configured_section+from hermes_cli.setup_agent_import import offer_agent_importfrom hermes_cli.setup_quick import _run_portal_one_shot, _run_quick_setup@@ -619,29 +620,30 @@ def _run_setup_section(config: dict, section: str) -> None:print_success(f"{label} configuration complete!")-def _run_full_setup(config: dict, hermes_home, *, is_existing: bool, migration_ran: bool) -> None:- """Full Setup — run all sections, honoring post-migration skips."""+def _run_full_setup(config: dict, hermes_home, *, is_existing: bool, imported_from: str = "") -> None:+ """Full Setup — run all sections; after an import (*imported_from* names the agents) each+ already-configured section offers to skip."""print_header("Configuration Location")_info(f"Config file: {get_config_path()}", f"Secrets file: {get_env_path()}",f"Data folder: {hermes_home}", f"Install dir: {PROJECT_ROOT}", None,"You can edit these files directly or use 'hermes config edit'")- if migration_ran:- _info(None, "Settings were imported from OpenClaw.",- "Each section below will show what was imported — press Enter to keep,",- "or choose to reconfigure if needed.")+ if imported_from:+ _info(None, f"Settings were imported from {imported_from}.",+ "Each section below shows what is already set up — keep it,",+ "or choose to reconfigure it.")# Agent Settings are not prompted: first installs get defaults, existing keep theirs.if not is_existing:_apply_default_agent_settings(config)def _skip(key: str, label: str) -> bool:- return migration_ran and _skip_configured_section(config, key, label)+ return bool(imported_from) and _skip_configured_section(config, key, label)def _gateway_step() -> None:if not _skip("gateway", "Messaging Platforms"):setup_gateway(config)return- # Migration does not imply consent to install a persistent service.+ # An import does not imply consent to install a persistent service.from hermes_cli.gateway_setup_service import ensure_gateway_serviceensure_gateway_service(context="setup", interactive=True, config=config)@@ -706,10 +708,10 @@ def _run_setup_wizard_impl(args):"├─────────────────────────────────────────────────────────┤","│ Let's configure your Hermes Agent installation. │","│ Press Ctrl+C at any time to exit. │")- migration_ran = False+ imported_from = ""if is_existing:# Full reconfigure wizard is the default (Enter keeps each current value); `--quick`- # narrows it to missing items (partial OpenClaw import, cleared key). --reconfigure is a+ # narrows it to missing items (partial import, cleared key). --reconfigure is a# backwards-compatible no-op here.if quick_requested:_run_setup_steps([("Quick Setup", lambda: _run_quick_setup(config, hermes_home))])@@ -726,9 +728,10 @@ def _run_setup_wizard_impl(args):print()if reconfigure_requested or quick_requested:_info("No existing configuration found — running first-time setup.", None)- migration_ran = _offer_openclaw_migration(hermes_home) # before configuration begins- if migration_ran:- config = load_config()+ # Before configuration begins. The plugin install and the import write config.yaml from+ # outside this dict (the import from another process), so reload it.+ imported_from = offer_agent_import(hermes_home)+ config = load_config()setup_mode = prompt_choice("How would you like to set up Hermes?", [label for label, _ in _FIRST_TIME_MODES], 0)label, runner = _FIRST_TIME_MODES[setup_mode]if runner is not None:@@ -736,7 +739,7 @@ def _run_setup_wizard_impl(args):_run_setup_steps([(label, lambda: getattr(setup_quick, runner)(config, hermes_home, is_existing))])_record_setup_completed(config)return- _run_full_setup(config, hermes_home, is_existing=is_existing, migration_ran=migration_ran)+ _run_full_setup(config, hermes_home, is_existing=is_existing, imported_from=imported_from)# Save and show summarysave_config(config)diff --git a/hermes_cli/setup_agent_import.py b/hermes_cli/setup_agent_import.pynew file mode 100644index 00000000000..2da8f2273d2--- /dev/null+++ b/hermes_cli/setup_agent_import.py@@ -0,0 +1,134 @@+"""First-time ``hermes setup``'s "Coming from another agent?" step (it replaces core's old OpenClaw+migration offer).++Detection is a few ``is_dir`` checks and needs nothing installed. Importing lives in the+``agent-importers`` catalog plugin (``hermes import-agent <source>``): only after the user says yes+does this step install it through the normal catalog install and run its import in a child process,+which owns the preview, the confirmation and what gets imported. Setup helpers are imported lazily+from hermes_cli.setup so test patches there apply.+"""++from __future__ import annotations++import os+import subprocess+import sys+from pathlib import Path+from typing import NamedTuple, Optional++PLUGIN = "agent-importers"+++class ImportSource(NamedTuple):+ name: str # ``hermes import-agent <name>``+ label: str+ dirs: tuple[str, ...] # dirs under ``~`` the plugin reads; the first one found wins+ extra_args: tuple[str, ...] = ()+++# The plugin's importers, with the dirs its own auto-detection checks.+IMPORT_SOURCES: tuple[ImportSource, ...] = (+ # Core's setup step migrated OpenClaw's allowlisted API keys and bot tokens after the preview, so+ # the provider and messaging sections that follow find them already set; kept.+ ImportSource("openclaw", "OpenClaw", (".openclaw", ".clawdbot", ".moltbot"), ("--migrate-secrets",)),+ ImportSource("claude-code", "Claude Code", (".claude",)),+ ImportSource("codex", "Codex CLI", (".codex",)),+ ImportSource("cursor", "Cursor", (".cursor",)),+)+++def detect_import_sources() -> list[tuple[ImportSource, Path]]:+ """The sources with a setup on this computer, each with the dir found."""+ found = []+ for source in IMPORT_SOURCES:+ home = next((p for p in (Path.home() / d for d in source.dirs) if p.is_dir()), None)+ if home is not None:+ found.append((source, home))+ return found+++def offer_agent_import(hermes_home: Path) -> str:+ """When another agent's setup is on this computer, offer to import it: pick which (when several),+ install the plugin if it is missing and run its import for each pick. Returns the labels whose+ import changed this home's config.yaml or .env (``""`` when none did). Asks nothing, and so never+ installs anything, when nothing is found or no one can answer the prompts."""+ from hermes_cli.setup import _info, is_noninteractive, print_header, print_info, prompt_yes_no+ found = [] if is_noninteractive() else detect_import_sources()+ if not found:+ return ""+ user_home = str(Path.home())+ print_header("Coming from another agent?", gap=True)+ _info("Found on this computer: " + ", ".join(+ f"{s.label} ({str(p).replace(user_home, '~', 1)})" for s, p in found) + ".",+ "Hermes can bring over its settings, memories, skills and MCP servers.",+ "You'll see a preview and confirm before anything changes.")+ names = " or ".join(s.label for s, _ in found) if len(found) <= 2 else "any of them"+ if not prompt_yes_no(f"Import your setup from {names}?", default=True):+ print_info(f"Skipped. Import later with: hermes plugins install {PLUGIN}, then hermes import-agent")+ return ""+ picked = _pick_sources(found)+ if not picked or not _ensure_plugin(hermes_home):+ return ""+ return ", ".join(s.label for s in picked if _run_import(s, hermes_home))+++def _pick_sources(found: list[tuple[ImportSource, Path]]) -> list[ImportSource]:+ """Only one found: that one (the question named it). Several: a checklist, all checked."""+ from hermes_cli.setup import print_info, prompt_checklist+ if len(found) == 1:+ return [found[0][0]]+ picked = prompt_checklist("Which agents should Hermes import from?", [s.label for s, _ in found],+ list(range(len(found))))+ if not picked:+ print_info("Nothing selected, so nothing was imported.")+ return [found[i][0] for i in picked]+++def _ensure_plugin(hermes_home: Path) -> bool:+ """The plugin installed and enabled in *hermes_home*: the catalog install (reviewed pin, the+ usual install checks) when it is missing, else just an enable."""+ from hermes_cli.left_core_migration import plugin_present+ from hermes_cli.plugins_cmd import cmd_enable+ from hermes_cli.plugins_cmd_install import cmd_install+ from hermes_cli.setup import _info, print_warning+ present = plugin_present(PLUGIN, hermes_home)+ if not present:+ _info(None, f"Importing is done by the '{PLUGIN}' plugin from the Hermes plugin catalog. "+ "Installing it now...")+ try:+ if present:+ cmd_enable(PLUGIN)+ else:+ cmd_install(PLUGIN, enable=True)+ except SystemExit: # both print their own error, then exit+ pass+ if plugin_present(PLUGIN, hermes_home):+ return True+ print_warning(f"The '{PLUGIN}' plugin could not be installed, so nothing was imported. "+ f"Try again later with: hermes plugins install {PLUGIN}")+ return False+++def _snapshot(hermes_home: Path) -> tuple[Optional[bytes], ...]:+ return tuple(p.read_bytes() if p.is_file() else None+ for p in (hermes_home / "config.yaml", hermes_home / ".env"))+++def _run_import(source: ImportSource, hermes_home: Path) -> bool:+ """``hermes import-agent <source>`` in a child process, so the freshly installed plugin's command+ is wired; it previews and asks before changing anything (and exits 0 on a no too). True when the+ run changed config.yaml or .env, which the setup sections after it read."""+ from hermes_cli.setup import print_header, print_warning+ from tools.environments.local import served_profile_child_env+ print_header(f"Importing from {source.label}", gap=True)+ before = _snapshot(hermes_home)+ argv = [sys.executable, "-m", "hermes_cli.main", "import-agent", source.name, *source.extra_args]+ env = served_profile_child_env(target_home=hermes_home)+ if os.environ.get("PYTHONPATH"): # this same interpreter running Hermes: keep the source tree+ env["PYTHONPATH"] = os.environ["PYTHONPATH"] # a checkout launched by path, which it strips+ # health: allow HX006 -- interactive child: the user reads its preview and answers its prompts+ if subprocess.run(argv, env=env, check=False).returncode:+ # An install from before the plugin gained this importer refuses the name (argparse, exit 2).+ print_warning(f"The {source.label} import did not run. If the error names an invalid choice, "+ f"update the plugin first: hermes plugins update {PLUGIN}")+ return _snapshot(hermes_home) != beforediff --git a/hermes_cli/setup_migration.py b/hermes_cli/setup_migration.pyindex f229bfb71b4..c40b64a46be 100644--- a/hermes_cli/setup_migration.py+++ b/hermes_cli/setup_migration.py@@ -1,19 +1,10 @@-"""Post-migration section-skip logic and the OpenClaw first-run migration flow (setup.py-re-exports the names it still uses; setup helpers are imported lazily so test patches apply)."""+"""Post-import section-skip logic: after ``hermes setup`` imported another agent's settings, each+section that is already configured shows its summary and offers to skip (setup.py re-exports the+names it uses; setup helpers are imported lazily so test patches apply)."""-import importlib.util-import logging-import sysfrom functools import partial-from pathlib import Pathfrom typing import Optional-from hermes_constants import get_optional_skills_dir--logger = logging.getLogger("hermes_cli.setup")--PROJECT_ROOT = Path(__file__).parent.parent.resolve()-# ── Post-Migration Section Skip Logic ──@@ -113,8 +104,8 @@ _SECTION_SUMMARIES = {def _get_section_config_summary(config: dict, section_key: str) -> Optional[str]:- """Short summary if a setup section is already configured (post-OpenClaw-migration skip- detection), else None. ``get_env_value`` is reached through hermes_cli.setup so test patches+ """Short summary if a setup section is already configured (post-import skip detection), else+ None. ``get_env_value`` is reached through hermes_cli.setup so test patcheson ``setup_mod.get_env_value`` apply."""summarize = _SECTION_SUMMARIES.get(section_key)return summarize(config) if summarize else None@@ -129,198 +120,3 @@ def _skip_configured_section(config: dict, section_key: str, label: str) -> boolprint()print_success(f" {label}: {summary}")return not prompt_yes_no(f" Reconfigure {label.lower()}?", default=False)---# ── OpenClaw Migration ──--_OPENCLAW_SCRIPT = (- get_optional_skills_dir(PROJECT_ROOT / "optional-skills")- / "migration" / "openclaw-migration" / "scripts" / "openclaw_to_hermes.py"-)---def _load_openclaw_migration_module():- """Load the openclaw_to_hermes migration script as a module; None if it can't be loaded."""- if not _OPENCLAW_SCRIPT.exists():- return None- spec = importlib.util.spec_from_file_location("openclaw_to_hermes", _OPENCLAW_SCRIPT)- if spec is None or spec.loader is None:- return None- mod = importlib.util.module_from_spec(spec)- # Registered in sys.modules so @dataclass can resolve the module (Python 3.11+ requirement).- sys.modules[spec.name] = mod- try:- spec.loader.exec_module(mod)- except Exception:- sys.modules.pop(spec.name, None)- raise- return mod---# Item kinds that warrant explicit warnings: gateway tokens/channels hijack the old agent's-# platforms; config values and instruction/context .md files may not map 1:1 to Hermes.-_HIGH_IMPACT_KIND_KEYWORDS = {- "gateway": "⚠ Gateway/messaging — this will configure Hermes to use your OpenClaw messaging channels",- "telegram": "⚠ Telegram — this will point Hermes at your OpenClaw Telegram bot",- "slack": "⚠ Slack — this will point Hermes at your OpenClaw Slack workspace",- "discord": "⚠ Discord — this will point Hermes at your OpenClaw Discord bot",- "whatsapp": "⚠ WhatsApp — this will point Hermes at your OpenClaw WhatsApp connection",- "config": "⚠ Config values — OpenClaw settings may not map 1:1 to Hermes equivalents",- "soul": "⚠ Instruction file — may contain OpenClaw-specific setup/restart procedures",- "memory": "⚠ Memory/context file — may reference OpenClaw-specific infrastructure",- "context": "⚠ Context file — may contain OpenClaw-specific instructions",-}--_MIGRATION_WARNING_NOTES = (- " Note: OpenClaw config values may have different semantics in Hermes.",- " For example, OpenClaw's tool_call_execution: \"auto\" ≠ Hermes's yolo mode.",- " Instruction files (.md) from OpenClaw may contain incompatible procedures.",-)---def _migrated_row(item: dict, kind: str) -> str:- dest = item.get("destination", "")- if dest:- return f" {kind:<22s} → {str(dest).replace(str(Path.home()), '~')}"- return f" {kind}"---def _reason_row(default_reason: str, item: dict, kind: str) -> str:- return f" {kind:<22s} {item.get('reason', default_reason)}"---def _print_migration_preview(report: dict):- """Dry-run preview grouped by status, with warnings for high-impact items (gateway takeover,- config semantics)."""- from hermes_cli.setup import color, Colors, print_info- items = report.get("items", [])- if not items:- print_info("Nothing to migrate.")- return- groups = (- ("migrated", " Would import:", Colors.GREEN, _migrated_row),- ("conflict", " Would overwrite (conflicts with existing Hermes config):", Colors.YELLOW,- partial(_reason_row, "already exists")),- ("skipped", " Would skip:", Colors.DIM, partial(_reason_row, "")),- )- warnings_shown = set()- for status, header, col, row in groups:- group = [i for i in items if i.get("status") == status]- if not group:- continue- print(color(header, col))- for item in group:- kind = item.get("kind", "unknown")- print(row(item, kind))- if status == "migrated": # collect warnings for high-impact items- kind_lower, dest_lower = kind.lower(), str(item.get("destination", "")).lower()- warnings_shown.update(- w for kw, w in _HIGH_IMPACT_KIND_KEYWORDS.items() if kw in kind_lower or kw in dest_lower)- print()- if warnings_shown:- print(color(" ── Warnings ──", Colors.YELLOW))- for warning in sorted(warnings_shown):- print(color(f" {warning}", Colors.YELLOW))- print()- for line in _MIGRATION_WARNING_NOTES:- print(color(line, Colors.YELLOW))- print()---def _run_migrator(mod, openclaw_dir: Path, hermes_home: Path, selected, *, execute: bool, overwrite: bool):- """Run a Migrator with the fixed first-time-setup options and return its report."""- return mod.Migrator(- source_root=openclaw_dir.resolve(), target_root=hermes_home.resolve(), execute=execute,- workspace_target=None, overwrite=overwrite, migrate_secrets=True, output_dir=None,- selected_options=selected, preset_name="full",- ).migrate()---_FAILED = object()---def _migration_step(label: str, log_label: str, fn):- """Run one migration phase; on failure warn ``"<label>: <exc>"``, log the trace and return- ``_FAILED`` (the caller aborts)."""- from hermes_cli.setup import print_warning- try:- return fn()- except Exception as e:- print_warning(f"{label}: {e}")- logger.debug(log_label, exc_info=True)- return _FAILED---def _offer_openclaw_migration(hermes_home: Path) -> bool:- """Detect ~/.openclaw and offer to migrate during first-time setup: dry-run preview first,- execute only after explicit confirmation. Returns True iff migration ran successfully."""- from hermes_cli.setup import (- get_config_path, _info, load_config, print_header, print_info, print_success, print_warning, prompt_yes_no,- save_config- )- openclaw_dir = Path.home() / ".openclaw"- if not openclaw_dir.is_dir() or not _OPENCLAW_SCRIPT.exists():- return False- print_header("OpenClaw Installation Detected", gap=True)- _info(f"Found OpenClaw data at {openclaw_dir}",- "Hermes can preview what would be imported before making any changes.", None)- if not prompt_yes_no("Would you like to see what can be imported?", default=True):- print_info("Skipping migration. You can run it later with: hermes claw migrate --dry-run")- return False-- # Ensure config.yaml exists before migration tries to read it- if not get_config_path().exists():- save_config(load_config())- mod = _migration_step("Could not load migration script", "OpenClaw migration module load error",- _load_openclaw_migration_module)- if mod is None:- print_warning("Could not load migration script.")- if mod is None or mod is _FAILED:- return False-- # ── Phase 1: Dry-run preview (overwrite=True shows everything, including conflicts) ──- def _preview():- selected = mod.resolve_selected_options(None, None, preset="full")- return selected, _run_migrator(mod, openclaw_dir, hermes_home, selected, execute=False, overwrite=True)-- previewed = _migration_step("Migration preview failed", "OpenClaw migration preview error", _preview)- if previewed is _FAILED:- return False- selected, preview_report = previewed- preview_count = preview_report.get("summary", {}).get("migrated", 0)- if preview_count == 0:- _info(None, "Nothing to import from OpenClaw.")- return False- print_header(f"Migration Preview — {preview_count} item(s) would be imported", gap=True)- _info("No changes have been made yet. Review the list below:", None)- _print_migration_preview(preview_report)-- # ── Phase 2: Confirm and execute ──- if not prompt_yes_no("Proceed with migration?", default=False):- _info("Migration cancelled. You can run it later with: hermes claw migrate",- "Use --dry-run to preview again, or --preset minimal for a lighter import.")- return False-- # overwrite=False so existing Hermes configs are preserved. The user saw the preview;- # conflicts are skipped by default.- report = _migration_step("Migration failed", "OpenClaw migration error", lambda: _run_migrator(- mod, openclaw_dir, hermes_home, selected, execute=True, overwrite=False))- if report is _FAILED:- return False- summary = report.get("summary", {})- print()- for key, printer, text in (- ("migrated", print_success, "Imported {n} item(s) from OpenClaw."),- ("conflict", print_info,- "Skipped {n} item(s) that already exist in Hermes (use hermes claw migrate --overwrite to force)."),- ("skipped", print_info, "Skipped {n} item(s) (not found or unchanged)."),- ("error", print_warning, "{n} item(s) had errors — check the migration report."),- ):- count = summary.get(key, 0)- if count:- printer(text.format(n=count))- output_dir = report.get("output_dir")- if output_dir:- print_info(f"Full report saved to: {output_dir}")- print_success("Migration complete! Continuing with setup...")- return Truediff --git a/hermes_cli/subcommands/claw.py b/hermes_cli/subcommands/claw.pydeleted file mode 100644index 98c2996095f..00000000000--- a/hermes_cli/subcommands/claw.py+++ /dev/null@@ -1,59 +0,0 @@-"""``hermes claw`` subcommand parser."""--from __future__ import annotations--from typing import Callable--from hermes_cli.subcommands._shared import add_yes_flag---def build_claw_parser(subparsers, *, cmd_claw: Callable) -> None:- """Attach the ``claw`` subcommand to ``subparsers``."""- claw_parser = subparsers.add_parser(- "claw", help="OpenClaw migration tools",- description="Migrate settings, memories, skills, and API keys from OpenClaw to Hermes")- claw_subparsers = claw_parser.add_subparsers(dest="claw_action")-- # claw migrate- claw_migrate = claw_subparsers.add_parser(- "migrate", help="Migrate from OpenClaw to Hermes",- description="Import settings, memories, skills, and API keys from an OpenClaw installation. "- "Always shows a preview before making changes.")- claw_migrate.add_argument("--source", help="Path to OpenClaw directory (default: ~/.openclaw)")- claw_migrate.add_argument(- "--dry-run", action="store_true",- help="Preview only — stop after showing what would be migrated")- claw_migrate.add_argument(- "--preset", choices=["user-data", "full"], default="full",- help="Migration preset (default: full). Neither preset imports secrets — "- "pass --migrate-secrets to include API keys.")- claw_migrate.add_argument(- "--overwrite", action="store_true",- help="Overwrite existing files (default: refuse to apply when the plan has conflicts)")- claw_migrate.add_argument(- "--migrate-secrets", action="store_true",- help="Include allowlisted secrets (TELEGRAM_BOT_TOKEN, API keys, etc.). "- "Required even under --preset full.")- claw_migrate.add_argument(- "--no-backup", action="store_true",- help="Skip the pre-migration zip snapshot of ~/.hermes/ (by default a "- "single restore-point archive is written to ~/.hermes/backups/ "- "before apply; restorable with 'hermes import').")- claw_migrate.add_argument(- "--workspace-target", help="Absolute path to copy workspace instructions into")- claw_migrate.add_argument(- "--skill-conflict", choices=["skip", "overwrite", "rename"], default="skip",- help="How to handle skill name conflicts (default: skip)")- add_yes_flag(claw_migrate, "Skip confirmation prompts")-- # claw cleanup- claw_cleanup = claw_subparsers.add_parser(- "cleanup", aliases=["clean"], help="Archive leftover OpenClaw directories after migration",- description="Scan for and archive leftover OpenClaw directories to prevent state fragmentation",- )- claw_cleanup.add_argument("--source", help="Path to a specific OpenClaw directory to clean up")- claw_cleanup.add_argument(- "--dry-run", action="store_true",- help="Preview what would be archived without making changes")- add_yes_flag(claw_cleanup, "Skip confirmation prompts")- claw_parser.set_defaults(func=cmd_claw)diff --git a/locales/af.yaml b/locales/af.yamlindex 8281a7abe06..a3ee8140e05 100644--- a/locales/af.yaml+++ b/locales/af.yaml@@ -3808,7 +3808,7 @@ tips:t272: "GPT-5 en Codex gebruik die 'developer'-rol in plaas van 'system' in die boodskapformaat."t273: "Hulp-oorskrywings per taak: auxiliary.vision.provider, auxiliary.compression.model, ens. in config.yaml."t274: "Die hulpkliënt behandel 'main' as 'n verskaffer-alias — dit los op na jou werklike primêre verskaffer + model."- t275: "hermes claw migrate --dry-run wys die OpenClaw-migrasie vooraf sonder om iets te skryf."+ t275: "hermes import-agent openclaw --dry-run wys die OpenClaw-migrasie vooraf sonder om iets te skryf."t276: "Lêerpaaie wat met aanhalingstekens of ontsnapte spasies geplak word, word outomaties hanteer — geen handmatige opruiming nodig nie."t277: "Slash-opdragte aktiveer nooit die groot-plak-invouing nie — /command met groot argumente werk korrek."t278: "In onderbreekmodus omseil slash-opdragte wat tydens agent-uitvoering getik word die onderbreeklogika en loop onmiddellik."diff --git a/locales/ar.yaml b/locales/ar.yamlindex 3468bb0cb3b..4c5ffb76c48 100644--- a/locales/ar.yaml+++ b/locales/ar.yaml@@ -3808,7 +3808,7 @@ tips:t272: "تستخدم نماذج GPT-5 وCodex الدور 'developer' بدلًا من 'system' في صيغة الرسائل."t273: "تجاوزات مساعدة لكل مهمة: auxiliary.vision.provider وauxiliary.compression.model وغيرها في config.yaml."t274: "يعامل العميل المساعد 'main' كاسم بديل للمزوّد — يُحلّ إلى مزوّدك الأساسي الفعلي ونموذجه."- t275: "يعرض hermes claw migrate --dry-run معاينة لترحيل OpenClaw دون كتابة أي شيء."+ t275: "يعرض hermes import-agent openclaw --dry-run معاينة لترحيل OpenClaw دون كتابة أي شيء."t276: "تُعالج مسارات الملفات الملصقة بعلامات اقتباس أو مسافات مهرّبة تلقائيًا — دون تنظيف يدوي."t277: "لا تُطلق أوامر الشرطة المائلة أبدًا طيّ اللصق الكبير — يعمل /command مع الوسائط الكبيرة بشكل صحيح."t278: "في وضع القطع، تتجاوز أوامر الشرطة المائلة المكتوبة أثناء تنفيذ الوكيل منطق القطع وتعمل فورًا."diff --git a/locales/de.yaml b/locales/de.yamlindex 0cb234f8578..802902190c6 100644--- a/locales/de.yaml+++ b/locales/de.yaml@@ -3808,7 +3808,7 @@ tips:t272: "GPT-5 und Codex verwenden im Nachrichtenformat die Rolle 'developer' statt 'system'."t273: "Hilfs-Overrides pro Aufgabe: auxiliary.vision.provider, auxiliary.compression.model usw. in config.yaml."t274: "Der Hilfs-Client behandelt 'main' als Anbieter-Alias — er wird zu Ihrem tatsächlichen Hauptanbieter + Modell aufgelöst."- t275: "hermes claw migrate --dry-run zeigt eine Vorschau der OpenClaw-Migration, ohne etwas zu schreiben."+ t275: "hermes import-agent openclaw --dry-run zeigt eine Vorschau der OpenClaw-Migration, ohne etwas zu schreiben."t276: "Eingefügte Dateipfade mit Anführungszeichen oder maskierten Leerzeichen werden automatisch verarbeitet — kein manuelles Aufräumen nötig."t277: "Slash-Befehle lösen nie das Zusammenklappen großer Einfügungen aus — /command mit großen Argumenten funktioniert korrekt."t278: "Im Unterbrechungsmodus umgehen Slash-Befehle, die während der Agentenausführung eingegeben werden, die Unterbrechungslogik und laufen sofort."diff --git a/locales/en.yaml b/locales/en.yamlindex 58899b78e16..008fae44cf6 100644--- a/locales/en.yaml+++ b/locales/en.yaml@@ -3922,7 +3922,7 @@ tips:t272: "GPT-5 and Codex use 'developer' role instead of 'system' in the message format."t273: "Per-task auxiliary overrides: auxiliary.vision.provider, auxiliary.compression.model, etc. in config.yaml."t274: "The auxiliary client treats 'main' as a provider alias — resolves to your actual primary provider + model."- t275: "hermes claw migrate --dry-run previews OpenClaw migration without writing anything."+ t275: "hermes import-agent openclaw --dry-run previews OpenClaw migration without writing anything."t276: "File paths pasted with quotes or escaped spaces are handled automatically — no manual cleanup needed."t277: "Slash commands never trigger the large-paste collapse — /command with big arguments works correctly."t278: "In interrupt mode, slash commands typed during agent execution bypass interrupt logic and run immediately."diff --git a/locales/es.yaml b/locales/es.yamlindex 044da5d956b..a0c5d84e320 100644--- a/locales/es.yaml+++ b/locales/es.yaml@@ -3808,7 +3808,7 @@ tips:t272: "GPT-5 y Codex usan el rol 'developer' en lugar de 'system' en el formato de mensajes."t273: "Anulaciones auxiliares por tarea: auxiliary.vision.provider, auxiliary.compression.model, etc. en config.yaml."t274: "El cliente auxiliar trata 'main' como alias de proveedor: se resuelve a tu proveedor y modelo principales reales."- t275: "hermes claw migrate --dry-run muestra una vista previa de la migración desde OpenClaw sin escribir nada."+ t275: "hermes import-agent openclaw --dry-run muestra una vista previa de la migración desde OpenClaw sin escribir nada."t276: "Las rutas de archivo pegadas con comillas o espacios escapados se procesan automáticamente: no hace falta limpiarlas a mano."t277: "Los comandos de barra nunca activan el colapso de pegados grandes: /command con argumentos largos funciona correctamente."t278: "En modo interrupción, los comandos de barra escritos durante la ejecución del agente omiten la lógica de interrupción y se ejecutan de inmediato."diff --git a/locales/fr.yaml b/locales/fr.yamlindex c016f349294..2a4d2d7e450 100644--- a/locales/fr.yaml+++ b/locales/fr.yaml@@ -4133,7 +4133,7 @@ tips:t272: "GPT-5 et Codex utilisent le rôle 'developer' au lieu de 'system' dans le format des messages."t273: "Surcharges auxiliaires par tâche : auxiliary.vision.provider, auxiliary.compression.model, etc. dans config.yaml."t274: "Le client auxiliaire traite 'main' comme un alias de fournisseur — il correspond à votre fournisseur et modèle principaux réels."- t275: "hermes claw migrate --dry-run prévisualise la migration OpenClaw sans rien écrire."+ t275: "hermes import-agent openclaw --dry-run prévisualise la migration OpenClaw sans rien écrire."t276: "Les chemins de fichiers collés avec des guillemets ou des espaces échappés sont gérés automatiquement — aucun nettoyage manuel nécessaire."t277: "Les commandes slash ne déclenchent jamais le repli des gros collages — /command avec de gros arguments fonctionne correctement."t278: "En mode interruption, les commandes slash saisies pendant l'exécution de l'agent contournent la logique d'interruption et s'exécutent immédiatement."diff --git a/locales/ga.yaml b/locales/ga.yamlindex 292ea98d7ba..c0058216eb0 100644--- a/locales/ga.yaml+++ b/locales/ga.yaml@@ -3808,7 +3808,7 @@ tips:t272: "Úsáideann GPT-5 agus Codex an ról 'developer' in ionad 'system' i bhformáid na dteachtaireachtaí."t273: "Sáruithe cúnta de réir taisc: auxiliary.vision.provider, auxiliary.compression.model, srl. in config.yaml."t274: "Láimhseálann an cliant cúnta 'main' mar ailias soláthraí — réitíonn sé go dtí do phríomhsholáthraí + samhail iarbhír."- t275: "Réamhthaispeánann hermes claw migrate --dry-run imirce OpenClaw gan aon rud a scríobh."+ t275: "Réamhthaispeánann hermes import-agent openclaw --dry-run imirce OpenClaw gan aon rud a scríobh."t276: "Láimhseáiltear conairí comhaid a ghreamaítear le comharthaí athfhriotail nó spásanna éalaithe go huathoibríoch — ní gá glanadh de láimh."t277: "Ní spreagann orduithe slaise cumhdach na greamála móire choíche — oibríonn /command le hargóintí móra i gceart."t278: "I mód idirbhriste, seachnaíonn orduithe slaise a chlóscríobhtar le linn rith an ghníomhaire loighic an idirbhriste agus ritheann siad ar an toirt."diff --git a/locales/hu.yaml b/locales/hu.yamlindex cda9efa151c..a8b24f8df39 100644--- a/locales/hu.yaml+++ b/locales/hu.yaml@@ -3825,7 +3825,7 @@ tips:t272: "A GPT-5 és a Codex az üzenetformátumban 'system' helyett 'developer' szerepet használ."t273: "Feladatonkénti kiegészítő felülírások: auxiliary.vision.provider, auxiliary.compression.model stb. a config.yaml-ban."t274: "A kiegészítő kliens a 'main' értéket szolgáltató-aliasként kezeli — a tényleges elsődleges szolgáltatódra és modelledre oldja fel."- t275: "A hermes claw migrate --dry-run megmutatja az OpenClaw-migráció eredményét anélkül, hogy bármit írna."+ t275: "A hermes import-agent openclaw --dry-run megmutatja az OpenClaw-migráció eredményét anélkül, hogy bármit írna."t276: "Az idézőjelekkel vagy escape-elt szóközökkel beillesztett fájlútvonalakat automatikusan kezeljük — nem kell kézzel tisztogatni."t277: "A slash-parancsok sosem váltják ki a nagy beillesztések összecsukását — a /command nagy argumentumokkal is helyesen működik."t278: "Megszakítás módban az ügynök futása közben beírt slash-parancsok megkerülik a megszakítási logikát, és azonnal lefutnak."diff --git a/locales/it.yaml b/locales/it.yamlindex 9740bc2a2d4..a7e2e8cdab0 100644--- a/locales/it.yaml+++ b/locales/it.yaml@@ -3808,7 +3808,7 @@ tips:t272: "GPT-5 e Codex usano il ruolo 'developer' invece di 'system' nel formato dei messaggi."t273: "Override ausiliari per attività: auxiliary.vision.provider, auxiliary.compression.model, ecc. in config.yaml."t274: "Il client ausiliario tratta 'main' come alias di provider — si risolve nel tuo provider primario + modello effettivi."- t275: "hermes claw migrate --dry-run mostra in anteprima la migrazione da OpenClaw senza scrivere nulla."+ t275: "hermes import-agent openclaw --dry-run mostra in anteprima la migrazione da OpenClaw senza scrivere nulla."t276: "I percorsi di file incollati con virgolette o spazi con escape vengono gestiti automaticamente — nessuna pulizia manuale."t277: "I comandi slash non attivano mai il collasso degli incolla lunghi — /command con argomenti grandi funziona correttamente."t278: "In modalità interrupt, i comandi slash digitati durante l'esecuzione dell'agente saltano la logica di interruzione e vengono eseguiti subito."diff --git a/locales/ja.yaml b/locales/ja.yamlindex 8fbe9bbb309..6a3c103c3e2 100644--- a/locales/ja.yaml+++ b/locales/ja.yaml@@ -3808,7 +3808,7 @@ tips:t272: "GPT-5 と Codex はメッセージ形式で 'system' の代わりに 'developer' ロールを使います。"t273: "タスクごとの補助モデルの上書き: config.yaml の auxiliary.vision.provider、auxiliary.compression.model など。"t274: "補助クライアントは 'main' をプロバイダーの別名として扱い、実際のプライマリプロバイダーとモデルに解決します。"- t275: "hermes claw migrate --dry-run は、何も書き込まずに OpenClaw からの移行内容をプレビューします。"+ t275: "hermes import-agent openclaw --dry-run は、何も書き込まずに OpenClaw からの移行内容をプレビューします。"t276: "引用符付きやスペースがエスケープされた状態で貼り付けたファイルパスは自動的に処理されるため、手で整える必要はありません。"t277: "スラッシュコマンドは大量貼り付けの折りたたみを引き起こしません。大きな引数を付けた /command も正しく動作します。"t278: "中断モードでは、エージェント実行中に入力したスラッシュコマンドは中断ロジックを経由せず即座に実行されます。"diff --git a/locales/ko.yaml b/locales/ko.yamlindex 8949babe11c..608f86a14d4 100644--- a/locales/ko.yaml+++ b/locales/ko.yaml@@ -3808,7 +3808,7 @@ tips:t272: "GPT-5와 Codex는 메시지 형식에서 'system' 대신 'developer' 역할을 사용해요."t273: "작업별 보조 모델 설정: config.yaml에서 auxiliary.vision.provider, auxiliary.compression.model 등을 지정할 수 있어요."t274: "보조 클라이언트는 'main'을 제공자 별칭으로 취급해요 — 실제 기본 제공자 + 모델로 해석돼요."- t275: "hermes claw migrate --dry-run은 아무것도 쓰지 않고 OpenClaw 마이그레이션 결과를 미리 보여줘요."+ t275: "hermes import-agent openclaw --dry-run은 아무것도 쓰지 않고 OpenClaw 마이그레이션 결과를 미리 보여줘요."t276: "따옴표나 이스케이프된 공백이 포함된 채로 붙여 넣은 파일 경로는 자동으로 처리돼요 — 직접 정리할 필요가 없어요."t277: "슬래시 명령은 대량 붙여넣기 접기를 절대 일으키지 않아요 — 긴 인자를 가진 /command도 정상 동작해요."t278: "인터럽트 모드에서 에이전트 실행 중 입력한 슬래시 명령은 인터럽트 로직을 건너뛰고 즉시 실행돼요."diff --git a/locales/pt.yaml b/locales/pt.yamlindex daf6d2db8b3..518610ed56e 100644--- a/locales/pt.yaml+++ b/locales/pt.yaml@@ -3808,7 +3808,7 @@ tips:t272: "GPT-5 e Codex usam o papel 'developer' em vez de 'system' no formato de mensagens."t273: "Substituições auxiliares por tarefa: auxiliary.vision.provider, auxiliary.compression.model etc. no config.yaml."t274: "O cliente auxiliar trata 'main' como alias de fornecedor — resolve para o seu fornecedor + modelo primário real."- t275: "hermes claw migrate --dry-run pré-visualiza a migração do OpenClaw sem gravar nada."+ t275: "hermes import-agent openclaw --dry-run pré-visualiza a migração do OpenClaw sem gravar nada."t276: "Caminhos de arquivo colados com aspas ou espaços escapados são tratados automaticamente — sem limpeza manual."t277: "Comandos de barra nunca acionam o recolhimento de colagens grandes — /command com argumentos extensos funciona corretamente."t278: "No modo de interrupção, comandos de barra digitados durante a execução do agente ignoram a lógica de interrupção e rodam imediatamente."diff --git a/locales/ru.yaml b/locales/ru.yamlindex 69c67e4aafb..45df961dc5c 100644--- a/locales/ru.yaml+++ b/locales/ru.yaml@@ -3808,7 +3808,7 @@ tips:t272: "GPT-5 и Codex используют в формате сообщений роль 'developer' вместо 'system'."t273: "Вспомогательные переопределения по задачам: auxiliary.vision.provider, auxiliary.compression.model и т. д. в config.yaml."t274: "Вспомогательный клиент считает 'main' псевдонимом провайдера — он разворачивается в ваш реальный основной провайдер и модель."- t275: "hermes claw migrate --dry-run показывает, как пройдёт миграция из OpenClaw, ничего не записывая."+ t275: "hermes import-agent openclaw --dry-run показывает, как пройдёт миграция из OpenClaw, ничего не записывая."t276: "Пути к файлам, вставленные с кавычками или экранированными пробелами, обрабатываются автоматически — чистить вручную не нужно."t277: "Слеш-команды никогда не сворачиваются как большая вставка — /команда с объёмными аргументами работает корректно."t278: "В режиме прерывания слеш-команды, введённые во время работы агента, обходят логику прерывания и выполняются сразу."diff --git a/locales/tr.yaml b/locales/tr.yamlindex b47f3038d75..4e4ed108311 100644--- a/locales/tr.yaml+++ b/locales/tr.yaml@@ -3808,7 +3808,7 @@ tips:t272: "GPT-5 ve Codex, mesaj biçiminde 'system' yerine 'developer' rolünü kullanır."t273: "Görev başına yardımcı geçersiz kılmalar: config.yaml içinde auxiliary.vision.provider, auxiliary.compression.model vb."t274: "Yardımcı istemci 'main' değerini bir sağlayıcı takma adı olarak ele alır — gerçek birincil sağlayıcınız + modelinize çözümlenir."- t275: "hermes claw migrate --dry-run, OpenClaw geçişini hiçbir şey yazmadan önizler."+ t275: "hermes import-agent openclaw --dry-run, OpenClaw geçişini hiçbir şey yazmadan önizler."t276: "Tırnaklı veya kaçış boşluklu yapıştırılan dosya yolları otomatik işlenir — elle temizlik gerekmez."t277: "Slash komutları büyük yapıştırma daraltmasını asla tetiklemez — büyük argümanlı /command doğru çalışır."t278: "Kesme modunda, ajan çalışırken yazılan slash komutları kesme mantığını atlar ve hemen çalışır."diff --git a/locales/uk.yaml b/locales/uk.yamlindex 8dca315b850..7c717a34196 100644--- a/locales/uk.yaml+++ b/locales/uk.yaml@@ -3808,7 +3808,7 @@ tips:t272: "GPT-5 і Codex використовують у форматі повідомлень роль 'developer' замість 'system'."t273: "Окремі допоміжні перевизначення для кожного завдання: auxiliary.vision.provider, auxiliary.compression.model тощо у config.yaml."t274: "Допоміжний клієнт трактує 'main' як псевдонім провайдера — він розгортається у ваші справжні основні провайдера та модель."- t275: "hermes claw migrate --dry-run показує попередній перегляд міграції з OpenClaw, нічого не записуючи."+ t275: "hermes import-agent openclaw --dry-run показує попередній перегляд міграції з OpenClaw, нічого не записуючи."t276: "Шляхи до файлів, вставлені з лапками або екранованими пробілами, обробляються автоматично — чистити вручну не потрібно."t277: "Слеш-команди ніколи не спричиняють згортання великої вставки — /command з великими аргументами працює коректно."t278: "У режимі переривання слеш-команди, введені під час роботи агента, оминають логіку переривання й виконуються негайно."diff --git a/locales/zh-hant.yaml b/locales/zh-hant.yamlindex 29738b46ca3..1c659f02698 100644--- a/locales/zh-hant.yaml+++ b/locales/zh-hant.yaml@@ -3808,7 +3808,7 @@ tips:t272: "GPT-5 與 Codex 在訊息格式中使用 'developer' 角色,而非 'system'。"t273: "按任務覆寫輔助設定:config.yaml 中的 auxiliary.vision.provider、auxiliary.compression.model 等。"t274: "輔助客戶端把 'main' 視為提供方別名 — 會解析為你實際使用的主要提供方與模型。"- t275: "hermes claw migrate --dry-run 可預覽 OpenClaw 遷移,而不會寫入任何內容。"+ t275: "hermes import-agent openclaw --dry-run 可預覽 OpenClaw 遷移,而不會寫入任何內容。"t276: "貼上帶有引號或跳脫空格的檔案路徑會自動處理 — 不需手動清理。"t277: "指令絕不會觸發大量貼上的收合 — 帶有大量參數的 /command 也能正常運作。"t278: "在中斷模式下,代理執行期間輸入的指令會繞過中斷邏輯並立即執行。"diff --git a/locales/zh.yaml b/locales/zh.yamlindex de3a9259b8f..7d981404211 100644--- a/locales/zh.yaml+++ b/locales/zh.yaml@@ -3808,7 +3808,7 @@ tips:t272: "GPT-5 和 Codex 在消息格式中使用 'developer' 角色,而不是 'system'。"t273: "按任务覆盖辅助设置:在 config.yaml 中设置 auxiliary.vision.provider、auxiliary.compression.model 等。"t274: "辅助客户端把 'main' 视为提供方别名——解析为你实际使用的主提供方和模型。"- t275: "hermes claw migrate --dry-run 预览 OpenClaw 迁移结果,不会写入任何内容。"+ t275: "hermes import-agent openclaw --dry-run 预览 OpenClaw 迁移结果,不会写入任何内容。"t276: "粘贴的带引号或转义空格的文件路径会被自动处理——无需手动清理。"t277: "斜杠命令永远不会触发大段粘贴折叠——带大参数的 /command 也能正常工作。"t278: "在中断模式下,代理执行期间输入的斜杠命令会绕过中断逻辑并立即执行。"diff --git a/optional-skills/migration/DESCRIPTION.md b/optional-skills/migration/DESCRIPTION.mddeleted file mode 100644index b135733921c..00000000000--- a/optional-skills/migration/DESCRIPTION.md+++ /dev/null@@ -1,2 +0,0 @@-Optional migration workflows for importing user state and customizations from-other agent systems into Hermes Agent.diff --git a/optional-skills/migration/openclaw-migration/SKILL.md b/optional-skills/migration/openclaw-migration/SKILL.mddeleted file mode 100644index 0913366c91c..00000000000--- a/optional-skills/migration/openclaw-migration/SKILL.md+++ /dev/null@@ -1,301 +0,0 @@-----name: openclaw-migration-description: Import an OpenClaw setup (memories, skills) into Hermes.-version: 1.0.0-author: Hermes Agent (Nous Research)-license: MIT-platforms: [linux, macos, windows]-metadata:- hermes:- tags: [Migration, OpenClaw, Hermes, Memory, Persona, Import]- related_skills: [hermes-agent]------# OpenClaw -> Hermes Migration--Use this skill when a user wants to move their OpenClaw setup into Hermes Agent with minimal manual cleanup.--## CLI Command--For a quick, non-interactive migration, use the built-in CLI command:--```bash-hermes claw migrate # Full interactive migration-hermes claw migrate --dry-run # Preview what would be migrated-hermes claw migrate --preset user-data # Migrate without secrets-hermes claw migrate --overwrite # Overwrite existing conflicts-hermes claw migrate --source /custom/path/.openclaw # Custom source-```--The CLI command runs the same migration script described below. Use this skill (via the agent) when you want an interactive, guided migration with dry-run previews and per-item conflict resolution.--**First-time setup:** The `hermes setup` wizard automatically detects `~/.openclaw` and offers migration before configuration begins.--## What this skill does--It uses `scripts/openclaw_to_hermes.py` to:--- import `SOUL.md` into the Hermes home directory as `SOUL.md`-- transform OpenClaw `MEMORY.md` and `USER.md` into Hermes memory entries-- merge OpenClaw command approval patterns into Hermes `command_allowlist`-- migrate Hermes-compatible messaging settings such as `TELEGRAM_ALLOWED_USERS`, and map OpenClaw workspace settings to Hermes working-directory configuration-- copy OpenClaw skills into `~/.hermes/skills/openclaw-imports/`-- optionally copy the OpenClaw workspace instructions file into a chosen Hermes workspace-- mirror compatible workspace assets such as `workspace/tts/` into `~/.hermes/tts/`-- archive non-secret docs that do not have a direct Hermes destination-- produce a structured report listing migrated items, conflicts, skipped items, and reasons--## Path resolution--The helper script lives in this skill directory at:--- `scripts/openclaw_to_hermes.py`--When this skill is installed from the Skills Hub, the normal location is:--- `~/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py`--Do not guess a shorter path like `~/.hermes/skills/openclaw-migration/...`.--Before running the helper:--1. Prefer the installed path under `~/.hermes/skills/migration/openclaw-migration/`.-2. If that path fails, inspect the installed skill directory and resolve the script relative to the installed `SKILL.md`.-3. Only use `find` as a fallback if the installed location is missing or the skill was moved manually.-4. When calling the terminal tool, do not pass `workdir: "~"`. Use an absolute directory such as the user's home directory, or omit `workdir` entirely.--With `--migrate-secrets`, it will also import a small allowlisted set of Hermes-compatible secrets, currently:--- `TELEGRAM_BOT_TOKEN`--## Default workflow--1. Inspect first with a dry run.-2. Present a simple summary of what can be migrated, what cannot be migrated, and what would be archived.-3. If the `clarify` tool is available, use it for user decisions instead of asking for a free-form prose reply.-4. If the dry run finds imported skill directory conflicts, ask how those should be handled before executing.-5. Ask the user to choose between the two supported migration modes before executing.-6. Ask for a target workspace path only if the user wants the workspace instructions file brought over.-7. Execute the migration with the matching preset and flags.-8. Summarize the results, especially:- - what was migrated- - what was archived for manual review- - what was skipped and why--## User interaction protocol--Hermes CLI supports the `clarify` tool for interactive prompts, but it is limited to:--- one choice at a time-- up to 4 predefined choices-- an automatic `Other` free-text option--It does **not** support true multi-select checkboxes in a single prompt.--For every `clarify` call:--- always include a non-empty `question`-- include `choices` only for real selectable prompts-- keep `choices` to 2-4 plain string options-- never emit placeholder or truncated options such as `...`-- never pad or stylize choices with extra whitespace-- never include fake form fields in the question such as `enter directory here`, blank lines to fill in, or underscores like `_____`-- for open-ended path questions, ask only the plain sentence; the user types in the normal CLI prompt below the panel--If a `clarify` call returns an error, inspect the error text, correct the payload, and retry once with a valid `questions` array and clean choices.--When `clarify` is available and the dry run reveals any required user decision, your **next action must be a `clarify` tool call**.-Do not end the turn with a normal assistant message such as:--- "Let me present the choices"-- "What would you like to do?"-- "Here are the options"--If a user decision is required, collect it via `clarify` before producing more prose.-If multiple unresolved decisions remain, do not insert an explanatory assistant message between them. After one `clarify` response is received, your next action should usually be the next required `clarify` call.--Treat `workspace-agents` as an unresolved decision whenever the dry run reports:--- `kind="workspace-agents"`-- `status="skipped"`-- reason containing `No workspace target was provided`--In that case, you must ask about workspace instructions before execution. Do not silently treat that as a decision to skip.--Because of that limitation, use this simplified decision flow:--1. For `SOUL.md` conflicts, use `clarify` with choices such as:- - `keep existing`- - `overwrite with backup`- - `review first`-2. If the dry run shows one or more `kind="skill"` items with `status="conflict"`, use `clarify` with choices such as:- - `keep existing skills`- - `overwrite conflicting skills with backup`- - `import conflicting skills under renamed folders`-3. For workspace instructions, use `clarify` with choices such as:- - `skip workspace instructions`- - `copy to a workspace path`- - `decide later`-4. If the user chooses to copy workspace instructions, ask a follow-up open-ended `clarify` question requesting an **absolute path**.-5. If the user chooses `skip workspace instructions` or `decide later`, proceed without `--workspace-target`.-5. For migration mode, use `clarify` with these 3 choices:- - `user-data only`- - `full compatible migration`- - `cancel`-6. `user-data only` means: migrate user data and compatible config, but do **not** import allowlisted secrets.-7. `full compatible migration` means: migrate the same compatible user data plus the allowlisted secrets when present.-8. If `clarify` is not available, ask the same question in normal text, but still constrain the answer to `user-data only`, `full compatible migration`, or `cancel`.--Execution gate:--- Do not execute while a `workspace-agents` skip caused by `No workspace target was provided` remains unresolved.-- The only valid ways to resolve it are:- - user explicitly chooses `skip workspace instructions`- - user explicitly chooses `decide later`- - user provides a workspace path after choosing `copy to a workspace path`-- Absence of a workspace target in the dry run is not itself permission to execute.-- Do not execute while any required `clarify` decision remains unresolved.--Use these exact `clarify` payload shapes as the default pattern:--- `{"question":"Your existing SOUL.md conflicts with the imported one. What should I do?","choices":["keep existing","overwrite with backup","review first"]}`-- `{"question":"One or more imported OpenClaw skills already exist in Hermes. How should I handle those skill conflicts?","choices":["keep existing skills","overwrite conflicting skills with backup","import conflicting skills under renamed folders"]}`-- `{"question":"Choose migration mode: migrate only user data, or run the full compatible migration including allowlisted secrets?","choices":["user-data only","full compatible migration","cancel"]}`-- `{"question":"Do you want to copy the OpenClaw workspace instructions file into a Hermes workspace?","choices":["skip workspace instructions","copy to a workspace path","decide later"]}`-- `{"question":"Please provide an absolute path where the workspace instructions should be copied."}`--## Decision-to-command mapping--Map user decisions to command flags exactly:--- If the user chooses `keep existing` for `SOUL.md`, do **not** add `--overwrite`.-- If the user chooses `overwrite with backup`, add `--overwrite`.-- If the user chooses `review first`, stop before execution and review the relevant files.-- If the user chooses `keep existing skills`, add `--skill-conflict skip`.-- If the user chooses `overwrite conflicting skills with backup`, add `--skill-conflict overwrite`.-- If the user chooses `import conflicting skills under renamed folders`, add `--skill-conflict rename`.-- If the user chooses `user-data only`, execute with `--preset user-data` and do **not** add `--migrate-secrets`.-- If the user chooses `full compatible migration`, execute with `--preset full --migrate-secrets`.-- Only add `--workspace-target` if the user explicitly provided an absolute workspace path.-- If the user chooses `skip workspace instructions` or `decide later`, do not add `--workspace-target`.--Before executing, restate the exact command plan in plain language and make sure it matches the user's choices.--## Post-run reporting rules--After execution, treat the script's JSON output as the source of truth.--1. Base all counts on `report.summary`.-2. Only list an item under "Successfully Migrated" if its `status` is exactly `migrated`.-3. Do not claim a conflict was resolved unless the report shows that item as `migrated`.-4. Do not say `SOUL.md` was overwritten unless the report item for `kind="soul"` has `status="migrated"`.-5. If `report.summary.conflict > 0`, include a conflict section instead of silently implying success.-6. If counts and listed items disagree, fix the list to match the report before responding.-7. Include the `output_dir` path from the report when available so the user can inspect `report.json`, `summary.md`, backups, and archived files.-8. For memory or user-profile overflow, do not say the entries were archived unless the report explicitly shows an archive path. If `details.overflow_file` exists, say the full overflow list was exported there.-9. If a skill was imported under a renamed folder, report the final destination and mention `details.renamed_from`.-10. If `report.skill_conflict_mode` is present, use it as the source of truth for the selected imported-skill conflict policy.-11. If an item has `status="skipped"`, do not describe it as overwritten, backed up, migrated, or resolved.-12. If `kind="soul"` has `status="skipped"` with reason `Target already matches source`, say it was left unchanged and do not mention a backup.-13. If a renamed imported skill has an empty `details.backup`, do not imply the existing Hermes skill was renamed or backed up. Say only that the imported copy was placed in the new destination and reference `details.renamed_from` as the pre-existing folder that remained in place.--## Migration presets--Prefer these two presets in normal use:--- `user-data`-- `full`--`user-data` includes:--- `soul`-- `workspace-agents`-- `memory`-- `user-profile`-- `messaging-settings`-- `command-allowlist`-- `skills`-- `tts-assets`-- `archive`--`full` includes everything in `user-data` plus:--- `secret-settings`--The helper script still supports category-level `--include` / `--exclude`, but treat that as an advanced fallback rather than the default UX.--## Commands--Run the helper with Hermes' Python environment, which includes `ruamel.yaml`.-For a standalone Python environment, install `ruamel.yaml==0.18.17` first.--Dry run with full discovery:--```bash-python ~/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py-```--When using the terminal tool, prefer an absolute invocation pattern such as:--```json-{"command":"python /home/USER/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py","workdir":"/home/USER"}-```--Dry run with the user-data preset:--```bash-python ~/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py --preset user-data-```--Execute a user-data migration:--```bash-python ~/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py --execute --preset user-data --skill-conflict skip-```--Execute a full compatible migration:--```bash-python ~/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py --execute --preset full --migrate-secrets --skill-conflict skip-```--Execute with workspace instructions included:--```bash-python ~/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py --execute --preset user-data --skill-conflict rename --workspace-target "/absolute/workspace/path"-```--Do not use `$PWD` or the home directory as the workspace target by default. Ask for an explicit workspace path first.--## Important rules--1. Run a dry run before writing unless the user explicitly says to proceed immediately.-2. Do not migrate secrets by default. Tokens, auth blobs, device credentials, and raw gateway config should stay out of Hermes unless the user explicitly asks for secret migration.-3. Do not silently overwrite non-empty Hermes targets unless the user explicitly wants that. The helper script will preserve backups when overwriting is enabled.-4. Always give the user the skipped-items report. That report is part of the migration, not an optional extra.-5. Prefer the primary OpenClaw workspace (`~/.openclaw/workspace/`) over `workspace.default/`. Only use the default workspace as fallback when the primary files are missing.-6. Even in secret-migration mode, only migrate secrets with a clean Hermes destination. Unsupported auth blobs must still be reported as skipped.-7. If the dry run shows a large asset copy, a conflicting `SOUL.md`, or overflowed memory entries, call those out separately before execution.-8. Default to `user-data only` if the user is unsure.-9. Only include `workspace-agents` when the user has explicitly provided a destination workspace path.-10. Treat category-level `--include` / `--exclude` as an advanced escape hatch, not the normal flow.-11. Do not end the dry-run summary with a vague “What would you like to do?” if `clarify` is available. Use structured follow-up prompts instead.-12. Do not use an open-ended `clarify` prompt when a real choice prompt would work. Prefer selectable choices first, then free text only for absolute paths or file review requests.-13. After a dry run, never stop after summarizing if there is still an unresolved decision. Use `clarify` immediately for the highest-priority blocking decision.-14. Priority order for follow-up questions:- - `SOUL.md` conflict- - imported skill conflicts- - migration mode- - workspace instructions destination-15. Do not promise to present choices later in the same message. Present them by actually calling `clarify`.-16. After the migration-mode answer, explicitly check whether `workspace-agents` is still unresolved. If it is, your next action must be the workspace-instructions `clarify` call.-17. After any `clarify` answer, if another required decision remains, do not narrate what was just decided. Ask the next required question immediately.--## Expected result--After a successful run, the user should have:--- Hermes persona state imported-- Hermes memory files populated with converted OpenClaw knowledge-- OpenClaw skills available under `~/.hermes/skills/openclaw-imports/`-- a migration report showing any conflicts, omissions, or unsupported datadiff --git a/optional-skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py b/optional-skills/migration/openclaw-migration/scripts/openclaw_to_hermes.pydeleted file mode 100644index 8cc95793820..00000000000--- a/optional-skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py+++ /dev/null@@ -1,3253 +0,0 @@-#!/usr/bin/env python3-"""OpenClaw -> Hermes migration helper.--This script migrates the parts of an OpenClaw user footprint that map cleanly-into Hermes Agent, archives selected unmapped docs for manual review, and-reports exactly what was skipped and why.-"""--from __future__ import annotations--import argparse-import errno-import hashlib-import json-import os-import re-import shutil-import tempfile-from dataclasses import asdict, dataclass, field-from datetime import datetime-from pathlib import Path-from typing import Any, Dict, List, Optional, Sequence, Tuple--try:- from ruamel import yaml-except Exception: # pragma: no cover - handled at runtime- yaml = None---ENTRY_DELIMITER = "\n§\n"-DEFAULT_MEMORY_CHAR_LIMIT = 2200-DEFAULT_USER_CHAR_LIMIT = 1375-SKILL_CATEGORY_DIRNAME = "openclaw-imports"-SKILL_CATEGORY_DESCRIPTION = (- "Skills migrated from an OpenClaw workspace."-)-SKILL_CONFLICT_MODES = {"skip", "overwrite", "rename"}-SUPPORTED_SECRET_TARGETS={- "TELEGRAM_BOT_TOKEN",- "OPENROUTER_API_KEY",- "OPENAI_API_KEY",- "ANTHROPIC_API_KEY",- "ELEVENLABS_API_KEY",- "VOICE_TOOLS_OPENAI_KEY",-}-WORKSPACE_INSTRUCTIONS_FILENAME = "AGENTS" + ".md"-MIGRATION_OPTION_METADATA: dict[str, dict[str, str]] = {- "soul": {- "label": "SOUL.md",- "description": "Import the OpenClaw persona file into Hermes.",- },- "workspace-agents": {- "label": "Workspace instructions",- "description": "Copy the OpenClaw workspace instructions file into a chosen workspace.",- },- "memory": {- "label": "MEMORY.md",- "description": "Import long-term memory entries into Hermes memories.",- },- "user-profile": {- "label": "USER.md",- "description": "Import user profile entries into Hermes memories.",- },- "messaging-settings": {- "label": "Messaging settings",- "description": "Import Hermes-compatible messaging settings such as allowlists and working directory.",- },- "secret-settings": {- "label": "Allowlisted secrets",- "description": "Import the small allowlist of Hermes-compatible secrets when explicitly enabled.",- },- "command-allowlist": {- "label": "Command allowlist",- "description": "Merge OpenClaw exec approval patterns into Hermes command_allowlist.",- },- "skills": {- "label": "User skills",- "description": "Copy OpenClaw skills into ~/.hermes/skills/openclaw-imports/.",- },- "tts-assets": {- "label": "TTS assets",- "description": "Copy compatible workspace TTS assets into ~/.hermes/tts/.",- },- "discord-settings": {- "label": "Discord settings",- "description": "Import Discord bot token and allowlist into Hermes .env.",- },- "slack-settings": {- "label": "Slack settings",- "description": "Import Slack bot/app tokens and allowlist into Hermes .env.",- },- "whatsapp-settings": {- "label": "WhatsApp settings",- "description": "Import WhatsApp allowlist into Hermes .env.",- },- "signal-settings": {- "label": "Signal settings",- "description": "Import Signal account, HTTP URL, and allowlist into Hermes .env.",- },- "provider-keys": {- "label": "Provider API keys",- "description": "Import model provider API keys into Hermes .env (requires --migrate-secrets).",- },- "model-config": {- "label": "Default model",- "description": "Import the default model setting into Hermes config.yaml.",- },- "tts-config": {- "label": "TTS configuration",- "description": "Import TTS provider and voice settings into Hermes config.yaml.",- },- "shared-skills": {- "label": "Shared skills",- "description": "Copy shared OpenClaw skills from ~/.openclaw/skills/ into Hermes.",- },- "daily-memory": {- "label": "Daily memory files",- "description": "Merge daily memory entries from workspace/memory/ into Hermes MEMORY.md.",- },- "archive": {- "label": "Archive unmapped docs",- "description": "Archive compatible-but-unmapped docs for later manual review.",- },- "mcp-servers": {- "label": "MCP servers",- "description": "Import MCP server definitions from OpenClaw into Hermes config.yaml.",- },- "plugins-config": {- "label": "Plugins configuration",- "description": "Archive OpenClaw plugin configuration and installed extensions for manual review.",- },- "cron-jobs": {- "label": "Cron / scheduled tasks",- "description": "Import cron job definitions. Archive for manual recreation via 'hermes cron'.",- },- "hooks-config": {- "label": "Hooks and webhooks",- "description": "Archive OpenClaw hook configuration (internal hooks, webhooks, Gmail integration).",- },- "agent-config": {- "label": "Agent defaults and multi-agent setup",- "description": "Import agent defaults (compaction, context, thinking) into Hermes config. Archive multi-agent list.",- },- "gateway-config": {- "label": "Gateway configuration",- "description": "Import gateway port and auth settings. Archive full gateway config for manual setup.",- },- "session-config": {- "label": "Session configuration",- "description": "Archive advanced session settings; automatic reset timers are not imported.",- },- "full-providers": {- "label": "Full model provider definitions",- "description": "Import custom model providers (baseUrl, apiType, headers) into Hermes custom_providers.",- },- "deep-channels": {- "label": "Deep channel configuration",- "description": "Import extended channel settings (Matrix, Mattermost, IRC, group configs). Archive complex settings.",- },- "browser-config": {- "label": "Browser configuration",- "description": "Import browser automation settings into Hermes config.yaml.",- },- "tools-config": {- "label": "Tools configuration",- "description": "Import tool settings (exec timeout, sandbox, web search) into Hermes config.yaml.",- },- "approvals-config": {- "label": "Approval rules",- "description": "Import approval mode and rules into Hermes config.yaml approvals section.",- },- "memory-backend": {- "label": "Memory backend configuration",- "description": "Archive OpenClaw memory backend settings (QMD, vector search, citations) for manual review.",- },- "skills-config": {- "label": "Skills registry configuration",- "description": "Archive per-skill enabled/config/env settings from OpenClaw skills.entries.",- },- "ui-identity": {- "label": "UI and identity settings",- "description": "Archive OpenClaw UI theme, assistant identity, and display preferences.",- },- "logging-config": {- "label": "Logging and diagnostics",- "description": "Archive OpenClaw logging and diagnostics configuration.",- },-}-MIGRATION_PRESETS: dict[str, set[str]] = {- "user-data": {- "soul",- "workspace-agents",- "memory",- "user-profile",- "messaging-settings",- "command-allowlist",- "skills",- "tts-assets",- "discord-settings",- "slack-settings",- "whatsapp-settings",- "signal-settings",- "model-config",- "tts-config",- "shared-skills",- "daily-memory",- "archive",- "mcp-servers",- "agent-config",- "session-config",- "browser-config",- "tools-config",- "approvals-config",- "deep-channels",- "full-providers",- "plugins-config",- "cron-jobs",- "hooks-config",- "memory-backend",- "skills-config",- "ui-identity",- "logging-config",- "gateway-config",- },- "full": set(MIGRATION_OPTION_METADATA),-}---# ───────────────────────────────────────────────────────────────────────-# Item shape constants — kept stable for downstream consumers of report.json.-# Inspired by OpenClaw's src/plugin-sdk/migration.ts so both sides speak the-# same vocabulary. Values intentionally match the strings already produced-# by this script (migrated/archived/skipped/conflict/error) so the addition-# is backward-compatible.-# ───────────────────────────────────────────────────────────────────────-STATUS_MIGRATED = "migrated"-STATUS_ARCHIVED = "archived"-STATUS_SKIPPED = "skipped"-STATUS_CONFLICT = "conflict"-STATUS_ERROR = "error"-STATUS_PLANNED = "planned"--REASON_TARGET_EXISTS = "Target exists and overwrite is disabled"-REASON_BLOCKED_BY_APPLY_CONFLICT = "blocked by earlier apply conflict"---@dataclass-class ItemResult:- kind: str- source: Optional[str]- destination: Optional[str]- status: str- reason: str = ""- details: dict[str, Any] = field(default_factory=dict)- sensitive: bool = False---def parse_selection_values(values: Optional[Sequence[str]]) -> list[str]:- parsed: list[str] = []- for value in values or ():- for part in str(value).split(","):- part = part.strip().lower()- if part:- parsed.append(part)- return parsed---def resolve_selected_options(- include: Optional[Sequence[str]] = None,- exclude: Optional[Sequence[str]] = None,- preset: Optional[str] = None,-) -> set[str]:- include_values = parse_selection_values(include)- exclude_values = parse_selection_values(exclude)- valid = set(MIGRATION_OPTION_METADATA)- preset_name = (preset or "").strip().lower()-- if preset_name and preset_name not in MIGRATION_PRESETS:- raise ValueError(- "Unknown migration preset: "- + preset_name- + ". Valid presets: "- + ", ".join(sorted(MIGRATION_PRESETS))- )-- unknown = (set(include_values) - {"all"} - valid) | (set(exclude_values) - {"all"} - valid)- if unknown:- raise ValueError(- "Unknown migration option(s): "- + ", ".join(sorted(unknown))- + ". Valid options: "- + ", ".join(sorted(valid))- )-- if preset_name:- selected = set(MIGRATION_PRESETS[preset_name])- elif not include_values or "all" in include_values:- selected = set(valid)- else:- selected = set(include_values)-- if "all" in exclude_values:- selected.clear()- selected -= (set(exclude_values) - {"all"})- return selected---def sha256_file(path: Path) -> str:- h = hashlib.sha256()- with path.open("rb") as fh:- for chunk in iter(lambda: fh.read(65536), b""):- h.update(chunk)- return h.hexdigest()---def read_text(path: Path) -> str:- return path.read_text(encoding="utf-8", errors="replace")---def normalize_text(text: str) -> str:- return re.sub(r"\s+", " ", text.strip())---def ensure_parent(path: Path) -> None:- path.parent.mkdir(parents=True, exist_ok=True)---def resolve_secret_input(value: Any, env: Optional[dict[str, str]] = None) -> Optional[str]:- """Resolve an OpenClaw SecretInput value to a plain string.-- SecretInput can be:- - A plain string: "sk-..."- - An env template: "${OPENROUTER_API_KEY}"- - A SecretRef object: {"source": "env", "id": "OPENROUTER_API_KEY"}- """- if isinstance(value, str):- # Check for env template: "${VAR_NAME}"- m = re.match(r"^\$\{(\w+)\}$", value.strip())- if m and env:- return env.get(m.group(1), "").strip() or None- return value.strip() or None- if isinstance(value, dict):- source = value.get("source", "")- ref_id = value.get("id", "")- if source == "env" and ref_id and env:- return env.get(ref_id, "").strip() or None- # File/exec sources can't be resolved here — return None- return None---class ConfigReadError(RuntimeError):- """An existing config file is present but cannot be read or parsed.-- Signals that a read-modify-write round trip must be abandoned: the caller- has no idea what the file holds, so writing a merged result back would- replace real settings with only the keys it merged.- """---def load_yaml_file(path: Path) -> dict[str, Any]:- """Load a YAML mapping, distinguishing "absent" from "unreadable".-- Every config.yaml caller here reads the file, merges a section into it and- writes the whole mapping straight back. Collapsing a present-but-unreadable- file to ``{}`` therefore destroys it: a YAML syntax error, a permission- problem or a broken mount would make the migration replace every setting- the user had with only the section it merged, and still report ``migrated``.-- - Absent, or present but empty -> ``{}``; first-time creation still works.- - Present but unreadable, unparseable, or not a mapping -> raise- :class:`ConfigReadError` so the caller refuses and leaves the file- byte-identical.-- ``yaml is None`` (ruamel.yaml not installed) still yields ``{}``: nothing can be- written in that state either, since :func:`dump_yaml_file` raises.- """- if yaml is None or not path.exists():- return {}- try:- # errors="replace" means read_text() cannot raise UnicodeDecodeError;- # OSError covers races like the file disappearing or being unreadable.- raw = path.read_text(encoding="utf-8", errors="replace")- except OSError as exc:- raise ConfigReadError(- f"Refusing to overwrite {path}: the existing file cannot be read "- f"({exc}). Fix the file permissions or move it aside first."- ) from exc- try:- reader = yaml.YAML(typ="safe")- reader.version = (1, 1) # Match Hermes' existing config scalar semantics.- data = reader.load(raw)- except yaml.YAMLError as exc:- raise ConfigReadError(- f"Refusing to overwrite {path}: the existing file is not valid YAML "- f"({exc}). Fix it with `hermes config edit` (or move it aside), then "- f"re-run the migration."- ) from exc- # An empty file parses to None — a legitimate state with nothing to lose.- if data is None:- return {}- if not isinstance(data, dict):- raise ConfigReadError(- f"Refusing to overwrite {path}: expected the existing file to hold a "- f"YAML mapping but found {type(data).__name__}. Fix it with "- f"`hermes config edit` (or move it aside), then re-run the migration."- )- return data---def dump_yaml_file(path: Path, data: dict[str, Any]) -> None:- """Write ``data`` as YAML via temp file + fsync + atomic rename.-- Only ever reached after :func:`load_yaml_file` has successfully read the- same path, so the mapping being written is the real file's content plus the- merged section — never a silently-empty stand-in. Writing atomically means- an interrupted migration cannot leave a truncated config.yaml behind.-- Inlined rather than importing ``utils.atomic_write_text``: this script is- standalone and runs with only the stdlib on its path. The symlink and- cross-device handling mirrors ``utils.atomic_replace``: a plain- ``os.replace`` onto a symlinked config.yaml would replace the *link* with a- regular file, silently detaching managed deployments that symlink- ``~/.hermes/config.yaml`` into a dotfiles repo or profile package.- """- if yaml is None:- raise RuntimeError("ruamel.yaml is required to update Hermes config.yaml")- ensure_parent(path)- target = os.path.realpath(str(path)) if os.path.islink(str(path)) else str(path)- fd, tmp_path = tempfile.mkstemp(- dir=os.path.dirname(target) or ".", prefix=".tmp_", suffix=".yaml"- )- try:- with os.fdopen(fd, "w", encoding="utf-8") as handle:- # The C emitter leaves YAML 1.1 boolean-like strings unquoted.- writer = yaml.YAML(typ="safe", pure=True)- writer.version = (1, 1)- writer.default_flow_style = False- writer.sort_base_mapping_type_on_output = False- writer.allow_unicode = False- writer.dump(data, handle)- handle.flush()- os.fsync(handle.fileno())- try:- os.replace(tmp_path, target)- except OSError as exc:- # Cross-device or bind-mount deployments cannot rename into place.- if exc.errno not in (errno.EXDEV, errno.EBUSY):- raise- shutil.copyfile(tmp_path, target)- try:- shutil.copystat(tmp_path, target)- except OSError:- pass- # fsync the copied target so the durability claim holds on the- # cross-device path too (mirrors utils.atomic_replace, including- # its swallow — a failed fsync must not report the already-copied- # write as failed).- try:- target_fd = os.open(target, os.O_RDONLY)- try:- os.fsync(target_fd)- finally:- os.close(target_fd)- except OSError:- pass- os.unlink(tmp_path)- except BaseException:- try:- os.unlink(tmp_path)- except OSError:- pass- raise---def parse_env_file(path: Path) -> dict[str, str]:- if not path.exists():- return {}- data: dict[str, str] = {}- try:- # errors="replace" means read_text() cannot raise UnicodeDecodeError;- # OSError covers races like the file disappearing or being unreadable.- lines = path.read_text(encoding="utf-8", errors="replace").splitlines()- except OSError:- return {}- for raw_line in lines:- line = raw_line.strip()- if not line or line.startswith("#") or "=" not in line:- continue- key, _, value = line.partition("=")- data[key.strip()] = value.strip()- return data---def save_env_file(path: Path, data: dict[str, str]) -> None:- ensure_parent(path)- lines = [f"{key}={value}" for key, value in data.items()]- path.write_text("\n".join(lines) + ("\n" if lines else ""), encoding="utf-8")---def backup_existing(path: Path, backup_root: Path) -> Optional[Path]:- if not path.exists():- return None- rel = Path(*path.parts[1:]) if path.is_absolute() and len(path.parts) > 1 else path- dest = backup_root / rel- ensure_parent(dest)- if path.is_dir():- shutil.copytree(path, dest, dirs_exist_ok=True)- else:- shutil.copy2(path, dest)- return dest---# ── Brand rewriting ─────────────────────────────────────────-# Replace OpenClaw brand names with Hermes in migrated text so that-# memory entries, user profiles, SOUL.md, and workspace instructions-# read as self-referential to the new agent identity.-#-# Case-preserving: ``OpenClaw`` → ``Hermes`` (prose), but lowercase matches-# like ``openclaw`` → ``hermes`` (so filesystem paths like ``~/.openclaw``-# become ``~/.hermes`` — the real Hermes home — not the broken ``~/.Hermes``).-_REBRAND_PATTERNS: list[tuple[re.Pattern, str]] = [- (re.compile(r'\bOpen[\s-]?Claw\b', re.IGNORECASE), 'Hermes'),- (re.compile(r'\bClawdBot\b', re.IGNORECASE), 'Hermes'),- (re.compile(r'\bMoltBot\b', re.IGNORECASE), 'Hermes'),-]---def _case_preserving_replacement(replacement: str):- """Return a re.sub replacement fn that lowercases the result when the- matched text was all-lowercase.-- Keeps ``OpenClaw`` → ``Hermes`` but maps ``openclaw`` → ``hermes`` so a- filesystem path like ``~/.openclaw/config.yaml`` rewrites to- ``~/.hermes/config.yaml`` (the real Hermes home) instead of the broken- ``~/.Hermes/config.yaml``.- """- def _sub(match: re.Match[str]) -> str:- matched = match.group(0)- if matched and matched.islower():- return replacement.lower()- return replacement- return _sub---def rebrand_text(text: str) -> str:- """Replace OpenClaw / ClawdBot / MoltBot brand names with Hermes.-- Preserves case so filesystem-path matches (lowercase) don't become- capitalized directory names that don't exist.- """- for pattern, replacement in _REBRAND_PATTERNS:- text = pattern.sub(_case_preserving_replacement(replacement), text)- return text---def parse_existing_memory_entries(path: Path) -> list[str]:- """Parse a DESTINATION Hermes memory store (memories/MEMORY.md, USER.md).-- Splits on ``ENTRY_DELIMITER`` only, matching ``MemoryStore._parse_entries``- in ``tools/memory_tool.py``: a store with no delimiter is ONE intact entry.- Do NOT fall back to :func:`extract_markdown_entries` — it is the *source*- parser (workspace/MEMORY.md and friends), it drops fenced code blocks and- table rows and splits a block into one entry per bullet, and the merged- result is written back over the destination.- """- if not path.exists():- return []- raw = read_text(path)- if not raw.strip():- return []- return [e.strip() for e in raw.split(ENTRY_DELIMITER) if e.strip()]---def extract_markdown_entries(text: str) -> list[str]:- entries: list[str] = []- headings: list[str] = []- paragraph_lines: list[str] = []-- def context_prefix() -> str:- filtered = [h for h in headings if h and not re.search(r"\b(MEMORY|USER|SOUL|AGENTS|TOOLS|IDENTITY)\.md\b", h, re.IGNORECASE)]- return " > ".join(filtered)-- def flush_paragraph() -> None:- nonlocal paragraph_lines- if not paragraph_lines:- return- text_block = " ".join(line.strip() for line in paragraph_lines).strip()- paragraph_lines = []- if not text_block:- return- prefix = context_prefix()- if prefix:- entries.append(f"{prefix}: {text_block}")- else:- entries.append(text_block)-- in_code_block = False- for raw_line in text.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()- level = len(heading_match.group(1))- text_value = heading_match.group(2).strip()- while len(headings) >= level:- headings.pop()- headings.append(text_value)- continue-- bullet_match = re.match(r"^\s*(?:[-*]|\d+\.)\s+(.*\S)\s*$", line)- if bullet_match:- flush_paragraph()- content = bullet_match.group(1).strip()- prefix = context_prefix()- entries.append(f"{prefix}: {content}" if prefix else content)- continue-- if not stripped:- flush_paragraph()- continue-- if stripped.startswith("|") and stripped.endswith("|"):- flush_paragraph()- continue-- paragraph_lines.append(stripped)-- flush_paragraph()-- deduped: list[str] = []- seen = set()- for entry in entries:- normalized = normalize_text(entry)- if not normalized or normalized in seen:- continue- seen.add(normalized)- deduped.append(entry.strip())- return deduped---def merge_entries(- existing: Sequence[str],- incoming: Sequence[str],- limit: int,-) -> tuple[list[str], dict[str, int], list[str]]:- merged = list(existing)- seen = {normalize_text(entry) for entry in existing if entry.strip()}- stats = {"existing": len(existing), "added": 0, "duplicates": 0, "overflowed": 0}- overflowed: list[str] = []-- current_len = len(ENTRY_DELIMITER.join(merged)) if merged else 0-- 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- overflowed.append(entry)- continue-- merged.append(entry)- seen.add(normalized)- current_len = candidate_len- stats["added"] += 1-- return merged, stats, overflowed---def relative_label(path: Path, root: Path) -> str:- try:- return str(path.relative_to(root))- except ValueError:- return str(path)---# ───────────────────────────────────────────────────────────────────────-# Secret redaction for migration reports.-#-# The report JSON persists to disk inside the migration output directory and-# frequently ends up in bug reports or support channels. Anything that looks-# like a credential — by key name or by value shape — is replaced with-# "[redacted]" before the report is written.-#-# Modelled on OpenClaw's src/plugin-sdk/migration.ts so both migration tools-# redact consistently. Pure function — safe to call on any plain-data dict.-# ───────────────────────────────────────────────────────────────────────-REDACTED_MIGRATION_VALUE = "[redacted]"--_SECRET_KEY_MARKERS = (- "accesstoken",- "apikey",- "authorization",- "bearertoken",- "clientsecret",- "cookie",- "credential",- "password",- "privatekey",- "refreshtoken",- "secret",-)--_SECRET_VALUE_PATTERNS = (- re.compile(r"\bBearer\s+[A-Za-z0-9._~+/=\-]+"),- re.compile(r"\bsk-[A-Za-z0-9_\-]{8,}\b"),- re.compile(r"\bgh[pousr]_[A-Za-z0-9_]{16,}\b"),- re.compile(r"\bxox[abprs]-[A-Za-z0-9\-]{8,}\b"),- re.compile(r"\bAIza[0-9A-Za-z_\-]{12,}\b"),-)---def _normalize_secret_key(key: str) -> str:- return re.sub(r"[^a-z0-9]", "", key.lower())---def _is_secret_key(key: str) -> bool:- normalized = _normalize_secret_key(key)- if normalized == "token" or normalized.endswith("token"):- return True- if normalized in {"auth", "authorization"}:- return True- return any(marker in normalized for marker in _SECRET_KEY_MARKERS)---def _redact_string(value: str) -> str:- for pattern in _SECRET_VALUE_PATTERNS:- value = pattern.sub(REDACTED_MIGRATION_VALUE, value)- return value---def redact_migration_value(value: Any) -> Any:- """Return a deep copy of ``value`` with secret-looking content replaced.-- Applied to every report written to disk. Keys whose normalized form- matches a credential marker get their value replaced wholesale. Strings- anywhere in the tree are scanned for common token patterns (sk-..., ghp_...,- xox*-, AIza*, Bearer ...) and those substrings are replaced inline.- """- return _redact_internal(value, set())---def _redact_internal(value: Any, seen: set) -> Any:- if isinstance(value, str):- return _redact_string(value)- if isinstance(value, (list, tuple)):- return [_redact_internal(entry, seen) for entry in value]- if isinstance(value, dict):- obj_id = id(value)- if obj_id in seen:- return REDACTED_MIGRATION_VALUE- seen.add(obj_id)- out: dict[str, Any] = {}- for key, entry in value.items():- if isinstance(key, str) and _is_secret_key(key):- out[key] = REDACTED_MIGRATION_VALUE- else:- out[key] = _redact_internal(entry, seen)- return out- return value---def write_report(output_dir: Path, report: dict[str, Any]) -> None:- output_dir.mkdir(parents=True, exist_ok=True)- # Always redact before persisting. Callers who need the raw object- # (in-process) still get it back from build_report(); only the on-disk- # copy is redacted.- redacted = redact_migration_value(report)- (output_dir / "report.json").write_text(- json.dumps(redacted, indent=2, ensure_ascii=False) + "\n",- encoding="utf-8",- )-- grouped: dict[str, list[dict[str, Any]]] = {}- for item in redacted["items"]:- grouped.setdefault(item["status"], []).append(item)-- lines = [- "# OpenClaw -> Hermes Migration Report",- "",- f"- Timestamp: {redacted['timestamp']}",- f"- Mode: {redacted['mode']}",- f"- Source: `{redacted['source_root']}`",- f"- Target: `{redacted['target_root']}`",- "",- "## Summary",- "",- ]-- for key, value in redacted["summary"].items():- lines.append(f"- {key}: {value}")-- warnings = redacted.get("warnings") or []- if warnings:- lines.extend(["", "## Warnings", ""])- for warning in warnings:- lines.append(f"- {warning}")-- lines.extend(["", "## What Was Not Fully Brought Over", ""])- skipped = grouped.get("skipped", []) + grouped.get("conflict", []) + grouped.get("error", [])- if not skipped:- lines.append("- Nothing. All discovered items were either migrated or archived.")- else:- for item in skipped:- source = item["source"] or "(n/a)"- dest = item["destination"] or "(n/a)"- reason = item["reason"] or item["status"]- lines.append(f"- `{source}` -> `{dest}`: {reason}")-- next_steps = redacted.get("next_steps") or []- if next_steps:- lines.extend(["", "## Next Steps", ""])- for step in next_steps:- lines.append(f"- {step}")-- (output_dir / "summary.md").write_text("\n".join(lines) + "\n", encoding="utf-8")---class Migrator:- def __init__(- self,- source_root: Path,- target_root: Path,- execute: bool,- workspace_target: Optional[Path],- overwrite: bool,- migrate_secrets: bool,- output_dir: Optional[Path],- selected_options: Optional[set[str]] = None,- preset_name: str = "",- skill_conflict_mode: str = "skip",- ):- self.source_root = source_root- self.target_root = target_root- self.execute = execute- self.workspace_target = workspace_target- self.overwrite = overwrite- self.migrate_secrets = migrate_secrets- self.selected_options = set(selected_options or MIGRATION_OPTION_METADATA.keys())- self.preset_name = preset_name.strip().lower()- self.skill_conflict_mode = skill_conflict_mode.strip().lower() or "skip"- self.timestamp = datetime.now().strftime("%Y%m%dT%H%M%S")- self.output_dir = output_dir or (- target_root / "migration" / "openclaw" / self.timestamp if execute else None- )- self.archive_dir = self.output_dir / "archive" if self.output_dir else None- self.backup_dir = self.output_dir / "backups" if self.output_dir else None- self.overflow_dir = self.output_dir / "overflow" if self.output_dir else None- self.items: list[ItemResult] = []- # Once a config.yaml write hits conflict/error mid-run, later- # config.yaml writes are deliberately short-circuited to avoid- # leaving config in a partially-written state. Modelled on- # OpenClaw's extensions/migrate-hermes/apply.ts "blocked by earlier- # apply conflict" sequencing.- self._config_apply_blocked: bool = False-- # Resolve the configured workspace directory from openclaw.json.- # Many users (especially those who started before the OpenClaw rebrand)- # have a custom workspace path (e.g. ~/clawd/) that differs from the- # default ~/.openclaw/workspace/. Reading agents.defaults.workspace- # lets source_candidate() find files in the actual workspace.- self._custom_workspace: Optional[Path] = None- oc_config = self.load_openclaw_config()- ws = (oc_config.get("agents", {}).get("defaults", {}).get("workspace") or "").strip()- if ws:- ws_path = Path(ws).expanduser().resolve()- # Only use it if it exists and is outside the source_root tree- # (otherwise the standard relative-path logic already covers it).- if ws_path.is_dir():- try:- ws_path.relative_to(self.source_root)- except ValueError:- # ws_path is outside source_root — use it as custom workspace- self._custom_workspace = ws_path-- # Read-only probe for the memory limits, during construction — nothing- # is written from here, so an unreadable config just falls back to the- # defaults. Every path that WRITES config.yaml refuses separately (see- # run_if_selected), so this cannot become a silent overwrite.- try:- config = load_yaml_file(self.target_root / "config.yaml")- except ConfigReadError:- config = {}- mem_cfg = config.get("memory", {}) if isinstance(config.get("memory"), dict) else {}- self.memory_limit = int(mem_cfg.get("memory_char_limit", DEFAULT_MEMORY_CHAR_LIMIT))- self.user_limit = int(mem_cfg.get("user_char_limit", DEFAULT_USER_CHAR_LIMIT))-- if self.skill_conflict_mode not in SKILL_CONFLICT_MODES:- raise ValueError(- "Unknown skill conflict mode: "- + self.skill_conflict_mode- + ". Valid modes: "- + ", ".join(sorted(SKILL_CONFLICT_MODES))- )-- def is_selected(self, option_id: str) -> bool:- return option_id in self.selected_options-- # Option ids that mutate the Hermes config.yaml file. Once any one of- # them records a conflict/error on config.yaml, subsequent ones are- # short-circuited to avoid partial writes. Keep in sync with methods- # that call load_yaml_file(target_root / "config.yaml") + dump_yaml_file.- _CONFIG_MUTATING_OPTIONS = frozenset({- "model-config",- "tts-config",- "mcp-servers",- "plugins-config",- "cron-jobs",- "hooks-config",- "agent-config",- "gateway-config",- "full-providers",- "deep-channels",- "browser-config",- "tools-config",- "approvals-config",- "memory-backend",- "skills-config",- "ui-identity",- "logging-config",- "command-allowlist",- })-- def record(- self,- kind: str,- source: Optional[Path],- destination: Optional[Path],- status: str,- reason: str = "",- **details: Any,- ) -> None:- sensitive = bool(details.pop("sensitive", False))- self.items.append(- ItemResult(- kind=kind,- source=str(source) if source else None,- destination=str(destination) if destination else None,- status=status,- reason=reason,- details=details,- sensitive=sensitive,- )- )- # Flip the config-block flag when a conflict/error occurs on a- # config.yaml write. Later config-mutating options will skip rather- # than attempting a partial write.- if status in {STATUS_CONFLICT, STATUS_ERROR} and destination is not None:- dest_str = str(destination)- if dest_str.endswith("config.yaml") or dest_str.endswith("config.yml"):- self._config_apply_blocked = True-- def source_candidate(self, *relative_paths: str) -> Optional[Path]:- for rel in relative_paths:- candidate = self.source_root / rel- if candidate.exists():- return candidate- # OpenClaw renamed workspace/ to workspace-main/ (and workspace-{agentId}- # for multi-agent). Try the new path as a fallback.- if rel.startswith("workspace/"):- suffix = rel[len("workspace/"):]- for variant in ("workspace-main", "workspace-assistant"):- alt = self.source_root / variant / suffix- if alt.exists():- return alt- elif rel.startswith("workspace.default/"):- suffix = rel[len("workspace.default/"):]- alt = self.source_root / "workspace-main" / suffix- if alt.exists():- return alt-- # Final fallback: check the configured workspace directory from- # agents.defaults.workspace in openclaw.json. Users who started- # before the OpenClaw rebrand (when the project was named clawd /- # clawdbot) often have a custom workspace path outside ~/.openclaw/.- if self._custom_workspace:- for rel in relative_paths:- # Strip the leading "workspace/" or "workspace.default/"- # prefix to get the bare filename/subpath.- for prefix in ("workspace/", "workspace.default/"):- if rel.startswith(prefix):- suffix = rel[len(prefix):]- alt = self._custom_workspace / suffix- if alt.exists():- return alt- break-- return None-- def resolve_skill_destination(self, destination: Path) -> Path:- if self.skill_conflict_mode != "rename" or not destination.exists():- return destination-- suffix = "-imported"- candidate = destination.with_name(destination.name + suffix)- counter = 2- while candidate.exists():- candidate = destination.with_name(f"{destination.name}{suffix}-{counter}")- counter += 1- return candidate-- def migrate(self) -> dict[str, Any]:- if not self.source_root.exists():- self.record("source", self.source_root, None, "error", "OpenClaw directory does not exist")- return self.build_report()-- config = self.load_openclaw_config()-- self.run_if_selected("soul", self.migrate_soul)- self.run_if_selected("workspace-agents", self.migrate_workspace_agents)- self.run_if_selected(- "memory",- lambda: self.migrate_memory(- self.source_candidate("workspace/MEMORY.md", "workspace.default/MEMORY.md"),- self.target_root / "memories" / "MEMORY.md",- self.memory_limit,- kind="memory",- ),- )- self.run_if_selected(- "user-profile",- lambda: self.migrate_memory(- self.source_candidate("workspace/USER.md", "workspace.default/USER.md"),- self.target_root / "memories" / "USER.md",- self.user_limit,- kind="user-profile",- ),- )- self.run_if_selected("messaging-settings", lambda: self.migrate_messaging_settings(config))- self.run_if_selected("secret-settings", lambda: self.handle_secret_settings(config))- self.run_if_selected("discord-settings", lambda: self.migrate_discord_settings(config))- self.run_if_selected("slack-settings", lambda: self.migrate_slack_settings(config))- self.run_if_selected("whatsapp-settings", lambda: self.migrate_whatsapp_settings(config))- self.run_if_selected("signal-settings", lambda: self.migrate_signal_settings(config))- self.run_if_selected("provider-keys", lambda: self.handle_provider_keys(config))- self.run_if_selected("model-config", lambda: self.migrate_model_config(config))- self.run_if_selected("tts-config", lambda: self.migrate_tts_config(config))- self.run_if_selected("command-allowlist", self.migrate_command_allowlist)- self.run_if_selected("skills", self.migrate_skills)- self.run_if_selected("shared-skills", self.migrate_shared_skills)- self.run_if_selected("daily-memory", self.migrate_daily_memory)- self.run_if_selected(- "tts-assets",- lambda: self.copy_tree_non_destructive(- self.source_candidate("workspace/tts"),- self.target_root / "tts",- kind="tts-assets",- ignore_dir_names={".venv", "generated", "__pycache__"},- ),- )- self.run_if_selected("archive", self.archive_docs)-- # ── v2 migration modules ──────────────────────────────- self.run_if_selected("mcp-servers", lambda: self.migrate_mcp_servers(config))- self.run_if_selected("plugins-config", lambda: self.migrate_plugins_config(config))- self.run_if_selected("cron-jobs", lambda: self.migrate_cron_jobs(config))- self.run_if_selected("hooks-config", lambda: self.migrate_hooks_config(config))- self.run_if_selected("agent-config", lambda: self.migrate_agent_config(config))- self.run_if_selected("gateway-config", lambda: self.migrate_gateway_config(config))- self.run_if_selected("session-config", lambda: self.migrate_session_config(config))- self.run_if_selected("full-providers", lambda: self.migrate_full_providers(config))- self.run_if_selected("deep-channels", lambda: self.migrate_deep_channels(config))- self.run_if_selected("browser-config", lambda: self.migrate_browser_config(config))- self.run_if_selected("tools-config", lambda: self.migrate_tools_config(config))- self.run_if_selected("approvals-config", lambda: self.migrate_approvals_config(config))- self.run_if_selected("memory-backend", lambda: self.migrate_memory_backend(config))- self.run_if_selected("skills-config", lambda: self.migrate_skills_config(config))- self.run_if_selected("ui-identity", lambda: self.migrate_ui_identity(config))- self.run_if_selected("logging-config", lambda: self.migrate_logging_config(config))-- # Generate migration notes- self.generate_migration_notes()-- return self.build_report()-- def run_if_selected(self, option_id: str, func) -> None:- if not self.is_selected(option_id):- meta = MIGRATION_OPTION_METADATA[option_id]- self.record(option_id, None, None, "skipped", "Not selected for this run", option_label=meta["label"])- return- # If a previous config.yaml write hit a conflict/error during apply,- # skip remaining config-mutating options rather than risk a partial- # write. Dry-run mode never blocks — the user needs the full preview- # to decide how to proceed (re-run with --overwrite, etc.).- if (- self.execute- and self._config_apply_blocked- and option_id in self._CONFIG_MUTATING_OPTIONS- ):- meta = MIGRATION_OPTION_METADATA[option_id]- self.record(- option_id,- None,- None,- STATUS_SKIPPED,- REASON_BLOCKED_BY_APPLY_CONFLICT,- option_label=meta["label"],- )- return- try:- func()- except ConfigReadError as exc:- # The destination config.yaml is present but unreadable, so this- # step cannot merge into it. Record the refusal against the- # config path — record() then flips _config_apply_blocked, and the- # remaining config-mutating options short-circuit above instead of- # each rediscovering the same unreadable file. The file itself is- # left byte-identical.- meta = MIGRATION_OPTION_METADATA[option_id]- self.record(- option_id,- None,- self.target_root / "config.yaml",- STATUS_ERROR,- str(exc),- option_label=meta["label"],- )-- def build_report(self) -> dict[str, Any]:- summary: dict[str, int] = {- "migrated": 0,- "archived": 0,- "skipped": 0,- "conflict": 0,- "error": 0,- }- for item in self.items:- summary[item.status] = summary.get(item.status, 0) + 1-- report = {- "timestamp": self.timestamp,- "mode": "execute" if self.execute else "dry-run",- "source_root": str(self.source_root),- "target_root": str(self.target_root),- "workspace_target": str(self.workspace_target) if self.workspace_target else None,- "output_dir": str(self.output_dir) if self.output_dir else None,- "migrate_secrets": self.migrate_secrets,- "preset": self.preset_name or None,- "skill_conflict_mode": self.skill_conflict_mode,- "selection": {- "selected": sorted(self.selected_options),- "preset": self.preset_name or None,- "skill_conflict_mode": self.skill_conflict_mode,- "available": [- {"id": option_id, **meta}- for option_id, meta in MIGRATION_OPTION_METADATA.items()- ],- "presets": [- {"id": preset_id, "selected": sorted(option_ids)}- for preset_id, option_ids in MIGRATION_PRESETS.items()- ],- },- "summary": summary,- "items": [asdict(item) for item in self.items],- "warnings": self._build_warnings(summary),- "next_steps": self._build_next_steps(summary),- }-- if self.output_dir:- write_report(self.output_dir, report)-- return report-- def _build_warnings(self, summary: dict[str, int]) -> list[str]:- """Structured warnings surfaced on the report for downstream consumers.-- Modelled on OpenClaw's extensions/migrate-hermes/plan.ts warnings[].- Keep the messages actionable — they show up in summary.md and the- JSON report.- """- warnings: list[str] = []- if summary.get("conflict", 0) > 0:- warnings.append(- "Conflicts were found. Re-run with --overwrite to replace conflicting "- "targets after item-level backups."- )- if summary.get("error", 0) > 0:- warnings.append(- "One or more items failed. Inspect the report and re-run after fixing "- "the underlying cause."- )- if self._config_apply_blocked and self.execute:- warnings.append(- "A config.yaml write hit a conflict or error mid-apply; later config "- "items were skipped to avoid a partial write."- )- # Detect whether secrets were detected but not migrated.- provider_keys_skipped = any(- item.kind == "provider-keys" and item.status == STATUS_SKIPPED- for item in self.items- )- if provider_keys_skipped and not self.migrate_secrets:- warnings.append(- "API keys and other credentials were detected but not imported. "- "Re-run with --migrate-secrets to copy supported keys into the "- "Hermes env file."- )- return warnings-- def _build_next_steps(self, summary: dict[str, int]) -> list[str]:- """Human-readable next-step guidance baked into the report."""- if not self.execute:- return [- "Re-run without --dry-run to apply the migration.",- "Pass --overwrite to resolve conflicts, or --migrate-secrets to "- "include API keys.",- ]- steps: list[str] = []- if summary.get("migrated", 0) > 0:- steps.append(- "Review the migration report at "- f"{self.output_dir}/summary.md"- if self.output_dir- else "Review the migration report."- )- steps.append(- "Start a new Hermes session (or /reset) to pick up the imported config."- )- if summary.get("conflict", 0) > 0:- steps.append(- "Re-run with --overwrite to apply items that were blocked by conflicts."- )- return steps-- def maybe_backup(self, path: Path) -> Optional[Path]:- if not self.execute or not self.backup_dir or not path.exists():- return None- return backup_existing(path, self.backup_dir)-- def write_overflow_entries(self, kind: str, entries: Sequence[str]) -> Optional[Path]:- if not entries or not self.overflow_dir:- return None- self.overflow_dir.mkdir(parents=True, exist_ok=True)- filename = f"{kind.replace('-', '_')}_overflow.txt"- path = self.overflow_dir / filename- path.write_text("\n".join(entries) + "\n", encoding="utf-8")- return path-- def copy_file(self, source: Path, destination: Path, kind: str,- transform: Optional[Any] = None) -> None:- if not source or not source.exists():- return-- if destination.exists():- if not transform and sha256_file(source) == sha256_file(destination):- self.record(kind, source, destination, "skipped", "Target already matches source")- return- if not self.overwrite:- self.record(kind, source, destination, "conflict", "Target exists and overwrite is disabled")- return-- if self.execute:- backup_path = self.maybe_backup(destination)- ensure_parent(destination)- if transform:- content = read_text(source)- content = transform(content)- destination.write_text(content, encoding="utf-8")- shutil.copystat(source, destination)- else:- shutil.copy2(source, destination)- self.record(kind, source, destination, "migrated", backup=str(backup_path) if backup_path else None)- else:- self.record(kind, source, destination, "migrated", "Would copy")-- def migrate_soul(self) -> None:- source = self.source_candidate("workspace/SOUL.md", "workspace.default/SOUL.md")- if not source:- self.record("soul", None, self.target_root / "SOUL.md", "skipped", "No OpenClaw SOUL.md found")- return- self.copy_file(source, self.target_root / "SOUL.md", kind="soul", transform=rebrand_text)-- def migrate_workspace_agents(self) -> None:- source = self.source_candidate(- f"workspace/{WORKSPACE_INSTRUCTIONS_FILENAME}",- f"workspace.default/{WORKSPACE_INSTRUCTIONS_FILENAME}",- )- if source is None:- self.record("workspace-agents", "workspace/AGENTS.md", "", "skipped", "Source file not found")- return- if not self.workspace_target:- self.record("workspace-agents", source, None, "skipped", "No workspace target was provided")- return- destination = self.workspace_target / WORKSPACE_INSTRUCTIONS_FILENAME- self.copy_file(source, destination, kind="workspace-agents", transform=rebrand_text)-- def migrate_memory(self, source: Optional[Path], destination: Path, limit: int, kind: str) -> None:- if not source or not source.exists():- self.record(kind, None, destination, "skipped", "Source file not found")- return-- incoming = extract_markdown_entries(read_text(source))- if not incoming:- self.record(kind, source, destination, "skipped", "No importable entries found")- return- incoming = [rebrand_text(entry) for entry in incoming]-- existing = parse_existing_memory_entries(destination)- merged, stats, overflowed = merge_entries(existing, incoming, limit)- details = {- "existing_entries": stats["existing"],- "added_entries": stats["added"],- "duplicate_entries": stats["duplicates"],- "overflowed_entries": stats["overflowed"],- "char_limit": limit,- "final_char_count": len(ENTRY_DELIMITER.join(merged)) if merged else 0,- }- overflow_file = self.write_overflow_entries(kind, overflowed)- if overflow_file is not None:- details["overflow_file"] = str(overflow_file)-- if self.execute:- if stats["added"] == 0 and not overflowed:- self.record(kind, source, destination, "skipped", "No new entries to import", **details)- return- backup_path = self.maybe_backup(destination)- ensure_parent(destination)- destination.write_text(ENTRY_DELIMITER.join(merged) + ("\n" if merged else ""), encoding="utf-8")- self.record(- kind,- source,- destination,- "migrated",- backup=str(backup_path) if backup_path else "",- overflow_preview=overflowed[:5],- **details,- )- else:- self.record(kind, source, destination, "migrated", "Would merge entries", overflow_preview=overflowed[:5], **details)-- def migrate_command_allowlist(self) -> None:- source = self.source_root / "exec-approvals.json"- destination = self.target_root / "config.yaml"- if not source.exists():- self.record("command-allowlist", None, destination, "skipped", "No OpenClaw exec approvals file found")- return- if yaml is None:- self.record("command-allowlist", source, destination, "error", "ruamel.yaml is not available")- return-- try:- data = json.loads(source.read_text(encoding="utf-8", errors="replace"))- except json.JSONDecodeError as exc:- self.record("command-allowlist", source, destination, "error", f"Invalid JSON: {exc}")- return- except OSError as exc:- self.record("command-allowlist", source, destination, "error", f"Could not read file: {exc}")- return-- patterns: list[str] = []- agents = data.get("agents", {})- if isinstance(agents, dict):- for agent_data in agents.values():- allowlist = agent_data.get("allowlist", []) if isinstance(agent_data, dict) else []- for entry in allowlist:- pattern = entry.get("pattern") if isinstance(entry, dict) else None- if pattern:- patterns.append(pattern)-- patterns = sorted(dict.fromkeys(patterns))- if not patterns:- self.record("command-allowlist", source, destination, "skipped", "No allowlist patterns found")- return- if not destination.exists():- self.record("command-allowlist", source, destination, "skipped", "Hermes config.yaml does not exist yet")- return-- config = load_yaml_file(destination)- current = config.get("command_allowlist", [])- if not isinstance(current, list):- current = []- merged = sorted(dict.fromkeys(list(current) + patterns))- added = [pattern for pattern in merged if pattern not in current]- if not added:- self.record("command-allowlist", source, destination, "skipped", "All patterns already present")- return-- if self.execute:- backup_path = self.maybe_backup(destination)- config["command_allowlist"] = merged- dump_yaml_file(destination, config)- self.record(- "command-allowlist",- source,- destination,- "migrated",- backup=str(backup_path) if backup_path else "",- added_patterns=added,- )- else:- self.record("command-allowlist", source, destination, "migrated", "Would merge patterns", added_patterns=added)-- def load_openclaw_config(self) -> dict[str, Any]:- # Check current name and legacy config filenames- for name in ("openclaw.json", "clawdbot.json", "moltbot.json"):- config_path = self.source_root / name- if config_path.exists():- try:- # errors="replace" means read_text() cannot raise- # UnicodeDecodeError; OSError covers unreadable/vanished files.- data = json.loads(config_path.read_text(encoding="utf-8", errors="replace"))- return data if isinstance(data, dict) else {}- except (json.JSONDecodeError, OSError):- continue- return {}-- def load_openclaw_env(self) -> dict[str, str]:- """Load the OpenClaw .env file for secrets that live there instead of config."""- return parse_env_file(self.source_root / ".env")-- def merge_env_values(self, additions: dict[str, str], kind: str, source: Path) -> None:- destination = self.target_root / ".env"- env_data = parse_env_file(destination)- added: dict[str, str] = {}- conflicts: list[str] = []-- for key, value in additions.items():- current = env_data.get(key)- if current == value:- continue- if current and not self.overwrite:- conflicts.append(key)- continue- env_data[key] = value- added[key] = value-- if conflicts and not added:- self.record(kind, source, destination, "conflict", "Destination .env already has different values", conflicting_keys=conflicts)- return- if not conflicts and not added:- self.record(kind, source, destination, "skipped", "All env values already present")- return-- if self.execute:- backup_path = self.maybe_backup(destination)- save_env_file(destination, env_data)- self.record(- kind,- source,- destination,- "migrated",- backup=str(backup_path) if backup_path else "",- added_keys=sorted(added.keys()),- conflicting_keys=conflicts,- )- else:- self.record(- kind,- source,- destination,- "migrated",- "Would merge env values",- added_keys=sorted(added.keys()),- conflicting_keys=conflicts,- )-- def migrate_messaging_settings(self, config: Optional[dict[str, Any]] = None) -> None:- config = config or self.load_openclaw_config()- additions: dict[str, str] = {}-- workspace = (- config.get("agents", {})- .get("defaults", {})- .get("workspace")- )- if isinstance(workspace, str) and workspace.strip():- ws_path = workspace.strip()- # Skip if the workspace points inside the OpenClaw source directory —- # that path will be stale after migration and would cause the Hermes- # gateway to use the old OpenClaw workspace as its cwd, picking up- # OpenClaw's AGENTS.md, MEMORY.md, etc.- try:- inside_source = Path(ws_path).resolve().is_relative_to(self.source_root.resolve())- except (ValueError, OSError):- inside_source = False- if not inside_source:- additions["MESSAGING_CWD"] = ws_path-- allowlist_path = self.source_root / "credentials" / "telegram-default-allowFrom.json"- if allowlist_path.exists():- try:- allow_data = json.loads(allowlist_path.read_text(encoding="utf-8", errors="replace"))- except json.JSONDecodeError:- self.record("messaging-settings", allowlist_path, self.target_root / ".env", "error", "Invalid JSON in Telegram allowlist file")- except OSError as exc:- self.record("messaging-settings", allowlist_path, self.target_root / ".env", "error", f"Could not read Telegram allowlist file: {exc}")- else:- allow_from = allow_data.get("allowFrom", [])- if isinstance(allow_from, list):- users = [str(user).strip() for user in allow_from if str(user).strip()]- if users:- additions["TELEGRAM_ALLOWED_USERS"] = ",".join(users)-- if additions:- self.merge_env_values(additions, "messaging-settings", self.source_root / "openclaw.json")- else:- self.record("messaging-settings", self.source_root / "openclaw.json", self.target_root / ".env", "skipped", "No Hermes-compatible messaging settings found")-- def handle_secret_settings(self, config: Optional[dict[str, Any]] = None) -> None:- config = config or self.load_openclaw_config()- if self.migrate_secrets:- self.migrate_secret_settings(config)- return-- config_path = self.source_root / "openclaw.json"- if config_path.exists():- self.record(- "secret-settings",- config_path,- self.target_root / ".env",- "skipped",- "Secret migration disabled. Re-run with --migrate-secrets to import allowlisted secrets.",- supported_targets=sorted(SUPPORTED_SECRET_TARGETS),- )- else:- self.record(- "secret-settings",- config_path,- self.target_root / ".env",- "skipped",- "OpenClaw config file not found",- supported_targets=sorted(SUPPORTED_SECRET_TARGETS),- )-- def migrate_secret_settings(self, config: dict[str, Any]) -> None:- secret_additions: dict[str, str] = {}-- tg_cfg = config.get("channels", {}).get("telegram", {})- telegram_token = self._get_channel_field(tg_cfg, "botToken") if isinstance(tg_cfg, dict) else None- if isinstance(telegram_token, str) and telegram_token.strip():- secret_additions["TELEGRAM_BOT_TOKEN"] = telegram_token.strip()-- if secret_additions:- self.merge_env_values(secret_additions, "secret-settings", self.source_root / "openclaw.json")- else:- self.record(- "secret-settings",- self.source_root / "openclaw.json",- self.target_root / ".env",- "skipped",- "No allowlisted Hermes-compatible secrets found",- supported_targets=sorted(SUPPORTED_SECRET_TARGETS),- )-- def _resolve_channel_secret(self, value: Any) -> Optional[str]:- """Resolve a channel config value that may be a SecretRef."""- return resolve_secret_input(value, self.load_openclaw_env())-- @staticmethod- def _get_channel_field(ch_cfg: dict[str, Any], field: str) -> Any:- """Get a field from channel config, checking both flat and accounts.default layout."""- val = ch_cfg.get(field)- if val is not None:- return val- accounts = ch_cfg.get("accounts")- if isinstance(accounts, dict):- default = accounts.get("default")- if isinstance(default, dict):- return default.get(field)- return None-- def migrate_discord_settings(self, config: Optional[dict[str, Any]] = None) -> None:- config = config or self.load_openclaw_config()- additions: dict[str, str] = {}- discord = config.get("channels", {}).get("discord", {})- if isinstance(discord, dict):- token = self._get_channel_field(discord, "token")- if isinstance(token, str) and token.strip():- additions["DISCORD_BOT_TOKEN"] = token.strip()- allow_from = self._get_channel_field(discord, "allowFrom") or []- if isinstance(allow_from, list):- users = [str(u).strip() for u in allow_from if str(u).strip()]- if users:- additions["DISCORD_ALLOWED_USERS"] = ",".join(users)- if additions:- self.merge_env_values(additions, "discord-settings", self.source_root / "openclaw.json")- else:- self.record("discord-settings", self.source_root / "openclaw.json", self.target_root / ".env", "skipped", "No Discord settings found")-- def migrate_slack_settings(self, config: Optional[dict[str, Any]] = None) -> None:- config = config or self.load_openclaw_config()- additions: dict[str, str] = {}- slack = config.get("channels", {}).get("slack", {})- if isinstance(slack, dict):- bot_token = self._get_channel_field(slack, "botToken")- if isinstance(bot_token, str) and bot_token.strip():- additions["SLACK_BOT_TOKEN"] = bot_token.strip()- app_token = self._get_channel_field(slack, "appToken")- if isinstance(app_token, str) and app_token.strip():- additions["SLACK_APP_TOKEN"] = app_token.strip()- allow_from = self._get_channel_field(slack, "allowFrom") or []- if isinstance(allow_from, list):- users = [str(u).strip() for u in allow_from if str(u).strip()]- if users:- additions["SLACK_ALLOWED_USERS"] = ",".join(users)- if additions:- self.merge_env_values(additions, "slack-settings", self.source_root / "openclaw.json")- else:- self.record("slack-settings", self.source_root / "openclaw.json", self.target_root / ".env", "skipped", "No Slack settings found")-- def migrate_whatsapp_settings(self, config: Optional[dict[str, Any]] = None) -> None:- config = config or self.load_openclaw_config()- additions: dict[str, str] = {}- whatsapp = config.get("channels", {}).get("whatsapp", {})- if isinstance(whatsapp, dict):- allow_from = self._get_channel_field(whatsapp, "allowFrom") or []- if isinstance(allow_from, list):- users = [str(u).strip() for u in allow_from if str(u).strip()]- if users:- additions["WHATSAPP_ALLOWED_USERS"] = ",".join(users)- if additions:- self.merge_env_values(additions, "whatsapp-settings", self.source_root / "openclaw.json")- else:- self.record("whatsapp-settings", self.source_root / "openclaw.json", self.target_root / ".env", "skipped", "No WhatsApp settings found")-- def migrate_signal_settings(self, config: Optional[dict[str, Any]] = None) -> None:- config = config or self.load_openclaw_config()- additions: dict[str, str] = {}- signal = config.get("channels", {}).get("signal", {})- if isinstance(signal, dict):- account = self._get_channel_field(signal, "account")- if isinstance(account, str) and account.strip():- additions["SIGNAL_ACCOUNT"] = account.strip()- http_url = self._get_channel_field(signal, "httpUrl")- if isinstance(http_url, str) and http_url.strip():- additions["SIGNAL_HTTP_URL"] = http_url.strip()- allow_from = self._get_channel_field(signal, "allowFrom") or []- if isinstance(allow_from, list):- users = [str(u).strip() for u in allow_from if str(u).strip()]- if users:- additions["SIGNAL_ALLOWED_USERS"] = ",".join(users)- if additions:- self.merge_env_values(additions, "signal-settings", self.source_root / "openclaw.json")- else:- self.record("signal-settings", self.source_root / "openclaw.json", self.target_root / ".env", "skipped", "No Signal settings found")-- def handle_provider_keys(self, config: Optional[dict[str, Any]] = None) -> None:- config = config or self.load_openclaw_config()- if not self.migrate_secrets:- config_path = self.source_root / "openclaw.json"- self.record(- "provider-keys",- config_path,- self.target_root / ".env",- "skipped",- "Secret migration disabled. Re-run with --migrate-secrets to import provider API keys.",- supported_targets=sorted(SUPPORTED_SECRET_TARGETS),- )- return- self.migrate_provider_keys(config)-- def migrate_provider_keys(self, config: dict[str, Any]) -> None:- secret_additions: dict[str, str] = {}-- # Extract provider API keys from models.providers- # Note: apiKey values can be strings, env templates, or SecretRef objects- openclaw_env = self.load_openclaw_env()- providers = config.get("models", {}).get("providers", {})- if isinstance(providers, dict):- for provider_name, provider_cfg in providers.items():- if not isinstance(provider_cfg, dict):- continue- raw_key = provider_cfg.get("apiKey")- api_key = resolve_secret_input(raw_key, openclaw_env)- if not api_key:- # Warn if a SecretRef with file/exec source was silently unresolvable- if isinstance(raw_key, dict) and raw_key.get("source") in {"file", "exec"}:- self.record(- "provider-keys",- self.source_root / "openclaw.json",- None,- "skipped",- f"Provider '{provider_name}' uses a {raw_key['source']}-backed SecretRef "- f"that cannot be auto-migrated. Add this key manually via: hermes config set",- )- continue-- base_url = provider_cfg.get("baseUrl", "")- api_type = provider_cfg.get("api", "")- env_var = None-- # Match by baseUrl first- if isinstance(base_url, str):- if "openrouter" in base_url.lower():- env_var = "OPENROUTER_API_KEY"- elif "openai.com" in base_url.lower():- env_var = "OPENAI_API_KEY"- elif "anthropic" in base_url.lower():- env_var = "ANTHROPIC_API_KEY"-- # Match by api type- if not env_var and isinstance(api_type, str) and api_type == "anthropic-messages":- env_var = "ANTHROPIC_API_KEY"-- # Match by provider name- if not env_var:- name_lower = provider_name.lower()- if name_lower == "openrouter":- env_var = "OPENROUTER_API_KEY"- elif "openai" in name_lower:- env_var = "OPENAI_API_KEY"-- if env_var:- secret_additions[env_var] = api_key-- # Extract TTS API keys- tts = config.get("messages", {}).get("tts", {})- if isinstance(tts, dict):- elevenlabs = tts.get("elevenlabs", {})- if isinstance(elevenlabs, dict):- el_key = elevenlabs.get("apiKey")- if isinstance(el_key, str) and el_key.strip():- secret_additions["ELEVENLABS_API_KEY"] = el_key.strip()- openai_tts = tts.get("openai", {})- if isinstance(openai_tts, dict):- oai_key = openai_tts.get("apiKey")- if isinstance(oai_key, str) and oai_key.strip():- secret_additions["VOICE_TOOLS_OPENAI_KEY"] = oai_key.strip()-- # Also check the OpenClaw .env file — many users store keys there- # instead of inline in openclaw.json- openclaw_env = self.load_openclaw_env()- env_key_mapping = {- "OPENROUTER_API_KEY": "OPENROUTER_API_KEY",- "OPENAI_API_KEY": "OPENAI_API_KEY",- "ANTHROPIC_API_KEY": "ANTHROPIC_API_KEY",- "ELEVENLABS_API_KEY": "ELEVENLABS_API_KEY",- "TELEGRAM_BOT_TOKEN": "TELEGRAM_BOT_TOKEN",- "DEEPSEEK_API_KEY": "DEEPSEEK_API_KEY",- "GEMINI_API_KEY": "GEMINI_API_KEY",- "ZAI_API_KEY": "ZAI_API_KEY",- "MINIMAX_API_KEY": "MINIMAX_API_KEY",- }- for oc_key, hermes_key in env_key_mapping.items():- val = openclaw_env.get(oc_key, "").strip()- if val and hermes_key not in secret_additions:- secret_additions[hermes_key] = val-- # Check the openclaw.json "env" sub-object — some OpenClaw setups- # store API keys here instead of in a separate .env file.- # Keys can be at env.<KEY> or env.vars.<KEY>.- json_env = config.get("env")- if isinstance(json_env, dict):- env_vars = json_env.get("vars")- sources = [json_env]- if isinstance(env_vars, dict):- sources.append(env_vars)- for src in sources:- for oc_key, hermes_key in env_key_mapping.items():- val = src.get(oc_key)- if isinstance(val, str) and val.strip() and hermes_key not in secret_additions:- secret_additions[hermes_key] = val.strip()-- # Check per-agent auth-profiles.json for additional credentials- auth_profiles_path = self.source_root / "agents" / "main" / "agent" / "auth-profiles.json"- if auth_profiles_path.exists():- try:- profiles = json.loads(auth_profiles_path.read_text(encoding="utf-8", errors="replace"))- if isinstance(profiles, dict):- # auth-profiles.json wraps profiles in a "profiles" key- profile_entries = profiles.get("profiles", profiles) if isinstance(profiles.get("profiles"), dict) else profiles- for profile_name, profile_data in profile_entries.items():- if not isinstance(profile_data, dict):- continue- # Canonical field is "key", "apiKey" is accepted as alias- api_key = profile_data.get("key", "") or profile_data.get("apiKey", "")- if not isinstance(api_key, str) or not api_key.strip():- continue- name_lower = profile_name.lower()- if "openrouter" in name_lower and "OPENROUTER_API_KEY" not in secret_additions:- secret_additions["OPENROUTER_API_KEY"] = api_key.strip()- elif "openai" in name_lower and "OPENAI_API_KEY" not in secret_additions:- secret_additions["OPENAI_API_KEY"] = api_key.strip()- elif "anthropic" in name_lower and "ANTHROPIC_API_KEY" not in secret_additions:- secret_additions["ANTHROPIC_API_KEY"] = api_key.strip()- except (json.JSONDecodeError, OSError):- pass-- if secret_additions:- self.merge_env_values(secret_additions, "provider-keys", self.source_root / "openclaw.json")- else:- self.record(- "provider-keys",- self.source_root / "openclaw.json",- self.target_root / ".env",- "skipped",- "No provider API keys found",- supported_targets=sorted(SUPPORTED_SECRET_TARGETS),- )-- def migrate_model_config(self, config: Optional[dict[str, Any]] = None) -> None:- config = config or self.load_openclaw_config()- destination = self.target_root / "config.yaml"- source_path = self.source_root / "openclaw.json"-- model_value = config.get("agents", {}).get("defaults", {}).get("model")- if model_value is None:- self.record("model-config", source_path, destination, "skipped", "No default model found in OpenClaw config")- return-- if isinstance(model_value, dict):- model_str = model_value.get("primary")- else:- model_str = model_value-- if not isinstance(model_str, str) or not model_str.strip():- self.record("model-config", source_path, destination, "skipped", "Default model value is empty or invalid")- return-- model_str = model_str.strip()-- # Resolve a model alias against the OpenClaw model catalog.- # OpenClaw stores agents.defaults.model as either a bare string or- # {"primary": "<value>"}, and that value can be either:- # - a full provider/model API ID (e.g. "anthropic/claude-opus-4-6"), or- # - a display alias (e.g. "Claude Opus 4.6") that maps to one.- # The catalog at agents.defaults.models is keyed by the full- # provider/model API ID with an "alias" field on the value, e.g.:- # {"anthropic/claude-opus-4-6": {"alias": "Claude Opus 4.6"}}- # If model_str matches an alias in the catalog, rewrite it to the- # catalog key (the real API ID). If it's already an API ID or has- # no catalog match, leave it alone and let downstream pass it through.- model_catalog = config.get("agents", {}).get("defaults", {}).get("models", {})- if isinstance(model_catalog, dict) and model_str not in model_catalog:- for api_id, entry in model_catalog.items():- if not isinstance(api_id, str):- continue- if isinstance(entry, dict) and entry.get("alias") == model_str:- model_str = api_id- break- if isinstance(entry, str) and entry == model_str:- model_str = api_id- break-- if yaml is None:- self.record("model-config", source_path, destination, "error", "ruamel.yaml is not available")- return-- hermes_config = load_yaml_file(destination)- current_model = hermes_config.get("model")- if current_model == model_str:- self.record("model-config", source_path, destination, "skipped", "Model already set to the same value")- return- if current_model and not self.overwrite:- self.record("model-config", source_path, destination, "conflict", "Model already set and overwrite is disabled", current=current_model, incoming=model_str)- return-- if self.execute:- backup_path = self.maybe_backup(destination)- existing_model = hermes_config.get("model")- if isinstance(existing_model, dict):- existing_model["default"] = model_str- else:- hermes_config["model"] = {"default": model_str}- dump_yaml_file(destination, hermes_config)- self.record("model-config", source_path, destination, "migrated", backup=str(backup_path) if backup_path else "", model=model_str)- else:- self.record("model-config", source_path, destination, "migrated", "Would set model", model=model_str)-- def migrate_tts_config(self, config: Optional[dict[str, Any]] = None) -> None:- config = config or self.load_openclaw_config()- destination = self.target_root / "config.yaml"- source_path = self.source_root / "openclaw.json"-- tts = config.get("messages", {}).get("tts", {})- if not isinstance(tts, dict) or not tts:- self.record("tts-config", source_path, destination, "skipped", "No TTS configuration found in OpenClaw config")- return-- if yaml is None:- self.record("tts-config", source_path, destination, "error", "ruamel.yaml is not available")- return-- tts_data: dict[str, Any] = {}-- provider = tts.get("provider")- if isinstance(provider, str) and provider in {"elevenlabs", "openai", "edge", "microsoft"}:- # OpenClaw renamed "edge" to "microsoft"; Hermes still uses "edge"- tts_data["provider"] = "edge" if provider == "microsoft" else provider-- # TTS provider settings live under messages.tts.providers.{provider}- # in OpenClaw (not messages.tts.elevenlabs directly)- providers = tts.get("providers") or {}-- # Also check the top-level "talk" config which has provider settings too- talk_cfg = (config or self.load_openclaw_config()).get("talk") or {}- talk_providers = talk_cfg.get("providers") or {}-- # Merge: messages.tts.providers takes priority, then talk.providers,- # then legacy flat keys (messages.tts.elevenlabs, etc.)- elevenlabs = (- (providers.get("elevenlabs") or {})- if isinstance(providers.get("elevenlabs"), dict) else- (talk_providers.get("elevenlabs") or {})- if isinstance(talk_providers.get("elevenlabs"), dict) else- (tts.get("elevenlabs") or {})- )- if isinstance(elevenlabs, dict):- el_settings: dict[str, str] = {}- voice_id = elevenlabs.get("voiceId") or talk_cfg.get("voiceId")- if isinstance(voice_id, str) and voice_id.strip():- el_settings["voice_id"] = voice_id.strip()- model_id = elevenlabs.get("modelId") or talk_cfg.get("modelId")- if isinstance(model_id, str) and model_id.strip():- el_settings["model_id"] = model_id.strip()- if el_settings:- tts_data["elevenlabs"] = el_settings-- openai_tts = (- (providers.get("openai") or {})- if isinstance(providers.get("openai"), dict) else- (talk_providers.get("openai") or {})- if isinstance(talk_providers.get("openai"), dict) else- (tts.get("openai") or {})- )- if isinstance(openai_tts, dict):- oai_settings: dict[str, str] = {}- oai_model = openai_tts.get("model") or openai_tts.get("modelId")- if isinstance(oai_model, str) and oai_model.strip():- oai_settings["model"] = oai_model.strip()- oai_voice = openai_tts.get("voice")- if isinstance(oai_voice, str) and oai_voice.strip():- oai_settings["voice"] = oai_voice.strip()- if oai_settings:- tts_data["openai"] = oai_settings-- edge_tts = (- (providers.get("edge") or providers.get("microsoft") or {})- if isinstance(providers.get("edge"), dict) or isinstance(providers.get("microsoft"), dict) else- (tts.get("edge") or tts.get("microsoft") or {})- )- if isinstance(edge_tts, dict):- edge_voice = edge_tts.get("voice")- if isinstance(edge_voice, str) and edge_voice.strip():- tts_data["edge"] = {"voice": edge_voice.strip()}-- if not tts_data:- self.record("tts-config", source_path, destination, "skipped", "No compatible TTS settings found")- return-- hermes_config = load_yaml_file(destination)- existing_tts = hermes_config.get("tts", {})- if not isinstance(existing_tts, dict):- existing_tts = {}-- if self.execute:- backup_path = self.maybe_backup(destination)- merged_tts = dict(existing_tts)- for key, value in tts_data.items():- if isinstance(value, dict) and isinstance(merged_tts.get(key), dict):- merged_tts[key] = {**merged_tts[key], **value}- else:- merged_tts[key] = value- hermes_config["tts"] = merged_tts- dump_yaml_file(destination, hermes_config)- self.record("tts-config", source_path, destination, "migrated", backup=str(backup_path) if backup_path else "", settings=list(tts_data.keys()))- else:- self.record("tts-config", source_path, destination, "migrated", "Would set TTS config", settings=list(tts_data.keys()))-- def migrate_shared_skills(self) -> None:- # Check all OpenClaw skill sources: managed, personal, project-level- skill_sources = [- (self.source_root / "skills", "shared-skills", "managed skills"),- (Path.home() / ".agents" / "skills", "personal-skills", "personal cross-project skills"),- (self.source_root / "workspace" / ".agents" / "skills", "project-skills", "project-level shared skills"),- (self.source_root / "workspace.default" / ".agents" / "skills", "project-skills", "project-level shared skills"),- ]- found_any = False- for source_root, kind_label, desc in skill_sources:- if source_root.exists():- found_any = True- self._import_skill_directory(source_root, kind_label, desc)- if not found_any:- destination_root = self.target_root / "skills" / SKILL_CATEGORY_DIRNAME- self.record("shared-skills", None, destination_root, "skipped", "No shared OpenClaw skills directories found")-- def _import_skill_directory(self, source_root: Path, kind_label: str, desc: str) -> None:- """Import skills from a single source directory into openclaw-imports."""- destination_root = self.target_root / "skills" / SKILL_CATEGORY_DIRNAME-- 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(kind_label, source_root, destination_root, "skipped", f"No skills with SKILL.md found in {desc}")- return-- for skill_dir in skill_dirs:- destination = destination_root / skill_dir.name- final_destination = destination- if destination.exists():- if self.skill_conflict_mode == "skip":- self.record(kind_label, skill_dir, destination, "conflict", "Destination skill already exists")- continue- if self.skill_conflict_mode == "rename":- final_destination = self.resolve_skill_destination(destination)- if self.execute:- backup_path = None- if final_destination == destination and destination.exists():- backup_path = self.maybe_backup(destination)- final_destination.parent.mkdir(parents=True, exist_ok=True)- if final_destination == destination and destination.exists():- shutil.rmtree(destination)- shutil.copytree(skill_dir, final_destination)- details: dict[str, Any] = {"backup": str(backup_path) if backup_path else ""}- if final_destination != destination:- details["renamed_from"] = str(destination)- self.record(kind_label, skill_dir, final_destination, "migrated", **details)- else:- if final_destination != destination:- self.record(- kind_label,- skill_dir,- final_destination,- "migrated",- f"Would copy {desc} directory under a renamed folder",- renamed_from=str(destination),- )- else:- self.record(kind_label, skill_dir, final_destination, "migrated", f"Would copy {desc} directory")-- desc_path = destination_root / "DESCRIPTION.md"- if self.execute:- desc_path.parent.mkdir(parents=True, exist_ok=True)- if not desc_path.exists():- desc_path.write_text(SKILL_CATEGORY_DESCRIPTION + "\n", encoding="utf-8")- elif not desc_path.exists():- self.record("shared-skill-category", None, desc_path, "migrated", "Would create category description")-- def migrate_daily_memory(self) -> None:- source_dir = self.source_candidate("workspace/memory")- destination = self.target_root / "memories" / "MEMORY.md"- if not source_dir or not source_dir.is_dir():- self.record("daily-memory", None, destination, "skipped", "No workspace/memory/ directory found")- return-- md_files = sorted(p for p in source_dir.iterdir() if p.is_file() and p.suffix == ".md")- if not md_files:- self.record("daily-memory", source_dir, destination, "skipped", "No .md files found in workspace/memory/")- return-- all_incoming: list[str] = []- for md_file in md_files:- try:- # read_text() uses errors="replace" so it cannot raise- # UnicodeDecodeError; OSError covers unreadable/vanished files.- entries = extract_markdown_entries(read_text(md_file))- except OSError:- continue- all_incoming.extend(entries)-- if not all_incoming:- self.record("daily-memory", source_dir, destination, "skipped", "No importable entries found in daily memory files")- return- all_incoming = [rebrand_text(entry) for entry in all_incoming]-- existing = parse_existing_memory_entries(destination)- merged, stats, overflowed = merge_entries(existing, all_incoming, self.memory_limit)- details = {- "source_files": len(md_files),- "existing_entries": stats["existing"],- "added_entries": stats["added"],- "duplicate_entries": stats["duplicates"],- "overflowed_entries": stats["overflowed"],- "char_limit": self.memory_limit,- "final_char_count": len(ENTRY_DELIMITER.join(merged)) if merged else 0,- }- overflow_file = self.write_overflow_entries("daily-memory", overflowed)- if overflow_file is not None:- details["overflow_file"] = str(overflow_file)-- if self.execute:- if stats["added"] == 0 and not overflowed:- self.record("daily-memory", source_dir, destination, "skipped", "No new entries to import", **details)- return- backup_path = self.maybe_backup(destination)- ensure_parent(destination)- destination.write_text(ENTRY_DELIMITER.join(merged) + ("\n" if merged else ""), encoding="utf-8")- self.record(- "daily-memory",- source_dir,- destination,- "migrated",- backup=str(backup_path) if backup_path else "",- overflow_preview=overflowed[:5],- **details,- )- else:- self.record("daily-memory", source_dir, destination, "migrated", "Would merge daily memory entries", overflow_preview=overflowed[:5], **details)-- def migrate_skills(self) -> None:- source_root = self.source_candidate("workspace/skills")- destination_root = self.target_root / "skills" / SKILL_CATEGORY_DIRNAME- if not source_root or not source_root.exists():- self.record("skills", None, destination_root, "skipped", "No OpenClaw 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-- for skill_dir in skill_dirs:- destination = destination_root / skill_dir.name- final_destination = destination- if destination.exists():- if self.skill_conflict_mode == "skip":- self.record("skill", skill_dir, destination, "conflict", "Destination skill already exists")- continue- if self.skill_conflict_mode == "rename":- final_destination = self.resolve_skill_destination(destination)- if self.execute:- backup_path = None- if final_destination == destination and destination.exists():- backup_path = self.maybe_backup(destination)- final_destination.parent.mkdir(parents=True, exist_ok=True)- if final_destination == destination and destination.exists():- shutil.rmtree(destination)- shutil.copytree(skill_dir, final_destination)- details: dict[str, Any] = {"backup": str(backup_path) if backup_path else ""}- if final_destination != destination:- details["renamed_from"] = str(destination)- self.record("skill", skill_dir, final_destination, "migrated", **details)- else:- if final_destination != destination:- self.record(- "skill",- skill_dir,- final_destination,- "migrated",- "Would copy skill directory under a renamed folder",- renamed_from=str(destination),- )- else:- self.record("skill", skill_dir, final_destination, "migrated", "Would copy skill directory")-- desc_path = destination_root / "DESCRIPTION.md"- if self.execute:- desc_path.parent.mkdir(parents=True, exist_ok=True)- if not desc_path.exists():- desc_path.write_text(SKILL_CATEGORY_DESCRIPTION + "\n", encoding="utf-8")- elif not desc_path.exists():- self.record("skill-category", None, desc_path, "migrated", "Would create category description")-- def copy_tree_non_destructive(- self,- source_root: Optional[Path],- destination_root: Path,- kind: str,- ignore_dir_names: Optional[set[str]] = None,- ) -> None:- if not source_root or not source_root.exists():- self.record(kind, None, destination_root, "skipped", "Source directory not found")- return-- ignore_dir_names = ignore_dir_names or set()- files = [- p- for p in source_root.rglob("*")- if p.is_file() and not any(part in ignore_dir_names for part in p.relative_to(source_root).parts[:-1])- ]- if not files:- self.record(kind, source_root, destination_root, "skipped", "No files found")- return-- copied = 0- skipped = 0- conflicts = 0-- for source in files:- rel = source.relative_to(source_root)- destination = destination_root / rel- if destination.exists():- if sha256_file(source) == sha256_file(destination):- skipped += 1- continue- if not self.overwrite:- conflicts += 1- self.record(kind, source, destination, "conflict", "Destination file already exists")- continue-- if self.execute:- self.maybe_backup(destination)- ensure_parent(destination)- shutil.copy2(source, destination)- copied += 1-- status = "migrated" if copied else "skipped"- reason = ""- if not copied and conflicts:- status = "conflict"- reason = "All candidate files conflicted with existing destination files"- elif not copied:- reason = "No new files to copy"-- self.record(kind, source_root, destination_root, status, reason, copied_files=copied, unchanged_files=skipped, conflicts=conflicts)-- def archive_docs(self) -> None:- candidates = [- self.source_candidate("workspace/IDENTITY.md", "workspace.default/IDENTITY.md"),- self.source_candidate("workspace/TOOLS.md", "workspace.default/TOOLS.md"),- self.source_candidate("workspace/HEARTBEAT.md", "workspace.default/HEARTBEAT.md"),- self.source_candidate("workspace/BOOTSTRAP.md", "workspace.default/BOOTSTRAP.md"),- ]- for candidate in candidates:- if candidate:- self.archive_path(candidate, reason="No direct Hermes destination; archived for manual review")-- for rel in ("workspace/.learnings", "workspace/memory"):- candidate = self.source_root / rel- if candidate.exists():- self.archive_path(candidate, reason="No direct Hermes destination; archived for manual review")-- partially_extracted = [- ("openclaw.json", "Selected Hermes-compatible values were extracted; raw OpenClaw config was not copied."),- ("credentials/telegram-default-allowFrom.json", "Selected Hermes-compatible values were extracted; raw credentials file was not copied."),- ]- for rel, reason in partially_extracted:- candidate = self.source_root / rel- if candidate.exists():- self.record("raw-config-skip", candidate, None, "skipped", reason)-- skipped_sensitive = [- "memory/main.sqlite",- "credentials",- "devices",- "identity",- "workspace.zip",- ]- for rel in skipped_sensitive:- candidate = self.source_root / rel- if candidate.exists():- self.record("sensitive-skip", candidate, None, "skipped", "Contains secrets, binary state, or product-specific runtime data")-- def archive_path(self, source: Path, reason: str) -> None:- destination = self.archive_dir / relative_label(source, self.source_root) if self.archive_dir else None- if self.execute and destination is not None:- ensure_parent(destination)- if source.is_dir():- shutil.copytree(source, destination, dirs_exist_ok=True)- else:- shutil.copy2(source, destination)- self.record("archive", source, destination, "archived", reason)- else:- self.record("archive", source, destination, "archived", reason)-- # ── MCP servers ─────────────────────────────────────────────- def migrate_mcp_servers(self, config: Optional[dict[str, Any]] = None) -> None:- config = config or self.load_openclaw_config()- mcp_raw = (config.get("mcp") or {}).get("servers") or {}- if not mcp_raw:- self.record("mcp-servers", None, None, "skipped", "No MCP servers found in OpenClaw config")- return-- hermes_cfg_path = self.target_root / "config.yaml"- hermes_cfg = load_yaml_file(hermes_cfg_path)- existing_mcp = hermes_cfg.get("mcp_servers") or {}- added = 0-- for name, srv in mcp_raw.items():- if not isinstance(srv, dict):- continue- if name in existing_mcp and not self.overwrite:- self.record("mcp-servers", f"mcp.servers.{name}", f"mcp_servers.{name}", "conflict",- "MCP server already exists in Hermes config")- continue-- hermes_srv: dict[str, Any] = {}- # STDIO transport- if srv.get("command"):- hermes_srv["command"] = srv["command"]- if srv.get("args"):- hermes_srv["args"] = srv["args"]- if srv.get("env"):- hermes_srv["env"] = srv["env"]- if srv.get("cwd"):- hermes_srv["cwd"] = srv["cwd"]- # HTTP/SSE transport- if srv.get("url"):- hermes_srv["url"] = srv["url"]- if srv.get("headers"):- hermes_srv["headers"] = srv["headers"]- if srv.get("auth"):- hermes_srv["auth"] = srv["auth"]- # Common fields- if srv.get("enabled") is False:- hermes_srv["enabled"] = False- if srv.get("timeout"):- hermes_srv["timeout"] = srv["timeout"]- if srv.get("connectTimeout"):- hermes_srv["connect_timeout"] = srv["connectTimeout"]- # Tool filtering- tools_cfg = srv.get("tools") or {}- if tools_cfg.get("include") or tools_cfg.get("exclude"):- hermes_srv["tools"] = {}- if tools_cfg.get("include"):- hermes_srv["tools"]["include"] = tools_cfg["include"]- if tools_cfg.get("exclude"):- hermes_srv["tools"]["exclude"] = tools_cfg["exclude"]- # Sampling- sampling = srv.get("sampling")- if sampling and isinstance(sampling, dict):- hermes_srv["sampling"] = {- k: v for k, v in {- "enabled": sampling.get("enabled"),- "model": sampling.get("model"),- "max_tokens_cap": sampling.get("maxTokensCap") or sampling.get("max_tokens_cap"),- "timeout": sampling.get("timeout"),- "max_rpm": sampling.get("maxRpm") or sampling.get("max_rpm"),- }.items() if v is not None- }-- existing_mcp[name] = hermes_srv- added += 1- self.record("mcp-servers", f"mcp.servers.{name}", f"config.yaml mcp_servers.{name}",- "migrated", servers_added=added)-- if added > 0 and self.execute:- self.maybe_backup(hermes_cfg_path)- hermes_cfg["mcp_servers"] = existing_mcp- dump_yaml_file(hermes_cfg_path, hermes_cfg)-- # ── Plugins ───────────────────────────────────────────────- def migrate_plugins_config(self, config: Optional[dict[str, Any]] = None) -> None:- config = config or self.load_openclaw_config()- plugins = config.get("plugins") or {}- if not plugins:- self.record("plugins-config", None, None, "skipped", "No plugins configuration found")- return-- # Archive the full plugins config- if self.archive_dir and self.execute:- self.archive_dir.mkdir(parents=True, exist_ok=True)- dest = self.archive_dir / "plugins-config.json"- dest.write_text(json.dumps(plugins, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")- self.record("plugins-config", "openclaw.json plugins.*", str(dest), "archived",- "Plugins config archived for manual review")- else:- self.record("plugins-config", "openclaw.json plugins.*", "archive/plugins-config.json",- "archived" if not self.execute else "migrated", "Would archive plugins config")-- # Copy extensions directory if it exists- ext_dir = self.source_root / "extensions"- if ext_dir.is_dir() and self.archive_dir:- dest_ext = self.archive_dir / "extensions"- if self.execute:- shutil.copytree(ext_dir, dest_ext, dirs_exist_ok=True)- self.record("plugins-config", str(ext_dir), str(dest_ext), "archived",- "Extensions directory archived")-- # Extract any plugin env vars- entries = plugins.get("entries") or {}- for plugin_name, plugin_cfg in entries.items():- if isinstance(plugin_cfg, dict):- api_key = plugin_cfg.get("apiKey")- if api_key and self.migrate_secrets:- env_key = f"PLUGIN_{plugin_name.upper().replace('-', '_')}_API_KEY"- self._set_env_var(env_key, api_key, f"plugins.entries.{plugin_name}.apiKey")-- # ── Cron jobs ─────────────────────────────────────────────- def migrate_cron_jobs(self, config: Optional[dict[str, Any]] = None) -> None:- config = config or self.load_openclaw_config()- cron = config.get("cron") or {}- cron_store = self.source_root / "cron"- found_any = False-- # Archive the full cron config when present- if cron:- found_any = True- if self.archive_dir and self.execute:- self.archive_dir.mkdir(parents=True, exist_ok=True)- dest = self.archive_dir / "cron-config.json"- dest.write_text(json.dumps(cron, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")- self.record("cron-jobs", "openclaw.json cron.*", str(dest), "archived",- "Cron config archived. Use 'hermes cron' to recreate jobs manually.")- else:- self.record("cron-jobs", "openclaw.json cron.*", "archive/cron-config.json",- "archived", "Would archive cron config")-- # Also check for cron store files even when config.cron is missing- if cron_store.is_dir() and self.archive_dir:- found_any = True- dest_cron = self.archive_dir / "cron-store"- if self.execute:- shutil.copytree(cron_store, dest_cron, dirs_exist_ok=True)- self.record("cron-jobs", str(cron_store), str(dest_cron), "archived",- "Cron job store archived")-- if not found_any:- self.record("cron-jobs", None, None, "skipped", "No cron configuration found")-- # ── Hooks ─────────────────────────────────────────────────- def migrate_hooks_config(self, config: Optional[dict[str, Any]] = None) -> None:- config = config or self.load_openclaw_config()- hooks = config.get("hooks") or {}- if not hooks:- self.record("hooks-config", None, None, "skipped", "No hooks configuration found")- return-- # Archive the full hooks config- if self.archive_dir and self.execute:- self.archive_dir.mkdir(parents=True, exist_ok=True)- dest = self.archive_dir / "hooks-config.json"- dest.write_text(json.dumps(hooks, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")- self.record("hooks-config", "openclaw.json hooks.*", str(dest), "archived",- "Hooks config archived for manual review")- else:- self.record("hooks-config", "openclaw.json hooks.*", "archive/hooks-config.json",- "archived", "Would archive hooks config")-- # Copy workspace hooks directory- for ws_name in ("workspace", "workspace.default"):- hooks_dir = self.source_root / ws_name / "hooks"- if hooks_dir.is_dir() and self.archive_dir:- dest_hooks = self.archive_dir / "workspace-hooks"- if self.execute:- shutil.copytree(hooks_dir, dest_hooks, dirs_exist_ok=True)- self.record("hooks-config", str(hooks_dir), str(dest_hooks), "archived",- "Workspace hooks directory archived")- break-- # ── Agent config ──────────────────────────────────────────- def migrate_agent_config(self, config: Optional[dict[str, Any]] = None) -> None:- config = config or self.load_openclaw_config()- agents = config.get("agents") or {}- defaults = agents.get("defaults") or {}- agent_list = agents.get("list") or []-- if not defaults and not agent_list:- self.record("agent-config", None, None, "skipped", "No agent configuration found")- return-- hermes_cfg_path = self.target_root / "config.yaml"- hermes_cfg = load_yaml_file(hermes_cfg_path)- changes = False-- # Map agent defaults- agent_cfg = hermes_cfg.get("agent") or {}- if defaults.get("contextTokens"):- # No direct mapping but useful context- pass- if defaults.get("timeoutSeconds"):- agent_cfg["max_turns"] = min(defaults["timeoutSeconds"] // 10, 200)- changes = True- if defaults.get("verboseDefault"):- agent_cfg["verbose"] = defaults["verboseDefault"]- changes = True- if defaults.get("thinkingDefault"):- # Map OpenClaw thinking -> Hermes reasoning_effort- thinking = defaults["thinkingDefault"]- if thinking in {"always", "high", "xhigh"}:- agent_cfg["reasoning_effort"] = "high"- elif thinking in {"auto", "medium", "adaptive"}:- agent_cfg["reasoning_effort"] = "medium"- elif thinking in {"off", "low", "none", "minimal"}:- agent_cfg["reasoning_effort"] = "low"- changes = True-- # Map compaction -> compression- compaction = defaults.get("compaction") or {}- if compaction:- compression = hermes_cfg.get("compression") or {}- if compaction.get("mode") == "off":- compression["enabled"] = False- else:- compression["enabled"] = True- if compaction.get("timeout"):- pass # No direct mapping- if compaction.get("model"):- aux = hermes_cfg.setdefault("auxiliary", {})- aux_comp = aux.setdefault("compression", {})- aux_comp["model"] = compaction["model"]- hermes_cfg["compression"] = compression- changes = True-- # Map humanDelay- human_delay = defaults.get("humanDelay") or {}- if human_delay:- hd = hermes_cfg.get("human_delay") or {}- hd_mode = human_delay.get("mode") or ("natural" if human_delay.get("enabled") else None)- if hd_mode and hd_mode != "off":- hd["mode"] = hd_mode- if human_delay.get("minMs"):- hd["min_ms"] = human_delay["minMs"]- if human_delay.get("maxMs"):- hd["max_ms"] = human_delay["maxMs"]- hermes_cfg["human_delay"] = hd- changes = True-- # Map userTimezone- if defaults.get("userTimezone"):- hermes_cfg["timezone"] = defaults["userTimezone"]- changes = True-- # Map terminal/exec settings- exec_cfg = (config.get("tools") or {}).get("exec") or {}- if exec_cfg:- terminal_cfg = hermes_cfg.get("terminal") or {}- if exec_cfg.get("timeoutSec") or exec_cfg.get("timeout"):- terminal_cfg["timeout"] = exec_cfg.get("timeoutSec") or exec_cfg.get("timeout")- changes = True- hermes_cfg["terminal"] = terminal_cfg-- # Map sandbox -> terminal docker settings- sandbox = defaults.get("sandbox") or {}- if sandbox and sandbox.get("backend") == "docker":- terminal_cfg = hermes_cfg.get("terminal") or {}- terminal_cfg["backend"] = "docker"- if sandbox.get("docker", {}).get("image"):- terminal_cfg["docker_image"] = sandbox["docker"]["image"]- hermes_cfg["terminal"] = terminal_cfg- changes = True-- if changes:- hermes_cfg["agent"] = agent_cfg- if self.execute:- self.maybe_backup(hermes_cfg_path)- dump_yaml_file(hermes_cfg_path, hermes_cfg)- self.record("agent-config", "openclaw.json agents.defaults", "config.yaml agent/compression/terminal",- "migrated", "Agent defaults mapped to Hermes config")-- # Archive multi-agent list- if agent_list:- if self.archive_dir and self.execute:- self.archive_dir.mkdir(parents=True, exist_ok=True)- dest = self.archive_dir / "agents-list.json"- dest.write_text(json.dumps(agent_list, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")- self.record("agent-config", "openclaw.json agents.list", "archive/agents-list.json",- "archived", f"Multi-agent setup ({len(agent_list)} agents) archived for manual recreation")-- # Archive bindings- bindings = config.get("bindings") or []- if bindings:- if self.archive_dir and self.execute:- self.archive_dir.mkdir(parents=True, exist_ok=True)- dest = self.archive_dir / "bindings.json"- dest.write_text(json.dumps(bindings, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")- self.record("agent-config", "openclaw.json bindings", "archive/bindings.json",- "archived", f"Agent routing bindings ({len(bindings)} rules) archived")-- # ── Gateway config ────────────────────────────────────────- def migrate_gateway_config(self, config: Optional[dict[str, Any]] = None) -> None:- config = config or self.load_openclaw_config()- gateway = config.get("gateway") or {}- if not gateway:- self.record("gateway-config", None, None, "skipped", "No gateway configuration found")- return-- # Archive the full gateway config (complex, many settings)- if self.archive_dir and self.execute:- self.archive_dir.mkdir(parents=True, exist_ok=True)- dest = self.archive_dir / "gateway-config.json"- dest.write_text(json.dumps(gateway, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")- self.record("gateway-config", "openclaw.json gateway.*", "archive/gateway-config.json",- "archived", "Gateway config archived. Use 'hermes gateway' to configure.")-- # Extract gateway auth token to .env if present- auth = gateway.get("auth") or {}- if auth.get("token") and self.migrate_secrets:- self._set_env_var("HERMES_GATEWAY_TOKEN", auth["token"], "gateway.auth.token")-- # ── Session config ────────────────────────────────────────- def migrate_session_config(self, config: Optional[dict[str, Any]] = None) -> None:- config = config or self.load_openclaw_config()- session = config.get("session") or {}- if not session:- self.record("session-config", None, None, "skipped", "No session configuration found")- return-- if session.get("reset") or session.get("resetTriggers") or session.get("reset_triggers"):- self.record("session-config", "session reset timers", None, "skipped",- "Hermes conversations do not reset on idle or daily timers")-- # Archive full session config (identity links, thread bindings, etc.)- complex_keys = {"identityLinks", "threadBindings", "maintenance", "scope", "sendPolicy"}- complex_session = {k: v for k, v in session.items() if k in complex_keys and v}- if complex_session and self.archive_dir:- if self.execute:- self.archive_dir.mkdir(parents=True, exist_ok=True)- dest = self.archive_dir / "session-config.json"- dest.write_text(json.dumps(complex_session, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")- self.record("session-config", "openclaw.json session (advanced)",- "archive/session-config.json", "archived",- "Advanced session settings archived (identity links, thread bindings, etc.)")-- # ── Full model providers ──────────────────────────────────- def migrate_full_providers(self, config: Optional[dict[str, Any]] = None) -> None:- config = config or self.load_openclaw_config()- models = config.get("models") or {}- providers = models.get("providers") or {}- if not providers:- self.record("full-providers", None, None, "skipped", "No model providers found")- return-- hermes_cfg_path = self.target_root / "config.yaml"- hermes_cfg = load_yaml_file(hermes_cfg_path)- custom_providers = hermes_cfg.get("custom_providers") or []- added = 0-- # Well-known providers: just extract API keys- WELL_KNOWN = {"openrouter", "openai", "anthropic", "deepseek", "google", "groq"}-- for prov_name, prov_cfg in providers.items():- if not isinstance(prov_cfg, dict):- continue-- # Extract API key to .env- api_key = prov_cfg.get("apiKey") or prov_cfg.get("api_key")- if api_key and self.migrate_secrets:- env_key = f"{prov_name.upper().replace('-', '_')}_API_KEY"- self._set_env_var(env_key, api_key, f"models.providers.{prov_name}.apiKey")-- # For non-well-known providers, create custom_providers entry- if prov_name.lower() not in WELL_KNOWN and prov_cfg.get("baseUrl"):- # Check if already exists- existing_names = {p.get("name", "").lower() for p in custom_providers}- if prov_name.lower() in existing_names and not self.overwrite:- self.record("full-providers", f"models.providers.{prov_name}",- "config.yaml custom_providers", "conflict",- f"Provider '{prov_name}' already exists")- continue-- api_type = prov_cfg.get("apiType") or prov_cfg.get("api") or prov_cfg.get("type") or "openai"- api_mode_map = {- "openai": "chat_completions",- "openai-completions": "chat_completions",- "openai-responses": "chat_completions",- "anthropic": "anthropic_messages",- "anthropic-messages": "anthropic_messages",- "google-generative-ai": "chat_completions",- "cohere": "chat_completions",- }- entry = {- "name": prov_name,- "base_url": prov_cfg["baseUrl"],- "api_key": "", # referenced from .env- "api_mode": api_mode_map.get(api_type, "chat_completions"),- }- custom_providers.append(entry)- added += 1- self.record("full-providers", f"models.providers.{prov_name}",- f"config.yaml custom_providers[{prov_name}]", "migrated")-- if added > 0 and self.execute:- self.maybe_backup(hermes_cfg_path)- hermes_cfg["custom_providers"] = custom_providers- dump_yaml_file(hermes_cfg_path, hermes_cfg)-- # Archive model aliases/catalog- agent_defaults = (config.get("agents") or {}).get("defaults") or {}- model_aliases = agent_defaults.get("models") or {}- if model_aliases:- if self.archive_dir and self.execute:- self.archive_dir.mkdir(parents=True, exist_ok=True)- dest = self.archive_dir / "model-aliases.json"- dest.write_text(json.dumps(model_aliases, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")- self.record("full-providers", "agents.defaults.models", "archive/model-aliases.json",- "archived", f"Model aliases/catalog ({len(model_aliases)} entries) archived")-- # ── Deep channel config ───────────────────────────────────- def migrate_deep_channels(self, config: Optional[dict[str, Any]] = None) -> None:- config = config or self.load_openclaw_config()- channels = config.get("channels") or {}- if not channels:- self.record("deep-channels", None, None, "skipped", "No channel configuration found")- return-- # Extended channel token/allowlist mapping- CHANNEL_ENV_MAP = {- "matrix": {"token": "MATRIX...OKEN", "tokenField": "accessToken", "allowFrom": "MATRIX_ALLOWED_USERS",- "extras": {"homeserverUrl": "MATRIX_HOMESERVER_URL", "userId": "MATRIX_USER_ID"}},- "mattermost": {"token": "MATTERMOST_BOT_TOKEN", "allowFrom": "MATTERMOST_ALLOWED_USERS",- "extras": {"url": "MATTERMOST_URL", "teamId": "MATTERMOST_TEAM_ID"}},- "irc": {"extras": {"server": "IRC_SERVER", "nick": "IRC_NICK", "channels": "IRC_CHANNELS"}},- "googlechat": {"extras": {"serviceAccountKeyPath": "GOOGLE_CHAT_SA_KEY_PATH"}},- "imessage": {},- "bluebubbles": {"extras": {"server": "BLUEBUBBLES_SERVER", "password": "BLUEBUBBLES_PASSWORD"}},- "msteams": {"token": "MSTEAMS_BOT_TOKEN", "allowFrom": "MSTEAMS_ALLOWED_USERS"},- "nostr": {"extras": {"nsec": "NOSTR_NSEC", "relays": "NOSTR_RELAYS"}},- "twitch": {"token": "TWITCH_BOT_TOKEN", "extras": {"channels": "TWITCH_CHANNELS"}},- }-- for ch_name, ch_mapping in CHANNEL_ENV_MAP.items():- ch_cfg = channels.get(ch_name) or {}- if not ch_cfg:- continue-- # Extract tokens (check flat path, then accounts.default)- token_field = ch_mapping.get("tokenField", "botToken")- bot_token = self._get_channel_field(ch_cfg, token_field)- if ch_mapping.get("token") and bot_token and self.migrate_secrets:- self._set_env_var(ch_mapping["token"], str(bot_token),- f"channels.{ch_name}.{token_field}")- allow_val = self._get_channel_field(ch_cfg, "allowFrom")- if ch_mapping.get("allowFrom") and allow_val:- if isinstance(allow_val, list):- allow_val = ",".join(str(x) for x in allow_val)- self._set_env_var(ch_mapping["allowFrom"], str(allow_val),- f"channels.{ch_name}.allowFrom")- # Extra fields- for oc_key, env_key in (ch_mapping.get("extras") or {}).items():- val = self._get_channel_field(ch_cfg, oc_key)- if val:- if isinstance(val, list):- val = ",".join(str(x) for x in val)- is_secret = "password" in oc_key.lower() or "token" in oc_key.lower() or "nsec" in oc_key.lower()- if is_secret and not self.migrate_secrets:- continue- self._set_env_var(env_key, str(val), f"channels.{ch_name}.{oc_key}")-- # Map Discord-specific settings to Hermes config- discord_cfg = channels.get("discord") or {}- if discord_cfg:- hermes_cfg_path = self.target_root / "config.yaml"- hermes_cfg = load_yaml_file(hermes_cfg_path)- discord_hermes = hermes_cfg.get("discord") or {}- changed = False- if "requireMention" in discord_cfg:- discord_hermes["require_mention"] = discord_cfg["requireMention"]- changed = True- if discord_cfg.get("autoThread") is not None:- discord_hermes["auto_thread"] = discord_cfg["autoThread"]- changed = True- if changed and self.execute:- hermes_cfg["discord"] = discord_hermes- dump_yaml_file(hermes_cfg_path, hermes_cfg)-- # Archive complex channel configs (group settings, thread bindings, etc.)- complex_archive = {}- for ch_name, ch_cfg in channels.items():- if not isinstance(ch_cfg, dict):- continue- complex_keys = {k: v for k, v in ch_cfg.items()- if k not in {"botToken", "appToken", "allowFrom", "enabled"}- and v and k not in {"requireMention", "autoThread"}}- if complex_keys:- complex_archive[ch_name] = complex_keys-- if complex_archive and self.archive_dir:- if self.execute:- self.archive_dir.mkdir(parents=True, exist_ok=True)- dest = self.archive_dir / "channels-deep-config.json"- dest.write_text(json.dumps(complex_archive, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")- self.record("deep-channels", "openclaw.json channels (advanced settings)",- "archive/channels-deep-config.json", "archived",- f"Deep channel config for {len(complex_archive)} channels archived")-- # ── Browser config ────────────────────────────────────────- def migrate_browser_config(self, config: Optional[dict[str, Any]] = None) -> None:- config = config or self.load_openclaw_config()- browser = config.get("browser") or {}- if not browser:- self.record("browser-config", None, None, "skipped", "No browser configuration found")- return-- hermes_cfg_path = self.target_root / "config.yaml"- hermes_cfg = load_yaml_file(hermes_cfg_path)- browser_hermes = hermes_cfg.get("browser") or {}- changed = False-- # Map fields that have Hermes equivalents- if browser.get("cdpUrl"):- browser_hermes["cdp_url"] = browser["cdpUrl"]- changed = True- if browser.get("headless") is not None:- browser_hermes["headless"] = browser["headless"]- changed = True-- if changed:- hermes_cfg["browser"] = browser_hermes- if self.execute:- self.maybe_backup(hermes_cfg_path)- dump_yaml_file(hermes_cfg_path, hermes_cfg)- self.record("browser-config", "openclaw.json browser.*", "config.yaml browser",- "migrated")-- # Archive remaining browser settings- advanced = {k: v for k, v in browser.items()- if k not in {"cdpUrl", "headless"} and v}- if advanced and self.archive_dir:- if self.execute:- self.archive_dir.mkdir(parents=True, exist_ok=True)- dest = self.archive_dir / "browser-config.json"- dest.write_text(json.dumps(advanced, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")- self.record("browser-config", "openclaw.json browser (advanced)",- "archive/browser-config.json", "archived")-- # ── Tools config ──────────────────────────────────────────- def migrate_tools_config(self, config: Optional[dict[str, Any]] = None) -> None:- config = config or self.load_openclaw_config()- tools = config.get("tools") or {}- if not tools:- self.record("tools-config", None, None, "skipped", "No tools configuration found")- return-- hermes_cfg_path = self.target_root / "config.yaml"- hermes_cfg = load_yaml_file(hermes_cfg_path)- changed = False-- # Map exec timeout -> terminal timeout (field is timeoutSec in OpenClaw)- exec_cfg = tools.get("exec") or {}- timeout_val = exec_cfg.get("timeoutSec") or exec_cfg.get("timeout")- if timeout_val:- terminal_cfg = hermes_cfg.get("terminal") or {}- terminal_cfg["timeout"] = timeout_val- hermes_cfg["terminal"] = terminal_cfg- changed = True-- # Map web search API key (path: tools.web.search.brave.apiKey in OpenClaw)- web_cfg = tools.get("web") or tools.get("webSearch") or {}- search_cfg = web_cfg.get("search") or web_cfg if not web_cfg.get("search") else web_cfg["search"]- brave_cfg = search_cfg.get("brave") or {}- brave_key = brave_cfg.get("apiKey") or search_cfg.get("braveApiKey") or web_cfg.get("braveApiKey")- if brave_key and isinstance(brave_key, str) and self.migrate_secrets:- self._set_env_var("BRAVE_API_KEY", brave_key, "tools.web.search.brave.apiKey")-- if changed and self.execute:- self.maybe_backup(hermes_cfg_path)- dump_yaml_file(hermes_cfg_path, hermes_cfg)- self.record("tools-config", "openclaw.json tools.*", "config.yaml terminal",- "migrated")-- # Archive full tools config- if self.archive_dir:- if self.execute:- self.archive_dir.mkdir(parents=True, exist_ok=True)- dest = self.archive_dir / "tools-config.json"- dest.write_text(json.dumps(tools, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")- self.record("tools-config", "openclaw.json tools (full)", "archive/tools-config.json",- "archived", "Full tools config archived for reference")-- # ── Approvals config ──────────────────────────────────────- def migrate_approvals_config(self, config: Optional[dict[str, Any]] = None) -> None:- config = config or self.load_openclaw_config()- approvals = config.get("approvals") or {}- if not approvals:- self.record("approvals-config", None, None, "skipped", "No approvals configuration found")- return-- hermes_cfg_path = self.target_root / "config.yaml"- hermes_cfg = load_yaml_file(hermes_cfg_path)-- # Map approval mode (nested under approvals.exec.mode in OpenClaw)- exec_approvals = approvals.get("exec") or {}- mode = (exec_approvals.get("mode") if isinstance(exec_approvals, dict) else None) or approvals.get("mode") or approvals.get("defaultMode")- if mode:- mode_map = {"auto": "off", "always": "manual", "smart": "smart", "manual": "manual"}- hermes_mode = mode_map.get(mode, "manual")- hermes_cfg.setdefault("approvals", {})["mode"] = hermes_mode- if self.execute:- self.maybe_backup(hermes_cfg_path)- dump_yaml_file(hermes_cfg_path, hermes_cfg)- self.record("approvals-config", "openclaw.json approvals.mode",- "config.yaml approvals.mode", "migrated", f"Mapped '{mode}' -> '{hermes_mode}'")-- # Archive full approvals config- if len(approvals) > 1 and self.archive_dir:- if self.execute:- self.archive_dir.mkdir(parents=True, exist_ok=True)- dest = self.archive_dir / "approvals-config.json"- dest.write_text(json.dumps(approvals, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")- self.record("approvals-config", "openclaw.json approvals (rules)",- "archive/approvals-config.json", "archived")-- # ── Memory backend ────────────────────────────────────────- def migrate_memory_backend(self, config: Optional[dict[str, Any]] = None) -> None:- config = config or self.load_openclaw_config()- memory = config.get("memory") or {}- if not memory:- self.record("memory-backend", None, None, "skipped", "No memory backend configuration found")- return-- if self.archive_dir and self.execute:- self.archive_dir.mkdir(parents=True, exist_ok=True)- dest = self.archive_dir / "memory-backend-config.json"- dest.write_text(json.dumps(memory, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")- self.record("memory-backend", "openclaw.json memory.*", "archive/memory-backend-config.json",- "archived", "Memory backend config (QMD, vector search, citations) archived for manual review")-- # ── Skills config ─────────────────────────────────────────- def migrate_skills_config(self, config: Optional[dict[str, Any]] = None) -> None:- config = config or self.load_openclaw_config()- skills = config.get("skills") or {}- entries = skills.get("entries") or {}- if not entries and not skills:- self.record("skills-config", None, None, "skipped", "No skills registry configuration found")- return-- if self.archive_dir and self.execute:- self.archive_dir.mkdir(parents=True, exist_ok=True)- dest = self.archive_dir / "skills-registry-config.json"- dest.write_text(json.dumps(skills, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")- self.record("skills-config", "openclaw.json skills.*", "archive/skills-registry-config.json",- "archived", f"Skills registry config ({len(entries)} entries) archived")-- # ── UI / Identity ─────────────────────────────────────────- def migrate_ui_identity(self, config: Optional[dict[str, Any]] = None) -> None:- config = config or self.load_openclaw_config()- ui = config.get("ui") or {}- if not ui:- self.record("ui-identity", None, None, "skipped", "No UI/identity configuration found")- return-- if self.archive_dir and self.execute:- self.archive_dir.mkdir(parents=True, exist_ok=True)- dest = self.archive_dir / "ui-identity-config.json"- dest.write_text(json.dumps(ui, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")- self.record("ui-identity", "openclaw.json ui.*", "archive/ui-identity-config.json",- "archived", "UI theme and identity settings archived")-- # ── Logging / Diagnostics ─────────────────────────────────- def migrate_logging_config(self, config: Optional[dict[str, Any]] = None) -> None:- config = config or self.load_openclaw_config()- logging_cfg = config.get("logging") or {}- diagnostics = config.get("diagnostics") or {}- combined = {}- if logging_cfg:- combined["logging"] = logging_cfg- if diagnostics:- combined["diagnostics"] = diagnostics- if not combined:- self.record("logging-config", None, None, "skipped", "No logging/diagnostics configuration found")- return-- if self.archive_dir and self.execute:- self.archive_dir.mkdir(parents=True, exist_ok=True)- dest = self.archive_dir / "logging-diagnostics-config.json"- dest.write_text(json.dumps(combined, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")- self.record("logging-config", "openclaw.json logging/diagnostics",- "archive/logging-diagnostics-config.json", "archived")-- # ── Helper: set env var ───────────────────────────────────- def _set_env_var(self, key: str, value: str, source_label: str) -> None:- env_path = self.target_root / ".env"- if self.execute:- env_data = parse_env_file(env_path)- if key in env_data and not self.overwrite:- self.record("env-var", source_label, f".env {key}", "conflict",- f"Env var {key} already set")- return- env_data[key] = value- save_env_file(env_path, env_data)- self.record("env-var", source_label, f".env {key}", "migrated")-- # ── Generate migration notes ──────────────────────────────- def generate_migration_notes(self) -> None:- if not self.output_dir:- return- notes = [- "# OpenClaw -> Hermes Migration Notes",- "",- "This document lists items that require manual attention after migration.",- "",- "## PM2 / External Processes",- "",- "Your PM2 processes (Discord bots, Telegram bots, etc.) are NOT affected",- "by this migration. They run independently and will continue working.",- "No action needed for PM2-managed processes.",- "",- ]-- archived = [i for i in self.items if i.status == "archived"]- if archived:- notes.extend([- "## Archived Items (Manual Review Needed)",- "",- "These OpenClaw configurations were archived because they don't have a",- "direct 1:1 mapping in Hermes. Review each file and recreate manually:",- "",- ])- for item in archived:- notes.append(f"- **{item.kind}**: `{item.destination}` -- {item.reason}")- notes.append("")-- conflicts = [i for i in self.items if i.status == "conflict"]- if conflicts:- notes.extend([- "## Conflicts (Existing Hermes Config Not Overwritten)",- "",- "These items already existed in your Hermes config. Re-run with",- "`--overwrite` to force, or merge manually:",- "",- ])- for item in conflicts:- notes.append(f"- **{item.kind}**: {item.reason}")- notes.append("")-- has_cron_config_archive = any(- i.kind == "cron-jobs" and i.status == "archived" and i.destination and i.destination.endswith("cron-config.json")- for i in self.items- )- has_cron_store_archive = any(- i.kind == "cron-jobs" and i.status == "archived" and i.destination and i.destination.endswith("cron-store")- for i in self.items- )-- notes.extend([- "## IMPORTANT: Archive the OpenClaw Directory",- "",- "After migration, your OpenClaw directory still exists on disk with workspace",- "state files (todo.json, sessions, logs). If the Hermes agent discovers these",- "directories, it may read/write to them instead of the Hermes state, causing",- "confusion (e.g., cron jobs reading a different todo list than interactive sessions).",- "",- "**Strongly recommended:** Run `hermes claw cleanup` to rename the OpenClaw",- "directory to `.openclaw.pre-migration`. This prevents the agent from finding it.",- "The directory is renamed, not deleted — you can undo this at any time.",- "",- "If you skip this step and notice the agent getting confused about workspaces",- "or todo lists, run `hermes claw cleanup` to fix it.",- "",- "## Hermes-Specific Setup",- "",- "After migration, you may want to:",- "- Run `hermes claw cleanup` to archive the OpenClaw directory (prevents state confusion)",- "- Run `hermes setup` to configure any remaining settings",- "- Run `hermes mcp list` to verify MCP servers were imported correctly",- ])-- if has_cron_config_archive:- notes.append("- Run `hermes cron` to recreate scheduled tasks (see archive/cron-config.json)")- elif has_cron_store_archive:- notes.append("- Run `hermes cron` to recreate scheduled tasks (see archived cron-store)")-- # Check if skills were imported- has_skills = any(i.kind == "skills" and i.status == "migrated" for i in self.items)- if has_skills:- notes.extend([- "",- "## Imported Skills",- "",- "Imported skills require a new session to take effect. After migration,",- "restart your agent or start a new chat session, then run `/skills`",- "to verify they loaded correctly.",- "",- ])-- # Check if WhatsApp was detected- has_whatsapp = any(i.kind == "whatsapp-settings" and i.status == "migrated" for i in self.items)- if has_whatsapp:- notes.extend([- "",- "## WhatsApp Requires Re-Pairing",- "",- "WhatsApp uses QR-code pairing, not token-based auth. Your allowlist",- "was migrated, but you must re-pair the device by running:",- "",- " hermes whatsapp",- "",- ])-- notes.extend([- "- Run `hermes gateway install` if you need the gateway service",- "- Review `~/.hermes/config.yaml` for any adjustments",- "",- ])-- if self.execute:- self.output_dir.mkdir(parents=True, exist_ok=True)- (self.output_dir / "MIGRATION_NOTES.md").write_text(- "\n".join(notes) + "\n", encoding="utf-8"- )---def parse_args() -> argparse.Namespace:- parser = argparse.ArgumentParser(description="Migrate OpenClaw user state into Hermes Agent.")- parser.add_argument("--source", default=str(Path.home() / ".openclaw"), help="OpenClaw home directory")- parser.add_argument("--target", default=os.environ.get("HERMES_HOME") or str(Path.home() / ".hermes"), help="Hermes home directory")- parser.add_argument(- "--workspace-target",- help="Optional workspace root where the workspace instructions file should be copied",- )- parser.add_argument("--execute", action="store_true", help="Apply changes instead of reporting a dry run")- parser.add_argument("--overwrite", action="store_true", help="Overwrite existing Hermes targets after backing them up")- parser.add_argument(- "--migrate-secrets",- action="store_true",- help="Import a narrow allowlist of Hermes-compatible secrets into the target env file",- )- parser.add_argument(- "--skill-conflict",- choices=sorted(SKILL_CONFLICT_MODES),- default="skip",- help="How to handle imported skill directory conflicts: skip, overwrite, or rename the imported copy.",- )- parser.add_argument(- "--preset",- choices=sorted(MIGRATION_PRESETS),- help="Apply a named migration preset. 'user-data' excludes allowlisted secrets; 'full' includes all compatible groups.",- )- parser.add_argument(- "--include",- action="append",- default=[],- help="Comma-separated migration option ids to include (default: all). "- f"Valid ids: {', '.join(sorted(MIGRATION_OPTION_METADATA))}",- )- parser.add_argument(- "--exclude",- action="append",- default=[],- help="Comma-separated migration option ids to skip. "- f"Valid ids: {', '.join(sorted(MIGRATION_OPTION_METADATA))}",- )- parser.add_argument("--output-dir", help="Where to write report, backups, and archived docs")- parser.add_argument(- "--json",- action="store_true",- dest="json_output",- help="Print the migration report as JSON on stdout (redacted). "- "Combine with no --execute for a safe plan-only machine-readable preview.",- )- return parser.parse_args()---def main() -> int:- args = parse_args()- try:- selected_options = resolve_selected_options(args.include, args.exclude, preset=args.preset)- except ValueError as exc:- print(json.dumps({"error": str(exc)}, indent=2, ensure_ascii=False))- return 2- migrator = Migrator(- source_root=Path(os.path.expanduser(args.source)).resolve(),- target_root=Path(os.path.expanduser(args.target)).resolve(),- execute=bool(args.execute),- workspace_target=Path(os.path.expanduser(args.workspace_target)).resolve() if args.workspace_target else None,- overwrite=bool(args.overwrite),- migrate_secrets=bool(args.migrate_secrets),- output_dir=Path(os.path.expanduser(args.output_dir)).resolve() if args.output_dir else None,- selected_options=selected_options,- preset_name=args.preset or "",- skill_conflict_mode=args.skill_conflict,- )- report = migrator.migrate()-- # ── Machine-readable JSON mode ────────────────────────────- # When --json is set, print the redacted report to stdout and skip the- # human-readable terminal recap. Useful for CI and scripted wrappers.- if getattr(args, "json_output", False):- print(json.dumps(redact_migration_value(report), indent=2, ensure_ascii=False))- return 0-- # ── Human-readable terminal recap ─────────────────────────- s = report["summary"]- items = report["items"]- mode_label = "DRY RUN" if not args.execute else "EXECUTED"- total = sum(s.values())-- print()- print(" ╔══════════════════════════════════════════════════════╗")- print(f" ║ OpenClaw -> Hermes Migration [{mode_label:>8s}] ║")- print(" ╠══════════════════════════════════════════════════════╣")- print(f" ║ Source: {str(report['source_root'])[:42]:<42s} ║")- print(f" ║ Target: {str(report['target_root'])[:42]:<42s} ║")- print(" ╠══════════════════════════════════════════════════════╣")- print(f" ║ ✔ Migrated: {s.get('migrated', 0):>3d} ◆ Archived: {s.get('archived', 0):>3d} ║")- print(f" ║ ⊘ Skipped: {s.get('skipped', 0):>3d} ⚠ Conflicts: {s.get('conflict', 0):>3d} ║")- print(f" ║ ✖ Errors: {s.get('error', 0):>3d} Total: {total:>3d} ║")- print(" ╚══════════════════════════════════════════════════════╝")-- # Show what was migrated- migrated = [i for i in items if i["status"] == "migrated"]- if migrated:- print()- print(" Migrated:")- seen_kinds = set()- for item in migrated:- label = item["kind"]- if label in seen_kinds:- continue- seen_kinds.add(label)- dest = item.get("destination") or ""- if dest.startswith(str(report["target_root"])):- dest = "~/.hermes/" + dest[len(str(report["target_root"])) + 1:]- meta = MIGRATION_OPTION_METADATA.get(label, {})- display = meta.get("label", label)- print(f" ✔ {display:<35s} -> {dest}")-- # Show what was archived- archived = [i for i in items if i["status"] == "archived"]- if archived:- print()- print(" Archived (manual review needed):")- seen_kinds = set()- for item in archived:- label = item["kind"]- if label in seen_kinds:- continue- seen_kinds.add(label)- reason = item.get("reason", "")- meta = MIGRATION_OPTION_METADATA.get(label, {})- display = meta.get("label", label)- short_reason = reason[:50] + "..." if len(reason) > 50 else reason- print(f" ◆ {display:<35s} {short_reason}")-- # Show conflicts- conflicts = [i for i in items if i["status"] == "conflict"]- if conflicts:- print()- print(" Conflicts (use --overwrite to force):")- for item in conflicts:- print(f" ⚠ {item['kind']}: {item.get('reason', '')}")-- # Show errors- errors = [i for i in items if i["status"] == "error"]- if errors:- print()- print(" Errors:")- for item in errors:- print(f" ✖ {item['kind']}: {item.get('reason', '')}")-- # PM2 reassurance- print()- print(" ℹ PM2 processes (Discord/Telegram bots) are NOT affected.")-- # Next steps- if args.execute:- print()- print(" Next steps:")- print(" 1. Review ~/.hermes/config.yaml")- print(" 2. Run: hermes mcp list")- if any(i["kind"] == "cron-jobs" and i["status"] == "archived" for i in items):- print(" 3. Recreate cron jobs: hermes cron")- if report.get("output_dir"):- print(f" → Full report: {report['output_dir']}/MIGRATION_NOTES.md")- elif not args.execute:- print()- print(" This was a dry run. Add --execute to apply changes.")-- print()-- # Also dump JSON for programmatic use- if os.environ.get("MIGRATION_JSON_OUTPUT"):- print(json.dumps(report, indent=2, ensure_ascii=False))-- return 0 if s.get("error", 0) == 0 else 1---if __name__ == "__main__":- raise SystemExit(main())diff --git a/skills/autonomous-ai-agents/hermes-agent/references/cli-reference.md b/skills/autonomous-ai-agents/hermes-agent/references/cli-reference.mdindex 1104b1bdadb..ec8b1b8a17d 100644--- a/skills/autonomous-ai-agents/hermes-agent/references/cli-reference.md+++ b/skills/autonomous-ai-agents/hermes-agent/references/cli-reference.md@@ -133,10 +133,10 @@ hermes send One-off message through a gateway platformhermes pairing / plugins / insights / journey / computer-usehermes acp ACP server (IDE integration)hermes completion bash|zsh|fish-hermes update / uninstall / claw migrate+hermes update / uninstall```-Plugin- and provider-supplied subcommands (e.g. `hermes photon setup`) only appear once their plugin is installed/active.+Plugin- and provider-supplied subcommands (e.g. `hermes photon setup`) only appear once their plugin is installed/active. Importing from OpenClaw, Claude Code, Codex CLI or Cursor (`hermes import-agent <agent>`, plus the older `hermes claw migrate|cleanup`) comes from the `agent-importers` plugin; a fresh `hermes setup` that finds one of those agents offers to install it.### Where to Find Thingsdiff --git a/tests/hermes_cli/test_agent_import_left_core.py b/tests/hermes_cli/test_agent_import_left_core.pyindex 185315efe8f..a9bef2701a1 100644--- a/tests/hermes_cli/test_agent_import_left_core.py+++ b/tests/hermes_cli/test_agent_import_left_core.py@@ -1,4 +1,5 @@-"""`hermes import-agent` left core for the agent-importers catalog plugin.+"""`hermes import-agent` and `hermes claw` (OpenClaw migration) 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 arestand-ins (the live install is exercised end to end outside the unit suite).@@ -21,11 +22,12 @@ def _fresh(monkeypatch):monkeypatch.setattr(mpm, "catalog_source", lambda name: name)-def test_old_spelling_without_the_plugin_names_the_install(tmp_path, monkeypatch, capsys):[email protected]("argv", [["import-agent", "claude-code", "--dry-run"], ["claw", "migrate", "--dry-run"]])+def test_old_spelling_without_the_plugin_names_the_install(argv, 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"])+ monkeypatch.setattr(sys, "argv", ["hermes", *argv])from hermes_cli.main import _build_cli_parserparser, _subparsers = _build_cli_parser()@@ -33,7 +35,7 @@ def test_old_spelling_without_the_plugin_names_the_install(tmp_path, monkeypatchparser.parse_args(sys.argv[1:])err = capsys.readouterr().errassert exc.value.code == 2- assert "moved out of core into the 'agent-importers' plugin, which is not loaded" in err+ assert f"`hermes {argv[0]}` moved out of core into the 'agent-importers' plugin, which is not loaded" in errassert "hermes plugins install agent-importers" in errdiff --git a/tests/hermes_cli/test_backup.py b/tests/hermes_cli/test_backup.pyindex d2230f085c5..f8913257ea2 100644--- a/tests/hermes_cli/test_backup.py+++ b/tests/hermes_cli/test_backup.py@@ -2041,12 +2041,12 @@ class TestRunPreUpdateBackup:# ----------------------------------------------------------------------------# Pre-migration backup (hermes claw migrate safety net)+# Pre-migration backup (safety net for agent imports, e.g. hermes import-agent openclaw)# ---------------------------------------------------------------------------class TestPreMigrationBackup:"""Tests for create_pre_migration_backup — the auto-backup- ``hermes claw migrate`` runs before mutating ~/.hermes/."""+ ``hermes import-agent openclaw`` runs before mutating ~/.hermes/."""@pytest.fixturedef hermes_home(self, tmp_path):diff --git a/tests/hermes_cli/test_claw.py b/tests/hermes_cli/test_claw.pydeleted file mode 100644index 03e4533f70c..00000000000--- a/tests/hermes_cli/test_claw.py+++ /dev/null@@ -1,366 +0,0 @@-"""Tests for hermes claw commands."""--from argparse import Namespace-import subprocess-from types import ModuleType-from unittest.mock import MagicMock, patch--import pytest--from hermes_cli import claw as claw_mod---# ----------------------------------------------------------------------------# _find_migration_script-# ------------------------------------------------------------------------------class TestFindMigrationScript:- """Test script discovery in known locations."""-- def test_finds_project_root_script(self, tmp_path):- script = tmp_path / "openclaw_to_hermes.py"- script.write_text("# placeholder", encoding="utf-8")- with patch.object(claw_mod, "_OPENCLAW_SCRIPT", script):- assert claw_mod._find_migration_script() == script---# ----------------------------------------------------------------------------# _find_openclaw_dirs-# ------------------------------------------------------------------------------class TestFindOpenclawDirs:- """Test discovery of OpenClaw directories."""-- def test_finds_openclaw_dir(self, tmp_path):- openclaw = tmp_path / ".openclaw"- openclaw.mkdir()- with patch("pathlib.Path.home", return_value=tmp_path):- found = claw_mod._find_openclaw_dirs()- assert openclaw in found-- def test_finds_legacy_dirs(self, tmp_path):- clawdbot = tmp_path / ".clawdbot"- clawdbot.mkdir()- moltbot = tmp_path / ".moltbot"- moltbot.mkdir()- with patch("pathlib.Path.home", return_value=tmp_path):- found = claw_mod._find_openclaw_dirs()- assert len(found) == 2- assert clawdbot in found- assert moltbot in found---# ----------------------------------------------------------------------------# _scan_workspace_state-# ------------------------------------------------------------------------------class TestScanWorkspaceState:- """Test scanning for workspace state files."""-- def test_finds_root_state_files(self, tmp_path):- (tmp_path / "todo.json").write_text("{}", encoding="utf-8")- (tmp_path / "sessions").mkdir()- findings = claw_mod._scan_workspace_state(tmp_path)- descs = [desc for _, desc in findings]- assert any("todo.json" in d for d in descs)- assert any("sessions" in d for d in descs)--- def test_ignores_hidden_dirs(self, tmp_path):- scan_dir = tmp_path / "scan_target"- scan_dir.mkdir()- hidden = scan_dir / ".git"- hidden.mkdir()- (hidden / "todo.json").write_text("{}", encoding="utf-8")- findings = claw_mod._scan_workspace_state(scan_dir)- assert len(findings) == 0---# ----------------------------------------------------------------------------# _archive_directory-# ------------------------------------------------------------------------------class TestArchiveDirectory:- """Test directory archival (rename)."""-- def test_renames_to_pre_migration(self, tmp_path):- source = tmp_path / ".openclaw"- source.mkdir()- (source / "test.txt").write_text("data", encoding="utf-8")-- archive_path = claw_mod._archive_directory(source)- assert archive_path == tmp_path / ".openclaw.pre-migration"- assert archive_path.is_dir()- assert not source.exists()- assert (archive_path / "test.txt").read_text(encoding="utf-8") == "data"-- def test_adds_timestamp_when_archive_exists(self, tmp_path):- source = tmp_path / ".openclaw"- source.mkdir()- # Pre-existing archive- (tmp_path / ".openclaw.pre-migration").mkdir()-- archive_path = claw_mod._archive_directory(source)- assert ".pre-migration-" in archive_path.name- assert archive_path.is_dir()- assert not source.exists()-- def test_dry_run_does_not_rename(self, tmp_path):- source = tmp_path / ".openclaw"- source.mkdir()-- archive_path = claw_mod._archive_directory(source, dry_run=True)- assert archive_path == tmp_path / ".openclaw.pre-migration"- assert source.is_dir() # Still exists---# ----------------------------------------------------------------------------# claw_command routing-# --------------------------------------------------------------------------------# ----------------------------------------------------------------------------# _cmd_migrate-# ------------------------------------------------------------------------------class TestCmdMigrate:- """Test the migrate command handler."""-- @pytest.fixture(autouse=True)- def _mock_openclaw_running(self):- with patch.object(claw_mod, "_detect_openclaw_processes", return_value=[]):- yield---------- def test_full_preset_does_not_enable_secrets_silently(self, tmp_path, capsys):- """The 'full' preset must NOT auto-enable migrate_secrets.-- Users have to opt in to secret import explicitly via --migrate-secrets,- even under the 'full' preset. This mirrors OpenClaw's migrate-hermes- posture (two-phase import) and prevents a 'full' run from silently- copying API keys.- """- openclaw_dir = tmp_path / ".openclaw"- openclaw_dir.mkdir()-- fake_mod = ModuleType("openclaw_to_hermes")- fake_mod.resolve_selected_options = MagicMock(return_value=set())- fake_migrator = MagicMock()- fake_migrator.migrate.return_value = {- "summary": {"migrated": 0, "skipped": 0, "conflict": 0, "error": 0},- "items": [],- }- fake_mod.Migrator = MagicMock(return_value=fake_migrator)-- args = Namespace(- source=str(openclaw_dir),- dry_run=True, preset="full", overwrite=False,- migrate_secrets=False, # Not explicitly set by user- workspace_target=None,- skill_conflict="skip", yes=False,- no_backup=False,- )-- with (- patch.object(claw_mod, "_find_migration_script", return_value=tmp_path / "s.py"),- patch.object(claw_mod, "_load_migration_module", return_value=fake_mod),- patch.object(claw_mod, "get_config_path", return_value=tmp_path / "config.yaml"),- patch.object(claw_mod, "save_config"),- patch.object(claw_mod, "load_config", return_value={}),- ):- claw_mod._cmd_migrate(args)-- # Migrator should have been called with migrate_secrets=False — the- # 'full' preset on its own no longer opts the user into secret import.- call_kwargs = fake_mod.Migrator.call_args[1]- assert call_kwargs["migrate_secrets"] is False-- def test_full_preset_with_explicit_migrate_secrets_passes_through(self, tmp_path, capsys):- """Explicit --migrate-secrets still works under --preset full."""- openclaw_dir = tmp_path / ".openclaw"- openclaw_dir.mkdir()-- fake_mod = ModuleType("openclaw_to_hermes")- fake_mod.resolve_selected_options = MagicMock(return_value=set())- fake_migrator = MagicMock()- fake_migrator.migrate.return_value = {- "summary": {"migrated": 0, "skipped": 0, "conflict": 0, "error": 0},- "items": [],- }- fake_mod.Migrator = MagicMock(return_value=fake_migrator)-- args = Namespace(- source=str(openclaw_dir),- dry_run=True, preset="full", overwrite=False,- migrate_secrets=True, # Explicitly requested- workspace_target=None,- skill_conflict="skip", yes=False,- no_backup=False,- )-- with (- patch.object(claw_mod, "_find_migration_script", return_value=tmp_path / "s.py"),- patch.object(claw_mod, "_load_migration_module", return_value=fake_mod),- patch.object(claw_mod, "get_config_path", return_value=tmp_path / "config.yaml"),- patch.object(claw_mod, "save_config"),- patch.object(claw_mod, "load_config", return_value={}),- ):- claw_mod._cmd_migrate(args)-- call_kwargs = fake_mod.Migrator.call_args[1]- assert call_kwargs["migrate_secrets"] is True---# ----------------------------------------------------------------------------# _cmd_cleanup-# ------------------------------------------------------------------------------class TestCmdCleanup:- """Test the cleanup command handler."""-- @pytest.fixture(autouse=True)- def _mock_openclaw_running(self):- with patch.object(claw_mod, "_detect_openclaw_processes", return_value=[]):- yield--- def test_dry_run_lists_dirs(self, tmp_path, capsys):- openclaw = tmp_path / ".openclaw"- openclaw.mkdir()- ws = openclaw / "workspace"- ws.mkdir()- (ws / "todo.json").write_text("{}", encoding="utf-8")-- args = Namespace(source=None, dry_run=True, yes=False)- with patch.object(claw_mod, "_find_openclaw_dirs", return_value=[openclaw]):- claw_mod._cmd_cleanup(args)-- captured = capsys.readouterr()- assert "Would archive" in captured.out- assert openclaw.is_dir() # Not actually archived--- def test_explicit_source(self, tmp_path, capsys):- custom_dir = tmp_path / "my-openclaw"- custom_dir.mkdir()- (custom_dir / "todo.json").write_text("{}", encoding="utf-8")-- args = Namespace(source=str(custom_dir), dry_run=False, yes=True)- claw_mod._cmd_cleanup(args)-- captured = capsys.readouterr()- assert "Archived" in captured.out- assert not custom_dir.exists()-----# ----------------------------------------------------------------------------# _print_migration_report-# --------------------------------------------------------------------------------class TestDetectOpenclawProcesses:-- @pytest.mark.platforms("linux")- def test_reports_union_of_exact_and_node_matches(self):- with patch.object(claw_mod, "subprocess") as mock_subprocess:- mock_subprocess.run.side_effect = [- MagicMock(returncode=1, stdout=""), # systemctl- MagicMock(returncode=0, stdout="1234\n"), # pgrep -x openclaw- MagicMock(returncode=1, stdout=""), # pgrep -x openclaw-gatewa- MagicMock(returncode=1, stdout=""), # pgrep -x clawd- MagicMock(returncode=0, stdout="1234\n5678\n"), # node cmdline probe- ]- mock_subprocess.TimeoutExpired = subprocess.TimeoutExpired- result = claw_mod._detect_openclaw_processes()- assert result == ["openclaw process(es) (PIDs: 1234, 5678)"]-- @pytest.mark.platforms("linux")- def test_live_pgrep_ignores_argv_mentions_but_finds_node_openclaw(self, tmp_path):- """A process that merely mentions "openclaw" in argv (the #12648 false positive) is not- OpenClaw; a node interpreter running an openclaw script is."""- from pathlib import Path- import time-- # Nix's sys.executable can be a launcher that re-execs Python,- # discarding both exec -a's argv[0] and the copied binary's comm.- # Exercise actual process names with the running interpreter binary.- executable = Path("/proc/self/exe").resolve()- idle = f'{executable} -c "import time; time.sleep(30)"'- # argv mentions openclaw but the binary is not one.- bystander = subprocess.Popen(["bash", "-c", f"exec {idle} {tmp_path}/openclaw-notes.txt"])- # argv[0] renamed to ``node`` running an openclaw script: the real launch shape.- node_like = subprocess.Popen(["bash", "-c", f"exec -a node {idle} {tmp_path}/openclaw/entry.js"])- # The gateway sets process.title="openclaw-gateway" (comm truncates to 15 chars); a- # copied interpreter with that file name yields the same comm.- import shutil- titled_bin = tmp_path / "openclaw-gateway"- shutil.copy2(executable, titled_bin)- titled = subprocess.Popen([str(titled_bin), "-c", "import time; time.sleep(30)"])- try:- time.sleep(0.3)- with patch.object(claw_mod, "_posix_probe", wraps=claw_mod._posix_probe) as probe:- result = claw_mod._detect_openclaw_processes()- assert not any(a[0][:2] == ["pgrep", "-f"] and a[0][2] == "openclaw" for a, _ in probe.call_args_list)- assert len(result) == 1- pids = result[0].split("PIDs: ")[1].rstrip(")").split(", ")- assert str(node_like.pid) in pids- assert str(titled.pid) in pids- assert str(bystander.pid) not in pids- finally:- for proc in (bystander, node_like, titled):- proc.kill()- proc.wait()--- @pytest.mark.platforms("windows")- def test_returns_empty_on_windows_when_nothing_found(self):- """Faking win32 picked the tasklist/powershell branch on a host that has- neither; only a real Windows host resolves those executables.-- ``return_value`` rather than a ``side_effect`` list: the branch's call- count is not the assertion, and pinning it breaks whenever the host- shells out once more than the dev box did.- """- with patch.object(claw_mod, "subprocess") as mock_subprocess:- mock_subprocess.run.return_value = MagicMock(returncode=0, stdout="")- result = claw_mod._detect_openclaw_processes()- assert result == []---class TestWarnIfOpenclawRunning:- def test_noop_when_not_running(self, capsys):- with patch.object(claw_mod, "_detect_openclaw_processes", return_value=[]):- claw_mod._warn_if_openclaw_running(auto_yes=False)- captured = capsys.readouterr()- assert captured.out == ""-- def test_warns_and_exits_when_running_and_user_declines(self, capsys):- with patch.object(claw_mod, "_detect_openclaw_processes", return_value=["openclaw process(es) (PIDs: 1234)"]):- with patch.object(claw_mod, "prompt_yes_no", return_value=False):- with patch.object(claw_mod.sys.stdin, "isatty", return_value=True):- with pytest.raises(SystemExit) as exc_info:- claw_mod._warn_if_openclaw_running(auto_yes=False)- assert exc_info.value.code == 0- captured = capsys.readouterr()- assert "OpenClaw appears to be running" in captured.out--diff --git a/tests/hermes_cli/test_multiplex_host_topology_reporting.py b/tests/hermes_cli/test_multiplex_host_topology_reporting.pyindex 9bb8aee8e5a..443227947ed 100644--- a/tests/hermes_cli/test_multiplex_host_topology_reporting.py+++ b/tests/hermes_cli/test_multiplex_host_topology_reporting.py@@ -5,7 +5,6 @@ Invariants (all fail on origin/main):user to start a second process.* ``hermes -p <served> doctor`` reports the single host gateway + its roster, not"Per-profile gateways: up/total", and still checks the HOST systemd unit's linger.-* ``hermes claw``'s destructive-action warning FIRES for a served profile.* the state.db holder line names the shared host process and the profiles it serves."""@@ -55,21 +54,6 @@ def test_cron_status_names_the_host_gateway_for_a_served_profile(served_host, caassert "sudo hermes gateway install --system" not in out-def test_claw_warning_fires_for_a_served_profile(served_host, capsys, monkeypatch):- from hermes_cli import claw-- (served_host / "gateway_state.json").write_text(json.dumps(- {"served_profiles": ["default", "served"],- "platforms": {"served:telegram": {"state": "connected"}, "telegram": {"state": "connected"}}}))- fired = []- monkeypatch.setattr(claw, "_warn_running", lambda *a, **k: fired.append(a) or True)-- claw._warn_if_gateway_running(auto_yes=True)-- assert fired, "destructive-action warning was silently skipped for a served profile"- assert "telegram" in fired[0][1]--def test_doctor_reports_the_single_host_gateway_not_per_profile_slots(served_host, capsys, monkeypatch):from hermes_cli import doctor_platformdiff --git a/tests/hermes_cli/test_setup_agent_import.py b/tests/hermes_cli/test_setup_agent_import.pynew file mode 100644index 00000000000..51b8b6cde3f--- /dev/null+++ b/tests/hermes_cli/test_setup_agent_import.py@@ -0,0 +1,101 @@+"""`hermes setup`'s "Coming from another agent?" step: it offers only the agents found on disk, installs+the agent-importers plugin through the catalog install only after a yes, then runs that plugin's+import for each pick.++Real step code, a temp HERMES_HOME and a fake HOME; the terminal prompts, the catalog install (network)+and the child `hermes import-agent` process are stand-ins that record what the step asked for.+"""++from __future__ import annotations++import subprocess++import pytest++from hermes_cli import setup_agent_import as step+++def homes(tmp_path, monkeypatch):+ user_home, hermes_home = tmp_path / "user", tmp_path / "user" / ".hermes"+ hermes_home.mkdir(parents=True)+ for var in ("HOME", "USERPROFILE"):+ monkeypatch.setenv(var, str(user_home))+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))+ monkeypatch.delenv("HERMES_NONINTERACTIVE", raising=False)+ calls: list = []+ answers = {"yes": True, "unpick": set()}++ def ask(question, default=True):+ calls.append(("ask", question, default))+ return answers["yes"]++ def checklist(title, items, pre_selected):+ calls.append(("pick", list(items), list(pre_selected)))+ return [i for i in pre_selected if items[i] not in answers["unpick"]]++ def install(name, enable=None, **_):+ calls.append(("install", name, enable))+ (hermes_home / "plugins" / name).mkdir(parents=True)++ def run(argv, env, check=False):+ calls.append(("import", argv[3:], env["HERMES_HOME"]))+ (hermes_home / "config.yaml").write_text(f"imported: {argv[4]}\n", encoding="utf-8")+ return subprocess.CompletedProcess(argv, 0)++ monkeypatch.setattr("hermes_cli.setup.prompt_yes_no", ask)+ monkeypatch.setattr("hermes_cli.setup.prompt_checklist", checklist)+ monkeypatch.setattr("hermes_cli.plugins_cmd_install.cmd_install", install)+ monkeypatch.setattr(step.subprocess, "run", run)+ return user_home, hermes_home, calls, answers+++def test_found_agent_is_offered_then_installed_from_the_catalog_and_imported(homes):+ user_home, hermes_home, calls, _answers = homes+ (user_home / ".openclaw").mkdir()++ assert step.offer_agent_import(hermes_home) == "OpenClaw"++ assert calls == [+ ("ask", "Import your setup from OpenClaw?", True),+ ("install", "agent-importers", True),+ # core's setup migrated OpenClaw's allowlisted secrets after the preview; so does this step+ ("import", ["import-agent", "openclaw", "--migrate-secrets"], str(hermes_home)),+ ]+++def test_several_found_are_offered_as_a_checklist_and_only_the_picks_import(homes):+ user_home, hermes_home, calls, answers = homes+ for d in (".claude", ".cursor"):+ (user_home / d).mkdir()+ answers["unpick"] = {"Cursor"}++ assert step.offer_agent_import(hermes_home) == "Claude Code"++ assert calls[1] == ("pick", ["Claude Code", "Cursor"], [0, 1]) # never an agent that is absent+ assert calls[2:] == [("install", "agent-importers", True),+ ("import", ["import-agent", "claude-code"], str(hermes_home))]+++def test_declining_installs_nothing(homes):+ user_home, hermes_home, calls, answers = homes+ (user_home / ".codex").mkdir()+ answers["yes"] = False++ assert step.offer_agent_import(hermes_home) == ""++ assert calls == [("ask", "Import your setup from Codex CLI?", True)]+ assert not (hermes_home / "plugins").exists()++[email protected]("headless", [True, False])+def test_headless_or_nothing_found_asks_nothing(headless, homes, monkeypatch):+ user_home, hermes_home, calls, _answers = homes+ if headless: # dashboard/Desktop-spawned setup: no one can answer+ (user_home / ".claude").mkdir()+ monkeypatch.setenv("HERMES_NONINTERACTIVE", "1")++ assert step.offer_agent_import(hermes_home) == ""++ assert calls == []+ assert not (hermes_home / "plugins").exists()diff --git a/tests/hermes_cli/test_setup_openclaw_migration.py b/tests/hermes_cli/test_setup_openclaw_migration.pydeleted file mode 100644index 7d8f0e3456a..00000000000--- a/tests/hermes_cli/test_setup_openclaw_migration.py+++ /dev/null@@ -1,274 +0,0 @@-"""Tests for OpenClaw migration integration in the setup wizard."""--from argparse import Namespace-from types import ModuleType-from unittest.mock import MagicMock, patch--from hermes_cli import setup as setup_mod-from hermes_cli import setup_migration---# ----------------------------------------------------------------------------# _offer_openclaw_migration — unit tests-# ------------------------------------------------------------------------------class TestOfferOpenclawMigration:- """Test the _offer_openclaw_migration helper in isolation."""---- def test_skips_when_user_declines(self, tmp_path):- """Should return False when user declines the migration prompt."""- openclaw_dir = tmp_path / ".openclaw"- openclaw_dir.mkdir()- script = tmp_path / "openclaw_to_hermes.py"- script.write_text("# placeholder")- with (- patch("hermes_cli.setup.Path.home", return_value=tmp_path),- patch.object(setup_migration, "_OPENCLAW_SCRIPT", script),- patch.object(setup_mod, "prompt_yes_no", return_value=False),- ):- assert setup_mod._offer_openclaw_migration(tmp_path / ".hermes") is False-- def test_runs_migration_when_user_accepts(self, tmp_path):- """Should run dry-run preview first, then execute after confirmation."""- openclaw_dir = tmp_path / ".openclaw"- openclaw_dir.mkdir()-- # Create a fake hermes home with config- hermes_home = tmp_path / ".hermes"- hermes_home.mkdir()- config_path = hermes_home / "config.yaml"- config_path.write_text("agent:\n max_turns: 90\n")-- # Build a fake migration module- fake_mod = ModuleType("openclaw_to_hermes")- fake_mod.resolve_selected_options = MagicMock(return_value={"soul", "memory"})- fake_migrator = MagicMock()- fake_migrator.migrate.return_value = {- "summary": {"migrated": 3, "skipped": 1, "conflict": 0, "error": 0},- "items": [{"kind": "config", "status": "migrated", "destination": "/tmp/x"}],- "output_dir": str(hermes_home / "migration"),- }- fake_mod.Migrator = MagicMock(return_value=fake_migrator)-- script = tmp_path / "openclaw_to_hermes.py"- script.write_text("# placeholder")-- with (- patch("hermes_cli.setup.Path.home", return_value=tmp_path),- patch.object(setup_migration, "_OPENCLAW_SCRIPT", script),- # Both prompts answered Yes: preview offer + proceed confirmation- patch.object(setup_mod, "prompt_yes_no", return_value=True),- patch.object(setup_mod, "get_config_path", return_value=config_path),- patch("importlib.util.spec_from_file_location") as mock_spec_fn,- ):- # Wire up the fake module loading- mock_spec = MagicMock()- mock_spec.loader = MagicMock()- mock_spec_fn.return_value = mock_spec-- def exec_module(mod):- mod.resolve_selected_options = fake_mod.resolve_selected_options- mod.Migrator = fake_mod.Migrator-- mock_spec.loader.exec_module = exec_module-- result = setup_mod._offer_openclaw_migration(hermes_home)-- assert result is True- fake_mod.resolve_selected_options.assert_called_once_with(- None, None, preset="full"- )- # Migrator called twice: once for dry-run preview, once for execution- assert fake_mod.Migrator.call_count == 2-- # First call: dry-run preview (execute=False, overwrite=True to show all)- preview_kwargs = fake_mod.Migrator.call_args_list[0][1]- assert preview_kwargs["execute"] is False- assert preview_kwargs["overwrite"] is True- assert preview_kwargs["migrate_secrets"] is True- assert preview_kwargs["preset_name"] == "full"-- # Second call: actual execution (execute=True, overwrite=False to preserve)- exec_kwargs = fake_mod.Migrator.call_args_list[1][1]- assert exec_kwargs["execute"] is True- assert exec_kwargs["overwrite"] is False- assert exec_kwargs["migrate_secrets"] is True- assert exec_kwargs["preset_name"] == "full"-- # migrate() called twice (once per Migrator instance)- assert fake_migrator.migrate.call_count == 2--- def test_handles_migration_error_gracefully(self, tmp_path):- """Should catch exceptions and return False."""- openclaw_dir = tmp_path / ".openclaw"- openclaw_dir.mkdir()- hermes_home = tmp_path / ".hermes"- hermes_home.mkdir()- config_path = hermes_home / "config.yaml"- config_path.write_text("")-- script = tmp_path / "openclaw_to_hermes.py"- script.write_text("# placeholder")-- with (- patch("hermes_cli.setup.Path.home", return_value=tmp_path),- patch.object(setup_migration, "_OPENCLAW_SCRIPT", script),- patch.object(setup_mod, "prompt_yes_no", return_value=True),- patch.object(setup_mod, "get_config_path", return_value=config_path),- patch(- "importlib.util.spec_from_file_location",- side_effect=RuntimeError("boom"),- ),- ):- result = setup_mod._offer_openclaw_migration(hermes_home)-- assert result is False---# ----------------------------------------------------------------------------# Integration with run_setup_wizard — first-time flow-# ------------------------------------------------------------------------------def _first_time_args() -> Namespace:- return Namespace(- section=None,- non_interactive=False,- reset=False,- )-----# ----------------------------------------------------------------------------# _get_section_config_summary / _skip_configured_section — unit tests-# ------------------------------------------------------------------------------class TestGetSectionConfigSummary:- """Test the _get_section_config_summary helper."""-- def test_model_returns_none_without_api_key(self):- with patch.object(setup_mod, "get_env_value", return_value=""):- result = setup_migration._get_section_config_summary({}, "model")- assert result is None----- # Regression tests for issue #13025: the model / gateway summaries used- # stale, hardcoded env-var allowlists that drifted from the real setup +- # status flows. Every case below would previously return ``None`` and- # force OpenClaw migration to re-run setup for an already-configured- # section.----- def test_model_ignores_claude_code_oauth_token(self):- """CLAUDE_CODE_OAUTH_TOKEN is set by Claude Code itself and must not- trigger skip — mirrors the _IMPLICIT_ENV_VARS guard in- is_provider_explicitly_configured()."""- def env_side(key):- return "sk-ant-oat01-xxx" if key == "CLAUDE_CODE_OAUTH_TOKEN" else ""-- with patch.object(setup_mod, "get_env_value", side_effect=env_side):- result = setup_migration._get_section_config_summary({}, "model")- assert result is None-----class TestSkipConfiguredSection:- """Test the _skip_configured_section helper."""--- def test_returns_true_when_user_skips(self):- def env_side(key):- return "sk-xxx" if key == "OPENROUTER_API_KEY" else ""-- with (- patch.object(setup_mod, "get_env_value", side_effect=env_side),- patch.object(setup_mod, "prompt_yes_no", return_value=False),- ):- result = setup_mod._skip_configured_section(- {"model": "openai/gpt-4"}, "model", "Model"- )- assert result is True---class TestSetupWizardSkipsConfiguredSections:- """After migration, already-configured sections should offer skip."""-- def test_sections_skipped_when_migration_imported_settings(self, tmp_path):- """When migration ran and API key exists, model section should be skippable.-- Simulates the real flow: get_env_value returns "" during the is_existing- check (before migration), then returns a key after migration imported it.- """- args = _first_time_args()-- # Track whether migration has "run" — after it does, API key is available- migration_done = {"value": False}-- def env_side(key):- if migration_done["value"] and key == "OPENROUTER_API_KEY":- return "sk-xxx"- return ""-- def fake_migration(hermes_home):- migration_done["value"] = True- return True-- reloaded_config = {"model": "openai/gpt-4"}-- # _platform_status (called by the gateway summary path) reads env- # vars via hermes_cli.gateway.get_env_value, NOT setup_mod's. Patch- # both so sibling tests can't leak a TELEGRAM_BOT_TOKEN /- # WHATSAPP_* / etc. through and trick the wizard into thinking the- # gateway section is already configured (which would skip it).- import hermes_cli.gateway as gateway_mod-- with (- patch.object(setup_mod, "ensure_hermes_home"),- patch.object(- setup_mod, "load_config",- side_effect=[{}, reloaded_config],- ),- patch.object(setup_mod, "get_hermes_home", return_value=tmp_path),- patch.object(setup_mod, "get_env_value", side_effect=env_side),- patch.object(gateway_mod, "get_env_value", side_effect=env_side),- patch.object(setup_mod, "is_interactive_stdin", return_value=True),- patch("hermes_cli.auth.get_active_provider", return_value=None),- patch("builtins.input", return_value=""),- patch.object(setup_mod, "prompt_choice", return_value=1),- # Migration succeeds and flips the env_side flag- patch.object(- setup_mod, "_offer_openclaw_migration",- side_effect=fake_migration,- ),- # User says No to all reconfig prompts- patch.object(setup_mod, "prompt_yes_no", return_value=False),- patch.object(setup_mod, "setup_model_provider") as mock_model,- patch.object(setup_mod, "setup_terminal_backend") as mock_terminal,- patch.object(setup_mod, "setup_agent_settings") as mock_agent,- patch.object(setup_mod, "setup_gateway") as mock_gateway,- patch.object(setup_mod, "setup_tools") as mock_tools,- patch.object(setup_mod, "save_config"),- patch.object(setup_mod, "_print_setup_summary"),- ):- setup_mod.run_setup_wizard(args)-- # Model has API key → skip offered, user said No → section NOT called- mock_model.assert_not_called()- # Terminal/agent always have a summary → skip offered, user said No- mock_terminal.assert_not_called()- mock_agent.assert_not_called()- # Gateway has no tokens (env_side returns "" for gateway keys) → section runs- mock_gateway.assert_called_once()- # Tools have no keys → section runs- mock_tools.assert_called_once()diff --git a/tests/hermes_cli/test_setup_reconfigure.py b/tests/hermes_cli/test_setup_reconfigure.pyindex 0c07b9403a4..afbf3711d28 100644--- a/tests/hermes_cli/test_setup_reconfigure.py+++ b/tests/hermes_cli/test_setup_reconfigure.py@@ -63,7 +63,7 @@ def _enter_existing_install_patches(stack, **extra):("hermes_cli.setup.get_env_value", {"return_value": None}),("hermes_cli.auth.get_active_provider", {"return_value": "openrouter"}),("hermes_cli.setup._print_setup_summary", {}),- ("hermes_cli.setup._offer_openclaw_migration", {"return_value": False}),+ ("hermes_cli.setup.offer_agent_import", {"return_value": ""}),]:stack.enter_context(patch(target, **kwargs))@@ -83,7 +83,7 @@ def _enter_fresh_install_patches(stack, **extra):("hermes_cli.setup.save_config", {}),("hermes_cli.auth.get_active_provider", {"return_value": None}),("hermes_cli.setup.get_env_value", {"return_value": None}),- ("hermes_cli.setup._offer_openclaw_migration", {"return_value": False}),+ ("hermes_cli.setup.offer_agent_import", {"return_value": ""}),]:stack.enter_context(patch(target, **kwargs))diff --git a/tests/skills/test_openclaw_migration.py b/tests/skills/test_openclaw_migration.pydeleted file mode 100644index 7fd75aea16d..00000000000--- a/tests/skills/test_openclaw_migration.py+++ /dev/null@@ -1,699 +0,0 @@-from __future__ import annotations--import importlib.util-import json-import sys-from pathlib import Path---SCRIPT_PATH = (- Path(__file__).resolve().parents[2]- / "optional-skills"- / "migration"- / "openclaw-migration"- / "scripts"- / "openclaw_to_hermes.py"-)---def load_module():- spec = importlib.util.spec_from_file_location("openclaw_to_hermes", SCRIPT_PATH)- module = importlib.util.module_from_spec(spec)- assert spec.loader is not None- sys.modules[spec.name] = module- spec.loader.exec_module(module)- return module---def load_skills_guard():- spec = importlib.util.spec_from_file_location(- "skills_guard_local",- Path(__file__).resolve().parents[2] / "tools" / "skills_guard.py",- )- module = importlib.util.module_from_spec(spec)- assert spec.loader is not None- sys.modules[spec.name] = module- spec.loader.exec_module(module)- return module---def test_extract_markdown_entries_promotes_heading_context():- mod = load_module()- text = """# MEMORY.md - Long-Term Memory--## Tyler Williams--- Founder of VANTA Research-- Timezone: America/Los_Angeles--### Active Projects--- Hermes Agent-"""- entries = mod.extract_markdown_entries(text)- assert "Tyler Williams: Founder of VANTA Research" in entries- assert "Tyler Williams: Timezone: America/Los_Angeles" in entries- assert "Tyler Williams > Active Projects: Hermes Agent" in entries-----def test_merge_entries_respects_limit_and_reports_overflow():- mod = load_module()- existing = ["alpha"]- incoming = ["beta", "gamma is too long"]- merged, stats, overflowed = mod.merge_entries(existing, incoming, limit=12)- assert merged == ["alpha", "beta"]- assert stats["added"] == 1- assert stats["overflowed"] == 1- assert overflowed == ["gamma is too long"]-----------def test_migrator_copies_skill_and_merges_allowlist(tmp_path: Path):- mod = load_module()- source = tmp_path / ".openclaw"- target = tmp_path / ".hermes"- target.mkdir()-- (source / "workspace" / "skills" / "demo-skill").mkdir(parents=True)- (source / "workspace" / "skills" / "demo-skill" / "SKILL.md").write_text(- "---\nname: demo-skill\ndescription: demo\n---\n\nbody\n",- encoding="utf-8",- )- (source / "exec-approvals.json").write_text(- json.dumps(- {- "agents": {- "*": {- "allowlist": [- {"pattern": "/usr/bin/*"},- {"pattern": "/home/test/**"},- ]- }- }- }- ),- encoding="utf-8",- )- (target / "config.yaml").write_text("command_allowlist:\n - /usr/bin/*\n", encoding="utf-8")-- migrator = mod.Migrator(- source_root=source,- target_root=target,- execute=True,- workspace_target=None,- overwrite=False,- migrate_secrets=False,- output_dir=target / "migration-report",- )- report = migrator.migrate()-- imported_skill = target / "skills" / mod.SKILL_CATEGORY_DIRNAME / "demo-skill" / "SKILL.md"- assert imported_skill.exists()- assert "/home/test/**" in (target / "config.yaml").read_text(encoding="utf-8")- assert report["summary"]["migrated"] >= 2- # The merge is written atomically — no temp file survives the run.- assert [p.name for p in target.glob(".tmp*")] == []---def _allowlist_migrator(mod, tmp_path: Path, existing_config: str):- """Migrator wired to merge an exec-approvals allowlist into config.yaml."""- source = tmp_path / ".openclaw"- target = tmp_path / ".hermes"- target.mkdir()- source.mkdir(parents=True)- (source / "exec-approvals.json").write_text(- json.dumps({"agents": {"*": {"allowlist": [{"pattern": "/home/test/**"}]}}}),- encoding="utf-8",- )- (target / "config.yaml").write_text(existing_config, encoding="utf-8")- return mod.Migrator(- source_root=source,- target_root=target,- execute=True,- workspace_target=None,- overwrite=False,- migrate_secrets=False,- output_dir=target / "migration-report",- ), target / "config.yaml"---MALFORMED_HERMES_CONFIG = """\-model: hermes-4-405b-api_key_env: OPENROUTER_API_KEY-command_allowlist:- - /usr/bin/*-approvals:- deny: [shutdown *-telegram:- enabled: true-"""---def test_unreadable_config_is_refused_not_overwritten(tmp_path: Path):- """A present-but-unparseable config.yaml must survive the migration.-- ``load_yaml_file`` returned ``{}`` for an absent file AND for one it could- not parse; the config-mutating steps read, merge and write the whole- mapping back, so a YAML syntax error meant every existing setting was- replaced by just the merged section.- """- mod = load_module()- migrator, config_path = _allowlist_migrator(- mod, tmp_path, MALFORMED_HERMES_CONFIG)- before = config_path.read_bytes()-- report = migrator.migrate()-- assert config_path.read_bytes() == before- allowlist = [i for i in report["items"] if i["kind"] == "command-allowlist"]- assert allowlist and allowlist[0]["status"] == mod.STATUS_ERROR- assert "not valid YAML" in allowlist[0]["reason"]---def test_unreadable_config_blocks_later_config_steps_instead_of_partial_writes(- tmp_path: Path):- """One refusal flips the existing _config_apply_blocked short-circuit."""- mod = load_module()- migrator, config_path = _allowlist_migrator(- mod, tmp_path, MALFORMED_HERMES_CONFIG)-- report = migrator.migrate()-- assert migrator._config_apply_blocked is True- statuses = {- i["status"] for i in report["items"]- if i["kind"] in mod.Migrator._CONFIG_MUTATING_OPTIONS- }- # Nothing claimed a successful config write.- assert "migrated" not in statuses- assert config_path.read_text(encoding="utf-8") == MALFORMED_HERMES_CONFIG---def test_readable_config_keeps_every_pre_existing_key(tmp_path: Path):- mod = load_module()- migrator, config_path = _allowlist_migrator(- mod,- tmp_path,- "model: hermes-4-405b\n"- "api_key_env: OPENROUTER_API_KEY\n"- "command_allowlist:\n - /usr/bin/*\n",- )-- migrator.migrate()-- import hermes_yaml as yaml-- merged = yaml.safe_load(config_path.read_text(encoding="utf-8"))- assert merged["model"] == "hermes-4-405b"- assert merged["api_key_env"] == "OPENROUTER_API_KEY"- assert "/usr/bin/*" in merged["command_allowlist"]- assert "/home/test/**" in merged["command_allowlist"]---def test_absent_config_is_still_created(tmp_path: Path):- """The guard must not break first-time creation.-- Only ``absent`` may read as ``{}``; ``model-config`` creates config.yaml- from scratch when the target has none.- """- mod = load_module()- source = tmp_path / ".openclaw"- target = tmp_path / ".hermes"- target.mkdir()- source.mkdir()- (source / "openclaw.json").write_text(- json.dumps({"agents": {"defaults": {"model": "anthropic/claude-sonnet-4"}}}),- encoding="utf-8",- )- config_path = target / "config.yaml"- assert not config_path.exists()-- mod.Migrator(- source_root=source, target_root=target, execute=True,- workspace_target=None, overwrite=True, migrate_secrets=False,- output_dir=None, selected_options={"model-config"},- ).migrate()-- assert "anthropic/claude-sonnet-4" in config_path.read_text(encoding="utf-8")---def test_symlinked_config_stays_a_symlink(tmp_path: Path):- """Managed deployments symlink ~/.hermes/config.yaml into a dotfiles repo.-- A plain ``os.replace`` onto the link would detach it into a regular file;- ``dump_yaml_file`` resolves the link first, as ``utils.atomic_replace`` does.- """- mod = load_module()- real = tmp_path / "dotfiles" / "config.yaml"- real.parent.mkdir(parents=True)- real.write_text("model: hermes-4-405b\ncommand_allowlist:\n - /usr/bin/*\n",- encoding="utf-8")- migrator, config_path = _allowlist_migrator(mod, tmp_path, "placeholder: true\n")- config_path.unlink()- config_path.symlink_to(real)-- migrator.migrate()-- assert config_path.is_symlink()- assert config_path.resolve() == real.resolve()- assert "/home/test/**" in real.read_text(encoding="utf-8")- assert "hermes-4-405b" in real.read_text(encoding="utf-8")---def test_unreadable_config_refused_by_model_config_too(tmp_path: Path):- """The refusal is at the shared helper, so every config step inherits it."""- mod = load_module()- source = tmp_path / ".openclaw"- target = tmp_path / ".hermes"- target.mkdir()- source.mkdir()- (source / "openclaw.json").write_text(- json.dumps({"agents": {"defaults": {"model": "anthropic/claude-sonnet-4"}}}),- encoding="utf-8",- )- config_path = target / "config.yaml"- config_path.write_text(MALFORMED_HERMES_CONFIG, encoding="utf-8")-- report = mod.Migrator(- source_root=source, target_root=target, execute=True,- workspace_target=None, overwrite=True, migrate_secrets=False,- output_dir=None, selected_options={"model-config"},- ).migrate()-- assert config_path.read_text(encoding="utf-8") == MALFORMED_HERMES_CONFIG- items = [i for i in report["items"] if i["kind"] == "model-config"]- assert items and items[0]["status"] == mod.STATUS_ERROR---def test_migrator_optionally_imports_supported_secrets_and_messaging_settings(tmp_path: Path):- mod = load_module()- source = tmp_path / ".openclaw"- target = tmp_path / ".hermes"-- (source / "credentials").mkdir(parents=True)- (source / "openclaw.json").write_text(- json.dumps(- {- "agents": {"defaults": {"workspace": "/tmp/openclaw-workspace"}},- "channels": {"telegram": {"botToken": "123:abc"}},- }- ),- encoding="utf-8",- )- (source / "credentials" / "telegram-default-allowFrom.json").write_text(- json.dumps({"allowFrom": ["111", "222"]}),- encoding="utf-8",- )- target.mkdir()-- migrator = mod.Migrator(- source_root=source,- target_root=target,- execute=True,- workspace_target=None,- overwrite=False,- migrate_secrets=True,- output_dir=target / "migration-report",- )- migrator.migrate()-- env_text = (target / ".env").read_text(encoding="utf-8")- assert "MESSAGING_CWD=/tmp/openclaw-workspace" in env_text- assert "TELEGRAM_ALLOWED_USERS=111,222" in env_text- assert "TELEGRAM_BOT_TOKEN=123:abc" in env_text---------def test_source_candidate_finds_files_in_custom_workspace(tmp_path: Path):- """When agents.defaults.workspace points outside ~/.openclaw, files should- be discovered there as a fallback."""- mod = load_module()- source = tmp_path / ".openclaw"- target = tmp_path / ".hermes"- custom_ws = tmp_path / "my-custom-workspace"-- target.mkdir()- source.mkdir()- custom_ws.mkdir()-- # No workspace/ directory inside .openclaw — files live in custom workspace- (custom_ws / "MEMORY.md").write_text("# Memory\n\n- custom workspace entry\n", encoding="utf-8")- (custom_ws / "SOUL.md").write_text("# Soul\n\nI am me.\n", encoding="utf-8")- (custom_ws / "skills" / "my-skill").mkdir(parents=True)- (custom_ws / "skills" / "my-skill" / "SKILL.md").write_text(- "---\nname: my-skill\ndescription: test\n---\n\nbody\n",- encoding="utf-8",- )- (custom_ws / "memory").mkdir()- (custom_ws / "memory" / "2026-01-01.md").write_text("- daily note\n", encoding="utf-8")-- (source / "openclaw.json").write_text(- json.dumps({"agents": {"defaults": {"workspace": str(custom_ws)}}}),- encoding="utf-8",- )-- migrator = mod.Migrator(- source_root=source,- target_root=target,- execute=True,- workspace_target=None,- overwrite=False,- migrate_secrets=False,- output_dir=target / "migration-report",- selected_options={"soul", "memory", "skills", "daily-memory"},- )- report = migrator.migrate()-- # SOUL.md should have been found and migrated- assert (target / "SOUL.md").exists()-- # MEMORY.md should have been found and migrated- assert (target / "memories" / "MEMORY.md").exists()- mem_content = (target / "memories" / "MEMORY.md").read_text(encoding="utf-8")- assert "custom workspace entry" in mem_content-- # Skills should have been found and migrated- imported_skill = target / "skills" / mod.SKILL_CATEGORY_DIRNAME / "my-skill" / "SKILL.md"- assert imported_skill.exists()-- migrated_kinds = {item["kind"] for item in report["items"] if item["status"] == "migrated"}- assert "soul" in migrated_kinds- assert "memory" in migrated_kinds- assert "skill" in migrated_kinds-------------def test_slack_settings_migrated(tmp_path: Path):- """Slack bot/app tokens and allowlist migrate to .env."""- mod = load_module()- source = tmp_path / ".openclaw"- target = tmp_path / ".hermes"- target.mkdir()- source.mkdir()-- (source / "openclaw.json").write_text(- json.dumps({- "channels": {- "slack": {- "botToken": "xoxb-slack-bot",- "appToken": "xapp-slack-app",- "allowFrom": ["U111", "U222"],- }- }- }),- encoding="utf-8",- )-- migrator = mod.Migrator(- source_root=source, target_root=target, execute=True,- workspace_target=None, overwrite=False, migrate_secrets=False, output_dir=None,- selected_options={"slack-settings"},- )- migrator.migrate()- env_text = (target / ".env").read_text(encoding="utf-8")- assert "SLACK_BOT_TOKEN=xoxb-slack-bot" in env_text- assert "SLACK_APP_TOKEN=xapp-slack-app" in env_text- assert "SLACK_ALLOWED_USERS=U111,U222" in env_text-----def test_model_config_migrated(tmp_path: Path):- """Default model setting migrates to config.yaml."""- mod = load_module()- source = tmp_path / ".openclaw"- target = tmp_path / ".hermes"- target.mkdir()- source.mkdir()-- (source / "openclaw.json").write_text(- json.dumps({- "agents": {"defaults": {"model": "anthropic/claude-sonnet-4"}}- }),- encoding="utf-8",- )- # config.yaml must exist for YAML merge to work- (target / "config.yaml").write_text("model: openrouter/auto\n", encoding="utf-8")-- migrator = mod.Migrator(- source_root=source, target_root=target, execute=True,- workspace_target=None, overwrite=True, migrate_secrets=False, output_dir=None,- selected_options={"model-config"},- )- migrator.migrate()- config_text = (target / "config.yaml").read_text(encoding="utf-8")- assert "anthropic/claude-sonnet-4" in config_text-------def test_shared_skills_migrated(tmp_path: Path):- """Shared skills from ~/.openclaw/skills/ are migrated."""- mod = load_module()- source = tmp_path / ".openclaw"- target = tmp_path / ".hermes"- target.mkdir()-- # Create a shared skill (not in workspace/skills/)- (source / "skills" / "my-shared-skill").mkdir(parents=True)- (source / "skills" / "my-shared-skill" / "SKILL.md").write_text(- "---\nname: my-shared-skill\ndescription: shared\n---\n\nbody\n",- encoding="utf-8",- )-- migrator = mod.Migrator(- source_root=source, target_root=target, execute=True,- workspace_target=None, overwrite=False, migrate_secrets=False, output_dir=None,- selected_options={"shared-skills"},- )- migrator.migrate()- imported = target / "skills" / mod.SKILL_CATEGORY_DIRNAME / "my-shared-skill" / "SKILL.md"- assert imported.exists()---def test_daily_memory_merged(tmp_path: Path):- """Daily memory notes from workspace/memory/*.md are merged into MEMORY.md."""- mod = load_module()- source = tmp_path / ".openclaw"- target = tmp_path / ".hermes"- target.mkdir()-- mem_dir = source / "workspace" / "memory"- mem_dir.mkdir(parents=True)- (mem_dir / "2026-03-01.md").write_text(- "# March 1 Notes\n\n- User prefers dark mode\n- Timezone: PST\n",- encoding="utf-8",- )- (mem_dir / "2026-03-02.md").write_text(- "# March 2 Notes\n\n- Working on migration project\n",- encoding="utf-8",- )-- migrator = mod.Migrator(- source_root=source, target_root=target, execute=True,- workspace_target=None, overwrite=False, migrate_secrets=False, output_dir=None,- selected_options={"daily-memory"},- )- migrator.migrate()- mem_path = target / "memories" / "MEMORY.md"- assert mem_path.exists()- content = mem_path.read_text(encoding="utf-8")- assert "dark mode" in content- assert "migration project" in content---def test_provider_keys_require_migrate_secrets_flag(tmp_path: Path):- """Provider keys migration is double-gated: needs option + --migrate-secrets."""- mod = load_module()- source = tmp_path / ".openclaw"- target = tmp_path / ".hermes"- target.mkdir()- source.mkdir()-- (source / "openclaw.json").write_text(- json.dumps({- "models": {- "providers": {- "openrouter": {- "apiKey": "sk-or-test-key",- "baseUrl": "https://openrouter.ai/api/v1",- }- }- }- }),- encoding="utf-8",- )-- # Without --migrate-secrets: should skip- migrator = mod.Migrator(- source_root=source, target_root=target, execute=True,- workspace_target=None, overwrite=False, migrate_secrets=False, output_dir=None,- selected_options={"provider-keys"},- )- migrator.migrate()- env_path = target / ".env"- if env_path.exists():- assert "sk-or-test-key" not in env_path.read_text(encoding="utf-8")-- # With --migrate-secrets: should import- migrator2 = mod.Migrator(- source_root=source, target_root=target, execute=True,- workspace_target=None, overwrite=False, migrate_secrets=True, output_dir=None,- selected_options={"provider-keys"},- )- migrator2.migrate()- env_text = (target / ".env").read_text(encoding="utf-8")- assert "OPENROUTER_API_KEY=sk-or-test-key" in env_text-------def test_skill_installs_cleanly_under_skills_guard():- skills_guard = load_skills_guard()- result = skills_guard.scan_skill(- SCRIPT_PATH.parents[1],- source="official/migration/openclaw-migration",- )-- # The migration script's references to agent config files are legitimate:- # it mentions AGENTS.md to migrate workspace instructions and points the- # user at ~/.hermes/config.yaml in its post-migration summary — it never- # writes to either. Under skills-guard-v2 (#92021) these score as- # informational _ref findings (the old critical agent_config_mod /- # hermes_config_mod findings no longer fire for bare mentions), so the- # verdict is "safe" with no modification-intent findings at all.- assert result.verdict == "safe", f"Unexpected verdict: {result.verdict}"- KNOWN_FALSE_POSITIVES = {"agent_config_ref", "hermes_config_ref"}- for f in result.findings:- assert f.pattern_id in KNOWN_FALSE_POSITIVES, f"Unexpected finding: {f}"---# ── rebrand_text tests ────────────────────────────────────────---def test_rebrand_text_replaces_openclaw_variants():- mod = load_module()- # Mixed-case / capitalized matches → capital-H ``Hermes``.- assert mod.rebrand_text("OpenClaw prefers Python 3.11") == "Hermes prefers Python 3.11"- assert mod.rebrand_text("I told Open Claw to use dark mode") == "I told Hermes to use dark mode"- assert mod.rebrand_text("Open-Claw config is great") == "Hermes config is great"- assert mod.rebrand_text("OPENCLAW uses tools well") == "Hermes uses tools well"- # All-lowercase matches → lowercase ``hermes``; this preserves the- # real filesystem path ``~/.hermes`` (Hermes home) when rebranding- # memory entries that reference ``~/.openclaw`` or ``openclaw`` prose.- assert mod.rebrand_text("openclaw should always respond concisely") == "hermes should always respond concisely"---------------# ── non-UTF-8 tolerance (issue #8901) ───────────────────────────────────────---def _write_invalid_utf8_json(path: Path, prefix: bytes, valid_value: bytes, suffix: bytes) -> None:- """Write a JSON-shaped file containing one invalid UTF-8 byte (0xB3) inside- a string value, alongside a separate, validly-encoded value. Used to check- that a single bad byte does not prevent the rest of the file's data from- being read (relies on read_text(..., errors="replace"))."""- path.write_bytes(prefix + b"\xb3" + valid_value + suffix)---def test_command_allowlist_handles_invalid_utf8_bytes(tmp_path: Path):- """exec-approvals.json with a non-UTF-8 byte should not abort migration;- valid patterns elsewhere in the same file must still be imported."""- mod = load_module()- source = tmp_path / ".openclaw"- target = tmp_path / ".hermes"- source.mkdir()- target.mkdir()-- _write_invalid_utf8_json(- source / "exec-approvals.json",- prefix=b'{"agents": {"*": {"allowlist": [{"pattern": "/bad',- valid_value=b'"}, {"pattern": "/usr/bin/*"}]}}}',- suffix=b"",- )- (target / "config.yaml").write_text("command_allowlist: []\n", encoding="utf-8")-- migrator = mod.Migrator(- source_root=source, target_root=target, execute=True,- workspace_target=None, overwrite=False, migrate_secrets=False, output_dir=None,- selected_options={"command-allowlist"},- )- report = migrator.migrate()-- items = [i for i in report["items"] if i["kind"] == "command-allowlist"]- assert items and items[0]["status"] == "migrated"- config_text = (target / "config.yaml").read_text(encoding="utf-8")- assert "/usr/bin/*" in config_text---def test_messaging_settings_handles_invalid_utf8_in_telegram_allowlist(tmp_path: Path):- """Telegram allowFrom file with a non-UTF-8 byte should not abort migration;- valid user IDs elsewhere in the same file must still be imported."""- mod = load_module()- source = tmp_path / ".openclaw"- target = tmp_path / ".hermes"- source.mkdir()- target.mkdir()-- creds_dir = source / "credentials"- creds_dir.mkdir()- _write_invalid_utf8_json(- creds_dir / "telegram-default-allowFrom.json",- prefix=b'{"allowFrom": ["bad',- valid_value=b'", "123456789"]}',- suffix=b"",- )-- migrator = mod.Migrator(- source_root=source, target_root=target, execute=True,- workspace_target=None, overwrite=False, migrate_secrets=False, output_dir=None,- selected_options={"messaging-settings"},- )- report = migrator.migrate()-- items = [i for i in report["items"] if i["kind"] == "messaging-settings"]- assert items and items[0]["status"] == "migrated"- env_text = (target / ".env").read_text(encoding="utf-8")- assert "123456789" in env_text----diff --git a/tests/skills/test_openclaw_migration_hardening.py b/tests/skills/test_openclaw_migration_hardening.pydeleted file mode 100644index 6381b268efd..00000000000--- a/tests/skills/test_openclaw_migration_hardening.py+++ /dev/null@@ -1,261 +0,0 @@-"""Tests for the OpenClaw→Hermes migration hardening features.--Covers the changes in the "claw migrate hardening" PR:- - secret redaction (engine-level, applied to report JSON)- - warnings[] / next_steps[] on the report- - blocked-by-earlier-conflict sequencing for config.yaml mutations- - --json output mode on the migration script- - enum-like constants and ItemResult.sensitive field-"""-from __future__ import annotations--import importlib.util-import json-import subprocess-import sys-from pathlib import Path--SCRIPT_PATH = (- Path(__file__).resolve().parents[2]- / "optional-skills"- / "migration"- / "openclaw-migration"- / "scripts"- / "openclaw_to_hermes.py"-)--def _load():- spec = importlib.util.spec_from_file_location("openclaw_to_hermes_hard", SCRIPT_PATH)- module = importlib.util.module_from_spec(spec)- assert spec.loader is not None- sys.modules[spec.name] = module- spec.loader.exec_module(module)- return module--# ───────────────────────────────────────────────────────────────────────-# Redaction-# ───────────────────────────────────────────────────────────────────────-def test_redact_replaces_secret_by_key_name():- mod = _load()- out = mod.redact_migration_value({"OPENROUTER_API_KEY": "sk-or-v1-abcdef12345678"})- assert out["OPENROUTER_API_KEY"] == mod.REDACTED_MIGRATION_VALUE--def test_redact_handles_github_token_pattern():- mod = _load()- out = mod.redact_migration_value({"detail": "token: ghp_1234567890abcdef1234"})- assert "ghp_" not in out["detail"]- assert mod.REDACTED_MIGRATION_VALUE in out["detail"]--def test_redact_is_recursive():- mod = _load()- nested = {- "outer": {- "items": [- {"password": "hunter2"},- {"details": {"apiKey": "my-key"}},- ],- },- }- out = mod.redact_migration_value(nested)- assert out["outer"]["items"][0]["password"] == mod.REDACTED_MIGRATION_VALUE- assert out["outer"]["items"][1]["details"]["apiKey"] == mod.REDACTED_MIGRATION_VALUE--def test_redact_preserves_non_secret_keys_and_values():- mod = _load()- input_data = {"name": "hermes", "count": 42, "tags": ["a", "b"]}- out = mod.redact_migration_value(input_data)- assert out == input_data--def test_redact_normalizes_key_case_and_punctuation():- mod = _load()- # "Api Key", "api-key", "API_KEY" all normalize the same way.- for key in ("Api Key", "api-key", "API_KEY", "apikey"):- out = mod.redact_migration_value({key: "secret"})- assert out[key] == mod.REDACTED_MIGRATION_VALUE, f"failed to redact: {key}"--def test_redact_leaves_env_secretref_alone():- """SecretRef-like shapes ({source: env, id: ...}) are pointers, not secrets."""- mod = _load()- ref = {"source": "env", "id": "OPENAI_API_KEY"}- out = mod.redact_migration_value({"apiKey": ref})- # The key "apiKey" itself triggers redaction today — this test locks that in.- # If we later want to exempt SecretRef values the way OpenClaw does, update- # both this test and _redact_internal together.- assert out["apiKey"] == mod.REDACTED_MIGRATION_VALUE--def test_write_report_redacts_api_keys_on_disk(tmp_path):- mod = _load()- report = {- "timestamp": "20260427T120000",- "mode": "execute",- "source_root": "/src",- "target_root": "/tgt",- "summary": {"migrated": 1, "conflict": 0, "error": 0, "skipped": 0, "archived": 0},- "items": [- {- "kind": "provider-keys",- "source": "openclaw.json",- "destination": "/tgt/.env",- "status": "migrated",- "reason": "",- "details": {"OPENROUTER_API_KEY": "sk-or-v1-1234567890abcdef"},- },- ],- }- mod.write_report(tmp_path, report)- persisted = json.loads((tmp_path / "report.json").read_text())- # The raw secret must not appear anywhere in the persisted JSON.- assert "sk-or-v1-1234567890abcdef" not in (tmp_path / "report.json").read_text()- assert persisted["items"][0]["details"]["OPENROUTER_API_KEY"] == mod.REDACTED_MIGRATION_VALUE--# ───────────────────────────────────────────────────────────────────────-# Warnings and next-steps-# ───────────────────────────────────────────────────────────────────────-def _make_minimal_migrator(mod, tmp_path, **overrides):- source = tmp_path / "openclaw"- source.mkdir()- # Minimal valid OpenClaw layout so the Migrator constructor doesn't choke.- (source / "openclaw.json").write_text("{}", encoding="utf-8")- target = tmp_path / "hermes"- target.mkdir()- defaults = dict(- source_root=source,- target_root=target,- execute=False,- workspace_target=None,- overwrite=False,- migrate_secrets=False,- output_dir=None,- selected_options=set(),- )- defaults.update(overrides)- return mod.Migrator(**defaults)--def test_conflict_produces_overwrite_warning(tmp_path):- mod = _load()- migrator = _make_minimal_migrator(mod, tmp_path, execute=True)- # Inject a conflict on a config.yaml target to exercise the warning pathway.- migrator.record(- "tts-config",- source=None,- destination=migrator.target_root / "config.yaml",- status=mod.STATUS_CONFLICT,- reason="TTS already configured",- )- report = migrator.build_report()- assert any("--overwrite" in w for w in report["warnings"])- # The conflict on config.yaml should have flipped the block flag too.- assert migrator._config_apply_blocked is True--def test_provider_keys_skipped_warning_when_secrets_disabled(tmp_path):- mod = _load()- migrator = _make_minimal_migrator(mod, tmp_path, execute=True, migrate_secrets=False)- migrator.record(- "provider-keys",- source=None,- destination=None,- status=mod.STATUS_SKIPPED,- reason="--migrate-secrets not set",- )- report = migrator.build_report()- assert any("--migrate-secrets" in w for w in report["warnings"])--# ───────────────────────────────────────────────────────────────────────-# Blocked-by-earlier-conflict sequencing-# ───────────────────────────────────────────────────────────────────────--def test_run_if_selected_skips_config_ops_after_block(tmp_path):- mod = _load()- migrator = _make_minimal_migrator(- mod, tmp_path, execute=True, selected_options={"model-config", "tts-config"}- )- migrator._config_apply_blocked = True- called = []- migrator.run_if_selected("tts-config", lambda: called.append(True))- assert called == []- # The skipped record uses the blocked reason.- blocked = [i for i in migrator.items if i.kind == "tts-config"]- assert len(blocked) == 1- assert blocked[0].status == mod.STATUS_SKIPPED- assert blocked[0].reason == mod.REASON_BLOCKED_BY_APPLY_CONFLICT--def test_dry_run_never_blocks_even_after_conflict(tmp_path):- """Dry runs must preview the full plan — blocking mid-preview would hide- conflicts and mislead the user about what would actually happen."""- mod = _load()- migrator = _make_minimal_migrator(- mod, tmp_path, execute=False, selected_options={"tts-config"}- )- migrator._config_apply_blocked = True- called = []- migrator.run_if_selected("tts-config", lambda: called.append(True))- assert called == [True]--# ───────────────────────────────────────────────────────────────────────-# --json output mode-# ───────────────────────────────────────────────────────────────────────-def test_json_mode_emits_structured_report(tmp_path):- """End-to-end: run the CLI with --json and no --execute, parse stdout."""- source = tmp_path / "openclaw"- source.mkdir()- (source / "openclaw.json").write_text(- json.dumps({"agents": {"defaults": {"model": "openrouter/anthropic/claude-sonnet-4"}}}),- encoding="utf-8",- )- target = tmp_path / "hermes"- target.mkdir()-- result = subprocess.run(- [- sys.executable,- str(SCRIPT_PATH),- "--source", str(source),- "--target", str(target),- "--json",- ],- capture_output=True,- text=True,- timeout=30,- check=False,- )- assert result.returncode == 0, result.stderr- payload = json.loads(result.stdout)- assert "summary" in payload- assert "warnings" in payload- assert "next_steps" in payload- assert payload["mode"] == "dry-run"--def test_json_mode_redacts_secrets_in_output(tmp_path):- """Even plan-only JSON output goes through the redactor — the stdout- capture path is what gets piped into CI / support tickets."""- source = tmp_path / "openclaw"- source.mkdir()- (source / "openclaw.json").write_text("{}", encoding="utf-8")- # Plant a fake OpenClaw .env with a recognizably-shaped key.- (source / ".env").write_text(- "OPENROUTER_API_KEY=sk-or-v1-abcdef1234567890abcdef\n", encoding="utf-8"- )- target = tmp_path / "hermes"- target.mkdir()-- result = subprocess.run(- [- sys.executable,- str(SCRIPT_PATH),- "--source", str(source),- "--target", str(target),- "--migrate-secrets", # so provider-keys surface in the plan- "--json",- ],- capture_output=True,- text=True,- timeout=30,- check=False,- )- assert result.returncode == 0, result.stderr- # The raw key value must never appear in the JSON output.- assert "sk-or-v1-abcdef1234567890abcdef" not in result.stdout--# ───────────────────────────────────────────────────────────────────────-# ItemResult schema additions-# ───────────────────────────────────────────────────────────────────────diff --git a/website/docs/getting-started/quickstart.md b/website/docs/getting-started/quickstart.mdindex 5c82a75ee22..b3304561ffd 100644--- a/website/docs/getting-started/quickstart.md+++ b/website/docs/getting-started/quickstart.md@@ -98,6 +98,8 @@ That logs you in, sets Nous as your provider, and turns on the Tool Gateway in o::::::info Setup modes+Coming from OpenClaw, Claude Code, Codex CLI or Cursor? When a fresh `hermes setup` finds one of them on your computer it first offers to import your setup (it installs the `agent-importers` plugin for that; see [Import from Other Agents](../user-guide/import-from-other-agents.md)).+On a fresh install, `hermes setup` offers three modes:- **Quick Setup (Nous Portal)** — OAuth login, no API keys to manage; sets up a model plus the Tool Gateway tools, billed to your [Nous Portal subscription](../integrations/nous-portal.md). The recommended fast path.diff --git a/website/docs/guides/migrate-from-openclaw.md b/website/docs/guides/migrate-from-openclaw.mdindex 4b08dc07f04..dd662aa7fcd 100644--- a/website/docs/guides/migrate-from-openclaw.md+++ b/website/docs/guides/migrate-from-openclaw.md@@ -6,10 +6,12 @@ description: "Complete guide to migrating your OpenClaw / Clawdbot setup to Herm# Migrate from OpenClaw-`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.+`hermes import-agent openclaw` 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**, **OpenAI Codex CLI** or **Cursor** instead? Use [`hermes import-agent`](../user-guide/import-from-other-agents.md) from the `agent-importers` plugin.+The command comes from the official **`agent-importers` plugin** in the [plugin catalog](../user-guide/features/plugins.md), which also imports Claude Code, Codex CLI and Cursor setups ([Import from Other Agents](../user-guide/import-from-other-agents.md)). The older spelling `hermes claw migrate` still works once the plugin is installed and runs the same import.++:::tip The easy way+On a fresh install, run `hermes setup`. When it finds `~/.openclaw` it asks **"Import your setup from OpenClaw?"**. Say yes and setup installs the plugin and runs `hermes import-agent openclaw --migrate-secrets`, preview and confirmation included, then continues with the sections the import did not already fill in.::::::tip@@ -19,14 +21,17 @@ If your OpenClaw setup was multi-provider, `hermes setup --portal` collapses it## Quick start```bash+# Once per profile: the command comes from this plugin+hermes plugins install agent-importers+# Preview then migrate (always shows a preview first, then asks to confirm)-hermes claw migrate+hermes import-agent openclaw# Preview only, no changes-hermes claw migrate --dry-run+hermes import-agent openclaw --dry-run# Full migration including API keys, skip confirmation-hermes claw migrate --preset full --migrate-secrets --yes+hermes import-agent openclaw --preset full --migrate-secrets --yes```The migration always shows a full preview of what will be imported before making any changes. Review the list, then confirm to proceed.@@ -250,3 +255,7 @@ Imported skills land in `~/.hermes/skills/openclaw-imports/`. Start a new sessio### TTS voice not migratedOpenClaw stores TTS settings in two places: `messages.tts.providers.*` and the top-level `talk` config. The migration checks both. If your voice ID was set via the OpenClaw UI (stored in a different path), you may need to set it manually: `hermes config set tts.elevenlabs.voice_id YOUR_VOICE_ID`.++## Upgrading from a version with `hermes claw` built in++OpenClaw migration used to ship inside Hermes core as `hermes claw migrate` and the optional `openclaw-migration` skill. Both moved into the `agent-importers` plugin, with the same flags and the same secrets rule (keys come over only with `--migrate-secrets`). Running `hermes claw` without the plugin prints the install command, and a fresh `hermes setup` that finds `~/.openclaw` offers to install it. The guided migration skill comes with the plugin as `agent-importers:openclaw-migration`. The old `official/migration/openclaw-migration` optional skill is gone. Nothing changes for an OpenClaw setup you have already migrated.diff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.mdindex 3ce3f89b97f..893a18d96d7 100644--- a/website/docs/reference/cli-commands.md+++ b/website/docs/reference/cli-commands.md@@ -102,8 +102,8 @@ The install also ships `hermes-agent`, a minimal runner that sends one query and| `hermes pets` | Browse, install, and select [petdex](../user-guide/features/pets.md) animated pets shown across the CLI, TUI, and desktop app. Subcommands: `list`, `install`, `select`, `show`, `off`, `scale`, `remove`, `doctor`. || `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, Codex CLI or Cursor setup (from the [`agent-importers`](../user-guide/import-from-other-agents.md) plugin). |+| `hermes claw` | OpenClaw migration (`migrate`, `cleanup`), from the [`agent-importers`](../user-guide/import-from-other-agents.md) plugin; `hermes claw migrate` is the same as `hermes import-agent openclaw`. |+| `hermes import-agent` | Import an OpenClaw, 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. |@@ -404,6 +404,8 @@ hermes setup [model|tts|terminal|gateway|tools|agent] [--non-interactive] [--res**Returning user (already configured):** drops straight into the full reconfigure wizard — every prompt shows your current value as its default, press Enter to keep or type a new value. No menu.+**Coming from another agent:** when the first run finds an OpenClaw, Claude Code, Codex CLI or Cursor setup (`~/.openclaw`, `~/.claude`, `~/.codex`, `~/.cursor`), it first asks **"Import your setup from …?"** (default yes). With more than one found, you then pick which from a checklist. Setup installs the [`agent-importers`](../user-guide/import-from-other-agents.md) plugin from the catalog, unless you already have it, and runs its import for each pick, which shows a preview and asks before changing anything (OpenClaw's allowlisted API keys and bot tokens are included, as the old built-in step did). Nothing found, a no, `--non-interactive` or a setup started by the dashboard: no question and nothing installed. On an already configured install, run `hermes import-agent` instead.+Jump into one section instead of the full wizard:| Section | Description |@@ -612,7 +614,7 @@ Common flags for migration subcommands:| `--apply` | Rewrite `config.yaml` in-place (default: dry-run, no writes). || `--no-backup` | Skip the timestamped backup of `config.yaml` when applying. |-> Not to be confused with `hermes claw migrate` (one-shot import of OpenClaw configuration into Hermes) — `hermes migrate` is the top-level config-rewrite command.+> Not to be confused with `hermes import-agent openclaw` (one-shot import of OpenClaw configuration into Hermes) — `hermes migrate` is the top-level config-rewrite command.## `hermes codex-runtime`@@ -1431,7 +1433,7 @@ hermes skills search react --source skills-shhermes skills search https://mintlify.com/docs --source well-knownhermes skills inspect official/security/1passwordhermes skills inspect skills-sh/vercel-labs/json-render/json-render-react-hermes skills install official/migration/openclaw-migration+hermes skills install official/mcp/fastmcphermes skills install skills-sh/anthropics/skills/pdf --forcehermes skills install https://sharethis.chat/SKILL.md # Direct URL (+ referenced support files)hermes skills install https://example.com/SKILL.md --name my-skill # Override name when frontmatter has none@@ -1804,10 +1806,22 @@ hermes insights [--days N] [--source platform]| `--days <n>` | Analyze the last `n` days (default: 30). || `--source <platform>` | Filter by source such as `cli`, `telegram`, or `discord`. |-## `hermes claw`+## `hermes import-agent`++```bash+hermes plugins install agent-importers # once; the command comes from this official plugin+hermes import-agent [openclaw|claude-code|codex|cursor] [options]+```++Import an **OpenClaw** (`~/.openclaw`), **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, except OpenClaw's allowlisted keys when you pass `--migrate-secrets`. `--sync` re-imports registered Claude Code, Codex and Cursor sources that changed. On a fresh install, `hermes setup` offers to install the plugin and run the import for you when it finds one of these agents.++The command moved out of core into the official `agent-importers` plugin, together with `hermes claw` (OpenClaw migration), whose spelling the plugin keeps. Without the plugin, `hermes import-agent` and `hermes claw` print the install line. See the **[import guide](../user-guide/import-from-other-agents.md)** for options and mapping tables.++### OpenClaw: `hermes import-agent openclaw````bash-hermes claw migrate [options]+hermes import-agent openclaw [options] # same as the older spelling: hermes claw migrate [options]+hermes claw cleanup [--source <path>] [--dry-run] [--yes]```Migrate your OpenClaw setup to Hermes. Reads from `~/.openclaw` (or a custom path) and writes to `~/.hermes`. Automatically detects legacy directory names (`~/.clawdbot`, `~/.moltbot`) and config filenames (`clawdbot.json`, `moltbot.json`).@@ -1824,7 +1838,9 @@ Migrate your OpenClaw setup to Hermes. Reads from `~/.openclaw` (or a custom pat| `--skill-conflict <mode>` | Handle skill name collisions: `skip` (default), `overwrite`, or `rename`. || `--yes` | Skip the confirmation prompt. |-### What gets migrated+`hermes claw cleanup` renames leftover OpenClaw directories to `*.pre-migration` once you have migrated (OpenClaw stops working after this; rename them back to undo).++#### What gets migratedThe migration covers 30+ categories across persona, memory, skills, model providers, messaging platforms, agent behavior, session policies, MCP servers, TTS, and more. Items are either **directly imported** into Hermes equivalents or **archived** for manual review.@@ -1836,36 +1852,25 @@ The migration covers 30+ categories across persona, memory, skills, model providFor the complete config key mapping, SecretRef handling details, and post-migration checklist, see the **[full migration guide](../guides/migrate-from-openclaw.md)**.-### Examples+#### Examples```bash# Preview what would be migrated-hermes claw migrate --dry-run+hermes import-agent openclaw --dry-run# Full migration (all compatible settings, no secrets)-hermes claw migrate --preset full+hermes import-agent openclaw --preset full# Full migration including API keys-hermes claw migrate --preset full --migrate-secrets+hermes import-agent openclaw --preset full --migrate-secrets# Migrate user data only (no secrets), overwrite conflicts-hermes claw migrate --preset user-data --overwrite+hermes import-agent openclaw --preset user-data --overwrite# Migrate from a custom OpenClaw path-hermes claw migrate --source /home/user/old-openclaw+hermes import-agent openclaw --source /home/user/old-openclaw```-## `hermes import-agent`--```bash-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`), **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.--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````bashdiff --git a/website/docs/reference/optional-skills-catalog.md b/website/docs/reference/optional-skills-catalog.mdindex df16db21de2..835f842e326 100644--- a/website/docs/reference/optional-skills-catalog.md+++ b/website/docs/reference/optional-skills-catalog.md@@ -155,12 +155,6 @@ hermes skills uninstall <skill-name>| [**mcp-oauth-remote-gateway**](../user-guide/skills/optional/mcp/mcp-mcp-oauth-remote-gateway.md) | Manual OAuth for remote MCP servers on headless gateways. || [**mcporter**](../user-guide/skills/optional/mcp/mcp-mcporter.md) | List, auth, and call MCP servers/tools from the terminal. |-## migration--| Skill | Description |-|-------|-------------|-| [**openclaw-migration**](../user-guide/skills/optional/migration/migration-openclaw-migration.md) | Import an OpenClaw setup (memories, skills) into Hermes. |-## mlops| Skill | Description |diff --git a/website/docs/user-guide/features/skills.md b/website/docs/user-guide/features/skills.mdindex 7c6b06930e5..4ecbd750b5a 100644--- a/website/docs/user-guide/features/skills.md+++ b/website/docs/user-guide/features/skills.md@@ -1115,4 +1115,4 @@ All the same commands work with `/skills`:/skills list```-Official optional skills still use identifiers like `official/security/1password` and `official/migration/openclaw-migration`.+Official optional skills still use identifiers like `official/security/1password` and `official/mcp/fastmcp`.diff --git a/website/docs/user-guide/import-from-other-agents.md b/website/docs/user-guide/import-from-other-agents.mdindex 6e5aee4eb84..89f56ec6cbc 100644--- a/website/docs/user-guide/import-from-other-agents.md+++ b/website/docs/user-guide/import-from-other-agents.md@@ -1,21 +1,30 @@---sidebar_position: 9title: "Import from Other Agents"-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."+description: "One-command import of an OpenClaw (~/.openclaw), 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**, **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.+`hermes import-agent` imports your existing **OpenClaw**, **Claude Code**, **OpenAI Codex CLI** or **Cursor** setup into Hermes with one command. 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:+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).++## The easy way: `hermes setup`++On a fresh install, `hermes setup` checks for `~/.openclaw` (or legacy `~/.clawdbot` / `~/.moltbot`), `~/.claude`, `~/.codex` and `~/.cursor` before anything else. When it finds one it asks **"Import your setup from Claude Code?"** (naming what it found); with several found you then pick which from a checklist, all checked. Say yes and setup installs the `agent-importers` plugin from the catalog, unless you already have it, and runs the import below for each pick, preview and confirmation included. For OpenClaw it passes `--migrate-secrets`, as Hermes' old built-in OpenClaw step did, so your API keys and bot tokens come over and the provider and messaging sections that follow are already filled in. Say no, or have none of these folders, and nothing is installed. Already set up? Use the commands below.++## By hand++Install the plugin once per profile:```bashhermes plugins install agent-importers``````bash-hermes import-agent # auto-detect ~/.claude, ~/.codex or ~/.cursor+hermes import-agent # auto-detect ~/.openclaw, ~/.claude, ~/.codex or ~/.cursor+hermes import-agent openclaw # import from ~/.openclaw (see the OpenClaw guide)hermes import-agent claude-code # import from ~/.claudehermes import-agent codex # import from ~/.codexhermes import-agent cursor # import from ~/.cursor@@ -26,6 +35,10 @@ hermes import-agent claude-code --overwrite --yes # replace conflicts, skip pro## What gets imported+### OpenClaw (`~/.openclaw`)++OpenClaw has its own guide, **[Migrate from OpenClaw](../guides/migrate-from-openclaw.md)**, with the full mapping (persona, memory, skills, model providers, messaging platforms, agent behaviour, MCP servers and more), the `--preset`, `--migrate-secrets`, `--workspace-target` and `--skill-conflict` flags, the pre-migration backup and `hermes claw cleanup`. The older spelling `hermes claw migrate` still works and runs the same import.+### Claude Code (`~/.claude`)| Claude Code | Hermes |@@ -61,7 +74,7 @@ Claude's `Bash(npm run test:*)` prefix rules become `npm run test*` globs. Non-`## What is never imported-**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`.+**API keys and credentials.** (OpenClaw is the one exception: its allowlisted API keys and bot tokens come over only when you pass `--migrate-secrets`.) 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@@ -69,11 +82,10 @@ Claude's `Bash(npm run test:*)` prefix rules become `npm run test*` globs. Non-`- **Merges, not replaces.** Memory entries are deduplicated against your existing `MEMORY.md`; allowlist/denylist patterns merge with what's already in `config.yaml`.- **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:+Every successful Claude Code, Codex CLI or Cursor 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:```bashhermes import-agent --sync # re-import every changed source@@ -93,7 +105,7 @@ The manifest is per profile. A profile created with `hermes profile create <name## 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:+`hermes import-agent` and `hermes claw` used to ship inside Hermes core. The commands, their 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.+- **Everyone else** installs it when they next need it: a fresh `hermes setup` that finds one of these agents offers it, and running `hermes import-agent` or `hermes claw` without the plugin prints the install command.diff --git a/website/docs/user-guide/skills/optional/migration/migration-openclaw-migration.md b/website/docs/user-guide/skills/optional/migration/migration-openclaw-migration.mddeleted file mode 100644index dd4bc26368d..00000000000--- a/website/docs/user-guide/skills/optional/migration/migration-openclaw-migration.md+++ /dev/null@@ -1,319 +0,0 @@-----title: "Openclaw Migration — Import an OpenClaw setup (memories, skills) into Hermes"-sidebar_label: "Openclaw Migration"-description: "Import an OpenClaw setup (memories, skills) into Hermes"------{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}--# Openclaw Migration--Import an OpenClaw setup (memories, skills) into Hermes.--## Skill metadata--| | |-|---|---|-| Source | Optional — install with `hermes skills install official/migration/openclaw-migration` |-| Path | `optional-skills/migration/openclaw-migration` |-| Version | `1.0.0` |-| Author | Hermes Agent (Nous Research) |-| License | MIT |-| Platforms | linux, macos, windows |-| Tags | `Migration`, `OpenClaw`, `Hermes`, `Memory`, `Persona`, `Import` |-| Related skills | [`hermes-agent`](../../bundled/autonomous-ai-agents/autonomous-ai-agents-hermes-agent.md) |--## Reference: full SKILL.md--:::info-The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.-:::--# OpenClaw -> Hermes Migration--Use this skill when a user wants to move their OpenClaw setup into Hermes Agent with minimal manual cleanup.--## CLI Command--For a quick, non-interactive migration, use the built-in CLI command:--```bash-hermes claw migrate # Full interactive migration-hermes claw migrate --dry-run # Preview what would be migrated-hermes claw migrate --preset user-data # Migrate without secrets-hermes claw migrate --overwrite # Overwrite existing conflicts-hermes claw migrate --source /custom/path/.openclaw # Custom source-```--The CLI command runs the same migration script described below. Use this skill (via the agent) when you want an interactive, guided migration with dry-run previews and per-item conflict resolution.--**First-time setup:** The `hermes setup` wizard automatically detects `~/.openclaw` and offers migration before configuration begins.--## What this skill does--It uses `scripts/openclaw_to_hermes.py` to:--- import `SOUL.md` into the Hermes home directory as `SOUL.md`-- transform OpenClaw `MEMORY.md` and `USER.md` into Hermes memory entries-- merge OpenClaw command approval patterns into Hermes `command_allowlist`-- migrate Hermes-compatible messaging settings such as `TELEGRAM_ALLOWED_USERS`, and map OpenClaw workspace settings to Hermes working-directory configuration-- copy OpenClaw skills into `~/.hermes/skills/openclaw-imports/`-- optionally copy the OpenClaw workspace instructions file into a chosen Hermes workspace-- mirror compatible workspace assets such as `workspace/tts/` into `~/.hermes/tts/`-- archive non-secret docs that do not have a direct Hermes destination-- produce a structured report listing migrated items, conflicts, skipped items, and reasons--## Path resolution--The helper script lives in this skill directory at:--- `scripts/openclaw_to_hermes.py`--When this skill is installed from the Skills Hub, the normal location is:--- `~/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py`--Do not guess a shorter path like `~/.hermes/skills/openclaw-migration/...`.--Before running the helper:--1. Prefer the installed path under `~/.hermes/skills/migration/openclaw-migration/`.-2. If that path fails, inspect the installed skill directory and resolve the script relative to the installed `SKILL.md`.-3. Only use `find` as a fallback if the installed location is missing or the skill was moved manually.-4. When calling the terminal tool, do not pass `workdir: "~"`. Use an absolute directory such as the user's home directory, or omit `workdir` entirely.--With `--migrate-secrets`, it will also import a small allowlisted set of Hermes-compatible secrets, currently:--- `TELEGRAM_BOT_TOKEN`--## Default workflow--1. Inspect first with a dry run.-2. Present a simple summary of what can be migrated, what cannot be migrated, and what would be archived.-3. If the `clarify` tool is available, use it for user decisions instead of asking for a free-form prose reply.-4. If the dry run finds imported skill directory conflicts, ask how those should be handled before executing.-5. Ask the user to choose between the two supported migration modes before executing.-6. Ask for a target workspace path only if the user wants the workspace instructions file brought over.-7. Execute the migration with the matching preset and flags.-8. Summarize the results, especially:- - what was migrated- - what was archived for manual review- - what was skipped and why--## User interaction protocol--Hermes CLI supports the `clarify` tool for interactive prompts, but it is limited to:--- one choice at a time-- up to 4 predefined choices-- an automatic `Other` free-text option--It does **not** support true multi-select checkboxes in a single prompt.--For every `clarify` call:--- always include a non-empty `question`-- include `choices` only for real selectable prompts-- keep `choices` to 2-4 plain string options-- never emit placeholder or truncated options such as `...`-- never pad or stylize choices with extra whitespace-- never include fake form fields in the question such as `enter directory here`, blank lines to fill in, or underscores like `_____`-- for open-ended path questions, ask only the plain sentence; the user types in the normal CLI prompt below the panel--If a `clarify` call returns an error, inspect the error text, correct the payload, and retry once with a valid `questions` array and clean choices.--When `clarify` is available and the dry run reveals any required user decision, your **next action must be a `clarify` tool call**.-Do not end the turn with a normal assistant message such as:--- "Let me present the choices"-- "What would you like to do?"-- "Here are the options"--If a user decision is required, collect it via `clarify` before producing more prose.-If multiple unresolved decisions remain, do not insert an explanatory assistant message between them. After one `clarify` response is received, your next action should usually be the next required `clarify` call.--Treat `workspace-agents` as an unresolved decision whenever the dry run reports:--- `kind="workspace-agents"`-- `status="skipped"`-- reason containing `No workspace target was provided`--In that case, you must ask about workspace instructions before execution. Do not silently treat that as a decision to skip.--Because of that limitation, use this simplified decision flow:--1. For `SOUL.md` conflicts, use `clarify` with choices such as:- - `keep existing`- - `overwrite with backup`- - `review first`-2. If the dry run shows one or more `kind="skill"` items with `status="conflict"`, use `clarify` with choices such as:- - `keep existing skills`- - `overwrite conflicting skills with backup`- - `import conflicting skills under renamed folders`-3. For workspace instructions, use `clarify` with choices such as:- - `skip workspace instructions`- - `copy to a workspace path`- - `decide later`-4. If the user chooses to copy workspace instructions, ask a follow-up open-ended `clarify` question requesting an **absolute path**.-5. If the user chooses `skip workspace instructions` or `decide later`, proceed without `--workspace-target`.-5. For migration mode, use `clarify` with these 3 choices:- - `user-data only`- - `full compatible migration`- - `cancel`-6. `user-data only` means: migrate user data and compatible config, but do **not** import allowlisted secrets.-7. `full compatible migration` means: migrate the same compatible user data plus the allowlisted secrets when present.-8. If `clarify` is not available, ask the same question in normal text, but still constrain the answer to `user-data only`, `full compatible migration`, or `cancel`.--Execution gate:--- Do not execute while a `workspace-agents` skip caused by `No workspace target was provided` remains unresolved.-- The only valid ways to resolve it are:- - user explicitly chooses `skip workspace instructions`- - user explicitly chooses `decide later`- - user provides a workspace path after choosing `copy to a workspace path`-- Absence of a workspace target in the dry run is not itself permission to execute.-- Do not execute while any required `clarify` decision remains unresolved.--Use these exact `clarify` payload shapes as the default pattern:--- `{"question":"Your existing SOUL.md conflicts with the imported one. What should I do?","choices":["keep existing","overwrite with backup","review first"]}`-- `{"question":"One or more imported OpenClaw skills already exist in Hermes. How should I handle those skill conflicts?","choices":["keep existing skills","overwrite conflicting skills with backup","import conflicting skills under renamed folders"]}`-- `{"question":"Choose migration mode: migrate only user data, or run the full compatible migration including allowlisted secrets?","choices":["user-data only","full compatible migration","cancel"]}`-- `{"question":"Do you want to copy the OpenClaw workspace instructions file into a Hermes workspace?","choices":["skip workspace instructions","copy to a workspace path","decide later"]}`-- `{"question":"Please provide an absolute path where the workspace instructions should be copied."}`--## Decision-to-command mapping--Map user decisions to command flags exactly:--- If the user chooses `keep existing` for `SOUL.md`, do **not** add `--overwrite`.-- If the user chooses `overwrite with backup`, add `--overwrite`.-- If the user chooses `review first`, stop before execution and review the relevant files.-- If the user chooses `keep existing skills`, add `--skill-conflict skip`.-- If the user chooses `overwrite conflicting skills with backup`, add `--skill-conflict overwrite`.-- If the user chooses `import conflicting skills under renamed folders`, add `--skill-conflict rename`.-- If the user chooses `user-data only`, execute with `--preset user-data` and do **not** add `--migrate-secrets`.-- If the user chooses `full compatible migration`, execute with `--preset full --migrate-secrets`.-- Only add `--workspace-target` if the user explicitly provided an absolute workspace path.-- If the user chooses `skip workspace instructions` or `decide later`, do not add `--workspace-target`.--Before executing, restate the exact command plan in plain language and make sure it matches the user's choices.--## Post-run reporting rules--After execution, treat the script's JSON output as the source of truth.--1. Base all counts on `report.summary`.-2. Only list an item under "Successfully Migrated" if its `status` is exactly `migrated`.-3. Do not claim a conflict was resolved unless the report shows that item as `migrated`.-4. Do not say `SOUL.md` was overwritten unless the report item for `kind="soul"` has `status="migrated"`.-5. If `report.summary.conflict > 0`, include a conflict section instead of silently implying success.-6. If counts and listed items disagree, fix the list to match the report before responding.-7. Include the `output_dir` path from the report when available so the user can inspect `report.json`, `summary.md`, backups, and archived files.-8. For memory or user-profile overflow, do not say the entries were archived unless the report explicitly shows an archive path. If `details.overflow_file` exists, say the full overflow list was exported there.-9. If a skill was imported under a renamed folder, report the final destination and mention `details.renamed_from`.-10. If `report.skill_conflict_mode` is present, use it as the source of truth for the selected imported-skill conflict policy.-11. If an item has `status="skipped"`, do not describe it as overwritten, backed up, migrated, or resolved.-12. If `kind="soul"` has `status="skipped"` with reason `Target already matches source`, say it was left unchanged and do not mention a backup.-13. If a renamed imported skill has an empty `details.backup`, do not imply the existing Hermes skill was renamed or backed up. Say only that the imported copy was placed in the new destination and reference `details.renamed_from` as the pre-existing folder that remained in place.--## Migration presets--Prefer these two presets in normal use:--- `user-data`-- `full`--`user-data` includes:--- `soul`-- `workspace-agents`-- `memory`-- `user-profile`-- `messaging-settings`-- `command-allowlist`-- `skills`-- `tts-assets`-- `archive`--`full` includes everything in `user-data` plus:--- `secret-settings`--The helper script still supports category-level `--include` / `--exclude`, but treat that as an advanced fallback rather than the default UX.--## Commands--Run the helper with Hermes' Python environment, which includes `ruamel.yaml`.-For a standalone Python environment, install `ruamel.yaml==0.18.17` first.--Dry run with full discovery:--```bash-python ~/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py-```--When using the terminal tool, prefer an absolute invocation pattern such as:--```json-{"command":"python /home/USER/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py","workdir":"/home/USER"}-```--Dry run with the user-data preset:--```bash-python ~/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py --preset user-data-```--Execute a user-data migration:--```bash-python ~/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py --execute --preset user-data --skill-conflict skip-```--Execute a full compatible migration:--```bash-python ~/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py --execute --preset full --migrate-secrets --skill-conflict skip-```--Execute with workspace instructions included:--```bash-python ~/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py --execute --preset user-data --skill-conflict rename --workspace-target "/absolute/workspace/path"-```--Do not use `$PWD` or the home directory as the workspace target by default. Ask for an explicit workspace path first.--## Important rules--1. Run a dry run before writing unless the user explicitly says to proceed immediately.-2. Do not migrate secrets by default. Tokens, auth blobs, device credentials, and raw gateway config should stay out of Hermes unless the user explicitly asks for secret migration.-3. Do not silently overwrite non-empty Hermes targets unless the user explicitly wants that. The helper script will preserve backups when overwriting is enabled.-4. Always give the user the skipped-items report. That report is part of the migration, not an optional extra.-5. Prefer the primary OpenClaw workspace (`~/.openclaw/workspace/`) over `workspace.default/`. Only use the default workspace as fallback when the primary files are missing.-6. Even in secret-migration mode, only migrate secrets with a clean Hermes destination. Unsupported auth blobs must still be reported as skipped.-7. If the dry run shows a large asset copy, a conflicting `SOUL.md`, or overflowed memory entries, call those out separately before execution.-8. Default to `user-data only` if the user is unsure.-9. Only include `workspace-agents` when the user has explicitly provided a destination workspace path.-10. Treat category-level `--include` / `--exclude` as an advanced escape hatch, not the normal flow.-11. Do not end the dry-run summary with a vague “What would you like to do?” if `clarify` is available. Use structured follow-up prompts instead.-12. Do not use an open-ended `clarify` prompt when a real choice prompt would work. Prefer selectable choices first, then free text only for absolute paths or file review requests.-13. After a dry run, never stop after summarizing if there is still an unresolved decision. Use `clarify` immediately for the highest-priority blocking decision.-14. Priority order for follow-up questions:- - `SOUL.md` conflict- - imported skill conflicts- - migration mode- - workspace instructions destination-15. Do not promise to present choices later in the same message. Present them by actually calling `clarify`.-16. After the migration-mode answer, explicitly check whether `workspace-agents` is still unresolved. If it is, your next action must be the workspace-instructions `clarify` call.-17. After any `clarify` answer, if another required decision remains, do not narrate what was just decided. Ask the next required question immediately.--## Expected result--After a successful run, the user should have:--- Hermes persona state imported-- Hermes memory files populated with converted OpenClaw knowledge-- OpenClaw skills available under `~/.hermes/skills/openclaw-imports/`-- a migration report showing any conflicts, omissions, or unsupported datadiff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/cli-commands.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/cli-commands.mdindex c2732ea4770..9dfe6349e78 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/cli-commands.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/cli-commands.md@@ -820,7 +820,7 @@ hermes skills search react --source skills-shhermes skills search https://mintlify.com/docs --source well-knownhermes skills inspect official/security/1passwordhermes skills inspect skills-sh/vercel-labs/json-render/json-render-react-hermes skills install official/migration/openclaw-migration+hermes skills install official/mcp/fastmcphermes skills install skills-sh/anthropics/skills/pdf --forcehermes skills install https://sharethis.chat/SKILL.md # 直接 URL(含引用的支持文件)hermes skills install https://example.com/SKILL.md --name my-skill # frontmatter 无名称时覆盖名称diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/optional-skills-catalog.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/optional-skills-catalog.mdindex 50c20d5dcc7..00afc679924 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/optional-skills-catalog.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/optional-skills-catalog.md@@ -119,12 +119,6 @@ hermes skills uninstall <skill-name>| [**fastmcp**](/user-guide/skills/optional/mcp/mcp-fastmcp) | 使用 Python 中的 FastMCP 构建、测试、检查、安装和部署 MCP 服务器。适用于创建新 MCP 服务器、将 API 或数据库封装为 MCP 工具、暴露资源或 prompt(提示词),或为 Claude Code、Cursor 等准备 FastMCP 服务器的场景。 || [**mcporter**](/user-guide/skills/optional/mcp/mcp-mcporter) | 使用 mcporter CLI 列出、配置、鉴权并直接调用 MCP 服务器/工具(HTTP 或 stdio),包括临时服务器、配置编辑及 CLI/类型生成。 |-## migration--| 技能 | 描述 |-|-------|-------------|-| [**openclaw-migration**](/user-guide/skills/optional/migration/migration-openclaw-migration) | 将用户的 OpenClaw 自定义配置迁移至 Hermes Agent。从 ~/.openclaw 导入兼容 Hermes 的记忆、SOUL.md、命令白名单、用户技能及选定的工作区资产,并报告无法迁移的内容。 |-## mlops| 技能 | 描述 |diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/skills.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/skills.mdindex b52aae4a83e..65a7567cec9 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/skills.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/skills.md@@ -757,4 +757,4 @@ hermes skills reset google-workspace --restore --yes/skills list```-官方可选 skills 仍使用 `official/security/1password` 和 `official/migration/openclaw-migration` 等标识符。\ No newline at end of file+官方可选 skills 仍使用 `official/security/1password` 和 `official/mcp/fastmcp` 等标识符。\ No newline at end of filediff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/skills/optional/migration/migration-openclaw-migration.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/skills/optional/migration/migration-openclaw-migration.mddeleted file mode 100644index 683e5f95b10..00000000000--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/skills/optional/migration/migration-openclaw-migration.md+++ /dev/null@@ -1,316 +0,0 @@-----title: "Openclaw Migration — 将用户的 OpenClaw 自定义配置迁移到 Hermes Agent"-sidebar_label: "Openclaw Migration"-description: "将用户的 OpenClaw 自定义配置迁移到 Hermes Agent"------{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}--# Openclaw Migration--将用户的 OpenClaw 自定义配置迁移到 Hermes Agent。从 `~/.openclaw` 导入 Hermes 兼容的记忆、`SOUL.md`、命令白名单、用户技能及所选工作区资产,并精确报告无法迁移的内容及原因。--## Skill 元数据--| | |-|---|---|-| 来源 | 可选 — 通过 `hermes skills install official/migration/openclaw-migration` 安装 |-| 路径 | `optional-skills/migration/openclaw-migration` |-| 版本 | `1.0.0` |-| 作者 | Hermes Agent (Nous Research) |-| 许可证 | MIT |-| 平台 | linux, macos, windows |-| 标签 | `Migration`, `OpenClaw`, `Hermes`, `Memory`, `Persona`, `Import` |-| 相关 skill | [`hermes-agent`](/user-guide/skills/bundled/autonomous-ai-agents/autonomous-ai-agents-hermes-agent) |--## 参考:完整 SKILL.md--:::info-以下是 Hermes 在触发此 skill 时加载的完整 skill 定义。这是 skill 激活时 agent 所看到的指令内容。-:::--# OpenClaw -> Hermes 迁移--当用户希望以最少的手动清理将其 OpenClaw 配置迁移到 Hermes Agent 时,使用此 skill。--## CLI 命令--如需快速、非交互式迁移,使用内置 CLI 命令:--```bash-hermes claw migrate # Full interactive migration-hermes claw migrate --dry-run # Preview what would be migrated-hermes claw migrate --preset user-data # Migrate without secrets-hermes claw migrate --overwrite # Overwrite existing conflicts-hermes claw migrate --source /custom/path/.openclaw # Custom source-```--CLI 命令运行与下文所述相同的迁移脚本。当需要交互式、引导式迁移并支持 dry-run(预览)和逐项冲突解决时,请通过 agent 使用此 skill。--**首次设置:** `hermes setup` 向导会自动检测 `~/.openclaw`,并在配置开始前提供迁移选项。--## 此 skill 的功能--它使用 `scripts/openclaw_to_hermes.py` 来:--- 将 `SOUL.md` 导入 Hermes 主目录,保存为 `SOUL.md`-- 将 OpenClaw 的 `MEMORY.md` 和 `USER.md` 转换为 Hermes 记忆条目-- 将 OpenClaw 命令审批模式合并到 Hermes `command_allowlist`-- 迁移 Hermes 兼容的消息设置,例如 `TELEGRAM_ALLOWED_USERS` 和 `MESSAGING_CWD`-- 将 OpenClaw skill 复制到 `~/.hermes/skills/openclaw-imports/`-- 可选地将 OpenClaw 工作区指令文件复制到所选 Hermes 工作区-- 将兼容的工作区资产(如 `workspace/tts/`)镜像到 `~/.hermes/tts/`-- 归档没有直接 Hermes 目标的非机密文档-- 生成结构化报告,列出已迁移项、冲突项、跳过项及原因--## 路径解析--辅助脚本位于此 skill 目录下:--- `scripts/openclaw_to_hermes.py`--从 Skills Hub 安装此 skill 后,通常位于:--- `~/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py`--请勿猜测更短的路径,如 `~/.hermes/skills/openclaw-migration/...`。--运行辅助脚本前:--1. 优先使用 `~/.hermes/skills/migration/openclaw-migration/` 下的已安装路径。-2. 如果该路径失败,检查已安装的 skill 目录,并相对于已安装的 `SKILL.md` 解析脚本路径。-3. 仅在已安装位置缺失或 skill 被手动移动时,才使用 `find` 作为备用方案。-4. 调用终端工具时,不要传入 `workdir: "~"`。请使用绝对目录(如用户主目录),或完全省略 `workdir`。--使用 `--migrate-secrets` 时,还将导入一小组 Hermes 兼容的白名单 secret,目前包括:--- `TELEGRAM_BOT_TOKEN`--## 默认工作流--1. 首先通过 dry run 进行检查。-2. 呈现简洁摘要,说明哪些内容可以迁移、哪些不能迁移、哪些将被归档。-3. 如果 `clarify` 工具可用,使用它处理用户决策,而非要求自由格式的文字回复。-4. 如果 dry run 发现已导入 skill 目录存在冲突,在执行前询问处理方式。-5. 在执行前,请用户在两种支持的迁移模式中选择一种。-6. 仅在用户希望迁移工作区指令文件时,才询问目标工作区路径。-7. 使用匹配的 preset 和标志执行迁移。-8. 汇总结果,重点说明:- - 已迁移的内容- - 已归档待手动审查的内容- - 已跳过的内容及原因--## 用户交互协议--Hermes CLI 支持 `clarify` 工具进行交互式提示,但有以下限制:--- 每次只能处理一个选择-- 最多 4 个预定义选项-- 自动提供 `Other` 自由文本选项--它**不**支持在单个提示中进行真正的多选复选框操作。--每次 `clarify` 调用:--- 必须包含非空的 `question`-- 仅对真实可选提示包含 `choices`-- `choices` 限制为 2-4 个纯字符串选项-- 不得输出占位符或截断选项,如 `...`-- 不得在选项中填充或添加额外空白-- 不得在问题中包含虚假表单字段,如 `在此输入目录`、空白行或下划线 `_____`-- 对于开放式路径问题,只询问纯文本句子;用户在面板下方的普通 CLI 提示符中输入--如果 `clarify` 调用返回错误,检查错误文本,修正 payload,并使用有效的 `question` 和干净的 choices 重试一次。--当 `clarify` 可用且 dry run 揭示任何需要用户决策的情况时,**下一个动作必须是 `clarify` 工具调用**。-不得以如下普通助手消息结束对话:--- "让我来呈现选项"-- "您希望怎么做?"-- "以下是选项"--如果需要用户决策,在生成更多文字之前通过 `clarify` 收集。-如果存在多个未解决的决策,不要在它们之间插入解释性助手消息。收到一个 `clarify` 响应后,下一个动作通常应是下一个必要的 `clarify` 调用。--当 dry run 报告以下情况时,将 `workspace-agents` 视为未解决的决策:--- `kind="workspace-agents"`-- `status="skipped"`-- 原因包含 `No workspace target was provided`--在这种情况下,必须在执行前询问工作区指令问题。不得静默地将其视为跳过的决策。--由于上述限制,使用以下简化决策流程:--1. 对于 `SOUL.md` 冲突,使用 `clarify`,选项如:- - `keep existing`- - `overwrite with backup`- - `review first`-2. 如果 dry run 显示一个或多个 `kind="skill"` 项的 `status="conflict"`,使用 `clarify`,选项如:- - `keep existing skills`- - `overwrite conflicting skills with backup`- - `import conflicting skills under renamed folders`-3. 对于工作区指令,使用 `clarify`,选项如:- - `skip workspace instructions`- - `copy to a workspace path`- - `decide later`-4. 如果用户选择复制工作区指令,追加一个开放式 `clarify` 问题,要求提供**绝对路径**。-5. 如果用户选择 `skip workspace instructions` 或 `decide later`,继续执行而不添加 `--workspace-target`。-5. 对于迁移模式,使用 `clarify`,提供以下 3 个选项:- - `user-data only`- - `full compatible migration`- - `cancel`-6. `user-data only` 表示:迁移用户数据和兼容配置,但**不**导入白名单 secret。-7. `full compatible migration` 表示:迁移相同的兼容用户数据,并在存在时导入白名单 secret。-8. 如果 `clarify` 不可用,以普通文本提出相同问题,但仍将答案限制为 `user-data only`、`full compatible migration` 或 `cancel`。--执行门控:--- 当由 `No workspace target was provided` 导致的 `workspace-agents` 跳过仍未解决时,不得执行。-- 唯一有效的解决方式为:- - 用户明确选择 `skip workspace instructions`- - 用户明确选择 `decide later`- - 用户在选择 `copy to a workspace path` 后提供了工作区路径-- dry run 中缺少工作区目标本身并不构成执行许可。-- 当任何必要的 `clarify` 决策仍未解决时,不得执行。--使用以下精确的 `clarify` payload 形式作为默认模式:--- `{"question":"Your existing SOUL.md conflicts with the imported one. What should I do?","choices":["keep existing","overwrite with backup","review first"]}`-- `{"question":"One or more imported OpenClaw skills already exist in Hermes. How should I handle those skill conflicts?","choices":["keep existing skills","overwrite conflicting skills with backup","import conflicting skills under renamed folders"]}`-- `{"question":"Choose migration mode: migrate only user data, or run the full compatible migration including allowlisted secrets?","choices":["user-data only","full compatible migration","cancel"]}`-- `{"question":"Do you want to copy the OpenClaw workspace instructions file into a Hermes workspace?","choices":["skip workspace instructions","copy to a workspace path","decide later"]}`-- `{"question":"Please provide an absolute path where the workspace instructions should be copied."}`--## 决策到命令的映射--将用户决策精确映射到命令标志:--- 如果用户对 `SOUL.md` 选择 `keep existing`,**不**添加 `--overwrite`。-- 如果用户选择 `overwrite with backup`,添加 `--overwrite`。-- 如果用户选择 `review first`,在执行前停止并审查相关文件。-- 如果用户选择 `keep existing skills`,添加 `--skill-conflict skip`。-- 如果用户选择 `overwrite conflicting skills with backup`,添加 `--skill-conflict overwrite`。-- 如果用户选择 `import conflicting skills under renamed folders`,添加 `--skill-conflict rename`。-- 如果用户选择 `user-data only`,使用 `--preset user-data` 执行,**不**添加 `--migrate-secrets`。-- 如果用户选择 `full compatible migration`,使用 `--preset full --migrate-secrets` 执行。-- 仅在用户明确提供绝对工作区路径时,才添加 `--workspace-target`。-- 如果用户选择 `skip workspace instructions` 或 `decide later`,不添加 `--workspace-target`。--执行前,用简洁语言重述精确的命令计划,并确保其与用户的选择一致。--## 运行后报告规则--执行后,将脚本的 JSON 输出作为事实来源。--1. 所有计数基于 `report.summary`。-2. 仅当 `status` 恰好为 `migrated` 时,才将该项列入"已成功迁移"。-3. 除非报告显示该项为 `migrated`,否则不得声称冲突已解决。-4. 除非 `kind="soul"` 的报告项 `status="migrated"`,否则不得声称 `SOUL.md` 已被覆盖。-5. 如果 `report.summary.conflict > 0`,包含冲突部分,而非静默暗示成功。-6. 如果计数与列出的项不一致,在回复前修正列表以匹配报告。-7. 在可用时包含报告中的 `output_dir` 路径,以便用户检查 `report.json`、`summary.md`、备份和归档文件。-8. 对于记忆或用户档案溢出,除非报告明确显示归档路径,否则不得声称条目已被归档。如果 `details.overflow_file` 存在,说明完整溢出列表已导出到该位置。-9. 如果 skill 以重命名文件夹导入,报告最终目标并提及 `details.renamed_from`。-10. 如果 `report.skill_conflict_mode` 存在,将其作为所选已导入 skill 冲突策略的事实来源。-11. 如果某项 `status="skipped"`,不得将其描述为已覆盖、已备份、已迁移或已解决。-12. 如果 `kind="soul"` 的 `status="skipped"` 且原因为 `Target already matches source`,说明其保持不变,不提及备份。-13. 如果重命名的已导入 skill 的 `details.backup` 为空,不得暗示现有 Hermes skill 已被重命名或备份。仅说明已导入的副本被放置在新目标位置,并将 `details.renamed_from` 作为保持原位的已有文件夹引用。--## 迁移 preset--正常使用时优先选择以下两个 preset:--- `user-data`-- `full`--`user-data` 包含:--- `soul`-- `workspace-agents`-- `memory`-- `user-profile`-- `messaging-settings`-- `command-allowlist`-- `skills`-- `tts-assets`-- `archive`--`full` 包含 `user-data` 中的所有内容,另加:--- `secret-settings`--辅助脚本仍支持类别级别的 `--include` / `--exclude`,但将其视为高级备用方案,而非默认用户体验。--## 命令--完整发现的 dry run:--```bash-python3 ~/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py-```--使用终端工具时,优先使用绝对调用模式,例如:--```json-{"command":"python3 /home/USER/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py","workdir":"/home/USER"}-```--使用 user-data preset 的 dry run:--```bash-python3 ~/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py --preset user-data-```--执行 user-data 迁移:--```bash-python3 ~/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py --execute --preset user-data --skill-conflict skip-```--执行完整兼容迁移:--```bash-python3 ~/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py --execute --preset full --migrate-secrets --skill-conflict skip-```--包含工作区指令的执行:--```bash-python3 ~/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py --execute --preset user-data --skill-conflict rename --workspace-target "/absolute/workspace/path"-```--默认情况下不要使用 `$PWD` 或主目录作为工作区目标。请先明确询问工作区路径。--## 重要规则--1. 除非用户明确表示立即执行,否则在写入前先运行 dry run。-2. 默认不迁移 secret。Token、认证 blob、设备凭据和原始 gateway 配置应保留在 Hermes 之外,除非用户明确要求迁移 secret。-3. 除非用户明确要求,否则不得静默覆盖非空的 Hermes 目标。辅助脚本在启用覆盖时会保留备份。-4. 始终向用户提供跳过项报告。该报告是迁移的一部分,而非可选附加内容。-5. 优先使用主 OpenClaw 工作区(`~/.openclaw/workspace/`)而非 `workspace.default/`。仅在主文件缺失时才使用默认工作区作为备用。-6. 即使在 secret 迁移模式下,也只迁移具有干净 Hermes 目标的 secret。不支持的认证 blob 仍须报告为已跳过。-7. 如果 dry run 显示大型资产复制、冲突的 `SOUL.md` 或溢出的记忆条目,在执行前单独指出这些情况。-8. 如果用户不确定,默认选择 `user-data only`。-9. 仅在用户明确提供目标工作区路径时,才包含 `workspace-agents`。-10. 将类别级别的 `--include` / `--exclude` 视为高级逃生通道,而非正常流程。-11. 如果 `clarify` 可用,不得在 dry run 摘要结尾使用含糊的"您希望怎么做?"。改用结构化的后续提示。-12. 当真实选择提示可用时,不要使用开放式 `clarify` 提示。优先使用可选选项,仅对绝对路径或文件审查请求使用自由文本。-13. dry run 后,如果仍有未解决的决策,不得在摘要后停止。立即对最高优先级的阻塞决策使用 `clarify`。-14. 后续问题的优先顺序:- - `SOUL.md` 冲突- - 已导入 skill 冲突- - 迁移模式- - 工作区指令目标-15. 不得在同一消息中承诺稍后呈现选项。通过实际调用 `clarify` 来呈现它们。-16. 在收到迁移模式答案后,明确检查 `workspace-agents` 是否仍未解决。如果是,下一个动作必须是工作区指令的 `clarify` 调用。-17. 在任何 `clarify` 答案之后,如果还有其他必要决策待处理,不要叙述刚刚决定的内容。立即提出下一个必要问题。--## 预期结果--成功运行后,用户应拥有:--- 已导入的 Hermes persona 状态-- 已填充转换后 OpenClaw 知识的 Hermes 记忆文件-- 在 `~/.hermes/skills/openclaw-imports/` 下可用的 OpenClaw skill-- 显示任何冲突、遗漏或不支持数据的迁移报告\ No newline at end of filediff --git a/website/sidebars.ts b/website/sidebars.tsindex d7cd25f6de7..59c6eab5443 100644--- a/website/sidebars.ts+++ b/website/sidebars.ts@@ -488,15 +488,6 @@ const sidebars: SidebarsConfig = {'user-guide/skills/optional/mcp/mcp-mcporter',],},- {- type: 'category',- label: 'migration',- key: 'skills-optional-migration',- collapsed: true,- items: [- 'user-guide/skills/optional/migration/migration-openclaw-migration',- ],- },{type: 'category',label: 'mlops',