Skip to content

The agent that grows with you

fix(sessions): /save json snapshots keep compaction-archived turns too

John Paul Soliva9cb2fddee47e
diff --git a/gateway/slash_commands_session.py b/gateway/slash_commands_session.py
index f1c54312edd..a4cd3111943 100644
--- a/gateway/slash_commands_session.py
+++ b/gateway/slash_commands_session.py
@@ -716,7 +716,7 @@ class GatewaySessionCommandsMixin:
"""Handle /save — export the current session and send it as a document."""
import tempfile
from hermes_cli.session_export import (
- SAVE_TRANSCRIPT_FORMATS, SAVE_USAGE, default_save_filename, normalize_save_format,
+ SAVE_TRANSCRIPT_FORMATS, SAVE_USAGE, default_save_filename, export_projection, normalize_save_format,
render_session_for_save)
parts = event.get_command_args().split()
@@ -738,7 +738,7 @@ class GatewaySessionCommandsMixin:
# Never trust path separators from chat input; the filename is only echoed to the platform.
filename = parts[1] if len(parts) > 1 else default_save_filename(session_id, fmt)
filename = os.path.basename(filename) or default_save_filename(session_id, fmt)
- export_data = await self._session_db.export_session(session_id, include_compacted=fmt in SAVE_TRANSCRIPT_FORMATS)
+ export_data = await self._session_db.export_session(session_id, **export_projection(fmt in SAVE_TRANSCRIPT_FORMATS))
if not export_data:
return t("gateway.save.no_messages", session_id=session_id)
if redact:
diff --git a/hermes_cli/cli_session_mixin.py b/hermes_cli/cli_session_mixin.py
index 59371922bab..e20ffe743e0 100644
--- a/hermes_cli/cli_session_mixin.py
+++ b/hermes_cli/cli_session_mixin.py
@@ -631,7 +631,7 @@ class CLISessionMixin:
"""
from cli import datetime
from hermes_cli.session_export import (
- SAVE_TRANSCRIPT_FORMATS, SAVE_USAGE, normalize_save_format, render_session_for_save)
+ SAVE_TRANSCRIPT_FORMATS, SAVE_USAGE, export_projection, normalize_save_format, render_session_for_save)
parts = cmd.split()[1:]
redact = bool(parts) and parts[-1].lower() in ("redact", "--redact")
@@ -655,7 +655,7 @@ class CLISessionMixin:
_sid = getattr(self, "session_id", None)
if _db and _sid:
try:
- session_data = _db.export_session(_sid, include_compacted=fmt in SAVE_TRANSCRIPT_FORMATS)
+ session_data = _db.export_session(_sid, **export_projection(fmt in SAVE_TRANSCRIPT_FORMATS))
except Exception:
session_data = None
if not session_data:
diff --git a/hermes_cli/session_export.py b/hermes_cli/session_export.py
index 188ba4ca8b9..d3f00471730 100644
--- a/hermes_cli/session_export.py
+++ b/hermes_cli/session_export.py
@@ -207,10 +207,16 @@ def _fenced_text(text: str, *, language: str = "text") -> str:
# --- Current-session save helper (shared by CLI /save and gateway /save) ---
SAVE_FORMATS = ("json", "md", "html")
-# Transcripts show what the user sees, compaction-archived turns included. JSON stays the live rows that
-# import_sessions restores: it would replay archived turns as live context.
SAVE_TRANSCRIPT_FORMATS = frozenset({"md", "html"})
+
+def export_projection(transcript: bool) -> Dict[str, bool]:
+ """``export_session`` flags for an export. A transcript shows what the user sees, compaction-archived
+ turns included. A JSON snapshot is what an import restores, so it carries every stored row with its
+ ``active``/``compacted`` flags: live rows alone would drop every turn in-place compaction archived, and
+ ``import_sessions`` brings the flagged rows back archived, never as live context."""
+ return {"include_compacted": True} if transcript else {"include_inactive": True}
+
SAVE_USAGE = """/save — export the current session to a file
Usage: /save <format> [filename] [redact]
diff --git a/hermes_cli/sessions_cmd.py b/hermes_cli/sessions_cmd.py
index fa00c0008b6..8fbc599fb2c 100644
--- a/hermes_cli/sessions_cmd.py
+++ b/hermes_cli/sessions_cmd.py
@@ -340,13 +340,10 @@ def _cmd_export(db, args):
from hermes_cli.session_export_md import redact_session_data
return redact_session_data(data)
- from hermes_cli.session_export import SAVE_TRANSCRIPT_FORMATS
+ from hermes_cli.session_export import SAVE_TRANSCRIPT_FORMATS, export_projection
# --only is a transcript view too (md/jsonl of what the user saw); md/qmd without --only go to _export_markdown.
shown = args.format in SAVE_TRANSCRIPT_FORMATS or bool(getattr(args, "only", None))
-
- # The json/jsonl backup is the TRANSFER projection (every row with its active/compacted flags) so
- # an import restores a compacted session's archived turns; a shown transcript is display history.
- projection = {"include_compacted": True} if shown else {"include_inactive": True}
+ projection = export_projection(shown)
def _too_large(session_ids=None) -> bool:
"""The transfer projection holds every stored row in memory: the console export's per-session
diff --git a/tests/hermes_cli/test_save_transcript_history.py b/tests/hermes_cli/test_save_transcript_history.py
index 97949a005ab..84c495b3f2b 100644
--- a/tests/hermes_cli/test_save_transcript_history.py
+++ b/tests/hermes_cli/test_save_transcript_history.py
@@ -65,3 +65,28 @@ def test_save_transcript_holds_display_history(tmp_path, monkeypatch, save):
finally:
db.close()
assert [f"answer {i}" in text for i in range(1, 7)] == [True] * 6
+
+
[email protected]("save", [_cli_save, _gateway_save], ids=["cli", "gateway"])
+def test_save_json_restores_compacted_history_as_archived(tmp_path, monkeypatch, save):
+ """/save json is the snapshot the dashboard import restores: the turns compaction archived come back
+ in the display history, and stay out of the live context."""
+ import json
+
+ from hermes_state import SessionDB
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ db = _compacted_store(tmp_path / "state.db")
+ shape = lambda store, **flags: [(m["role"], m["content"]) for m in store.get_messages("s1", **flags)] # noqa: E731
+ try:
+ shown, live = shape(db, include_compacted=True), shape(db)
+ snapshot = json.loads(save(db, "json", tmp_path / "saved.json"))
+ finally:
+ db.close()
+ restored = SessionDB(db_path=tmp_path / "restored.db")
+ try:
+ assert restored.import_sessions([snapshot])["ok"]
+ assert shape(restored, include_compacted=True) == shown
+ assert shape(restored) == live
+ finally:
+ restored.close()
diff --git a/website/docs/user-guide/sessions.md b/website/docs/user-guide/sessions.md
index 4ead2264d04..3cf4f9625f6 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_a1b2c3d4
hermes sessions export backup.jsonl --redact
```
-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)).
+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. A `/save json` snapshot holds the same rows. 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)).
Filtered exports include matching pinned and archived sessions. Pinning protects a session from pruning, rather than excluding it from a backup. If an explicit `--session-id` cannot be resolved, export exits with a non-zero status and creates no output file.
@@ -458,7 +458,7 @@ hermes sessions export --format md --model sonnet --min-messages 50 --redact
hermes 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 (`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.
+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`) and `/save json` are backups of every stored row, archived rows included (see [Export Sessions](#export-sessions)). `--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
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/sessions.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/sessions.md
index 208987be459..fa2bdb53514 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/sessions.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/sessions.md
@@ -301,7 +301,7 @@ hermes sessions export session.jsonl --session-id 20250305_091523_a1b2c3d4
hermes sessions export backup.jsonl --redact
```
-导出文件每行包含一个 JSON 对象,包含完整的 session 元数据和所有消息。
+导出文件每行包含一个 JSON 对象,包含完整的 session 元数据和每一条已存储的消息,每条都带有 `active`/`compacted` 标记。其中包括原地压缩归档的轮次,以及被 rewind 或编辑移除的消息。导入该文件(dashboard 的 session 导入)时,这些行会恢复为已归档的历史,而不会成为活跃的模型上下文。`/save json` 的快照同样如此。请把备份视为包含该 session 曾经有过的全部内容;要分享对话,请用 `--redact` 导出显示格式(`--format md` 或 `html`,只包含 session 显示的历史)。每个 session 的备份在内存中构建,因此已存储行数超过 `sessions.max_export_messages` 的 session 会被拒绝。
#### HTML