Skip to content

The agent that grows with you

refactor(sessions): one export-guard helper and refusal text for CLI and console

kshitijk4poor2358519860bc
diff --git a/hermes_cli/console_engine.py b/hermes_cli/console_engine.py
index 98ae62c728b..fe5431b43b0 100644
--- a/hermes_cli/console_engine.py
+++ b/hermes_cli/console_engine.py
@@ -651,20 +651,11 @@ def _config_migrate(_engine: HermesConsoleEngine, args: list[str]) -> None:
def _guard_exports(db, session_ids: list[str]) -> None:
"""Per-session export budget: only an individual runaway transcript trips it; 0 disables."""
- from hermes_state import SessionExportTooLargeError, resolved_max_export_messages
- limit = resolved_max_export_messages()
- if limit <= 0:
- return
+ from hermes_state import SessionExportTooLargeError, export_too_large_message
try:
- for session_id in session_ids:
- db.assert_export_safe(session_id, max_messages=limit)
+ db.assert_exports_safe(session_ids)
except SessionExportTooLargeError as exc:
- raise ConsoleCommandError(
- f"Session '{exc.session_id}' has more than {limit:,} "
- "exportable messages; in-memory export is capped per session. "
- "Use the Sessions page's streaming Export action, or set "
- "sessions.max_export_messages: 0 in config.yaml to disable "
- "the guard.") from exc
+ raise ConsoleCommandError(export_too_large_message(exc)) from exc
@_captured
diff --git a/hermes_cli/sessions_cmd.py b/hermes_cli/sessions_cmd.py
index d47af13ee2a..d5efc4160f7 100644
--- a/hermes_cli/sessions_cmd.py
+++ b/hermes_cli/sessions_cmd.py
@@ -341,29 +341,26 @@ def _cmd_export(db, args):
# --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))
- # A shown transcript is the display history; the json/jsonl backup is the TRANSFER projection —
- # every row with its active/compacted flags, so an import restores a compacted session's whole
- # history (live-only dropped every turn in-place compaction archived; #122679 fixed only the
- # console export).
+ # 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}
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
+ from hermes_state import SessionExportTooLargeError, export_too_large_message, resolved_max_export_messages
if shown:
return False
+ limit = resolved_max_export_messages()
+ if limit == 0:
+ return False # resolved before the bare-path scan: a disabled guard costs nothing
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)
+ db.assert_exports_safe(session_ids, max_messages=limit)
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.")
+ print(f"Error: {export_too_large_message(exc)}")
return True
return False
diff --git a/hermes_state.py b/hermes_state.py
index bbb6bca3773..affa023a8ac 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -130,6 +130,15 @@ class SessionExportTooLargeError(ValueError):
)
+def export_too_large_message(exc: SessionExportTooLargeError) -> str:
+ """User-facing refusal shared by every in-memory JSON/JSONL export (CLI and console)."""
+ return (
+ f"Session '{exc.session_id}' has more than {exc.limit:,} exportable 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."
+ )
+
+
def _compression_lock_holder_process_is_dead(holder: str) -> bool:
"""True only when a ``pid=<n>`` lock holder's local PID is provably gone.
Reclaim on kernel proof only: unstructured/same-process holders (another
diff --git a/hermes_state_sessions.py b/hermes_state_sessions.py
index b70536ebd62..31963330800 100644
--- a/hermes_state_sessions.py
+++ b/hermes_state_sessions.py
@@ -1460,6 +1460,16 @@ class SessionSessionsMixin:
raise SessionExportTooLargeError(session_id, message_count, max_messages)
return message_count
+ def assert_exports_safe(self, session_ids, max_messages: Optional[int] = None) -> None:
+ """assert_export_safe for each id with the limit resolved once; 0 disables (no queries)."""
+ from hermes_state import resolved_max_export_messages
+ if max_messages is None:
+ max_messages = resolved_max_export_messages()
+ if max_messages == 0:
+ return
+ for session_id in session_ids:
+ self.assert_export_safe(session_id, max_messages=max_messages)
+
def _is_explicit_branch_session(self, session_id: str) -> bool:
"""Copied user-facing branch (``_branched_from``)? Branches own a copied transcript;
compression continuations need the parent's archived rows."""
diff --git a/tests/hermes_cli/test_sessions_export_backup_round_trip.py b/tests/hermes_cli/test_sessions_export_backup_round_trip.py
index 136344ff28f..3a03e3d767c 100644
--- a/tests/hermes_cli/test_sessions_export_backup_round_trip.py
+++ b/tests/hermes_cli/test_sessions_export_backup_round_trip.py
@@ -71,10 +71,11 @@ def test_jsonl_backup_refuses_a_session_over_max_export_messages(tmp_path, monke
cfg = load_config()
cfg.setdefault("sessions", {})["max_export_messages"] = live + 1
save_config(cfg)
- assert live < live + 1 < stored
+ assert stored > live + 1
backup = tmp_path / "backup.jsonl"
_export(monkeypatch, backup, *selection)
assert not backup.exists()
- assert SID in capsys.readouterr().out
+ out = capsys.readouterr().out
+ assert SID in out and "max_export_messages" in out
diff --git a/tests/hermes_cli/test_sessions_export_output_dir.py b/tests/hermes_cli/test_sessions_export_output_dir.py
index 50fcec6e00d..0e5321e0f4e 100644
--- a/tests/hermes_cli/test_sessions_export_output_dir.py
+++ b/tests/hermes_cli/test_sessions_export_output_dir.py
@@ -14,8 +14,8 @@ 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 assert_exports_safe(self, session_ids, max_messages=None):
+ return None
def close(self):
pass
diff --git a/website/docs/user-guide/sessions.md b/website/docs/user-guide/sessions.md
index 8f6c6204de9..0e28eec6a28 100644
--- a/website/docs/user-guide/sessions.md
+++ b/website/docs/user-guide/sessions.md
@@ -1110,7 +1110,7 @@ never closed by this sweep.
### Oversized-Transcript Guards
Two limits stop a runaway transcript from being loaded into memory all at once
-(both default to `20000` active messages; `0` disables the guard):
+(both default to `20000` messages; `0` disables the guard):
```yaml
sessions: