Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix
Notify plugin users when Hermes supports native warm handoff
Elevatormusic88a39ab3eb9b
diff --git a/README.md b/README.mdindex a65cf06..efde96e 100644--- a/README.md+++ b/README.md@@ -125,6 +125,38 @@ context:Start a new Hermes session after the change.+## Native warm handoff++Some Hermes versions include warm handoff in the built-in compressor. This plugin checks the installed+constructor and default configuration for that feature. It does not use a release number or the merge state+of a pull request. Updating Hermes keeps `context.engine: warm_compaction` selected.++Update this plugin to get the notice. When the feature is available, the plugin supplies one notice through+the automatic compaction status API for each engine instance. A pending warm-request failure warning has+priority; the native notice stays pending for the next permitted status. Session reset and warm-path recovery+do not repeat the notice. A new engine instance, including a clone, gets its own notice.++Hermes controls how each surface shows automatic status. The plugin keeps the notice pending when the API+suppresses status, but it cannot detect suppression after it returns the text. This is not a startup banner+or a guaranteed notice on every surface. Manual `/compress` does not use this status API. The first actual+compaction also writes the notice once to `logs/agent.log` for each engine instance. There is no persistent+notice record, configuration change, or conversation message.++To use native warm handoff, set these values in your Hermes configuration and restart Hermes:++```yaml+context:+ engine: compressor+compression:+ warm_handoff: "on"+```++The native default is `"off"`. `"on"` tries the warm request when a usable captured request is available.+`"auto"` also requires the compression summary route to use the main model, reported cached prompt tokens+greater than zero, and a captured request no more than five minutes old. A server that does not report cached+tokens needs `"on"` to try the native warm path. Refused or failed warm requests use the normal auxiliary summary.+The native mode keeps the built-in history policy, so retained history can differ from this plugin.+## SettingsThe settings are in `plugins.entries.warm_compaction.settings`. An invalid value uses the default and writes a warning to the log.diff --git a/scripts/check_plugin_hermes.py b/scripts/check_plugin_hermes.pyindex 6b9d3c1..0867b71 100644--- a/scripts/check_plugin_hermes.py+++ b/scripts/check_plugin_hermes.py@@ -14,6 +14,7 @@ from __future__ import annotationsimport argparseimport hashlib+import inspectimport jsonimport osfrom pathlib import Path@@ -68,6 +69,7 @@ SCENARIOS = ("enable_manual_warm", "manual_fallback", "manual_fixed", "auto_tool# The scenarios with automatic compaction in a tool loop.AUTO_SCENARIOS = ("auto_tool_loop", "auto_warm_failures")NOTICE_MARK = "Warm compaction unavailable"+NATIVE_NOTICE_MARK = "Hermes includes native warm handoff."# The rollback scenario has a third process: a new Hermes process with the built-in compressor.PHASES = {"rollback": ("install", "run", "rollback")}DEFAULT_PHASES = ("install", "run")@@ -508,6 +510,8 @@ def run_phase(spec, session_dir):from hermes_state import SessionDBfrom run_agent import AIAgentfrom tui_gateway.server import _compress_session_history+ result["native_warm_handoff"] = native_warm_handoff_capabilities()+ config_before = (home / "config.yaml").read_bytes()checks["listed_in_engine_picker"] = any(name == "warm_compaction" for name, *_ in _discover_context_engines())fence = Fence(session_dir, server.httpd.server_port, spec["hermes_source"],home / "plugins" / "warm_compaction")@@ -530,14 +534,19 @@ def run_phase(spec, session_dir):checks["engine_selected"] = getattr(engine, "name", None) == "warm_compaction"result["engine"] = {"name": getattr(engine, "name", None), "threshold_tokens": engine.threshold_tokens,"context_length": engine.context_length}+ checks["native_notice_not_logged_before_compaction"] = NATIVE_NOTICE_MARK not in read_agent_log(home)history = db.get_messages_as_conversation(sid)if scenario == "auto_tool_loop":- run_auto(agent, engine, history, server, result, checks)+ run_auto(agent, engine, history, server, result, checks, statuses)elif scenario == "auto_warm_failures":run_auto_failures(agent, engine, history, server, result, checks, statuses, home)else:run_manual(agent, engine, db, history, server, result, checks, scenario,_compress_session_history, finalize_context_engine_compression_notification)+ check_native_notice(agent, engine, db, server, result, checks, statuses, home, config_before)+ if scenario == "auto_warm_failures":+ # The boundary probe uses a second engine. Check the main engine's log count first.+ check_host_commit_boundaries(engine, checks)result["fence_denied"] = fence.deniedresult["fence_blocked_programs"] = sorted(fence.programs)result["fence_blocked_hosts"] = sorted(fence.hosts)@@ -712,6 +721,42 @@ def summary_rows_ok(history):and str(history[1].get("content") or "").startswith("[CONTEXT SUMMARY]:"))+def native_warm_handoff_capabilities():+ """Read the native constructor and config contract from the real Hermes source."""+ from agent.context_compressor import ContextCompressor+ from hermes_cli import config++ parameter = inspect.signature(ContextCompressor.__init__).parameters.get("warm_handoff")+ constructor = parameter is not None and parameter.kind in (+ inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY)+ defaults = getattr(config, "DEFAULT_CONFIG", {})+ setting = defaults.get("compression", {}).get("warm_handoff") in ("off", "on", "auto")+ return {"constructor_parameter": constructor, "config_setting": setting, "available": constructor and setting}+++def read_agent_log(home):+ path = home / "logs" / "agent.log"+ return path.read_text(encoding="utf-8", errors="replace") if path.is_file() else ""+++def check_native_notice(agent, engine, db, server, result, checks, statuses, home, config_before):+ """Check notice delivery and isolation without changing the host or engine selection."""+ expected = result["native_warm_handoff"]["available"]+ notices = [message for _kind, message in statuses if NATIVE_NOTICE_MARK in message]+ log_count = read_agent_log(home).count(NATIVE_NOTICE_MARK)+ automatic = result["scenario"] in AUTO_SCENARIOS+ result["native_notice"] = {"status_count": len(notices), "log_count": log_count}+ checks["native_notice_status_count"] = len(notices) == int(expected and automatic)+ checks["native_notice_log_count"] = log_count == int(expected)+ checks["native_notice_engine_unchanged"] = (+ agent.context_compressor is engine and getattr(engine, "name", None) == "warm_compaction")+ checks["native_notice_config_unchanged"] = (home / "config.yaml").read_bytes() == config_before+ checks["native_notice_not_in_requests"] = all(+ NATIVE_NOTICE_MARK not in json.dumps(request["body"]) for request in server.requests)+ saved = db.get_messages_as_conversation(agent.session_id)+ checks["native_notice_not_in_saved_history"] = NATIVE_NOTICE_MARK not in json.dumps(saved)++def run_manual(agent, engine, db, history, server, result, checks, scenario, compress, finalize):seed = agent.run_conversation(SEED_QUESTION, system_message=SYSTEM, conversation_history=history)messages = seed.get("messages") or []@@ -739,6 +784,7 @@ def run_manual(agent, engine, db, history, server, result, checks, scenario, comchecks["path_and_reason"] = (warm_last.get("path"), warm_last.get("reason")) == expectedchecks["removed_rows"] = removed > 0after = session["history"]+ checks["native_notice_not_in_manual_history"] = NATIVE_NOTICE_MARK not in json.dumps(after)checks["summary_rows"] = summary_rows_ok(after)checks["tail_starts_with_user"] = after[2].get("role") == "user"if scenario == "enable_manual_warm":@@ -766,9 +812,12 @@ def run_manual(agent, engine, db, history, server, result, checks, scenario, comlater[0]["body"]["messages"][0].get("content") or "")-def run_auto(agent, engine, history, server, result, checks):+def run_auto(agent, engine, history, server, result, checks, statuses):checks["threshold_from_settings"] = engine.threshold_tokens == int(CONTEXT_LENGTH * 0.4)first = agent.run_conversation(TOOL_QUESTION, system_message=SYSTEM, conversation_history=history)+ first_notice_count = sum(NATIVE_NOTICE_MARK in message for _kind, message in statuses)+ checks["native_notice_on_first_automatic_compaction"] = (+ first_notice_count == int(result["native_warm_handoff"]["available"]))checks["first_turn_final"] = first.get("final_response") == "Done."checks["first_warm_request"] = len(by_kind(server, "warm")) == 1result["warm_last_1"] = dict(engine.warm_last or {})@@ -781,6 +830,10 @@ def run_auto(agent, engine, history, server, result, checks):second = agent.run_conversation(TOOL_AGAIN_QUESTION, system_message=SYSTEM,conversation_history=list(after_first))checks["second_turn_final"] = second.get("final_response") == "Done again."+ checks["native_notice_not_repeated"] = (+ sum(NATIVE_NOTICE_MARK in message for _kind, message in statuses) == first_notice_count)+ checks["native_notice_not_in_automatic_history"] = all(+ NATIVE_NOTICE_MARK not in json.dumps(rows) for rows in (after_first, second.get("messages") or []))checks["second_warm_request"] = len(by_kind(server, "warm")) == 2result["warm_last_2"] = dict(engine.warm_last or {})checks["second_path_warm"] = result["warm_last_2"].get("path") == "warm"@@ -850,7 +903,6 @@ def run_auto_failures(agent, engine, history, server, result, checks, statuses,checks["each_refusal_in_agent_log"] = agent_log.count(refusal) == 3checks["each_refusal_in_errors_log"] = errors_log.count(refusal) == 3checks["notice_in_errors_log"] = errors_log.count("Warm compaction failed 3 times in a row") == 1- check_host_commit_boundaries(engine, checks)def check_host_commit_boundaries(engine, checks):diff --git a/tests/test_wc_native.py b/tests/test_wc_native.pynew file mode 100644index 0000000..6df9044--- /dev/null+++ b/tests/test_wc_native.py@@ -0,0 +1,103 @@+"""Native capability and one-time notice tests with stand-in Hermes modules."""++import unittest+from types import SimpleNamespace+from unittest.mock import patch++import wc_hermes_stub+++class NativeCapabilityTest(unittest.TestCase):+ def probe(self, constructor, defaults):+ from warm_compaction.native import native_available+ modules = {"agent.context_compressor": SimpleNamespace(ContextCompressor=constructor),+ "hermes_cli.config": SimpleNamespace(DEFAULT_CONFIG=defaults)}+ with patch("warm_compaction.native.importlib.import_module", side_effect=modules.__getitem__):+ return native_available()++ def test_explicit_native_setting_and_constructor_are_required(self):+ class Native:+ def __init__(self, *, warm_handoff="off"):+ pass++ class Old:+ def __init__(self, **kwargs):+ pass++ defaults = {"compression": {"warm_handoff": "off"}}+ self.assertTrue(self.probe(Native, defaults))+ self.assertFalse(self.probe(Old, defaults))+ self.assertFalse(self.probe(Native, {"compression": {}}))+ self.assertFalse(self.probe(Native, {"compression": {"warm_handoff": "unknown"}}))++ def test_import_failure_is_quiet(self):+ from warm_compaction.native import native_available+ with patch("warm_compaction.native.importlib.import_module", side_effect=ImportError):+ self.assertFalse(native_available())+++class NativeNoticeTest(unittest.TestCase):+ def setUp(self):+ wc_hermes_stub.install(self)+ from warm_compaction.engine import WarmCompactionEngine+ self.engine_class = WarmCompactionEngine+ self.probe = patch("warm_compaction.engine.native.native_available", return_value=True)+ self.probe.start()+ self.addCleanup(self.probe.stop)+ self.engine = self.engine_class()++ def status(self, engine=None):+ return (engine or self.engine).get_automatic_compaction_status_message(+ phase="compress", default_message="Normal compaction status")++ def test_notice_once_and_not_reset_by_session_or_recovery(self):+ from warm_compaction.native import NOTICE+ self.assertEqual(self.status(), NOTICE)+ self.engine.on_session_reset()+ self.engine.on_session_start("new", boundary_reason="compression", old_session_id="old")+ self.engine._clear_warm_failures()+ self.assertEqual(self.status(), "Normal compaction status")++ def test_suppressed_status_keeps_the_notice(self):+ from warm_compaction.native import NOTICE+ self.engine.emit_automatic_compaction_status = False+ self.assertIsNone(self.status())+ self.engine.emit_automatic_compaction_status = True+ self.assertEqual(self.status(), NOTICE)++ def test_failure_notice_has_priority_and_native_notice_stays_pending(self):+ from warm_compaction.native import NOTICE+ self.engine._warm_notice = "Warm request failed; fallback summary used"+ self.engine.emit_automatic_compaction_status = False+ self.assertIsNone(self.status())+ self.engine.emit_automatic_compaction_status = True+ self.assertEqual(self.status(), "Warm request failed; fallback summary used")+ self.assertEqual(self.status(), NOTICE)+ self.assertEqual(self.status(), "Normal compaction status")++ def test_clone_has_its_own_notice_state(self):+ from warm_compaction.native import NOTICE+ self.assertEqual(self.status(), NOTICE)+ clone = self.engine.clone_for_agent()+ self.assertEqual(self.status(clone), NOTICE)+ self.assertEqual(self.status(), "Normal compaction status")++ def test_old_host_keeps_normal_status(self):+ with patch("warm_compaction.engine.native.native_available", return_value=False):+ engine = self.engine_class()+ self.assertEqual(self.status(engine), "Normal compaction status")++ def test_manual_compaction_logs_once_after_it_has_content(self):+ from warm_compaction.native import NOTICE+ from wc_fixtures import assistant, user+ rows = [user("synthetic old request " + "x" * 500), assistant("synthetic old answer " + "y" * 500),+ user("synthetic latest request")]+ self.engine.update_model("synthetic-model", 200_000)+ self.engine._settings["tail_tokens"] = 20+ with patch("warm_compaction.engine.logger.info") as log:+ self.engine.compress([])+ log.assert_not_called()+ self.engine.compress(rows)+ self.engine.compress(rows)+ self.assertEqual(sum(call.args == (NOTICE,) for call in log.call_args_list), 1)+ self.assertEqual(self.status(), NOTICE)diff --git a/warm_compaction/engine.py b/warm_compaction/engine.pyindex b505390..8d53372 100644--- a/warm_compaction/engine.py+++ b/warm_compaction/engine.py@@ -11,7 +11,7 @@ from collections.abc import Callablefrom agent.context_engine import ContextEngine-from . import fallback, handoff, layout, warm+from . import fallback, handoff, layout, native, warmfrom .capture import CaptureStore, key_stampfrom .rows import SendPolicy, api_content, attr, estimate_tokens, hermes_value, sent_rows, sent_tokens@@ -174,6 +174,9 @@ class WarmCompactionEngine(ContextEngine):self._wc_provider: str = ""# True after the first update_model: an empty provider and key are an identity too.self._wc_identity_set = False+ self._native_available = native.native_available()+ self._native_notice_pending = self._native_available+ self._native_notice_logged = False# Compactions in a row without the warm path, their reasons, and the notice for the next status.self._clear_warm_failures()@@ -306,6 +309,10 @@ class WarmCompactionEngine(ContextEngine):policy)if start <= 0:return messages+ with self._wc_result_lock:+ if self._native_available and not self._native_notice_logged:+ self._native_notice_logged = True+ logger.info(native.NOTICE)memory = sanitize_memory(memory_context)record: dict[str, Any] = {"path": None, "reason": None, "elapsed_s": None, "prompt_tokens": None,"cached_tokens": None}@@ -758,11 +765,16 @@ class WarmCompactionEngine(ContextEngine):def get_automatic_compaction_status_message(self, *, phase: str, default_message: str,**context: Any) -> str | None:- """Return one pending warning when Hermes permits an automatic compaction status."""+ """Return a pending failure warning first, then the native notice, when status is permitted."""message = super().get_automatic_compaction_status_message(phase=phase, default_message=default_message,**context)if message is None:return Nonewith self._wc_result_lock:notice, self._warm_notice = self._warm_notice, None- return notice if notice is not None else message+ if notice is not None:+ return notice+ if self._native_notice_pending:+ self._native_notice_pending = False+ return native.NOTICE+ return messagediff --git a/warm_compaction/native.py b/warm_compaction/native.pynew file mode 100644index 0000000..5a7f3ee--- /dev/null+++ b/warm_compaction/native.py@@ -0,0 +1,27 @@+"""Check for native warm handoff without a version or merge-status check."""++from __future__ import annotations++import importlib+import inspect++NOTICE = (+ 'Hermes includes native warm handoff. The warm_compaction plugin remains active. '+ 'To switch, set context.engine: compressor and compression.warm_handoff: "on", then restart Hermes. '+ 'The native mode keeps the built-in history policy; retained history can differ from the plugin. '+ 'For auto mode and details, see https://github.com/Elevatormusic/hermes-warm-compaction#native-warm-handoff.'+)+++def native_available() -> bool:+ """Return true only when the constructor and default config support warm handoff."""+ try:+ compressor = importlib.import_module("agent.context_compressor").ContextCompressor+ parameter = inspect.signature(compressor.__init__).parameters.get("warm_handoff")+ defaults = importlib.import_module("hermes_cli.config").DEFAULT_CONFIG+ value = defaults.get("compression", {}).get("warm_handoff")+ return (parameter is not None+ and parameter.kind in {inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY}+ and value in ("off", "on", "auto"))+ except Exception:+ return False