The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tools): keep spillover archives for the session retention window
liuhao1024dc6e76f468e3
diff --git a/gateway/run_housekeeping_disk.py b/gateway/run_housekeeping_disk.pyindex d37991e0cf0..a93765154a0 100644--- a/gateway/run_housekeeping_disk.py+++ b/gateway/run_housekeeping_disk.py@@ -18,7 +18,9 @@ logger = logging.getLogger(__name__)def housekeeping_media_caches() -> None:- """Every platform media cache prunes on the same hourly cadence (24h max age)."""+ """Every platform media cache prunes on the same hourly cadence (24h max age).+ Spillover is the exception: its files are archives the transcript points at, so+ cleanup_spillover_cache() keeps them for the session retention window (#126351)."""from gateway.platforms.base import (cleanup_audio_cache, cleanup_document_cache, cleanup_image_cache, cleanup_screenshot_cache,cleanup_video_cache)@@ -32,7 +34,7 @@ def housekeeping_media_caches() -> None:for cache_name, cleanup_fn in (("Image", cleanup_image_cache), ("Document", cleanup_document_cache),("Audio", cleanup_audio_cache), ("Video", cleanup_video_cache),- ("Screenshot", cleanup_screenshot_cache), ("Spillover", cleanup_spillover_cache),+ ("Screenshot", cleanup_screenshot_cache),("Terminal temp", cleanup_terminal_temp_cache), ("Bot DM", cleanup_bot_dm_cache),("Bot relay", cleanup_bot_relay_artifacts)):def _one(name=cache_name, fn=cleanup_fn):@@ -41,6 +43,12 @@ def housekeeping_media_caches() -> None:logger.info("%s cache cleanup: removed %d stale file(s)", name, removed)_housekeeping_chore(f"{cache_name} cache cleanup", _one)+ def _spillover():+ removed = cleanup_spillover_cache()+ if removed:+ logger.info("Spillover cache cleanup: removed %d stale file(s)", removed)+ _housekeeping_chore("Spillover cache cleanup", _spillover)+def maybe_post_auto_prune_prompt(runner, loop) -> None:"""One housekeeping tick: post the prompt to every served profile that has a home channel, adiff --git a/tests/tools/test_tool_result_storage.py b/tests/tools/test_tool_result_storage.pyindex 90f1b1343b7..d9cf1c82d0c 100644--- a/tests/tools/test_tool_result_storage.py+++ b/tests/tools/test_tool_result_storage.py@@ -211,6 +211,16 @@ class TestBuildPersistedMessage:assert "first 100 chars..." in msgassert "..." in msg # has_more indicator+ def test_message_conditions_the_do_not_rerequest_promise(self):+ """#126351: the pointer must not promise the file forever — spill files are+ pruned after the session retention window, and the notice says what to do."""+ msg = _build_persisted_message(+ preview="preview", has_more=True, original_size=50_000,+ file_path="/tmp/hermes-results/test123.txt")+ assert "retention" in msg+ assert "pruned" in msg+ assert "re-run the original tool" in msg+# ── maybe_persist_tool_result ─────────────────────────────────────────class TestMaybePersistToolResult:@@ -501,14 +511,62 @@ class TestSpillover:assert not old.exists()assert new.exists()+ def test_cleanup_default_age_is_session_retention_not_24h(self, monkeypatch):+ """#126351: a 48h-old spill must survive the DEFAULT cleanup — the durable+ transcript points at it, so files live for the session retention window."""+ import os+ import time as _time++ import tools.tool_result_storage as trs+ spill_dir = get_spillover_dir()+ spill_dir.mkdir(parents=True, exist_ok=True)+ old = spill_dir / "old.txt"+ old.write_text("old", encoding="utf-8")+ stale = _time.time() - (48 * 3600)+ os.utime(old, (stale, stale))++ monkeypatch.setattr(trs, "_spillover_retention_hours", lambda: 90 * 24)+ removed = cleanup_spillover_cache()++ assert removed == 0+ assert old.exists()++ def test_retention_hours_reads_session_retention_days(self, monkeypatch):+ import hermes_cli.config+ import tools.tool_result_storage as trs++ monkeypatch.setattr(+ hermes_cli.config, "load_config_readonly",+ lambda: {"sessions": {"retention_days": 7}})+ assert trs._spillover_retention_hours() == 7 * 24++ def test_retention_hours_defaults_and_falls_back(self, monkeypatch):+ import hermes_cli.config+ import tools.tool_result_storage as trs++ monkeypatch.setattr(hermes_cli.config, "load_config_readonly", lambda: {})+ assert trs._spillover_retention_hours() == 90 * 24++ def _boom():+ raise RuntimeError("config unreadable")++ monkeypatch.setattr(hermes_cli.config, "load_config_readonly", _boom)+ assert trs._spillover_retention_hours() == trs.SPILLOVER_MAX_AGE_HOURS++ monkeypatch.setattr(+ hermes_cli.config, "load_config_readonly",+ lambda: {"sessions": {"retention_days": -5}})+ assert trs._spillover_retention_hours() == trs.SPILLOVER_MAX_AGE_HOURS+def test_cleanup_missing_dir_returns_zero(self):assert cleanup_spillover_cache() == 0- def test_first_spill_prunes_expired_files(self):+ def test_first_spill_prunes_expired_files(self, monkeypatch):"""The once-per-process prune fires on the first host-side spill."""import osimport time as _time+ import tools.tool_result_storage as trsspill_dir = get_spillover_dir()spill_dir.mkdir(parents=True, exist_ok=True)old = spill_dir / "ancient.txt"@@ -516,6 +574,9 @@ class TestSpillover:stale = _time.time() - (48 * 3600)os.utime(old, (stale, stale))+ # The prune default is the session retention window (>= 24h), so pin a+ # one-day retention to prove the sweep actually fires on a 48h-old file.+ monkeypatch.setattr(trs, "_spillover_retention_hours", lambda: 24)maybe_persist_tool_result(content="v" * 60_000,tool_name="tool_call",diff --git a/tools/tool_result_storage.py b/tools/tool_result_storage.pyindex 33c50e827d2..68ea0610f4a 100644--- a/tools/tool_result_storage.py+++ b/tools/tool_result_storage.py@@ -22,6 +22,8 @@ PERSISTED_OUTPUT_TAG = "<persisted-output>"PERSISTED_OUTPUT_CLOSING_TAG = "</persisted-output>"STORAGE_DIR = os.path.join(tempfile.gettempdir(), "hermes-results")SPILLOVER_SUBDIR = "cache/spillover"+# Fallback spillover age only (unreadable config); the real default is the session+# retention window — see _spillover_retention_hours().SPILLOVER_MAX_AGE_HOURS = 24_BUDGET_TOOL_NAME = "__budget_enforcement__"# The exact key set tools/mcp_tool_handlers.py::_render_call_tool_result emits. A JSON object whose@@ -42,10 +44,26 @@ def get_spillover_dir():return get_hermes_home() / SPILLOVER_SUBDIR-def cleanup_spillover_cache(max_age_hours: int = SPILLOVER_MAX_AGE_HOURS) -> int:+def _spillover_retention_hours() -> int:+ """Default spillover age = the session retention window (``sessions.retention_days``).+ Spill files are archives the durable transcript points at, not a cache: a session resumed+ days later must still find what the ``<persisted-output>`` pointer promises (#126351).+ Falls back to the legacy 24h cache age when the config is unreadable."""+ try:+ from hermes_cli.config import load_config_readonly+ days = int((load_config_readonly().get("sessions") or {}).get("retention_days", 90))+ except Exception:+ return SPILLOVER_MAX_AGE_HOURS+ return SPILLOVER_MAX_AGE_HOURS if days < 0 else days * 24+++def cleanup_spillover_cache(max_age_hours: int | None = None) -> int:"""Delete spillover files older than *max_age_hours*; returns count removed (same- contract as the ``cleanup_*_cache`` helpers the gateway housekeeping loop runs hourly)."""- cutoff = time.time() - (max_age_hours * 3600)+ contract as the ``cleanup_*_cache`` helpers the gateway housekeeping loop runs hourly).+ A ``None`` age means the session retention window, not a cache TTL — an explicit+ ``max_age_hours`` (tests, legacy callers) still wins."""+ age_hours = _spillover_retention_hours() if max_age_hours is None else max_age_hours+ cutoff = time.time() - (age_hours * 3600)removed = 0try:entries = list(get_spillover_dir().iterdir())@@ -273,7 +291,9 @@ def _build_persisted_message(preview: str, has_more: bool, original_size: int,"Use the read_file tool with offset and limit to access specific sections of this output.\n""Recovery: page through the saved file with read_file (offset/limit) or ""process it with execute_code — do NOT re-request the same data from the "- "remote API; the full result is already on disk.\n\n"+ "remote API while the file exists; it is kept for the session retention "+ "window, and if it has since been pruned, re-run the original tool to "+ "regenerate the output.\n\n"f"Preview (first {len(preview)} chars):\n"+ preview + ("\n..." if has_more else "")+ f"\n{PERSISTED_OUTPUT_CLOSING_TAG}")