Skip to content

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

test: cover native provider conversations and generated histories

Elevatormusic5775a3cf6888
diff --git a/.coveragerc b/.coveragerc
new file mode 100644
index 0000000..d3f3615
--- /dev/null
+++ b/.coveragerc
@@ -0,0 +1,7 @@
+[run]
+branch = True
+source = warm_compaction
+data_file = .work/.coverage
+
+[report]
+show_missing = True
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
index c5ef447..64a3aae 100644
--- a/.github/dependabot.yml
+++ b/.github/dependabot.yml
@@ -1,6 +1,6 @@
version: 2
updates:
- # The plugin has no Python dependency. Only the CI actions get updates.
+ # The plugin has no runtime dependency. Update CI actions and test tools.
- package-ecosystem: github-actions
directory: /
schedule:
@@ -8,3 +8,10 @@ updates:
groups:
actions:
patterns: ["*"]
+ - package-ecosystem: pip
+ directory: /
+ schedule:
+ interval: weekly
+ groups:
+ test-tools:
+ patterns: ["*"]
diff --git a/.github/workflows/hermes-compatibility.yml b/.github/workflows/hermes-compatibility.yml
index 60519d9..bb1ee79 100644
--- a/.github/workflows/hermes-compatibility.yml
+++ b/.github/workflows/hermes-compatibility.yml
@@ -54,7 +54,7 @@ jobs:
- 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
+ uv sync --project .work/hermes --frozen --no-dev --extra anthropic --python 3.14
- name: Check real middleware and capture behavior
run: |
.work/hermes/.venv/bin/python -B scripts/check_hermes_compatibility.py \
@@ -63,7 +63,17 @@ jobs:
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
+ - name: Check native provider requests and replies
+ if: ${{ !cancelled() }}
+ run: |
+ .work/hermes/.venv/bin/python -B scripts/check_provider_apis.py \
+ --hermes-source .work/hermes --report .work/provider-api.json
+ - name: Check native conversation and saved-session behavior
+ if: ${{ !cancelled() }}
+ run: |
+ .work/hermes/.venv/bin/python -B scripts/check_native_conversations.py \
+ --hermes-source .work/hermes --report .work/native-conversations.json
+ - name: Save the metadata reports
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
@@ -71,5 +81,7 @@ jobs:
path: |
.work/hermes-compatibility.json
.work/hermes-integration.json
+ .work/provider-api.json
+ .work/native-conversations.json
if-no-files-found: warn
retention-days: 14
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 02b916e..e2c2810 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -34,8 +34,30 @@ jobs:
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
with:
python-version: ${{ matrix.python-version }}
- - name: Unit tests
- run: python -m unittest discover -s tests -p "test_wc_*.py" -v
+ - name: Install test tools
+ run: python -m pip install -r requirements-test.txt
+ - name: Unit tests with branch coverage
+ run: python -m coverage run -m unittest discover -s tests -p "test_wc_*.py" -v
+ - name: Property tests with branch coverage
+ if: ${{ !cancelled() }}
+ run: python -m coverage run --append -m unittest discover -s tests/property -p "test_*.py" -v
+ - name: Report branch coverage
+ if: always()
+ run: |
+ python -c "from pathlib import Path; Path('.work').mkdir(exist_ok=True)"
+ python -m coverage report -m
+ python -m coverage xml -o .work/coverage.xml
+ python -m coverage json -o .work/coverage.json
+ - name: Save branch coverage reports
+ if: always()
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: coverage-${{ matrix.os }}-python-${{ matrix.python-version }}
+ path: |
+ .work/coverage.xml
+ .work/coverage.json
+ if-no-files-found: warn
+ retention-days: 14
# One stable check name for branch protection: it passes only when every unit job passed.
tests-passed:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a2ddd28..6178740 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 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.
- Keep safe request refusal codes in status and logs, instead of the generic `settings_unsupported`.
- Keep the captured `x-opencode-session` header on warm requests, including the header that Hermes adds for OpenCode routes. Refuse unknown headers and header rewrites; send the session value only as an HTTP header.
@@ -15,6 +16,8 @@ All notable changes are listed here. The format follows [Keep a Changelog](https
- Warm request adapters for Responses and Anthropic Messages. Keep native input prefixes, cache controls, and verified encrypted or signed reasoning. Unsupported request shapes and authentication routes use the fallback. See [Provider support](docs/provider-support.md) for limits.
- Native reply completion checks, token counters, and a synthetic real-Hermes provider integration check. Native replay blocks count in tail estimates and cannot be cut apart.
+- Native provider and conversation checks in CI against the minimum Hermes version and upstream `main`. The conversation checks cover manual and automatic compaction, tools, and saved-session reload.
+- Hypothesis tests for native histories, stream events, and capture changes, plus branch coverage reports. These tools are test dependencies only.
- A WARNING for each saved compaction that Hermes confirms without the warm path, with its reason (Hermes copies it to `errors.log`).
- After 3 confirmed compactions in a row without the warm path, one notice with a hint for each distinct reason, in the logs and at the next automatic compaction when engine status is enabled. The notice has no routine progress text. Later confirmed failures update the pending notice and its fixed-summary count until Hermes shows it.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 6c92683..8c66c5d 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -52,12 +52,23 @@ Agents must read [AGENTS.md](AGENTS.md) before work. [CLAUDE.md](CLAUDE.md) has
You need Python 3.10 or later and Git. The plugin has no third-party dependency.
-For Python changes, run the unit tests and lint. Unit tests check local behavior with fixtures; they do not prove deployed compatibility, summary quality, or cache reuse.
+For Python changes, run the unit tests, property tests, and lint. These checks use local fixtures. They do not prove deployed compatibility, summary quality, or cache reuse.
```bash
python -m unittest discover -s tests -p "test_wc_*.py"
```
+Install the test tools in a separate test environment, then run the property tests and branch coverage:
+
+```bash
+python -m pip install -r requirements-test.txt
+python -m coverage run -m unittest discover -s tests -p "test_wc_*.py"
+python -m coverage run --append -m unittest discover -s tests/property -p "test_*.py"
+python -m coverage report -m
+```
+
+The [property tests](tests/property/test_native_properties.py) use Hypothesis to generate synthetic native records and request options. The [coverage settings](.coveragerc) measure branches in the plugin. Coverage reports show which paths need more checks; there is no minimum percentage gate. These tools are test dependencies only. The plugin still has no third-party dependency.
+
Lint with [ruff](https://docs.astral.sh/ruff/) (the version that CI uses):
```bash
@@ -73,17 +84,20 @@ For changes to Hermes interaction, also run the integration check. It runs real
The integration check covers install, request, compaction, and history behavior on that Hermes version. It does not call a real model or prove live cache reuse or a performance gain. Keep evidence small and metadata only.
-For changes to Responses or Anthropic Messages routes, also run the native provider check. It uses real Hermes transports and synthetic loopback replies. The isolated interpreter needs the Hermes dependencies for both API formats. Use `--dependency-path <dependency-folder>` if those dependencies are in a separate local folder.
+For changes to Responses or Anthropic Messages routes, also run both native checks. The provider check uses real Hermes transports and synthetic loopback replies. The conversation check runs the real Hermes agent loop, manual and automatic compaction, native tools, and saved-session reload. Each case uses a fresh process and temporary home. The isolated interpreter needs the Hermes dependencies for both API formats. Use `--dependency-path <dependency-folder>` if those dependencies are in a separate local folder.
```bash
<hermes-venv-python> -B scripts/check_provider_apis.py --hermes-source <clean-hermes-checkout> --report .work/provider-api-report.json
+<hermes-venv-python> -B scripts/check_native_conversations.py --hermes-source <clean-hermes-checkout> --report .work/native-conversations-report.json
```
+The [Hermes compatibility workflow](.github/workflows/hermes-compatibility.yml) uses the minimum Hermes commit `45871e100feceb89769536c88e5e6e265226a409` and current upstream `main`. It prepares a separate runtime from each checkout's `uv.lock`, with the `anthropic` extra. It does not change the plugin's runtime dependencies. Native check failures fail the job, including upstream changes; they are not treated as unsupported-version skips. The report records the exact Hermes commit and source hashes. The jobs have read-only repository access, no stored checkout credentials, no secrets, and no Actions cache access. Only metadata reports are saved.
+
See [provider support](docs/provider-support.md) for the supported request and authentication limits. A passing local check does not qualify a live provider.
For document or form changes, check local Markdown links and run `git diff --check`. For issue forms, parse the YAML and check its fields against the [GitHub form schema](https://docs.github.com/en/communities/using-templates-to-encourage-useful-issues-and-pull-requests/syntax-for-githubs-form-schema). No live model check is needed for these changes.
-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.
+CI runs unit and property tests on Python 3.10 to 3.13 (Linux) and on Python 3.12 (Windows and macOS). It saves branch coverage reports for each job and runs lint. A pull request must pass the test and lint checks. The Hermes compatibility workflow also runs on pull requests, pushes to `main`, each day, and by manual dispatch.
## Style
diff --git a/README.md b/README.md
index 144b8ee..e67b962 100644
--- a/README.md
+++ b/README.md
@@ -303,7 +303,7 @@ The new history uses summary rows that Hermes recognizes. The [integration check
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 [compatibility workflow](.github/workflows/hermes-compatibility.yml) tests the real Hermes middleware, plugin install, native provider requests, and native conversation loop 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. The checks use synthetic data and a loopback server. Native failures fail the job; an upstream change is not skipped. 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:
@@ -311,7 +311,7 @@ The check uses synthetic requests and a fake provider callback. It checks captur
<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.
+The middleware check alone does not prove full conversation-loop compatibility or a cache benefit. Before adopting a Hermes update, also run the plugin and native checks 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.
@@ -331,6 +331,8 @@ Run the integration check on a clean Hermes checkout with the Python of the Herm
The 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.
+For native provider edits, run both `scripts/check_provider_apis.py` and `scripts/check_native_conversations.py`. The second check covers the real agent loop, manual and automatic compaction, native tool rounds, and saved-session reload. See [Provider support](docs/provider-support.md#retained-history-and-checks) for commands and limits. The [contribution guide](CONTRIBUTING.md#run-the-checks) also gives the Hypothesis property tests and branch coverage commands. Test tools are separate from the plugin's runtime dependencies.
+
## 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).
diff --git a/docs/provider-support.md b/docs/provider-support.md
index e668251..9b34782 100644
--- a/docs/provider-support.md
+++ b/docs/provider-support.md
@@ -32,12 +32,19 @@ Forced or server tools, media, structured output, unknown request controls, and
Native replay fields count in retained-tail estimates. A signed or encrypted assistant record stays whole, including the canonical text and tool data that its replay blocks describe. If an indivisible retained record exceeds the context budget, the attempt returns the original history with `path=unchanged reason=capacity`.
-The adapters are checked against Hermes `bc2e4d3773518f2129023383a29dc51133dc6048` with synthetic data and a loopback server. These checks prove local request and history behavior on that source. The native test driver calls real hooks and middleware explicitly; the full native conversation loop has not been tested. The checks do not prove every deployed provider, summary quality, cached-token reuse, or a speed gain. The plugin has no documented final-wire capture or raw provider-dispatch API; future host transforms still need review.
+The provider transport check uses synthetic data and a loopback server. It calls real Hermes transports, hooks, and middleware explicitly. A separate native conversation check runs the real Hermes agent loop. It covers manual and automatic compaction, native tool rounds, and saved-session reload in a fresh process. Both checks require a clean source checkout and keep source and plugin hashes unchanged.
+
+The [compatibility workflow](../.github/workflows/hermes-compatibility.yml) runs these checks against the minimum Hermes commit `45871e100feceb89769536c88e5e6e265226a409` and current upstream `main`. It installs the locked Hermes runtime with the `anthropic` extra. Native failures fail the job; upstream changes are not silently skipped. The jobs have read-only repository access, no stored checkout credentials, no secrets, and no Actions cache access. Their saved reports contain metadata only.
+
+A passing report proves synthetic request and history behavior on the exact source commit in that report. The checks do not prove every deployed provider, summary quality, cached-token reuse, or a speed gain. The plugin has no documented final-wire capture or raw provider-dispatch API; future host transforms still need review.
Run the provider integration check with an isolated Hermes dependency interpreter:
```bash
<hermes-venv-python> -B scripts/check_provider_apis.py --hermes-source <clean-hermes-checkout> --report .work/provider-api-report.json
+<hermes-venv-python> -B scripts/check_native_conversations.py --hermes-source <clean-hermes-checkout> --report .work/native-conversations-report.json
```
+Use `--dependency-path <dependency-folder>` if the native API dependencies are in a separate folder. The [property tests](../tests/property/test_native_properties.py) generate synthetic native records and request options for local checks. Branch coverage reports show untested plugin paths without imposing a percentage gate.
+
The [contribution guide](../CONTRIBUTING.md#run-the-checks) gives the full regression checks.
diff --git a/evidence/native-conversation-integration.json b/evidence/native-conversation-integration.json
new file mode 100644
index 0000000..48e8752
--- /dev/null
+++ b/evidence/native-conversation-integration.json
@@ -0,0 +1,658 @@
+{
+ "check": "native full Hermes conversation loops",
+ "python": "3.14.7",
+ "hermes": {
+ "commit": "bc2e4d3773518f2129023383a29dc51133dc6048",
+ "clean": true
+ },
+ "synthetic": true,
+ "live_provider": false,
+ "cache_reuse_proved": false,
+ "privacy": "metadata only",
+ "cases": [
+ {
+ "case": "responses_manual",
+ "phases": [
+ {
+ "case": "responses_manual",
+ "phase": "run",
+ "status": "passed",
+ "checks": {
+ "agent_origin_is_pinned_source": true,
+ "plugin_selected": true,
+ "plugin_origin_is_temporary_install": true,
+ "real_conversation_final_reply": true,
+ "real_conversation_not_failed": true,
+ "responses_stream_added_by_host": true,
+ "real_hook_capture_exact_wire": true,
+ "real_post_hook_usage": true,
+ "real_hook_capture_no_refusal": true,
+ "manual_real_entry_result_valid": true,
+ "manual_real_entry_compression_count": true,
+ "manual_real_entry_summary_rows": true,
+ "manual_request_order": true,
+ "warm_accepted": true,
+ "synthetic_cached_counter": true,
+ "synthetic_summary_in_history": true,
+ "engine_session_follows_host": true,
+ "one_native_warm_request": true,
+ "native_warm_prefix_exact": true,
+ "native_warm_prompt_tools_exact": true,
+ "native_warm_endpoint_exact": true,
+ "native_auth_exact": true,
+ "no_json_headers": true,
+ "no_fallback": true,
+ "handoff_not_in_main_output": true,
+ "native_history_saved_exact": true,
+ "plugin_made_no_blocked_call": true,
+ "no_private_profile_read": true
+ },
+ "error": null,
+ "tool_discovery": {
+ "registered": true,
+ "selected": true,
+ "same_scope": true,
+ "loaded": [
+ {
+ "name": "wc_test_tools",
+ "enabled": true,
+ "error_present": false
+ }
+ ]
+ },
+ "native_capability": "supported",
+ "outcome": {
+ "path": "warm",
+ "reason": "accepted",
+ "prompt_tokens": 200,
+ "cached_tokens": 120
+ },
+ "fence_callers": [
+ "child_process_blocked from hermes_cli/source_check.py:_git_run < hermes_cli/source_check.py:_git_stdout < hermes_cli/source_check.py:_read_checkout",
+ "child_process_blocked from tools/env_probe.py:_run < tools/env_probe.py:_py_out < tools/env_probe.py:_pip_python_version",
+ "child_process_blocked from tools/env_probe.py:_run < tools/env_probe.py:_py_out < tools/env_probe.py:_python_version_of",
+ "network_host_blocked from hermes_cli/release_channels.py:read < hermes_cli/release_channels.py:read_bytes < hermes_cli/release_channels.py:read_record"
+ ],
+ "request_counts": {
+ "main": 1,
+ "warm": 1,
+ "fallback": 0
+ },
+ "history_rows": 4,
+ "compression_count": 1,
+ "fence_denied": {
+ "child_process_blocked": 5,
+ "network_host_blocked": 1
+ },
+ "blocked_host_network_attempts": 1,
+ "exit_ok": true
+ },
+ {
+ "case": "responses_manual",
+ "phase": "reload",
+ "status": "passed",
+ "checks": {
+ "agent_origin_is_pinned_source": true,
+ "plugin_selected": true,
+ "plugin_origin_is_temporary_install": true,
+ "reloaded_summary": true,
+ "reload_has_no_process_capture": true,
+ "saved_native_rows_exact_after_process_reload": true,
+ "real_conversation_final_reply": true,
+ "real_conversation_not_failed": true,
+ "responses_stream_added_by_host": true,
+ "real_hook_capture_exact_wire": true,
+ "real_post_hook_usage": true,
+ "real_hook_capture_no_refusal": true,
+ "manual_real_entry_result_valid": true,
+ "manual_real_entry_compression_count": true,
+ "manual_real_entry_summary_rows": true,
+ "manual_request_order": true,
+ "warm_accepted": true,
+ "synthetic_cached_counter": true,
+ "synthetic_summary_in_history": true,
+ "engine_session_follows_host": true,
+ "one_native_warm_request": true,
+ "native_warm_prefix_exact": true,
+ "native_warm_prompt_tools_exact": true,
+ "native_warm_endpoint_exact": true,
+ "native_auth_exact": true,
+ "no_json_headers": true,
+ "no_fallback": true,
+ "handoff_not_in_main_output": true,
+ "native_history_saved_exact": true,
+ "plugin_made_no_blocked_call": true,
+ "no_private_profile_read": true
+ },
+ "error": null,
+ "tool_discovery": {
+ "registered": true,
+ "selected": true,
+ "same_scope": true,
+ "loaded": [
+ {
+ "name": "wc_test_tools",
+ "enabled": true,
+ "error_present": false
+ }
+ ]
+ },
+ "native_capability": "supported",
+ "outcome": {
+ "path": "warm",
+ "reason": "accepted",
+ "prompt_tokens": 200,
+ "cached_tokens": 120
+ },
+ "fence_callers": [
+ "child_process_blocked from hermes_cli/source_check.py:_git_run < hermes_cli/source_check.py:_git_stdout < hermes_cli/source_check.py:_read_checkout",
+ "child_process_blocked from tools/env_probe.py:_run < tools/env_probe.py:_py_out < tools/env_probe.py:_pip_python_version",
+ "child_process_blocked from tools/env_probe.py:_run < tools/env_probe.py:_py_out < tools/env_probe.py:_python_version_of"
+ ],
+ "request_counts": {
+ "main": 1,
+ "warm": 1,
+ "fallback": 0
+ },
+ "history_rows": 6,
+ "compression_count": 1,
+ "fence_denied": {
+ "child_process_blocked": 6
+ },
+ "blocked_host_network_attempts": 0,
+ "exit_ok": true
+ }
+ ],
+ "passed": true
+ },
+ {
+ "case": "responses_auto_tool",
+ "phases": [
+ {
+ "case": "responses_auto_tool",
+ "phase": "run",
+ "status": "passed",
+ "checks": {
+ "agent_origin_is_pinned_source": true,
+ "plugin_selected": true,
+ "plugin_origin_is_temporary_install": true,
+ "real_conversation_final_reply": true,
+ "real_conversation_not_failed": true,
+ "tool_registered": true,
+ "automatic_summary_rows": true,
+ "actual_loop_request_order": true,
+ "tool_result_retained": true,
+ "warm_accepted": true,
+ "synthetic_cached_counter": true,
+ "synthetic_summary_in_history": true,
+ "engine_session_follows_host": true,
+ "one_native_warm_request": true,
+ "native_warm_prefix_exact": true,
+ "native_warm_prompt_tools_exact": true,
+ "native_warm_endpoint_exact": true,
+ "native_auth_exact": true,
+ "no_json_headers": true,
+ "no_fallback": true,
+ "handoff_not_in_main_output": true,
+ "native_tool_pair_once": true,
+ "real_tool_result_replayed": true,
+ "native_history_saved_exact": true,
+ "plugin_made_no_blocked_call": true,
+ "no_private_profile_read": true
+ },
+ "error": null,
+ "tool_discovery": {
+ "registered": true,
+ "selected": true,
+ "same_scope": true,
+ "loaded": [
+ {
+ "name": "wc_test_tools",
+ "enabled": true,
+ "error_present": false
+ }
+ ]
+ },
+ "native_capability": "supported",
+ "outcome": {
+ "path": "warm",
+ "reason": "accepted",
+ "prompt_tokens": 200,
+ "cached_tokens": 120
+ },
+ "fence_callers": [
+ "child_process_blocked from hermes_cli/source_check.py:_git_run < hermes_cli/source_check.py:_git_stdout < hermes_cli/source_check.py:_read_checkout",
+ "child_process_blocked from tools/env_probe.py:_run < tools/env_probe.py:_py_out < tools/env_probe.py:_pip_python_version",
+ "child_process_blocked from tools/env_probe.py:_run < tools/env_probe.py:_py_out < tools/env_probe.py:_python_version_of",
+ "network_host_blocked from hermes_cli/release_channels.py:read < hermes_cli/release_channels.py:read_bytes < hermes_cli/release_channels.py:read_record"
+ ],
+ "request_counts": {
+ "main": 2,
+ "warm": 1,
+ "fallback": 0
+ },
+ "history_rows": 6,
+ "compression_count": 1,
+ "fence_denied": {
+ "child_process_blocked": 5,
+ "network_host_blocked": 1
+ },
+ "blocked_host_network_attempts": 1,
+ "exit_ok": true
+ },
+ {
+ "case": "responses_auto_tool",
+ "phase": "reload",
+ "status": "passed",
+ "checks": {
+ "agent_origin_is_pinned_source": true,
+ "plugin_selected": true,
+ "plugin_origin_is_temporary_install": true,
+ "reloaded_summary": true,
+ "reload_has_no_process_capture": true,
+ "saved_native_rows_exact_after_process_reload": true,
+ "real_conversation_final_reply": true,
+ "real_conversation_not_failed": true,
+ "responses_stream_added_by_host": true,
+ "real_hook_capture_exact_wire": true,
+ "real_post_hook_usage": true,
+ "real_hook_capture_no_refusal": true,
+ "manual_real_entry_result_valid": true,
+ "manual_real_entry_compression_count": true,
+ "manual_real_entry_summary_rows": true,
+ "manual_request_order": true,
+ "warm_accepted": true,
+ "synthetic_cached_counter": true,
+ "synthetic_summary_in_history": true,
+ "engine_session_follows_host": true,
+ "one_native_warm_request": true,
+ "native_warm_prefix_exact": true,
+ "native_warm_prompt_tools_exact": true,
+ "native_warm_endpoint_exact": true,
+ "native_auth_exact": true,
+ "no_json_headers": true,
+ "no_fallback": true,
+ "handoff_not_in_main_output": true,
+ "native_tool_pair_once": true,
+ "real_tool_result_replayed": true,
+ "native_history_saved_exact": true,
+ "plugin_made_no_blocked_call": true,
+ "no_private_profile_read": true
+ },
+ "error": null,
+ "tool_discovery": {
+ "registered": true,
+ "selected": true,
+ "same_scope": true,
+ "loaded": [
+ {
+ "name": "wc_test_tools",
+ "enabled": true,
+ "error_present": false
+ }
+ ]
+ },
+ "native_capability": "supported",
+ "outcome": {
+ "path": "warm",
+ "reason": "accepted",
+ "prompt_tokens": 200,
+ "cached_tokens": 120
+ },
+ "fence_callers": [
+ "child_process_blocked from hermes_cli/source_check.py:_git_run < hermes_cli/source_check.py:_git_stdout < hermes_cli/source_check.py:_read_checkout",
+ "child_process_blocked from tools/env_probe.py:_run < tools/env_probe.py:_py_out < tools/env_probe.py:_pip_python_version",
+ "child_process_blocked from tools/env_probe.py:_run < tools/env_probe.py:_py_out < tools/env_probe.py:_python_version_of"
+ ],
+ "request_counts": {
+ "main": 1,
+ "warm": 1,
+ "fallback": 0
+ },
+ "history_rows": 8,
+ "compression_count": 1,
+ "fence_denied": {
+ "child_process_blocked": 5
+ },
+ "blocked_host_network_attempts": 0,
+ "exit_ok": true
+ }
+ ],
+ "passed": true
+ },
+ {
+ "case": "anthropic_manual",
+ "phases": [
+ {
+ "case": "anthropic_manual",
+ "phase": "run",
+ "status": "passed",
+ "checks": {
+ "agent_origin_is_pinned_source": true,
+ "plugin_selected": true,
+ "plugin_origin_is_temporary_install": true,
+ "real_conversation_final_reply": true,
+ "real_conversation_not_failed": true,
+ "real_hook_capture_exact_wire": true,
+ "real_post_hook_usage": true,
+ "real_hook_capture_no_refusal": true,
+ "manual_real_entry_result_valid": true,
+ "manual_real_entry_compression_count": true,
+ "manual_real_entry_summary_rows": true,
+ "manual_request_order": true,
+ "warm_accepted": true,
+ "synthetic_cached_counter": true,
+ "synthetic_summary_in_history": true,
+ "engine_session_follows_host": true,
+ "one_native_warm_request": true,
+ "native_warm_prefix_exact": true,
+ "native_warm_prompt_tools_exact": true,
+ "native_warm_endpoint_exact": true,
+ "native_auth_exact": true,
+ "no_json_headers": true,
+ "no_fallback": true,
+ "handoff_not_in_main_output": true,
+ "native_history_saved_exact": true,
+ "plugin_made_no_blocked_call": true,
+ "no_private_profile_read": true
+ },
+ "error": null,
+ "tool_discovery": {
+ "registered": true,
+ "selected": true,
+ "same_scope": true,
+ "loaded": [
+ {
+ "name": "wc_test_tools",
+ "enabled": true,
+ "error_present": false
+ }
+ ]
+ },
+ "native_capability": "supported",
+ "outcome": {
+ "path": "warm",
+ "reason": "accepted",
+ "prompt_tokens": 200,
+ "cached_tokens": 120
+ },
+ "fence_callers": [
+ "child_process_blocked from hermes_cli/source_check.py:_git_run < hermes_cli/source_check.py:_git_stdout < hermes_cli/source_check.py:_read_checkout",
+ "child_process_blocked from tools/env_probe.py:_run < tools/env_probe.py:_py_out < tools/env_probe.py:_pip_python_version",
+ "child_process_blocked from tools/env_probe.py:_run < tools/env_probe.py:_py_out < tools/env_probe.py:_python_version_of",
+ "network_host_blocked from hermes_cli/release_channels.py:read < hermes_cli/release_channels.py:read_bytes < hermes_cli/release_channels.py:read_record"
+ ],
+ "request_counts": {
+ "main": 1,
+ "warm": 1,
+ "fallback": 0
+ },
+ "history_rows": 4,
+ "compression_count": 1,
+ "fence_denied": {
+ "child_process_blocked": 5,
+ "network_host_blocked": 1
+ },
+ "blocked_host_network_attempts": 1,
+ "exit_ok": true
+ },
+ {
+ "case": "anthropic_manual",
+ "phase": "reload",
+ "status": "passed",
+ "checks": {
+ "agent_origin_is_pinned_source": true,
+ "plugin_selected": true,
+ "plugin_origin_is_temporary_install": true,
+ "reloaded_summary": true,
+ "reload_has_no_process_capture": true,
+ "saved_native_rows_exact_after_process_reload": true,
+ "real_conversation_final_reply": true,
+ "real_conversation_not_failed": true,
+ "real_hook_capture_exact_wire": true,
+ "real_post_hook_usage": true,
+ "real_hook_capture_no_refusal": true,
+ "manual_real_entry_result_valid": true,
+ "manual_real_entry_compression_count": true,
+ "manual_real_entry_summary_rows": true,
+ "manual_request_order": true,
+ "warm_accepted": true,
+ "synthetic_cached_counter": true,
+ "synthetic_summary_in_history": true,
+ "engine_session_follows_host": true,
+ "one_native_warm_request": true,
+ "native_warm_prefix_exact": true,
+ "native_warm_prompt_tools_exact": true,
+ "native_warm_endpoint_exact": true,
+ "native_auth_exact": true,
+ "no_json_headers": true,
+ "no_fallback": true,
+ "handoff_not_in_main_output": true,
+ "native_history_saved_exact": true,
+ "plugin_made_no_blocked_call": true,
+ "no_private_profile_read": true
+ },
+ "error": null,
+ "tool_discovery": {
+ "registered": true,
+ "selected": true,
+ "same_scope": true,
+ "loaded": [
+ {
+ "name": "wc_test_tools",
+ "enabled": true,
+ "error_present": false
+ }
+ ]
+ },
+ "native_capability": "supported",
+ "outcome": {
+ "path": "warm",
+ "reason": "accepted",
+ "prompt_tokens": 200,
+ "cached_tokens": 120
+ },
+ "fence_callers": [
+ "child_process_blocked from hermes_cli/source_check.py:_git_run < hermes_cli/source_check.py:_git_stdout < hermes_cli/source_check.py:_read_checkout",
+ "child_process_blocked from tools/env_probe.py:_run < tools/env_probe.py:_py_out < tools/env_probe.py:_pip_python_version",
+ "child_process_blocked from tools/env_probe.py:_run < tools/env_probe.py:_py_out < tools/env_probe.py:_python_version_of"
+ ],
+ "request_counts": {
+ "main": 1,
+ "warm": 1,
+ "fallback": 0
+ },
+ "history_rows": 6,
+ "compression_count": 1,
+ "fence_denied": {
+ "child_process_blocked": 5
+ },
+ "blocked_host_network_attempts": 0,
+ "exit_ok": true
+ }
+ ],
+ "passed": true
+ },
+ {
+ "case": "anthropic_auto_tool",
+ "phases": [
+ {
+ "case": "anthropic_auto_tool",
+ "phase": "run",
+ "status": "passed",
+ "checks": {
+ "agent_origin_is_pinned_source": true,
+ "plugin_selected": true,
+ "plugin_origin_is_temporary_install": true,
+ "real_conversation_final_reply": true,
+ "real_conversation_not_failed": true,
+ "tool_registered": true,
+ "automatic_summary_rows": true,
+ "actual_loop_request_order": true,
+ "tool_result_retained": true,
+ "warm_accepted": true,
+ "synthetic_cached_counter": true,
+ "synthetic_summary_in_history": true,
+ "engine_session_follows_host": true,
+ "one_native_warm_request": true,
+ "native_warm_prefix_exact": true,
+ "native_warm_prompt_tools_exact": true,
+ "native_warm_endpoint_exact": true,
+ "native_auth_exact": true,
+ "no_json_headers": true,
+ "no_fallback": true,
+ "handoff_not_in_main_output": true,
+ "native_tool_pair_once": true,
+ "real_tool_result_replayed": true,
+ "native_history_saved_exact": true,
+ "plugin_made_no_blocked_call": true,
+ "no_private_profile_read": true
+ },
+ "error": null,
+ "tool_discovery": {
+ "registered": true,
+ "selected": true,
+ "same_scope": true,
+ "loaded": [
+ {
+ "name": "wc_test_tools",
+ "enabled": true,
+ "error_present": false
+ }
+ ]
+ },
+ "native_capability": "supported",
+ "outcome": {
+ "path": "warm",
+ "reason": "accepted",
+ "prompt_tokens": 200,
+ "cached_tokens": 120
+ },
+ "fence_callers": [
+ "child_process_blocked from hermes_cli/source_check.py:_git_run < hermes_cli/source_check.py:_git_stdout < hermes_cli/source_check.py:_read_checkout",
+ "child_process_blocked from tools/env_probe.py:_run < tools/env_probe.py:_py_out < tools/env_probe.py:_pip_python_version",
+ "child_process_blocked from tools/env_probe.py:_run < tools/env_probe.py:_py_out < tools/env_probe.py:_python_version_of",
+ "network_host_blocked from hermes_cli/release_channels.py:read < hermes_cli/release_channels.py:read_bytes < hermes_cli/release_channels.py:read_record"
+ ],
+ "request_counts": {
+ "main": 2,
+ "warm": 1,
+ "fallback": 0
+ },
+ "history_rows": 6,
+ "compression_count": 1,
+ "fence_denied": {
+ "child_process_blocked": 5,
+ "network_host_blocked": 1
+ },
+ "blocked_host_network_attempts": 1,
+ "exit_ok": true
+ },
+ {
+ "case": "anthropic_auto_tool",
+ "phase": "reload",
+ "status": "passed",
+ "checks": {
+ "agent_origin_is_pinned_source": true,
+ "plugin_selected": true,
+ "plugin_origin_is_temporary_install": true,
+ "reloaded_summary": true,
+ "reload_has_no_process_capture": true,
+ "saved_native_rows_exact_after_process_reload": true,
+ "real_conversation_final_reply": true,
+ "real_conversation_not_failed": true,
+ "real_hook_capture_exact_wire": true,
+ "real_post_hook_usage": true,
+ "real_hook_capture_no_refusal": true,
+ "manual_real_entry_result_valid": true,
+ "manual_real_entry_compression_count": true,
+ "manual_real_entry_summary_rows": true,
+ "manual_request_order": true,
+ "warm_accepted": true,
+ "synthetic_cached_counter": true,
+ "synthetic_summary_in_history": true,
+ "engine_session_follows_host": true,
+ "one_native_warm_request": true,
+ "native_warm_prefix_exact": true,
+ "native_warm_prompt_tools_exact": true,
+ "native_warm_endpoint_exact": true,
+ "native_auth_exact": true,
+ "no_json_headers": true,
+ "no_fallback": true,
+ "handoff_not_in_main_output": true,
+ "native_tool_pair_once": true,
+ "real_tool_result_replayed": true,
+ "native_history_saved_exact": true,
+ "plugin_made_no_blocked_call": true,
+ "no_private_profile_read": true
+ },
+ "error": null,
+ "tool_discovery": {
+ "registered": true,
+ "selected": true,
+ "same_scope": true,
+ "loaded": [
+ {
+ "name": "wc_test_tools",
+ "enabled": true,
+ "error_present": false
+ }
+ ]
+ },
+ "native_capability": "supported",
+ "outcome": {
+ "path": "warm",
+ "reason": "accepted",
+ "prompt_tokens": 200,
+ "cached_tokens": 120
+ },
+ "fence_callers": [
+ "child_process_blocked from hermes_cli/source_check.py:_git_run < hermes_cli/source_check.py:_git_stdout < hermes_cli/source_check.py:_read_checkout",
+ "child_process_blocked from tools/env_probe.py:_run < tools/env_probe.py:_py_out < tools/env_probe.py:_pip_python_version",
+ "child_process_blocked from tools/env_probe.py:_run < tools/env_probe.py:_py_out < tools/env_probe.py:_python_version_of"
+ ],
+ "request_counts": {
+ "main": 1,
+ "warm": 1,
+ "fallback": 0
+ },
+ "history_rows": 8,
+ "compression_count": 1,
+ "fence_denied": {
+ "child_process_blocked": 5
+ },
+ "blocked_host_network_attempts": 0,
+ "exit_ok": true
+ }
+ ],
+ "passed": true
+ }
+ ],
+ "error": null,
+ "plugin_sha256": {
+ "warm_compaction/__init__.py": "760484ace80b9da77d7397828f69178905c9ac95df7b8114956bde727bd98aef",
+ "warm_compaction/anthropic.py": "7bd4cb0e075c4f279f62d3b6f0c3dcf7405308c7360f9136369476a59dca4fd3",
+ "warm_compaction/capture.py": "d2ce12d20fca5649d94b17d376a7bd9e21ba7f6a828b94cb62d030ca55adf791",
+ "warm_compaction/engine.py": "97a5ca7b779d4cfbaf4f4b2c9cd9d8e4616985d19578551d9c76679011204a12",
+ "warm_compaction/fallback.py": "9b2d0529767ff157bbe0d1cbf096ca6ac35217118f81eee769adf41d50189a9a",
+ "warm_compaction/handoff.py": "fcab51def8fbcc2b1928957930c9a5c58a4ad202c949fd9f870a77f3b30276ae",
+ "warm_compaction/layout.py": "3722ca05a4b84c9ed9f5cef5c7f7a175201efaba4208f3819dabcc556a2cfd57",
+ "warm_compaction/native.py": "2bac322bf7779e7d4ec78137a1ba1fdff25d3e58910ace51200147aebf15f494",
+ "warm_compaction/plugin.yaml": "baa7820b3ce9a40d2a53f70a4d0525131860ea2ec670143d0a7742b59c4d937b",
+ "warm_compaction/protocol.py": "f319d7a38ebb60d68d09b3575fe4f88f324b03be6017efbc5fd9932f05299853",
+ "warm_compaction/responses.py": "70c8c912b39b377945488f4fb68f032ca0aa9be5a4340df0c1af7fd5961ee103",
+ "warm_compaction/rows.py": "2f5d9bd1e1d72c620354c4ec317526b4bca56033e9f080dde9967feff4bdb50c",
+ "warm_compaction/warm.py": "6b5cacd003acfa5027b871a73d3ca34ec1612ac70b7497e24cd8ecb74e9025d2"
+ },
+ "helper_sha256": {
+ "check_provider_apis.py": "acae5d374986f4bca21f5bac2c8eefc6bac1c2e665fea58a3e11793eadc3d546",
+ "check_plugin_hermes.py": "47dd18b7a403c298eebbc1fbc5e6f0d41b926ac22b541da275f155c77d4485ec",
+ "check_hermes_compatibility.py": "641b1acb9a311ebad570c4a06800ff866030471db3b4d745148244b2e8ca75c0"
+ },
+ "script_sha256": "05c8eb9bf37ab1a322f4f3255946c9015614def0dea9372f8a732d0e18fa9828",
+ "hermes_source_unchanged": true,
+ "plugin_source_unchanged": true,
+ "helpers_unchanged": true,
+ "script_unchanged": true,
+ "passed": true
+}
diff --git a/evidence/provider-api-integration.json b/evidence/provider-api-integration.json
index df85975..fd109d0 100644
--- a/evidence/provider-api-integration.json
+++ b/evidence/provider-api-integration.json
@@ -1,6 +1,6 @@
{
"check": "native provider transport and warm loopback check",
- "python": "3.11.14",
+ "python": "3.14.7",
"hermes": {
"commit": "bc2e4d3773518f2129023383a29dc51133dc6048",
"clean": true
@@ -441,7 +441,7 @@
}
],
"error": null,
- "script_sha256": "e3c74c4e14de19bb2d799f279b100d247cc9fbc962bbb6f87ba3fe9ef9af1c67",
+ "script_sha256": "acae5d374986f4bca21f5bac2c8eefc6bac1c2e665fea58a3e11793eadc3d546",
"plugin_sha256": {
"warm_compaction/__init__.py": "760484ace80b9da77d7397828f69178905c9ac95df7b8114956bde727bd98aef",
"warm_compaction/anthropic.py": "7bd4cb0e075c4f279f62d3b6f0c3dcf7405308c7360f9136369476a59dca4fd3",
@@ -453,7 +453,7 @@
"warm_compaction/native.py": "2bac322bf7779e7d4ec78137a1ba1fdff25d3e58910ace51200147aebf15f494",
"warm_compaction/plugin.yaml": "baa7820b3ce9a40d2a53f70a4d0525131860ea2ec670143d0a7742b59c4d937b",
"warm_compaction/protocol.py": "f319d7a38ebb60d68d09b3575fe4f88f324b03be6017efbc5fd9932f05299853",
- "warm_compaction/responses.py": "1b9b85cd3821455d462dc4fb6f0d63b9a7f2ca65d450fcd5e9cdb320d3367104",
+ "warm_compaction/responses.py": "70c8c912b39b377945488f4fb68f032ca0aa9be5a4340df0c1af7fd5961ee103",
"warm_compaction/rows.py": "2f5d9bd1e1d72c620354c4ec317526b4bca56033e9f080dde9967feff4bdb50c",
"warm_compaction/warm.py": "6b5cacd003acfa5027b871a73d3ca34ec1612ac70b7497e24cd8ecb74e9025d2"
},
diff --git a/requirements-test.txt b/requirements-test.txt
new file mode 100644
index 0000000..fa28a7d
--- /dev/null
+++ b/requirements-test.txt
@@ -0,0 +1,4 @@
+# Test and CI tools only. The plugin needs no third-party package.
+hypothesis==6.168.5
+sortedcontainers==2.4.0
+coverage==7.16.2
diff --git a/scripts/check_native_conversations.py b/scripts/check_native_conversations.py
new file mode 100644
index 0000000..6cacd43
--- /dev/null
+++ b/scripts/check_native_conversations.py
@@ -0,0 +1,359 @@
+"""Check real native Hermes conversation loops with synthetic loopback replies.
+
+Each case runs in a fresh process and isolated home. A second process loads the saved
+session. No host code is patched or wrapped. Reports contain metadata only.
+These checks do not prove live provider support, summary quality, or cache reuse.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import os
+from pathlib import Path
+import platform
+import shutil
+import subprocess
+import sys
+import tempfile
+import threading
+import traceback
+
+ROOT = Path(__file__).resolve().parents[1]
+CASES = ("responses_manual", "responses_auto_tool", "anthropic_manual", "anthropic_auto_tool")
+MODEL = "synthetic-model"
+KEY = "synthetic-api-key"
+CONTEXT_LENGTH = 200_000
+SID = "synthetic-native-session"
+
+
+def mode_for(case):
+ return "codex_responses" if case.startswith("responses_") else "anthropic_messages"
+
+
+def source_state(source):
+ from check_hermes_compatibility import source_state as inspect_source
+ state = inspect_source(source)
+ if not state["clean"]:
+ raise ValueError("hermes_source_not_clean")
+ return state
+
+
+def hashes():
+ from check_plugin_hermes import plugin_files_sha256
+ return plugin_files_sha256()
+
+
+def helper_hashes():
+ names = ("check_provider_apis.py", "check_plugin_hermes.py", "check_hermes_compatibility.py")
+ return {name: hashlib.sha256((ROOT / "scripts" / name).read_bytes()).hexdigest() for name in names}
+
+
+def native_server(case, reload_phase):
+ """Reuse the native server. Change only the synthetic response plan."""
+ from check_provider_apis import FakeServer, HANDOFF, MAIN_TEXT, TOOL_ID, TOOL_NAME
+
+ class ConversationServer(FakeServer):
+ def __init__(self):
+ self.main_count = 0
+ super().__init__("responses_text" if case.startswith("responses_") else "anthropic_text")
+
+ def payload(self, kind):
+ payload = super().payload(kind)
+ if kind != "main":
+ return payload
+ self.main_count += 1
+ tool = case.endswith("_auto_tool") and not reload_phase and self.main_count == 1
+ prompt_tokens = 150_000 if tool else 2_000
+ if mode_for(case) == "codex_responses":
+ payload["usage"]["input_tokens"] = prompt_tokens
+ payload["usage"]["total_tokens"] = prompt_tokens + 40
+ if tool:
+ payload["output"] = [{"type": "function_call", "id": "fc_native", "call_id": TOOL_ID,
+ "status": "completed", "name": TOOL_NAME, "arguments": "{}"}]
+ else:
+ payload["output"][0]["content"][0]["text"] = MAIN_TEXT
+ else:
+ payload["usage"]["input_tokens"] = prompt_tokens - 120
+ if tool:
+ payload["content"] = [{"type": "tool_use", "id": TOOL_ID, "name": TOOL_NAME, "input": {}}]
+ payload["stop_reason"] = "tool_use"
+ return payload
+
+ return ConversationServer(), HANDOFF, MAIN_TEXT
+
+
+def row_content(rows):
+ """Compare persisted public conversation fields. Ignore host database markers."""
+ fields = ("role", "content", "tool_calls", "tool_call_id", "codex_reasoning_items",
+ "codex_message_items", "reasoning_content", "phase", "reasoning_details", "anthropic_content_blocks")
+ return [{key: row[key] for key in fields if key in row and row[key] is not None} for row in rows]
+
+
+def check_warm_wire(server, checks):
+ """The last real main request must be the exact warm prefix."""
+ from check_provider_apis import HANDOFF, TOOL_ID
+ warm = [r for r in server.requests if r["kind"] == "warm"]
+ checks["one_native_warm_request"] = len(warm) == 1
+ if not warm:
+ return
+ index = server.requests.index(warm[0])
+ main = [r for r in server.requests[:index] if r["kind"] == "main"][-1]
+ sent, earlier = warm[0]["body"], main["body"]
+ field = "input" if "input" in earlier else "messages"
+ checks["native_warm_prefix_exact"] = sent[field][:len(earlier[field])] == earlier[field]
+ checks["native_warm_prompt_tools_exact"] = all(sent.get(key) == earlier.get(key)
+ for key in ("instructions", "system", "tools"))
+ checks["native_warm_endpoint_exact"] = warm[0]["path"] == main["path"]
+ header = "authorization" if field == "input" else "x-api-key"
+ checks["native_auth_exact"] = main["headers"].get(header) == warm[0]["headers"].get(header) == (
+ f"Bearer {KEY}" if field == "input" else KEY)
+ checks["no_json_headers"] = "extra_headers" not in sent
+ checks["no_fallback"] = not any(r["kind"] == "fallback" for r in server.requests)
+ checks["handoff_not_in_main_output"] = HANDOFF not in json.dumps(earlier)
+ if any(TOOL_ID in json.dumps(r["body"]) for r in server.requests[:index + 1]):
+ if field == "input":
+ calls = [x for x in sent[field] if x.get("type") == "function_call" and x.get("call_id") == TOOL_ID]
+ outputs = [x for x in sent[field] if x.get("type") == "function_call_output"
+ and x.get("call_id") == TOOL_ID]
+ else:
+ blocks = [b for row in sent[field] if isinstance(row.get("content"), list) for b in row["content"]]
+ calls = [b for b in blocks if b.get("type") == "tool_use" and b.get("id") == TOOL_ID]
+ outputs = [b for b in blocks if b.get("type") == "tool_result" and b.get("tool_use_id") == TOOL_ID]
+ checks["native_tool_pair_once"] = len(calls) == len(outputs) == 1
+ checks["real_tool_result_replayed"] = len(outputs) == 1 and "The test note says BLUE-7." in json.dumps(outputs)
+
+
+def worker(source, case, dependency_paths, phase):
+ """Run the host loop. Do not call plugin hooks or middleware by hand."""
+ sys.path[:0] = [str(source), *map(str, dependency_paths), str(ROOT / "scripts")]
+ from check_plugin_hermes import Fence, merge_config, summary_rows_ok, synthetic_history
+ home = Path(os.environ["HERMES_HOME"])
+ scenario = home.parent
+ installed = home / "plugins" / "warm_compaction"
+ server, handoff, main_text = native_server(case, phase == "reload")
+ server.thread.start()
+ fence = Fence(scenario, server.httpd.server_port, source, installed)
+
+ def early_network_fence(event, args):
+ if event in {"socket.getaddrinfo", "socket.connect", "socket.connect_ex"}:
+ fence(event, args)
+
+ sys.addaudithook(early_network_fence)
+ result = {"case": case, "phase": phase, "status": "failed", "checks": {}, "error": None}
+ checks = result["checks"]
+ db, agent = None, None
+ try:
+ merge_config(home / "config.yaml", {
+ "model": {"default": MODEL, "model": MODEL, "provider": "custom", "base_url": server.base_url,
+ "api_key": KEY, "api_mode": mode_for(case), "context_length": CONTEXT_LENGTH,
+ "streaming": False},
+ "context": {"engine": "warm_compaction"},
+ "tools": {"tool_search": {"enabled": "off"}},
+ "compression": {"progress_notices": False},
+ "auxiliary": {"warm_compaction": {"provider": "auto", "model": MODEL},
+ "title_generation": {"enabled": False, "model_upgrade_enabled": False}},
+ "plugins": {"enabled": ["warm_compaction", "wc_test_tools"], "hook_callback_timeout": 0,
+ "entries": {"warm_compaction": {"settings": {"threshold": 0.4, "tail_tokens": 1024}}}},
+ })
+ # A fresh synthetic catalogue prevents host discovery from making an external request.
+ (home / "models_dev_cache.json").write_text(json.dumps({"synthetic": {"models": {}}}), encoding="utf-8")
+ platform.uname()
+ platform.platform()
+ platform.architecture()
+ from run_agent import AIAgent
+ from hermes_state import SessionDB
+ from agent.conversation_compression import finalize_context_engine_compression_notification
+ from tui_gateway.server import _compress_session_history
+ from agent.transports import registered_api_modes
+ from hermes_cli import plugins
+ manager = plugins.get_plugin_manager()
+ manager.discover_and_load()
+ from tools.registry import registry
+ from toolsets import resolve_toolset
+ result["tool_discovery"] = {"registered": registry.get_entry("wc_note") is not None,
+ "selected": "wc_note" in resolve_toolset("wc_test"),
+ "same_scope": registry.current_scope_key() == manager.scope_key,
+ "loaded": [{"name": p.manifest.name, "enabled": p.enabled,
+ "error_present": bool(p.error)} for p in manager._plugins.values()
+ if p.manifest.name == "wc_test_tools"]}
+ available = mode_for(case) in registered_api_modes()
+ result["native_capability"] = "supported" if available else "unavailable"
+ if not available:
+ result["error"] = "native_transport_unavailable"
+ return result
+ origin = Path(sys.modules[AIAgent.__module__].__file__).resolve()
+ checks["agent_origin_is_pinned_source"] = origin.is_relative_to(source)
+ sys.addaudithook(fence)
+ db = SessionDB(home / "state.db")
+ if phase == "run":
+ db.create_session(SID, "cli")
+ history = synthetic_history(20)
+ for row in history:
+ row["content"] = row["content"].strip()
+ db.append_messages_batch(SID, history)
+ session_id = SID
+ else:
+ session_id = (scenario / "session-id").read_text(encoding="utf-8")
+ agent = AIAgent(base_url=server.base_url, api_key=KEY, provider="custom", api_mode=mode_for(case), model=MODEL,
+ enabled_toolsets=["wc_test"] if case.endswith("_auto_tool") else [], disabled_toolsets=[],
+ quiet_mode=True, skip_context_files=True, skip_memory=True, skip_background_review=True,
+ capabilities={"vision": False}, session_id=session_id, session_db=db, max_tokens=4096,
+ reasoning_config={"enabled": False}, platform="cli", cwd=str(scenario), max_iterations=5)
+ engine = agent.context_compressor
+ checks["plugin_selected"] = getattr(engine, "name", None) == "warm_compaction"
+ checks["plugin_origin_is_temporary_install"] = Path(
+ sys.modules[type(engine).__module__].__file__).resolve().is_relative_to(installed)
+ history = db.get_messages_as_conversation(session_id, repair_alternation=True)
+ if phase == "reload":
+ checks["reloaded_summary"] = summary_rows_ok(history)
+ checks["reload_has_no_process_capture"] = engine._store.latest(session_id) is None
+ before = json.loads((scenario / "saved-shape.json").read_text(encoding="utf-8"))
+ checks["saved_native_rows_exact_after_process_reload"] = row_content(history) == before
+ reply = agent.run_conversation("Continue the synthetic task.", system_message="Keep the code word BLUE-7.",
+ conversation_history=history)
+ messages = reply.get("messages") or []
+ checks["real_conversation_final_reply"] = reply.get("final_response") == main_text
+ checks["real_conversation_not_failed"] = not reply.get("failed")
+ auto = case.endswith("_auto_tool") and phase == "run"
+ if auto:
+ checks["tool_registered"] = "wc_note" in agent.valid_tool_names
+ checks["automatic_summary_rows"] = summary_rows_ok(messages)
+ checks["actual_loop_request_order"] = [r["kind"] for r in server.requests] == ["main", "warm", "main"]
+ checks["tool_result_retained"] = any(r.get("role") == "tool" and
+ "The test note says BLUE-7." in str(r.get("content")) for r in messages)
+ else:
+ capture = engine._store.latest(engine._wc_session_id) or {}
+ main = [r for r in server.requests if r["kind"] == "main"][-1]
+ # Hermes adds stream=True for Responses after capture. All other fields must match.
+ wire = dict(main["body"])
+ if mode_for(case) == "codex_responses":
+ checks["responses_stream_added_by_host"] = wire.pop("stream", None) is True
+ checks["real_hook_capture_exact_wire"] = capture.get("body") == wire
+ checks["real_post_hook_usage"] = capture.get("prompt_tokens") == 2_000
+ checks["real_hook_capture_no_refusal"] = capture.get("refusal") is None
+ session = {"agent": agent, "history": list(messages), "history_lock": threading.Lock(),
+ "history_version": 1, "session_key": agent.session_id}
+ removed, _usage = _compress_session_history(session, "")
+ finalize_context_engine_compression_notification(agent, committed=True)
+ checks["manual_real_entry_result_valid"] = removed >= 0 if phase == "reload" else removed > 0
+ checks["manual_real_entry_compression_count"] = engine.compression_count == 1
+ checks["manual_real_entry_summary_rows"] = summary_rows_ok(session["history"])
+ checks["manual_request_order"] = [r["kind"] for r in server.requests] == ["main", "warm"]
+ messages = session["history"]
+ outcome = engine.warm_last or {}
+ result["outcome"] = {k: outcome.get(k) for k in ("path", "reason", "prompt_tokens", "cached_tokens")}
+ checks["warm_accepted"] = (outcome.get("path"), outcome.get("reason")) == ("warm", "accepted")
+ checks["synthetic_cached_counter"] = outcome.get("cached_tokens") == 120
+ checks["synthetic_summary_in_history"] = any(handoff in str(r.get("content")) for r in messages)
+ checks["engine_session_follows_host"] = engine._wc_session_id == agent.session_id
+ check_warm_wire(server, checks)
+ saved = db.get_messages_as_conversation(agent.session_id)
+ checks["native_history_saved_exact"] = row_content(saved) == row_content(messages)
+ if not checks["native_history_saved_exact"]:
+ result["history_mismatch"] = [{"index": i, "keys": [key for key in set(a) | set(b)
+ if a.get(key) != b.get(key)]} for i, (a, b) in enumerate(zip(row_content(saved), row_content(messages)))
+ if a != b]
+ result["fence_callers"] = sorted(fence.callers)
+ if phase == "run":
+ (scenario / "session-id").write_text(agent.session_id, encoding="utf-8")
+ (scenario / "saved-shape.json").write_text(json.dumps(row_content(saved)), encoding="utf-8")
+ result["request_counts"] = {kind: sum(r["kind"] == kind for r in server.requests)
+ for kind in ("main", "warm", "fallback")}
+ result["history_rows"] = len(saved)
+ result["compression_count"] = engine.compression_count
+ result["fence_denied"] = fence.denied
+ checks["plugin_made_no_blocked_call"] = fence.plugin_denied == 0
+ # Host startup can probe release metadata. The fence blocks each non-loopback attempt.
+ result["blocked_host_network_attempts"] = sum(v for k, v in fence.denied.items() if k.startswith("network_"))
+ checks["no_private_profile_read"] = "private_profile_read_blocked" not in fence.denied
+ result["status"] = "passed" if checks and all(checks.values()) else "failed"
+ return result
+ finally:
+ if agent is not None:
+ agent.close()
+ if db is not None:
+ db.close()
+ server.httpd.shutdown()
+ server.httpd.server_close()
+
+
+def run(source, cases, paths):
+ """Discard synthetic histories and captured worker output when each case ends."""
+ from check_hermes_compatibility import worker_environment
+ from check_plugin_hermes import TOOL_PLUGIN
+ report = {"check": "native full Hermes conversation loops", "python": sys.version.split()[0],
+ "hermes": source_state(source), "synthetic": True, "live_provider": False,
+ "cache_reuse_proved": False, "privacy": "metadata only", "cases": [], "error": None,
+ "plugin_sha256": hashes(), "helper_sha256": helper_hashes(),
+ "script_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest()}
+ for case in cases:
+ with tempfile.TemporaryDirectory(prefix="wc-native-loop-") as folder:
+ scenario = Path(folder)
+ for name in ("home", "runtime", "os-home", "tmp"):
+ (scenario / name).mkdir()
+ home = scenario / "home"
+ shutil.copytree(ROOT / "warm_compaction", home / "plugins" / "warm_compaction",
+ ignore=shutil.ignore_patterns("__pycache__"))
+ tool = home / "plugins" / "wc_test_tools"
+ tool.mkdir()
+ for name, content in TOOL_PLUGIN.items():
+ (tool / name).write_text(content, encoding="utf-8")
+ result = {"case": case, "phases": [], "passed": False}
+ for phase in ("run", "reload"):
+ target = scenario / f"{phase}.json"
+ command = [sys.executable, "-I", "-B", str(Path(__file__).resolve()), "--hermes-source", str(source),
+ "--worker-case", case, "--phase", phase, "--report", str(target)]
+ for path in paths:
+ command += ["--dependency-path", str(path)]
+ completed = subprocess.run(command, cwd=scenario, env=worker_environment(home),
+ capture_output=True, timeout=240)
+ item = json.loads(target.read_text(encoding="utf-8")) if target.exists() else {
+ "status": "failed", "error": "worker_no_report", "checks": {}}
+ item["exit_ok"] = completed.returncode == 0
+ result["phases"].append(item)
+ if item["status"] != "passed" or not item["exit_ok"]:
+ break
+ result["passed"] = len(result["phases"]) == 2 and all(
+ p["status"] == "passed" and p["exit_ok"] for p in result["phases"])
+ report["cases"].append(result)
+ print(f"{case}: {'passed' if result['passed'] else 'failed'}", flush=True)
+ report["hermes_source_unchanged"] = source_state(source) == report["hermes"]
+ report["plugin_source_unchanged"] = hashes() == report["plugin_sha256"]
+ report["helpers_unchanged"] = helper_hashes() == report["helper_sha256"]
+ report["script_unchanged"] = hashlib.sha256(Path(__file__).read_bytes()).hexdigest() == report["script_sha256"]
+ guards = ("hermes_source_unchanged", "plugin_source_unchanged", "script_unchanged", "helpers_unchanged")
+ report["passed"] = all(report[k] for k in guards) and all(c["passed"] for c in report["cases"])
+ return report
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--hermes-source", type=Path, required=True)
+ parser.add_argument("--dependency-path", type=Path, action="append", default=[])
+ parser.add_argument("--case", choices=CASES, action="append")
+ parser.add_argument("--report", type=Path)
+ parser.add_argument("--worker-case", choices=CASES, help=argparse.SUPPRESS)
+ parser.add_argument("--phase", choices=("run", "reload"), default="run", help=argparse.SUPPRESS)
+ args = parser.parse_args()
+ source, paths = args.hermes_source.resolve(), [p.resolve() for p in args.dependency_path]
+ try:
+ report = worker(source, args.worker_case, paths, args.phase) if args.worker_case else run(
+ source, args.case or CASES, paths)
+ except Exception as error:
+ code = "worker_runtime_failed" if args.worker_case else "setup_failed"
+ report = {"passed": False, "status": "failed", "error": code,
+ "error_type": type(error).__name__, "checks": {},
+ "error_locations": [{"file": Path(f.filename).name, "function": f.name, "line": f.lineno}
+ for f in traceback.extract_tb(error.__traceback__)[-3:]]}
+ passed = report.get("passed", report.get("status") == "passed")
+ if args.report:
+ args.report.parent.mkdir(parents=True, exist_ok=True)
+ args.report.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
+ print(json.dumps({"passed": passed, "error": report.get("error")}))
+ return 0 if passed else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/check_provider_apis.py b/scripts/check_provider_apis.py
index 830e62a..3bfef50 100644
--- a/scripts/check_provider_apis.py
+++ b/scripts/check_provider_apis.py
@@ -122,11 +122,12 @@ class FakeServer:
if body.get("stream") and mode_for(owner.case) == "codex_responses":
event = "response.incomplete" if payload["status"] == "incomplete" else "response.completed"
parts = []
+ # The real conversation loop reads completed items, not the terminal output list.
+ for index, item in enumerate(payload["output"]):
+ done = {"type": "response.output_item.done", "output_index": index, "item": item}
+ parts.append("event: response.output_item.done\ndata: " + json.dumps(done) + "\n\n")
if owner.case == "responses_codex" and kind == "warm":
# The consumer route can send completed items before an empty terminal envelope.
- for index, item in enumerate(payload["output"]):
- done = {"type": "response.output_item.done", "output_index": index, "item": item}
- parts.append("event: response.output_item.done\ndata: " + json.dumps(done) + "\n\n")
payload = {**payload, "output": None}
parts.append(f"event: {event}\ndata: "
+ json.dumps({"type": event, "response": payload}) + "\n\n")
diff --git a/tests/property/test_native_properties.py b/tests/property/test_native_properties.py
new file mode 100644
index 0000000..cc20485
--- /dev/null
+++ b/tests/property/test_native_properties.py
@@ -0,0 +1,360 @@
+"""Bounded native API properties. All data is synthetic; no provider request runs."""
+
+from __future__ import annotations
+
+import copy
+import json
+import sys
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import patch
+
+from hypothesis import given, settings, strategies as st
+
+from warm_compaction import anthropic, handoff, protocol, responses, warm
+from warm_compaction.capture import CaptureStore
+from warm_compaction.rows import row_digest
+
+RESPONSES = ("fake-model", "http://127.0.0.1:9/v1", "codex_responses")
+CODEX = ("fake-model", "https://chatgpt.com/backend-api/codex", "codex_responses")
+MESSAGES = ("fake-model", "http://127.0.0.1:9", "anthropic_messages")
+ANTHROPIC = ("fake-model", "https://api.anthropic.com", "anthropic_messages")
+TEXT = st.text(alphabet="abcdefghijklmnopqrstuvwxyz ABCXYZ0123456789éλ\n\t", min_size=1, max_size=40)
+SEALED = st.binary(min_size=1, max_size=40).map(bytes.hex)
+PROPERTIES = settings(max_examples=60, deadline=None, derandomize=True, database=None)
+INSTRUCTION = "Write a synthetic handoff."
+
+
+def user(text):
+ return {"role": "user", "content": "Synthetic " + text}
+
+
+def assistant(text, calls=(), **extra):
+ row = {"role": "assistant", "content": "Synthetic " + text, **extra}
+ if calls:
+ row["tool_calls"] = [{"id": call_id, "type": "function", "function": {
+ "name": "read", "arguments": json.dumps(arguments)}} for call_id, arguments in calls]
+ return row
+
+
+def tool(call_id, text):
+ return {"role": "tool", "tool_call_id": call_id, "content": "Synthetic " + text}
+
+
+def histories(draw):
+ """Make complete turns with distinct tool IDs and a final user request."""
+ rows = []
+ turns = draw(st.lists(st.tuples(TEXT, TEXT, st.booleans()), min_size=1, max_size=5))
+ for index, (question, answer, use_tool) in enumerate(turns):
+ rows.append(user(question))
+ calls = [(f"call_{index}", {"path": answer, "index": index})] if use_tool else []
+ rows.append(assistant(answer, calls))
+ if use_tool:
+ rows.append(tool(f"call_{index}", answer))
+ rows.append(user(draw(TEXT)))
+ return rows
+
+
+def capture(rows, reply, route):
+ """Make a native capture with fake route and session values."""
+ body = {"model": route[0]}
+ if route[2] == "codex_responses":
+ body.update(instructions="Synthetic system rule.", store=False,
+ input=responses.wire_rows(rows, route[1], model=route[0]))
+ else:
+ body.update(system=[{"type": "text", "text": "Synthetic system rule.",
+ "cache_control": {"type": "ephemeral"}}],
+ messages=anthropic._rows(rows), max_tokens=4096, thinking={"type": "disabled"})
+ return {"session_id": "synthetic-session", "route": route, "body": body,
+ "digests": [row_digest(row) for row in rows], "reply": {
+ "content": reply["content"], "tool_calls": [[call["id"], call["function"]["name"]]
+ for call in reply.get("tool_calls", [])]}}
+
+
+def build(saved, rows, route):
+ adapter = responses if route[2] == "codex_responses" else anthropic
+ return adapter.build_request(saved, rows, route, 200_000, INSTRUCTION)
+
+
+def summary(text):
+ return "\n\n".join(heading + "\nSynthetic " + text for heading in handoff.HEADINGS)
+
+
+def sse(events):
+ return "".join("data: " + json.dumps(event, ensure_ascii=False) + "\n\n" for event in events).encode()
+
+
+def response_events(text):
+ item = {"id": "msg_synthetic", "type": "message", "role": "assistant", "status": "completed",
+ "content": [{"type": "output_text", "text": text}]}
+ return [{"type": "response.output_item.added", "output_index": 0,
+ "item": {"id": item["id"], "type": "message"}},
+ {"type": "response.output_text.delta", "output_index": 0, "item_id": item["id"], "delta": text},
+ {"type": "response.output_item.done", "output_index": 0, "item": item},
+ {"type": "response.completed", "response": {"status": "completed", "output": []}}]
+
+
+def message_events(text, chunks):
+ points = sorted({0, len(text), *(point % (len(text) + 1) for point in chunks)})
+ return [{"type": "message_start", "message": {"type": "message", "role": "assistant", "usage": {}}},
+ {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}},
+ *[{"type": "content_block_delta", "index": 0, "delta": {
+ "type": "text_delta", "text": text[start:end]}} for start, end in zip(points, points[1:])],
+ {"type": "content_block_stop", "index": 0},
+ {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {}},
+ {"type": "message_stop"}]
+
+
+def accepted(raw, mode):
+ """Run the same envelope, native reply, and handoff gates as the warm path."""
+ try:
+ payload = protocol.envelope(raw, mode)
+ reply = (responses if mode == "codex_responses" else anthropic).parse_reply(payload)
+ except warm.WarmRefusal:
+ return None
+ return handoff.gate(reply)[0]
+
+
+class NativeHistoryProperties(unittest.TestCase):
+ @PROPERTIES
+ @given(histories(), TEXT, st.sampled_from((RESPONSES, CODEX, MESSAGES)), st.lists(TEXT, max_size=4))
+ def test_extension_keeps_captured_prefix_and_does_not_change_inputs(self, rows, answer, route, new_users):
+ reply = assistant(answer)
+ saved = capture(rows, reply, route)
+ current = [*rows, reply, *(user(text) for text in new_users)]
+ before = copy.deepcopy((saved, current))
+ body = build(saved, current, route)
+ field = protocol.history_key(route[2])
+ prefix = before[0]["body"][field]
+ self.assertEqual(json.dumps(body[field][:len(prefix)]), json.dumps(prefix))
+ self.assertEqual((saved, current), before)
+ # Editing the result must not edit the in-memory capture.
+ body[field][0].clear()
+ self.assertEqual((saved, current), before)
+
+ @PROPERTIES
+ @given(histories(), TEXT, st.sampled_from((RESPONSES, MESSAGES)), st.integers(min_value=0, max_value=50))
+ def test_changed_stored_history_cannot_use_the_capture(self, rows, answer, route, position):
+ reply = assistant(answer)
+ saved = capture(rows, reply, route)
+ changed = copy.deepcopy(rows)
+ changed[position % len(changed)]["content"] += " changed"
+ with self.assertRaises(warm.WarmRefusal):
+ build(saved, [*changed, reply], route)
+
+ @PROPERTIES
+ @given(histories(), TEXT, st.sampled_from((RESPONSES, MESSAGES)), st.integers(min_value=1, max_value=4), st.data())
+ def test_new_tool_pairs_match_even_with_result_order_changes(self, rows, answer, route, count, data):
+ calls = [(f"new_{index}", {"path": answer, "index": index}) for index in range(count)]
+ reply = assistant(answer, calls)
+ results = [tool(call_id, answer) for call_id, _ in calls]
+ order = data.draw(st.permutations(results))
+ saved = capture(rows, reply, route)
+ body = build(saved, [*rows, reply, *order], route)
+ if route[2] == "codex_responses":
+ tail = body["input"][len(saved["body"]["input"]):]
+ sent_calls = [item["call_id"] for item in tail if item["type"] == "function_call"]
+ sent_results = [item["call_id"] for item in tail if item["type"] == "function_call_output"]
+ else:
+ blocks = [block for row in body["messages"][len(saved["body"]["messages"]):]
+ for block in row["content"]]
+ sent_calls = [block["id"] for block in blocks if block["type"] == "tool_use"]
+ sent_results = [block["tool_use_id"] for block in blocks if block["type"] == "tool_result"]
+ self.assertCountEqual(sent_calls, sent_results)
+ self.assertEqual(len(sent_calls), count)
+ for broken in (results[:-1], [*results, results[0]], [tool("unknown", answer), *results[1:]]):
+ with self.assertRaises(warm.WarmRefusal):
+ build(saved, [*rows, reply, *broken], route)
+
+ @PROPERTIES
+ @given(TEXT, SEALED, SEALED)
+ def test_signed_messages_payload_stays_intact_or_refuses(self, text, signature, redacted):
+ rows, reply = [user(text)], assistant(text)
+ blocks = [{"type": "thinking", "thinking": text, "signature": signature},
+ {"type": "redacted_thinking", "data": redacted}]
+ reply.update(reasoning_details=blocks, reasoning_content=text)
+ saved = capture(rows, reply, ANTHROPIC)
+ before = copy.deepcopy(reply)
+ body = build(saved, [*rows, reply], ANTHROPIC)
+ self.assertEqual(body["messages"][-2]["content"][:2], blocks)
+ self.assertEqual(reply, before)
+ invalid = copy.deepcopy(reply)
+ invalid["reasoning_details"][0].pop("signature")
+ with self.assertRaises(warm.WarmRefusal):
+ build(saved, [*rows, invalid], ANTHROPIC)
+ custom = capture(rows, reply, MESSAGES)
+ with self.assertRaises(warm.WarmRefusal):
+ build(custom, [*rows, reply], MESSAGES)
+
+ @PROPERTIES
+ @given(TEXT, SEALED, st.sampled_from(("_issuer_model", "_issuer_kind")))
+ def test_encrypted_responses_payload_stays_intact_or_refuses(self, text, sealed, stamp):
+ rows = [user(text)]
+ native = {"type": "reasoning", "encrypted_content": sealed,
+ "_issuer_kind": "codex_backend", "_issuer_model": CODEX[0]}
+ reply = assistant(text, codex_reasoning_items=[native])
+ saved = capture(rows, reply, CODEX)
+ before = copy.deepcopy(reply)
+ body = build(saved, [*rows, reply], CODEX)
+ replayed = [item for item in body["input"] if item["type"] == "reasoning"]
+ self.assertEqual([item["encrypted_content"] for item in replayed], [sealed])
+ self.assertEqual(reply, before)
+ invalid = copy.deepcopy(reply)
+ invalid["codex_reasoning_items"][0][stamp] = "foreign"
+ with self.assertRaises(warm.WarmRefusal):
+ build(saved, [*rows, invalid], CODEX)
+
+
+class NativeStreamProperties(unittest.TestCase):
+ @PROPERTIES
+ @given(TEXT, st.lists(st.integers(min_value=0, max_value=1000), max_size=12))
+ def test_messages_chunk_boundaries_do_not_change_the_handoff(self, text, chunks):
+ handoff_text = summary(text)
+ self.assertEqual(accepted(sse(message_events(handoff_text, chunks)), "anthropic_messages"),
+ handoff_text.strip())
+
+ @PROPERTIES
+ @given(TEXT, st.sampled_from(("terminal", "block_stop", "wrong_delta", "length", "error", "duplicate_stop")))
+ def test_unsafe_messages_event_sequences_cannot_yield_a_handoff(self, text, fault):
+ events = message_events(summary(text), [])
+ if fault == "terminal":
+ events.pop()
+ elif fault == "block_stop":
+ events = [event for event in events if event["type"] != "content_block_stop"]
+ elif fault == "wrong_delta":
+ events[2]["delta"]["type"] = "thinking_delta"
+ elif fault == "length":
+ events[-2]["delta"]["stop_reason"] = "max_tokens"
+ elif fault == "error":
+ events.insert(3, {"type": "error", "error": {"type": "synthetic_error"}})
+ else:
+ events.append({"type": "message_stop"})
+ self.assertIsNone(accepted(sse(events), "anthropic_messages"))
+
+ @PROPERTIES
+ @given(TEXT, st.sampled_from(("terminal", "done", "identity", "duplicate", "length", "tool", "refusal")))
+ def test_unsafe_responses_event_sequences_cannot_yield_a_handoff(self, text, fault):
+ events = response_events(summary(text))
+ self.assertEqual(accepted(sse(events), "codex_responses"), summary(text).strip())
+ if fault == "terminal":
+ events.pop()
+ elif fault == "done":
+ events.pop(2)
+ elif fault == "identity":
+ events[2]["item"]["id"] = "msg_foreign"
+ elif fault == "duplicate":
+ events.insert(3, copy.deepcopy(events[2]))
+ elif fault == "length":
+ events[-1]["response"]["status"] = "incomplete"
+ elif fault == "tool":
+ events.insert(3, {"type": "response.output_item.done", "output_index": 1,
+ "item": {"id": "fc_synthetic", "type": "function_call", "name": "read"}})
+ else:
+ events[2]["item"]["content"].append({"type": "refusal", "refusal": "Synthetic refusal."})
+ self.assertIsNone(accepted(sse(events), "codex_responses"))
+
+ @PROPERTIES
+ @given(TEXT, st.sampled_from(("codex_responses", "anthropic_messages")), st.integers(min_value=0, max_value=5000))
+ def test_truncated_native_stream_cannot_yield_a_handoff(self, text, mode, position):
+ events = response_events(summary(text)) if mode == "codex_responses" else message_events(summary(text), [])
+ raw = sse(events)
+ # The cut removes at least the final JSON brace, not only the optional SSE separator.
+ cut = position % (len(raw) - 2)
+ self.assertIsNone(accepted(raw[:cut], mode))
+
+ @PROPERTIES
+ @given(TEXT, st.sampled_from(("codex_responses", "anthropic_messages")), st.integers(min_value=0, max_value=5000))
+ def test_malformed_native_bytes_cannot_yield_a_handoff(self, text, mode, position):
+ events = response_events(summary(text)) if mode == "codex_responses" else message_events(summary(text), [])
+ raw = sse(events)
+ cut = position % len(raw)
+ self.assertIsNone(accepted(raw[:cut] + b"\xff" + raw[cut:], mode))
+
+
+class CaptureLifecycleProperties(unittest.TestCase):
+ def setUp(self):
+ # The separate property command has no tests/ path. Load only the existing synthetic Hermes stand-in.
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+ self.addCleanup(sys.path.pop, 0)
+ import wc_hermes_stub
+ wc_hermes_stub.install(self)
+
+ @PROPERTIES
+ @given(histories(), TEXT, st.sampled_from((RESPONSES, MESSAGES)),
+ st.lists(st.sampled_from(("same", "route", "provider", "credential", "session", "history")),
+ min_size=1, max_size=12))
+ def test_capture_cannot_cross_identity_or_history_changes(self, rows, answer, route, actions):
+ from warm_compaction.engine import WarmCompactionEngine
+ reply = assistant(answer)
+ saved = capture(rows, reply, route)
+ store = CaptureStore()
+ engine = WarmCompactionEngine(store=store)
+ engine.update_model(*route[:1], 200_000, base_url=route[1], api_mode=route[2],
+ provider="synthetic-provider", api_key="synthetic-key")
+ engine.on_session_start("synthetic-session")
+ saved["key_stamp"] = engine._key_stamp()
+ store._sessions["synthetic-session"] = copy.deepcopy(saved)
+ current = copy.deepcopy([*rows, reply])
+ valid = True
+ for step, action in enumerate(actions):
+ if action == "same":
+ engine.update_model(engine._wc_route[0], 200_000, base_url=engine._wc_route[1],
+ api_mode=engine._wc_route[2], provider=engine._wc_provider,
+ api_key=engine._wc_api_key)
+ elif action in ("route", "provider", "credential"):
+ provider = f"changed-provider-{step}" if action == "provider" else engine._wc_provider
+ engine.update_model("changed-model" if action == "route" else engine._wc_route[0],
+ 200_000, base_url=engine._wc_route[1], api_mode=engine._wc_route[2],
+ provider=provider,
+ api_key=f"changed-key-{step}" if action == "credential" else engine._wc_api_key)
+ valid = False
+ elif action == "session":
+ engine.on_session_start(f"changed-session-{step}")
+ valid = False
+ else:
+ current[0]["content"] += " changed"
+ valid = False
+ record = {}
+ with patch.object(engine, "_execute", return_value={"content": summary("state"), "finish_reason": "stop",
+ "tool_calls": False, "refusal": False, "prompt_tokens": None,
+ "cached_tokens": None}) as send:
+ candidate = engine._warm_summary(current, store.latest(engine._wc_session_id), None, "", (),
+ record, engine._attempt())
+ self.assertEqual(candidate is not None, valid)
+ self.assertEqual(send.called, valid)
+
+ @PROPERTIES
+ @given(TEXT, st.lists(st.sampled_from(("same", "rotate", "forget", "wrong_session")), min_size=1, max_size=10))
+ def test_open_capture_is_not_published_after_key_or_session_changes(self, text, actions):
+ import wc_hermes_stub
+ store = CaptureStore()
+ credential = ["synthetic-stamp"]
+ store.set_stamp("synthetic-session", lambda: credential[0])
+ rows = [user(text)]
+ store.on_pre_api_request(api_request_id="synthetic-request", session_id="synthetic-session",
+ conversation_history=rows, model=RESPONSES[0], base_url=RESPONSES[1],
+ api_mode=RESPONSES[2])
+ wc_hermes_stub.CAPTURE_CHAIN[:] = [store.on_llm_execution]
+ store.on_llm_execution(api_request_id="synthetic-request", request=capture(rows, assistant(text),
+ RESPONSES)["body"], next_call=lambda: None)
+ valid = True
+ session = "synthetic-session"
+ for step, action in enumerate(actions):
+ if action == "rotate":
+ credential[0] = f"changed-stamp-{step}"
+ valid = False
+ elif action == "forget":
+ store.forget("synthetic-session")
+ valid = False
+ elif action == "wrong_session":
+ session = "different-session"
+ valid = False
+ store.on_post_api_request(api_request_id="synthetic-request", session_id=session, finish_reason="stop",
+ assistant_message=SimpleNamespace(content="Synthetic reply", tool_calls=[]))
+ self.assertEqual(store.latest("synthetic-session") is not None, valid)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_wc_responses.py b/tests/test_wc_responses.py
index 760db70..e50a4c0 100644
--- a/tests/test_wc_responses.py
+++ b/tests/test_wc_responses.py
@@ -65,6 +65,16 @@ class ResponsesSourceTest(unittest.TestCase):
wire = responses.wire_rows(rows)
self.assertEqual([item["call_id"] for item in wire], ["call_a", "call_a"])
+ def test_copilot_host_check_requires_a_domain_boundary(self):
+ row = assistant("a", codex_message_items=[{
+ "type": "message", "role": "assistant", "id": "msg_synthetic", "status": "completed",
+ "content": [{"type": "output_text", "text": "a"}]}])
+ for host, expected in (("githubcopilot.com", False), ("api.githubcopilot.com", False),
+ ("evilgithubcopilot.com", True), ("githubcopilot.com.evil.test", True)):
+ with self.subTest(host=host):
+ wire = responses.wire_rows([row], "https://" + host + "/v1")
+ self.assertEqual("id" in wire[0], expected)
+
def test_source_change_is_refused(self):
rows = [user("original")]
body = {"model": ROUTE[0], "instructions": "Synthetic system text.", "store": False,
diff --git a/warm_compaction/responses.py b/warm_compaction/responses.py
index ac45018..eb2c2b3 100644
--- a/warm_compaction/responses.py
+++ b/warm_compaction/responses.py
@@ -157,7 +157,8 @@ def _replay_messages(row: dict, content: str, base_url: Any) -> list:
raise WarmRefusal("source_transform_unsupported")
items, final_text = [], []
linked = bool(row.get("codex_reasoning_items") or row.get("codex_reasoning_trimmed"))
- copilot = (urlsplit(str(base_url or "")).hostname or "").endswith("githubcopilot.com")
+ host = urlsplit(str(base_url or "")).hostname or ""
+ copilot = host == "githubcopilot.com" or host.endswith(".githubcopilot.com")
for raw in replay:
if not isinstance(raw, dict) or raw.get("type") != "message" or raw.get("role") != "assistant":
raise WarmRefusal("source_transform_unsupported")