Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix
Add lint CI, a wider test matrix, Dependabot, and the contributing, security, and conduct files
Elevatormusic4b4a9b98d44b
diff --git a/.editorconfig b/.editorconfignew file mode 100644index 0000000..1b26674--- /dev/null+++ b/.editorconfig@@ -0,0 +1,15 @@+root = true++[*]+charset = utf-8+end_of_line = lf+insert_final_newline = true+trim_trailing_whitespace = true+indent_style = space+indent_size = 4++[*.{yml,yaml,json,md}]+indent_size = 2++[*.md]+trim_trailing_whitespace = falsediff --git a/.github/CODEOWNERS b/.github/CODEOWNERSnew file mode 100644index 0000000..c5467f1--- /dev/null+++ b/.github/CODEOWNERS@@ -0,0 +1 @@+* @Elevatormusicdiff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlnew file mode 100644index 0000000..584a1c2--- /dev/null+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -0,0 +1,45 @@+name: Bug report+description: The plugin does something wrong or fails.+labels: ["bug"]+body:+ - type: markdown+ attributes:+ value: |+ Do not paste private conversations, API keys, or full request bodies. For a security problem, use the Security tab instead (see SECURITY.md).+ - type: textarea+ id: what+ attributes:+ label: What happened+ description: What you did, what you expected, and what happened.+ validations:+ required: true+ - type: textarea+ id: log+ attributes:+ label: warm_compaction log lines+ description: The `warm_compaction:` lines from `logs/agent.log`. They have the path, the reason, and the time, and no conversation text.+ render: text+ - type: input+ id: plugin+ attributes:+ label: Plugin version or commit+ validations:+ required: true+ - type: input+ id: hermes+ attributes:+ label: Hermes Agent commit or version+ validations:+ required: true+ - type: input+ id: route+ attributes:+ label: API mode and server+ description: For example `chat_completions` on vLLM 0.x, llama.cpp, LM Studio, or a hosted API.+ validations:+ required: true+ - type: textarea+ id: steps+ attributes:+ label: Steps to reproduce+ description: Use a synthetic conversation if you can.diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.ymlnew file mode 100644index 0000000..530689b--- /dev/null+++ b/.github/ISSUE_TEMPLATE/config.yml@@ -0,0 +1,8 @@+blank_issues_enabled: false+contact_links:+ - name: Security problem+ url: https://github.com/Elevatormusic/hermes-warm-compaction/security/advisories/new+ about: Report a vulnerability privately. Do not open a public issue.+ - name: Hermes Agent problem+ url: https://github.com/NousResearch/hermes-agent/issues+ about: A problem in Hermes Agent itself, not in this plugin.diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.ymlnew file mode 100644index 0000000..97cb79b--- /dev/null+++ b/.github/ISSUE_TEMPLATE/feature_request.yml@@ -0,0 +1,21 @@+name: Feature request+description: Propose a change or a new capability.+labels: ["enhancement"]+body:+ - type: textarea+ id: problem+ attributes:+ label: Problem+ description: What do you want to do that the plugin does not do now?+ validations:+ required: true+ - type: textarea+ id: proposal+ attributes:+ label: Proposal+ description: How could the plugin do it? The plugin uses documented Hermes plugin APIs only.+ - type: textarea+ id: context+ attributes:+ label: Server and setup+ description: The server, model, and API mode where you need it, if it matters.diff --git a/.github/dependabot.yml b/.github/dependabot.ymlnew file mode 100644index 0000000..c5ef447--- /dev/null+++ b/.github/dependabot.yml@@ -0,0 +1,10 @@+version: 2+updates:+ # The plugin has no Python dependency. Only the CI actions get updates.+ - package-ecosystem: github-actions+ directory: /+ schedule:+ interval: weekly+ groups:+ actions:+ patterns: ["*"]diff --git a/.github/pull_request_template.md b/.github/pull_request_template.mdnew file mode 100644index 0000000..5b31c76--- /dev/null+++ b/.github/pull_request_template.md@@ -0,0 +1,13 @@+## What and why++<!-- What this change does, and the problem it fixes. Link the issue. -->++## How it was tested++<!-- The new test that failed before the change, and the checks you ran. -->++- [ ] `python -m unittest discover -s tests -p "test_wc_*.py"` passes+- [ ] `ruff check .` passes+- [ ] The integration check passes on a clean Hermes checkout (when the change touches Hermes behavior)+- [ ] README Limits and CHANGELOG are updated (when behavior changes)+- [ ] No private conversation, key, or full request body in the changediff --git a/.github/workflows/lint.yml b/.github/workflows/lint.ymlnew file mode 100644index 0000000..11c3f83--- /dev/null+++ b/.github/workflows/lint.yml@@ -0,0 +1,31 @@+name: lint++on:+ push:+ branches: [main]+ pull_request:++permissions:+ contents: read++concurrency:+ group: ${{ github.workflow }}-${{ github.ref }}+ cancel-in-progress: true++jobs:+ ruff:+ runs-on: ubuntu-latest+ timeout-minutes: 10+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: "3.12"+ - name: Install ruff+ run: python -m pip install ruff==0.16.10+ - name: Lint+ run: ruff check --output-format=github .+ - name: Compile with the oldest supported Python syntax+ run: python -m compileall -q warm_compaction scripts testsdiff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex 70f0b4d..02b916e 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -8,16 +8,40 @@ on:permissions:contents: read+concurrency:+ group: ${{ github.workflow }}-${{ github.ref }}+ cancel-in-progress: true+jobs:unit:- runs-on: ubuntu-latest+ name: unit (${{ matrix.os }}, ${{ matrix.python-version }})+ runs-on: ${{ matrix.os }}+ timeout-minutes: 15strategy:+ fail-fast: falsematrix:+ os: [ubuntu-latest]python-version: ["3.10", "3.11", "3.12", "3.13"]+ include:+ - os: windows-latest+ python-version: "3.12"+ - os: macos-latest+ python-version: "3.12"steps:- - uses: actions/checkout@v4- - uses: actions/setup-python@v5+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0with:python-version: ${{ matrix.python-version }}- name: Unit testsrun: python -m unittest discover -s tests -p "test_wc_*.py" -v++ # One stable check name for branch protection: it passes only when every unit job passed.+ tests-passed:+ if: always()+ needs: unit+ runs-on: ubuntu-latest+ steps:+ - name: All unit jobs passed+ run: test "${{ needs.unit.result }}" = "success"diff --git a/CHANGELOG.md b/CHANGELOG.mdnew file mode 100644index 0000000..ccb48fc--- /dev/null+++ b/CHANGELOG.md@@ -0,0 +1,18 @@+# Changelog++All notable changes are listed here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the versions follow [Semantic Versioning](https://semver.org/).++## [0.2.0] - 2026-10-06++First public release.++### Added++- `warm_compaction` context engine for unpatched Hermes Agent (`45871e10` or later), with documented plugin APIs only.+- Warm request: at each compaction, the main model writes the handoff on the cached prefix of the last main-model request. Manual `/compress` and automatic compaction.+- Fallback summary through the Hermes auxiliary model route, and a fixed-format summary without a model request when that also fails.+- Checks before the warm request is sent: route, key, and session identity; middleware rewrites; capacity; the five-heading handoff gate.+- Settings: `threshold`, `tail_tokens`, `user_copy_chars`, `warm`.+- Integration check against real Hermes code and a loopback fake server, and live results on DGX and LM Studio.++[0.2.0]: https://github.com/Elevatormusic/hermes-warm-compaction/releases/tag/v0.2.0diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.mdnew file mode 100644index 0000000..749486e--- /dev/null+++ b/CODE_OF_CONDUCT.md@@ -0,0 +1,7 @@+# Code of conduct++This project follows the [Contributor Covenant, version 2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/).++In short: be respectful, assume good intent, and keep discussion about the work. Harassment, personal attacks, and discrimination are not accepted in issues, pull requests, or any other project space.++To report a problem, contact the maintainer, [@Elevatormusic](https://github.com/Elevatormusic), privately through the contact details on that GitHub profile. Reports are kept confidential. The maintainer can remove content and block participants who break this code.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdnew file mode 100644index 0000000..aa975f6--- /dev/null+++ b/CONTRIBUTING.md@@ -0,0 +1,53 @@+# Contributing++Thank you for your help. This guide tells you how to report a problem, propose a change, and run the checks.++## Report a problem++- For a bug, open an issue with the **Bug report** form. Give the Hermes Agent commit, the plugin version, the API mode, and the server (for example vLLM, llama.cpp, or a hosted API).+- Each compaction writes one `warm_compaction:` line to `logs/agent.log`. Add that line: it has the path (`warm`, `fallback`, or `fixed`), the reason, and the time. It has no conversation text.+- Do not attach private conversations, API keys, or full request bodies. Use a synthetic conversation that shows the problem.+- For a security problem, do not open an issue. See [SECURITY.md](SECURITY.md).++## Propose a change++1. Open an issue first for a large change, so that we can agree on the design.+2. Fork the repository and make a branch from `main`.+3. Write a test that fails without your change. Then make the change.+4. Run the checks below.+5. Open a pull request. Fill in the template.++Keep each pull request to one subject. The plugin uses documented Hermes plugin APIs only: no patch of Hermes, no subclass of the built-in compressor, and no runtime wrapping of Hermes code. A change that needs one of those cannot be merged.++## Run the checks++You need Python 3.10 or later and Git. The plugin has no third-party dependency.++```bash+python -m unittest discover -s tests -p "test_wc_*.py"+```++Lint with [ruff](https://docs.astral.sh/ruff/) (the version that CI uses):++```bash+pip install ruff==0.16.10+ruff check .+```++The integration check runs real Hermes code against a loopback fake server. Run it with the Python of a Hermes virtual environment and a **clean** Hermes checkout, not your installed Hermes:++```bash+<hermes-venv-python> -B scripts/check_plugin_hermes.py --hermes-source <clean-hermes-checkout> --report .work/plugin-integration-report.json+```++CI runs the unit tests on Python 3.10 to 3.13 (Linux) and on Python 3.12 (Windows and macOS), and the lint. A pull request must pass both.++## Style++- Match the code around your change: names, comment density, and line length (120).+- Write comments, docstrings, and documents in short, simple sentences.+- A measured result needs its record in `evidence/` with metadata only. Report a missing counter as unknown.++## License++By contributing, you agree that your contribution is licensed under the [Apache License 2.0](LICENSE). Keep the [NOTICE](NOTICE) file in copies and derivative works.diff --git a/README.md b/README.mdindex ba19eb5..f4ab626 100644--- a/README.md+++ b/README.md@@ -4,6 +4,7 @@<p align="center"><a href="https://github.com/Elevatormusic/hermes-warm-compaction/actions/workflows/tests.yml"><img src="https://github.com/Elevatormusic/hermes-warm-compaction/actions/workflows/tests.yml/badge.svg" alt="Tests"></a>+ <a href="https://github.com/Elevatormusic/hermes-warm-compaction/actions/workflows/lint.yml"><img src="https://github.com/Elevatormusic/hermes-warm-compaction/actions/workflows/lint.yml/badge.svg" alt="Lint"></a><a href="LICENSE"><img src="https://img.shields.io/badge/license-Apache--2.0-FF6B3D" alt="License: Apache-2.0"></a><img src="https://img.shields.io/badge/python-3.10%2B-3776AB" alt="Python 3.10 or later"><a href="https://github.com/NousResearch/hermes-agent"><img src="https://img.shields.io/badge/Hermes%20Agent-45871e10%2B-5E6878" alt="Hermes Agent 45871e10 or later"></a>@@ -234,6 +235,10 @@ Run the integration check on a clean Hermes checkout with the Python of the HermThe integration check installs the plugin with the Hermes install command in a temporary Hermes home. It runs real Hermes conversation and compaction code against a loopback fake server, and it sends no request to a real model. An audit-hook fence blocks other network access, child processes, and writes outside the scenario folder. The report has metadata only.+## Contributing++Bug reports, server results, and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) for the checks, and [SECURITY.md](SECURITY.md) to report a vulnerability privately. Changes are listed in [CHANGELOG.md](CHANGELOG.md).+## License and creditApache License 2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE). A copy, a port, or a derivative work of this code must keep the NOTICE file. If you use this design in Hermes Agent or in a different project, please credit Elevatormusic and link to this repository.diff --git a/SECURITY.md b/SECURITY.mdnew file mode 100644index 0000000..8198a35--- /dev/null+++ b/SECURITY.md@@ -0,0 +1,23 @@+# Security policy++## Supported versions++Only the latest release gets security fixes.++## Report a vulnerability++Do not open a public issue for a security problem.++Use GitHub private vulnerability reporting: go to the **Security** tab of this repository and click **Report a vulnerability**. Give the steps to reproduce, the effect, and the plugin and Hermes Agent versions. Do not include real API keys or private conversations.++You get a first reply within 7 days. When the fix is ready, we publish a security advisory and credit you, unless you ask us not to.++## Scope++The plugin sends the warm request with the credentials and headers of the Hermes main-model route, and it keeps the last request of each session in memory. Problems in these areas are in scope, for example:++- a request that goes to a different route, key, or session than the captured one;+- conversation text or credentials in logs, evidence files, or error messages;+- a summary that replaces history it does not describe.++Problems in Hermes Agent itself go to the [Hermes Agent repository](https://github.com/NousResearch/hermes-agent/security).diff --git a/pyproject.toml b/pyproject.tomlnew file mode 100644index 0000000..a599c11--- /dev/null+++ b/pyproject.toml@@ -0,0 +1,18 @@+# Tool settings only. The plugin installs with `hermes plugins install` and has no package build.++[tool.ruff]+line-length = 120+target-version = "py310"++[tool.ruff.lint]+select = ["E", "F", "W", "B", "UP"]+ignore = [+ # SendPolicy() and similar defaults are immutable NamedTuples: a shared default is safe.+ "B008",+ # zip() of rows and their wire forms: an explicit strict= adds no check that the code needs.+ "B905",+]++[tool.ruff.lint.per-file-ignores]+# SVG markup in f-strings: a wrapped line changes the SVG text.+"assets/make_charts.py" = ["E501"]diff --git a/tests/test_wc_capture.py b/tests/test_wc_capture.pyindex 054098e..b30b943 100644--- a/tests/test_wc_capture.py+++ b/tests/test_wc_capture.py@@ -14,7 +14,8 @@ def request(**extra):def reply_object(content="done", calls=()):- tool_calls = [SimpleNamespace(id=call_id, function=SimpleNamespace(name=name, arguments="{}")) for call_id, name in calls]+ tool_calls = [SimpleNamespace(id=call_id, function=SimpleNamespace(name=name, arguments="{}"))+ for call_id, name in calls]return SimpleNamespace(content=content, tool_calls=tool_calls or None)@@ -85,7 +86,8 @@ class CaptureStoreTest(unittest.TestCase):# A later middleware can change the request after the capture saw it. The capture cannot see that change.def other(request=None, next_call=None, **context):return next_call()- for chain, kept in (([self.store.on_llm_execution, other], False), ([other, self.store.on_llm_execution], True)):+ own = self.store.on_llm_execution+ for chain, kept in (([own, other], False), ([other, own], True)):wc_hermes_stub.CAPTURE_CHAIN[:] = chainwith self.subTest(kept=kept):self.run_request()diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.pyindex 643cf34..845014a 100644--- a/tests/test_wc_engine.py+++ b/tests/test_wc_engine.py@@ -618,7 +618,8 @@ class EngineTest(unittest.TestCase):self.engine.compress([*rows, reply])self.assertEqual(self.engine.warm_last["path"], "warm")headers = self.post.calls[0]["headers"]- self.assertEqual((headers["X-Title"], headers["User-Agent"], headers["X-Gateway-Key"], headers["Authorization"]),+ names = ("X-Title", "User-Agent", "X-Gateway-Key", "Authorization")+ self.assertEqual(tuple(headers[name] for name in names),("Hermes Agent", "allowed-agent", "synthetic-header-secret", "Bearer k"))self.assertNotIn("synthetic-header-secret", json.dumps(self.engine.warm_last))# Without a host factory, the provider profile gives the headers.@@ -838,7 +839,7 @@ class EngineTest(unittest.TestCase):assistant_message=reply_object(rows[-1]))engine.update_model(model="another-model", context_length=64_000, base_url=ROUTE[1], api_key="k",provider="custom", api_mode=ROUTE[2])- new = engine.compress(rows, current_tokens=estimate_tokens(rows) + 1_000)+ engine.compress(rows, current_tokens=estimate_tokens(rows) + 1_000)self.assertEqual(engine.warm_last["reason"], "route_changed")self.assertIsNone(engine._budget_capture(self.store.latest("s1"), rows))@@ -1122,7 +1123,8 @@ class EngineTest(unittest.TestCase):def test_a_fallback_summary_above_the_reserve_goes_to_the_fixed_summary(self):# A dense summary (CJK) can pass the byte gate and still be above the token reserve: the tail would then# cut more than the fallback transcript had.- self.llm = FakeLlm(text=HEADINGS_TEXT.replace("Finish the test task.", "\u76ee\u6807" * 2_500) + "\n" + END_LINE)+ dense = HEADINGS_TEXT.replace("Finish the test task.", "\u76ee\u6807" * 2_500)+ self.llm = FakeLlm(text=dense + "\n" + END_LINE)engine = self.make(warm=False)engine.compress([*old_turns(), assistant("done")])self.assertEqual(engine.warm_last["path"], "fixed")diff --git a/tests/test_wc_fallback.py b/tests/test_wc_fallback.pyindex 57667c7..ca0b3d8 100644--- a/tests/test_wc_fallback.py+++ b/tests/test_wc_fallback.py@@ -33,7 +33,8 @@ class FakeLlm:class TranscriptTest(unittest.TestCase):def test_attachments_are_marked_in_the_transcript(self):- text = transcript([user([{"type": "text", "text": "see"}, {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}]), assistant("ok")], PREFIXES)+ image = {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}+ text = transcript([user([{"type": "text", "text": "see"}, image]), assistant("ok")], PREFIXES)self.assertIn("[first user message]\nsee\n[image attachment]", text)self.assertIn("[user]\nsee\n[image attachment]", text)diff --git a/tests/test_wc_rows.py b/tests/test_wc_rows.pyindex de405cf..e43e8eb 100644--- a/tests/test_wc_rows.py+++ b/tests/test_wc_rows.py@@ -11,7 +11,8 @@ from warm_compaction.rows import (class RowsTest(unittest.TestCase):def test_visible_text_marks_each_non_text_part(self):- content = [{"type": "text", "text": "see"}, {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}},+ content = [{"type": "text", "text": "see"},+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}},{"type": "image_url", "image_url": {"url": "https://example.invalid/a.png"}},{"type": "input_audio", "input_audio": {"data": "AAAA", "format": "wav"}},{"type": "file", "file": {"filename": "report.pdf", "file_data": "AAAA"}}]@@ -26,7 +27,8 @@ class RowsTest(unittest.TestCase):def test_tool_calls_of_reads_rows_and_reply_objects(self):row = {"tool_calls": [{"id": "c1", "function": {"name": "read", "arguments": "{\"p\":1}"}}]}- reply = SimpleNamespace(tool_calls=[SimpleNamespace(id="c2", function=SimpleNamespace(name="ls", arguments="{}"))])+ call = SimpleNamespace(id="c2", function=SimpleNamespace(name="ls", arguments="{}"))+ reply = SimpleNamespace(tool_calls=[call])self.assertEqual(tool_calls_of(row), [("c1", "read", "{\"p\":1}")])self.assertEqual(tool_calls_of(reply), [("c2", "ls", "{}")])self.assertEqual(tool_calls_of({"role": "user"}), [])diff --git a/tests/test_wc_warm.py b/tests/test_wc_warm.pyindex 4eae6b3..668cf3e 100644--- a/tests/test_wc_warm.py+++ b/tests/test_wc_warm.py@@ -7,8 +7,8 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom warm_compaction.rows import estimate_tokensfrom warm_compaction.warm import (- HANDOFF_MAX_TOKENS, ends_with_instruction, HANDOFF_MIN_TOKENS, SAFETY, WarmRefusal, build_request, check_settings, fits, send, split_history, urllib_post,- wire_row,+ HANDOFF_MAX_TOKENS, HANDOFF_MIN_TOKENS, SAFETY, WarmRefusal, build_request, check_settings, ends_with_instruction,+ fits, send, split_history, urllib_post, wire_row,)from wc_fixtures import ROUTE, assistant, capture_for, tool, user@@ -75,7 +75,8 @@ class ApiContentHistoryTest(unittest.TestCase):def test_the_digest_covers_the_api_content(self):from warm_compaction.rows import row_digest- self.assertNotEqual(row_digest(user("hi", api_content="[a]\n\nhi")), row_digest(user("hi", api_content="[b]\n\nhi")))+ self.assertNotEqual(row_digest(user("hi", api_content="[a]\n\nhi")),+ row_digest(user("hi", api_content="[b]\n\nhi")))self.assertNotEqual(row_digest(user("hi", api_content="[a]\n\nhi")), row_digest(user("hi")))self.assertEqual(row_digest(dict(tool("c1", "r"), api_content="x")), row_digest(tool("c1", "r")))@@ -296,9 +297,9 @@ class BuildRequestTest(unittest.TestCase):capture["body"]["messages"][-1]["content"] = "A different request."rewritten = self._tool_round()rewritten["body"]["messages"][-3]["tool_calls"][0]["function"]["arguments"] = "{\"path\":\"other\"}"- for capture in (capture, rewritten):+ for changed in (capture, rewritten):with self.subTest(), self.assertRaises(WarmRefusal) as caught:- self.build(capture)+ self.build(changed)self.assertEqual(caught.exception.code, "source_transform_unsupported")def test_refuses_a_changed_tool_call_type(self):@@ -400,7 +401,8 @@ class BuildRequestTest(unittest.TestCase):details = [{"type": "reasoning.encrypted", "data": "abc"}, {"type": "x.native_assistant", "data": "n"}]reply = assistant("", [("c1", "read", "{}")], reasoning_details=details)self.messages = [*self.rows, reply, tool("c1", "r1")]- for base_url, expected in (("https://openrouter.ai/api/v1", [details[0]]), ("https://api.example.com/v1", None)):+ for base_url, expected in (("https://openrouter.ai/api/v1", [details[0]]),+ ("https://api.example.com/v1", None)):route = (ROUTE[0], base_url, ROUTE[2])sent = build_request(capture_for(self.rows, self.reply, route=route), self.messages, route, 100_000,INSTRUCTION)["messages"][-3]@@ -504,7 +506,8 @@ class BuildRequestTest(unittest.TestCase):self.build(capture, context_length=window)self.assertEqual(caught.exception.code, "capacity")capture["prompt_tokens"] = 1- self.assertLess(1 + estimate_tokens({"messages": body["messages"][sent:]}) * SAFETY + HANDOFF_MAX_TOKENS, window)+ added = estimate_tokens({"messages": body["messages"][sent:]})+ self.assertLess(1 + added * SAFETY + HANDOFF_MAX_TOKENS, window)self.assertEqual(self.build(capture, context_length=window)["messages"], body["messages"])diff --git a/warm_compaction/capture.py b/warm_compaction/capture.pyindex d28dc82..e7e9ce9 100644--- a/warm_compaction/capture.py+++ b/warm_compaction/capture.py@@ -8,7 +8,8 @@ import jsonimport threadingimport timefrom collections import OrderedDict-from typing import Any, Callable+from typing import Any+from collections.abc import Callablefrom .rows import attr, plain_text, row_digest, tool_calls_ofdiff --git a/warm_compaction/engine.py b/warm_compaction/engine.pyindex 282c13d..eecb4cd 100644--- a/warm_compaction/engine.py+++ b/warm_compaction/engine.py@@ -5,7 +5,8 @@ from __future__ import annotationsimport copyimport loggingimport time-from typing import Any, Callable+from typing import Any+from collections.abc import Callablefrom agent.context_engine import ContextEngine@@ -105,8 +106,8 @@ def request_overhead(capture: dict[str, Any] | None, messages: list | None = Nondef request_reserve(capture: dict[str, Any] | None, context_length: int = 0) -> int:"""The reply reserve of the captured request (warm.reply_reserve). Without a captured body or a positive- captured limit, the reply limit of the next request is unknown (Hermes does not give it to a context engine): a quarter of the window, at most- UNKNOWN_RESERVE_MAX, and at least the default."""+ captured limit, the reply limit of the next request is unknown (Hermes does not give it to a context engine):+ a quarter of the window, at most UNKNOWN_RESERVE_MAX, and at least the default."""body = (capture or {}).get("body")if isinstance(body, dict) and isinstance(body.get("messages"), list) and any(type(body.get(key)) is int and body[key] > 0 for key in warm.LIMIT_KEYS):@@ -148,7 +149,7 @@ class WarmCompactionEngine(ContextEngine):def name(self) -> str:return NAME- def clone_for_agent(self) -> "WarmCompactionEngine":+ def clone_for_agent(self) -> WarmCompactionEngine:"""Return a new engine for one agent. The clone shares the capture store and the model access."""clone = WarmCompactionEngine(store=self._store, llm=self._llm, settings=self._settings, task=self._task,post=self._post, clock=self._clock)diff --git a/warm_compaction/fallback.py b/warm_compaction/fallback.pyindex 460cdab..ef15666 100644--- a/warm_compaction/fallback.py+++ b/warm_compaction/fallback.py@@ -4,7 +4,8 @@ from __future__ import annotationsimport collectionsimport logging-from typing import Any, Callable, Iterable+from typing import Any+from collections.abc import Callable, Iterablefrom .handoff import END_MARKER, LEGACY_PREFIX, extras, gatefrom .layout import CUT_NOTE, is_real_user, is_summary, quotediff --git a/warm_compaction/handoff.py b/warm_compaction/handoff.pyindex 9b1c536..0b8c8d6 100644--- a/warm_compaction/handoff.py+++ b/warm_compaction/handoff.py@@ -2,7 +2,8 @@from __future__ import annotations-from typing import Any, Iterable+from typing import Any+from collections.abc import Iterablefrom .rows import reply_textdiff --git a/warm_compaction/layout.py b/warm_compaction/layout.pyindex 9ef0df4..69e49ec 100644--- a/warm_compaction/layout.py+++ b/warm_compaction/layout.py@@ -6,7 +6,8 @@ import copyimport functoolsimport heapqimport re-from typing import Any, Iterable+from typing import Any+from collections.abc import Iterablefrom .handoff import END_MARKER, LEGACY_PREFIXfrom .rows import (api_content, attr, compact_json, cut_bounds, cut_middle, estimate_tokens, hermes_value, plain_text,@@ -311,7 +312,8 @@ def _tail_parts(row: Any, policy: SendPolicy = SendPolicy()) -> list[tuple[tuplecontinueif isinstance(function, dict) and function.get("arguments") is not None:arguments = function["arguments"]- parts.append((("arguments", index), arguments if isinstance(arguments, str) else compact_json(arguments)))+ text = arguments if isinstance(arguments, str) else compact_json(arguments)+ parts.append((("arguments", index), text))key = sent_reasoning_key(row, policy) if policy.cut_reasoning else Noneif key is not None:parts.append(((key,), row[key]))@@ -364,10 +366,10 @@ def bound_tail(rows: list, tokens: int, removed: list | None = None, policy: Senbe larger than the tail budget (a large user message, assistant reply, tool call, or tool result). Then thelargest sent payloads (_tail_parts) are cut to their start and end, until the rows fit or no payload has morethan MIN_COPY_CHARS characters. A tool call keeps its id and name, and its arguments stay a JSON object. A- media part (an image, for example) is replaced by its attachment mark. Other rows and fields stay as they are; signed- reasoning_details stay, because a cut breaks the signature. When the minimum cuts are not enough (a small cap,- or many small payloads), the payloads are dropped (DROPPED), largest first. Only the row structure (roles, tool- call ids and names) can then stay above the cap.+ media part (an image, for example) is replaced by its attachment mark. Other rows and fields stay as they are;+ signed reasoning_details stay, because a cut breaks the signature. When the minimum cuts are not enough (a small+ cap, or many small payloads), the payloads are dropped (DROPPED), largest first. Only the row structure (roles,+ tool call ids and names) can then stay above the cap.With a removed list, one row for each cut payload is added to it: the removed middle after CUT_NOTE, with therole (and the tool call id) of the row. The fallback summary can then keep what the tail cuts."""diff --git a/warm_compaction/warm.py b/warm_compaction/warm.pyindex 1a6e7d9..edcdfa1 100644--- a/warm_compaction/warm.py+++ b/warm_compaction/warm.py@@ -10,7 +10,8 @@ import timeimport urllib.errorimport urllib.parseimport urllib.request-from typing import Any, Callable+from typing import Any+from collections.abc import Callablefrom .rows import (api_content, attr, compact_json, estimate_tokens, has_thought_signature, hermes_value, plain_text,