The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: import and resume Claude Code / Codex CLI sessions
Teknium04c61f294920
diff --git a/hermes_cli/foreign_sessions.py b/hermes_cli/foreign_sessions.pynew file mode 100644index 00000000000..40407c7f653--- /dev/null+++ b/hermes_cli/foreign_sessions.py@@ -0,0 +1,484 @@+"""Import sessions from foreign coding agents (Claude Code, Codex CLI).++``hermes sessions import`` (and ``--resume @claude`` / ``--resume @codex``)+let a user pull a conversation they started in another agent CLI into+Hermes and continue it here.++Sources (read-only — foreign files are never modified):++* **Claude Code** stores one JSONL file per session under+ ``~/.claude/projects/<encoded-cwd>/<uuid>.jsonl``. Each line is a JSON+ object; ``type: "user"`` / ``type: "assistant"`` lines carry an+ Anthropic-format ``message`` payload whose ``content`` is either a string+ or a list of blocks (``text``, ``tool_use``, ``tool_result``, ...).+ ``type: "summary"`` lines carry a human title for the thread.++* **Codex CLI** stores rollout JSONL under+ ``~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl``. The first line is a+ ``session_meta`` record (cwd, session id); conversation turns are+ ``response_item`` records whose payload is ``{"type": "message",+ "role": user|assistant|developer, "content": [{"type": "input_text"|+ "output_text", "text": ...}]}`` plus ``custom_tool_call`` /+ ``function_call`` payloads for tool activity. (Schema verified against+ real rollout files, Codex CLI 0.147.)++Conversion contract — imported history must satisfy the provider+role-alternation invariant Hermes enforces everywhere else:++* only plain ``user`` / ``assistant`` text messages are produced (tool+ calls become short bracketed summaries inside the assistant text; we+ never fabricate ``tool_calls`` structures);+* consecutive same-role turns are merged rather than stubbed;+* system/developer payloads are never imported.+"""++from __future__ import annotations++import json+import re+import uuid+from dataclasses import dataclass+from datetime import datetime+from pathlib import Path+from typing import Any, Dict, List, Optional, Tuple++# User-message texts that are really injected context wrappers, not typed+# input. Matched against the stripped start of the text.+_WRAPPER_TAG_RE = re.compile(+ r"^<(?:user_instructions|environment_context|recommended_plugins|"+ r"skills_instructions|permissions[_-]instructions|turn_context|"+ r"command-name|command-message|local-command-stdout|system-reminder)\b",+ re.IGNORECASE,+)++_TITLE_MAX = 60+++@dataclass+class ForeignSession:+ """A discoverable session in another tool's on-disk store."""++ source: str # "claude" | "codex"+ path: Path+ mtime: float+ cwd: Optional[str] = None+ title_guess: Optional[str] = None+ turn_count: int = 0+ session_id: Optional[str] = None # the foreign tool's own id++ @property+ def label(self) -> str:+ name = {"claude": "Claude Code", "codex": "Codex CLI"}.get(+ self.source, self.source+ )+ title = (self.title_guess or "").strip() or self.path.stem+ return f"[{name}] {title[:_TITLE_MAX]}"+++def _read_json_lines(path: Path):+ """Yield parsed JSON objects, silently skipping unparseable lines."""+ try:+ with open(path, "r", encoding="utf-8", errors="replace") as f:+ for line in f:+ line = line.strip()+ if not line:+ continue+ try:+ obj = json.loads(line)+ except (json.JSONDecodeError, ValueError):+ continue+ if isinstance(obj, dict):+ yield obj+ except OSError:+ return+++def _flatten_blocks(content: Any, *, source: str) -> str:+ """Flatten a message ``content`` (string or block list) to plain text.++ Tool activity becomes a short bracketed summary; unknown block types+ are skipped rather than guessed at.+ """+ if isinstance(content, str):+ return content+ if not isinstance(content, list):+ return ""+ parts: List[str] = []+ for block in content:+ if not isinstance(block, dict):+ if isinstance(block, str):+ parts.append(block)+ continue+ btype = block.get("type")+ if btype in ("text", "input_text", "output_text"):+ text = block.get("text")+ if isinstance(text, str) and text:+ parts.append(text)+ elif btype == "tool_use": # Claude Code assistant block+ name = block.get("name") or "tool"+ parts.append(f"[ran tool: {name}]")+ elif btype == "tool_result":+ # Tool output echoed into a user message — not typed input.+ continue+ elif btype in ("thinking", "redacted_thinking", "reasoning"):+ continue+ elif btype == "image":+ parts.append("[image]")+ return "\n\n".join(p for p in (s.strip() for s in parts) if p)+++def _is_wrapper_text(text: str) -> bool:+ return bool(_WRAPPER_TAG_RE.match(text.lstrip()))+++def _merge_turns(raw_turns: List[Tuple[str, str]]) -> List[Dict[str, str]]:+ """Merge consecutive same-role turns; guarantee strict alternation.++ A leading assistant turn (session began before the log window) gets a+ minimal user stub so the first message is always ``user``; this is the+ only place a stub is ever inserted.+ """+ merged: List[Dict[str, str]] = []+ for role, text in raw_turns:+ text = text.strip()+ if not text:+ continue+ if merged and merged[-1]["role"] == role:+ merged[-1]["content"] += "\n\n" + text+ else:+ merged.append({"role": role, "content": text})+ if merged and merged[0]["role"] == "assistant":+ merged.insert(+ 0,+ {+ "role": "user",+ "content": "(imported conversation begins with an assistant reply)",+ },+ )+ return merged+++# ── Claude Code ──────────────────────────────────────────────────────────+++def parse_claude_session(path: Path) -> Dict[str, Any]:+ """Parse one Claude Code session JSONL into normalized turns + meta."""+ turns: List[Tuple[str, str]] = []+ cwd: Optional[str] = None+ summary: Optional[str] = None+ session_id: Optional[str] = None+ for obj in _read_json_lines(path):+ otype = obj.get("type")+ if otype == "summary":+ s = obj.get("summary")+ if isinstance(s, str) and s.strip():+ summary = s.strip()+ continue+ if otype not in ("user", "assistant"):+ continue+ if obj.get("isSidechain") or obj.get("isMeta"):+ continue+ if cwd is None and isinstance(obj.get("cwd"), str):+ cwd = obj["cwd"]+ if session_id is None and isinstance(obj.get("sessionId"), str):+ session_id = obj["sessionId"]+ message = obj.get("message")+ if not isinstance(message, dict):+ continue+ role = message.get("role")+ if role not in ("user", "assistant"):+ continue+ text = _flatten_blocks(message.get("content"), source="claude")+ if not text or (role == "user" and _is_wrapper_text(text)):+ continue+ turns.append((role, text))+ return {+ "turns": _merge_turns(turns),+ "cwd": cwd,+ "title_guess": summary or _first_user_line(turns),+ "session_id": session_id,+ }+++def list_claude_sessions(root: Optional[Path] = None) -> List[ForeignSession]:+ """Discover Claude Code sessions under ``~/.claude/projects``."""+ root = Path(root) if root else Path.home() / ".claude" / "projects"+ results: List[ForeignSession] = []+ if not root.is_dir():+ return results+ for jsonl in sorted(root.glob("*/*.jsonl")):+ try:+ mtime = jsonl.stat().st_mtime+ except OSError:+ continue+ parsed = parse_claude_session(jsonl)+ if not parsed["turns"]:+ continue+ results.append(+ ForeignSession(+ source="claude",+ path=jsonl,+ mtime=mtime,+ cwd=parsed["cwd"],+ title_guess=parsed["title_guess"],+ turn_count=len(parsed["turns"]),+ session_id=parsed["session_id"],+ )+ )+ results.sort(key=lambda s: s.mtime, reverse=True)+ return results+++# ── Codex CLI ────────────────────────────────────────────────────────────+++def parse_codex_session(path: Path) -> Dict[str, Any]:+ """Parse one Codex CLI rollout JSONL into normalized turns + meta."""+ turns: List[Tuple[str, str]] = []+ cwd: Optional[str] = None+ session_id: Optional[str] = None+ for obj in _read_json_lines(path):+ otype = obj.get("type")+ payload = obj.get("payload")+ if not isinstance(payload, dict):+ continue+ if otype == "session_meta":+ if isinstance(payload.get("cwd"), str):+ cwd = payload["cwd"]+ sid = payload.get("session_id") or payload.get("id")+ if isinstance(sid, str):+ session_id = sid+ continue+ if otype != "response_item":+ continue+ ptype = payload.get("type")+ if ptype == "message":+ role = payload.get("role")+ if role not in ("user", "assistant"):+ continue # developer/system payloads never imported+ text = _flatten_blocks(payload.get("content"), source="codex")+ if not text or (role == "user" and _is_wrapper_text(text)):+ continue+ turns.append((role, text))+ elif ptype in ("custom_tool_call", "function_call", "local_shell_call"):+ name = payload.get("name") or payload.get("tool") or "tool"+ # Attach as assistant activity; merged into neighbors later.+ turns.append(("assistant", f"[ran tool: {name}]"))+ # tool outputs / reasoning / web_search etc. are skipped+ return {+ "turns": _merge_turns(turns),+ "cwd": cwd,+ "title_guess": _first_user_line(turns),+ "session_id": session_id,+ }+++def list_codex_sessions(root: Optional[Path] = None) -> List[ForeignSession]:+ """Discover Codex CLI rollouts under ``~/.codex/sessions``."""+ root = Path(root) if root else Path.home() / ".codex" / "sessions"+ results: List[ForeignSession] = []+ if not root.is_dir():+ return results+ for jsonl in sorted(root.rglob("rollout-*.jsonl")):+ try:+ mtime = jsonl.stat().st_mtime+ except OSError:+ continue+ parsed = parse_codex_session(jsonl)+ if not parsed["turns"]:+ continue+ results.append(+ ForeignSession(+ source="codex",+ path=jsonl,+ mtime=mtime,+ cwd=parsed["cwd"],+ title_guess=parsed["title_guess"],+ turn_count=len(parsed["turns"]),+ session_id=parsed["session_id"],+ )+ )+ results.sort(key=lambda s: s.mtime, reverse=True)+ return results+++def _first_user_line(turns: List[Tuple[str, str]]) -> Optional[str]:+ for role, text in turns:+ if role == "user":+ line = text.strip().splitlines()[0].strip()+ if line:+ return line[:_TITLE_MAX * 2]+ return None+++# ── Import ───────────────────────────────────────────────────────────────++_SOURCE_LABELS = {"claude": "Claude Code", "codex": "Codex CLI"}+_SOURCE_DB_NAMES = {"claude": "claude-code", "codex": "codex-cli"}+++def import_foreign_session(source: str, path, db=None) -> str:+ """Import one foreign session into the Hermes SessionDB.++ Returns the new Hermes session id. The foreign file is only read.+ Raises ``ValueError`` on unknown source or a session with no usable+ conversation turns.+ """+ source = (source or "").strip().lower().lstrip("@")+ if source not in _SOURCE_LABELS:+ raise ValueError(f"Unknown foreign session source: {source!r}")+ path = Path(path).expanduser()+ if not path.is_file():+ raise ValueError(f"Session file not found: {path}")++ parsed = (+ parse_claude_session(path)+ if source == "claude"+ else parse_codex_session(path)+ )+ turns = parsed["turns"]+ if not turns:+ raise ValueError(+ f"No user/assistant conversation turns found in {path}"+ )++ label = _SOURCE_LABELS[source]+ first_user = _first_user_line(+ [(t["role"], t["content"]) for t in turns]+ ) or path.stem+ if len(first_user) > _TITLE_MAX:+ first_user = first_user[: _TITLE_MAX - 1] + "…"+ title = f"Imported from {label}: {first_user}"++ owns_db = db is None+ if owns_db:+ from hermes_state import SessionDB++ db = SessionDB()+ try:+ session_id = (+ f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}"+ )+ origin = {+ "imported_from": {+ "tool": _SOURCE_DB_NAMES[source],+ "path": str(path),+ "foreign_session_id": parsed.get("session_id"),+ }+ }+ db.create_session(+ session_id,+ source=_SOURCE_DB_NAMES[source],+ cwd=parsed.get("cwd"),+ origin_json=json.dumps(origin),+ )+ for turn in turns:+ db.append_message(session_id, turn["role"], turn["content"])+ try:+ db.set_session_title(session_id, title)+ except Exception:+ pass # title is cosmetic; the import itself succeeded+ return session_id+ finally:+ if owns_db:+ try:+ db.close()+ except Exception:+ pass+++# ── Picker / CLI helpers ─────────────────────────────────────────────────+++def gather_foreign_sessions(+ source: Optional[str] = None,+ *,+ claude_root: Optional[Path] = None,+ codex_root: Optional[Path] = None,+ limit: int = 25,+) -> List[ForeignSession]:+ """List foreign sessions across sources, newest first."""+ sessions: List[ForeignSession] = []+ if source in (None, "claude"):+ sessions.extend(list_claude_sessions(claude_root))+ if source in (None, "codex"):+ sessions.extend(list_codex_sessions(codex_root))+ sessions.sort(key=lambda s: s.mtime, reverse=True)+ return sessions[:limit] if limit else sessions+++def pick_foreign_session(+ source: Optional[str] = None, *, limit: int = 25+) -> Optional[ForeignSession]:+ """Interactive numbered picker. Returns None when nothing was chosen."""+ import os+ import sys++ sessions = gather_foreign_sessions(source, limit=limit)+ if not sessions:+ where = _SOURCE_LABELS.get(source or "", "Claude Code or Codex CLI")+ print(f"No {where} sessions found on this machine.")+ return None+ print("Foreign sessions (newest first):")+ for i, s in enumerate(sessions, 1):+ when = datetime.fromtimestamp(s.mtime).strftime("%Y-%m-%d %H:%M")+ ws = ""+ if s.cwd:+ ws = f" ({os.path.basename(s.cwd.rstrip('/')) or s.cwd})"+ print(f" {i:>2}. {when} {s.label}{ws} [{s.turn_count} turns]")+ if not sys.stdin.isatty():+ print(+ "Non-interactive terminal — pass the file path directly:\n"+ " hermes sessions import --from claude|codex <path>"+ )+ return None+ try:+ raw = input(f"Import which session? [1-{len(sessions)}, empty to cancel] ")+ except (EOFError, KeyboardInterrupt):+ return None+ raw = raw.strip()+ if not raw:+ return None+ try:+ idx = int(raw)+ except ValueError:+ print(f"Not a number: {raw}")+ return None+ if not 1 <= idx <= len(sessions):+ print(f"Out of range: {idx}")+ return None+ return sessions[idx - 1]+++def run_sessions_import(args, db=None) -> Optional[str]:+ """`hermes sessions import` entry point. Returns new session id or None."""+ source = getattr(args, "from_source", None)+ path = getattr(args, "path", None)++ if path:+ if not source:+ # Guess from the path shape.+ p = str(path)+ if "/.claude/" in p or p.endswith(".jsonl") and "claude" in p:+ source = "claude"+ if "/.codex/" in p or Path(p).name.startswith("rollout-"):+ source = "codex"+ if not source:+ print("Cannot infer source from path; pass --from claude|codex.")+ return None+ chosen_path = Path(path)+ else:+ picked = pick_foreign_session(source)+ if picked is None:+ return None+ source, chosen_path = picked.source, picked.path++ try:+ session_id = import_foreign_session(source, chosen_path, db=db)+ except ValueError as e:+ print(f"Error: {e}")+ return None+ label = _SOURCE_LABELS.get(source, source)+ print(f"✓ Imported {label} session as {session_id}")+ print(f" Continue it with: hermes --resume {session_id}")+ return session_iddiff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 610d69ee723..8d87e8e5b57 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -2684,6 +2684,31 @@ def cmd_chat(args):print(f"No previous {kind} session found to continue.")sys.exit(1)+ # --resume @claude / --resume @codex: import a foreign session (Claude+ # Code / Codex CLI) and resume the newly created Hermes session.+ _resume_foreign = getattr(args, "resume", None)+ if isinstance(_resume_foreign, str) and _resume_foreign.strip().lower() in (+ "@claude",+ "@codex",+ ):+ from hermes_cli.foreign_sessions import (+ import_foreign_session,+ pick_foreign_session,+ )++ _foreign_source = _resume_foreign.strip().lower().lstrip("@")+ _picked = pick_foreign_session(_foreign_source)+ if _picked is None:+ sys.exit(1)+ try:+ _imported_id = import_foreign_session(_picked.source, _picked.path)+ except ValueError as e:+ print(f"Error: {e}")+ sys.exit(1)+ print(f"✓ Imported as {_imported_id} — resuming it now.")+ print(f" (later: hermes --resume {_imported_id})")+ args.resume = _imported_id+# Resolve --resume by title if it's not a direct session IDresume_val = getattr(args, "resume", None)if resume_val:@@ -12987,6 +13012,28 @@ def main():"--limit", type=int, default=500, help="Max sessions to load (default: 500)")+ sessions_import = sessions_subparsers.add_parser(+ "import",+ help="Import a Claude Code or Codex CLI session into Hermes",+ description=(+ "Pull a conversation started in Claude Code (~/.claude/projects) "+ "or Codex CLI (~/.codex/sessions) into the Hermes session store "+ "so it can be resumed with 'hermes --resume <id>'. The foreign "+ "files are only read, never modified."+ ),+ )+ sessions_import.add_argument(+ "--from",+ dest="from_source",+ choices=["claude", "codex"],+ help="Which tool to import from (default: pick across both)",+ )+ sessions_import.add_argument(+ "path",+ nargs="?",+ help="Path to a specific session JSONL file (skips the picker)",+ )+# cmd_sessions lives in hermes_cli/sessions_cmd.py (main.py decomposition).# sessions_parser is threaded in via functools.partial because thediff --git a/hermes_cli/sessions_cmd.py b/hermes_cli/sessions_cmd.pyindex d5a33953dc5..25a4d9ec3cd 100644--- a/hermes_cli/sessions_cmd.py+++ b/hermes_cli/sessions_cmd.py@@ -302,6 +302,12 @@ def cmd_sessions(args, sessions_parser=None):print(" Do not install it. Review the JSON report for partial data or errors.")return 1+ if action == "import":+ from hermes_cli.foreign_sessions import run_sessions_import++ run_sessions_import(args)+ return+try:from hermes_state import SessionDBdiff --git a/tests/hermes_cli/test_foreign_sessions.py b/tests/hermes_cli/test_foreign_sessions.pynew file mode 100644index 00000000000..941455af923--- /dev/null+++ b/tests/hermes_cli/test_foreign_sessions.py@@ -0,0 +1,261 @@+"""Tests for hermes_cli.foreign_sessions — Claude Code / Codex CLI import.++Fixture JSONL is synthesized inline (tmp_path); the SessionDB is opened+against a temp path so nothing touches the real HERMES_HOME store.+"""++import json++import pytest++from hermes_cli.foreign_sessions import (+ gather_foreign_sessions,+ import_foreign_session,+ list_claude_sessions,+ list_codex_sessions,+ parse_claude_session,+ parse_codex_session,+)+++# ── fixture builders ─────────────────────────────────────────────────────+++def _claude_lines():+ def msg(role, content):+ return {+ "type": role,+ "sessionId": "abc-123",+ "cwd": "/home/user/proj",+ "message": {"role": role, "content": content},+ }++ return [+ {"type": "summary", "summary": "Fix the flaky test"},+ msg("user", "Please fix the flaky test in CI."),+ msg(+ "assistant",+ [+ {"type": "text", "text": "Looking into it now."},+ {"type": "tool_use", "name": "Bash", "id": "t1", "input": {}},+ ],+ ),+ # tool_result echoed back as a user message — must NOT become a turn+ msg("user", [{"type": "tool_result", "tool_use_id": "t1", "content": "ok"}]),+ msg("assistant", [{"type": "text", "text": "Fixed — the sleep was too short."}]),+ msg("user", "Great, thanks!"),+ msg("assistant", [{"type": "text", "text": "Anytime."}]),+ ]+++def _write_claude_fixture(tmp_path, extra_lines=None):+ proj = tmp_path / ".claude" / "projects" / "-home-user-proj"+ proj.mkdir(parents=True)+ f = proj / "abc-123.jsonl"+ lines = [json.dumps(entry) for entry in _claude_lines()]+ if extra_lines:+ lines = extra_lines + lines+ f.write_text("\n".join(lines) + "\n", encoding="utf-8")+ return f+++def _codex_lines():+ def item(payload):+ return {"timestamp": "2026-08-15T21:35:28Z", "type": "response_item", "payload": payload}++ def message(role, kind, text):+ return item({"type": "message", "role": role, "content": [{"type": kind, "text": text}]})++ return [+ {+ "type": "session_meta",+ "payload": {"session_id": "0000-1111", "cwd": "/home/user/repo"},+ },+ # developer/system payloads must never be imported+ message("developer", "input_text", "<skills_instructions>secret system stuff"),+ message("user", "input_text", "<recommended_plugins>\ninjected wrapper"),+ message("user", "input_text", "Summarize the transcripts please."),+ message("assistant", "output_text", "Reading them one at a time."),+ item({"type": "custom_tool_call", "name": "shell", "call_id": "c1"}),+ item({"type": "custom_tool_call_output", "call_id": "c1", "output": "big output"}),+ message("assistant", "output_text", "Done — here is the summary."),+ message("user", "input_text", "Now write it to a file."),+ message("assistant", "output_text", "Written to summary.md."),+ ]+++def _write_codex_fixture(tmp_path, extra_lines=None):+ day = tmp_path / ".codex" / "sessions" / "2026" / "08" / "15"+ day.mkdir(parents=True)+ f = day / "rollout-2026-08-15T21-35-28-0000-1111.jsonl"+ lines = [json.dumps(entry) for entry in _codex_lines()]+ if extra_lines:+ lines = extra_lines + lines+ f.write_text("\n".join(lines) + "\n", encoding="utf-8")+ return f+++def session_db(tmp_path):+ from hermes_state import SessionDB++ db = SessionDB(db_path=tmp_path / "state.db")+ yield db+ db.close()+++def _assert_alternating(messages):+ roles = [m["role"] for m in messages]+ assert roles, "no messages"+ assert roles[0] == "user"+ for a, b in zip(roles, roles[1:]):+ assert a != b, f"two consecutive {a} messages"+++# ── parsing ──────────────────────────────────────────────────────────────+++def test_parse_claude_session(tmp_path):+ f = _write_claude_fixture(tmp_path)+ parsed = parse_claude_session(f)+ turns = parsed["turns"]+ _assert_alternating(turns)+ assert len(turns) == 4 # tool_result-only user line skipped; assistants merge+ assert parsed["cwd"] == "/home/user/proj"+ assert parsed["title_guess"] == "Fix the flaky test"+ assert parsed["session_id"] == "abc-123"+ # tool_use flattened to a bracketed summary, merged with adjacent text+ joined_assistant = "\n".join(t["content"] for t in turns if t["role"] == "assistant")+ assert "[ran tool: Bash]" in joined_assistant+ # no fabricated tool_call structures+ assert all(set(t) == {"role", "content"} for t in turns)+++def test_parse_codex_session(tmp_path):+ f = _write_codex_fixture(tmp_path)+ parsed = parse_codex_session(f)+ turns = parsed["turns"]+ _assert_alternating(turns)+ assert len(turns) == 4+ assert parsed["cwd"] == "/home/user/repo"+ assert parsed["session_id"] == "0000-1111"+ assert parsed["title_guess"].startswith("Summarize the transcripts")+ # developer + wrapper user lines excluded+ all_text = "\n".join(t["content"] for t in turns)+ assert "skills_instructions" not in all_text+ assert "recommended_plugins" not in all_text+ # tool call summarized in assistant text+ assert "[ran tool: shell]" in all_text+++def test_malformed_lines_are_skipped(tmp_path):+ garbage = [+ "this is not json at all {{{",+ '"just a string"',+ json.dumps({"type": "user", "message": "not-a-dict-payload... wait, string"}),+ json.dumps({"type": "user"}), # missing message+ "",+ ]+ f = _write_claude_fixture(tmp_path, extra_lines=garbage)+ parsed = parse_claude_session(f)+ assert len(parsed["turns"]) == 4 # good lines still parse++ g = _write_codex_fixture(tmp_path, extra_lines=["not json", json.dumps({"type": "response_item"})])+ parsed_codex = parse_codex_session(g)+ assert len(parsed_codex["turns"]) == 4+++# ── discovery ────────────────────────────────────────────────────────────+++def test_list_sessions(tmp_path):+ _write_claude_fixture(tmp_path)+ _write_codex_fixture(tmp_path)+ claude = list_claude_sessions(tmp_path / ".claude" / "projects")+ codex = list_codex_sessions(tmp_path / ".codex" / "sessions")+ assert len(claude) == 1 and claude[0].source == "claude"+ assert claude[0].turn_count == 4+ assert len(codex) == 1 and codex[0].source == "codex"+ assert codex[0].turn_count == 4+ both = gather_foreign_sessions(+ claude_root=tmp_path / ".claude" / "projects",+ codex_root=tmp_path / ".codex" / "sessions",+ )+ assert len(both) == 2+ assert both[0].mtime >= both[1].mtime # newest first+++def test_list_sessions_missing_roots(tmp_path):+ assert list_claude_sessions(tmp_path / "nope") == []+ assert list_codex_sessions(tmp_path / "nope") == []+++# ── import into SessionDB ────────────────────────────────────────────────+++def test_import_claude_session(tmp_path, session_db):+ f = _write_claude_fixture(tmp_path)+ session_id = import_foreign_session("claude", f, db=session_db)+ row = session_db.get_session(session_id)+ assert row is not None+ assert row["source"] == "claude-code"+ assert row["cwd"] == "/home/user/proj"+ assert row["message_count"] == 4+ title = session_db.get_session_title(session_id)+ assert title.startswith("Imported from Claude Code: ")+ assert "Please fix the flaky test" in title+ messages = session_db.get_messages(session_id)+ assert len(messages) == 4+ _assert_alternating(messages)+ origin = json.loads(row["origin_json"])+ assert origin["imported_from"]["tool"] == "claude-code"+ assert origin["imported_from"]["path"] == str(f)+++def test_import_codex_session(tmp_path, session_db):+ f = _write_codex_fixture(tmp_path)+ session_id = import_foreign_session("@codex", f, db=session_db)+ row = session_db.get_session(session_id)+ assert row is not None+ assert row["source"] == "codex-cli"+ assert row["message_count"] == 4+ title = session_db.get_session_title(session_id)+ assert title.startswith("Imported from Codex CLI: ")+ messages = session_db.get_messages(session_id)+ _assert_alternating(messages)+ # resumable: resolve_session_id round-trips+ assert session_db.resolve_session_id(session_id) == session_id+++def test_import_rejects_bad_input(tmp_path, session_db):+ with pytest.raises(ValueError, match="Unknown foreign session source"):+ import_foreign_session("gemini", tmp_path / "x.jsonl", db=session_db)+ with pytest.raises(ValueError, match="not found"):+ import_foreign_session("claude", tmp_path / "missing.jsonl", db=session_db)+ empty = tmp_path / "empty.jsonl"+ empty.write_text("not json\n", encoding="utf-8")+ with pytest.raises(ValueError, match="No user/assistant conversation"):+ import_foreign_session("claude", empty, db=session_db)+++def test_leading_assistant_gets_single_stub(tmp_path):+ day = tmp_path / ".codex" / "sessions" / "2026" / "01" / "01"+ day.mkdir(parents=True)+ f = day / "rollout-x.jsonl"+ lines = [+ json.dumps(+ {+ "type": "response_item",+ "payload": {+ "type": "message",+ "role": "assistant",+ "content": [{"type": "output_text", "text": "Continuing from before."}],+ },+ }+ )+ ]+ f.write_text("\n".join(lines) + "\n", encoding="utf-8")+ parsed = parse_codex_session(f)+ _assert_alternating(parsed["turns"])+ assert len(parsed["turns"]) == 2+ assert parsed["turns"][0]["role"] == "user"diff --git a/website/docs/user-guide/sessions.md b/website/docs/user-guide/sessions.mdindex 7d36dfa256e..705e189c80d 100644--- a/website/docs/user-guide/sessions.md+++ b/website/docs/user-guide/sessions.md@@ -610,6 +610,38 @@ routing is the only thing the repair changes. Back up first(`cp ~/.hermes/state.db ~/.hermes/state.db.bak`).+## Importing Sessions from Claude Code and Codex CLI++Started a conversation in another agent CLI? You can pull it into Hermes and+continue it here. Hermes reads Claude Code's session logs+(`~/.claude/projects/`) and Codex CLI's rollouts (`~/.codex/sessions/`) —+the foreign files are only read, never modified.++```bash+# Interactive picker across both tools, newest first+hermes sessions import++# Limit to one tool, or point at a specific file+hermes sessions import --from claude+hermes sessions import --from codex ~/.codex/sessions/2026/08/15/rollout-....jsonl++# Import-and-resume in one step+hermes --resume @claude+hermes --resume @codex+```++`hermes sessions import` creates a new Hermes session titled+`Imported from Claude Code: <first user message>` (or Codex CLI) and prints+the id plus a ready-to-paste `hermes --resume <id>` command.+`--resume @claude` / `--resume @codex` show the same picker and drop you+straight into the imported conversation.++What carries over: the ordered user/assistant conversation, with tool+activity condensed to short `[ran tool: …]` notes inside assistant turns.+System prompts, injected context, reasoning traces, and raw tool output are+left behind — the import is a clean transcript, not a byte-for-byte replay.++## Session Search ToolThe agent has a built-in `session_search` tool that performs full-text search across all past conversations using SQLite's FTS5 engine — and lets the agent scroll through any session it finds. It makes no LLM calls and returns views of actual messages from the DB rather than generating summaries.