Skip to content

Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix

Refuse repeated headings, bound the fallback extras, and cut the last copy to fit

Elevatormusic6f05c309cecc
diff --git a/README.md b/README.md
index 4537919..04c75c4 100644
--- a/README.md
+++ b/README.md
@@ -116,7 +116,7 @@ The warm request sends the whole earlier request again, plus the new rows and th
## Fallback model and keys
-The fallback summary uses the auxiliary task `warm_compaction`. Set `auxiliary.warm_compaction.provider` and `auxiliary.warm_compaction.model` to use a different model. The default `auto` uses the main model route. The fallback request is at most about 11,000 tokens: a transcript of about 8,000 tokens, the instruction, and a 2,048-token reply. A fallback model needs a context window of at least 16,000 tokens. Hermes accepts main models with 64,000 tokens or more, so the default route has enough space.
+The fallback summary uses the auxiliary task `warm_compaction`. Set `auxiliary.warm_compaction.provider` and `auxiliary.warm_compaction.model` to use a different model. The default `auto` uses the main model route. The fallback request is at most about 11,000 tokens: a transcript of about 8,000 tokens, the instruction, and a 2,048-token reply. The focus topic and the memory context are cut to about 1,000 tokens and take their size from the transcript. A fallback model needs a context window of at least 16,000 tokens. Hermes accepts main models with 64,000 tokens or more, so the default route has enough space.
For a custom endpoint that needs a key, put the key name in the model settings:
diff --git a/evidence/plugin-integration.json b/evidence/plugin-integration.json
index e3a24e3..d208268 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-06T09:47:38Z",
+ "started_utc": "2026-10-06T10:05:44Z",
"hermes": {
"commit": "45871e100feceb89769536c88e5e6e265226a409",
"clean": true
@@ -11,9 +11,9 @@
"warm_compaction/__init__.py": "11e038f05813627b2d1d8b82b3b775ecfe41015746c8e90ed6d452cfdaec65a6",
"warm_compaction/capture.py": "9f195ff31821b1dfc486373b074b799f4bc8750b07d10b53073374f760b2f2eb",
"warm_compaction/engine.py": "dfa9d6fb060d4d7665f0467630086ecfd076742e097258415c47bb5084134888",
- "warm_compaction/fallback.py": "b5ccd56550381fc8033351156cbf2dcf0a7e667f8f9bbf0d15bb2101f3abb97e",
- "warm_compaction/handoff.py": "a88b580a909ea832b53d6e2be58fa213ce621bd486df7a43d0b835ac9ccb8563",
- "warm_compaction/layout.py": "84673bd98710416599b3718071dcc24e0c230e4845cdbffb47fd743b2a21f423",
+ "warm_compaction/fallback.py": "fe6bfbd18359b84a9ebc0519b73a865fa5736a62f87e06f83535968b49317972",
+ "warm_compaction/handoff.py": "3ce85d76fce4afbefec0d9c2e91b100e09ac677a28e50ea749f4d25533d68c7e",
+ "warm_compaction/layout.py": "5e730211647eed0beec1e6819dfc008b0855a0866dc920bb0cf8d6d8ab2dfa92",
"warm_compaction/plugin.yaml": "d67560fd4625ec80d9e26f3e6d712763e77474f68d469c7e48f09fd3506ccc71",
"warm_compaction/rows.py": "cc2a8a3d0561559f24fc40881453441d938ea9d7803e1df81a107a5e05e5f00a",
"warm_compaction/warm.py": "b429103b13301e2eb82fb9c7bae422d28be5049114e27d71c5586762856b8c03"
@@ -75,11 +75,11 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.094,
+ "compress_seconds": 0.097,
"warm_last": {
"path": "warm",
"reason": "accepted",
- "elapsed_s": 0.018,
+ "elapsed_s": 0.022,
"prompt_tokens": 33883,
"cached_tokens": 16941
},
@@ -188,7 +188,7 @@
"install",
"run"
],
- "process_seconds": 54.245
+ "process_seconds": 57.137
},
{
"scenario": "manual_fallback",
@@ -247,11 +247,11 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.217,
+ "compress_seconds": 0.228,
"warm_last": {
"path": "fallback",
"reason": "provider_error",
- "elapsed_s": 0.094,
+ "elapsed_s": 0.093,
"prompt_tokens": null,
"cached_tokens": null
},
@@ -360,7 +360,7 @@
"install",
"run"
],
- "process_seconds": 32.083
+ "process_seconds": 33.072
},
{
"scenario": "manual_fixed",
@@ -418,11 +418,11 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.235,
+ "compress_seconds": 0.234,
"warm_last": {
"path": "fixed",
"reason": "provider_error",
- "elapsed_s": 0.11,
+ "elapsed_s": 0.094,
"prompt_tokens": null,
"cached_tokens": null
},
@@ -531,7 +531,7 @@
"install",
"run"
],
- "process_seconds": 29.805
+ "process_seconds": 29.807
},
{
"scenario": "auto_tool_loop",
@@ -625,8 +625,8 @@
"path": "warm",
"reason": "accepted",
"elapsed_s": 0.0,
- "prompt_tokens": 18206,
- "cached_tokens": 9103
+ "prompt_tokens": 18427,
+ "cached_tokens": 9213
},
"compression_count": 2,
"fence_denied": {
@@ -734,7 +734,7 @@
"install",
"run"
],
- "process_seconds": 33.575
+ "process_seconds": 32.601
},
{
"scenario": "rollback",
@@ -784,11 +784,11 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.257,
+ "compress_seconds": 0.155,
"warm_last": {
"path": "warm",
"reason": "accepted",
- "elapsed_s": 0.016,
+ "elapsed_s": 0.0,
"prompt_tokens": 33873,
"cached_tokens": 16936
},
@@ -929,7 +929,7 @@
{
"role": "assistant",
"summary_flag": null,
- "chars": 23524
+ "chars": 24406
},
{
"role": "user",
@@ -970,10 +970,10 @@
"run",
"rollback"
],
- "process_seconds": 37.135
+ "process_seconds": 39.1
}
],
- "finished_utc": "2026-10-06T09:50:45Z",
+ "finished_utc": "2026-10-06T10:08:56Z",
"passed": true,
"run_folder": "outside repository"
}
diff --git a/tests/test_wc_fallback.py b/tests/test_wc_fallback.py
index e08bdde..39e8d16 100644
--- a/tests/test_wc_fallback.py
+++ b/tests/test_wc_fallback.py
@@ -155,6 +155,20 @@ class LlmSummaryTest(unittest.TestCase):
self.assertIn("Give more detail to this topic: db", messages[0]["content"])
self.assertEqual(messages[1]["role"], "user")
+ def test_the_memory_context_counts_against_the_transcript_budget(self):
+ # A memory provider can give a very large context. The fallback request must stay inside its budget.
+ from warm_compaction.fallback import EXTRAS_CHARS
+ llm = FakeLlm()
+ rows = [user("first"), *[assistant(f"row {index} " + "x" * 3_500) for index in range(12)]]
+ llm_summary(llm, rows, PREFIXES, memory_context="m" * 200_000 + " the end")
+ messages, _kwargs = llm.calls[0]
+ extra = messages[0]["content"][len(FALLBACK_INSTRUCTION):]
+ self.assertLessEqual(len(extra), EXTRAS_CHARS)
+ self.assertTrue(extra.rstrip().endswith("the end"))
+ self.assertLessEqual(len(extra) + len(messages[1]["content"]), TRANSCRIPT_CHARS)
+ self.assertLessEqual(estimate_tokens(extra) + estimate_tokens(messages[1]["content"]),
+ TRANSCRIPT_TOKENS + 16)
+
def test_a_reply_that_reached_the_token_limit_is_refused(self):
# ctx.llm reports no finish reason. A reply at the max_tokens limit can be cut off.
long_summary = SUMMARY + "\n" + "- fact\n" * 1_000
diff --git a/tests/test_wc_handoff.py b/tests/test_wc_handoff.py
index 93cca6d..78be2d5 100644
--- a/tests/test_wc_handoff.py
+++ b/tests/test_wc_handoff.py
@@ -39,6 +39,8 @@ class HandoffTest(unittest.TestCase):
"heading_order": reply("## Next step\nx\n## Goal\ng\n## User instructions\n## Current state\n- s\n"
"## Key facts\n"),
"section_empty": reply("## Goal\n## User instructions\n## Current state\n## Key facts\n## Next step"),
+ "heading_repeated": reply("## Goal\n## Goal\n## User instructions\n## Current state\n## Current state\n"
+ "## Key facts\n## Next step\n## Next step"),
}
for expected, value in cases.items():
with self.subTest(expected=expected):
diff --git a/tests/test_wc_layout.py b/tests/test_wc_layout.py
index 26ae98b..bbe75f5 100644
--- a/tests/test_wc_layout.py
+++ b/tests/test_wc_layout.py
@@ -83,9 +83,25 @@ class CopyTest(unittest.TestCase):
# Six 4,000-character CJK messages are about 24,000 tokens. A 5,000-token budget keeps one.
rows = [user("\u4f60" * 4_000) for _ in range(6)]
self.assertEqual(len(copied_user_messages(rows, 24_000, PREFIXES)), 6)
- self.assertEqual(len(copied_user_messages(rows, 24_000, PREFIXES, max_tokens=5_000)), 1)
+ # The second copy is cut to the remaining 1,000 tokens or less.
+ copies = copied_user_messages(rows, 24_000, PREFIXES, max_tokens=5_000)
+ self.assertEqual(len(copies), 2)
+ self.assertLess(len(copies[0]), COPY_EACH)
+ # A remainder below MIN_COPY_CHARS characters gives no copy.
self.assertEqual(copied_user_messages(rows, 24_000, PREFIXES, max_tokens=100), [])
+ def test_a_message_larger_than_the_budget_is_cut_to_the_budget(self):
+ from warm_compaction.layout import MIN_COPY_CHARS, quote
+ from warm_compaction.rows import estimate_tokens
+ text = "start " + "x" * 2_000 + " the real question"
+ [copy] = copied_user_messages([user(text)], 1_000, PREFIXES)
+ self.assertEqual(len(copy), 1_000)
+ self.assertTrue(copy.startswith("start ") and copy.endswith(" the real question"))
+ [copy] = copied_user_messages([user(text)], 24_000, PREFIXES, max_tokens=150)
+ self.assertLessEqual(estimate_tokens(quote(copy)), 150)
+ self.assertTrue(copy.endswith(" the real question"))
+ self.assertEqual(copied_user_messages([user(text)], MIN_COPY_CHARS - 1, PREFIXES), [])
+
class CopyFormTest(unittest.TestCase):
def test_copies_use_the_sent_api_content(self):
@@ -97,7 +113,10 @@ class CopyFormTest(unittest.TestCase):
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), [])
+ # The quote marks make the full copy too large: the copy is cut to fit.
+ [copy] = copied_user_messages(rows, 24_000, PREFIXES, max_tokens=estimate_tokens(text) + 10)
+ self.assertLess(len(copy), len(text.strip()))
+ self.assertLessEqual(estimate_tokens(quote(copy)), estimate_tokens(text) + 10)
quoted = estimate_tokens(quote(text.strip()))
self.assertEqual(len(copied_user_messages(rows, 24_000, PREFIXES, max_tokens=quoted)), 1)
diff --git a/warm_compaction/fallback.py b/warm_compaction/fallback.py
index 7a83fb3..2959577 100644
--- a/warm_compaction/fallback.py
+++ b/warm_compaction/fallback.py
@@ -33,6 +33,10 @@ TRANSCRIPT_TOKENS = TRANSCRIPT_CHARS // 4
EARLIER_SUMMARY_TOKENS = EARLIER_SUMMARY_CHARS // 4
FIRST_USER_TOKENS = FIRST_USER_CHARS // 4
ROW_TOKENS = ROW_CHARS // 4
+# The focus topic and the memory context. They come from the host and can be large; they take their size from
+# the transcript budget, so the request stays the same size.
+EXTRAS_CHARS = 4_000
+EXTRAS_TOKENS = EXTRAS_CHARS // 4
MARK_TOKENS = 8
FALLBACK_INSTRUCTION = """\
@@ -115,11 +119,12 @@ def render_row(row: Any, call_names: dict[str, str] | None = None) -> str:
return "\n".join(lines)
-def transcript(messages: list, prefixes: Iterable[str]) -> str:
+def transcript(messages: list, prefixes: Iterable[str], reserve_chars: int = 0, reserve_tokens: int = 0) -> str:
"""Return a bounded transcript: the earlier summary, the first user message, then the newest rows.
Each row entry keeps at most ROW_CHARS characters (its start and its end), so that one long row cannot
push all earlier turns out. The oldest row that does not fit in the remaining budget is cut to fit.
+ reserve_chars and reserve_tokens are taken from the budget for other text in the same request.
"""
prefixes = tuple(prefixes)
head = []
@@ -133,8 +138,8 @@ def transcript(messages: list, prefixes: Iterable[str]) -> str:
# The start and the end: a long request often has the question or the output rules at the end.
head.append("[first user message]\n" + _bound(visible_text(api_content(first)).strip(), FIRST_USER_CHARS,
FIRST_USER_TOKENS, middle=True))
- budget = TRANSCRIPT_CHARS - sum(len(part) + 2 for part in head)
- tokens = TRANSCRIPT_TOKENS - sum(estimate_tokens(part) + 1 for part in head)
+ budget = TRANSCRIPT_CHARS - reserve_chars - sum(len(part) + 2 for part in head)
+ tokens = TRANSCRIPT_TOKENS - reserve_tokens - sum(estimate_tokens(part) + 1 for part in head)
# A tool row takes the names of the nearest earlier tool calls. Providers can use the same call id again
# in a later turn.
turn_names: list[dict[str, str]] = []
@@ -177,9 +182,11 @@ def llm_summary(llm: Any, messages: list, prefixes: Iterable[str], *, focus_topi
if llm is None:
return None, None
prefixes = tuple(prefixes)
+ # The start (the focus line) and the end of a large memory context.
+ extra = _bound(extras(focus_topic, memory_context), EXTRAS_CHARS, EXTRAS_TOKENS, middle=True)
request = [
- {"role": "system", "content": FALLBACK_INSTRUCTION + extras(focus_topic, memory_context)},
- {"role": "user", "content": transcript(messages, prefixes)},
+ {"role": "system", "content": FALLBACK_INSTRUCTION + extra},
+ {"role": "user", "content": transcript(messages, prefixes, len(extra), estimate_tokens(extra))},
]
try:
result = llm.complete(request, task=task, max_tokens=MAX_TOKENS, timeout=timeout_s, purpose=PURPOSE)
diff --git a/warm_compaction/handoff.py b/warm_compaction/handoff.py
index fb15adb..b576ef4 100644
--- a/warm_compaction/handoff.py
+++ b/warm_compaction/handoff.py
@@ -87,6 +87,9 @@ def gate(reply: dict[str, Any], summary_prefixes: Iterable[str] = ()) -> tuple[s
lines = [line.strip() for line in text.splitlines()]
if any(heading not in lines for heading in HEADINGS):
return None, "heading_missing"
+ # A repeated heading is not section text: "## Goal" twice must not count as a goal.
+ if any(lines.count(heading) > 1 for heading in HEADINGS):
+ return None, "heading_repeated"
starts = [lines.index(heading) for heading in HEADINGS]
if starts != sorted(starts):
return None, "heading_order"
diff --git a/warm_compaction/layout.py b/warm_compaction/layout.py
index 477e5cd..a8925b7 100644
--- a/warm_compaction/layout.py
+++ b/warm_compaction/layout.py
@@ -12,6 +12,7 @@ from .rows import api_content, attr, cut_middle, estimate_tokens, hermes_value,
HEADER_TEXT = "The summary of the earlier turns follows."
COPY_HEADING = "## Copied user messages"
COPY_EACH = 4_000
+MIN_COPY_CHARS = 200
NO_COPIES = "(none)"
STEER_KIND = "steer"
SYNTHETIC_FLAGS = ("_dropped_toolcall_nudge",)
@@ -143,9 +144,9 @@ def tail_start(messages: list, tail_tokens: int, prefixes: Iterable[str]) -> tup
def 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 (its start and its end). 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."""
+ to COPY_EACH characters (its start and its end). The oldest copy that does not fit is cut to the remaining
+ budget. 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 = 0
@@ -155,6 +156,9 @@ def copied_user_messages(messages: list, total_chars: int, prefixes: Iterable[st
text = cut_middle(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):
+ part = _fit_copy(text, total_chars - used, None if max_tokens is None else max_tokens - tokens)
+ if part is not None:
+ chosen.append(part)
break
chosen.append(text)
used += len(text)
@@ -163,6 +167,19 @@ def copied_user_messages(messages: list, total_chars: int, prefixes: Iterable[st
return chosen
+def _fit_copy(text: str, chars: int, tokens: int | None) -> str | None:
+ """Return the start and the end of the text in at most chars characters and, in the quoted form, at most
+ tokens estimated tokens. Return None when less than MIN_COPY_CHARS characters fit."""
+ limit = min(len(text), chars)
+ while limit >= MIN_COPY_CHARS:
+ part = cut_middle(text, limit)
+ cost = estimate_tokens(quote(part))
+ if tokens is None or cost <= tokens:
+ return part
+ limit = min(limit - 1, limit * tokens // cost)
+ return None
+
+
def quote(text: str) -> str:
"""Return the text as a Markdown block quote."""
return "\n".join(">" + (" " + line if line else "") for line in text.splitlines()) or ">"