Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix
Fail closed on an unknown middleware order, and budget copies without a capture
Elevatormusic5b3c92018dfc
diff --git a/README.md b/README.mdindex 04c75c4..7171240 100644--- a/README.md+++ b/README.md@@ -138,7 +138,7 @@ warm_compaction: path=warm reason=accepted elapsed_s=10.656 prompt_tokens=108021```- `path` is `warm`, `fallback`, or `fixed`.-- `reason` is `accepted` or the refusal code of the warm request: `disabled`, `no_capture`, `api_mode_unsupported`, `route_changed`, `settings_unsupported`, `source_transform_unsupported`, `history_changed`, `capacity`, `cancelled`, `middleware_unavailable`, `middleware_refused`, `middleware_rewrite`, `middleware_repeated`, `middleware_after_capture`, `middleware_changed_reply`, `provider_error`, `timeout`, `incomplete_response`, or `gate:<reason>`. The warm request goes through the Hermes `llm_request` and `llm_execution` middleware, as a main request does.+- `reason` is `accepted` or the refusal code of the warm request: `disabled`, `no_capture`, `api_mode_unsupported`, `route_changed`, `settings_unsupported`, `source_transform_unsupported`, `history_changed`, `capacity`, `cancelled`, `middleware_unavailable`, `middleware_refused`, `middleware_rewrite`, `middleware_repeated`, `middleware_after_capture`, `middleware_order_unknown`, `middleware_changed_reply`, `provider_error`, `timeout`, `incomplete_response`, or `gate:<reason>`. The warm request goes through the Hermes `llm_request` and `llm_execution` middleware, as a main request does.- `cached_tokens` is `None` when the server does not report it. Then the cache reuse is unknown.The engine status (`get_status()`) has the same values in `warm_last`. The log never contains message text, request bodies, or keys.diff --git a/evidence/plugin-integration.json b/evidence/plugin-integration.jsonindex 7b5a133..c7c512a 100644--- a/evidence/plugin-integration.json+++ b/evidence/plugin-integration.json@@ -1,6 +1,6 @@{"check": "standalone warm_compaction plugin on unpatched Hermes Agent",- "started_utc": "2026-10-06T10:19:34Z",+ "started_utc": "2026-10-06T10:34:19Z","hermes": {"commit": "45871e100feceb89769536c88e5e6e265226a409","clean": true@@ -9,8 +9,8 @@"script_sha256": "85397c1e4879f7cf21d3b2619baecf72fb67eb27e69376f428d0426ee69ab3d1","plugin_files_sha256": {"warm_compaction/__init__.py": "11e038f05813627b2d1d8b82b3b775ecfe41015746c8e90ed6d452cfdaec65a6",- "warm_compaction/capture.py": "9f195ff31821b1dfc486373b074b799f4bc8750b07d10b53073374f760b2f2eb",- "warm_compaction/engine.py": "dfa9d6fb060d4d7665f0467630086ecfd076742e097258415c47bb5084134888",+ "warm_compaction/capture.py": "387a5bda2c97530c6e9114e810ac062199e3731c12a582d75598d2bdb95e8c57",+ "warm_compaction/engine.py": "e0778987d455048b8aa31e36dfd9308b89d54ae756fb66ec944271863fb5af0c","warm_compaction/fallback.py": "fe6bfbd18359b84a9ebc0519b73a865fa5736a62f87e06f83535968b49317972","warm_compaction/handoff.py": "3ce85d76fce4afbefec0d9c2e91b100e09ac677a28e50ea749f4d25533d68c7e","warm_compaction/layout.py": "5e730211647eed0beec1e6819dfc008b0855a0866dc920bb0cf8d6d8ab2dfa92",@@ -75,11 +75,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.093,+ "compress_seconds": 0.101,"warm_last": {"path": "warm","reason": "accepted",- "elapsed_s": 0.018,+ "elapsed_s": 0.023,"prompt_tokens": 33883,"cached_tokens": 16941},@@ -87,11 +87,10 @@"final_session_id": "wc-enable_manual_warm","continuation_keeps_custom_system_text": false,"fence_denied": {- "child_process_blocked": 4,- "network_host_blocked": 1+ "network_host_blocked": 1,+ "child_process_blocked": 3},"fence_blocked_programs": [- "git","pip","python","python3"@@ -100,7 +99,6 @@"hermes-assets.nousresearch.com"],"fence_blocked_callers": [- "child_process_blocked from hermes_cli/source_check.py:_git_run < hermes_cli/source_check.py:_git_stdout < hermes_cli/source_check.py:_read_checkout","child_process_blocked from tools/env_probe.py:_run < tools/env_probe.py:_py_out < tools/env_probe.py:_pip_python_version","child_process_blocked from tools/env_probe.py:_run < tools/env_probe.py:_py_out < tools/env_probe.py:_python_version_of","network_host_blocked from hermes_cli/release_channels.py:read < hermes_cli/release_channels.py:read_bytes < hermes_cli/release_channels.py:read_record"@@ -188,7 +186,7 @@"install","run"],- "process_seconds": 53.953+ "process_seconds": 56.287},{"scenario": "manual_fallback",@@ -247,7 +245,7 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.25,+ "compress_seconds": 0.239,"warm_last": {"path": "fallback","reason": "provider_error",@@ -360,7 +358,7 @@"install","run"],- "process_seconds": 32.264+ "process_seconds": 35.614},{"scenario": "manual_fixed",@@ -418,11 +416,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.211,+ "compress_seconds": 0.291,"warm_last": {"path": "fixed","reason": "provider_error",- "elapsed_s": 0.094,+ "elapsed_s": 0.141,"prompt_tokens": null,"cached_tokens": null},@@ -430,7 +428,7 @@"final_session_id": "wc-manual_fixed","continuation_keeps_custom_system_text": false,"fence_denied": {- "child_process_blocked": 5,+ "child_process_blocked": 4,"network_host_blocked": 1},"fence_blocked_programs": [@@ -531,7 +529,7 @@"install","run"],- "process_seconds": 29.438+ "process_seconds": 32.777},{"scenario": "auto_tool_loop",@@ -617,20 +615,20 @@"warm_last_1": {"path": "warm","reason": "accepted",- "elapsed_s": 0.0,+ "elapsed_s": 0.016,"prompt_tokens": 35201,"cached_tokens": 17600},"warm_last_2": {"path": "warm","reason": "accepted",- "elapsed_s": 0.015,+ "elapsed_s": 0.016,"prompt_tokens": 18427,"cached_tokens": 9213},"compression_count": 2,"fence_denied": {- "child_process_blocked": 9,+ "child_process_blocked": 8,"network_host_blocked": 1},"fence_blocked_programs": [@@ -734,7 +732,7 @@"install","run"],- "process_seconds": 32.516+ "process_seconds": 34.717},{"scenario": "rollback",@@ -784,11 +782,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.159,+ "compress_seconds": 0.149,"warm_last": {"path": "warm","reason": "accepted",- "elapsed_s": 0.015,+ "elapsed_s": 0.016,"prompt_tokens": 33873,"cached_tokens": 16936},@@ -796,7 +794,7 @@"final_session_id": "wc-rollback","continuation_keeps_custom_system_text": false,"fence_denied": {- "child_process_blocked": 5,+ "child_process_blocked": 4,"network_host_blocked": 1},"fence_blocked_programs": [@@ -947,7 +945,8 @@"stored": 30},"fence_denied": {- "child_process_blocked": 5+ "child_process_blocked": 5,+ "network_host_blocked": 1},"fence_blocked_programs": ["git",@@ -955,7 +954,9 @@"python","python3"],- "fence_blocked_hosts": []+ "fence_blocked_hosts": [+ "hermes-assets.nousresearch.com"+ ]},"exit": [0,@@ -967,10 +968,10 @@"run","rollback"],- "process_seconds": 37.062+ "process_seconds": 39.397}],- "finished_utc": "2026-10-06T10:22:40Z",+ "finished_utc": "2026-10-06T10:37:38Z","passed": true,"run_folder": "outside repository"}diff --git a/tests/test_wc_capture.py b/tests/test_wc_capture.pyindex 9a27c9a..054098e 100644--- a/tests/test_wc_capture.py+++ b/tests/test_wc_capture.py@@ -3,6 +3,7 @@import unittestfrom types import SimpleNamespace+import wc_hermes_stubfrom warm_compaction.capture import CaptureStore, UnsupportedRequest, final_bodyfrom warm_compaction.rows import row_digestfrom wc_fixtures import user@@ -39,7 +40,9 @@ class FinalBodyTest(unittest.TestCase):class CaptureStoreTest(unittest.TestCase):def setUp(self):+ wc_hermes_stub.install(self)self.store = CaptureStore(clock=lambda: 5.0)+ wc_hermes_stub.CAPTURE_CHAIN.append(self.store.on_llm_execution)self.history = [user("u")]def run_request(self, request_id="r1", session="s1", api_mode="chat_completions", finish="stop",@@ -80,21 +83,35 @@ class CaptureStoreTest(unittest.TestCase):def test_no_body_when_an_execution_middleware_runs_after_the_capture(self):# A later middleware can change the request after the capture saw it. The capture cannot see that change.- import wc_hermes_stub- wc_hermes_stub.install(self)-def other(request=None, next_call=None, **context):return next_call()for chain, kept in (([self.store.on_llm_execution, other], False), ([other, self.store.on_llm_execution], True)):- wc_hermes_stub.PLUGINS._delivery_manager = lambda chain=chain: SimpleNamespace(- _middleware={"llm_execution": chain})- self.addCleanup(lambda: wc_hermes_stub.PLUGINS.__dict__.pop("_delivery_manager", None))+ wc_hermes_stub.CAPTURE_CHAIN[:] = chainwith self.subTest(kept=kept):self.run_request()capture = self.store.latest("s1")self.assertEqual(capture["body"] is not None, kept)self.assertEqual(capture.get("refusal"), None if kept else "middleware_after_capture")+ def test_no_body_when_the_middleware_order_cannot_be_read(self):+ # A later Hermes can keep the chain in another form. Then a later middleware can change the request+ # without this capture seeing it: fail closed.+ def broken():+ raise AttributeError("_middleware")+ cases = (("no manager", lambda: wc_hermes_stub.PLUGINS.__dict__.pop("_delivery_manager")),+ ("manager fails", lambda: setattr(wc_hermes_stub.PLUGINS, "_delivery_manager", broken)),+ ("capture not in the chain", wc_hermes_stub.CAPTURE_CHAIN.clear))+ manager = wc_hermes_stub.PLUGINS._delivery_manager+ for name, change in cases:+ wc_hermes_stub.CAPTURE_CHAIN[:] = [self.store.on_llm_execution]+ wc_hermes_stub.PLUGINS._delivery_manager = manager+ change()+ with self.subTest(name):+ self.run_request()+ capture = self.store.latest("s1")+ self.assertEqual((capture["body"], capture["refusal"]), (None, "middleware_order_unknown"))+ wc_hermes_stub.PLUGINS._delivery_manager = manager+def test_keeps_tool_call_ids_and_names(self):self.run_request(finish="tool_calls", message=reply_object("", [("c1", "read")]))self.assertEqual(self.store.latest("s1")["reply"]["tool_calls"], [["c1", "read"]])diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.pyindex f7316f8..cc1f0d7 100644--- a/tests/test_wc_engine.py+++ b/tests/test_wc_engine.py@@ -50,6 +50,7 @@ class EngineTest(unittest.TestCase):from warm_compaction.engine import WarmCompactionEngineself.engine_class = WarmCompactionEngineself.store = CaptureStore()+ wc_hermes_stub.CAPTURE_CHAIN.append(self.store.on_llm_execution)self.llm = FakeLlm()self.post = fake_post()self.engine = self.make()@@ -352,7 +353,26 @@ class EngineTest(unittest.TestCase):self.seed(rows, assistant("final"))capture = self.store.latest("s1")self.assertEqual(request_overhead(capture), estimate_tokens({"messages": [SYSTEM], "tools": None}))- self.assertEqual(request_overhead(None), 0)+ # Without a captured body: the host's token count less the history estimate, or unknown.+ self.assertIsNone(request_overhead(None))+ self.assertIsNone(request_overhead({"body": None}, rows, None))+ self.assertEqual(request_overhead(None, rows, estimate_tokens(rows) + 45_000), 45_000)+ self.assertEqual(request_overhead(None, rows, 10), 0)++ def test_without_a_capture_the_copies_leave_room_for_the_system_prompt_and_tools(self):+ # After a restart there is no capture. The system prompt and the tool schemas still take their space.+ from warm_compaction.rows import estimate_tokens+ rows = old_turns(20)+ engine = self.make(threshold=0.95, tail_tokens=2_000)+ engine.update_model(model=ROUTE[0], context_length=64_000, base_url=ROUTE[1], api_key="k",+ provider="custom", api_mode=ROUTE[2])+ for current, copied in ((estimate_tokens(rows), True), (estimate_tokens(rows) + 60_000, False),+ (None, False)):+ with self.subTest(current=current):+ new = engine.compress(rows, current_tokens=current)+ summary = next(row["content"] for row in new if "## Copied user messages" in str(row["content"]))+ section = summary.split("## Copied user messages", 1)[1].strip()+ self.assertEqual(not section.startswith("(none)"), copied)def test_fixed_summary_when_the_fallback_fails(self):self.llm = FakeLlm(error=RuntimeError("down"))diff --git a/tests/wc_hermes_stub.py b/tests/wc_hermes_stub.pyindex 12bba35..789e340 100644--- a/tests/wc_hermes_stub.py+++ b/tests/wc_hermes_stub.py@@ -103,6 +103,10 @@ PLUGINS = _module("hermes_cli.plugins", VALID_HOOKS={"on_session_reset"})EXECUTION_MIDDLEWARE = []REQUEST_MIDDLEWARE = []+# The llm_execution callbacks in the order that the Hermes plugin manager keeps them. A test that runs a capture+# store adds its on_llm_execution here, as the plugin registration does.+CAPTURE_CHAIN = []+PLUGINS._delivery_manager = lambda: SimpleNamespace(_middleware={"llm_execution": list(CAPTURE_CHAIN)})def apply_llm_request_middleware(request, **context):@@ -156,3 +160,4 @@ def install(test_case):test_case.addCleanup(patcher.stop)test_case.addCleanup(EXECUTION_MIDDLEWARE.clear)test_case.addCleanup(REQUEST_MIDDLEWARE.clear)+ test_case.addCleanup(CAPTURE_CHAIN.clear)diff --git a/warm_compaction/capture.py b/warm_compaction/capture.pyindex 59f16b1..04b8acd 100644--- a/warm_compaction/capture.py+++ b/warm_compaction/capture.py@@ -102,27 +102,31 @@ class CaptureStore:body = final_body(request)except UnsupportedRequest:body = None- if body is not None and self._runs_before_other_middleware():+ if body is not None:# A later middleware can change the request after this capture saw it. The warm request would# then send a body that the provider never received.- body, refusal = None, "middleware_after_capture"+ refusal = self._middleware_order_refusal()+ if refusal is not None:+ body = Nonewith self._lock:entry["body"] = bodyentry["refusal"] = refusal- def _runs_before_other_middleware(self) -> bool:- """True when another llm_execution middleware runs after this capture. The chain order is in the- Hermes plugin manager; when it cannot be read, the capture is kept."""+ def _middleware_order_refusal(self) -> str | None:+ """Return None when this capture is the last llm_execution middleware. The chain order is in the Hermes+ plugin manager (a private form). When another middleware runs after the capture, return+ middleware_after_capture; when the order cannot be read or the capture is not in it, return+ middleware_order_unknown: a later middleware could change the request (fail closed)."""try:from hermes_cli.plugins import _delivery_managerchain = list(_delivery_manager()._middleware.get("llm_execution", []))except Exception:- return False+ return "middleware_order_unknown"own = CaptureStore.on_llm_executionfor index, callback in enumerate(chain):if getattr(callback, "__self__", None) is self and getattr(callback, "__func__", None) is own:- return index < len(chain) - 1- return False+ return "middleware_after_capture" if index < len(chain) - 1 else None+ return "middleware_order_unknown"def on_post_api_request(self, api_request_id: Any = None, session_id: Any = None, finish_reason: Any = None,assistant_message: Any = None, usage: Any = None, **_: Any) -> None:diff --git a/warm_compaction/engine.py b/warm_compaction/engine.pyindex 29ce04a..7427f0a 100644--- a/warm_compaction/engine.py+++ b/warm_compaction/engine.py@@ -76,12 +76,16 @@ def sanitize_memory(memory_context: Any) -> str:return ""-def request_overhead(capture: dict[str, Any] | None) -> int:+def request_overhead(capture: dict[str, Any] | None, messages: list | None = None,+ current_tokens: Any = None) -> int | None:"""Estimated tokens of the request parts that are not history rows: the system rows and the tool schemas of- the captured request. 0 without a captured request body."""+ the captured request. Without a captured request body (for example, after a restart), the host's token+ count of the request less the history estimate. None when neither is known."""body = (capture or {}).get("body")if not isinstance(body, dict) or not isinstance(body.get("messages"), list):- return 0+ if messages is None or type(current_tokens) is not int or current_tokens <= 0:+ return None+ return max(0, current_tokens - estimate_tokens(messages))count = max(len(body["messages"]) - len(capture.get("digests") or ()), 0)return estimate_tokens({"messages": body["messages"][:count], "tools": body.get("tools")})@@ -198,14 +202,17 @@ class WarmCompactionEngine(ContextEngine):if summary is None:summary = fallback.fixed_summary(messages[:start])record["path"] = "fixed"+ # An unknown overhead can be most of the window: then no copies.+ overhead = request_overhead(capture, messages, current_tokens)+ copy_tokens = 0 if overhead is None else self._copy_tokens(messages[start:], summary, overhead,+ request_reserve(capture))new = layout.build(messages, summary, start=start, prepend=prepend, copy_chars=int(self._settings["user_copy_chars"]),header_prefix=hermes_value("agent.context_compressor", "SUMMARY_PREFIX", handoff.LEGACY_PREFIX),prefixes=prefixes,end_marker=hermes_value("agent.context_compressor", "_SUMMARY_END_MARKER", HERMES_END_MARKER),marker=hermes_value("agent.context_compressor", "_DB_PERSISTED_MARKER", HERMES_DB_MARKER),- copy_tokens=self._copy_tokens(messages[start:], summary, request_overhead(capture),- request_reserve(capture)))+ copy_tokens=copy_tokens)self.compression_count += 1self._finish(record, started)return new