The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(gateway): retire automatic expiry contracts
Tekniumf597c3161ab2
diff --git a/tests/gateway/test_53175_cleanup_off_loop.py b/tests/gateway/test_53175_cleanup_off_loop.pyindex c341c284164..2dc1b9feda5 100644--- a/tests/gateway/test_53175_cleanup_off_loop.py+++ b/tests/gateway/test_53175_cleanup_off_loop.py@@ -7,7 +7,7 @@ browser daemons / background processes; shutdown_memory_provider() may doSQLite / network IO via a memory plugin) was still called INLINE on the eventloop from three other places:- * ``_session_expiry_watcher`` (the 5-minute idle sweep) — live loop+ * ``_session_housekeeping_watcher`` (the 5-minute idle sweep) — live loop* ``_handle_message_with_agent`` cache-hygiene re-eviction — live loop* ``_finalize_shutdown_agents`` / ``stop()`` idle-cache loop — shutdown@@ -164,5 +164,3 @@ async def test_cleanup_off_loop_swallows_executor_failure(caplog):assert any("failed" in r.message and "#53175" in r.message for r in caplog.records), "expected the cleanup-failure warning to be logged"--diff --git a/tests/gateway/test_agent_cache.py b/tests/gateway/test_agent_cache.pyindex 2430816faa5..088829ea894 100644--- a/tests/gateway/test_agent_cache.py+++ b/tests/gateway/test_agent_cache.py@@ -303,15 +303,8 @@ class TestAgentCacheBoundedGrowth:return m- def test_cap_commits_memory_before_evicting_finalizable(self, monkeypatch):- """LRU-cap eviction of a finalizable, not-yet-expired agent commits- on_session_end extraction before releasing.-- The agent would otherwise vanish from _agent_cache before the expiry- watcher runs, so the watcher would never fire on_session_end() and- memory providers would miss the transcript (#11205, LRU-cap variant).- We hold the live agent at eviction time, so commit its memory then.- """+ def test_cap_commits_memory_before_soft_release(self, monkeypatch):+ """LRU eviction commits the transcript before releasing clients."""from gateway import run as gw_runmonkeypatch.setattr(gw_run, "_AGENT_CACHE_MAX_SIZE", 1)@@ -321,11 +314,8 @@ class TestAgentCacheBoundedGrowth:release_calls: list = []runner._release_evicted_agent_soft = lambda agent: release_calls.append(agent)- # Finalizable (finite policy), not yet expired.runner.session_store = MagicMock()runner.session_store._entries = {"old": MagicMock(), "new": MagicMock()}- runner.session_store.is_session_finalizable.return_value = True- runner.session_store._is_session_expired.return_value = Falseold_agent = self._fake_agent()old_agent._memory_manager = MagicMock() # has an external provider@@ -346,124 +336,6 @@ class TestAgentCacheBoundedGrowth:assert commit_calls == [[{"role": "user", "content": "hi"}]]assert old_agent in release_calls- def test_cap_skips_memory_commit_for_non_finalizable(self, monkeypatch):- """LRU-cap eviction of a mode='none' agent does NOT commit memory.-- The expiry watcher never finalizes a mode='none' session, so there is- no missed on_session_end boundary to compensate for. Committing here- would fire premature/repeat extraction for a session that simply keeps- living. The agent is released without a commit.- """- from gateway import run as gw_run-- monkeypatch.setattr(gw_run, "_AGENT_CACHE_MAX_SIZE", 1)- runner = self._bounded_runner()-- commit_calls: list = []- release_calls: list = []- runner._release_evicted_agent_soft = lambda agent: release_calls.append(agent)-- runner.session_store = MagicMock()- runner.session_store._entries = {"old": MagicMock(), "new": MagicMock()}- runner.session_store.is_session_finalizable.return_value = False # mode='none'- runner.session_store._is_session_expired.return_value = False-- old_agent = self._fake_agent()- old_agent._memory_manager = MagicMock()- old_agent._session_messages = [{"role": "user", "content": "hi"}]- old_agent.commit_memory_session = lambda msgs=None: commit_calls.append(msgs)- new_agent = self._fake_agent()-- with runner._agent_cache_lock:- runner._agent_cache["old"] = (old_agent, "sig_old")- runner._agent_cache["new"] = (new_agent, "sig_new")- runner._enforce_agent_cache_cap()-- import time as _t- deadline = _t.time() + 2.0- while _t.time() < deadline and not release_calls:- _t.sleep(0.02)- assert commit_calls == [] # no premature extraction- assert old_agent in release_calls # still released--- def test_idle_sweep_keeps_agent_when_session_not_expired(self, monkeypatch):- """Agents past idle TTL are kept if the session hasn't expired yet.-- In daily-reset mode the reset can fire hours after the last- user message — evicting the agent early means the- session-expiry watcher has nothing to call on_session_end()- with, and memory providers miss the live transcript.- """- from gateway import run as gw_run-- monkeypatch.setattr(gw_run, "_AGENT_CACHE_IDLE_TTL_SECS", 0.01)- runner = self._bounded_runner()- runner._cleanup_agent_resources = MagicMock()-- import time as _t- stale = self._fake_agent(last_activity=_t.time() - 10.0)-- # Session store says the session is still alive AND is finalizable- # (finite reset policy) — so deferring eviction is correct: the expiry- # watcher will find this agent later and fire on_session_end().- session_entry = MagicMock()- runner.session_store = MagicMock()- runner.session_store._entries = {"stale-session": session_entry}- runner.session_store.is_session_finalizable.return_value = True- runner.session_store._is_session_expired.return_value = False-- runner._agent_cache["stale-session"] = (stale, "sig")-- evicted = runner._sweep_idle_cached_agents()- assert evicted == 0- assert "stale-session" in runner._agent_cache--- def test_is_session_finalizable_real_predicate(self, tmp_path):- """is_session_finalizable() reflects the real reset policy.-- Uses a real SessionStore + GatewayConfig (no mocks) so the predicate- is exercised against actual get_reset_policy() output: True for finite- policies (idle/daily/both), False only for mode='none'.- """- from datetime import datetime- from unittest.mock import patch as _patch-- from gateway.config import GatewayConfig, Platform, SessionResetPolicy- from gateway.session import (- SessionEntry, SessionSource, SessionStore, build_session_key,- )-- def _entry_for(platform: Platform) -> SessionEntry:- src = SessionSource(- platform=platform, user_id="u1", chat_id="c1",- user_name="t", chat_type="dm",- )- return SessionEntry(- session_key=build_session_key(src),- session_id="s1",- created_at=datetime.now(),- updated_at=datetime.now(),- origin=src,- platform=src.platform,- chat_type=src.chat_type,- )-- config = GatewayConfig()- # Give Telegram a 'none' policy via the per-platform override; leave the- # default policy finite ('both') for the Discord case.- config.default_reset_policy = SessionResetPolicy(mode="both")- config.reset_by_platform[Platform.TELEGRAM] = SessionResetPolicy(mode="none")-- with _patch("gateway.session.SessionStore._ensure_loaded"):- store = SessionStore(sessions_dir=tmp_path, config=config)- store._db = None-- # mode='none' → never finalized by the watcher.- assert store.is_session_finalizable(_entry_for(Platform.TELEGRAM)) is False- # default 'both' → finite, will eventually expire.- assert store.is_session_finalizable(_entry_for(Platform.DISCORD)) is Truedef test_plain_dict_cache_is_tolerated(self):"""Test fixtures using plain {} don't crash _enforce_agent_cache_cap."""@@ -1111,4 +983,3 @@ class TestCrossProcessInvalidationDefersCleanup:# Stale entry was popped, hard-teardown path never used.assert "telegram:s1" not in runner._agent_cacherunner._cleanup_agent_resources.assert_not_called()-diff --git a/tests/gateway/test_channel_continuity_hint.py b/tests/gateway/test_channel_continuity_hint.pyindex 057336af9ac..10aada01a7a 100644--- a/tests/gateway/test_channel_continuity_hint.py+++ b/tests/gateway/test_channel_continuity_hint.py@@ -13,7 +13,7 @@ from datetime import datetime, timedeltaimport pytest-from gateway.config import GatewayConfig, Platform, SessionResetPolicy+from gateway.config import GatewayConfig, Platformfrom gateway.session import (SessionEntry,SessionSource,@@ -31,10 +31,8 @@ def _isolated_db(tmp_path, monkeypatch):return tmp_path-def _make_store(tmp_path, policy=None):+def _make_store(tmp_path):config = GatewayConfig()- if policy:- config.default_reset_policy = policyreturn SessionStore(sessions_dir=tmp_path / "sessions", config=config)@@ -54,14 +52,14 @@ def _slack_source(thread_id=None):class TestPrevSessionIdCapture:def test_prev_session_id_set_on_auto_reset(self, _isolated_db, tmp_path):- store = _make_store(tmp_path, SessionResetPolicy(mode="idle", idle_minutes=1))+ store = _make_store(tmp_path)source = _slack_source(thread_id="T9")entry1 = store.get_or_create_session(source)assert entry1.prev_session_id is None # fresh session, nothing replacedentry1.last_prompt_tokens = 4000 # had real conversation- entry1.updated_at = datetime.now() - timedelta(minutes=5)+ entry1.suspended = Truestore._save()entry2 = store.get_or_create_session(source)@@ -82,7 +80,7 @@ def _reset_entry(platform, prev="20260101_000000_abc", had_activity=True):updated_at=datetime.now(),platform=platform,was_auto_reset=True,- auto_reset_reason="daily",+ auto_reset_reason="suspended",reset_had_activity=had_activity,prev_session_id=prev,)@@ -101,4 +99,3 @@ class TestBuildChannelContinuityNote:def test_no_activity_returns_none(self):entry = _reset_entry(Platform.SLACK, had_activity=False)assert build_channel_continuity_note(entry, _slack_source()) is None-diff --git a/tests/gateway/test_clean_shutdown_marker.py b/tests/gateway/test_clean_shutdown_marker.pyindex 03e3d4ebb2b..25c79f674b3 100644--- a/tests/gateway/test_clean_shutdown_marker.py+++ b/tests/gateway/test_clean_shutdown_marker.py@@ -23,10 +23,8 @@ def _make_source(platform=Platform.TELEGRAM, chat_id="123", user_id="u1"):return SessionSource(platform=platform, chat_id=chat_id, user_id=user_id)-def _make_store(tmp_path, policy=None):+def _make_store(tmp_path):config = GatewayConfig()- if policy:- config.default_reset_policy = policyreturn SessionStore(sessions_dir=tmp_path, config=config)@@ -131,71 +129,3 @@ class TestCleanShutdownMarker:# ---------------------------------------------------------------------------# resume_pending freshness gate (#46934)# -----------------------------------------------------------------------------class TestResumePendingFreshnessGate:- """A resume_pending session is only returned while it is still fresh.-- ``get_or_create_session`` returns a ``resume_pending`` session so its- transcript reloads intact after a restart. But the idle/daily reset- policy keys on ``updated_at``, which is bumped to ``now`` on every- message — so a zombie session that keeps receiving messages never trips- it and would resume stale context forever. The freshness gate keys on- ``last_resume_marked_at`` (set once at resume-mark, never bumped) so it- catches that case.- """-- def _mark_resume_pending(self, store, source):- """Put the session into resume_pending and return the entry."""- store.get_or_create_session(source)- count = store.suspend_recently_active()- assert count == 1- with store._lock:- entry = store._entries[store._generate_session_key(source)]- assert entry.resume_pending- assert entry.last_resume_marked_at is not None- return entry--- def test_stale_resume_pending_falls_through_to_reset(self, tmp_path, monkeypatch):- monkeypatch.setenv("HERMES_AUTO_CONTINUE_FRESHNESS", "3600")- # The freshness gate only applies when the user has opted into- # automatic resets — session_reset.mode: none disables it (#61052).- from gateway.config import SessionResetPolicy- store = _make_store(- tmp_path, policy=SessionResetPolicy(mode="idle", idle_minutes=999999)- )- source = _make_source()- entry = self._mark_resume_pending(store, source)-- # Backdate the resume mark past the freshness window. Keep updated_at- # fresh (as a per-message zombie would have) so the idle/daily policy- # would NOT fire — only the freshness gate should catch this.- with store._lock:- entry.last_resume_marked_at = datetime.now() - timedelta(seconds=7200)- entry.updated_at = datetime.now()- store._save()-- fresh = store.get_or_create_session(source)- # Zombie detected → brand-new session, not the stale transcript.- assert fresh.session_id != entry.session_id- assert not fresh.resume_pending-- def test_reset_mode_none_disables_freshness_gate(self, tmp_path, monkeypatch):- """session_reset.mode: none opts out of ALL automatic resets —- including the resume_pending freshness gate (#61052)."""- monkeypatch.setenv("HERMES_AUTO_CONTINUE_FRESHNESS", "3600")- from gateway.config import SessionResetPolicy- store = _make_store(tmp_path, policy=SessionResetPolicy(mode="none"))- source = _make_source()- entry = self._mark_resume_pending(store, source)-- with store._lock:- entry.last_resume_marked_at = datetime.now() - timedelta(seconds=7200)- entry.updated_at = datetime.now()- store._save()-- refreshed = store.get_or_create_session(source)- # Explicit opt-out honored: same session back, transcript preserved.- assert refreshed.session_id == entry.session_id- assert refreshed.resume_pending-diff --git a/tests/gateway/test_config.py b/tests/gateway/test_config.pyindex 480e26d48c9..8cdd6d62533 100644--- a/tests/gateway/test_config.py+++ b/tests/gateway/test_config.py@@ -19,7 +19,6 @@ from gateway.config import (HomeChannel,Platform,PlatformConfig,- SessionResetPolicy,StreamingConfig,_apply_env_overrides,load_gateway_config,@@ -168,29 +167,6 @@ class TestGetConnectedPlatforms:assert Platform.DINGTALK in config.get_connected_platforms()-class TestSessionResetPolicy:- def test_roundtrip(self):- policy = SessionResetPolicy(mode="idle", at_hour=6, idle_minutes=120,- bg_process_max_age_hours=48)- d = policy.to_dict()- restored = SessionResetPolicy.from_dict(d)- assert restored.mode == "idle"- assert restored.at_hour == 6- assert restored.idle_minutes == 120- assert restored.bg_process_max_age_hours == 48--- def test_from_dict_treats_null_values_as_defaults(self):- restored = SessionResetPolicy.from_dict(- {"mode": None, "at_hour": None, "idle_minutes": None,- "bg_process_max_age_hours": None}- )- assert restored.mode == "none"- assert restored.at_hour == 4- assert restored.idle_minutes == 1440- assert restored.bg_process_max_age_hours == 24--class TestStreamingConfig:@@ -278,58 +254,6 @@ class TestGatewayConfigRoundtrip:class TestLoadGatewayConfig:- def test_shipped_template_does_not_enable_auto_reset(self, tmp_path, monkeypatch):- """A fresh install seeded from cli-config.yaml.example must not- auto-reset sessions.-- Installers (scripts/install.sh, scripts/install.ps1,- docker/stage2-hook.sh, hermes doctor) copy the template verbatim to- ~/.hermes/config.yaml, so whatever ``session_reset.mode`` the template- ships becomes an EXPLICIT user setting that overrides the code- default. After #60194 flipped the default to "none", the template- still said "both" — every new install kept 24h-idle resets on- (Luciano's report, July 2026). This pins the invariant: template- seed == no auto-reset.- """- template = (- Path(__file__).resolve().parents[2] / "cli-config.yaml.example"- )- hermes_home = tmp_path / ".hermes"- hermes_home.mkdir()- (hermes_home / "config.yaml").write_text(- template.read_text(encoding="utf-8"), encoding="utf-8"- )- monkeypatch.setenv("HERMES_HOME", str(hermes_home))-- config = load_gateway_config()-- assert config.default_reset_policy.mode == "none"-- def test_no_config_yaml_means_no_auto_reset(self, tmp_path, monkeypatch):- """With no config.yaml at all, sessions must never auto-reset."""- hermes_home = tmp_path / ".hermes"- hermes_home.mkdir()- monkeypatch.setenv("HERMES_HOME", str(hermes_home))-- config = load_gateway_config()-- assert config.default_reset_policy.mode == "none"--- def test_explicit_session_reset_opt_in_is_honored(self, tmp_path, monkeypatch):- """Users who explicitly opt in to auto-reset keep their policy."""- hermes_home = tmp_path / ".hermes"- hermes_home.mkdir()- (hermes_home / "config.yaml").write_text(- "session_reset:\n mode: idle\n idle_minutes: 30\n",- encoding="utf-8",- )- monkeypatch.setenv("HERMES_HOME", str(hermes_home))-- config = load_gateway_config()-- assert config.default_reset_policy.mode == "idle"- assert config.default_reset_policy.idle_minutes == 30def test_slack_ignored_channels_config_sets_env_bridge(self, tmp_path, monkeypatch):@@ -442,22 +366,6 @@ class TestLoadGatewayConfig:assert extra["websocket_heartbeat_ack_max_age_seconds"] == 75assert extra["websocket_max_latency_seconds"] == 30- def test_session_reset_from_nested_gateway_section(self, tmp_path, monkeypatch):- """``gateway.session_reset`` (nested form) must reach default_reset_policy,- mirroring the gateway.multiplex_profiles precedent."""- hermes_home = tmp_path / ".hermes"- hermes_home.mkdir()- config_path = hermes_home / "config.yaml"- config_path.write_text(- "gateway:\n session_reset:\n mode: idle\n idle_minutes: 30\n",- encoding="utf-8",- )- monkeypatch.setenv("HERMES_HOME", str(hermes_home))-- config = load_gateway_config()-- assert config.default_reset_policy.mode == "idle"- assert config.default_reset_policy.idle_minutes == 30def test_quick_commands_from_nested_gateway_section(self, tmp_path, monkeypatch):hermes_home = tmp_path / ".hermes"@@ -660,29 +568,6 @@ class TestLoadGatewayConfig:assert config.unauthorized_dm_behavior == "ignore"- def test_present_empty_top_level_session_reset_blocks_nested_fallback(self, tmp_path, monkeypatch):- """Key-presence precedence: a present (even empty) top-level- session_reset must NOT be replaced by gateway.session_reset —- the fallback fires only when the top-level key is absent."""- hermes_home = tmp_path / ".hermes"- hermes_home.mkdir()- config_path = hermes_home / "config.yaml"- config_path.write_text(- "session_reset: {}\n"- "gateway:\n"- " session_reset:\n"- " mode: idle\n"- " idle_minutes: 30\n",- encoding="utf-8",- )- monkeypatch.setenv("HERMES_HOME", str(hermes_home))-- config = load_gateway_config()-- # The nested value must not leak through the present top-level key.- assert config.default_reset_policy.mode != "idle"--def test_relay_platform_enabled_from_env_url(self, tmp_path, monkeypatch):"""GATEWAY_RELAY_URL must enable Platform.RELAY in config.platforms sostart_gateway()'s connect loop actually dials the connector. Registeringdiff --git a/tests/gateway/test_multiplex_session_db_profile_scope.py b/tests/gateway/test_multiplex_session_db_profile_scope.pyindex 10833311b33..2c5c8e11e39 100644--- a/tests/gateway/test_multiplex_session_db_profile_scope.py+++ b/tests/gateway/test_multiplex_session_db_profile_scope.py@@ -531,13 +531,8 @@ def test_scoped_inbound_turn_lands_in_profile_store(multiplex_homes):def test_unscoped_background_finalize_reaches_the_key_owner_store(multiplex_homes):"""Background work carries no scope but owns every profile's keys.- ``_session_expiry_watcher`` walks the process-wide ``_entries`` dict and- finalizes expired sessions without entering ``_profile_runtime_scope``, so- resolving from the ambient home wrote the flag to the ROOT store while the- row lives under ``profiles/<name>/``. Two copies of one session then drift- apart until the #54878 guard drops a live conversation.-- Fails before this change with ``expiry_finalized`` still 0 on the profile row.+ Background lifecycle work must resolve the routing key owner profile,+ not the default profile database."""root, profile = multiplex_homesstore = _multiplex_store(root)diff --git a/tests/gateway/test_reaped_session_recovery.py b/tests/gateway/test_reaped_session_recovery.pyindex fa19d772ea5..15983d18538 100644--- a/tests/gateway/test_reaped_session_recovery.py+++ b/tests/gateway/test_reaped_session_recovery.py@@ -20,7 +20,6 @@ from gateway.config import (GatewayConfig,Platform,PlatformConfig,- SessionResetPolicy,)from gateway.platforms.base import MessageEvent, MessageTypefrom gateway.run import GatewayRunner@@ -93,7 +92,7 @@ def _source(chat_id="555001") -> SessionSource:def _store(tmp_path) -> SessionStore:config = GatewayConfig(- default_reset_policy=SessionResetPolicy(mode="none")+)return SessionStore(sessions_dir=tmp_path, config=config)diff --git a/tests/gateway/test_session_boundary_hooks.py b/tests/gateway/test_session_boundary_hooks.pydeleted file mode 100644index 297c9e22a47..00000000000--- a/tests/gateway/test_session_boundary_hooks.py+++ /dev/null@@ -1,228 +0,0 @@-"""Tests that on_session_finalize and on_session_reset plugin hooks fire in the gateway."""-from datetime import datetime-from types import SimpleNamespace-from unittest.mock import AsyncMock, MagicMock, patch--import pytest--from gateway.config import GatewayConfig, Platform, PlatformConfig-from gateway.platforms.base import MessageEvent-from gateway.session import SessionEntry, SessionSource, build_session_key---def _make_source() -> SessionSource:- return SessionSource(- platform=Platform.TELEGRAM,- user_id="u1",- chat_id="c1",- user_name="tester",- chat_type="dm",- )---def _make_event(text: str) -> MessageEvent:- return MessageEvent(text=text, source=_make_source(), message_id="m1")---def _make_runner():- from gateway.run import GatewayRunner-- runner = object.__new__(GatewayRunner)- runner.config = GatewayConfig(- platforms={Platform.TELEGRAM: PlatformConfig(enabled=True, token="***")}- )- adapter = MagicMock()- adapter.send = AsyncMock()- runner.adapters = {Platform.TELEGRAM: adapter}- runner._voice_mode = {}- runner.hooks = SimpleNamespace(emit=AsyncMock(), loaded_hooks=False)- runner._session_model_overrides = {}- runner._pending_model_notes = {}- runner._background_tasks = set()-- session_key = build_session_key(_make_source())- session_entry = SessionEntry(- session_key=session_key,- session_id="sess-old",- created_at=datetime.now(),- updated_at=datetime.now(),- platform=Platform.TELEGRAM,- chat_type="dm",- )- new_session_entry = SessionEntry(- session_key=session_key,- session_id="sess-new",- created_at=datetime.now(),- updated_at=datetime.now(),- platform=Platform.TELEGRAM,- chat_type="dm",- )- runner.session_store = MagicMock()- runner.session_store.get_or_create_session.return_value = new_session_entry- runner.session_store.reset_session.return_value = new_session_entry- runner.session_store._entries = {session_key: session_entry}- runner.session_store._generate_session_key.return_value = session_key- runner._running_agents = {}- runner._pending_messages = {}- runner._pending_approvals = {}- runner._session_db = None- runner._agent_cache_lock = None- runner._is_user_authorized = lambda _source: True- runner._format_session_info = lambda: ""-- return runner---@patch("hermes_cli.plugins.invoke_hook")-async def test_idle_expiry_fires_finalize_hook(mock_invoke_hook):- """Regression test for #14981.-- When ``_session_expiry_watcher`` sweeps a session that has aged past- its reset policy (idle timeout, scheduled reset), it must fire- ``on_session_finalize`` so plugin providers get the same final-pass- extraction opportunity they'd get from /new or CLI shutdown. Before- the fix, the expiry path evicted the agent but silently skipped the- hook.- """- from datetime import datetime, timedelta-- from gateway.run import GatewayRunner-- runner = object.__new__(GatewayRunner)- runner._running = True- runner._running_agents = {}- runner._agent_cache = {}- runner._agent_cache_lock = None- runner._last_session_store_prune_ts = 0.0-- session_key = "agent:main:telegram:dm:42"- expired_entry = SessionEntry(- session_key=session_key,- session_id="sess-expired",- created_at=datetime.now() - timedelta(hours=2),- updated_at=datetime.now() - timedelta(hours=2),- platform=Platform.TELEGRAM,- chat_type="dm",- )- expired_entry.expiry_finalized = False-- runner.session_store = MagicMock()- runner.session_store._ensure_loaded = MagicMock()- runner.session_store._entries = {session_key: expired_entry}- runner.session_store._is_session_expired = MagicMock(return_value=True)- runner.session_store._lock = MagicMock()- runner.session_store._lock.__enter__ = MagicMock(return_value=None)- runner.session_store._lock.__exit__ = MagicMock(return_value=None)- runner.session_store._save = MagicMock()-- runner._evict_cached_agent = MagicMock()- runner._cleanup_agent_resources = MagicMock()- runner._sweep_idle_cached_agents = MagicMock(return_value=0)-- # The watcher starts with `await asyncio.sleep(0.2)` and loops while- # `self._running`. Patch sleep so the 60s initial delay is instant, and- # make the expiry hook invocation flip `_running` false so the loop- # exits cleanly after one pass.- _orig_sleep = __import__("asyncio").sleep-- async def _fast_sleep(_):- await _orig_sleep(0)-- def _hook_and_stop(*a, **kw):- runner._running = False- return None-- mock_invoke_hook.side_effect = _hook_and_stop-- with patch("gateway.run.asyncio.sleep", side_effect=_fast_sleep):- await runner._session_expiry_watcher(interval=0)-- # Look for the finalize call targeting the expired session.- finalize_calls = [- c for c in mock_invoke_hook.call_args_list- if c[0] and c[0][0] == "on_session_finalize"- ]- session_ids = {c[1].get("session_id") for c in finalize_calls}- assert "sess-expired" in session_ids, (- f"on_session_finalize was not fired during idle expiry; "- f"got session_ids={session_ids} (regression of #14981)"- )---@patch("hermes_cli.plugins.invoke_hook")-async def test_idle_expiry_clears_last_resolved_model(mock_invoke_hook):- """Regression test for #58403.-- ``_session_expiry_watcher`` permanently finalizes an expired session and- already drops ``_session_model_overrides`` / the reasoning override /- ``_pending_model_notes`` — a resumed conversation must not inherit stale- per-session state. It missed ``_last_resolved_model``: without clearing- it, a resumed session could serve a cached model from before it went- idle on a transient config-cache miss, exactly the #58403 class the- /new and compression-exhausted-reset paths already guard against.- """- from datetime import datetime, timedelta-- from gateway.run import GatewayRunner-- runner = object.__new__(GatewayRunner)- runner._running = True- runner._running_agents = {}- runner._agent_cache = {}- runner._agent_cache_lock = None- runner._last_session_store_prune_ts = 0.0-- session_key = "agent:main:telegram:dm:42"- expired_entry = SessionEntry(- session_key=session_key,- session_id="sess-expired",- created_at=datetime.now() - timedelta(hours=2),- updated_at=datetime.now() - timedelta(hours=2),- platform=Platform.TELEGRAM,- chat_type="dm",- )- expired_entry.expiry_finalized = False-- runner.session_store = MagicMock()- runner.session_store._ensure_loaded = MagicMock()- runner.session_store._entries = {session_key: expired_entry}- runner.session_store._is_session_expired = MagicMock(return_value=True)- runner.session_store._lock = MagicMock()- runner.session_store._lock.__enter__ = MagicMock(return_value=None)- runner.session_store._lock.__exit__ = MagicMock(return_value=None)- runner.session_store._save = MagicMock()-- runner._evict_cached_agent = MagicMock()- runner._cleanup_agent_resources = MagicMock()- runner._sweep_idle_cached_agents = MagicMock(return_value=0)- runner._session_model_overrides = {}- runner._pending_model_notes = {}- runner._last_resolved_model = {- session_key: "gpt-5",- "agent:main:telegram:dm:other": "keep-me",- }-- _orig_sleep = __import__("asyncio").sleep-- async def _fast_sleep(_):- await _orig_sleep(0)-- def _hook_and_stop(*a, **kw):- runner._running = False- return None-- mock_invoke_hook.side_effect = _hook_and_stop-- with patch("gateway.run.asyncio.sleep", side_effect=_fast_sleep):- await runner._session_expiry_watcher(interval=0)-- assert session_key not in runner._last_resolved_model, (- "session-expiry finalization did not clear the expired session's "- "_last_resolved_model entry (#58403)"- )- assert runner._last_resolved_model["agent:main:telegram:dm:other"] == "keep-me", (- "session-expiry finalization must only clear the expired session's "- "own key, not unrelated sessions' cached entries"- )diff --git a/tests/gateway/test_session_reset_notify.py b/tests/gateway/test_session_reset_notify.pyindex e1e5b343a17..f464395bc36 100644--- a/tests/gateway/test_session_reset_notify.py+++ b/tests/gateway/test_session_reset_notify.py@@ -1,331 +1,32 @@-"""Tests for session auto-reset notifications.--Verifies that:-- _should_reset() returns a reason string ("idle" or "daily") instead of bool-- SessionEntry captures auto_reset_reason-- SessionResetPolicy.notify controls whether notifications are sent-- notify_exclude_platforms skips notifications for excluded platforms-- resume_pending_expired auto-reset sets the correct reason and DB end_reason-"""-+"""Internal turns preserve the user activity clock."""import jsonfrom datetime import datetime, timedelta-from unittest.mock import MagicMock, patch-from gateway.config import (- GatewayConfig,- Platform,- SessionResetPolicy,-)-from gateway.session import SessionEntry, SessionSource, SessionStore+from gateway.config import GatewayConfig, Platform+from gateway.session import SessionSource, SessionStore-# ----------------------------------------------------------------------------# Helpers-# ---------------------------------------------------------------------------+def test_internal_turn_does_not_advance_activity_clock(tmp_path):+ store = SessionStore(tmp_path / "sessions", GatewayConfig())+ source = SessionSource(platform=Platform.TELEGRAM, chat_id="123", user_id="u1")+ entry = store.get_or_create_session(source)+ prior_activity = datetime.now() - timedelta(minutes=10)+ entry.updated_at = prior_activity+ store._save()-def _make_source(platform=Platform.TELEGRAM, chat_id="123", user_id="u1"):- return SessionSource(- platform=platform,- chat_id=chat_id,- user_id=user_id,+ reused = store.get_or_create_session(source, touch_activity=False)+ store.update_session(+ reused.session_key,+ last_prompt_tokens=123,+ touch_activity=False,)--def _make_store(policy=None, tmp_path=None, has_active_processes_fn=None):- config = GatewayConfig()- if policy:- config.default_reset_policy = policy- store = SessionStore(- sessions_dir=tmp_path or "/tmp/test-sessions",- config=config,- has_active_processes_fn=has_active_processes_fn,+ assert reused.session_id == entry.session_id+ assert reused.updated_at == prior_activity+ assert reused.last_prompt_tokens == 123+ rows = store._db.load_gateway_routing_entries(+ scope=store._routing_scope())- return store---# ----------------------------------------------------------------------------# _should_reset returns reason string-# -----------------------------------------------------------------------------class TestShouldResetReason:-- def test_returns_idle_when_idle_expired(self, tmp_path):- store = _make_store(- SessionResetPolicy(mode="idle", idle_minutes=30),- tmp_path,- )- entry = SessionEntry(- session_key="test",- session_id="s1",- created_at=datetime.now() - timedelta(hours=2),- updated_at=datetime.now() - timedelta(hours=1), # 60min ago > 30min threshold- )- source = _make_source()- assert store._should_reset(entry, source) == "idle"--- def test_returns_none_when_active_process_check_raises(self, tmp_path):- def _raise(_session_key):- raise RuntimeError("process registry unavailable")-- store = _make_store(- SessionResetPolicy(mode="idle", idle_minutes=30),- tmp_path,- has_active_processes_fn=_raise,- )- entry = SessionEntry(- session_key="test",- session_id="s1",- created_at=datetime.now() - timedelta(hours=2),- updated_at=datetime.now() - timedelta(hours=1),- )- source = _make_source()-- assert store._should_reset(entry, source) is None---# ----------------------------------------------------------------------------# SessionEntry captures reason-# -----------------------------------------------------------------------------class TestSessionEntryReason:--- def test_reset_had_activity_true_when_tokens_used(self, tmp_path):- """Expired session with tokens → reset_had_activity=True."""- store = _make_store(- SessionResetPolicy(mode="idle", idle_minutes=1),- tmp_path,- )- source = _make_source()-- entry1 = store.get_or_create_session(source)- # Simulate some conversation happened (last_prompt_tokens is the field- # written on every turn; total_tokens is never persisted).- entry1.last_prompt_tokens = 5000- entry1.updated_at = datetime.now() - timedelta(minutes=5)- store._save()-- entry2 = store.get_or_create_session(source)- assert entry2.was_auto_reset is True- assert entry2.reset_had_activity is True---class TestInternalActivityResetPolicy:- def test_internal_turn_does_not_advance_activity_clock(self, tmp_path):- store = _make_store(- SessionResetPolicy(mode="idle", idle_minutes=60),- tmp_path,- )- source = _make_source()- entry = store.get_or_create_session(source)- prior_activity = datetime.now() - timedelta(minutes=10)- entry.updated_at = prior_activity- store._save()-- reused = store.get_or_create_session(source, touch_activity=False)- store.update_session(- reused.session_key,- last_prompt_tokens=123,- touch_activity=False,- )-- assert reused.session_id == entry.session_id- assert reused.updated_at == prior_activity- assert reused.last_prompt_tokens == 123- rows = store._db.load_gateway_routing_entries(- scope=store._routing_scope()- )- durable = json.loads(rows[reused.session_key])- assert durable["updated_at"] == prior_activity.isoformat()- assert durable["last_prompt_tokens"] == 123-- def test_internal_turn_still_triggers_due_reset(self, tmp_path):- store = _make_store(- SessionResetPolicy(mode="idle", idle_minutes=1),- tmp_path,- )- source = _make_source()- entry = store.get_or_create_session(source)- entry.updated_at = datetime.now() - timedelta(minutes=5)- store._save()-- reset = store.get_or_create_session(source, touch_activity=False)-- assert reset.session_id != entry.session_id- assert reset.was_auto_reset is True- assert reset.auto_reset_reason == "idle"---# ----------------------------------------------------------------------------# SessionResetPolicy notify config-# -----------------------------------------------------------------------------class TestResetPolicyNotify:-- def test_notify_exclude_defaults(self):- policy = SessionResetPolicy()- assert "api_server" in policy.notify_exclude_platforms- assert "webhook" in policy.notify_exclude_platforms--- def test_from_dict_with_custom_excludes(self):- policy = SessionResetPolicy.from_dict({- "notify_exclude_platforms": ["api_server", "webhook", "homeassistant"],- })- assert "homeassistant" in policy.notify_exclude_platforms---# ----------------------------------------------------------------------------# SessionEntry to_dict / from_dict roundtrip for auto-reset fields-# -----------------------------------------------------------------------------class TestSessionEntryAutoResetRoundtrip:- def test_was_auto_reset_persists_across_roundtrip(self, tmp_path):- """was_auto_reset=True survives to_dict() → from_dict() (gateway restart)."""- store = _make_store(- SessionResetPolicy(mode="idle", idle_minutes=1),- tmp_path,- )- source = _make_source()-- entry = store.get_or_create_session(source)- entry.updated_at = datetime.now() - timedelta(minutes=5)- store._save()-- entry2 = store.get_or_create_session(source)- assert entry2.was_auto_reset is True- assert entry2.auto_reset_reason == "idle"- assert entry2.session_id != entry.session_id-- # Simulate gateway restart: reload from disk- store._loaded = False- store._entries.clear()- store._ensure_loaded()-- reloaded = store._entries.get(entry2.session_key)- assert reloaded is not None- assert reloaded.was_auto_reset is True- assert reloaded.auto_reset_reason == "idle"---# ----------------------------------------------------------------------------# resume_pending_expired: auto_reset_reason and DB end_reason (#58933)-# -----------------------------------------------------------------------------def _make_db_mock() -> MagicMock:- """Return a SessionDB mock with safe defaults for all lookup methods."""- db = MagicMock()- db.get_session.return_value = None- db.get_compression_tip.return_value = None # avoids MagicMock leaking into session_id- db.find_latest_gateway_session_for_peer.return_value = None- db.reopen_session.return_value = None- db.create_session.return_value = None- return db---def _make_store_with_db(tmp_path, db_mock=None, policy=None) -> SessionStore:- """Build a SessionStore with a mock SessionDB, bypassing disk load."""- cfg_policy = policy or SessionResetPolicy(mode="none")- config = GatewayConfig(default_reset_policy=cfg_policy)- with patch("gateway.session.SessionStore._ensure_loaded"):- store = SessionStore(sessions_dir=tmp_path, config=config)- store._db = db_mock if db_mock is not None else _make_db_mock()- store._loaded = True- return store---class TestResumePendingExpiredAutoReset:- """resume_pending sessions past the freshness window should fire- was_auto_reset=True with auto_reset_reason='resume_pending_expired' and- persist that reason to state.db (#58933)."""-- def _seed_stale_resume_pending(self, store, source, freshness_seconds=3600):- """Create a session, mark it resume_pending, then backdate the mark- past the freshness window so get_or_create_session treats it as a- zombie."""- entry = store.get_or_create_session(source)- store.mark_resume_pending(entry.session_key)- with store._lock:- entry = store._entries[entry.session_key]- entry.last_resume_marked_at = (- datetime.now() - timedelta(seconds=freshness_seconds + 60)- )- entry.updated_at = datetime.now() # keep updated_at fresh- store._save()- return entry-- def test_stale_resume_pending_sets_auto_reset_reason(- self, tmp_path, monkeypatch- ):- """Stale resume_pending triggers was_auto_reset=True with reason- 'resume_pending_expired', NOT 'idle'."""- monkeypatch.setenv("HERMES_AUTO_CONTINUE_FRESHNESS", "3600")- # The freshness gate requires an opted-in reset policy — mode "none"- # disables it entirely (#61052). Use a huge idle window so only the- # freshness gate (not the idle policy) can fire.- store = _make_store_with_db(- tmp_path,- policy=SessionResetPolicy(mode="idle", idle_minutes=999999),- )- source = _make_source()-- old = self._seed_stale_resume_pending(store, source)-- new = store.get_or_create_session(source)-- assert new.session_id != old.session_id, "should have created a new session"- assert new.was_auto_reset is True- assert new.auto_reset_reason == "resume_pending_expired"--- def test_stale_resume_pending_db_end_reason_is_specific(- self, tmp_path, monkeypatch- ):- """state.db must record end_reason='resume_pending_expired', NOT the- generic 'session_reset', so the event is auditable (#58933 fix)."""- monkeypatch.setenv("HERMES_AUTO_CONTINUE_FRESHNESS", "3600")- db = _make_db_mock()- store = _make_store_with_db(- tmp_path, db,- policy=SessionResetPolicy(mode="idle", idle_minutes=999999),- )- source = _make_source()-- old = self._seed_stale_resume_pending(store, source)- store.get_or_create_session(source)-- # Auto-reset now writes through promote_to_session_reset so an- # accidental agent_close end can't shadow the reset boundary.- db.promote_to_session_reset.assert_called_once()- ended_id, ended_reason = db.promote_to_session_reset.call_args.args- assert ended_id == old.session_id- assert ended_reason == "resume_pending_expired", (- f"expected 'resume_pending_expired', got {ended_reason!r} — "- "the DB end_reason must not be the generic 'session_reset'"- )-- def test_idle_reset_db_end_reason_reflects_idle(- self, tmp_path- ):- """Regular idle auto-reset persists 'idle' as end_reason so that all- auto-reset paths are auditable (#58933 should not regress the common- idle/daily path)."""- db = _make_db_mock()- store = _make_store_with_db(- tmp_path, db, policy=SessionResetPolicy(mode="idle", idle_minutes=1)- )- source = _make_source()-- entry = store.get_or_create_session(source)- # Age past idle threshold.- with store._lock:- entry.updated_at = datetime.now() - timedelta(minutes=5)- store._save()-- store.get_or_create_session(source)-- db.promote_to_session_reset.assert_called_once()- _, ended_reason = db.promote_to_session_reset.call_args.args- assert ended_reason == "idle"+ durable = json.loads(rows[reused.session_key])+ assert durable["updated_at"] == prior_activity.isoformat()+ assert durable["last_prompt_tokens"] == 123diff --git a/tests/gateway/test_session_store_lock_io.py b/tests/gateway/test_session_store_lock_io.pyindex 7f5c1f0b6c2..d1575f0d741 100644--- a/tests/gateway/test_session_store_lock_io.py+++ b/tests/gateway/test_session_store_lock_io.py@@ -16,7 +16,7 @@ from unittest.mock import MagicMock, patchimport pytest-from gateway.config import GatewayConfig, Platform, SessionResetPolicy+from gateway.config import GatewayConfig, Platformfrom gateway.session import SessionEntry, SessionSource, SessionStore@@ -70,7 +70,7 @@ def _db_with_rows(rows: dict) -> MagicMock:def _make_store(tmp_path, db_mock=None) -> SessionStore:"""Build a SessionStore with a ``_TrackedLock``, bypassing disk load."""- config = GatewayConfig(default_reset_policy=SessionResetPolicy(mode="none"))+ config = GatewayConfig()with patch("gateway.session.SessionStore._ensure_loaded"):store = SessionStore(sessions_dir=tmp_path, config=config)if db_mock is not None:@@ -252,5 +252,3 @@ def test_auto_reset_does_not_recover_session_being_ended(tmp_path):old.session_id, "suspended")db.end_session.assert_not_called()--diff --git a/tests/gateway/test_session_store_prune.py b/tests/gateway/test_session_store_prune.pyindex d171f527b9e..d585cd0e570 100644--- a/tests/gateway/test_session_store_prune.py+++ b/tests/gateway/test_session_store_prune.py@@ -20,7 +20,7 @@ from datetime import datetime, timedeltafrom unittest.mock import patch-from gateway.config import GatewayConfig, Platform, SessionResetPolicy+from gateway.config import GatewayConfig, Platformfrom gateway.session import SessionEntry, SessionStore@@ -31,7 +31,7 @@ def test_session_store_default_db_uses_runtime_hermes_home(tmp_path, monkeypatchhermes_state before a fixture redirected HERMES_HOME used to pin everydefault SessionDB() at the developer's real ~/.hermes/state.db."""- config = GatewayConfig(default_reset_policy=SessionResetPolicy(mode="none"))+ config = GatewayConfig()fake_home = tmp_path / "alt_hermes_home"fake_home.mkdir()monkeypatch.setenv("HERMES_HOME", str(fake_home))@@ -50,7 +50,7 @@ def test_session_store_default_db_uses_runtime_hermes_home(tmp_path, monkeypatchdef _make_store(tmp_path, max_age_days: int = 90, has_active_processes_fn=None):"""Build a SessionStore bypassing SQLite/disk-load side effects."""config = GatewayConfig(- default_reset_policy=SessionResetPolicy(mode="none"),+session_store_max_age_days=max_age_days,)with patch("gateway.session.SessionStore._ensure_loaded"):@@ -188,7 +188,7 @@ class TestPrunePersistsToDisk:def test_prune_rewrites_sessions_json(self, tmp_path):"""After prune, sessions.json on disk reflects the new dict."""config = GatewayConfig(- default_reset_policy=SessionResetPolicy(mode="none"),+session_store_max_age_days=90,)store = SessionStore(sessions_dir=tmp_path, config=config)@@ -258,4 +258,3 @@ class TestReadmeSentinel:# The note points users at the real store and command.assert "state.db" in raw["_README"]assert "hermes sessions list" in raw["_README"]-diff --git a/tests/gateway/test_session_store_runtime_stale_guard.py b/tests/gateway/test_session_store_runtime_stale_guard.pyindex fd5ae50f344..782db55e0c9 100644--- a/tests/gateway/test_session_store_runtime_stale_guard.py+++ b/tests/gateway/test_session_store_runtime_stale_guard.py@@ -20,7 +20,7 @@ transcript) or, failing recovery, to a fresh session.from datetime import datetime, timedeltafrom unittest.mock import MagicMock, patch-from gateway.config import GatewayConfig, Platform, SessionResetPolicy+from gateway.config import GatewayConfig, Platformfrom gateway.session import SessionEntry, SessionSource, SessionStore@@ -58,7 +58,7 @@ def _db_returning(rows: dict) -> MagicMock:def _make_store_with_db(tmp_path, db_mock) -> SessionStore:"""Build a SessionStore with a mock SessionDB, bypassing disk load."""- config = GatewayConfig(default_reset_policy=SessionResetPolicy(mode="none"))+ config = GatewayConfig()with patch("gateway.session.SessionStore._ensure_loaded"):store = SessionStore(sessions_dir=tmp_path, config=config)store._db = db_mock@@ -117,65 +117,8 @@ class TestRuntimeStaleGuard:db.create_session.assert_not_called()- def test_stale_agent_close_overdue_policy_creates_fresh_session(- self, tmp_path,- ):- """Stale `agent_close` entry + overdue reset policy → fresh session.-- The #54878 self-healing path popped the stale sessions.json entry and- recovered the same session_id from the DB without checking whether a- daily/idle reset was actually due. This test guards the fix at- gateway/session.py:1765 — when the session is overdue under the- configured reset policy, we must create a fresh session (new id,- auto-reset metadata set, reopen_session NOT called).- """- source = _source()- # Idle policy: reset after 60 minutes of inactivity.- config = GatewayConfig(- default_reset_policy=SessionResetPolicy(mode="idle", idle_minutes=60),- )- db = _db_returning({"sid_stale": {"end_reason": "agent_close", "id": "sid_stale"}})- # Recovery would normally reopen this row — but it shouldn't, because- # the reset policy says this session is overdue.- db.find_latest_gateway_session_for_peer.return_value = {- "id": "sid_stale",- "started_at": (datetime.now() - timedelta(hours=3)).timestamp(),- }-- with patch("gateway.session.SessionStore._ensure_loaded"):- store = SessionStore(sessions_dir=tmp_path, config=config)- store._db = db- store._loaded = True-- key = store._generate_session_key(source)- # Entry last updated 2 hours ago → well past the 60-minute idle window.- store._entries[key] = _make_entry(key, "sid_stale")- store._entries[key].updated_at = datetime.now() - timedelta(hours=2)-- result = store.get_or_create_session(source)-- # Fresh session — NOT the stale session_id.- assert result.session_id != "sid_stale"- # Auto-reset metadata is set.- assert result.was_auto_reset is True- assert result.auto_reset_reason == "idle"- # reopen_session must NOT have been called (we skipped recovery).- db.reopen_session.assert_not_called()- # A brand-new session row was created.- db.create_session.assert_called_once()---class TestRecoveredSessionResetPolicy:- """Recovery must not resurrect sessions as freshly active.-- ``_create_entry_from_recovered_row`` used to stamp ``updated_at=now`` on- the rebuilt entry, so an opt-in idle/daily ``session_reset`` policy could- never fire across a gateway restart: the recovered session always looked- freshly active, and every subsequent message bumped ``updated_at`` again- — a recovered stale session could never age out. The entry now carries- the durable ``last_activity_at`` the finder already returns on the row- and the recovery paths evaluate ``_should_reset`` before resuming.- """+class TestRecoveredSessionActivity:+ """Recovery keeps the durable session and activity timestamp."""def test_recovered_entry_carries_durable_last_activity(self, tmp_path):"""A recovered mapping reports the DB's last message time, not now()."""@@ -197,42 +140,9 @@ class TestRecoveredSessionResetPolicy:assert result.updated_at == datetime.fromtimestamp(last_activity)assert result.reset_had_activity is True- def test_recovered_session_past_idle_policy_resets_instead_of_resuming(- self, tmp_path,- ):- """Lost mapping + overdue recoverable row → reset, not silent resume."""- source = _source()- config = GatewayConfig(- default_reset_policy=SessionResetPolicy(mode="idle", idle_minutes=60),- )- db = _db_returning({})- db.find_latest_gateway_session_for_peer.return_value = {- "id": "sid_idle",- "started_at": (datetime.now() - timedelta(hours=3)).timestamp(),- "last_activity_at": (- datetime.now() - timedelta(hours=2)- ).timestamp(),- }- with patch("gateway.session.SessionStore._ensure_loaded"):- store = SessionStore(sessions_dir=tmp_path, config=config)- store._db = db- store._loaded = True- # No in-memory entry: the mapping was lost (e.g. crash before save).-- result = store.get_or_create_session(source)-- assert result.session_id != "sid_idle"- assert result.was_auto_reset is True- assert result.auto_reset_reason == "idle"- assert result.reset_had_activity is True- assert result.prev_session_id == "sid_idle"- db.reopen_session.assert_not_called()- db.promote_to_session_reset.assert_called_once_with("sid_idle", "idle")- db.end_session.assert_not_called()- db.create_session.assert_called_once()- def test_default_none_policy_recovery_resumes_unchanged(self, tmp_path):- """mode="none" (the default) still resumes recoverable rows as before."""+ def test_recovery_resumes_unchanged(self, tmp_path):+ """Recoverable rows resume as before."""source = _source()db = _db_returning({})db.find_latest_gateway_session_for_peer.return_value = {@@ -312,5 +222,3 @@ class TestAdvanceCompressionSession:assert result is not Noneassert result.updated_at == idleassert store.suspend_recently_active(max_age_seconds=120) == 0--diff --git a/tests/gateway/test_session_store_stale_prune.py b/tests/gateway/test_session_store_stale_prune.pyindex 41167ab9f6a..5fa62992582 100644--- a/tests/gateway/test_session_store_stale_prune.py+++ b/tests/gateway/test_session_store_stale_prune.py@@ -11,7 +11,7 @@ import jsonfrom datetime import datetime, timedeltafrom unittest.mock import MagicMock, patch-from gateway.config import GatewayConfig, Platform, SessionResetPolicy+from gateway.config import GatewayConfig, Platformfrom gateway.session import SessionEntry, SessionSource, SessionStore@@ -45,7 +45,7 @@ def _make_entry_with_origin(key: str, session_id: str) -> SessionEntry:def _make_store_with_db(tmp_path, db_mock) -> SessionStore:"""Build a SessionStore with a mock SessionDB, bypassing disk load."""- config = GatewayConfig(default_reset_policy=SessionResetPolicy(mode="none"))+ config = GatewayConfig()with patch("gateway.session.SessionStore._ensure_loaded"):store = SessionStore(sessions_dir=tmp_path, config=config)store._db = db_mock@@ -152,7 +152,7 @@ class TestPruneStaleSessionsLocked:mock_save.assert_not_called()def test_noop_when_db_is_none(self, tmp_path):- config = GatewayConfig(default_reset_policy=SessionResetPolicy(mode="none"))+ config = GatewayConfig()with patch("gateway.session.SessionStore._ensure_loaded"):store = SessionStore(sessions_dir=tmp_path, config=config)store._db = None@@ -220,47 +220,12 @@ class TestPruneStaleSessionsLocked:# Startup recovery honours the reset policy# ----------------------------------------------------------------------------class TestStartupRecoveryResetPolicy:- """Startup repoint must not resurrect an overdue session as fresh.+class TestStartupRecovery:+ """Recovery keeps the durable session and activity timestamp."""- The startup pruner repoints a stale entry to the recovered row via- ``_recover_session_from_db``. The rebuilt entry used to be stamped- ``updated_at=now``, so an opt-in idle/daily ``session_reset`` policy was- silently skipped across every gateway restart. Recovery now evaluates- ``_should_reset`` against the durable last message timestamp and promotes- an overdue session to a durable reset boundary instead of reopening it.- """- def test_overdue_recovered_session_promoted_to_reset_and_pruned(self, tmp_path):- key = "agent:main:telegram:dm:5140768830"- db = _db_returning(- {"sid_parent": {"end_reason": "agent_close", "id": "sid_parent"}}- )- db.find_latest_gateway_session_for_peer.return_value = {- "id": "sid_child",- "started_at": (datetime.now() - timedelta(hours=5)).timestamp(),- "last_activity_at": (- datetime.now() - timedelta(hours=4)- ).timestamp(),- }- config = GatewayConfig(- default_reset_policy=SessionResetPolicy(mode="idle", idle_minutes=60),- )- with patch("gateway.session.SessionStore._ensure_loaded"):- store = SessionStore(sessions_dir=tmp_path, config=config)- store._db = db- store._loaded = True- store._entries[key] = _make_entry_with_origin(key, "sid_parent")-- with patch.object(store, "_save"):- store._prune_stale_sessions_locked()-- assert key not in store._entries- db.promote_to_session_reset.assert_called_once_with("sid_child", "idle")- db.reopen_session.assert_not_called()-- def test_none_policy_startup_repoint_unchanged(self, tmp_path):- """mode="none" (the default) still repoints to the recovered row."""+ def test_startup_repoint_unchanged(self, tmp_path):+ """Startup repoints to the recovered row."""key = "agent:main:telegram:dm:5140768830"db = _db_returning({"sid_parent": {"end_reason": "compression", "id": "sid_parent"}}@@ -296,11 +261,10 @@ class TestEnsureLoadedCallsPrune:json.dumps({"dm_key": entry.to_dict()}, indent=2), encoding="utf-8")db = _db_returning({"sid_stale": {"end_reason": "agent_close", "id": "sid_stale"}})- config = GatewayConfig(default_reset_policy=SessionResetPolicy(mode="none"))+ config = GatewayConfig()store = SessionStore(sessions_dir=tmp_path, config=config)store._db = dbstore._ensure_loaded()assert "dm_key" not in store._entries-diff --git a/tests/gateway/test_session_time_persistence.py b/tests/gateway/test_session_time_persistence.pyindex b96b983e1be..38d52721a87 100644--- a/tests/gateway/test_session_time_persistence.py+++ b/tests/gateway/test_session_time_persistence.py@@ -27,7 +27,7 @@ def test_old_reset_config_cannot_rotate_durable_conversation(tmp_path, mode):store._save()routed = store.get_or_create_session(source)assert routed.session_id == old.session_id- assert store.load_transcript(routed.session_id) == messages+ assert [{"role": m["role"], "content": m["content"]} for m in store.load_transcript(routed.session_id)] == messagesassert store._db.get_session(old.session_id)["end_reason"] is None# Missing routing indexes must recover the same durable transcript too.store._entries.clear()@@ -37,5 +37,5 @@ def test_old_reset_config_cannot_rotate_durable_conversation(tmp_path, mode):explicit = store.reset_session(recovered.session_key)assert explicit.session_id != old.session_idassert store._db.get_session(old.session_id)["end_reason"] == "session_reset"- assert store.load_transcript(old.session_id) == messages+ assert [{"role": m["role"], "content": m["content"]} for m in store.load_transcript(old.session_id)] == messagesstore._db.close()diff --git a/tests/gateway/test_slack_approval_buttons.py b/tests/gateway/test_slack_approval_buttons.pyindex c6fb73ffe0c..bfe3b0ef61d 100644--- a/tests/gateway/test_slack_approval_buttons.py+++ b/tests/gateway/test_slack_approval_buttons.py@@ -480,38 +480,6 @@ class TestSlackThreadContext:# _has_active_session_for_thread — session key fix (#5833)# ===========================================================================-class TestSessionKeyFix:- """Test that _has_active_session_for_thread uses build_session_key."""--- def test_stale_session_returns_false(self):- """A session key that exists but would be rolled by the reset policy- must NOT count as active — otherwise the reset-time first turn skips- the thread-history reseed (#55239)."""- adapter = _make_adapter()-- class Store:- config = MagicMock()- config.group_sessions_per_user = False- config.thread_sessions_per_user = False- _entries = {- "agent:main:slack:group:C1:1000.0": MagicMock()- }-- def _ensure_loaded(self):- return None-- def _should_reset(self, entry, source):- return "idle"-- adapter._session_store = Store()-- result = adapter._has_active_session_for_thread(- channel_id="C1", thread_ts="1000.0", user_id="U123"- )-- assert result is False-class TestSessionKeyChatType:"""Test that _has_active_session_for_thread passes event-derived chat_type.@@ -840,4 +808,3 @@ class TestSlackReactionAuthorizationGate:assert "U_RANDO" in runner.auth_checkedassert runner.handled == []adapter.handle_message.assert_not_called()-diff --git a/tests/gateway/test_startup_restart_race.py b/tests/gateway/test_startup_restart_race.pyindex 8d0529c1d88..b024bcc7559 100644--- a/tests/gateway/test_startup_restart_race.py+++ b/tests/gateway/test_startup_restart_race.py@@ -109,7 +109,7 @@ def make_startup_runner(tmp_path):async def no_op_watcher(*args, **kwargs):await asyncio.Event().wait()- runner._session_expiry_watcher = no_op_watcher+ runner._session_housekeeping_watcher = no_op_watcherrunner._platform_reconnect_watcher = no_op_watcherrunner._run_process_watcher = no_op_watcherrunner._safe_adapter_disconnect = gateway_run.GatewayRunner._safe_adapter_disconnect.__get__(diff --git a/tests/hermes_cli/test_setup_agent_settings.py b/tests/hermes_cli/test_setup_agent_settings.pyindex b0e1d906ab9..54bf3e81b72 100644--- a/tests/hermes_cli/test_setup_agent_settings.py+++ b/tests/hermes_cli/test_setup_agent_settings.py@@ -16,7 +16,6 @@ def test_setup_agent_settings_uses_displayed_max_iterations_value(tmp_path, monk"agent": {"max_turns": 60},"display": {"tool_progress": "all"},"compression": {"threshold": 0.50},- "session_reset": {"mode": "both", "idle_minutes": 1440, "at_hour": 4},}prompt_answers = iter(["60", "all", "0.5"])@@ -47,7 +46,6 @@ def test_setup_agent_settings_prefers_config_over_stale_env(tmp_path, monkeypatc"agent": {"max_turns": 500}, # user bumped this in config.yaml"display": {"tool_progress": "all"},"compression": {"threshold": 0.50},- "session_reset": {"mode": "both", "idle_minutes": 1440, "at_hour": 4},}prompt_answers = iter(["500", "all", "0.5"])diff --git a/tests/hermes_cli/test_setup_blank_slate.py b/tests/hermes_cli/test_setup_blank_slate.pyindex c526b326866..67b3101c884 100644--- a/tests/hermes_cli/test_setup_blank_slate.py+++ b/tests/hermes_cli/test_setup_blank_slate.py@@ -15,7 +15,6 @@ from hermes_cli import setup_quickclass TestBlankSlateMinimalToolsets:-def test_no_disabled_bundle_overlaps_kept_tools(self):"""Invariant: ``disabled_toolsets`` is applied at *tool* granularity anda single tool can belong to several toolsets, so no disabled entry may@@ -36,7 +35,6 @@ class TestBlankSlateMinimalToolsets:)-def test_tool_schema_survives_disabled_toolsets_from_config(self, monkeypatch):"""Regression: disabled_toolsets must not erase the minimal Blank Slatesurface when passed to model_tools. Before the fix, posture toolsets@@ -87,7 +85,6 @@ class TestBlankSlateMinimizeConfig:assert cfg["memory"]["user_profile_enabled"] is Falseassert cfg["checkpoints"]["enabled"] is Falseassert cfg["smart_model_routing"]["enabled"] is False- assert cfg["session_reset"]["mode"] == "none"class TestBlankSlateFork:@@ -125,4 +122,3 @@ class TestBlankSlateFork:assert walked["called"] is False# Finish-now path records the skill opt-out (no bundled skills).assert opted_out["value"] is True-