Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix
Check Hermes compatibility and report host API failures early
Elevatormusic59ae36afeace
diff --git a/.github/workflows/hermes-compatibility.yml b/.github/workflows/hermes-compatibility.ymlnew file mode 100644index 0000000..116be21--- /dev/null+++ b/.github/workflows/hermes-compatibility.yml@@ -0,0 +1,66 @@+name: Hermes compatibility++on:+ pull_request:+ push:+ branches: [main]+ schedule:+ - cron: "23 9 * * *"+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: ${{ github.workflow }}-${{ github.ref }}+ cancel-in-progress: true++jobs:+ contract:+ name: Hermes contract (${{ matrix.hermes.name }})+ runs-on: ubuntu-latest+ timeout-minutes: 30+ strategy:+ fail-fast: false+ matrix:+ hermes:+ - name: minimum+ ref: 45871e100feceb89769536c88e5e6e265226a409+ - name: upstream-main+ ref: main+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ - name: Check out Hermes source+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ repository: NousResearch/hermes-agent+ ref: ${{ matrix.hermes.ref }}+ path: .work/hermes+ persist-credentials: false+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: "3.14"+ - name: Install the Hermes locked runtime+ run: |+ python -m pip install uv==0.12.17+ uv sync --project .work/hermes --frozen --no-dev --python 3.14+ - name: Check real middleware and capture behavior+ run: |+ .work/hermes/.venv/bin/python -B scripts/check_hermes_compatibility.py \+ --hermes-source .work/hermes --report .work/hermes-compatibility.json+ - name: Check install, compaction, fallback, and rollback+ run: |+ .work/hermes/.venv/bin/python -B scripts/check_plugin_hermes.py \+ --hermes-source .work/hermes --report .work/hermes-integration.json+ - name: Save the metadata report+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: hermes-compatibility-${{ matrix.hermes.name }}+ path: |+ .work/hermes-compatibility.json+ .work/hermes-integration.json+ if-no-files-found: warn+ retention-days: 14diff --git a/README.md b/README.mdindex 9b68dfb..a65cf06 100644--- a/README.md+++ b/README.md@@ -184,6 +184,7 @@ Manual `/compress` can report `No changes from compression` when all messages fiWhen the warm summary cannot be used, the plugin tries the fallback summary. If that summary cannot be used, it uses the fixed summary. The plugin reports these results:- Each saved compaction that Hermes confirms without the warm path writes a WARNING with its reason, for example `Warm compaction skipped (provider_error); used the fallback summary`. Hermes copies warnings to `logs/errors.log`.+- A host compatibility failure (`middleware_order_unknown` or `middleware_unavailable`) prepares a notice after the first confirmed failure. It identifies the failed Hermes check and the summary path used. It does not wait for three failures.- After 3 confirmed compactions in a row without the warm path, the plugin writes one WARNING with a hint for each distinct reason. When automatic engine status is enabled, Hermes shows the notice at the next automatic compaction. The notice has no routine progress text, so a gateway filter for that text does not discard it. Later confirmed failures update the pending notice until Hermes shows it. For example:```text@@ -192,7 +193,7 @@ When the warm summary cannot be used, the plugin tries the fallback summary. If- When the fallback summary could not be used, the notice says how many times, and that those compactions used the fixed summary (no model, less detail).- A warm summary can fail the handoff checks even when the server reports cached tokens. The notice describes the summary result. It does not prove a cache miss, a speed change, or that all details were kept.-- A confirmed warm compaction or a session reset ends the streak, and the notice can show again after the next 3 failures. A cancelled or rejected attempt does not count or clear the streak, and `warm: false` is not a failure.+- A confirmed warm compaction or a session reset ends the streak. The notice can then show again at the first host compatibility failure, or after 3 other failures. A cancelled or rejected attempt does not count or clear the streak, and `warm: false` is not a failure.- When the engine's automatic status is disabled, warnings stay in the logs. The engine keeps a pending notice until status is enabled or a confirmed warm compaction or session reset clears it.- The streak belongs to one engine instance. It is not saved across a restart or shared with separate gateway manual-command engines. A host that sends no successful compaction notification has attempt metadata only.- Manual `/compress` has no status line from the engine: after manual compactions only, the notice is in the logs.@@ -264,6 +265,22 @@ context:The new history uses summary rows that Hermes recognizes. The [integration check](evidence/plugin-integration.json) checked a rollback with the plugin still enabled: the built-in compressor loaded the saved history and compacted it again with its own summary. To remove the plugin, use `hermes plugins disable warm_compaction` or `hermes plugins remove warm_compaction`.+## Hermes update compatibility++A future Hermes update can change an API that this plugin uses. The plugin currently reads the private middleware registry to confirm that no execution middleware runs after its capture. A later middleware could send a different request, so removing this check would make the capture unsafe. If the order cannot be checked, the plugin refuses the warm path and uses a fallback. Fallback summaries can omit details; they are not a guarantee of complete retention.++The [compatibility workflow](.github/workflows/hermes-compatibility.yml) tests the real Hermes middleware against the minimum supported revision and upstream `main`. It runs on pull requests, pushes to `main`, each day, and by manual dispatch. Each report records the exact Hermes commit and plugin file hashes. A failed workflow needs review; it does not update or change an installed Hermes. GitHub Actions notification settings control failure notifications.++The check uses synthetic requests and a fake provider callback. It checks capture ordering, request changes before and after capture, and refusal when ordering cannot be read. It does not call a model. Run it with a Hermes dependency interpreter and a clean, isolated source checkout:++```bash+<hermes-venv-python> -B scripts/check_hermes_compatibility.py --hermes-source <clean-hermes-checkout> --report .work/hermes-compatibility.json+```++This check does not prove full conversation-loop compatibility or a cache benefit. Before adopting a Hermes update, also run `scripts/check_plugin_hermes.py` as described in [Contributing](CONTRIBUTING.md#run-the-checks). Check `path`, `reason`, and available token counters in an isolated synthetic session. Keep the last working Hermes version available until these checks pass.++To remove the private ordering dependency, Hermes needs a documented execution-middleware contract that tells each callback whether another callback follows it. That information must come from the same chain snapshot that the request executes. It must not be inferred from a separate registry read or from request text. The current Hermes API does not provide it. This plugin does not patch Hermes or assume that this proposed API exists.+## DevelopmentRun the unit tests from the repository root:diff --git a/scripts/check_hermes_compatibility.py b/scripts/check_hermes_compatibility.pynew file mode 100644index 0000000..2a20b02--- /dev/null+++ b/scripts/check_hermes_compatibility.py@@ -0,0 +1,244 @@+"""Check the plugin capture against a clean Hermes middleware implementation.++Each case uses a fresh process and temporary home. No model or network request runs.+The report contains versions, hashes, check results, and fixed error codes only.+This check does not prove conversation-loop hook order or provider wire behavior.+"""++from __future__ import annotations++import argparse+import copy+import hashlib+import json+import os+from pathlib import Path+import platform+import subprocess+import sys+import tempfile+from types import SimpleNamespace++ROOT = Path(__file__).resolve().parents[1]+CASES = ("capture_last", "earlier_rewrite", "later_rewrite", "unknown_order")+WORKER_TIMEOUT = 60+SOURCE_MARKERS = ("hermes_cli/plugins.py", "hermes_cli/middleware.py", "agent/context_engine.py", "run_agent.py")+++def plugin_hashes() -> dict[str, str]:+ """Hash the plugin source files. Do not include paths outside the plugin."""+ return {path.relative_to(ROOT).as_posix(): hashlib.sha256(path.read_bytes()).hexdigest()+ for path in sorted((ROOT / "warm_compaction").iterdir())+ if path.is_file() and path.suffix in (".py", ".yaml")}+++def source_state(source: Path) -> dict:+ """Get the exact source commit and reject a dirty checkout."""+ def git(*args):+ return subprocess.run(["git", "-C", str(source), *args], check=True, capture_output=True,+ text=True, timeout=20).stdout.strip()+ commit = git("rev-parse", "HEAD")+ if len(commit) != 40 or any(char not in "0123456789abcdef" for char in commit):+ raise ValueError("invalid_commit")+ if git("status", "--porcelain", "--untracked-files=all"):+ raise ValueError("dirty_hermes_source")+ if not all((source / name).is_file() for name in SOURCE_MARKERS):+ raise ValueError("invalid_hermes_source")+ return {"commit": commit, "clean": True}+++def check_import_origins(source: Path) -> None:+ """Refuse Hermes modules from an installed runtime or another source root."""+ for name, module in tuple(sys.modules.items()):+ if name == "warm_compaction.capture":+ if Path(module.__file__).resolve() != (ROOT / "warm_compaction" / "capture.py").resolve():+ raise ValueError("source_mismatch")+ continue+ if name not in ("hermes_cli", "agent", "hermes_constants", "registration_lifecycle", "utils") and (+ not name.startswith(("hermes_cli.", "agent."))):+ continue+ path = getattr(module, "__file__", None)+ if path is None or not Path(path).resolve().is_relative_to(source):+ raise ValueError("source_mismatch")+++def worker_environment(home: Path) -> dict[str, str]:+ """Keep the runtime paths only. Do not pass credentials or profile settings."""+ names = ("PATH", "SYSTEMROOT", "WINDIR", "PATHEXT", "COMSPEC", "SYSTEMDRIVE",+ "LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH")+ env = {key: value for key, value in os.environ.items() if key.upper() in names}+ env.update({key: str(home) for key in ("HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA",+ "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "TEMP", "TMP")})+ env.update({"HERMES_HOME": str(home), "HERMES_RUNTIME_DIR": str(home / "runtime"),+ "HERMES_DISABLE_LAZY_INSTALLS": "1", "HERMES_ENABLE_PROJECT_PLUGINS": "0",+ "PYTHONNOUSERSITE": "1", "PYTHONDONTWRITEBYTECODE": "1"})+ return env+++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.+ platform.uname()+ def no_network(event, _args):+ if event in ("socket.connect", "socket.connect_ex", "socket.bind", "socket.getaddrinfo",+ "subprocess.Popen", "os.system"):+ raise RuntimeError("external_operation_blocked")+ sys.addaudithook(no_network)+ sys.path[:0] = [str(ROOT), str(source)]+ try:+ from hermes_cli import plugins+ from hermes_cli.middleware import apply_llm_request_middleware, run_llm_execution_middleware+ from hermes_cli.plugins import PluginContext, PluginManager, PluginManifest+ from warm_compaction.capture import CaptureStore+ except ImportError as error:+ raise ValueError("hermes_import_failed") from error+ check_import_origins(source)++ manager = plugins.get_plugin_manager()+ if not isinstance(manager, PluginManager):+ raise RuntimeError("manager_type_changed")+ manager.discover_and_load()+ context = PluginContext(PluginManifest(name="wc_compatibility_probe", version="0.0.0"), manager)+ store = CaptureStore()+ context.register_hook("pre_api_request", store.on_pre_api_request)+ context.register_hook("post_api_request", store.on_post_api_request)++ def request_rewrite(request, **_kwargs):+ return {"request": {**request, "temperature": 0.25}, "source": "synthetic_probe"}++ def execution_rewrite(request, next_call, **_kwargs):+ changed = copy.deepcopy(request)+ changed["extra_body"]["synthetic_marker"] = "execution_rewrite"+ return next_call(changed)++ def unknown_capture(**kwargs):+ # The registered callback cannot be identified as the store callback.+ return store.on_llm_execution(**kwargs)++ context.register_middleware("llm_request", request_rewrite)+ if case == "earlier_rewrite":+ context.register_middleware("llm_execution", execution_rewrite)+ context.register_middleware("llm_execution", unknown_capture if case == "unknown_order"+ else store.on_llm_execution)+ if case == "later_rewrite":+ context.register_middleware("llm_execution", execution_rewrite)++ history = [{"role": "user", "content": "Synthetic probe question."}]+ request = {"model": "synthetic-model", "messages": history, "max_tokens": 128,+ "extra_body": {"synthetic_marker": "initial"},+ "extra_headers": {"x-opencode-session": "synthetic-session-header"}}+ runtime = {"api_request_id": "synthetic-request", "session_id": "synthetic-session",+ "model": "synthetic-model", "base_url": "https://example.invalid/v1",+ "api_mode": "chat_completions"}+ applied = apply_llm_request_middleware(request, **runtime)+ plugins.invoke_hook("pre_api_request", conversation_history=history, **runtime)+ calls = []+ response = object()++ def terminal(payload):+ calls.append(copy.deepcopy(payload))+ return response++ returned = run_llm_execution_middleware(applied.payload, terminal,+ original_request=applied.original_payload, **runtime)+ plugins.invoke_hook("post_api_request", finish_reason="stop",+ assistant_message=SimpleNamespace(content="Synthetic reply.", tool_calls=[]),+ usage={"prompt_tokens": 123}, **runtime)+ capture = store.latest(runtime["session_id"]) or {}+ expected_refusal = {"later_rewrite": "middleware_after_capture",+ "unknown_order": "middleware_order_unknown"}.get(case)+ marker = "execution_rewrite" if case in ("earlier_rewrite", "later_rewrite") else "initial"+ expected_headers = {"x-opencode-session": "synthetic-session-header"}+ expected_body = {"model": "synthetic-model", "messages": history, "max_tokens": 128,+ "temperature": 0.25, "synthetic_marker": marker}+ expected_kwargs = {"model": "synthetic-model", "messages": history, "max_tokens": 128,+ "temperature": 0.25, "extra_body": {"synthetic_marker": marker},+ "extra_headers": expected_headers}+ checks = {"terminal_once": len(calls) == 1, "response_unchanged": returned is response,+ "terminal_payload_exact": bool(calls) and calls[0] == expected_kwargs,+ "request_middleware_applied": bool(calls) and calls[0].get("temperature") == 0.25,+ "request_header_forwarded": bool(calls) and calls[0].get("extra_headers") == expected_headers,+ "reported_prompt_tokens": capture.get("prompt_tokens") == 123,+ "refusal_expected": capture.get("refusal") == expected_refusal}+ if expected_refusal:+ checks["capture_body_refused"] = capture.get("body") is None+ checks["capture_headers_refused"] = capture.get("request_headers") == {}+ else:+ checks["capture_body_exact"] = capture.get("body") == expected_body+ checks["capture_headers_exact"] = capture.get("request_headers") == expected_headers+ if case in ("earlier_rewrite", "later_rewrite"):+ checks["execution_rewrite_reaches_terminal"] = bool(calls) and (+ calls[0].get("extra_body", {}).get("synthetic_marker") == "execution_rewrite")+ check_import_origins(source)+ checks["import_origins_match_source"] = True+ return {"case": case, "passed": all(checks.values()), "checks": checks,+ "error": None if all(checks.values()) else "contract_check_failed"}+++def run(source: Path) -> dict:+ """Run each contract case in a separate process. Discard raw child output."""+ report = {"check": "real Hermes middleware capture compatibility", "passed": False,+ "python": sys.version.split()[0], "hermes": None, "plugin_sha256": {},+ "script_sha256": None, "cases": [], "error": None}+ try:+ report["script_sha256"] = hashlib.sha256(Path(__file__).read_bytes()).hexdigest()+ report["hermes"] = source_state(source)+ report["plugin_sha256"] = plugin_hashes()+ for case in CASES:+ with tempfile.TemporaryDirectory(prefix="wc-compatibility-") as folder:+ home = Path(folder)+ (home / "config.yaml").write_text("plugins:\n enabled: []\n", encoding="utf-8")+ result_path = home / "result.json"+ completed = subprocess.run(+ [sys.executable, "-B", str(Path(__file__).resolve()), "--hermes-source", str(source),+ "--worker-case", case, "--report", str(result_path)], cwd=home,+ env=worker_environment(home), capture_output=True, timeout=WORKER_TIMEOUT)+ result = (json.loads(result_path.read_text(encoding="utf-8")) if result_path.exists()+ else {"case": case, "passed": False, "checks": {}, "error": "worker_no_report"})+ result["exit_ok"] = completed.returncode == 0+ report["cases"].append(result)+ report["checks"] = {"hermes_source_unchanged": source_state(source) == report["hermes"],+ "plugin_source_unchanged": plugin_hashes() == report["plugin_sha256"],+ "script_unchanged": hashlib.sha256(Path(__file__).read_bytes()).hexdigest()+ == report["script_sha256"]}+ report["passed"] = all(report["checks"].values()) and all(+ item["passed"] and item["exit_ok"] for item in report["cases"])+ if not report["passed"]:+ report["error"] = "compatibility_check_failed"+ except Exception as error:+ code = error.args[0] if type(error) is ValueError and error.args else None+ report["error"] = code if code in (+ "dirty_hermes_source", "invalid_commit", "invalid_hermes_source") else "probe_setup_failed"+ report["error_type"] = type(error).__name__+ return report+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--hermes-source", required=True, type=Path)+ parser.add_argument("--report", type=Path)+ parser.add_argument("--worker-case", choices=CASES, help=argparse.SUPPRESS)+ args = parser.parse_args()+ if args.worker_case:+ try:+ report = worker(args.hermes_source.resolve(), args.worker_case)+ except Exception as error:+ code = error.args[0] if type(error) is ValueError and error.args else None+ report = {"case": args.worker_case, "passed": False, "checks": {},+ "error": code if code in ("hermes_import_failed", "source_mismatch") else "worker_runtime_failed",+ "error_type": type(error.__cause__ or error).__name__}+ else:+ report = run(args.hermes_source.resolve())+ if args.report:+ try:+ args.report.parent.mkdir(parents=True, exist_ok=True)+ args.report.write_text(json.dumps(report, sort_keys=True, indent=2) + "\n", encoding="utf-8")+ except OSError as error:+ print(json.dumps({"passed": False, "error": "report_write_failed", "error_type": type(error).__name__}))+ return 1+ print(json.dumps({"passed": report["passed"], "error": report["error"]}))+ return 0 if report["passed"] else 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.pyindex 10d0316..979ff9b 100644--- a/tests/test_wc_engine.py+++ b/tests/test_wc_engine.py@@ -749,6 +749,154 @@ class EngineTest(unittest.TestCase):engine = self.make(tail_tokens=500_000)self.assertEqual(engine._tail_cap(0, None, 0) - engine._tail_cap(2_000, None, 0, 1_000), 3_000)+ def compatibility_candidate(self, engine, reason):+ """Run a synthetic compaction with one missing Hermes middleware API."""+ rows, reply = old_turns(), assistant("done")+ if reason == "middleware_order_unknown":+ with patch.object(wc_hermes_stub.PLUGINS, "_delivery_manager",+ side_effect=AttributeError("synthetic change")):+ self.seed(rows, reply)+ result = engine.compress([*rows, reply])+ else:+ self.seed(rows, reply)+ with patch.dict(wc_hermes_stub.MIDDLEWARE.__dict__, clear=True):+ result = engine.compress([*rows, reply])+ self.assertEqual(engine.warm_last["reason"], reason)+ self.assertEqual(self.post.calls, [])+ return result++ def test_a_host_compatibility_failure_tells_the_user_at_the_first_commit(self):+ for reason in ("middleware_order_unknown", "middleware_unavailable"):+ for path in ("fallback", "fixed"):+ with self.subTest(reason=reason, path=path):+ self.llm.error = RuntimeError("synthetic fallback failure") if path == "fixed" else None+ engine = self.make()+ self.compatibility_candidate(engine, reason)+ self.assertEqual(engine.warm_last["path"], path)+ self.assertEqual(engine._warm_failures, 0)+ self.assertIsNone(engine._warm_notice)+ self.commit(engine)+ notice = engine.get_automatic_compaction_status_message(+ phase="compress", default_message="Compacting")+ self.assertIn("Hermes compatibility", notice)+ self.assertIn(reason, notice)+ self.assertIn("fallback summary", notice)+ self.assertIn("logs/agent.log", notice)+ self.assertNotIn("no messages were dropped", notice)+ if path == "fixed":+ self.assertIn("fixed summary (no model, less detail)", notice)+ else:+ self.assertIn("Compaction continues with the fallback summary.", notice)++ def test_a_compatibility_notice_stays_pending_when_the_host_hides_status(self):+ engine = self.make()+ self.compatibility_candidate(engine, "middleware_order_unknown")+ self.commit(engine)+ pending = engine._warm_notice+ self.assertIsNotNone(pending)+ engine.emit_automatic_compaction_status = False+ self.assertIsNone(engine.get_automatic_compaction_status_message(+ phase="compress", default_message="Compacting"))+ self.assertEqual(engine._warm_notice, pending)+ self.llm.error = RuntimeError("synthetic fallback failure")+ self.compress_committed(engine, [*old_turns(), assistant("done")])+ engine.emit_automatic_compaction_status = True+ notice = engine.get_automatic_compaction_status_message(phase="compress", default_message="Compacting")+ self.assertIn("Hermes compatibility", notice)+ self.assertIn("no_capture", notice)+ self.assertIn("the last 2 compactions", notice)+ self.assertIn("the fallback summary could not be used 1 of 2 times", notice)+ self.assertEqual(engine.get_automatic_compaction_status_message(+ phase="compress", default_message="Compacting"), "Compacting")++ def test_a_consumed_compatibility_notice_does_not_repeat_at_the_third_failure(self):+ engine = self.make()+ self.compatibility_candidate(engine, "middleware_unavailable")+ self.commit(engine)+ self.assertIn("Hermes compatibility", engine.get_automatic_compaction_status_message(+ phase="compress", default_message="Compacting"))+ for _ in range(4):+ self.compatibility_candidate(engine, "middleware_order_unknown")+ self.commit(engine)+ self.assertEqual(engine.get_automatic_compaction_status_message(+ phase="compress", default_message="Compacting"), "Compacting")++ def test_a_host_failure_updates_a_pending_provider_notice_or_follows_a_displayed_one(self):+ def refused(*args, **kwargs):+ raise RuntimeError("synthetic provider refusal")++ for consumed in (False, True):+ with self.subTest(consumed=consumed):+ engine = self.make()+ engine._post = refused+ rows, reply = old_turns(), assistant("done")+ for _ in range(3):+ self.seed(rows, reply)+ self.compress_committed(engine, [*rows, reply])+ self.assertIsNotNone(engine._warm_notice)+ self.assertNotIn("Hermes compatibility", engine._warm_notice)+ if consumed:+ notice = engine.get_automatic_compaction_status_message(+ phase="compress", default_message="Compacting")+ self.assertIn("provider_error", notice)+ self.compatibility_candidate(engine, "middleware_order_unknown")+ self.commit(engine)+ notice = engine.get_automatic_compaction_status_message(phase="compress", default_message="Compacting")+ self.assertIn("Hermes compatibility", notice)+ self.assertIn("middleware_order_unknown", notice)+ self.assertIn("provider_error", notice)+ for reason in ("middleware_order_unknown", "middleware_unavailable"):+ self.compatibility_candidate(engine, reason)+ self.commit(engine)+ self.assertEqual(engine.get_automatic_compaction_status_message(+ phase="compress", default_message="Compacting"), "Compacting")++ def test_warm_success_and_session_reset_allow_a_new_compatibility_notice(self):+ for action in ("warm", "reset"):+ for consumed in (False, True):+ with self.subTest(action=action, consumed=consumed):+ engine = self.make()+ self.compatibility_candidate(engine, "middleware_order_unknown")+ self.commit(engine)+ self.assertIsNotNone(engine._warm_notice)+ if consumed:+ engine.get_automatic_compaction_status_message(phase="compress", default_message="Compacting")+ if action == "reset":+ engine.on_session_reset()+ else:+ rows, reply = old_turns(), assistant("done")+ self.seed(rows, reply)+ self.compress_committed(engine, [*rows, reply])+ self.assertEqual(engine.warm_last["path"], "warm")+ self.post.calls.clear()+ self.assertEqual(engine._warm_failures, 0)+ self.assertIsNone(engine._warm_notice)+ self.compatibility_candidate(engine, "middleware_order_unknown")+ self.commit(engine)+ self.assertIn("Hermes compatibility", engine.get_automatic_compaction_status_message(+ phase="compress", default_message="Compacting"))++ def test_provider_and_capture_failures_keep_the_three_failure_notice_delay(self):+ def refused(*args, **kwargs):+ raise RuntimeError("synthetic refusal")++ for reason in ("provider_error", "no_capture"):+ with self.subTest(reason=reason):+ engine = self.make()+ rows, reply = old_turns(), assistant("done")+ for count in range(1, 4):+ if reason == "provider_error":+ self.seed(rows, reply)+ engine._post = refused+ self.compress_committed(engine, [*rows, reply])+ self.assertEqual(engine.warm_last["reason"], reason)+ notice = engine.get_automatic_compaction_status_message(+ phase="compress", default_message="Compacting")+ if count < 3:+ self.assertEqual(notice, "Compacting")+ else:+ self.assertIn("the last 3 compactions", notice)+def test_three_compactions_without_the_warm_path_tell_the_user_one_time(self):# No capture: each compaction uses the fallback. Each refusal is a WARNING; the third one adds one notice# to the next automatic compaction status that Hermes shows.diff --git a/warm_compaction/engine.py b/warm_compaction/engine.pyindex 0fc4b26..b505390 100644--- a/warm_compaction/engine.py+++ b/warm_compaction/engine.py@@ -34,7 +34,9 @@ SUMMARY_RESERVE = 2 * fallback.MAX_TOKENS# The largest reply reserve for an unknown reply limit: the Hermes output reserve of a native Gemini route.UNKNOWN_RESERVE_MAX = 65_536# After this many compactions in a row without the warm path, the user gets one notice.+# A host compatibility refusal starts the notice at the first failure.WARM_FAILURE_STREAK = 3+HOST_COMPATIBILITY_REFUSALS = frozenset({"middleware_order_unknown", "middleware_unavailable"})# What a user can do about the common reasons. Other reasons point to the README Limits.FAILURE_HINTS = {"no_capture": "no main-model request completed in this Hermes process before the compaction",@@ -53,6 +55,7 @@ FAILURE_HINTS = {"tls_unknown": "the TLS settings of the route could not be read","middleware_after_capture": "another plugin middleware runs after the capture and can change the request","middleware_order_unknown": "the order of the plugin middleware could not be read",+ "middleware_unavailable": "the Hermes middleware API could not be loaded","source_transform_unsupported": "a hook or middleware changed the stored rows in the request",}HERMES_END_MARKER = "--- END OF CONTEXT SUMMARY — respond to the message below, not the summary above ---"@@ -700,15 +703,18 @@ class WarmCompactionEngine(ContextEngine):self._warm_failures, self._warm_fixed = 0, 0self._warm_failure_reasons: list[str] = []self._warm_notice: str | None = None+ self._warm_notice_issued = False+ self._warm_compatibility_notice_issued = Falsedef _note_warm_result(self, record: dict[str, Any]) -> None:"""Count the compactions in a row without the warm path. Each one is a WARNING (errors.log has it too).- After WARM_FAILURE_STREAK of them, one WARNING names the reasons and their hints. The next automatic- compaction status shows the notice. Until then, later failures update it. A warm compaction ends the- streak. A cancelled attempt and the warm setting off do not count."""+ A host compatibility refusal starts the notice at the first failure. Other failures wait for+ WARM_FAILURE_STREAK. A first host refusal can update a pending notice or start one after a displayed+ generic notice. The next automatic compaction status shows each notice once. Until then, later failures+ update it. A warm compaction ends the streak. A cancelled attempt and the warm setting off do not count."""path, reason = record["path"], str(record["reason"])if path == "warm":- if self._warm_failures >= WARM_FAILURE_STREAK:+ if self._warm_notice_issued:logger.info("Warm compaction works again after %d compactions without it", self._warm_failures)self._clear_warm_failures()return@@ -718,8 +724,9 @@ class WarmCompactionEngine(ContextEngine):self._warm_failures += 1self._warm_fixed += path == "fixed"self._warm_failure_reasons.append(reason)- if self._warm_failures >= WARM_FAILURE_STREAK and (- self._warm_failures == WARM_FAILURE_STREAK or self._warm_notice is not None):+ first_notice = ((not self._warm_notice_issued and self._warm_failures >= WARM_FAILURE_STREAK)+ or (reason in HOST_COMPATIBILITY_REFUSALS and not self._warm_compatibility_notice_issued))+ if first_notice or self._warm_notice is not None:reasons = ", ".join(dict.fromkeys(self._warm_failure_reasons))hints = "; ".join(f"{item}: {FAILURE_HINTS.get(item.split(':', 1)[0], 'see the Limits section of the plugin README')}"@@ -733,13 +740,21 @@ class WarmCompactionEngine(ContextEngine):continues = "Compaction continues with the fallback summary"log_continues = "compaction continues with the fallback summary"# The Hermes warning style on screen: the sign, the subject, what continues, and where to look.+ compatibility = ("Hermes compatibility check failed; "+ if HOST_COMPATIBILITY_REFUSALS.intersection(self._warm_failure_reasons) else "")+ compactions = "compaction" if self._warm_failures == 1 else "compactions"self._warm_notice = (- f"\u26a0 Warm compaction unavailable: the last {self._warm_failures} compactions did not use the "+ f"\u26a0 Warm compaction unavailable: {compatibility}the last {self._warm_failures} {compactions} "+ "did not use the "f"warm summary ({hints}). {continues}. ""Details: the warm_compaction lines in logs/agent.log.")- if self._warm_failures == WARM_FAILURE_STREAK:- logger.warning("Warm compaction failed %d times in a row (%s): %s; %s", self._warm_failures, reasons,- hints, log_continues)+ self._warm_notice_issued = True+ if compatibility:+ self._warm_compatibility_notice_issued = True+ if first_notice:+ times = "time" if self._warm_failures == 1 else "times"+ logger.warning("Warm compaction failed %d %s in a row (%s): %s; %s", self._warm_failures, times,+ reasons, hints, log_continues)def get_automatic_compaction_status_message(self, *, phase: str, default_message: str,**context: Any) -> str | None: