Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix
Cut every list text shape, snapshot before the request middleware, and count all structured fields as overhead
Elevatormusicdb63d61d4bd9
diff --git a/evidence/plugin-integration.json b/evidence/plugin-integration.jsonindex 5923640..dc1501f 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-06T12:56:31Z",+ "started_utc": "2026-10-06T13:12:39Z","hermes": {"commit": "45871e100feceb89769536c88e5e6e265226a409","clean": true@@ -10,10 +10,10 @@"plugin_files_sha256": {"warm_compaction/__init__.py": "11e038f05813627b2d1d8b82b3b775ecfe41015746c8e90ed6d452cfdaec65a6","warm_compaction/capture.py": "387a5bda2c97530c6e9114e810ac062199e3731c12a582d75598d2bdb95e8c57",- "warm_compaction/engine.py": "d910f67fab4eb1fbfc108216b4bc7f47d583135c537043be73d1f3548b1dbf32",+ "warm_compaction/engine.py": "4364e59bc2f896a5ea138de88895c127e0a3d41e44586cdcac983905af2b194a","warm_compaction/fallback.py": "30ef046f0511491175d99a772afcc2c9a8f3a9920d0c077821a89f19147682f9","warm_compaction/handoff.py": "3ce85d76fce4afbefec0d9c2e91b100e09ac677a28e50ea749f4d25533d68c7e",- "warm_compaction/layout.py": "ba910e9df1ee04bb4f9d5c9ab6dda48e3975634e6b7b05dd930f273d3cea2b74",+ "warm_compaction/layout.py": "e0f5a265278f64bf89f826ccea04b084973c0fcf38df26effd53eb02a5dbd359","warm_compaction/plugin.yaml": "d67560fd4625ec80d9e26f3e6d712763e77474f68d469c7e48f09fd3506ccc71","warm_compaction/rows.py": "689c0619df6a7f8b89ef05ae87ec81b62c812ce34f81bfe557eb653158effac4","warm_compaction/warm.py": "081642f19498b379551af33b70ad01dae3902e1e805c360a08be9f74242d320f"@@ -76,11 +76,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.117,+ "compress_seconds": 0.098,"warm_last": {"path": "warm","reason": "accepted",- "elapsed_s": 0.038,+ "elapsed_s": 0.023,"prompt_tokens": 33883,"cached_tokens": 16941},@@ -189,7 +189,7 @@"install","run"],- "process_seconds": 52.454+ "process_seconds": 53.019},{"scenario": "manual_fallback",@@ -248,11 +248,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.22,+ "compress_seconds": 0.241,"warm_last": {"path": "fallback","reason": "provider_error",- "elapsed_s": 0.109,+ "elapsed_s": 0.11,"prompt_tokens": null,"cached_tokens": null},@@ -361,7 +361,7 @@"install","run"],- "process_seconds": 31.415+ "process_seconds": 31.935},{"scenario": "manual_fixed",@@ -419,11 +419,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.246,+ "compress_seconds": 0.24,"warm_last": {"path": "fixed","reason": "provider_error",- "elapsed_s": 0.109,+ "elapsed_s": 0.11,"prompt_tokens": null,"cached_tokens": null},@@ -532,7 +532,7 @@"install","run"],- "process_seconds": 29.036+ "process_seconds": 29.927},{"scenario": "auto_tool_loop",@@ -737,7 +737,7 @@"install","run"],- "process_seconds": 32.294+ "process_seconds": 33.118},{"scenario": "rollback",@@ -787,7 +787,7 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.154,+ "compress_seconds": 0.21,"warm_last": {"path": "warm","reason": "accepted",@@ -973,10 +973,10 @@"run","rollback"],- "process_seconds": 39.378+ "process_seconds": 37.359}],- "finished_utc": "2026-10-06T12:59:36Z",+ "finished_utc": "2026-10-06T13:15:44Z","passed": true,"run_folder": "outside repository"}diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.pyindex 13491a8..336e94c 100644--- a/tests/test_wc_engine.py+++ b/tests/test_wc_engine.py@@ -396,7 +396,7 @@ class EngineTest(unittest.TestCase):rows = old_turns(2)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(capture), estimate_tokens({"messages": [SYSTEM]}))# Without a captured body the overhead is unknown: the host's token count and the plugin estimate do not# use the same tokenizer, so their difference is not a measurement.self.assertIsNone(request_overhead(None))@@ -409,10 +409,41 @@ class EngineTest(unittest.TestCase):added = "hi\n\n" + "[recalled] " * 400capture = {"digests": [None, None], "body": {"messages": [SYSTEM, {"role": "user", "content": added},{"role": "assistant", "content": "ok"}]}}- base = estimate_tokens({"messages": [SYSTEM], "tools": None})+ base = estimate_tokens({"messages": [SYSTEM]})self.assertEqual(request_overhead(capture, rows), base + estimate_tokens(added) - estimate_tokens("hi"))self.assertEqual(request_overhead(capture), base)+ def test_request_overhead_counts_every_structured_request_field(self):+ # The legacy functions field (and tools, response schemas) comes again with the next ordinary request.+ from warm_compaction.engine import request_overhead+ from warm_compaction.rows import estimate_tokens+ functions = [{"name": "f", "description": "d " * 4_000, "parameters": {"type": "object"}}]+ capture = {"digests": [], "body": {"model": "m", "temperature": 0.2, "messages": [SYSTEM],+ "functions": functions}}+ self.assertEqual(request_overhead(capture), estimate_tokens({"messages": [SYSTEM], "functions": functions}))++ def test_a_request_middleware_that_changes_the_request_in_place_is_refused(self):+ # A host whose request chain passes the request itself: the plugin compares with its own snapshot.+ import sys+ from types import SimpleNamespace++ def in_place(request, **context):+ request["messages"].insert(0, {"role": "system", "content": "policy"})+ return SimpleNamespace(payload=request)+ module = sys.modules["hermes_cli.middleware"]+ original = module.apply_llm_request_middleware+ module.apply_llm_request_middleware = in_place+ self.addCleanup(setattr, module, "apply_llm_request_middleware", original)+ rows = old_turns()+ reply = assistant("final")+ self.seed(rows, reply)+ stored = json.dumps(self.store.latest("s1")["body"], sort_keys=True)+ self.engine.compress([*rows, reply])+ self.assertEqual((self.engine.warm_last["path"], self.engine.warm_last["reason"]),+ ("fallback", "middleware_rewrite"))+ self.assertEqual(self.post.calls, [])+ self.assertEqual(json.dumps(self.store.latest("s1")["body"], sort_keys=True), stored)+def test_request_reserve_is_the_larger_limit(self):from warm_compaction.engine import request_reserveself.assertEqual(request_reserve({"body": {"messages": [], "max_tokens": 100,diff --git a/tests/test_wc_layout.py b/tests/test_wc_layout.pyindex 51331d4..c9f890f 100644--- a/tests/test_wc_layout.py+++ b/tests/test_wc_layout.py@@ -225,6 +225,22 @@ class BoundTailTest(unittest.TestCase):self.assertEqual(note, {"type": "text", "text": "[image_url removed]"})self.assertIs(rows[0]["content"][1], image)+ def test_raw_string_parts_and_untyped_text_parts_are_cut_as_text(self):+ # visible_text reads both shapes as text: the bound cuts them, and does not replace them with a note.+ from warm_compaction.layout import CUT_NOTE, bound_tail+ from warm_compaction.rows import estimate_tokens+ rows = [user(["raw " + "a" * 20_000 + " raw-end", {"text": "untyped " + "b" * 20_000 + " untyped-end"}]),+ assistant("ok")]+ removed = []+ bounded = bound_tail(rows, 2_000, removed)+ self.assertLessEqual(sum(estimate_tokens(row) for row in bounded), 2_000)+ raw, untyped = bounded[0]["content"]+ self.assertTrue(isinstance(raw, str) and raw.startswith("raw ") and raw.endswith(" raw-end"))+ self.assertEqual(set(untyped), {"text"})+ self.assertTrue(untyped["text"].startswith("untyped ") and untyped["text"].endswith(" untyped-end"))+ self.assertEqual(len(removed), 2)+ self.assertTrue(all(part["content"].startswith(CUT_NOTE) for part in removed))+def test_the_cut_middles_are_given_back(self):# The fallback summary gets the parts that the tail cuts: they are not lost.from warm_compaction.layout import CUT_NOTE, bound_taildiff --git a/warm_compaction/engine.py b/warm_compaction/engine.pyindex caa5f97..a97d0db 100644--- a/warm_compaction/engine.py+++ b/warm_compaction/engine.py@@ -90,7 +90,9 @@ def request_overhead(capture: dict[str, Any] | None, messages: list | None = Nonif not isinstance(body, dict) or not isinstance(body.get("messages"), list):return Nonecount = max(len(body["messages"]) - len(capture.get("digests") or ()), 0)- overhead = estimate_tokens({"messages": body["messages"][:count], "tools": body.get("tools")})+ # Every structured field comes again with the next request: tools, the legacy functions, response schemas.+ structured = {key: value for key, value in body.items() if key != "messages" and isinstance(value, (dict, list))}+ overhead = estimate_tokens({"messages": body["messages"][:count], **structured})if messages is not None:# Request-time text in the captured rows (context that Hermes or a middleware added) comes again with# the next request, so it is overhead too.@@ -288,7 +290,9 @@ class WarmCompactionEngine(ContextEngine):context = {"purpose": NAME, "api_request_id": None, "session_id": self._wc_session_id,"model": self._wc_route[0], "base_url": self._wc_route[1], "api_mode": self._wc_route[2]}try:- changed = apply_llm_request_middleware(body, **context).payload+ # A copy: a host chain that passes the request itself to a middleware that changes it in place+ # would change the body that the checks below compare with (and the stored capture).+ changed = apply_llm_request_middleware(copy.deepcopy(body), **context).payloadexcept Exception as error:raise warm.WarmRefusal("middleware_refused") from errorif not isinstance(changed, dict) or not isinstance(changed.get("messages"), list):diff --git a/warm_compaction/layout.py b/warm_compaction/layout.pyindex b321260..c806b61 100644--- a/warm_compaction/layout.py+++ b/warm_compaction/layout.py@@ -241,7 +241,10 @@ def _tail_parts(row: Any) -> list[tuple[tuple, Any]]:parts.append((("content",), content))elif isinstance(content, list):for index, item in enumerate(content):- if isinstance(item, dict) and item.get("type") == "text" and isinstance(item.get("text"), str):+ # The text shapes of visible_text: a raw string, and a text dictionary with or without its type.+ if isinstance(item, str):+ parts.append((("content", index), item))+ elif isinstance(item, dict) and item.get("type", "text") == "text" and isinstance(item.get("text"), str):parts.append((("content", index), item["text"]))elif isinstance(item, dict):parts.append((("media", index), item))@@ -266,7 +269,11 @@ def _set_part(row: dict[str, Any], key: tuple, value: Any) -> dict[str, Any]:new["content"] = valueelse:items = list(content)- items[key[1]] = {**items[key[1]], "text": value} if key[0] == "content" else value+ item = items[key[1]]+ if key[0] == "media" or isinstance(item, str):+ items[key[1]] = value+ else:+ items[key[1]] = {**item, "text": value}new["content"] = itemselif key[0] == "arguments":calls = [dict(call) for call in row["tool_calls"]]