The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(sessions): include protected rows in retention backups
itsflownium5b33f3128aca
diff --git a/hermes_cli/sessions_cmd.py b/hermes_cli/sessions_cmd.pyindex 06d220602dd..8e6ef41cd0c 100644--- a/hermes_cli/sessions_cmd.py+++ b/hermes_cli/sessions_cmd.py@@ -328,8 +328,9 @@ def _cmd_export(db, args):except ValueError as e:print(f"Error: {e}")return- # Unlike prune/archive, export includes archived sessions.+ # A backup includes protected rows; prune's keep rules must not omit them.filters["archived"] = None+ filters["include_pinned"] = Truedef _redact(data):if not args.redact or data is None:@@ -365,7 +366,7 @@ def _cmd_export(db, args):return Falsedef _collect_sessions():- """--session-id / filters / bare export -> redacted session dicts, or None after printing an error."""+ """Return exported sessions, a failure exit code, or None for a dry-run preview."""def _one(session_id):return _redact(db.export_session(session_id, **projection))if args.session_id:@@ -374,8 +375,7 @@ def _cmd_export(db, args):return Nonedata = _one(resolved) if resolved else Noneif not data:- _not_found(args.session_id)- return None+ return _not_found(args.session_id)return [data]if filters:candidates = db.list_prune_candidates(**filters)@@ -436,6 +436,8 @@ def _export_flat(kind, args, collect):print(message)returnsessions = collect()+ if isinstance(sessions, int):+ return sessionsif sessions is not None:from hermes_cli.session_export import default_save_filenamename = (default_save_filename(sessions[0].get("id", ""), args.format) if len(sessions) == 1@@ -455,8 +457,7 @@ def _export_trace(db, args, filters):print("No session found to export. Pass --session-id.")returnif session_id and not db.resolve_session_id(session_id):- _not_found(session_id)- return+ return _not_found(session_id)from agent.trace_upload import TraceRedactionError, build_trace_jsonl, upload_session_traceredact_trace = not getattr(args, "no_redact", False)if getattr(args, "upload", False):@@ -559,8 +560,7 @@ def _export_markdown_single(db, args, export_one, output_dir, lineage_is_logicalfrom hermes_cli.session_export_md import verify_export_fileresolved_session_id = db.resolve_session_id(args.session_id)if not resolved_session_id:- _not_found(args.session_id)- return+ return _not_found(args.session_id)delete_target_ids = (db.get_session_delete_targets(resolved_session_id) if args.delete_after_verified else [resolved_session_id])diff --git a/tests/hermes_cli/test_sessions_export_retention.py b/tests/hermes_cli/test_sessions_export_retention.pynew file mode 100644index 00000000000..4d479353200--- /dev/null+++ b/tests/hermes_cli/test_sessions_export_retention.py@@ -0,0 +1,69 @@+"""Regression for #131075: a retention backup must cover the rows prune can delete."""++import json+import sys+from pathlib import Path++import pytest++from hermes_cli import main+from hermes_state import SessionDB+++def store(tmp_path, monkeypatch):+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ with SessionDB() as db:+ for session_id in ("normal", "pinned", "archived"):+ db.create_session(session_id, "cli")+ db.append_message(session_id, "user", f"Keep {session_id}")+ db.end_session(session_id, "done")+ db.set_session_pinned("pinned", True)+ db.set_session_archived("archived", True)+ db._conn.execute("UPDATE sessions SET started_at=1")+ db._conn.commit()+ return home+++def _run(monkeypatch, *args):+ monkeypatch.setattr(sys, "argv", ["hermes", "sessions", *args])+ return main.main()+++def test_filtered_backup_covers_protected_sessions_before_retention_prune(store, tmp_path, monkeypatch):+ backup = tmp_path / "backup.jsonl"+ _run(monkeypatch, "export", "--before", "2000-01-01", "--format", "jsonl", "--yes", str(backup))+ exported = {row["id"]: row for row in map(json.loads, backup.read_text(encoding="utf-8").splitlines())}+ with SessionDB() as db:+ assert Path(db.db_path).resolve().is_relative_to(tmp_path.resolve())+ candidates = db.list_prune_candidates(+ older_than_days=None, started_before=946684800, archived=None, include_pinned=True,+ )+ assert {row["id"] for row in candidates} <= exported.keys()+ for row in candidates:+ assert exported[row["id"]]["messages"]+ assert exported["pinned"]["pinned"] == 1+ assert exported["archived"]["archived"] == 1++ # This fixture is the sole writer; bypass the unrelated host-wide holder inventory.+ _run(monkeypatch, "prune", "--before", "2000-01-01", "--include-archived", "--include-pinned", "--yes", "--force")+ with SessionDB() as db:+ assert all(db.get_session(session_id) is None for session_id in exported)+++def test_explicit_missing_export_fails_without_creating_an_output(store, tmp_path, monkeypatch, capsys):+ for fmt in ("jsonl", "html", "md", "qmd", "trace"):+ output = tmp_path / f"missing-{fmt}"+ with pytest.raises(SystemExit) as error:+ _run(monkeypatch, "export", "--session-id", "missing-session", "--format", fmt, str(output))+ assert error.value.code != 0+ assert "missing-session" in capsys.readouterr().out+ assert not output.exists()++ # An explicit archived id remains exportable; protection flags concern deletion.+ output = tmp_path / "archived.jsonl"+ _run(monkeypatch, "export", "--session-id", "archived", "--format", "jsonl", str(output))+ assert json.loads(output.read_text(encoding="utf-8"))["archived"] == 1diff --git a/website/docs/user-guide/sessions.md b/website/docs/user-guide/sessions.mdindex 0e28eec6a28..4d0370f176f 100644--- a/website/docs/user-guide/sessions.md+++ b/website/docs/user-guide/sessions.md@@ -387,6 +387,8 @@ hermes sessions export backup.jsonl --redactExported 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)).+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.+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.#### HTML