Skip to content

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

Retry the fallback summary twice and repeat the marker requirement

pableras391cc57da374
diff --git a/README.md b/README.md
index ddc5530..ccf177d 100644
--- a/README.md
+++ b/README.md
@@ -206,7 +206,7 @@ The complete body still has at most 2,048 estimated tokens. The original reply m
Each request gets a fresh random end marker, in the form `[END OF SUMMARY <nonce>]`. The reply must contain that exact marker once, as its final visible line. The plugin removes the marker before it stores the summary. A fixed marker, an old marker, text after the marker, or a missing marker fails the check. This checks the reply format. It does not prove that every fact is correct or tell the plugin why the server stopped; the public auxiliary API does not report a finish reason.
-If a reply fails the checks, the plugin can retry once. It uses the same original transcript, a fresh marker, and a shorter summary instruction of at most 300 words. It does not try to complete a partial reply. Both calls share a 120-second deadline. The plugin checks cancellation and route changes before each call and after each reply. It does not retry a request error. If no reply passes, it preserves the input history.
+If a reply fails the checks, the plugin can retry twice. Each retry uses the same original transcript, a fresh marker, and a shorter summary instruction of at most 300 words. When the failure is a missing or duplicated end marker, the retry repeats the marker requirement explicitly. It does not try to complete a partial reply. All calls share a 120-second deadline. The plugin checks cancellation and route changes before each call and after each reply. It does not retry a request error. If no reply passes, it preserves the input history.
When the server applies the requested generation limit, the request is about 18,000 tokens or less: about 8,000 transcript tokens, the instruction, and up to 8,192 generated tokens. The focus topic and memory context take their space from the transcript budget. Use a fallback model with at least a 24,000-token context window. The deadline can prevent a retry or reject a late reply, but the public API cannot stop an in-flight call. Hermes controls its own retries, so two plugin calls can cause more than two server requests.
diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.py
index aa0c7cc..2b8fa79 100644
--- a/tests/test_wc_engine.py
+++ b/tests/test_wc_engine.py
@@ -1751,13 +1751,13 @@ class EngineTest(unittest.TestCase):
self.assertNotIn(state, summary)
self.assertEqual(len(self.llm.calls), 1)
- def test_invalid_fallback_protocol_keeps_history_after_two_calls(self):
+ def test_invalid_fallback_protocol_keeps_history_after_three_calls(self):
state = json.dumps("synthetic unsupported state")
self.llm = FakeLlm(text=HEADINGS_TEXT.replace("- [OPEN] Write the report.", "- " + state))
engine = self.make(warm=False)
history = [user("Check PKG-17 progress."), *old_turns(), assistant("synthetic final reply")]
self.assert_aborted(engine, history, "gate:missing_end_marker")
- self.assertEqual(len(self.llm.calls), 2)
+ self.assertEqual(len(self.llm.calls), 3)
def test_fallback_refusal_status_has_safe_counts_and_marker_code(self):
# These replies and counts are synthetic. History must stay unchanged.
@@ -1780,13 +1780,13 @@ class EngineTest(unittest.TestCase):
self.assertEqual(status["fallback_output_tokens"], expected_output)
self.assertEqual(status["fallback_requested_max_tokens"], 8192)
self.assertEqual(status["fallback_end_marker"], marker)
- self.assertEqual(status["fallback_attempts"], 2)
+ self.assertEqual(status["fallback_attempts"], 3)
self.assertEqual(status["fallback_body_tokens"], estimate_tokens(text.removesuffix("\n" + END_LINE)))
logged = "\n".join(logs.output)
self.assertIn(f"fallback_output_tokens={expected_output}", logged)
self.assertIn("fallback_requested_max_tokens=8192", logged)
self.assertIn(f"fallback_end_marker={marker}", logged)
- self.assertIn("fallback_attempts=2", logged)
+ self.assertIn("fallback_attempts=3", logged)
self.assertNotIn(HEADINGS_TEXT, logged + json.dumps(status))
def test_late_backup_errors_after_cancel_or_route_switch_keep_history(self):
@@ -2196,12 +2196,12 @@ class EngineTest(unittest.TestCase):
provider="custom", api_mode=ROUTE[2])
self.assert_aborted(engine, rows, "error:RuntimeError")
- def test_two_all_unknown_replies_preserve_history(self):
+ def test_three_all_unknown_replies_preserve_history(self):
self.llm = FakeLlm(FALLBACK_TEXT + "\n" + END_LINE)
engine = self.engine = self.make(warm=False, tail_tokens=10)
rows = [*old_turns(4), user("Check JOB-X3."), assistant("done")]
self.assert_aborted(engine, rows, "gate:no_useful_evidence")
- self.assertEqual(len(self.llm.calls), 2)
+ self.assertEqual(len(self.llm.calls), 3)
def test_failed_summary_keeps_the_middles_that_the_tail_would_cut(self):
self.llm.error = RuntimeError("synthetic failure")
diff --git a/tests/test_wc_fallback.py b/tests/test_wc_fallback.py
index 9cb369c..1263b3f 100644
--- a/tests/test_wc_fallback.py
+++ b/tests/test_wc_fallback.py
@@ -229,10 +229,31 @@ class LlmSummaryTest(unittest.TestCase):
failure = {}
self.assertEqual(llm_summary(llm, [user("hi")], PREFIXES, failure=failure), (None, None))
self.assertEqual(failure["reason"], "gate:" + reason)
- self.assertEqual(failure["attempts"], 2)
- self.assertEqual(len(llm.calls), 2)
+ self.assertEqual(failure["attempts"], 3)
+ self.assertEqual(len(llm.calls), 3)
self.assertNotIn(self.marker(llm.calls[-1][0]), str(logs.output) + str(failure))
+ def test_missing_marker_retry_repeats_the_marker_requirement(self):
+ def reply(messages, kwargs, count):
+ body = useful_summary("hi")
+ return body if count == 1 else body + "\n" + self.marker(messages)
+ llm, failure = FakeLlm(text=reply), {}
+ self.assertEqual(llm_summary(llm, [user("hi")], PREFIXES, failure=failure), (useful_summary("hi"), 321))
+ self.assertEqual(len(llm.calls), 2)
+ first, second = llm.calls
+ self.assertNotIn("did not end with the marker line", first[0][0]["content"])
+ self.assertIn("did not end with the marker line", second[0][0]["content"])
+ self.assertEqual(failure, {})
+
+ def test_third_attempt_passes_after_two_missing_markers(self):
+ def reply(messages, kwargs, count):
+ body = useful_summary("hi")
+ return body + ("\n" + self.marker(messages) if count == 3 else "")
+ llm, failure = FakeLlm(text=reply), {}
+ self.assertEqual(llm_summary(llm, [user("hi")], PREFIXES, failure=failure), (useful_summary("hi"), 321))
+ self.assertEqual(len(llm.calls), 3)
+ self.assertEqual(failure, {})
+
def test_thinking_is_removed_before_the_content_and_body_checks(self):
body = useful_summary("hi")
llm = FakeLlm(text="<think>" + "private-plan" * 4_000 + "</think>\n" + body + "\n" + END_LINE + "\n")
@@ -248,7 +269,7 @@ class LlmSummaryTest(unittest.TestCase):
self.assertEqual(llm_summary(llm, [user("hi")], PREFIXES, failure=failure), (None, None))
self.assertEqual(failure["reason"], "gate:body_token_limit")
self.assertGreater(failure["body_tokens"], MAX_TOKENS)
- self.assertEqual(len(llm.calls), 2)
+ self.assertEqual(len(llm.calls), 3)
def test_content_checks_stay_in_force(self):
for text, reason in (("answer", "heading_missing"), (SUMMARY + "\n[CONTEXT SUMMARY]: x", "carrier_marker"),
@@ -269,7 +290,7 @@ class LlmSummaryTest(unittest.TestCase):
safe_output = output if type(output) is int and 0 < output <= 2 ** 63 - 1 else None
self.assertEqual(failure, {"reason": "gate:missing_end_marker", "output_tokens": safe_output,
"requested_max_tokens": REQUEST_MAX_TOKENS, "end_marker": "missing",
- "attempts": 2, "body_tokens": estimate_tokens(SUMMARY + "\n" + private)})
+ "attempts": 3, "body_tokens": estimate_tokens(SUMMARY + "\n" + private)})
logged = "\n".join(logs.output)
self.assertNotIn(private, logged + str(failure))
self.assertNotIn(SUMMARY, logged + str(failure))
@@ -436,7 +457,7 @@ class CurrentStateSourceTest(unittest.TestCase):
if expected == "- progress unknown":
self.assertEqual(result, (None, None))
self.assertEqual(failure["reason"], "gate:no_useful_evidence")
- self.assertEqual(len(llm.calls), 2)
+ self.assertEqual(len(llm.calls), 3)
else:
self.assertEqual(result, (body, 321))
self.assertEqual(failure, {})
@@ -598,7 +619,7 @@ class CurrentStateSourceTest(unittest.TestCase):
llm, failure = FakeLlm(text=body + "\n" + END_LINE), {}
self.assertEqual(llm_summary(llm, [user("Check progress.")], PREFIXES, failure=failure), (None, None))
self.assertEqual(failure["reason"], "gate:body_token_limit")
- self.assertEqual(len(llm.calls), 2)
+ self.assertEqual(len(llm.calls), 3)
def test_an_actual_protocol_failure_retries_with_the_same_source(self):
reported = "not complete"
@@ -693,7 +714,7 @@ class AllFieldsSourceTest(unittest.TestCase):
raw = field_summary("## Next step", '- "Review JOB-X3 after approval."\nDo not perform it yet.')
llm = FakeLlm(raw + "\n" + END_LINE)
self.assertEqual(llm_summary(llm, [user("Review JOB-X3.")], PREFIXES), (None, None))
- self.assertEqual(len(llm.calls), 2)
+ self.assertEqual(len(llm.calls), 3)
def test_next_step_keeps_supported_action_and_records_lost_tail_condition(self):
raw = field_summary("## Next step", '- "Review JOB-X3."\nDo not perform it yet.')
@@ -818,7 +839,7 @@ class SourceContextTest(unittest.TestCase):
llm = FakeLlm(raw + "\n" + END_LINE)
self.assertEqual(llm_summary(llm, [assistant(prior, _compressed_summary=True), row], PREFIXES),
(None, None))
- self.assertEqual(len(llm.calls), 2)
+ self.assertEqual(len(llm.calls), 3)
def test_bounded_context_keeps_tail_fact_but_drops_missing_middle(self):
from warm_compaction.fallback import EXTRAS_CHARS, EXTRAS_TOKENS, _bound
@@ -844,7 +865,7 @@ class SourceContextTest(unittest.TestCase):
llm = FakeLlm(raw + "\n" + END_LINE)
self.assertEqual(llm_summary(llm, [user("Check memory.")], PREFIXES, memory_context=memory), (None, None))
self.assertIn("[cut]", llm.calls[0][0][0]["content"])
- self.assertEqual(len(llm.calls), 2)
+ self.assertEqual(len(llm.calls), 3)
def test_context_and_transcript_do_not_make_new_source_adjacency(self):
quoted = "Transcript report.\nMemory report."
@@ -889,12 +910,13 @@ class SourceContextTest(unittest.TestCase):
class UsefulEvidenceTest(unittest.TestCase):
- def test_all_unknown_uses_one_retry_then_refuses_without_provider_text(self):
+ def test_all_unknown_retries_then_refuses_without_provider_text(self):
llm, failure = FakeLlm(SUMMARY + "\n" + END_LINE), {}
self.assertEqual(llm_summary(llm, [user("Check JOB-X3.")], PREFIXES, failure=failure), (None, None))
- self.assertEqual(len(llm.calls), 2)
+ self.assertEqual(len(llm.calls), 3)
self.assertEqual(failure["reason"], "gate:no_useful_evidence")
- self.assertEqual(failure["attempts"], 2)
+ self.assertEqual(failure["attempts"], 3)
+ self.assertIn("failed a summary check", llm.calls[2][0][0]["content"])
self.assertNotIn("Check JOB-X3.", str(failure))
def test_generated_labels_alone_do_not_count_as_useful_evidence(self):
@@ -905,7 +927,7 @@ class UsefulEvidenceTest(unittest.TestCase):
llm, failure = FakeLlm(body + "\n" + END_LINE), {}
self.assertEqual(llm_summary(llm, rows, PREFIXES, failure=failure), (None, None))
self.assertEqual(failure["reason"], "gate:no_useful_evidence")
- self.assertEqual(len(llm.calls), 2)
+ self.assertEqual(len(llm.calls), 3)
def test_copied_appendix_cannot_cut_a_core_fact_that_fits_the_existing_share(self):
fact = "JOB-X3 output is 28 V."
@@ -938,7 +960,7 @@ class UsefulEvidenceTest(unittest.TestCase):
self.assertEqual(llm_summary(llm, [assistant("", [("c1", "read", "")])], PREFIXES, failure=failure),
(None, None))
self.assertEqual(failure["reason"], "gate:no_useful_evidence")
- self.assertEqual(len(llm.calls), 2)
+ self.assertEqual(len(llm.calls), 3)
self.assertEqual(llm_summary(FakeLlm(body + "\n" + END_LINE), [user(label)], PREFIXES), (body, 321))
def test_nonempty_supplied_tool_argument_can_supply_evidence(self):
@@ -1117,7 +1139,7 @@ class PriorStateTest(unittest.TestCase):
llm = FakeLlm(raw + "\n" + END_LINE)
self.assertEqual(llm_summary(llm, [assistant(prior, _compressed_summary=True), user(wrapper)], PREFIXES),
(None, None))
- self.assertEqual(len(llm.calls), 2)
+ self.assertEqual(len(llm.calls), 3)
def test_no_one_layer_decode_from_arbitrary_user_or_tool_rows(self):
prior = state_summary('- "Task not complete."')
@@ -1171,7 +1193,7 @@ class PriorStateTest(unittest.TestCase):
llm, failure = FakeLlm(raw + "\n" + END_LINE), {}
self.assertEqual(llm_summary(llm, [assistant(reported)], PREFIXES, failure=failure), (None, None))
self.assertEqual(failure["reason"], "gate:" + reason)
- self.assertEqual(len(llm.calls), 2)
+ self.assertEqual(len(llm.calls), 3)
def test_lone_surrogate_in_expanded_source_is_stored_as_json_escape(self):
reported = "Task not complete \ud800."
diff --git a/warm_compaction/fallback.py b/warm_compaction/fallback.py
index 774d323..5654e99 100644
--- a/warm_compaction/fallback.py
+++ b/warm_compaction/fallback.py
@@ -27,6 +27,8 @@ PURPOSE = "warm_compaction_fallback"
MAX_TOKENS = 2048
MAX_STATE_TOKENS = 512
REQUEST_MAX_TOKENS = 8192
+# The attempts of one fallback summary: the first reply plus up to two retries of an invalid reply.
+MAX_ATTEMPTS = 3
TIMEOUT_S = 120.0
TRANSCRIPT_CHARS = 32_000
EARLIER_SUMMARY_CHARS = 8_000
@@ -568,7 +570,7 @@ def llm_summary(llm: Any, messages: list, prefixes: Iterable[str], *, focus_topi
failure: dict[str, Any] | None = None) -> tuple[str | None, int | None]:
"""Return (summary text, prompt tokens) from ctx.llm, or (None, None) when the request or the reply fails.
ready checks the route and cancellation before each call and after each reply.
- Only an invalid reply gets one retry. Both calls share one time limit.
+ An invalid reply gets up to two retries. All calls share one time limit.
failure gets safe codes and bounded reply metadata only. It never gets provider text."""
if failure is not None:
failure.clear()
@@ -583,13 +585,23 @@ def llm_summary(llm: Any, messages: list, prefixes: Iterable[str], *, focus_topi
content: list[str] = []
original = transcript(messages, prefixes, len(extra), estimate_tokens(extra), _content=content)
source = _SourceTable(original, _earlier_summary(messages, prefixes), extra, content)
- for attempt in range(1, 3):
+ reason: str | None = None # The previous attempt's failure code; the loop only continues on one.
+ for attempt in range(1, MAX_ATTEMPTS + 1):
end_line = END_LINE.replace("{nonce}", secrets.token_hex(16))
words = int(summary_words) if attempt == 1 else min(int(summary_words), 300)
instruction = FALLBACK_INSTRUCTION_TEMPLATE.replace(SUMMARY_WORDS_TOKEN, str(words))
instruction = instruction.replace(END_LINE, end_line)
- if attempt == 2:
- extra_instruction = "\nThe previous reply failed a summary check. Write a shorter, complete summary.\n"
+ if attempt > 1:
+ # The dominant failure of a local model is the missing marker line; repeat that requirement
+ # instead of the generic shorter-summary note. reason is the last attempt's failure code.
+ if reason in ("missing_end_marker", "duplicate_end_marker"):
+ extra_instruction = ("\nThe previous reply did not end with the marker line. Write the "
+ "summary again. The marker line below must be the final line of "
+ "your reply, with nothing after it.\n")
+ else:
+ extra_instruction = ("\nThe previous reply failed a summary check. Write a shorter, "
+ "complete summary. The marker line below must be the final line "
+ "of your reply, with nothing after it.\n")
else:
extra_instruction = ""
instruction = instruction.replace("End the summary with this line:",
@@ -648,7 +660,7 @@ def llm_summary(llm: Any, messages: list, prefixes: Iterable[str], *, focus_topi
if text is not None:
tokens = getattr(getattr(result, "usage", None), "input_tokens", None)
return text, tokens if isinstance(tokens, int) and not isinstance(tokens, bool) and tokens > 0 else None
- if attempt == 2:
+ if attempt == MAX_ATTEMPTS:
metadata = _reply_metadata(result, raw, end_line, body, attempt)
if failure is not None:
failure["reason"] = f"gate:{reason}"