Skip to content

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

Skip background-review fork requests in the capture store (#41)

gasb95952763305
diff --git a/scripts/check_hermes_compatibility.py b/scripts/check_hermes_compatibility.py
index 2a20b02..2973dd1 100644
--- a/scripts/check_hermes_compatibility.py
+++ b/scripts/check_hermes_compatibility.py
@@ -20,7 +20,7 @@ import tempfile
from types import SimpleNamespace
ROOT = Path(__file__).resolve().parents[1]
-CASES = ("capture_last", "earlier_rewrite", "later_rewrite", "unknown_order")
+CASES = ("capture_last", "earlier_rewrite", "later_rewrite", "unknown_order", "fork_prompt_prefixes")
WORKER_TIMEOUT = 60
SOURCE_MARKERS = ("hermes_cli/plugins.py", "hermes_cli/middleware.py", "agent/context_engine.py", "run_agent.py")
@@ -75,6 +75,32 @@ def worker_environment(home: Path) -> dict[str, str]:
return env
+def fork_prompt_prefix_case(source: Path) -> dict:
+ """Check the fork prompt prefixes against the real Hermes prompt texts of this checkout.
+
+ The capture filter falls back to the prompt prefixes where the host passes no turn origin.
+ A reworded prompt would make the filter miss that fork type, so the check reads the prompt
+ constants from the checked-out source instead of from literals in the test suite.
+ """
+ try:
+ from agent import background_review, side_question
+ from warm_compaction.capture import REVIEW_PROMPT_PREFIX, SIDE_QUESTION_PROMPT_PREFIX
+ except ImportError as error:
+ raise ValueError("hermes_import_failed") from error
+ check_import_origins(source)
+ review_prompts = (background_review._SKILL_REVIEW_PROMPT, background_review._MEMORY_REVIEW_PROMPT,
+ background_review._COMBINED_REVIEW_PROMPT)
+ checks = {
+ "review_prompts_start_with_the_review_prefix": all(
+ type(prompt) is str and prompt.startswith(REVIEW_PROMPT_PREFIX) for prompt in review_prompts),
+ "side_question_prompt_starts_with_the_side_prefix": type(side_question._FORK_PROMPT) is str
+ and side_question._FORK_PROMPT.startswith(SIDE_QUESTION_PROMPT_PREFIX),
+ }
+ passed = all(checks.values())
+ return {"case": "fork_prompt_prefixes", "passed": passed, "checks": checks,
+ "error": None if passed else "contract_check_failed"}
+
+
def worker(source: Path, case: str) -> dict:
"""Use the real Hermes manager, registrations, hooks, and middleware chain."""
# Windows can use a system process for this standard-library value. Cache it before the fence.
@@ -85,6 +111,8 @@ def worker(source: Path, case: str) -> dict:
raise RuntimeError("external_operation_blocked")
sys.addaudithook(no_network)
sys.path[:0] = [str(ROOT), str(source)]
+ if case == "fork_prompt_prefixes":
+ return fork_prompt_prefix_case(source)
try:
from hermes_cli import plugins
from hermes_cli.middleware import apply_llm_request_middleware, run_llm_execution_middleware
diff --git a/tests/test_wc_capture.py b/tests/test_wc_capture.py
index a9363f5..61d732f 100644
--- a/tests/test_wc_capture.py
+++ b/tests/test_wc_capture.py
@@ -9,10 +9,22 @@ from types import SimpleNamespace
from unittest.mock import patch
import wc_hermes_stub
-from warm_compaction.capture import CaptureStore, UnsupportedRequest, final_body, key_stamp
+from warm_compaction.capture import (CaptureStore, FORK_TURN_ORIGINS, REVIEW_PROMPT_PREFIX,
+ SIDE_QUESTION_PROMPT_PREFIX, UnsupportedRequest, final_body, key_stamp)
from warm_compaction.rows import row_digest
from wc_fixtures import user
+# A copy of the current Hermes side-question fork prompt (agent/side_question.py:
+# _FORK_PROMPT), so the replacement test uses the real text. Drift from Hermes is caught by
+# the "fork_prompt_prefixes" case of scripts/check_hermes_compatibility.py, not by this unit test.
+_SIDE_QUESTION_PROMPT = (
+ "The user asked a quick SIDE question with /btw while the main work continues in the original "
+ "session.\nRules:\n- Answer ONLY the side question, using the conversation above as context. Do not continue, "
+ "redo, or critique the main task.\n- Do NOT call any tools — they are disabled for this side question. Answer "
+ "directly in text.\n- If the conversation does not contain enough information to answer, say so plainly instead "
+ "of guessing.\n- Be concise and direct."
+)
+
def request(**extra):
return {"model": "m", "messages": [{"role": "system", "content": "s"}, {"role": "user", "content": "u"}], **extra}
@@ -78,9 +90,11 @@ class CaptureStoreTest(unittest.TestCase):
self.history = [user("u")]
def run_request(self, request_id="r1", session="s1", api_mode="chat_completions", finish="stop",
- body=None, message=None, usage=None):
- self.store.on_pre_api_request(api_request_id=request_id, session_id=session, conversation_history=self.history,
- model="m", base_url="http://x/v1", api_mode=api_mode, request={"sanitized": 1})
+ body=None, message=None, usage=None, user_message=None, turn_origin=None, history=None):
+ self.store.on_pre_api_request(api_request_id=request_id, session_id=session,
+ conversation_history=history if history is not None else self.history,
+ model="m", base_url="http://x/v1", api_mode=api_mode, request={"sanitized": 1},
+ user_message=user_message, turn_origin=turn_origin)
calls = []
result = self.store.on_llm_execution(request=body if body is not None else request(),
next_call=lambda: calls.append(1) or "response", api_request_id=request_id,
@@ -139,6 +153,88 @@ class CaptureStoreTest(unittest.TestCase):
self.assertEqual(capture["reply"], {"role": "assistant", "content": "done", "tool_calls": []})
self.assertEqual((capture["finish_reason"], capture["captured_at"]), ("stop", 5.0))
+ def test_review_fork_request_is_not_captured(self):
+ self.run_request(user_message="Review the conversation above and consider saving to memory.")
+ self.assertIsNone(self.store.latest("s1"))
+
+ def test_review_fork_request_does_not_replace_a_live_capture(self):
+ # The real replacement case: a completed live capture already exists, and a same-session
+ # review fork request (same session id, shared for prefix warmth) runs through all three
+ # hooks with the live history plus the fork prompt row, its own body, and a later clock.
+ # The live capture must survive it unchanged. Without the fork filter the fork capture
+ # replaces the live one and differs in digests, body, and captured_at, so this fails.
+ review_prompt = "Review the conversation above and consider saving to memory."
+ self.run_request()
+ saved = self.store.latest("s1")
+ self.assertIsNotNone(saved)
+ fork_history = self.history + [user(review_prompt)]
+ self.store._clock = lambda: 6.0
+ result, calls = self.run_request(
+ request_id="r2", history=fork_history, user_message=review_prompt,
+ body=request(messages=[{"role": "system", "content": "s"}, {"role": "user", "content": review_prompt}]))
+ self.assertEqual((result, calls), ("response", [1]))
+ self.assertEqual(self.store.latest("s1"), saved)
+
+ def test_side_question_fork_request_is_not_captured(self):
+ self.run_request(user_message=(_SIDE_QUESTION_PROMPT
+ + "\n\nSide question: what time is it?"))
+ self.assertIsNone(self.store.latest("s1"))
+
+ def test_side_question_fork_request_does_not_replace_a_live_capture(self):
+ # The /btw hole: the side-question fork (agent/side_question.py) also shares the
+ # parent's session_id and model, so its request must not replace the live
+ # capture either (the next warm compaction would hit history_changed:digest).
+ # As with the review fork: the fork runs with the live history plus the fork
+ # prompt row, its own body, and a later clock, so the test fails without the
+ # fork filter.
+ side_prompt = _SIDE_QUESTION_PROMPT + "\n\nSide question: what time is it?"
+ self.run_request()
+ saved = self.store.latest("s1")
+ self.assertIsNotNone(saved)
+ fork_history = self.history + [user(side_prompt)]
+ self.store._clock = lambda: 6.0
+ result, calls = self.run_request(
+ request_id="r2", history=fork_history, user_message=side_prompt,
+ body=request(messages=[{"role": "system", "content": "s"}, {"role": "user", "content": side_prompt}]))
+ self.assertEqual((result, calls), ("response", [1]))
+ self.assertEqual(self.store.latest("s1"), saved)
+
+ def test_turn_origin_marks_a_fork_without_a_known_prefix(self):
+ # Where the host passes the turn's origin, it is the authoritative signal: a fork
+ # prompt Hermes reworded (no known prefix) is still recognised by its origin.
+ for origin in FORK_TURN_ORIGINS:
+ with self.subTest(origin=origin):
+ self.run_request(request_id=origin, turn_origin=origin,
+ user_message="an unrecognised fork prompt")
+ self.assertIsNone(self.store.latest("s1"))
+
+ def test_a_known_non_fork_turn_origin_is_trusted_over_the_prompt_check(self):
+ # The host identified the turn: a non-fork origin is authoritative, so a live
+ # turn whose text starts with a fork prefix is captured. The prompt-prefix
+ # check runs only where the host passes no origin.
+ self.run_request(request_id="r2", turn_origin="live",
+ user_message="Review the conversation above and tell me what we decided.")
+ capture = self.store.latest("s1")
+ self.assertIsNotNone(capture)
+ self.assertIsNone(capture["refusal"])
+
+ def test_fork_constants_keep_their_values(self):
+ # Guard the constants against an accidental edit. This test compares the constants
+ # with literals, so it cannot detect a Hermes reword; the Hermes compatibility
+ # job does that (case "fork_prompt_prefixes").
+ self.assertEqual(REVIEW_PROMPT_PREFIX, "Review the conversation above")
+ self.assertEqual(SIDE_QUESTION_PROMPT_PREFIX, "The user asked a quick SIDE question with /btw")
+ self.assertEqual(FORK_TURN_ORIGINS, ("background_review", "side_question"))
+
+ def test_review_prompt_in_history_still_captures_the_live_turn(self):
+ self.history = [user("Review the conversation above and consider saving to memory."),
+ user("continue the build")]
+ self.run_request(user_message="continue the build")
+ capture = self.store.latest("s1")
+ self.assertEqual(len(capture["digests"]), 2)
+ self.assertIsNone(capture["refusal"])
+ self.assertEqual(capture["body"]["messages"][1]["content"], "u")
+
def test_a_repeated_call_id_gets_the_hermes_rename(self):
# Hermes renames a repeated id in one reply (c1, c1 -> c1, c1_d2) after this hook runs.
self.run_request(finish="tool_calls", message=reply_object("", [("c1", "read"), ("c1", "ls"), ("c1", "cat")]))
diff --git a/warm_compaction/capture.py b/warm_compaction/capture.py
index d54700b..5abd390 100644
--- a/warm_compaction/capture.py
+++ b/warm_compaction/capture.py
@@ -19,6 +19,28 @@ MAX_SESSIONS = 16
CLIENT_OPTIONS = ("extra_body", "extra_headers", "extra_query", "timeout")
CAPTURE_FINISH = ("stop", "tool_calls")
REQUEST_REFUSALS = ("request_not_mapping", "request_options_unsupported", "request_not_json")
+# The user prompts of the Hermes detached-fork requests. A fork shares the parent's
+# session and model ("shared session_id for prefix warmth"), so a completed fork
+# request must not replace the live conversation's capture: the next warm compaction
+# would build on the fork's prefix and degrade to the fallback (history_changed:digest).
+#
+# Both fork types are built with build_cache_parity_fork: the background review
+# (agent/background_review.py, origin "background_review") and the /btw side question
+# (agent/side_question.py, origin "side_question").
+#
+# The prompt prefixes match the current Hermes prompt texts:
+# - background_review: _SKILL_REVIEW_PROMPT, _MEMORY_REVIEW_PROMPT and
+# _COMBINED_REVIEW_PROMPT all start with REVIEW_PROMPT_PREFIX;
+# - side_question: _FORK_PROMPT starts with SIDE_QUESTION_PROMPT_PREFIX.
+# If Hermes rewords a prompt, the matching below stops covering that fork type until the
+# prefix is updated. The "fork_prompt_prefixes" case of scripts/check_hermes_compatibility.py
+# reads the prompts from the Hermes checkout, so a reword fails CI. Where the host passes
+# the turn's origin to the pre_api_request hook, the origin is the authoritative signal:
+# a fork origin drops the request and a non-fork origin is trusted and captured. The
+# prefixes are the fallback only where the host passes no origin.
+REVIEW_PROMPT_PREFIX = "Review the conversation above"
+SIDE_QUESTION_PROMPT_PREFIX = "The user asked a quick SIDE question with /btw"
+FORK_TURN_ORIGINS = ("background_review", "side_question")
# A random salt for each plugin load: the stamps of one key differ between processes.
_KEY_STAMP_SECRET = secrets.token_bytes(32)
# PBKDF2 work for each stamp (about 3 ms): a stamp is made a few times for each main request.
@@ -35,6 +57,22 @@ class UnsupportedRequest(ValueError):
"""The request body cannot become a warm request. The message is the reason code."""
+def _is_fork_request(user_message: Any, turn_origin: Any = None) -> bool:
+ """True for a detached-fork request (background review, side question). The fork's
+ rows never enter the parent's stored conversation (Hermes severs the fork's
+ session binding), so the turn origin — or, where the host passes no origin, the
+ turn's user message — is the only check. A host-supplied origin is authoritative
+ in both directions: a fork origin drops the request, and a non-fork origin is
+ trusted, so a live turn whose text starts with a fork prefix is still captured."""
+ if turn_origin is not None:
+ return turn_origin in FORK_TURN_ORIGINS
+ try:
+ text = plain_text(user_message).lstrip()
+ return text.startswith(REVIEW_PROMPT_PREFIX) or text.startswith(SIDE_QUESTION_PROMPT_PREFIX)
+ except Exception:
+ return False
+
+
def request_headers(request: Any, api_mode: str = "chat_completions") -> dict[str, str]:
"""Copy known session and API headers. Refuse other headers and unsafe HTTP values.
@@ -132,10 +170,16 @@ class CaptureStore:
def on_pre_api_request(self, api_request_id: Any = None, session_id: Any = None,
conversation_history: Any = None, model: Any = None, base_url: Any = None,
- api_mode: Any = None, **_: Any) -> None:
+ api_mode: Any = None, user_message: Any = None, turn_origin: Any = None,
+ **_: Any) -> None:
"""Hook pre_api_request: keep the route and one digest for each stored history row."""
if not api_request_id or not session_id or not isinstance(conversation_history, list):
return None
+ # A fork (background review, side question) shares the session for prefix warmth;
+ # its request must not become the capture of the live conversation (see
+ # FORK_TURN_ORIGINS and the prompt prefixes).
+ if _is_fork_request(user_message, turn_origin):
+ return None
try:
digests = [row_digest(row) for row in conversation_history]
except Exception: