Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix
Fix matching of captured context rows
Elevatormusic0fc0a75a458e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cf7d0b5..d9e81cc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,7 @@ All notable changes are listed here. The format follows [Keep a Changelog](https### Fixed+- Match captured content with the stored `api_content` text for context-injected rows. Keep role, tool, and native replay checks. Report each history refusal stage and use the fallback when the capture is ahead of the live history.- Keep the original history when an indivisible native replay block exceeds the compaction budget. Check the threshold, reply reserve, and unknown request overhead before accepting the new history.- Match Copilot hostnames at a domain boundary. A lookalike hostname no longer gets Copilot replay handling.- Accept trailing whitespace removal by Hermes from complete text strings, including `api_content`, without a false `source_transform_unsupported` fallback. Keep the captured request prefix unchanged.diff --git a/README.md b/README.mdindex 95cb601..de207b1 100644--- a/README.md+++ b/README.md@@ -207,6 +207,8 @@ warm_compaction: path=warm reason=accepted elapsed_s=10.656 prompt_tokens=108021Capture refusal codes identify the failed check: `request_not_mapping` means that the request is not a mapping; `request_options_unsupported` means that extra headers, query options, or `extra_body` cannot be kept; `request_not_json` means that a body value cannot be sent as JSON (including NaN and infinity). `settings_unsupported` still applies to unsupported model settings. These codes contain no request values.+History refusal codes identify the failed stage: `history_changed:capture_ahead` means that the capture has more rows than the live history; `history_changed:reply_missing` means that the captured reply is absent; `history_changed:digest` means that a captured row differs; `history_changed:reply` means that the next row does not match the reply; `history_changed:tool_extra` or `history_changed:tool_count` means that tool results do not match the captured calls; `history_changed:trailing` means that later rows include a role other than user. These codes contain no message text or tool IDs. A shorter live history uses the fallback; the plugin cannot reuse unmatched future rows.+The engine status (`get_status()`) has the same values in `warm_last`. After a new attempt starts, an older worker cannot replace this status or write a final metadata line. The log never contains message text, request bodies, or keys.Manual `/compress` can report `No changes from compression` when all messages fit in the recent-history tail. Then the plugin has no older history to summarize. The request estimate also includes system instructions and tool definitions, which the plugin does not compress. Use `/context` to see the token counts for each part. This unchanged result does not count as a warm-path failure.diff --git a/evidence/README.md b/evidence/README.mdindex 480d7af..277eb10 100644--- a/evidence/README.md+++ b/evidence/README.md@@ -4,6 +4,8 @@ These records cover research runs and issue checks. They have metadata only: cou| File | Content || --- | --- |+| [issue24-validation.json](issue24-validation.json) | Issue 24: assembled-capture refusal before the fix, effective-content matching after it, safe capture-ahead refusal, and synthetic checks on clean minimum and current Hermes source |+| [issue24-live-dgx-20261009.json](issue24-live-dgx-20261009.json) | Issue 24: one manual and one automatic live DGX test with synthetic context; exact request prefixes, saved-history reloads, reported cached tokens, and measurement limits || [issue-12-whitespace.json](issue-12-whitespace.json) | Issue 12: refusal before the fix, three warm compactions after it, and seven integration scenarios on clean Hermes `e36a8180`; synthetic conversations and a loopback fake server || [plugin-integration.json](plugin-integration.json) | The integration check: install with the Hermes install command, manual and automatic compaction, fallback, tools, and rollback on unpatched Hermes `45871e10`, against a loopback fake server || [plugin-live.json](plugin-live.json) | Live runs, plugin against the built-in compressor: DGX and LM Studio, manual and automatic, ten synthetic cases of 100,000 or more tokens each |diff --git a/evidence/issue24-live-dgx-20261009.json b/evidence/issue24-live-dgx-20261009.jsonnew file mode 100644index 0000000..36d6c1c--- /dev/null+++ b/evidence/issue24-live-dgx-20261009.json@@ -0,0 +1,253 @@+{+ "date": "2026-10-09",+ "issue": 24,+ "purpose": "Check synthetic manual and automatic compaction with real Hermes and the existing DGX route.",+ "outcome": "passed",+ "hermes_commit": "46d7718a52ff33accb15dc0501736fbdb6833cab",+ "hermes_source_clean": true,+ "runner_python": "3.14.5",+ "worker_python": "3.14.5",+ "mode": "fresh-profile one-shot CLI agent and gateway manual handler",+ "provider": "custom",+ "model": "dgx-model",+ "api_mode": "chat_completions",+ "route": "Existing DGX route through a fixed loopback relay",+ "server_version": "unknown",+ "context_window": 131072,+ "reply_limit": 4096,+ "settings": {+ "threshold": 0.95,+ "tail_tokens": 1200,+ "user_copy_chars": 2000+ },+ "automatic_threshold_tokens": 8000,+ "request_option_names": [+ "seed",+ "draft",+ "chat_template_kwargs.enable_thinking",+ "chat_template_kwargs.reasoning_effort"+ ],+ "synthetic_fixture": {+ "seed_turns": 12,+ "seed_prompt_tokens": 14202,+ "context_hook": "Documented pre_llm_call hook adds synthetic text to each request.",+ "main_reply_before_compaction": true,+ "private_history_used": false+ },+ "plugin_sha256": {+ "anthropic.py": "7bd4cb0e075c4f279f62d3b6f0c3dcf7405308c7360f9136369476a59dca4fd3",+ "capture.py": "d2ce12d20fca5649d94b17d376a7bd9e21ba7f6a828b94cb62d030ca55adf791",+ "engine.py": "368b4ec95f31d0f6fc868f6184730d513e02f61764be60a1fabdb00cdececfd6",+ "fallback.py": "9b2d0529767ff157bbe0d1cbf096ca6ac35217118f81eee769adf41d50189a9a",+ "handoff.py": "fcab51def8fbcc2b1928957930c9a5c58a4ad202c949fd9f870a77f3b30276ae",+ "layout.py": "3722ca05a4b84c9ed9f5cef5c7f7a175201efaba4208f3819dabcc556a2cfd57",+ "native.py": "2bac322bf7779e7d4ec78137a1ba1fdff25d3e58910ace51200147aebf15f494",+ "plugin.yaml": "baa7820b3ce9a40d2a53f70a4d0525131860ea2ec670143d0a7742b59c4d937b",+ "protocol.py": "f319d7a38ebb60d68d09b3575fe4f88f324b03be6017efbc5fd9932f05299853",+ "responses.py": "70c8c912b39b377945488f4fb68f032ca0aa9be5a4340df0c1af7fd5961ee103",+ "rows.py": "656d1eb02d7d31d51b89937a50878a8235093d82e8fbbab76526d80f8b182d80",+ "warm.py": "153ea2d3add81cec6abf2ca5e3873a6d83ed9d5772f711fb1aefb60fe3e11662",+ "__init__.py": "760484ace80b9da77d7397828f69178905c9ac95df7b8114956bde727bd98aef"+ },+ "plugin_sha256_scope": "Tested working bytes before Git LF normalization",+ "plugin_lf_sha256": {+ "anthropic.py": "7bd4cb0e075c4f279f62d3b6f0c3dcf7405308c7360f9136369476a59dca4fd3",+ "capture.py": "d2ce12d20fca5649d94b17d376a7bd9e21ba7f6a828b94cb62d030ca55adf791",+ "engine.py": "368b4ec95f31d0f6fc868f6184730d513e02f61764be60a1fabdb00cdececfd6",+ "fallback.py": "9b2d0529767ff157bbe0d1cbf096ca6ac35217118f81eee769adf41d50189a9a",+ "handoff.py": "fcab51def8fbcc2b1928957930c9a5c58a4ad202c949fd9f870a77f3b30276ae",+ "layout.py": "3722ca05a4b84c9ed9f5cef5c7f7a175201efaba4208f3819dabcc556a2cfd57",+ "native.py": "2bac322bf7779e7d4ec78137a1ba1fdff25d3e58910ace51200147aebf15f494",+ "plugin.yaml": "baa7820b3ce9a40d2a53f70a4d0525131860ea2ec670143d0a7742b59c4d937b",+ "protocol.py": "f319d7a38ebb60d68d09b3575fe4f88f324b03be6017efbc5fd9932f05299853",+ "responses.py": "70c8c912b39b377945488f4fb68f032ca0aa9be5a4340df0c1af7fd5961ee103",+ "rows.py": "656d1eb02d7d31d51b89937a50878a8235093d82e8fbbab76526d80f8b182d80",+ "warm.py": "84c66a79dc6b3d4d5b641a8b48d1341e5e765d31f07126ff3fd6108ac01cb3b9",+ "__init__.py": "760484ace80b9da77d7397828f69178905c9ac95df7b8114956bde727bd98aef"+ },+ "normalization": "Git stores LF. The recorded LF hashes differ only by CRLF-to-LF conversion.",+ "runs": [+ {+ "mode": "manual",+ "passed": true,+ "checks": {+ "real_source": true,+ "isolated_plugin_selected": true,+ "seed_completed": true,+ "context_sidecar_present": true,+ "seed_did_not_compact": true,+ "manual_removed_rows": true,+ "warm_accepted": true,+ "one_compaction": true,+ "continuation_code_retained": true,+ "summary_in_history": true,+ "summary_saved": true,+ "plugin_no_blocked_calls": true+ },+ "prefix_exact": true,+ "request_counts": {+ "main": 2,+ "warm": 1,+ "fallback": 0+ },+ "warm_last": {+ "path": "warm",+ "reason": "accepted",+ "elapsed_s": 6.479,+ "prompt_tokens": 14679,+ "cached_tokens": 14144+ },+ "requests": [+ {+ "kind": "main",+ "status": 200,+ "elapsed_s": 9.699,+ "usage": {+ "prompt_tokens": 14202,+ "completion_tokens": 6,+ "total_tokens": 14208,+ "prompt_tokens_details": {+ "cached_tokens": 0+ }+ },+ "error_type": null+ },+ {+ "kind": "warm",+ "status": 200,+ "elapsed_s": 6.402,+ "usage": {+ "prompt_tokens": 14679,+ "completion_tokens": 267,+ "total_tokens": 14946,+ "prompt_tokens_details": {+ "cached_tokens": 14144+ }+ },+ "error_type": null+ },+ {+ "kind": "main",+ "status": 200,+ "elapsed_s": 3.88,+ "usage": {+ "prompt_tokens": 4494,+ "completion_tokens": 5,+ "total_tokens": 4499,+ "prompt_tokens_details": {+ "cached_tokens": 0+ }+ },+ "error_type": null+ }+ ],+ "saved_reload": {+ "summary_saved": true,+ "active_rows": 6+ },+ "saved_reload_audit": {+ "original_receipt": "result.json",+ "original_passed": false,+ "reason": "The first checker omitted repair_alternation=True. Hermes returns summary markers with this option.",+ "fresh_process_reload": true,+ "new_model_requests": 0+ }+ },+ {+ "mode": "auto",+ "passed": true,+ "checks": {+ "real_source": true,+ "isolated_plugin_selected": true,+ "seed_completed": true,+ "context_sidecar_present": true,+ "seed_did_not_compact": true,+ "warm_accepted": true,+ "one_compaction": true,+ "continuation_code_retained": true,+ "summary_in_history": true,+ "summary_saved": true,+ "plugin_no_blocked_calls": true+ },+ "prefix_exact": true,+ "request_counts": {+ "main": 2,+ "warm": 1,+ "fallback": 0+ },+ "warm_last": {+ "path": "warm",+ "reason": "accepted",+ "elapsed_s": 5.706,+ "prompt_tokens": 14691,+ "cached_tokens": 14144+ },+ "requests": [+ {+ "kind": "main",+ "status": 200,+ "elapsed_s": 9.923,+ "usage": {+ "prompt_tokens": 14202,+ "completion_tokens": 6,+ "total_tokens": 14208,+ "prompt_tokens_details": {+ "cached_tokens": 0+ }+ },+ "error_type": null+ },+ {+ "kind": "warm",+ "status": 200,+ "elapsed_s": 5.663,+ "usage": {+ "prompt_tokens": 14691,+ "completion_tokens": 234,+ "total_tokens": 14925,+ "prompt_tokens_details": {+ "cached_tokens": 14144+ }+ },+ "error_type": null+ },+ {+ "kind": "main",+ "status": 200,+ "elapsed_s": 3.34,+ "usage": {+ "prompt_tokens": 3422,+ "completion_tokens": 5,+ "total_tokens": 3427,+ "prompt_tokens_details": {+ "cached_tokens": 0+ }+ },+ "error_type": null+ }+ ],+ "saved_reload": {+ "summary_saved": true,+ "active_rows": 4+ },+ "saved_reload_audit": {+ "original_receipt": "result.json",+ "original_passed": true,+ "reason": "Check the saved summary again in a fresh process.",+ "fresh_process_reload": true,+ "new_model_requests": 0+ }+ }+ ],+ "server_cache_counters": "unknown",+ "performance_qualified": false,+ "limits": [+ "One manual and one automatic run. No baseline or repeated comparison was run.",+ "Cached tokens are response metadata. Independent server cache counters were not collected.",+ "The provider saw the exact captured prefix. This does not qualify cache reuse or a speed gain.",+ "The clean host capture retains display rows. The reported assembled-capture shape has a separate unit regression.",+ "Saved synthetic histories were reloaded in fresh processes. This does not prove private-session compatibility.",+ "The initial manual checker omitted the loader option for summary markers. The initial failed receipt was kept.",+ "No host source, deployment, or production cache was changed."+ ]+}diff --git a/evidence/issue24-validation.json b/evidence/issue24-validation.jsonnew file mode 100644index 0000000..597810b--- /dev/null+++ b/evidence/issue24-validation.json@@ -0,0 +1,290 @@+{+ "schema_version": 1,+ "issue": 24,+ "date": "2026-10-09",+ "privacy": "metadata only",+ "baseline_plugin_commit": "31d6448a5ea553091fed0e5826a3209c37f38551",+ "synthetic": true,+ "reproduction_scope": "Assembled capture rows and stored rows with the same effective content.",+ "before_fix": [+ {+ "command": "python -B -m unittest discover -s tests -p test_wc_warm.py -k assembled",+ "status": "failed",+ "tests": 1,+ "reason": "history_changed"+ },+ {+ "command": "python -B -m unittest discover -s tests -p test_wc_engine.py -k assembled",+ "status": "failed",+ "tests": 1,+ "path": "fallback",+ "reason": "history_changed"+ }+ ],+ "after_fix": [+ {+ "command": "python -B -m unittest discover -s tests -p test_wc_warm.py -k assembled",+ "status": "passed",+ "tests": 1+ },+ {+ "command": "python -B -m unittest discover -s tests -p test_wc_engine.py -k assembled",+ "status": "passed",+ "tests": 1+ }+ ],+ "local_checks": [+ {+ "command": "python -m coverage run -m unittest discover -s tests -p \"test_wc_*.py\"",+ "status": "passed",+ "tests": 385,+ "python": "3.14.5"+ },+ {+ "command": "python -m coverage run --append -m unittest discover -s tests/property -p \"test_*.py\"",+ "status": "passed",+ "tests": 12,+ "hypothesis": "6.168.5"+ },+ {+ "command": "python -B -m unittest discover -s tests -p \"test_issue_policy.py\"",+ "status": "passed",+ "tests": 193+ },+ {+ "command": "python -m coverage report -m",+ "status": "passed",+ "coverage": "7.16.2",+ "total_percent": 92,+ "branches_measured": true+ },+ {+ "command": "ruff check .",+ "status": "passed",+ "ruff": "0.16.10"+ },+ {+ "check": "local Markdown links",+ "status": "passed"+ },+ {+ "check": "AGENTS.md and CLAUDE.md byte match",+ "status": "passed"+ },+ {+ "command": "git diff --check",+ "status": "passed"+ }+ ],+ "behavior_checks": {+ "same_effective_text_matches": true,+ "captured_prefix_kept": true,+ "role_tool_and_native_fields_still_checked": true,+ "non_string_or_empty_sidecar_ignored": true,+ "capture_ahead_refused": true,+ "capture_ahead_reason": "history_changed:capture_ahead",+ "unmatched_future_rows_not_sent": true,+ "history_refusal_codes_have_no_message_or_tool_id": true+ },+ "hermes_checks": [+ {+ "source": "minimum",+ "commit": "45871e100feceb89769536c88e5e6e265226a409",+ "clean": true,+ "checks": [+ {+ "check": "middleware",+ "status": "passed",+ "python": "3.14.7",+ "command": "<hermes-python> -B scripts/check_hermes_compatibility.py --hermes-source <clean-hermes> --report <metadata-report>",+ "case_count": 4,+ "case_names": [+ "capture_last",+ "earlier_rewrite",+ "later_rewrite",+ "unknown_order"+ ],+ "script_sha256": "641b1acb9a311ebad570c4a06800ff866030471db3b4d745148244b2e8ca75c0"+ },+ {+ "check": "plugin_integration",+ "status": "passed",+ "python": "3.14.7",+ "command": "<hermes-python> -B scripts/check_plugin_hermes.py --hermes-source <clean-hermes> --report <metadata-report>",+ "case_count": 9,+ "case_names": [+ "enable_manual_warm",+ "manual_context",+ "manual_whitespace",+ "manual_fallback",+ "manual_fixed",+ "auto_tool_loop",+ "auto_context_tool",+ "auto_warm_failures",+ "rollback"+ ],+ "script_sha256": "e476408c2a3d7322cd008a9a612edc3f4eb4a3cd91f6af95ed06b299c15b7b85"+ },+ {+ "check": "native_provider",+ "status": "passed",+ "python": "3.14.7",+ "command": "<hermes-python> -B scripts/check_provider_apis.py --hermes-source <clean-hermes> --report <metadata-report>",+ "case_count": 9,+ "case_names": [+ "responses_text",+ "responses_tool",+ "responses_incomplete",+ "responses_codex",+ "responses_codex_reasoning",+ "anthropic_text",+ "anthropic_tool",+ "anthropic_refusal",+ "anthropic_signed"+ ],+ "script_sha256": "acae5d374986f4bca21f5bac2c8eefc6bac1c2e665fea58a3e11793eadc3d546"+ },+ {+ "check": "native_conversations",+ "status": "passed",+ "python": "3.14.7",+ "command": "<hermes-python> -B scripts/check_native_conversations.py --hermes-source <clean-hermes> --report <metadata-report>",+ "case_count": 4,+ "case_names": [+ "responses_manual",+ "responses_auto_tool",+ "anthropic_manual",+ "anthropic_auto_tool"+ ],+ "script_sha256": "05c8eb9bf37ab1a322f4f3255946c9015614def0dea9372f8a732d0e18fa9828"+ }+ ]+ },+ {+ "source": "current",+ "commit": "46d7718a52ff33accb15dc0501736fbdb6833cab",+ "clean": true,+ "checks": [+ {+ "check": "middleware",+ "status": "passed",+ "python": "3.14.7",+ "command": "<hermes-python> -B scripts/check_hermes_compatibility.py --hermes-source <clean-hermes> --report <metadata-report>",+ "case_count": 4,+ "case_names": [+ "capture_last",+ "earlier_rewrite",+ "later_rewrite",+ "unknown_order"+ ],+ "script_sha256": "641b1acb9a311ebad570c4a06800ff866030471db3b4d745148244b2e8ca75c0"+ },+ {+ "check": "plugin_integration",+ "status": "passed",+ "python": "3.14.5",+ "command": "<hermes-python> -B scripts/check_plugin_hermes.py --hermes-source <clean-hermes> --report <metadata-report>",+ "case_count": 9,+ "case_names": [+ "enable_manual_warm",+ "manual_context",+ "manual_whitespace",+ "manual_fallback",+ "manual_fixed",+ "auto_tool_loop",+ "auto_context_tool",+ "auto_warm_failures",+ "rollback"+ ],+ "script_sha256": "e476408c2a3d7322cd008a9a612edc3f4eb4a3cd91f6af95ed06b299c15b7b85"+ },+ {+ "check": "native_provider",+ "status": "passed",+ "python": "3.14.7",+ "command": "<hermes-python> -B scripts/check_provider_apis.py --hermes-source <clean-hermes> --report <metadata-report>",+ "case_count": 9,+ "case_names": [+ "responses_text",+ "responses_tool",+ "responses_incomplete",+ "responses_codex",+ "responses_codex_reasoning",+ "anthropic_text",+ "anthropic_tool",+ "anthropic_refusal",+ "anthropic_signed"+ ],+ "script_sha256": "acae5d374986f4bca21f5bac2c8eefc6bac1c2e665fea58a3e11793eadc3d546"+ },+ {+ "check": "native_conversations",+ "status": "passed",+ "python": "3.14.7",+ "command": "<hermes-python> -B scripts/check_native_conversations.py --hermes-source <clean-hermes> --report <metadata-report>",+ "case_count": 4,+ "case_names": [+ "responses_manual",+ "responses_auto_tool",+ "anthropic_manual",+ "anthropic_auto_tool"+ ],+ "script_sha256": "05c8eb9bf37ab1a322f4f3255946c9015614def0dea9372f8a732d0e18fa9828"+ }+ ]+ }+ ],+ "reported_host": {+ "commit": "d0288be5b3330d2442e3907185b8e9d0958297bb",+ "clean": true,+ "admission_status": "unavailable",+ "available_validation_checks_passed": 13,+ "missing_validation_check": "no core override",+ "conversation_worker_ran": false,+ "source_observation": "The inspected hook passes stored messages as conversation_history. It passes request_messages separately.",+ "limit": "The reported assembled capture was reproduced with synthetic rows. Its exact running hook contract remains unknown."+ },+ "live_model_run_in_this_record": false,+ "cache_reuse_proved": false,+ "performance_qualification": false,+ "limits": [+ "Loopback replies use fake counters. They do not prove live cache reuse or a speed gain.",+ "Live route checks have a separate receipt. These checks do not prove the reporter's deployment."+ ],+ "tested_plugin_sha256": {+ "__init__.py": "760484ace80b9da77d7397828f69178905c9ac95df7b8114956bde727bd98aef",+ "anthropic.py": "7bd4cb0e075c4f279f62d3b6f0c3dcf7405308c7360f9136369476a59dca4fd3",+ "capture.py": "d2ce12d20fca5649d94b17d376a7bd9e21ba7f6a828b94cb62d030ca55adf791",+ "engine.py": "368b4ec95f31d0f6fc868f6184730d513e02f61764be60a1fabdb00cdececfd6",+ "fallback.py": "9b2d0529767ff157bbe0d1cbf096ca6ac35217118f81eee769adf41d50189a9a",+ "handoff.py": "fcab51def8fbcc2b1928957930c9a5c58a4ad202c949fd9f870a77f3b30276ae",+ "layout.py": "3722ca05a4b84c9ed9f5cef5c7f7a175201efaba4208f3819dabcc556a2cfd57",+ "native.py": "2bac322bf7779e7d4ec78137a1ba1fdff25d3e58910ace51200147aebf15f494",+ "plugin.yaml": "baa7820b3ce9a40d2a53f70a4d0525131860ea2ec670143d0a7742b59c4d937b",+ "protocol.py": "f319d7a38ebb60d68d09b3575fe4f88f324b03be6017efbc5fd9932f05299853",+ "responses.py": "70c8c912b39b377945488f4fb68f032ca0aa9be5a4340df0c1af7fd5961ee103",+ "rows.py": "656d1eb02d7d31d51b89937a50878a8235093d82e8fbbab76526d80f8b182d80",+ "warm.py": "153ea2d3add81cec6abf2ca5e3873a6d83ed9d5772f711fb1aefb60fe3e11662"+ },+ "normalized_plugin_sha256": {+ "anthropic.py": "7bd4cb0e075c4f279f62d3b6f0c3dcf7405308c7360f9136369476a59dca4fd3",+ "capture.py": "d2ce12d20fca5649d94b17d376a7bd9e21ba7f6a828b94cb62d030ca55adf791",+ "engine.py": "368b4ec95f31d0f6fc868f6184730d513e02f61764be60a1fabdb00cdececfd6",+ "fallback.py": "9b2d0529767ff157bbe0d1cbf096ca6ac35217118f81eee769adf41d50189a9a",+ "handoff.py": "fcab51def8fbcc2b1928957930c9a5c58a4ad202c949fd9f870a77f3b30276ae",+ "layout.py": "3722ca05a4b84c9ed9f5cef5c7f7a175201efaba4208f3819dabcc556a2cfd57",+ "native.py": "2bac322bf7779e7d4ec78137a1ba1fdff25d3e58910ace51200147aebf15f494",+ "plugin.yaml": "baa7820b3ce9a40d2a53f70a4d0525131860ea2ec670143d0a7742b59c4d937b",+ "protocol.py": "f319d7a38ebb60d68d09b3575fe4f88f324b03be6017efbc5fd9932f05299853",+ "responses.py": "70c8c912b39b377945488f4fb68f032ca0aa9be5a4340df0c1af7fd5961ee103",+ "rows.py": "656d1eb02d7d31d51b89937a50878a8235093d82e8fbbab76526d80f8b182d80",+ "warm.py": "84c66a79dc6b3d4d5b641a8b48d1341e5e765d31f07126ff3fd6108ac01cb3b9",+ "__init__.py": "760484ace80b9da77d7397828f69178905c9ac95df7b8114956bde727bd98aef"+ },+ "source_byte_relation": {+ "file": "warm.py",+ "change": "CRLF to LF only",+ "compiled_code_identical": true,+ "comparison_python": "3.14.5"+ }+}diff --git a/scripts/check_plugin_hermes.py b/scripts/check_plugin_hermes.pyindex eef9cf4..634abb9 100644--- a/scripts/check_plugin_hermes.py+++ b/scripts/check_plugin_hermes.py@@ -38,8 +38,13 @@ SEED_QUESTION = "What is the code word?"NEXT_QUESTION = "What is the next step?"TOOL_QUESTION = "Call the note tool, then answer."TOOL_AGAIN_QUESTION = "Call the note tool again, then answer."+CONTEXT_QUESTION = "Context check: what is the code word?"+CONTEXT_TOOL_QUESTION = "Context check: call the note tool, then answer."+CONTEXT_TOOL_AGAIN_QUESTION = "Context check: call the note tool again, then answer."+INJECTED_CONTEXT = "Synthetic plugin context: keep the code word BLUE-7."WHITESPACE_QUESTIONS = ("Hello there ", "Hello there\n")-QUESTIONS = (SEED_QUESTION, NEXT_QUESTION, TOOL_QUESTION, TOOL_AGAIN_QUESTION, "Hello there")+QUESTIONS = (SEED_QUESTION, NEXT_QUESTION, TOOL_QUESTION, TOOL_AGAIN_QUESTION, "Hello there",+ CONTEXT_QUESTION, CONTEXT_TOOL_QUESTION, CONTEXT_TOOL_AGAIN_QUESTION)HANDOFF = ("## Goal\nFinish the synthetic test task.\n\n""## User instructions\n- \"Answer in one short sentence.\"\n\n"@@ -54,21 +59,27 @@ TOOL_PLUGIN = {"plugin.yaml": ("manifest_version: 2\nname: wc_test_tools\nversion: 0.0.1\n""description: \"Test tool for the warm_compaction integration check.\"\nkind: standalone\n"+ "provides_hooks:\n - pre_llm_call\n"),"__init__.py": ('"""Test tool plugin for the warm_compaction integration check."""\n\nimport json\n\n\n'"def _note(args, **_kwargs):\n"' return json.dumps({"note": "The test note says BLUE-7."})\n\n\n'+ "def _context(user_message=None, **_kwargs):\n"+ ' if isinstance(user_message, str) and user_message.startswith("Context check:"):\n'+ f' return {{"context": {INJECTED_CONTEXT!r}}}\n'+ " return None\n\n\n""def register(ctx):\n"+ ' ctx.register_hook("pre_llm_call", _context)\n'' ctx.register_tool(name="wc_note", toolset="wc_test", handler=_note, schema={\n'' "name": "wc_note", "description": "Return a fixed test note.",\n'' "parameters": {"type": "object", "properties": {}, "required": []}})\n'),}-SCENARIOS = ("enable_manual_warm", "manual_whitespace", "manual_fallback", "manual_fixed", "auto_tool_loop",- "auto_warm_failures", "rollback")+SCENARIOS = ("enable_manual_warm", "manual_context", "manual_whitespace", "manual_fallback", "manual_fixed",+ "auto_tool_loop", "auto_context_tool", "auto_warm_failures", "rollback")# The scenarios with automatic compaction in a tool loop.-AUTO_SCENARIOS = ("auto_tool_loop", "auto_warm_failures")+AUTO_SCENARIOS = ("auto_tool_loop", "auto_context_tool", "auto_warm_failures")NOTICE_MARK = "Warm compaction unavailable"NATIVE_NOTICE_MARK = "Hermes includes native warm handoff."# The rollback scenario has a third process: a new Hermes process with the built-in compressor.@@ -115,7 +126,8 @@ def classify(body) -> str:if last.get("role") == "user" and str(last.get("content") or "").startswith(WARM_MARK):return "warm"users = [row for row in messages if row.get("role") == "user"]- if users and str(users[-1].get("content") or "") in QUESTIONS:+ if users and str(users[-1].get("content") or "") in (+ *QUESTIONS, *(question + "\n\n" + INJECTED_CONTEXT for question in QUESTIONS)):return "main"return "other"@@ -361,7 +373,7 @@ def plan_for(scenario):if scenario == "manual_whitespace":return {"main": [{"content": "The code word is BLUE-7."}, {"content": "Hello."},{"content": "Hello again."}]}- if scenario in ("enable_manual_warm", "rollback"):+ if scenario in ("enable_manual_warm", "manual_context", "rollback"):return {"main": [{"content": "The code word is BLUE-7."}, {"content": "Next: report BLUE-7."}]}if scenario == "manual_fallback":return {"warm_status": 500, "main": [{"content": "The code word is BLUE-7."}, {"content": "Next."}]}@@ -375,7 +387,7 @@ def plan_for(scenario):main += [{"tool": {"id": f"call_{index + 1}", "name": "wc_note"}, "prompt_tokens": 150_000},{"content": f"Done {index + 1}.", "prompt_tokens": 20_000}]return {"warm_fail_first": 3, "main": main}- if scenario == "auto_tool_loop":+ if scenario in ("auto_tool_loop", "auto_context_tool"):return {"main": [{"tool": {"id": "call_1", "name": "wc_note"}, "prompt_tokens": 150_000},{"content": "Done.", "prompt_tokens": 20_000},@@ -453,7 +465,7 @@ def install_phase(spec, session_dir):documented = scenario == "enable_manual_warm"cmd_install(spec["plugin_url"], enable=documented)names = ["warm_compaction"]- if scenario in AUTO_SCENARIOS:+ if scenario in (*AUTO_SCENARIOS, "manual_context"):cmd_install(spec["tool_plugin_url"], enable=False)names.append("wc_test_tools")if not documented:@@ -540,7 +552,7 @@ def run_phase(spec, session_dir):"context_length": engine.context_length}checks["native_notice_not_logged_before_compaction"] = NATIVE_NOTICE_MARK not in read_agent_log(home)history = db.get_messages_as_conversation(sid)- if scenario == "auto_tool_loop":+ if scenario in ("auto_tool_loop", "auto_context_tool"):run_auto(agent, engine, history, server, result, checks, statuses)elif scenario == "auto_warm_failures":run_auto_failures(agent, engine, history, server, result, checks, statuses, home)@@ -765,7 +777,8 @@ def check_native_notice(agent, engine, db, server, result, checks, statuses, homdef run_manual(agent, engine, db, history, server, result, checks, scenario, compress, finalize):- seed = agent.run_conversation(SEED_QUESTION, system_message=SYSTEM, conversation_history=history)+ question = CONTEXT_QUESTION if scenario == "manual_context" else SEED_QUESTION+ seed = agent.run_conversation(question, system_message=SYSTEM, conversation_history=history)messages = seed.get("messages") or []checks["seed_turn"] = len(messages) == len(history) + 2session = {"agent": agent, "history": list(messages), "history_lock": threading.Lock(),@@ -773,6 +786,8 @@ def run_manual(agent, engine, db, history, server, result, checks, scenario, com# The capture keeps the prompt count that the server reported, through the real post_api_request hook.capture = engine._store.latest(engine._wc_session_id) or {}seed_request = by_kind(server, "main")[-1]+ if scenario == "manual_context":+ check_injected_context(messages, seed_request, checks, "manual", question)checks["capture_keeps_reported_prompt_tokens"] = capture.get("prompt_tokens") == len(json.dumps(seed_request["body"]["messages"])) // 4begin = time.perf_counter()@@ -786,7 +801,8 @@ def run_manual(agent, engine, db, history, server, result, checks, scenario, comresult["compress_seconds"] = round(time.perf_counter() - begin, 3)warm_last = dict(engine.warm_last or {})result["warm_last"] = warm_last- expected = {"enable_manual_warm": ("warm", "accepted"), "manual_fallback": ("fallback", "provider_error"),+ expected = {"enable_manual_warm": ("warm", "accepted"), "manual_context": ("warm", "accepted"),+ "manual_fallback": ("fallback", "provider_error"),"manual_fixed": ("fixed", "provider_error"), "rollback": ("warm", "accepted")}[scenario]checks["path_and_reason"] = (warm_last.get("path"), warm_last.get("reason")) == expectedchecks["removed_rows"] = removed > 0@@ -794,7 +810,7 @@ def run_manual(agent, engine, db, history, server, result, checks, scenario, comchecks["native_notice_not_in_manual_history"] = NATIVE_NOTICE_MARK not in json.dumps(after)checks["summary_rows"] = summary_rows_ok(after)checks["tail_starts_with_user"] = after[2].get("role") == "user"- if scenario == "enable_manual_warm":+ if scenario in ("enable_manual_warm", "manual_context"):check_warm_request(server, checks, "warm")checks["handoff_in_summary"] = HANDOFF in str(after[1].get("content"))checks["no_fallback_request"] = not by_kind(server, "fallback")@@ -868,9 +884,21 @@ def run_manual_whitespace(agent, engine, db, history, server, result, checks, cochecks["no_fallback_request"] = not by_kind(server, "fallback")+def check_injected_context(messages, request, checks, label, question):+ """Check the host's stored row and wire text after the real context hook runs."""+ stored = [row for row in messages if row.get("role") == "user" and row.get("content") == question]+ checks[f"{label}_display_question_exact"] = len(stored) == 1+ effective = question + "\n\n" + INJECTED_CONTEXT+ checks[f"{label}_context_sidecar_exact"] = len(stored) == 1 and stored[0].get("api_content") == effective+ checks[f"{label}_context_sent_exact"] = any(+ row.get("role") == "user" and row.get("content") == effective for row in request["body"]["messages"])++def run_auto(agent, engine, history, server, result, checks, statuses):checks["threshold_from_settings"] = engine.threshold_tokens == int(CONTEXT_LENGTH * 0.4)- first = agent.run_conversation(TOOL_QUESTION, system_message=SYSTEM, conversation_history=history)+ context_case = result["scenario"] == "auto_context_tool"+ question = CONTEXT_TOOL_QUESTION if context_case else TOOL_QUESTION+ first = agent.run_conversation(question, system_message=SYSTEM, conversation_history=history)first_notice_count = sum(NATIVE_NOTICE_MARK in message for _kind, message in statuses)checks["native_notice_on_first_automatic_compaction"] = (first_notice_count == int(result["native_warm_handoff"]["available"]))@@ -881,11 +909,16 @@ def run_auto(agent, engine, history, server, result, checks, statuses):if by_kind(server, "warm"):check_warm_request(server, checks, "auto1", tool_rows=1)after_first = first.get("messages") or []+ if context_case:+ check_injected_context(after_first, by_kind(server, "main")[0], checks, "auto1", question)checks["first_summary_rows"] = summary_rows_ok(after_first)checks["wait_flag_cleared"] = engine.awaiting_real_usage_after_compression is False- second = agent.run_conversation(TOOL_AGAIN_QUESTION, system_message=SYSTEM,+ question = CONTEXT_TOOL_AGAIN_QUESTION if context_case else TOOL_AGAIN_QUESTION+ second = agent.run_conversation(question, system_message=SYSTEM,conversation_history=list(after_first))checks["second_turn_final"] = second.get("final_response") == "Done again."+ if context_case:+ check_injected_context(second.get("messages") or [], by_kind(server, "main")[-1], checks, "auto2", question)checks["native_notice_not_repeated"] = (sum(NATIVE_NOTICE_MARK in message for _kind, message in statuses) == first_notice_count)checks["native_notice_not_in_automatic_history"] = all(diff --git a/tests/test_wc_anthropic.py b/tests/test_wc_anthropic.pyindex b37c9d0..4156ed8 100644--- a/tests/test_wc_anthropic.py+++ b/tests/test_wc_anthropic.py@@ -110,7 +110,7 @@ class BuildTest(unittest.TestCase):def test_missing_tool_result_and_changed_route_are_refused(self):reply = assistant("call", [("c1", "read", "{}")])cap = capture(self.rows, reply)- self.refusal("history_changed", lambda: self.build(cap, [*self.rows, reply]))+ self.refusal("history_changed:tool_count", lambda: self.build(cap, [*self.rows, reply]))cap["route"] = ("changed", *ROUTE[1:])self.refusal("route_changed", lambda: self.build(cap))diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.pyindex 979ff9b..9bb1688 100644--- a/tests/test_wc_engine.py+++ b/tests/test_wc_engine.py@@ -149,6 +149,31 @@ class EngineTest(unittest.TestCase):self.assertEqual([row["role"] for row in new], ["user", "assistant", "user", "assistant", "tool"])self.assertEqual(new[2], {"role": "user", "content": "run the tool"})+ def test_assembled_context_capture_keeps_the_warm_prefix(self):+ rows = [*old_turns(), user("synthetic question", api_content="[synthetic context]\n\nsynthetic question")]+ assembled = copy.deepcopy(rows)+ assembled[-1]["content"] = assembled[-1].pop("api_content")+ reply = assistant("synthetic answer")+ self.seed(assembled, reply)+ new = self.engine.compress([*rows, reply])+ self.assertEqual((self.engine.warm_last["path"], self.engine.warm_last["reason"]), ("warm", "accepted"))+ self.assertEqual(self.post.calls[0]["body"]["messages"][:len(rows) + 1], [SYSTEM, *wire(assembled)])+ self.assertEqual(new[-2:], [rows[-1], reply])+ self.assertEqual(self.llm.calls, [])++ def test_capture_ahead_uses_only_live_rows_for_fallback(self):+ rows = [*old_turns(), user("synthetic live question")]+ future = [assistant("synthetic unmatched future reply"), tool("future-call", "future result")]+ self.seed([*rows, *future], assistant("captured answer"))+ original = copy.deepcopy(rows)+ new = self.engine.compress(rows)+ self.assertEqual((self.engine.warm_last["path"], self.engine.warm_last["reason"]),+ ("fallback", "history_changed:capture_ahead"))+ self.assertEqual(self.post.calls, [])+ self.assertNotIn("synthetic unmatched future reply", json.dumps(self.llm.calls))+ self.assertNotIn("future result", json.dumps(new))+ self.assertEqual(rows, original)+def test_fallback_without_a_capture(self):new = self.engine.compress([*old_turns(), assistant("done")])self.assertEqual((self.engine.warm_last["path"], self.engine.warm_last["reason"]), ("fallback", "no_capture"))diff --git a/tests/test_wc_rows.py b/tests/test_wc_rows.pyindex e43e8eb..a2ee62a 100644--- a/tests/test_wc_rows.py+++ b/tests/test_wc_rows.py@@ -62,6 +62,38 @@ class RowsTest(unittest.TestCase):self.assertNotEqual(row_digest(base), row_digest(other))self.assertEqual(len(row_digest(base)), 64)+ def test_digest_uses_effective_content_without_string_identity(self):+ for role in ("user", "assistant"):+ with self.subTest(role=role):+ base = {"role": role, "content": "synthetic sent text"}+ sidecar = "".join(("synthetic sent", " text"))+ self.assertEqual(row_digest(base), row_digest(dict(base, api_content=sidecar)))+ self.assertEqual(row_digest(base), row_digest(dict(base, content="display text", api_content=sidecar)))+ for unused in (None, "", 42, ["synthetic sent text"]):+ self.assertEqual(row_digest(base), row_digest(dict(base, api_content=unused)))++ def test_effective_content_does_not_hide_checked_field_changes(self):+ base = {"role": "assistant", "content": "display text", "api_content": "synthetic sent text"}+ changes = {"role": "user", "content": "changed", "api_content": "changed", "name": "synthetic-name",+ "tool_call_id": "synthetic-call", "tool_calls": [+ {"id": "c1", "function": {"name": "read", "arguments": "{}"}}]}+ # Display text can change when the exact sent text stays. All checked fields must still match.+ self.assertEqual(row_digest(base), row_digest(dict(base, content=changes.pop("content"))))+ for field in ("reasoning_content", "reasoning_details", "codex_message_items", "codex_reasoning_items",+ "codex_checkpoint_items", "codex_reasoning_trimmed", "phase", "anthropic_content_blocks",+ "_anthropic_content_blocks", "call_id", "response_item_id"):+ changes[field] = "synthetic-change"+ for field, value in changes.items():+ with self.subTest(field=field):+ self.assertNotEqual(row_digest(base), row_digest(dict(base, **{field: value})))++ def test_sidecars_do_not_replace_content_on_other_roles(self):+ for role in ("system", "developer", "tool"):+ with self.subTest(role=role):+ base = {"role": role, "content": "synthetic text"}+ self.assertEqual(row_digest(base), row_digest(dict(base, api_content="other text")))+ self.assertNotEqual(row_digest(base), row_digest(dict(base, content="other text")))+if __name__ == "__main__":unittest.main()diff --git a/tests/test_wc_warm.py b/tests/test_wc_warm.pyindex 3006d28..8dc9b83 100644--- a/tests/test_wc_warm.py+++ b/tests/test_wc_warm.py@@ -41,17 +41,35 @@ class SplitHistoryTest(unittest.TestCase):reply = assistant("", [("c1", "read", "{}")])capture = capture_for(rows, reply)cases = {- "changed row": [user("u1"), assistant("other"), user("u2"), reply, tool("c1", "r")],- "no reply": rows,- "other reply": [*rows, assistant("", [("c9", "read", "{}")]), tool("c9", "r")],- "missing tool row": [*rows, reply],- "unknown tool row": [*rows, reply, tool("c1", "r"), tool("c7", "r")],- "assistant after tools": [*rows, reply, tool("c1", "r"), assistant("next")],+ "history_changed:digest": [user("u1"), assistant("other"), user("u2"), reply, tool("c1", "r")],+ "history_changed:reply_missing": rows,+ "history_changed:capture_ahead": rows[:-1],+ "history_changed:reply": [*rows, assistant("", [("c9", "read", "{}")]), tool("c9", "r")],+ "history_changed:tool_count": [*rows, reply],+ "history_changed:trailing": [*rows, reply, tool("c1", "r"), assistant("next")],}for label, messages in cases.items():with self.subTest(label), self.assertRaises(WarmRefusal) as caught:split_history(capture, messages)- self.assertEqual(caught.exception.code, "history_changed")+ self.assertEqual(caught.exception.args, (label,))++ def test_capture_ahead_cannot_use_a_matching_earlier_reply(self):+ rows = history()+ reply = assistant("synthetic answer")+ capture = capture_for([*rows, reply, user("future synthetic question")], reply)+ with self.assertRaises(WarmRefusal) as caught:+ split_history(capture, [*rows, reply])+ self.assertEqual(caught.exception.args, ("history_changed:capture_ahead",))++ def test_extra_or_missing_tool_results_have_a_fixed_code(self):+ rows = history()+ reply = assistant("", [("c1", "read", "{}"), ("c2", "read", "{}")])+ capture = capture_for(rows, reply)+ for results, code in (([tool("c1", "r")], "tool_count"),+ ([tool("c1", "r"), tool("c2", "r"), tool("c7", "r")], "tool_extra")):+ with self.subTest(results=results), self.assertRaises(WarmRefusal) as caught:+ split_history(capture, [*rows, reply, *results])+ self.assertEqual(caught.exception.args, ("history_changed:" + code,))class RepeatedCallIdTest(unittest.TestCase):@@ -68,6 +86,17 @@ class RepeatedCallIdTest(unittest.TestCase):class ApiContentHistoryTest(unittest.TestCase):+ def test_assembled_capture_matches_stored_context(self):+ rows = [user("synthetic question", api_content="[synthetic context]\n\nsynthetic question"),+ assistant("display reply", api_content="synthetic sent reply"), user("next question")]+ assembled = copy.deepcopy(rows)+ for row in assembled:+ if "api_content" in row:+ row["content"] = row.pop("api_content")+ reply = assistant("synthetic answer")+ capture = capture_for(assembled, reply)+ self.assertEqual(split_history(capture, [*rows, reply]), ([reply], []))+def test_the_reply_matches_by_its_api_content(self):rows = history()capture = capture_for(rows, assistant("The answer is 4."))diff --git a/warm_compaction/rows.py b/warm_compaction/rows.pyindex 8940085..6141e44 100644--- a/warm_compaction/rows.py+++ b/warm_compaction/rows.py@@ -262,16 +262,17 @@ def estimate_tokens(value: Any) -> int:def row_digest(row: Any) -> str:- """Return the SHA-256 of the canonical JSON of the row fields that the model sees, with the api_content- sidecar of a user or assistant row."""+ """Return the SHA-256 of the effective content and the checked row fields.++ Hermes can pass assembled content to the hook and keep the same text in stored api_content.+ Both forms must have the same digest. Role, tool, and native replay fields stay in the digest.+ """canonical = {"role": attr(row, "role"),- "content": attr(row, "content"),+ "content": api_content(row),"tool_call_id": attr(row, "tool_call_id"),"name": attr(row, "name"),"tool_calls": [list(call) for call in tool_calls_of(row)],- # The text that the provider saw, when Hermes keeps it in the api_content sidecar.- "api_content": api_content(row) if api_content(row) is not attr(row, "content") else None,# Native replay fields can change the provider input without changing the visible text."native": {name: attr(row, name) for name in ("reasoning_content", "reasoning_details", "codex_message_items", "codex_reasoning_items",diff --git a/warm_compaction/warm.py b/warm_compaction/warm.pyindex 71fc66e..ba4f705 100644--- a/warm_compaction/warm.py+++ b/warm_compaction/warm.py@@ -53,11 +53,15 @@ def split_history(capture: dict[str, Any], messages: list) -> tuple[list, list]:"""Return (new rows, trailing user rows) after the captured rows. Refuse a changed history."""digests = capture["digests"]count = len(digests)- if len(messages) <= count or [row_digest(row) for row in messages[:count]] != digests:- raise WarmRefusal("history_changed")+ if len(messages) < count:+ raise WarmRefusal("history_changed:capture_ahead")+ if [row_digest(row) for row in messages[:count]] != digests:+ raise WarmRefusal("history_changed:digest")+ if len(messages) == count:+ raise WarmRefusal("history_changed:reply_missing")rest = messages[count:]if not _matches_reply(rest[0], capture["reply"]):- raise WarmRefusal("history_changed")+ raise WarmRefusal("history_changed:reply")# A multiset: one tool row for each tool call, also when an id repeats.expected = collections.Counter(call_id for call_id, _name in capture["reply"]["tool_calls"])answered: collections.Counter = collections.Counter()@@ -65,14 +69,14 @@ def split_history(capture: dict[str, Any], messages: list) -> tuple[list, list]:while index < len(rest) and attr(rest[index], "role") == "tool":call_id = attr(rest[index], "tool_call_id")if answered[call_id] >= expected[call_id]:- raise WarmRefusal("history_changed")+ raise WarmRefusal("history_changed:tool_extra")answered[call_id] += 1index += 1if answered != expected:- raise WarmRefusal("history_changed")+ raise WarmRefusal("history_changed:tool_count")trailing = rest[index:]if any(attr(row, "role") != "user" for row in trailing):- raise WarmRefusal("history_changed")+ raise WarmRefusal("history_changed:trailing")return rest[:index], trailing