Skip to content

The agent that grows with you

fix(sessions): auto-prune state.db by default (90d) and gate VACUUM on freelist ratio (#54189)

Teknium73f68362b3f6
diff --git a/cli-config.yaml.example b/cli-config.yaml.example
index c18759d2f2a..687badff7d5 100644
--- a/cli-config.yaml.example
+++ b/cli-config.yaml.example
@@ -948,6 +948,32 @@ max_concurrent_sessions: null
# explicitly want one shared "room brain" per group/channel.
group_sessions_per_user: true
+# =============================================================================
+# Session Storage Retention (state.db)
+# =============================================================================
+# ~/.hermes/state.db keeps every session, message, and tool call, plus the
+# FTS5 search indexes. Since #54189, auto-pruning is ON by default so the file
+# stays bounded: at CLI/gateway/cron startup (at most once per
+# min_interval_hours) Hermes deletes ENDED sessions whose last activity is
+# older than retention_days. Open, pinned, and in-progress sessions are never
+# deleted. Stale automation sessions (cron/kanban/subagent/one-shot CLI) whose
+# process died without closing them are first *closed*, then aged through a
+# further full retention window before removal.
+#
+# After a prune that removed rows, VACUUM reclaims disk space only when both
+# the time throttle (min_vacuum_interval_days) has elapsed AND more than 25%
+# of the file's pages are reclaimable — a dense database never pays for a full
+# rewrite to reclaim a few MB.
+#
+# Uncomment to change the defaults shown; set auto_prune: false to keep every
+# ended session forever (the pre-#54189 behavior).
+# sessions:
+# auto_prune: true
+# retention_days: 90
+# vacuum_after_prune: true
+# min_vacuum_interval_days: 30
+# min_interval_hours: 24
+
# Optional direct endpoint for autonomous Bot Mode rooms spanning gateways.
# Leave unset for the safe default: Desktop coordinates cross-gateway rooms and
# same-gateway rooms can still continue on their own. Set this only to the
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index b766a166e53..6cfc67692f9 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -3482,13 +3482,18 @@ DEFAULT_CONFIG = {
# reports 384MB+ databases with 68K+ messages, which slows down FTS5
# inserts, /resume listing, and insights queries.
"sessions": {
- # When true, prune ended sessions inactive for retention_days once
+ # When true, prune ENDED sessions inactive for retention_days once
# per (roughly) min_interval_hours at CLI/gateway/cron startup.
# Activity is the latest message timestamp, falling back to creation
- # time for empty sessions. Active sessions are always preserved.
- # Default false: session history is valuable for search recall, and
- # silently deleting it could surprise users. Opt in explicitly.
- "auto_prune": False,
+ # time for empty sessions. Sessions that are still open, pinned, or
+ # mid-turn are never deleted — the only open rows the sweep touches
+ # are stale automation sessions (cron/kanban/subagent/one-shot CLI)
+ # whose process died without closing them; those are *closed*, not
+ # deleted, and get a further full retention window before removal.
+ # Default true since #54189: without it state.db grows without bound
+ # (multi-GB installs reported within weeks). Set false to keep every
+ # ended session forever.
+ "auto_prune": True,
# How many inactive days of ended-session history to keep. Matches
# the default of ``hermes sessions prune``.
"retention_days": 90,
@@ -3506,7 +3511,9 @@ DEFAULT_CONFIG = {
# subsequent INSERTs — so without VACUUM the file stays bloated
# even after pruning. VACUUM blocks writes for a few seconds per
# 100MB, so it only runs at startup, and only when prune deleted
- # ≥1 session.
+ # ≥1 session AND the reclaimable fraction of the file
+ # (PRAGMA freelist_count / page_count) exceeds 25% — a dense DB
+ # never pays for a full rewrite to reclaim a few MB (#54189).
"vacuum_after_prune": True,
# Minimum days between successful VACUUM rewrites. Pruning can still
# run on its normal cadence while SQLite reuses the freed pages.
diff --git a/hermes_state.py b/hermes_state.py
index 06d7b192337..f9696fc6fd1 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -116,6 +116,13 @@ logger = logging.getLogger(__name__)
MAX_SAFE_RESUME_MESSAGES = 20_000
MAX_SAFE_EXPORT_MESSAGES = 20_000
+# Auto-maintenance only VACUUMs when at least this fraction of the database
+# file is reclaimable (``PRAGMA freelist_count / PRAGMA page_count``). Below
+# it a full rewrite costs more I/O than it returns — pruning a handful of small
+# sessions on a dense multi-GB state.db should never rewrite the whole file to
+# reclaim a few MB (#54189). Composes with ``min_vacuum_interval_days``.
+AUTO_VACUUM_MIN_FREELIST_RATIO = 0.25
+
def _configured_transcript_limit(key: str, fallback: int) -> int:
"""Resolve a transcript safety limit from config at call time.
@@ -16728,6 +16735,31 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
logger.debug("Could not read logical DB size: %s", exc)
return None
+ def _freelist_ratio(self) -> Optional[float]:
+ """Fraction of database pages that are on the freelist (reclaimable).
+
+ ``PRAGMA freelist_count / PRAGMA page_count`` read over the existing
+ connection (never a byte-level probe of the live file — see
+ ``sqlite_safe_read``). This is what VACUUM would actually give back;
+ it is the gate :meth:`maybe_auto_prune_and_vacuum` uses to decide
+ whether a full rewrite pays off (#54189).
+
+ Returns None if the pragmas cannot be read (callers treat that as
+ "unknown" and fall back to the time throttle alone).
+ """
+ try:
+ with self._read_ctx() as conn:
+ if self._conn is None:
+ return None
+ page_count = int(conn.execute("PRAGMA page_count").fetchone()[0])
+ freelist = int(conn.execute("PRAGMA freelist_count").fetchone()[0])
+ if page_count <= 0:
+ return 0.0
+ return freelist / page_count
+ except Exception as exc:
+ logger.debug("Could not read freelist ratio: %s", exc)
+ return None
+
def vacuum(self) -> int:
"""Run VACUUM to reclaim disk space after large deletes.
@@ -16792,15 +16824,21 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
vacuum: bool = True,
sessions_dir: Optional[Path] = None,
min_vacuum_interval_days: int = 30,
+ min_vacuum_freelist_ratio: float = AUTO_VACUUM_MIN_FREELIST_RATIO,
) -> Dict[str, Any]:
"""Idempotent auto-maintenance: prune inactive sessions + optional VACUUM.
Records the last run timestamp in state_meta so subsequent calls
within ``min_interval_hours`` no-op. VACUUM has its own, typically
longer, throttle controlled by ``min_vacuum_interval_days`` so routine
- pruning does not repeatedly rewrite the database. Designed to be
- called once at startup from long-lived entrypoints (CLI, gateway, cron
- scheduler).
+ pruning does not repeatedly rewrite the database, and is additionally
+ gated on the reclaimable fraction of the file: it only runs when
+ ``PRAGMA freelist_count / PRAGMA page_count`` exceeds
+ ``min_vacuum_freelist_ratio`` (default
+ :data:`AUTO_VACUUM_MIN_FREELIST_RATIO`, 25%), so pruning a few small
+ sessions on a dense multi-GB database never triggers a full rewrite
+ (#54189). Designed to be called once at startup from long-lived
+ entrypoints (CLI, gateway, cron scheduler).
When *sessions_dir* is provided, on-disk transcript files
(``.json`` / ``.jsonl`` / ``request_dump_*``) for pruned sessions
@@ -16825,6 +16863,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
- ``"pruned"`` (int) — number of sessions deleted
- ``"closed"`` (int) — stale open state-owned sessions marked ended
- ``"vacuumed"`` (bool) — true if VACUUM ran
+ - ``"freelist_ratio"`` (float|None) — reclaimable fraction measured
+ when a VACUUM was considered (absent when it was not)
- ``"error"`` (str, optional) — present only on failure
"""
result: Dict[str, Any] = {
@@ -16871,13 +16911,19 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
respect_gateway_heartbeats=False,
)
result["closed"] = len(closed)
- # Only VACUUM if we actually freed rows, and no more often than
- # once every min_vacuum_interval_days -- a large prune (e.g. the
- # first one to cross retention_days on a DB with tens of
- # thousands of rows) can free enough pages that pruned > 0 fires
- # on every subsequent startup even though a VACUUM already ran
- # recently. VACUUM on this DB's size (FTS5 shadow tables) is not
- # cheap -- it holds an exclusive lock for the full rewrite.
+ # Only VACUUM if we actually freed rows, no more often than once
+ # every min_vacuum_interval_days, AND only when the rewrite pays
+ # off: the reclaimable fraction of the file (freelist_count /
+ # page_count) must exceed AUTO_VACUUM_MIN_FREELIST_RATIO (#54189).
+ # A large prune (e.g. the first one to cross retention_days on a
+ # DB with tens of thousands of rows) can free enough pages that
+ # pruned > 0 fires on every subsequent startup even though a
+ # VACUUM already ran recently; and pruning one tiny session on a
+ # dense multi-GB DB would otherwise rewrite the whole file to
+ # reclaim a few MB. VACUUM on this DB's size (FTS5 shadow tables)
+ # is not cheap -- it holds an exclusive lock for the full rewrite.
+ # The time throttle says "not too often"; the ratio gate says
+ # "only when it pays off". Both must pass.
last_vacuum_raw = self.get_meta("last_vacuum")
vacuum_due = True
if last_vacuum_raw:
@@ -16886,12 +16932,22 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
except (TypeError, ValueError):
vacuum_due = True
if vacuum and pruned > 0 and vacuum_due:
- try:
- self.vacuum()
- result["vacuumed"] = True
- self.set_meta("last_vacuum", str(now))
- except Exception as exc:
- logger.warning("state.db VACUUM failed: %s", exc)
+ ratio = self._freelist_ratio()
+ result["freelist_ratio"] = ratio
+ if ratio is None or ratio > min_vacuum_freelist_ratio:
+ try:
+ self.vacuum()
+ result["vacuumed"] = True
+ self.set_meta("last_vacuum", str(now))
+ except Exception as exc:
+ logger.warning("state.db VACUUM failed: %s", exc)
+ else:
+ logger.debug(
+ "state.db auto-maintenance: skipping VACUUM, only "
+ "%.1f%% of pages reclaimable (threshold %.0f%%)",
+ ratio * 100.0,
+ min_vacuum_freelist_ratio * 100.0,
+ )
# Record the attempt even if pruned == 0, so we don't retry
# every startup within the min_interval_hours window.
diff --git a/tests/test_hermes_state.py b/tests/test_hermes_state.py
index 04e066858de..a52a90aa653 100644
--- a/tests/test_hermes_state.py
+++ b/tests/test_hermes_state.py
@@ -3007,6 +3007,7 @@ class TestVacuum:
def test_auto_maintenance_records_successful_vacuum(self, db, monkeypatch):
monkeypatch.setattr(db, "prune_sessions", lambda **_kwargs: 3)
+ monkeypatch.setattr(db, "_freelist_ratio", lambda: 0.5) # ratio gate open
vacuum_calls = []
monkeypatch.setattr(db, "vacuum", lambda: vacuum_calls.append(True))
@@ -3018,6 +3019,7 @@ class TestVacuum:
def test_auto_maintenance_skips_recent_vacuum(self, db, monkeypatch):
monkeypatch.setattr(db, "prune_sessions", lambda **_kwargs: 3)
+ monkeypatch.setattr(db, "_freelist_ratio", lambda: 0.5) # ratio gate open
db.set_meta("last_vacuum", str(time.time()))
vacuum_calls = []
monkeypatch.setattr(db, "vacuum", lambda: vacuum_calls.append(True))
@@ -3032,6 +3034,7 @@ class TestVacuum:
def test_auto_maintenance_retries_after_vacuum_interval(self, db, monkeypatch):
monkeypatch.setattr(db, "prune_sessions", lambda **_kwargs: 3)
+ monkeypatch.setattr(db, "_freelist_ratio", lambda: 0.5) # ratio gate open
db.set_meta("last_vacuum", str(time.time() - 31 * 86400))
vacuum_calls = []
monkeypatch.setattr(db, "vacuum", lambda: vacuum_calls.append(True))
@@ -3046,6 +3049,7 @@ class TestVacuum:
def test_auto_maintenance_retries_after_failed_vacuum(self, db, monkeypatch):
monkeypatch.setattr(db, "prune_sessions", lambda **_kwargs: 3)
+ monkeypatch.setattr(db, "_freelist_ratio", lambda: 0.5) # ratio gate open
vacuum_calls = []
def fail_first_vacuum():
@@ -3066,6 +3070,97 @@ class TestVacuum:
assert vacuum_calls == [True, True]
assert db.get_meta("last_vacuum") is not None
+ # ── freelist-ratio gate (#54189) ─────────────────────────────────────
+ def test_auto_maintenance_skips_vacuum_below_freelist_ratio(self, db, monkeypatch):
+ """A prune that frees few pages on a dense DB must NOT trigger VACUUM."""
+ monkeypatch.setattr(db, "prune_sessions", lambda **_kwargs: 1)
+ monkeypatch.setattr(db, "_freelist_ratio", lambda: 0.05)
+ vacuum_calls = []
+ monkeypatch.setattr(db, "vacuum", lambda: vacuum_calls.append(True))
+
+ result = db.maybe_auto_prune_and_vacuum(min_interval_hours=0)
+
+ assert result["pruned"] == 1
+ assert result["vacuumed"] is False
+ assert result["freelist_ratio"] == 0.05
+ assert vacuum_calls == []
+ assert db.get_meta("last_vacuum") is None
+ # The prune itself still counts as a maintenance run.
+ assert db.get_meta("last_auto_prune") is not None
+
+ def test_auto_maintenance_vacuums_above_freelist_ratio(self, db, monkeypatch):
+ monkeypatch.setattr(db, "prune_sessions", lambda **_kwargs: 1)
+ monkeypatch.setattr(db, "_freelist_ratio", lambda: 0.40)
+ vacuum_calls = []
+ monkeypatch.setattr(db, "vacuum", lambda: vacuum_calls.append(True))
+
+ result = db.maybe_auto_prune_and_vacuum(min_interval_hours=0)
+
+ assert result["vacuumed"] is True
+ assert result["freelist_ratio"] == 0.40
+ assert vacuum_calls == [True]
+
+ def test_auto_maintenance_freelist_ratio_exactly_at_threshold_skips(self, db, monkeypatch):
+ """Gate is strictly greater-than: 25.0% reclaimable does not VACUUM."""
+ from hermes_state import AUTO_VACUUM_MIN_FREELIST_RATIO
+
+ monkeypatch.setattr(db, "prune_sessions", lambda **_kwargs: 1)
+ monkeypatch.setattr(db, "_freelist_ratio", lambda: AUTO_VACUUM_MIN_FREELIST_RATIO)
+ vacuum_calls = []
+ monkeypatch.setattr(db, "vacuum", lambda: vacuum_calls.append(True))
+
+ result = db.maybe_auto_prune_and_vacuum(min_interval_hours=0)
+
+ assert result["vacuumed"] is False
+ assert vacuum_calls == []
+
+ def test_auto_maintenance_unknown_freelist_ratio_falls_back_to_time_throttle(self, db, monkeypatch):
+ """If the pragmas cannot be read, don't silently disable VACUUM forever."""
+ monkeypatch.setattr(db, "prune_sessions", lambda **_kwargs: 1)
+ monkeypatch.setattr(db, "_freelist_ratio", lambda: None)
+ vacuum_calls = []
+ monkeypatch.setattr(db, "vacuum", lambda: vacuum_calls.append(True))
+
+ result = db.maybe_auto_prune_and_vacuum(min_interval_hours=0)
+
+ assert result["vacuumed"] is True
+ assert result["freelist_ratio"] is None
+ assert vacuum_calls == [True]
+
+ def test_auto_maintenance_ratio_gate_threshold_is_overridable(self, db, monkeypatch):
+ monkeypatch.setattr(db, "prune_sessions", lambda **_kwargs: 1)
+ monkeypatch.setattr(db, "_freelist_ratio", lambda: 0.10)
+ vacuum_calls = []
+ monkeypatch.setattr(db, "vacuum", lambda: vacuum_calls.append(True))
+
+ result = db.maybe_auto_prune_and_vacuum(
+ min_interval_hours=0, min_vacuum_freelist_ratio=0.05
+ )
+
+ assert result["vacuumed"] is True
+ assert vacuum_calls == [True]
+
+ def test_freelist_ratio_reads_real_pragmas(self, db):
+ """Real-DB check: freeing most of the file pushes the ratio past the gate."""
+ from hermes_state import AUTO_VACUUM_MIN_FREELIST_RATIO
+
+ db.create_session(session_id="keep", source="cli")
+ db.append_message(session_id="keep", role="user", content="hi")
+ for i in range(6):
+ sid = f"bulk{i}"
+ db.create_session(session_id=sid, source="cli")
+ for _ in range(20):
+ db.append_message(session_id=sid, role="assistant", content="z" * 4000)
+ db._conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
+ dense = db._freelist_ratio()
+ assert dense is not None and dense < AUTO_VACUUM_MIN_FREELIST_RATIO
+
+ for i in range(6):
+ db.delete_session(f"bulk{i}")
+ db._conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
+ sparse = db._freelist_ratio()
+ assert sparse is not None and sparse > AUTO_VACUUM_MIN_FREELIST_RATIO
+
def test_wal_size_limit_is_bounded(self, db):
"""journal_size_limit must be a finite bound, not SQLite's -1 default.
@@ -3196,7 +3291,8 @@ class TestAutoMaintenance:
)
db._conn.commit()
- def test_first_run_prunes_and_vacuums(self, db):
+ def test_first_run_prunes_and_skips_vacuum_when_little_reclaimable(self, db):
+ """Pruning two empty sessions frees almost nothing → prune yes, VACUUM no."""
self._make_old_ended(db, "old1", days_old=100)
self._make_old_ended(db, "old2", days_old=100)
db.create_session(session_id="new", source="cli") # active, must survive
@@ -3204,12 +3300,40 @@ class TestAutoMaintenance:
result = db.maybe_auto_prune_and_vacuum(retention_days=90)
assert result["skipped"] is False
assert result["pruned"] == 2
- assert result["vacuumed"] is True
+ assert result["vacuumed"] is False # freelist ratio gate (#54189)
+ assert result["freelist_ratio"] is not None
+ assert result["freelist_ratio"] <= 0.25
assert result.get("error") is None
assert db.get_session("old1") is None
assert db.get_session("old2") is None
assert db.get_session("new") is not None
+ def test_first_run_prunes_and_vacuums_when_mostly_reclaimable(self, db):
+ """Pruning the bulk of the file's pages crosses the 25% gate → VACUUM runs."""
+ db.create_session(session_id="new", source="cli") # active, must survive
+ db.append_message(session_id="new", role="user", content="hi")
+ for i in range(6):
+ sid = f"old{i}"
+ self._make_old_ended(db, sid, days_old=100)
+ for _ in range(20):
+ db.append_message(session_id=sid, role="assistant", content="z" * 4000)
+ # Keep the row aged: append_message bumps activity, prune ages by
+ # latest message, so push the message timestamps back too.
+ db._conn.execute(
+ "UPDATE messages SET timestamp = ? WHERE session_id = ?",
+ (time.time() - 100 * 86400, sid),
+ )
+ db._conn.commit()
+
+ result = db.maybe_auto_prune_and_vacuum(retention_days=90)
+ assert result["skipped"] is False
+ assert result["pruned"] == 6
+ assert result["freelist_ratio"] > 0.25
+ assert result["vacuumed"] is True
+ assert result.get("error") is None
+ assert db.get_session("new") is not None
+ assert db.get_meta("last_vacuum") is not None
+
def test_second_call_within_interval_skips(self, db):
self._make_old_ended(db, "old", days_old=100)
first = db.maybe_auto_prune_and_vacuum(
diff --git a/tests/test_session_vacuum_config.py b/tests/test_session_vacuum_config.py
index d231996b598..43adfdacbaa 100644
--- a/tests/test_session_vacuum_config.py
+++ b/tests/test_session_vacuum_config.py
@@ -8,6 +8,87 @@ def test_default_config_exposes_vacuum_interval():
assert DEFAULT_CONFIG["sessions"]["min_vacuum_interval_days"] == 30
+def test_default_config_auto_prune_on_with_90_day_retention():
+ """#54189: state.db retention is ON by default (ended sessions, 90 days)."""
+ from hermes_cli.config import DEFAULT_CONFIG
+
+ sessions = DEFAULT_CONFIG["sessions"]
+ assert sessions["auto_prune"] is True
+ assert sessions["retention_days"] == 90
+ assert sessions["vacuum_after_prune"] is True
+
+
+def test_fresh_config_runs_auto_prune_at_startup(monkeypatch, tmp_path: Path):
+ """A config.yaml with NO ``sessions:`` keys must reach the prune call with the
+ new defaults (the loader deep-merges DEFAULT_CONFIG)."""
+ import cli
+ import hermes_cli.config
+ import hermes_constants
+ from hermes_cli.config import DEFAULT_CONFIG
+
+ session_db = MagicMock()
+ session_db.get_meta.return_value = "already-done"
+ # Simulate load_config() on a fresh home: only defaults for the section.
+ monkeypatch.setattr(
+ hermes_cli.config,
+ "load_config",
+ lambda: {"sessions": dict(DEFAULT_CONFIG["sessions"])},
+ )
+ monkeypatch.setattr(hermes_constants, "get_hermes_home", lambda: tmp_path)
+
+ cli._run_state_db_auto_maintenance(session_db)
+
+ session_db.maybe_auto_prune_and_vacuum.assert_called_once_with(
+ retention_days=90,
+ min_interval_hours=24,
+ min_vacuum_interval_days=30,
+ vacuum=True,
+ sessions_dir=tmp_path / "sessions",
+ )
+
+
+def test_explicit_auto_prune_false_is_respected(monkeypatch, tmp_path: Path):
+ """Migration guard: an install that explicitly opted out keeps its choice."""
+ import cli
+ import hermes_cli.config
+ import hermes_constants
+
+ session_db = MagicMock()
+ session_db.get_meta.return_value = "already-done"
+ monkeypatch.setattr(
+ hermes_cli.config,
+ "load_config",
+ lambda: {"sessions": {"auto_prune": False, "retention_days": 90}},
+ )
+ monkeypatch.setattr(hermes_constants, "get_hermes_home", lambda: tmp_path)
+
+ cli._run_state_db_auto_maintenance(session_db)
+
+ session_db.maybe_auto_prune_and_vacuum.assert_not_called()
+
+
+def test_shipped_template_does_not_pin_sessions_keys():
+ """Installers copy cli-config.yaml.example verbatim into config.yaml, so any
+ uncommented ``sessions:`` value there becomes an EXPLICIT user setting that
+ would freeze the retention defaults. The template must leave them commented
+ so code defaults (and future flips) apply."""
+ import yaml
+
+ template = Path(__file__).resolve().parents[1] / "cli-config.yaml.example"
+ data = yaml.safe_load(template.read_text(encoding="utf-8")) or {}
+ assert "sessions" not in data
+
+
+def test_loader_yields_new_defaults_for_fresh_home(monkeypatch, tmp_path: Path):
+ """Real load_config() against an empty HERMES_HOME → auto_prune on, 90 days."""
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ from hermes_cli.config import load_config
+
+ sessions = load_config().get("sessions") or {}
+ assert sessions.get("auto_prune") is True
+ assert sessions.get("retention_days") == 90
+
+
def test_cli_auto_maintenance_forwards_vacuum_interval(monkeypatch, tmp_path: Path):
import cli
import hermes_cli.config
diff --git a/website/docs/user-guide/sessions.md b/website/docs/user-guide/sessions.md
index 35fcd2b1a63..67fa40e0939 100644
--- a/website/docs/user-guide/sessions.md
+++ b/website/docs/user-guide/sessions.md
@@ -869,24 +869,28 @@ Key tables in `state.db`:
- Gateway sessions auto-reset based on the configured reset policy
- Before reset, the agent saves memories and skills from the expiring session
-- Opt-in auto-pruning: when `sessions.auto_prune` is `true`, ended sessions inactive for `sessions.retention_days` (default 90) are pruned at CLI/gateway startup
-- After a prune that actually removed rows, `state.db` is `VACUUM`ed to reclaim disk space when at least `sessions.min_vacuum_interval_days` (default 30) have elapsed since the last successful `VACUUM` (SQLite does not shrink the file on plain DELETE)
+- Auto-pruning (**on by default** since #54189): when `sessions.auto_prune` is `true`, ended sessions inactive for `sessions.retention_days` (default 90) are pruned at CLI/gateway/cron startup
+- After a prune that actually removed rows, `state.db` is `VACUUM`ed to reclaim disk space only when **both** gates pass: at least `sessions.min_vacuum_interval_days` (default 30) have elapsed since the last successful `VACUUM`, **and** more than 25% of the file's pages are reclaimable (`PRAGMA freelist_count / page_count`). A dense database never pays for a full rewrite to reclaim a few MB (SQLite does not shrink the file on plain DELETE)
- Pruning runs at most once per `sessions.min_interval_hours` (default 24); the last-run timestamp is tracked inside `state.db` itself so it's shared across every Hermes process in the same `HERMES_HOME`
-Default is **off** — session history is valuable for `session_search` recall, and silently deleting it could surprise users. Enable in `~/.hermes/config.yaml`:
+Without pruning, `state.db` grows without bound — multi-GB files within weeks were reported on gateway + cron installs. If you would rather keep every ended session forever (the pre-#54189 behavior), turn it off in `~/.hermes/config.yaml`:
```yaml
sessions:
- auto_prune: true # opt in — default is false
+ auto_prune: false # default is true — set false to keep all history
retention_days: 90 # keep ended sessions active within this window
vacuum_after_prune: true # reclaim disk space after a pruning sweep
min_vacuum_interval_days: 30 # don't rewrite the DB more often than this
min_interval_hours: 24 # don't re-run the sweep more often than this
```
-Active sessions are never auto-pruned, regardless of age. Ended sessions are
-aged from their latest message, so a long-lived conversation used recently is
-not deleted merely because it began before the retention window.
+Existing installs that already set any of these keys explicitly keep their
+values; only unset keys pick up the new defaults.
+
+Only **ended** sessions are ever deleted. Active sessions are never auto-pruned,
+regardless of age. Ended sessions are aged from their latest message, so a
+long-lived conversation used recently is not deleted merely because it began
+before the retention window.
**Stale open sessions from automation.** Some producers — cron jobs, kanban
workers, subagents, one-shot CLI runs — can die without ever marking their