The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(sessions): address review — guard the JSONL backup with max_export_messages; document it
Froraut0f548a9cf9e9
diff --git a/hermes_cli/sessions_cmd.py b/hermes_cli/sessions_cmd.pyindex fd22b0386df..d47af13ee2a 100644--- a/hermes_cli/sessions_cmd.py+++ b/hermes_cli/sessions_cmd.py@@ -347,12 +347,34 @@ def _cmd_export(db, args):# console export).projection = {"include_compacted": True} if shown else {"include_inactive": True}+ def _too_large(session_ids=None) -> bool:+ """The transfer projection holds every stored row in memory: the console export's per-session+ ``sessions.max_export_messages`` guard (0 disables) runs before any is loaded. ``None`` = the+ sessions a bare export loads."""+ from hermes_state import SessionExportTooLargeError+ if shown:+ return False+ if session_ids is None:+ session_ids = [s["id"] for s in db.search_sessions(source=None, limit=100000)]+ try:+ for session_id in session_ids:+ db.assert_export_safe(session_id)+ except SessionExportTooLargeError as exc:+ print(f"Error: session '{exc.session_id}' has more than {exc.limit:,} stored messages; the "+ "JSON/JSONL backup is built in memory and capped per session. Use the dashboard Sessions "+ "page's streaming Export action, or set sessions.max_export_messages: 0 in config.yaml "+ "to disable the guard.")+ return True+ return False+def _collect_sessions():"""--session-id / filters / bare export -> redacted session dicts, or None after printing an error."""def _one(session_id):return _redact(db.export_session(session_id, **projection))if args.session_id:resolved = db.resolve_session_id(args.session_id)+ if resolved and _too_large([resolved]):+ return Nonedata = _one(resolved) if resolved else Noneif not data:_not_found(args.session_id)@@ -362,9 +384,13 @@ def _cmd_export(db, args):candidates = db.list_prune_candidates(**filters)if args.dry_run:return _print_dry_run_preview(candidates, filters)+ if _too_large([row["id"] for row in candidates]):+ return Nonereturn [s for s in (_one(row["id"]) for row in candidates) if s]if args.dry_run:return print("--dry-run requires at least one filter.")+ if _too_large():+ return Nonereturn [_redact(s) for s in db.export_all(source=None, **projection)]if getattr(args, "only", None):return _export_flat("only", args, _collect_sessions)diff --git a/tests/hermes_cli/test_sessions_export_backup_round_trip.py b/tests/hermes_cli/test_sessions_export_backup_round_trip.pyindex 4bb236b934b..136344ff28f 100644--- a/tests/hermes_cli/test_sessions_export_backup_round_trip.py+++ b/tests/hermes_cli/test_sessions_export_backup_round_trip.py@@ -1,10 +1,14 @@"""`hermes sessions export` JSONL — the documented backup format — must round-trip a compactedsession: import restores the turns in-place compaction archived, still archived (#122679 fixed-only the console export; the primary CLI kept the live-only projection)."""+only the console export; the primary CLI kept the live-only projection). That backup materializes+every stored row in memory, so it is bounded per session by ``sessions.max_export_messages``, as the+console export is."""import jsonimport sys+import pytest+import hermes_cli.main as main_modfrom hermes_state import SessionDB@@ -16,7 +20,8 @@ def _shape(db, **flags):for m in db.get_messages(SID, **flags)]-def test_jsonl_backup_round_trips_compaction_archived_turns(tmp_path, monkeypatch):+def _seed_compacted_session() -> SessionDB:+ """8 turns compacted to a summary + 2-row live tail: few live rows, many stored rows."""src = SessionDB()src.create_session(SID, source="cli")for i in range(1, 5):@@ -24,13 +29,22 @@ def test_jsonl_backup_round_trips_compaction_archived_turns(tmp_path, monkeypatcsrc.append_message(SID, "assistant", f"answer {i}")tail = src.get_messages(SID)[-2:]src.archive_and_compact(SID, [{"role": "user", "content": "[summary]"}, *tail], tail_count=2)+ return src+++def _export(monkeypatch, backup, *selection):+ monkeypatch.setattr(sys, "argv", ["hermes", "sessions", "export", str(backup), *selection])+ main_mod.main()+++def test_jsonl_backup_round_trips_compaction_archived_turns(tmp_path, monkeypatch):+ src = _seed_compacted_session()shown, live = _shape(src, include_compacted=True), _shape(src)src.close()assert len(shown) > len(live)backup = tmp_path / "backup.jsonl"- monkeypatch.setattr(sys, "argv", ["hermes", "sessions", "export", str(backup)])- main_mod.main()+ _export(monkeypatch, backup)dst = SessionDB(db_path=tmp_path / "restored.db")try:@@ -40,3 +54,27 @@ def test_jsonl_backup_round_trips_compaction_archived_turns(tmp_path, monkeypatcassert _shape(dst) == live, "archived turns must not come back as live context"finally:dst.close()++[email protected]("selection", [("--session-id", SID), ("--source", "cli"), ()],+ ids=["session-id", "filter", "bare"])+def test_jsonl_backup_refuses_a_session_over_max_export_messages(tmp_path, monkeypatch, capsys, selection):+ """Every selection path applies the per-session guard to the STORED row count the backup+ materializes, so a small live tail over a large archive cannot slip past it."""+ from hermes_cli.config import load_config, save_config++ src = _seed_compacted_session()+ live = len(_shape(src))+ stored = len(_shape(src, include_inactive=True))+ src.end_session(SID, "user_exit") # bulk filters match ended sessions+ src.close()+ cfg = load_config()+ cfg.setdefault("sessions", {})["max_export_messages"] = live + 1+ save_config(cfg)+ assert live < live + 1 < stored++ backup = tmp_path / "backup.jsonl"+ _export(monkeypatch, backup, *selection)++ assert not backup.exists()+ assert SID in capsys.readouterr().outdiff --git a/tests/hermes_cli/test_sessions_export_output_dir.py b/tests/hermes_cli/test_sessions_export_output_dir.pyindex cd7aa5b102c..50fcec6e00d 100644--- a/tests/hermes_cli/test_sessions_export_output_dir.py+++ b/tests/hermes_cli/test_sessions_export_output_dir.py@@ -14,6 +14,9 @@ class _FakeDB:def export_session(self, session_id, **_projection):return {"id": "sess-123", "source": "cli", "messages": [{"role": "user", "content": "hi"}]}+ def assert_export_safe(self, session_id, max_messages=None):+ return 1+def close(self):passdiff --git a/website/docs/user-guide/sessions.md b/website/docs/user-guide/sessions.mdindex 8ad285e0003..8f6c6204de9 100644--- a/website/docs/user-guide/sessions.md+++ b/website/docs/user-guide/sessions.md@@ -385,7 +385,7 @@ hermes sessions export ~/exports/ --session-id 20250305_091523_a1b2c3d4hermes sessions export backup.jsonl --redact```-Exported files contain one JSON object per line with full session metadata and all messages.+Exported files contain one JSON object per line with full session metadata and every stored message, each with its `active`/`compacted` flags. That includes turns archived by in-place compaction and messages removed by rewind or edit. Importing the file (the dashboard's session import) restores those rows as archived history, not as live model context. Treat a backup as holding everything the session ever contained. To share a conversation, export a display format (`--format md` or `html`, which holds only the history the session shows) with `--redact`. Each session's backup is built in memory, so a session with more stored rows than `sessions.max_export_messages` is refused (see [Oversized-Transcript Guards](#oversized-transcript-guards)).Each record also carries a `timings` block derived from the message timestamps, so a reader of an export attached to a bug report can tell a single long model gap from many small tool round-trips without reconstructing it by hand. It holds only ids, roles, counts and durations — `wall_clock_ms`, `largest_gap_ms`, `role_counts`, `tool_calls_emitted` and per-message `intervals` — never prompt text, tool arguments or results, so it survives `--redact` unchanged. Hermes does not persist a model/tool stopwatch, so `complete` is always `false`; when a session has no timestamped messages, `available` is `false` and `unavailable_reason` says why. The block is rebuilt on every export and ignored (and not counted toward size limits) on import.@@ -456,7 +456,7 @@ hermes sessions export --format md --model sonnet --min-messages 50 --redacthermes sessions export --format md --session-id 20250305_091523_a1b2c3d4 --delete-after-verified --yes```-Markdown/QMD export writes one `.md` or `.qmd` file per exported session plus a `manifest.jsonl` with the file path, message count, lineage ids, and SHA-256. Bulk export requires at least one filter; a bare bulk export is refused. `--delete-after-verified` is intentionally limited to `--session-id` and requires `--yes`. Because deleting a parent session also removes its delegate/subagent sessions, this mode exports and verifies each delegate in a separate file before deleting anything. Markdown/QMD files hold the full history shown by the session, including turns archived by in-place compaction. Deletion compares that exact display transcript and the delegate set again inside the same database transaction that performs the delete; any intervening append, rewrite, rewind, compaction, or delegate change refuses deletion. The same display-history rule applies to `--format html`, `--only user-prompts` (with either Markdown or JSONL output), and `/save md|html`. Full-session JSON/JSONL exports and `/save json` remain live-only because importing archived turns would restore them as live model context. `--redact` scrubs secrets (API keys, tokens, credentials) from message content and tool output before writing — recommended for any export you plan to share.+Markdown/QMD export writes one `.md` or `.qmd` file per exported session plus a `manifest.jsonl` with the file path, message count, lineage ids, and SHA-256. Bulk export requires at least one filter; a bare bulk export is refused. `--delete-after-verified` is intentionally limited to `--session-id` and requires `--yes`. Because deleting a parent session also removes its delegate/subagent sessions, this mode exports and verifies each delegate in a separate file before deleting anything. Markdown/QMD files hold the full history shown by the session, including turns archived by in-place compaction. Deletion compares that exact display transcript and the delegate set again inside the same database transaction that performs the delete; any intervening append, rewrite, rewind, compaction, or delegate change refuses deletion. The same display-history rule applies to `--format html`, `--only user-prompts` (with either Markdown or JSONL output), and `/save md|html`. Full-session JSON/JSONL exports (`hermes sessions export` without `--only`) are backups of every stored row, archived rows included (see [Export Sessions](#export-sessions)). `/save json` remains live-only. `--redact` scrubs secrets (API keys, tokens, credentials) from message content and tool output before writing — recommended for any export you plan to share.### Delete a Session@@ -1118,6 +1118,11 @@ sessions:max_export_messages: 20000 # one-shot in-memory export of a single session```+`max_export_messages` applies per session to the JSON/JSONL backup (`hermes sessions export`, and+`sessions export` in `hermes console`). It counts every stored row, archived included, because+the backup holds all of them. A heavily compacted session with a small live tail can still exceed it.+The dashboard Sessions page's Export action streams the rows instead and is not capped.+`max_resume_messages` bounds **what the resume actually loads**, not the wholehistory of the conversation:@@ -1133,7 +1138,8 @@ history of the conversation:When a resume is refused the client receives error code `4130` with the countand the scope it was measured against (`across its lineage` or-`in its tip segment`). `hermes sessions export` still works for such sessions.+`in its tip segment`). `hermes sessions export` still works for such sessions; its JSON/JSONL+backup needs each session to stay under `max_export_messages`.### Manual Cleanup