Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix
Accept only the warm reply itself, compare text exactly, and copy the sent text
Elevatormusic722edca415d0
diff --git a/evidence/plugin-integration.json b/evidence/plugin-integration.jsonindex f53250e..9b87532 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-06T07:51:51Z",+ "started_utc": "2026-10-06T08:09:55Z","hermes": {"commit": "45871e100feceb89769536c88e5e6e265226a409","clean": true@@ -10,13 +10,13 @@"plugin_files_sha256": {"warm_compaction/__init__.py": "11e038f05813627b2d1d8b82b3b775ecfe41015746c8e90ed6d452cfdaec65a6","warm_compaction/capture.py": "3ee60f35ae4e8fc0376ab6634c721ae1ca429593d10730f19addc3be545fe682",- "warm_compaction/engine.py": "0f989bf6668a6f1b9c37e112a5d4f1fd8df1cb588ee44d3af31aaf0a1e435f1d",- "warm_compaction/fallback.py": "83c00652f9fc1aeb1673636e1cf33f1793a0c5adb46a613368d27abad80592df",+ "warm_compaction/engine.py": "60f78d788eb7abb2e76a86fe2148837b233758e2ce7c05eccec9fb5c27001149",+ "warm_compaction/fallback.py": "f2551f0cf957b07fa6ba79dd92c8c5e211d70810d675e492ca509063b92de5a1","warm_compaction/handoff.py": "2fcdc2af2eba2d36eaabfef912ce0dd6d64bccc7849849e6411869a0025a06c2",- "warm_compaction/layout.py": "e6f6c92c91b8c9da415bff6e430c1eaaddb62d14ed403ff700cf8ed23bb1ecca",+ "warm_compaction/layout.py": "fd4d260380ce2cc44aa846758762a05bb4737c10677bceec0b17fd3c59c943f5","warm_compaction/plugin.yaml": "d67560fd4625ec80d9e26f3e6d712763e77474f68d469c7e48f09fd3506ccc71","warm_compaction/rows.py": "a8943216049ef95742466c5628108154e239b96672726c732c508e30c95ac914",- "warm_compaction/warm.py": "93401d68420d9e2e99f7f4bc83eed6a530fa38f43c6c27d53fe655b085166747"+ "warm_compaction/warm.py": "595ab834836c6605480df8a6b9decadde19f6d114e7781b04e6d0cfddb3b1b18"},"privacy": "metadata only: names, counts, codes, booleans, and times; no message text","scenarios": [@@ -75,7 +75,7 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.109,+ "compress_seconds": 0.118,"warm_last": {"path": "warm","reason": "accepted",@@ -188,7 +188,7 @@"install","run"],- "process_seconds": 58.832+ "process_seconds": 61.681},{"scenario": "manual_fallback",@@ -247,11 +247,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.242,+ "compress_seconds": 0.36,"warm_last": {"path": "fallback","reason": "provider_error",- "elapsed_s": 0.109,+ "elapsed_s": 0.172,"prompt_tokens": null,"cached_tokens": null},@@ -360,7 +360,7 @@"install","run"],- "process_seconds": 32.847+ "process_seconds": 36.723},{"scenario": "manual_fixed",@@ -418,11 +418,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.254,+ "compress_seconds": 0.255,"warm_last": {"path": "fixed","reason": "provider_error",- "elapsed_s": 0.125,+ "elapsed_s": 0.11,"prompt_tokens": null,"cached_tokens": null},@@ -430,7 +430,7 @@"final_session_id": "wc-manual_fixed","continuation_keeps_custom_system_text": false,"fence_denied": {- "child_process_blocked": 4,+ "child_process_blocked": 5,"network_host_blocked": 1},"fence_blocked_programs": [@@ -531,7 +531,7 @@"install","run"],- "process_seconds": 31.429+ "process_seconds": 35.632},{"scenario": "auto_tool_loop",@@ -617,7 +617,7 @@"warm_last_1": {"path": "warm","reason": "accepted",- "elapsed_s": 0.015,+ "elapsed_s": 0.016,"prompt_tokens": 35205,"cached_tokens": 17602},@@ -734,7 +734,7 @@"install","run"],- "process_seconds": 34.844+ "process_seconds": 37.074},{"scenario": "rollback",@@ -784,11 +784,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.176,+ "compress_seconds": 0.132,"warm_last": {"path": "warm","reason": "accepted",- "elapsed_s": 0.016,+ "elapsed_s": 0.0,"prompt_tokens": 33873,"cached_tokens": 16936},@@ -796,7 +796,7 @@"final_session_id": "wc-rollback","continuation_keeps_custom_system_text": false,"fence_denied": {- "child_process_blocked": 4,+ "child_process_blocked": 5,"network_host_blocked": 1},"fence_blocked_programs": [@@ -947,8 +947,7 @@"stored": 30},"fence_denied": {- "child_process_blocked": 5,- "network_host_blocked": 1+ "child_process_blocked": 5},"fence_blocked_programs": ["git",@@ -956,9 +955,7 @@"python","python3"],- "fence_blocked_hosts": [- "hermes-assets.nousresearch.com"- ]+ "fence_blocked_hosts": []},"exit": [0,@@ -970,10 +967,10 @@"run","rollback"],- "process_seconds": 40.93+ "process_seconds": 40.907}],- "finished_utc": "2026-10-06T07:55:10Z",+ "finished_utc": "2026-10-06T08:13:27Z","passed": true,"run_folder": "outside repository"}diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.pyindex 28f1a64..35ef278 100644--- a/tests/test_wc_engine.py+++ b/tests/test_wc_engine.py@@ -187,6 +187,25 @@ class EngineTest(unittest.TestCase):("fallback", reason))self.assertEqual(self.post.calls, [])+ def test_a_replacement_reply_of_the_right_shape_stops_the_warm_request(self):+ def replace(request=None, next_call=None, **context):+ return {"content": HEADINGS_TEXT, "finish_reason": "stop", "prompt_tokens": 10, "completion_tokens": 5,+ "cached_tokens": 0, "tool_calls": False, "refusal": False, "elapsed_s": 0.0}++ def change(request=None, next_call=None, **context):+ reply = next_call()+ reply["content"] = HEADINGS_TEXT.replace("report.txt", "other.txt")+ return reply+ for middleware in (replace, change):+ with self.subTest(middleware.__name__):+ wc_hermes_stub.EXECUTION_MIDDLEWARE[:] = [middleware]+ rows = old_turns()+ reply = assistant("final")+ self.seed(rows, reply)+ self.engine.compress([*rows, reply])+ self.assertEqual((self.engine.warm_last["path"], self.engine.warm_last["reason"]),+ ("fallback", "middleware_changed_reply"))+def test_a_rewriting_middleware_stops_the_warm_request(self):# The capture keeps the body before later middleware. A middleware that rewrites requests can have# rewritten the captured request too, so the warm request is not sent.diff --git a/tests/test_wc_fallback.py b/tests/test_wc_fallback.pyindex 2725fe4..35f86ec 100644--- a/tests/test_wc_fallback.py+++ b/tests/test_wc_fallback.py@@ -68,6 +68,12 @@ class TranscriptTest(unittest.TestCase):text = transcript(rows, PREFIXES)self.assertIn("[first user message]\n[ctx]\n\nfirst", text)+ def test_a_long_earlier_summary_keeps_its_end(self):+ old = "[CONTEXT SUMMARY]:\n## Goal\n" + "x" * 10_000 + "\n## Next step\nthe final step"+ text = transcript([assistant(old, _compressed_summary=True), user("go"), assistant("ok")], PREFIXES)+ self.assertIn("## Goal", text)+ self.assertIn("## Next step\nthe final step", text)+def test_names_are_in_the_transcript_labels(self):text = transcript([user("ship it", name="alice"), user("wait", name="bob"), assistant("ok", name="lead")],PREFIXES)diff --git a/tests/test_wc_layout.py b/tests/test_wc_layout.pyindex e4cc939..782a60a 100644--- a/tests/test_wc_layout.py+++ b/tests/test_wc_layout.py@@ -80,6 +80,21 @@ class CopyTest(unittest.TestCase):self.assertEqual(copied_user_messages(rows, 24_000, PREFIXES, max_tokens=100), [])+class CopyFormTest(unittest.TestCase):+ def test_copies_use_the_sent_api_content(self):+ self.assertEqual(copied_user_messages([user("hi", api_content="[ctx]\n\nhi")], 1_000, PREFIXES),+ ["[ctx]\n\nhi"])++ def test_the_token_budget_counts_the_quote_marks(self):+ from warm_compaction.layout import quote+ from warm_compaction.rows import estimate_tokens+ text = "a\n" * 1_000+ rows = [user(text)]+ self.assertEqual(copied_user_messages(rows, 24_000, PREFIXES, max_tokens=estimate_tokens(text) + 10), [])+ quoted = estimate_tokens(quote(text.strip()))+ self.assertEqual(len(copied_user_messages(rows, 24_000, PREFIXES, max_tokens=quoted)), 1)++class AttachmentAndPrependTest(unittest.TestCase):def test_an_image_only_user_row_is_real_and_copied_as_a_mark(self):row = user([{"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}])diff --git a/tests/test_wc_warm.py b/tests/test_wc_warm.pyindex e09218b..9eba35f 100644--- a/tests/test_wc_warm.py+++ b/tests/test_wc_warm.py@@ -240,6 +240,15 @@ class BuildRequestTest(unittest.TestCase):sent[-3]["tool_calls"][0]["function"]["arguments"] = "{ \"path\": \"a\" }"self.assertEqual(self.build(capture)["messages"][: len(sent)], sent)+ def test_refuses_changed_whitespace_inside_the_text(self):+ self.rows = [user("def f():\n return 1"), assistant("a1"), user("u2")]+ self.messages = [*self.rows, self.reply, tool("c1", "r1"), user("u3")]+ capture = capture_for(self.rows, self.reply)+ capture["body"]["messages"][1]["content"] = "def f():\n return 1"+ with self.assertRaises(WarmRefusal) as caught:+ self.build(capture)+ self.assertEqual(caught.exception.code, "source_transform_unsupported")+def test_refuses_when_the_window_is_too_small(self):with self.assertRaises(WarmRefusal) as caught:self.build(capture_for(self.rows, self.reply), context_length=4_096)diff --git a/warm_compaction/engine.py b/warm_compaction/engine.pyindex 75d1db8..ba346b4 100644--- a/warm_compaction/engine.py+++ b/warm_compaction/engine.py@@ -248,20 +248,24 @@ class WarmCompactionEngine(ContextEngine):raise warm.WarmRefusal("middleware_refused")# A copy that no middleware can change in place.base = copy.deepcopy(body)+ sent: list[tuple[dict[str, Any], dict[str, Any]]] = []def terminal(request: Any) -> dict[str, Any]:# The capture keeps the body before the execution middleware. An execution middleware that rewrites# this request can also have rewritten the captured request, so the warm request is not sent.if request != base:raise warm.WarmRefusal("middleware_rewrite")- return warm.send(base, self._wc_route[1], self._wc_api_key, post=self._post)+ result = warm.send(base, self._wc_route[1], self._wc_api_key, post=self._post)+ sent.append((result, dict(result)))+ return resulttry:reply = run_llm_execution_middleware(body, terminal, original_request=base, **context)except warm.WarmRefusal:raiseexcept Exception as error:raise warm.WarmRefusal("middleware_refused") from error- if not isinstance(reply, dict) or not {"content", "finish_reason", "prompt_tokens"} <= reply.keys():+ # Only the reply of this request: a middleware that skipped the request or changed its reply stops it.+ if not sent or reply is not sent[0][0] or reply != sent[0][1]:raise warm.WarmRefusal("middleware_changed_reply")return replydiff --git a/warm_compaction/fallback.py b/warm_compaction/fallback.pyindex 9125546..dad3d63 100644--- a/warm_compaction/fallback.py+++ b/warm_compaction/fallback.py@@ -135,8 +135,9 @@ def transcript(messages: list, prefixes: Iterable[str]) -> str:head = []summaries = [row for row in messages if is_summary(row, prefixes)]if summaries:+ # The start and the end: "## Key facts", "## Next step", and the newest copies are at the end.head.append("[earlier summary]\n" + _bound(_summary_text(summaries[-1], prefixes), EARLIER_SUMMARY_CHARS,- EARLIER_SUMMARY_TOKENS))+ EARLIER_SUMMARY_TOKENS, middle=True))first = next((row for row in messages if is_real_user(row, prefixes)), None)if first is not None:head.append("[first user message]\n" + _bound(visible_text(api_content(first)).strip(), FIRST_USER_CHARS,diff --git a/warm_compaction/layout.py b/warm_compaction/layout.pyindex de2e08f..2d6cb11 100644--- a/warm_compaction/layout.py+++ b/warm_compaction/layout.py@@ -7,7 +7,7 @@ import functoolsfrom typing import Any, Iterablefrom .handoff import END_MARKER, LEGACY_PREFIX-from .rows import attr, estimate_tokens, hermes_value, plain_text, visible_text+from .rows import api_content, attr, estimate_tokens, hermes_value, plain_text, visible_textHEADER_TEXT = "The summary of the earlier turns follows."COPY_HEADING = "## Copied user messages"@@ -143,15 +143,16 @@ def tail_start(messages: list, tail_tokens: int, prefixes: Iterable[str]) -> tupdef copied_user_messages(messages: list, total_chars: int, prefixes: Iterable[str],max_tokens: int | None = None) -> list[str]:"""Return the newest real user messages that fit in total_chars and in max_tokens (estimated), each cut- to COPY_EACH characters. The token limit keeps dense text, such as CJK text, inside the window."""+ to COPY_EACH characters. Each copy is the text that Hermes sent (api_content when the row has it). The token+ limit counts the quoted form and keeps dense text, such as CJK text, inside the window."""prefixes = tuple(prefixes)chosen: list[str] = []used = tokens = 0for row in reversed(messages):if not is_real_user(row, prefixes):continue- text = visible_text(row.get("content")).strip()[:COPY_EACH]- cost = estimate_tokens(text)+ text = visible_text(api_content(row)).strip()[:COPY_EACH]+ cost = estimate_tokens(quote(text))if used + len(text) > total_chars or (max_tokens is not None and tokens + cost > max_tokens):breakchosen.append(text)diff --git a/warm_compaction/warm.py b/warm_compaction/warm.pyindex 29ade5b..40a5643 100644--- a/warm_compaction/warm.py+++ b/warm_compaction/warm.py@@ -81,20 +81,16 @@ def _shape(row: Any) -> tuple:return attr(row, "role"), attr(row, "tool_call_id") or None, calls-def _words(text: str) -> str:- return " ".join(text.split())--def _is_text(part: Any) -> bool:return isinstance(part, str) or (isinstance(part, dict) and part.get("type", "text") == "text" and isinstance(part.get("text"), str))def _parts(content: Any) -> tuple[list[str], list]:- """Return the text runs between the non-text parts (as words) and the non-text parts, in order. A message- with n image, audio, or file parts has n + 1 text runs."""+ """Return the text runs between the non-text parts and the non-text parts, in order. A message with n image,+ audio, or file parts has n + 1 text runs. White space stays: it can change code, tables, or commands."""if not isinstance(content, list):- return [_words(plain_text(content))], []+ return [plain_text(content)], []runs: list[str] = []media: list = []current: list[str] = []@@ -102,10 +98,10 @@ def _parts(content: Any) -> tuple[list[str], list]:if _is_text(part):current.append(part if isinstance(part, str) else part["text"])else:- runs.append(_words(" ".join(current)))+ runs.append("\n".join(current))media.append(part)current = []- runs.append(_words(" ".join(current)))+ runs.append("\n".join(current))return runs, media@@ -131,7 +127,8 @@ def _same_row(wire: Any, row: Any) -> bool:return Falsesent_runs, sent_media = _parts(attr(wire, "content"))stored_runs, stored_media = _parts(api_content(row))- if sent_media != stored_media or not all(stored in sent for stored, sent in zip(stored_runs, sent_runs)):+ if sent_media != stored_media or not all(+ stored.strip() in sent for stored, sent in zip(stored_runs, sent_runs)):return Falsereturn [_arguments(arguments) for _id, _name, arguments in tool_calls_of(wire)] == [_arguments(arguments) for _id, _name, arguments in tool_calls_of(row)]