Files
hermes-agent/scripts/compression_eval/compressor_driver.py
Teknium 1e6285c53d feat: compression eval harness for agent/context_compressor.py
Ships a complete offline eval harness at scripts/compression_eval/. Runs
a real conversation fixture through ContextCompressor.compress(), asks
the compressor model to answer probe questions from the compressed
state, then has a judge model score each answer 0-5 on six dimensions
(accuracy, context_awareness, artifact_trail, completeness, continuity,
instruction_following). Methodology adapted from Factory's Dec 2025
write-up (https://factory.ai/news/evaluating-compression); the
scoreboard framing is not adopted.

Motivation: we edit context_compressor.py prompts and _template_sections
by hand and ship with no automated check that compression still
preserves file paths, error codes, or the active task. Until now there
has been no signal between 'test suite green' and 'a user hits a bad
summary in production.'

What's shipped
- DESIGN.md — full architecture, fixture/probe format, scrubber
  pipeline, grading rubric, open follow-ups
- README.md — usage, cost expectations, when to run it
- scrub_fixtures.py — reproducible pipeline that converts real sessions
  from ~/.hermes/sessions/*.jsonl into public-safe JSON fixtures. Applies
  agent.redact.redact_sensitive_text + username path normalisation +
  personal handle scrubbing + email/git-author normalisation + reasoning
  scratchpad stripping + platform-mention scrubbing + first-user
  paraphrase + system-prompt placeholder + orphan-message pruning + 2KB
  tool-output truncation
- fixtures/ — three scrubbed session snapshots covering three session
  shapes:
    feature-impl-context-priority  (75 msgs / ~17k tokens)
    debug-session-feishu-id-model  (59 msgs / ~13k tokens)
    config-build-competitive-scouts (61 msgs / ~23k tokens)
- probes/ — three probe banks (10-11 probes each) covering all four
  types (recall/artifact/continuation/decision) with expected_facts
  anchors (PR numbers, file paths, error codes, commands)
- rubric.py — six-dimension grading rubric, judge-prompt builder,
  JSON-with-fallback response parser
- compressor_driver.py — thin wrapper around ContextCompressor for
  forced single-shot compression (fixtures are below the default
  100k threshold so we force compress() to attribute score deltas
  to prompt changes, not threshold-fire variance)
- grader.py — two-phase continuation + grading calls via the OpenAI
  SDK directly against the resolved provider endpoint
- report.py — markdown report renderer (paste-ready for PR bodies),
  --compare-to delta mode, per-run JSON dumper
- run_eval.py — fire-style CLI (--fixtures, --runs, --judge-model,
  --compressor-model, --label, --focus-topic, --compare-to, --verbose)
- tests/scripts/test_compression_eval.py — 33 hermetic unit tests
  covering rubric parsing edge cases, judge-prompt building, report
  rendering, summariser medians, per-run JSON roundtrip, fixture and
  probe loading, and a PII smoke check on the checked-in fixtures

Non-LLM paths are covered by the 33-test suite that runs in CI. The
LLM paths (continuation + grading) require credentials and real API
calls, so they're exercised by running the eval itself — not by CI.

Validation
- 33/33 unit tests pass in 0.33s via scripts/run_tests.sh
- 50/50 adjacent tests (tests/agent/test_context_compressor.py) still
  pass — no regression introduced
- End-to-end dry run against debug-session-feishu-id-model with
  openai/gpt-5.4-mini via Nous Portal:
    Compression: 13081 -> 3055 tokens (76.6% ratio), 59 -> 10 messages
    Overall score: 3.25 (artifact_trail 1.50 is the weak spot,
    matching Factory's published observation)
    Specific probe misses surfaced with concrete judge notes

Noise floor (one empirical data point)
Same inputs re-run: overall 3.25 -> 3.17 (delta -0.08). Individual
dimensions varied up to ±0.5 between two single-run medians. Confirms
the DESIGN.md < 0.3 noise guidance is the right order of magnitude
for single-run comparisons. Tighter noise measurement (N=10) is
tracked as an open follow-up in DESIGN.md.

Why scripts/ and not tests/
Requires API credentials, costs ~$0.50-1.50 per run, minutes to
execute, LLM-graded (non-deterministic). Incompatible with
scripts/run_tests.sh which is hermetic, parallel, credential-free.
scripts/sample_and_compress.py is the existing precedent for offline
credentialed tooling.

Open follow-ups (tracked in DESIGN.md, not blocking this PR)
1. Iterative-merge fixture (two chained compressions on one session)
2. Precise noise-floor measurement at N=10
3. Scripted scrubber helpers to lower the cost of fixture #4+
4. Judge model selection policy (pin vs. per-user)
2026-04-25 06:17:44 -07:00

115 lines
3.7 KiB
Python

"""Wraps ContextCompressor to run a single forced compression on a fixture.
The real agent loop checks ``should_compress()`` before calling ``compress()``.
Fixtures are intentionally sized below the 100k threshold so ``compress()``
runs in a controlled, single-shot mode — score deltas attribute to the
prompt change, not to whether the threshold happened to fire at the same
boundary twice.
Resolves the provider for the compression call via the same path the real
agent uses (``hermes_cli.runtime_provider.resolve_runtime_provider``) so
behaviour matches production aside from being a single call.
"""
from __future__ import annotations
import sys
from pathlib import Path
from typing import Any, Dict, List, Optional
# Make sibling imports work whether invoked as a script or as a module.
_REPO_ROOT = Path(__file__).resolve().parents[2]
if str(_REPO_ROOT) not in sys.path:
sys.path.insert(0, str(_REPO_ROOT))
from agent.context_compressor import ( # noqa: E402
ContextCompressor,
estimate_messages_tokens_rough,
)
def run_compression(
*,
messages: List[Dict[str, Any]],
compressor_model: str,
compressor_provider: str,
compressor_base_url: str,
compressor_api_key: str,
compressor_api_mode: str,
context_length: int,
focus_topic: Optional[str] = None,
summary_model_override: Optional[str] = None,
) -> Dict[str, Any]:
"""Run a single forced compression pass over the fixture messages.
Returns a dict with:
- compressed_messages: the post-compression message list
- summary_text: the summary produced (extracted from the compressed head)
- pre_tokens, post_tokens: rough token counts before/after
- compression_ratio: 1 - (post/pre)
- pre_message_count, post_message_count
"""
compressor = ContextCompressor(
model=compressor_model,
threshold_percent=0.50,
protect_first_n=3,
protect_last_n=20,
summary_target_ratio=0.20,
quiet_mode=True,
summary_model_override=summary_model_override or "",
base_url=compressor_base_url,
api_key=compressor_api_key,
config_context_length=context_length,
provider=compressor_provider,
api_mode=compressor_api_mode,
)
pre_tokens = estimate_messages_tokens_rough(messages)
compressed = compressor.compress(
messages,
current_tokens=pre_tokens,
focus_topic=focus_topic,
)
post_tokens = estimate_messages_tokens_rough(compressed)
summary_text = _extract_summary_from_messages(compressed)
ratio = (1.0 - (post_tokens / pre_tokens)) if pre_tokens > 0 else 0.0
return {
"compressed_messages": compressed,
"summary_text": summary_text,
"pre_tokens": pre_tokens,
"post_tokens": post_tokens,
"compression_ratio": ratio,
"pre_message_count": len(messages),
"post_message_count": len(compressed),
}
_SUMMARY_MARKERS = (
"## Active Task",
"## Goal",
"## Completed Actions",
)
def _extract_summary_from_messages(messages: List[Dict[str, Any]]) -> str:
"""Find the structured summary block inside the compressed message list.
The compressor injects the summary as a user (or system-appended) message
near the head. We look for the section-header markers from
``_template_sections`` in ``agent/context_compressor.py``.
"""
for msg in messages:
content = msg.get("content")
if not isinstance(content, str):
if isinstance(content, list):
content = "\n".join(
p.get("text", "") for p in content if isinstance(p, dict)
)
else:
continue
if any(marker in content for marker in _SUMMARY_MARKERS):
return content
return ""