Skip to content

The agent that grows with you

feat(relay): emit compaction marks from the compression attempt record

mnajafian-nva64501e60c9c
diff --git a/agent/codex_runtime.py b/agent/codex_runtime.py
index 7ff003d9fcc..3edd95d5969 100644
--- a/agent/codex_runtime.py
+++ b/agent/codex_runtime.py
@@ -251,6 +251,13 @@ def _record_codex_app_server_compaction(agent, turn, *, approx_tokens: int | Non
"compression_count": getattr(compressor, "compression_count", 0) if compressor is not None else 0,
"runtime": "codex_app_server", "thread_id": thread_id, "turn_id": turn_id,
}))
+ if not force:
+ # Hermes-forced compactions are recorded by their compress_context attempt; this one Codex ran alone.
+ from agent.compaction_events import publish_provider_native
+ publish_provider_native(
+ session_id=getattr(agent, "session_id", None) or "",
+ compression_count=getattr(compressor, "compression_count", None),
+ )
return True
diff --git a/agent/compaction_events.py b/agent/compaction_events.py
new file mode 100644
index 00000000000..1257d01f18d
--- /dev/null
+++ b/agent/compaction_events.py
@@ -0,0 +1,257 @@
+"""Content-free ``hermes.compaction`` v1 records for every history rewrite, and their fan-out.
+
+One record per ``compress_context`` attempt (built from the attempt telemetry seam), per
+micro-compaction pass, per committed proactive tool-result prune, and per Codex-native thread
+compaction Hermes observes. The payload is flat because OpenTelemetry exporters flatten only top-level
+keys; every categorical field comes from a closed set with an ``other`` fallback; no field carries
+message, summary, focus-topic, error or path text. Publishing never raises into compaction.
+"""
+
+from __future__ import annotations
+
+import functools
+import logging
+import threading
+import uuid
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+SCHEMA_NAME = "hermes.compaction"
+SCHEMA_VERSION = "1"
+# Relay's reserved mark name: it resets the owning agent scope's LLM-history freshness, so it is used only
+# for a committed rewrite of what the model will see next. Everything else is an ordinary attempt mark.
+COMPACTION_MARK = "compaction"
+ATTEMPT_MARK = "compaction.attempt"
+
+_KINDS = frozenset({
+ "summarize", "micro_summarize", "prune_tool_results", "provider_native", "request_truncation", "window_reduction",
+})
+_SCOPES = frozenset({"history", "provider", "request"})
+_METHODS = frozenset({
+ "llm_summary", "aux_fallback_main", "deterministic_fallback", "deterministic_prune", "provider", "none",
+})
+_TRIGGERS = frozenset({
+ "manual", "turn_start_threshold", "pre_api", "post_tool", "idle", "engine_preflight", "overflow",
+ "gateway_hygiene", "between_turns", "proactive_prune", "provider", "recovery", "unknown",
+})
+_TRIGGER_CLASSES = {"manual": "manual", "overflow": "overflow", "provider": "provider"}
+_OUTCOMES = frozenset({"committed", "aborted", "failed", "skipped", "blocked", "noop"})
+_SPLIT_STATUSES = frozenset({
+ "not_applicable", "in_place_committed", "rotated_committed", "failed_not_indexed", "aborted", "pending", "unknown",
+})
+_TOKEN_COUNT_METHODS = frozenset({"estimate_rough", "provider_usage"})
+# Attempt classes beyond the shared-metrics closed set: guards, Codex route exits, lease races, and the
+# micro-compaction pass outcomes.
+_EXTRA_FAILURE_CLASSES = frozenset({
+ "blocked:cooldown", "blocked:structural_backoff", "blocked:ineffective", "blocked:unknown",
+ "codex_auto_native", "codex_auto_off", "codex_no_thread", "codex_compaction_failed",
+ "session_ownership_lost", "cooldown_state_unreadable", "summary_model_benched",
+ "summarize_failed", "exchange_skipped", "defrag_failed", "stale_generation", "watermark_unavailable",
+})
+# An aborted attempt the compressor ran but deliberately did not commit; other aborts are failures.
+_ABORTED_CLASSES = frozenset({"would_grow", "no_progress", "commit_fence_cancelled"})
+_MICRO_OUTCOMES = {
+ "absorbed": "committed", "defrag": "committed", "stale_generation": "skipped", "watermark_unavailable": "skipped",
+}
+
+# Every v1 key, so consumers see a stable shape; unknown values stay null.
+_FIELDS = (
+ "harness", "kind", "scope", "official", "method", "trigger", "trigger_class", "overflow_reason", "outcome",
+ "failure_class", "attempt_id", "session_id", "tokens_before", "tokens_after", "tokens_reclaimed",
+ "token_count_method", "messages_before", "messages_after", "items_dropped", "context_limit", "threshold_tokens",
+ "protected_head_tokens", "middle_window_tokens", "protected_tail_tokens", "duration_ms",
+ "summary_generation_ms", "aux_call_duration_ms", "queue_wait_ms", "commit_ms", "summarizer_provider",
+ "summarizer_model", "tool_results_pruned", "reasoning_items_pruned", "summary_input_omitted_chars",
+ "compression_count", "in_place", "session_rotated", "split_status", "cache_break", "has_focus_topic",
+)
+# Integer fields copied as-is from the attempt record (record key -> payload key).
+_ATTEMPT_INTS = {
+ "tokens_before": "tokens_before", "tokens_after": "tokens_after", "tokens_reclaimed": "tokens_reclaimed",
+ "messages_before": "messages_before", "messages_after": "messages_after", "items_dropped": "items_dropped",
+ "main_context_limit": "context_limit", "effective_threshold": "threshold_tokens",
+ "protected_head_tokens": "protected_head_tokens", "middle_window_tokens": "middle_window_tokens",
+ "protected_tail_tokens": "protected_tail_tokens", "total_duration_ms": "duration_ms",
+ "summary_generation_ms": "summary_generation_ms", "aux_call_duration_ms": "aux_call_duration_ms",
+ "queue_wait_ms": "queue_wait_ms", "commit_ms": "commit_ms", "tool_results_pruned": "tool_results_pruned",
+ "reasoning_items_pruned": "reasoning_items_pruned", "summary_input_omitted_chars": "summary_input_omitted_chars",
+}
+
+_warned_lock = threading.Lock()
+_warned = False
+
+
+def _failure_classes() -> frozenset[str]:
+ from hermes_cli.observability.shared_metrics_contract import COMPRESSION_FAILURE_CLASSES
+
+ return COMPRESSION_FAILURE_CLASSES | _EXTRA_FAILURE_CLASSES
+
+
+def _skip_classes() -> frozenset[str]:
+ from hermes_cli.observability.shared_metrics_contract import COMPRESSION_SKIP_CLASSES
+
+ return COMPRESSION_SKIP_CLASSES
+
+
+def _closed(value: Any, allowed: frozenset[str], default: str | None = "other") -> str | None:
+ if not isinstance(value, str) or not value:
+ return None
+ return value if value in allowed else default
+
+
+def _int(value: Any) -> int | None:
+ return value if isinstance(value, int) and not isinstance(value, bool) else None
+
+
+def failure_class(value: Any) -> str:
+ """Closed failure class: ``exception:<Type>`` / ``rollback:<Type>`` keep only the prefix (the type name
+ may be a plugin's); a missing class reads ``none``."""
+ if not isinstance(value, str) or not value:
+ return "none"
+ if value.startswith(("exception:", "rollback:")):
+ value = value.split(":", 1)[0]
+ return value if value in _failure_classes() else "other"
+
+
+def event_name(payload: dict[str, Any]) -> str:
+ """``compaction`` only for a committed history or provider rewrite; ``compaction.attempt`` otherwise."""
+ committed = payload.get("outcome") == "committed" and payload.get("scope") in {"history", "provider"}
+ return COMPACTION_MARK if committed else ATTEMPT_MARK
+
+
+def _payload(**values: Any) -> dict[str, Any]:
+ payload = dict.fromkeys(_FIELDS)
+ payload.update(values, harness="hermes")
+ payload["kind"] = _closed(payload["kind"], _KINDS)
+ payload["scope"] = _closed(payload["scope"], _SCOPES)
+ payload["method"] = _closed(payload["method"], _METHODS) or "none"
+ payload["trigger"] = _closed(payload["trigger"], _TRIGGERS) or "unknown"
+ payload["trigger_class"] = _TRIGGER_CLASSES.get(payload["trigger"], "auto")
+ payload["outcome"] = _closed(payload["outcome"], _OUTCOMES) or "other"
+ payload["token_count_method"] = _closed(payload["token_count_method"], _TOKEN_COUNT_METHODS)
+ payload["attempt_id"] = payload["attempt_id"] or uuid.uuid4().hex
+ payload["session_id"] = payload["session_id"] or ""
+ if payload["cache_break"] is None and payload["scope"] == "history":
+ payload["cache_break"] = payload["outcome"] == "committed"
+ return payload
+
+
+def _attempt_outcome(commit_status: Any, failure: str) -> str:
+ if commit_status != "aborted":
+ return commit_status if commit_status in _OUTCOMES else "other"
+ if failure in _skip_classes():
+ return "skipped"
+ return "aborted" if failure in _ABORTED_CLASSES else "failed"
+
+
+def _attempt_trigger(trigger_source: Any) -> str:
+ # ``auto`` is what an unlabelled automatic caller records: the reason is unknown, not "other".
+ if trigger_source == "auto" or not trigger_source:
+ return "unknown"
+ return trigger_source
+
+
+def attempt_payload(record: dict[str, Any], *, compression_count: Any = None) -> dict[str, Any]:
+ """Map one attempt telemetry record (the attempt log line's dict) onto the v1 schema."""
+ codex = record.get("route") == "codex_app_server"
+ failure = failure_class(record.get("failure_class"))
+ split_status = _closed(record.get("split_status"), _SPLIT_STATUSES)
+ outcome = _attempt_outcome(record.get("commit_status"), failure)
+ committed = outcome == "committed"
+ values: dict[str, Any] = {key: _int(record.get(src)) for src, key in _ATTEMPT_INTS.items()}
+ values.update(
+ kind="provider_native" if codex else "summarize", scope="provider" if codex else "history", official=True,
+ method=record.get("method"), trigger=_attempt_trigger(record.get("trigger_source")),
+ outcome=outcome, failure_class=failure,
+ attempt_id=record.get("attempt_id"), session_id=record.get("session_id"),
+ token_count_method=record.get("token_count_method"),
+ summarizer_provider=record.get("aux_provider") or None, summarizer_model=record.get("aux_model") or None,
+ compression_count=_int(compression_count), split_status=split_status,
+ in_place=split_status == "in_place_committed" if committed else None,
+ session_rotated=split_status == "rotated_committed" if committed else None,
+ has_focus_topic=record.get("has_focus_topic") if isinstance(record.get("has_focus_topic"), bool) else None,
+ )
+ if codex:
+ values["cache_break"] = None # the Codex thread's provider cache is not Hermes's prompt cache
+ return _payload(**values)
+
+
+def micro_payload(record: dict[str, Any]) -> dict[str, Any]:
+ """Map one micro-compaction telemetry record onto the v1 schema."""
+ outcome = _MICRO_OUTCOMES.get(record.get("outcome"), "failed")
+ before, after = _int(record.get("tokens_before")), _int(record.get("tokens_after"))
+ return _payload(
+ kind="micro_summarize", scope="history", official=False, trigger="between_turns", outcome=outcome,
+ method="llm_summary" if outcome == "committed" else "none",
+ failure_class="none" if outcome == "committed" else failure_class(record.get("outcome")),
+ session_id=record.get("session_id"), tokens_before=before, tokens_after=after,
+ tokens_reclaimed=before - after if before is not None and after is not None else None,
+ token_count_method="estimate_rough", messages_before=_int(record.get("messages_before")),
+ messages_after=_int(record.get("messages_after")), duration_ms=_int(record.get("duration_ms")),
+ threshold_tokens=_int(record.get("threshold_tokens")), context_limit=_int(record.get("context_limit")),
+ summarizer_model=record.get("aux_model") or None,
+ )
+
+
+def prune_payload(
+ *, session_id: str, tokens_before: int, tokens_after: int, messages: int, tool_results_pruned: int,
+) -> dict[str, Any]:
+ """A committed proactive tool-result prune: deterministic, no LLM, message count unchanged."""
+ return _payload(
+ kind="prune_tool_results", scope="history", official=False, trigger="proactive_prune", outcome="committed",
+ method="deterministic_prune", failure_class="none", session_id=session_id, tokens_before=tokens_before,
+ tokens_after=tokens_after, tokens_reclaimed=tokens_before - tokens_after, token_count_method="estimate_rough",
+ messages_before=messages, messages_after=messages, tool_results_pruned=tool_results_pruned,
+ )
+
+
+def provider_native_payload(*, session_id: str, compression_count: Any = None) -> dict[str, Any]:
+ """A compaction the provider ran on its own thread and Hermes only observed."""
+ return _payload(
+ kind="provider_native", scope="provider", official=False, trigger="provider", outcome="committed",
+ method="provider", failure_class="none", session_id=session_id, compression_count=_int(compression_count),
+ )
+
+
+def _publish(build: Any, *args: Any, **kwargs: Any) -> None:
+ """Build one record and fan it out to the built-in Relay integration. Never raises into compaction: the
+ first failure logs at WARNING with its traceback, later ones at DEBUG."""
+ global _warned
+ try:
+ payload = build(*args, **kwargs)
+ from agent.relay_compaction import emit_compaction_mark
+
+ emit_compaction_mark(payload["session_id"], event_name(payload), payload)
+ except Exception:
+ with _warned_lock:
+ first, _warned = not _warned, True
+ logger.log(logging.WARNING if first else logging.DEBUG, "compaction event publish failed", exc_info=True)
+
+
+def publish_attempt(agent: Any, record: dict[str, Any]) -> None:
+ """Publish one ``compress_context`` attempt record (the attempt telemetry seam calls this)."""
+ _publish(lambda: attempt_payload(
+ record, compression_count=getattr(getattr(agent, "context_compressor", None), "compression_count", None),
+ ))
+
+
+def publish_micro(record: dict[str, Any]) -> None:
+ """Publish one micro-compaction pass record."""
+ _publish(micro_payload, record)
+
+
+def publish_prune(
+ *, session_id: str, tokens_before: int, tokens_after: int, messages: int, tool_results_pruned: int,
+) -> None:
+ """Publish one committed proactive tool-result prune."""
+ _publish(
+ prune_payload, session_id=session_id, tokens_before=tokens_before, tokens_after=tokens_after,
+ messages=messages, tool_results_pruned=tool_results_pruned,
+ )
+
+
+def publish_provider_native(*, session_id: str, compression_count: Any = None) -> None:
+ """Publish one provider-native compaction Hermes observed but did not run."""
+ _publish(provider_native_payload, session_id=session_id, compression_count=compression_count)
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index 9e4564944cd..851482c2b79 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -30,6 +30,7 @@ from agent.auxiliary_client import (
call_llm,
extract_content_or_reasoning,
)
+from agent.compaction_events import publish_prune
from agent.context_engine import ContextEngine, sanitize_memory_context
from agent.context_compressor_prellm import PreLlmSkipMixin
from agent.context_compressor_summary import SummaryDispatchMixin
@@ -3483,6 +3484,10 @@ class ContextCompressor(
self._proactive_prune_rearm_tokens = next_rearm_tokens
# Reclamation just ran: let a future lockout warn again.
self._last_reclaim_block_warn = None
+ publish_prune(
+ session_id=session_id or "", tokens_before=before, tokens_after=after, messages=len(pruned_msgs),
+ tool_results_pruned=pruned_count,
+ )
return pruned_msgs, pruned_count
def _compute_summary_budget(self, turns_to_summarize: list[dict[str, Any]]) -> int:
@@ -5578,6 +5583,7 @@ Write only the summary body. Do not include any preamble or prefix."""
_raise_if_stale_attempt(self)
telemetry = self._begin_compress_attempt(current_tokens, force)
+ telemetry["has_focus_topic"] = bool(focus_topic)
n_messages = len(messages)
# Only need head + 3 tail messages minimum (token budget decides the real tail size)
_min_for_compress = self._protect_head_size(messages) + 3 + 1
diff --git a/agent/context_compressor_telemetry.py b/agent/context_compressor_telemetry.py
index 669c953e6c9..d684ef84f05 100644
--- a/agent/context_compressor_telemetry.py
+++ b/agent/context_compressor_telemetry.py
@@ -53,7 +53,7 @@ class CompressionTelemetryMixin:
# Candidate effect is captured by the compressor, then replaced with the exact committed shape.
"method": "none", "items_dropped": 0, "messages_before": None, "messages_after": None,
"tokens_before": None, "tokens_after": None, "tokens_reclaimed": None, "token_count_method": None,
- "tool_results_pruned": None, "reasoning_items_pruned": None,
+ "tool_results_pruned": None, "reasoning_items_pruned": None, "has_focus_topic": False,
}
self._active_compression_telemetry = self._last_compression_telemetry = telemetry
return telemetry
diff --git a/agent/conversation_compression_telemetry.py b/agent/conversation_compression_telemetry.py
index 9da06f428bc..bfd51ee023b 100644
--- a/agent/conversation_compression_telemetry.py
+++ b/agent/conversation_compression_telemetry.py
@@ -1,4 +1,4 @@
-"""Content-free per-attempt compression telemetry (attempt log line + shared metric).
+"""Content-free per-attempt compression telemetry (attempt log line, Relay mark, shared metric).
Sibling of ``agent/conversation_compression.py`` (the facade), which imports it at module level; this
module must never import the facade (import cycle). It logs under the facade's logger name so log
@@ -14,6 +14,8 @@ import time
import uuid
from typing import Any
+from agent.compaction_events import publish_attempt
+
logger = logging.getLogger("agent.conversation_compression")
@@ -127,6 +129,7 @@ def _emit_compression_attempt_telemetry(
logger.info(
"context compression attempt telemetry: %s", json.dumps(payload, sort_keys=True, separators=(",", ":"))
)
+ publish_attempt(agent, payload)
from hermes_cli.observability.shared_metrics_events import finish_compression_attempt
finish_compression_attempt(
@@ -169,6 +172,7 @@ def _emit_bypassed_attempt_telemetry(
logger.info(
"context compression attempt telemetry: %s", json.dumps(payload, sort_keys=True, separators=(",", ":"))
)
+ publish_attempt(agent, payload)
except Exception as exc:
logger.debug("failed to emit compression attempt telemetry: %s", exc, exc_info=True)
finally:
diff --git a/agent/micro_compaction.py b/agent/micro_compaction.py
index d0401fd61d5..02255683f0e 100644
--- a/agent/micro_compaction.py
+++ b/agent/micro_compaction.py
@@ -11,6 +11,7 @@ import logging
import time
from typing import Any, Dict, List, Optional
+from agent.compaction_events import publish_micro
from agent.message_metadata import record_absorbed_message
from agent.model_metadata import estimate_messages_tokens_rough, estimate_tokens_rough
@@ -368,6 +369,7 @@ class MicroCompactionMixin:
"occupancy_pct": occupancy, "main_model": self.model or "", "aux_model": self.summary_model or "",
}
logger.info("micro compaction telemetry: %s", json.dumps(payload, sort_keys=True, separators=(",", ":")))
+ publish_micro(payload)
except Exception as exc:
logger.debug("failed to emit micro-compaction telemetry: %s", exc)
diff --git a/agent/relay_compaction.py b/agent/relay_compaction.py
new file mode 100644
index 00000000000..a7ea44ee40e
--- /dev/null
+++ b/agent/relay_compaction.py
@@ -0,0 +1,50 @@
+"""Emit ``hermes.compaction`` records as NeMo Relay marks on the owning session's scope stack.
+
+The mark goes under the live turn of the same session when there is one, else under that session's
+scope (gateway hygiene and other out-of-turn compactions). The session's own stack matters: Relay resets
+LLM-history freshness only for the agent scope that owns a ``compaction`` mark, so the next LLM start
+after a committed rewrite records the full history again. No live Relay host or session scope means
+there is nothing to record. Relay exporters are configured by the user, so the mark adds no outbound
+path of its own.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from agent import relay_runtime
+
+logger = logging.getLogger(__name__)
+
+COMPACTION_DATA_SCHEMA = {"name": "hermes.compaction", "version": "1"}
+
+
+def _resolve_target(session_id: str) -> tuple[relay_runtime.RelayRuntime, relay_runtime.RelaySession, Any] | None:
+ """``(host, session, parent handle)`` for ``session_id``: its live turn first, then its session scope."""
+ turn = relay_runtime.active_turn(session_id)
+ host = turn.lease.live_runtime() if turn is not None else None
+ if host is not None:
+ session = turn.lease.session
+ return host, session, turn.handle or session.handle
+ host = relay_runtime.HOST_REGISTRY.for_profile(create=False)
+ if not isinstance(host, relay_runtime.RelayRuntime):
+ return None
+ session = host.get_session(session_id)
+ if session is None or session.handle is None:
+ return None
+ return host, session, session.handle
+
+
+def emit_compaction_mark(session_id: str, name: str, data: dict[str, Any]) -> bool:
+ """Emit one mark; returns False when no Relay session owns ``session_id``."""
+ target = _resolve_target(session_id) if session_id else None
+ if target is None:
+ logger.debug("no live Relay session for %s; %s mark not recorded", session_id or "none", name)
+ return False
+ host, session, handle = target
+ host.run_in_session(
+ session, host.relay.scope.event, name, handle=handle, data=data, data_schema=dict(COMPACTION_DATA_SCHEMA),
+ metadata=relay_runtime.runtime_metadata(host.runtime_id),
+ )
+ return True
diff --git a/tests/agent/test_compaction_events.py b/tests/agent/test_compaction_events.py
new file mode 100644
index 00000000000..ab67a16d852
--- /dev/null
+++ b/tests/agent/test_compaction_events.py
@@ -0,0 +1,339 @@
+"""``hermes.compaction`` v1 records: one content-free record per history rewrite, on every path.
+
+The record is the contract a Relay consumer reads, so these tests pin the field set, the closed enums,
+the ``compaction`` vs ``compaction.attempt`` name rule, and that publishing can never change what a
+compaction returns.
+"""
+
+import json
+import logging
+import os
+import tempfile
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import pytest
+
+from agent import compaction_events
+from agent.context_compressor import ContextCompressor
+from agent.conversation_compression import compress_context
+from agent.transports.codex_app_server_session import TurnResult
+
+SECRET = "TOPSECRET_TRANSCRIPT_TEXT"
+V1_FIELDS = {
+ "harness", "kind", "scope", "official", "method", "trigger", "trigger_class", "overflow_reason", "outcome",
+ "failure_class", "attempt_id", "session_id", "tokens_before", "tokens_after", "tokens_reclaimed",
+ "token_count_method", "messages_before", "messages_after", "items_dropped", "context_limit", "threshold_tokens",
+ "protected_head_tokens", "middle_window_tokens", "protected_tail_tokens", "duration_ms",
+ "summary_generation_ms", "aux_call_duration_ms", "queue_wait_ms", "commit_ms", "summarizer_provider",
+ "summarizer_model", "tool_results_pruned", "reasoning_items_pruned", "summary_input_omitted_chars",
+ "compression_count", "in_place", "session_rotated", "split_status", "cache_break", "has_focus_topic",
+}
+
+
+def published(monkeypatch):
+ """Every (session_id, mark name, payload) handed to the Relay emitter."""
+ marks = []
+ monkeypatch.setattr(
+ "agent.relay_compaction.emit_compaction_mark",
+ lambda session_id, name, data: marks.append((session_id, name, data)) or True,
+ )
+ return marks
+
+
+class _TodoStore:
+ def format_for_injection(self):
+ return ""
+
+
+class _Agent:
+ def __init__(self, compressor):
+ self.context_compressor = compressor
+ self.session_id = "session-events-test"
+ self.platform = "cli"
+ self.model = "test/main-model"
+ self.provider = "test-provider"
+ self.tools = []
+ self._compression_feasibility_checked = True
+ self.compression_in_place = False
+ self._memory_manager = None
+ self._session_db = None
+ self._todo_store = _TodoStore()
+ self._cached_system_prompt = None
+
+ def _emit_status(self, _message):
+ pass
+
+ def _emit_warning(self, _message):
+ pass
+
+ def _invalidate_system_prompt(self):
+ self._cached_system_prompt = None
+
+ def _build_system_prompt(self, system_message):
+ return system_message
+
+ def commit_memory_session(self, _messages):
+ pass
+
+
+def _compressor(**kwargs):
+ with patch("agent.context_compressor.get_model_context_length", return_value=100_000):
+ compressor = ContextCompressor(
+ model="test/main-model", provider="test-provider", threshold_percent=0.50, quiet_mode=True,
+ config_context_length=100_000, **kwargs,
+ )
+ compressor.tail_token_budget = 10
+ return compressor
+
+
+def _messages():
+ filler = " ".join(["context"] * 200)
+ msgs = [{"role": "system", "content": "system prompt"}]
+ for idx in range(10):
+ msgs.append({"role": "user", "content": f"user message {idx} {SECRET} {filler}"})
+ msgs.append({"role": "assistant", "content": f"assistant reply {idx} {SECRET} {filler}"})
+ return msgs
+
+
+def test_committed_summary_publishes_one_compaction_mark_with_the_v1_shape(published):
+ agent = _Agent(_compressor())
+
+ with patch.object(agent.context_compressor, "_generate_summary", return_value="SANITIZED SUMMARY"):
+ compress_context(
+ agent, _messages(), "system prompt", approx_tokens=80_000, trigger="pre_api",
+ focus_topic=f"focus on {SECRET}",
+ )
+
+ [(session_id, name, payload)] = published
+ assert (session_id, name) == ("session-events-test", "compaction")
+ assert set(payload) == V1_FIELDS
+ assert payload["harness"] == "hermes"
+ assert (payload["kind"], payload["scope"], payload["official"]) == ("summarize", "history", True)
+ assert (payload["method"], payload["outcome"], payload["failure_class"]) == ("llm_summary", "committed", "none")
+ assert (payload["trigger"], payload["trigger_class"]) == ("pre_api", "auto")
+ assert payload["tokens_reclaimed"] == payload["tokens_before"] - payload["tokens_after"] > 0
+ assert payload["token_count_method"] == "estimate_rough"
+ assert payload["compression_count"] == 1 and payload["cache_break"] is True
+ assert payload["has_focus_topic"] is True
+ raw = json.dumps(payload)
+ assert SECRET not in raw and "SANITIZED SUMMARY" not in raw and "focus on" not in raw
+
+
+def test_deterministic_fallback_is_a_committed_compaction_with_its_method(published):
+ agent = _Agent(_compressor())
+
+ with patch.object(agent.context_compressor, "_generate_summary", return_value=None):
+ compress_context(agent, _messages(), "system prompt", approx_tokens=80_000)
+
+ [(_sid, name, payload)] = published
+ assert name == "compaction"
+ assert (payload["method"], payload["failure_class"]) == ("deterministic_fallback", "summary_generation_failed")
+ assert payload["items_dropped"] > 0
+ assert payload["trigger"] == "unknown" # an unlabelled automatic caller
+
+
+def test_aborted_summary_failure_is_an_attempt_mark_not_a_compaction(published):
+ agent = _Agent(_compressor())
+ agent.context_compressor.abort_on_summary_failure = True
+
+ with patch.object(agent.context_compressor, "_generate_summary", return_value=None):
+ returned, _ = compress_context(agent, _messages(), "system prompt", approx_tokens=80_000, trigger="post_tool")
+
+ [(_sid, name, payload)] = published
+ assert name == "compaction.attempt"
+ assert (payload["outcome"], payload["failure_class"]) == ("failed", "summary_generation_aborted")
+ assert payload["cache_break"] is False and payload["in_place"] is None
+
+
+def test_a_raising_emitter_never_changes_the_compaction_result(monkeypatch, caplog):
+ def explode(*_args, **_kwargs):
+ raise RuntimeError("relay down")
+
+ monkeypatch.setattr("agent.relay_compaction.emit_compaction_mark", explode)
+ monkeypatch.setattr(compaction_events, "_warned", False)
+ results = []
+ for _ in range(2):
+ agent = _Agent(_compressor())
+ with patch.object(agent.context_compressor, "_generate_summary", return_value="SANITIZED SUMMARY"):
+ with caplog.at_level(logging.DEBUG, logger="agent.compaction_events"):
+ results.append(compress_context(agent, _messages(), "system prompt", approx_tokens=80_000))
+
+ assert all(len(compressed) < len(_messages()) for compressed, _ in results)
+ failures = [r for r in caplog.records if r.getMessage() == "compaction event publish failed"]
+ assert [r.levelno for r in failures] == [logging.WARNING, logging.DEBUG]
+ assert failures[0].exc_info is not None
+
+
+def test_gate_blocked_attempt_publishes_exactly_one_blocked_attempt_mark(published):
+ compressor = _compressor()
+ agent = _Agent(compressor)
+
+ with patch.object(type(compressor), "_compression_block_reason", return_value="cooldown:42"), \
+ patch.object(type(compressor), "_automatic_compression_blocked", return_value=True):
+ compress_context(agent, _messages(), "system prompt", approx_tokens=80_000, trigger="idle")
+
+ [(_sid, name, payload)] = published
+ assert name == "compaction.attempt"
+ assert (payload["outcome"], payload["failure_class"], payload["trigger"]) == ("blocked", "blocked:cooldown", "idle")
+
+
+def _codex_agent(result, auto_mode):
+ agent = SimpleNamespace(
+ api_mode="codex_app_server", codex_app_server_auto_compaction=auto_mode, session_id="codex-session",
+ platform="cli", model="gpt-test", provider="openai-codex", _cached_system_prompt="cached prompt",
+ _codex_session=SimpleNamespace(compact_thread=lambda: result, close=lambda: None),
+ _compression_activity_heartbeat_interval=0.1,
+ context_compressor=SimpleNamespace(
+ compression_count=0, last_compression_rough_tokens=0, last_prompt_tokens=1, last_completion_tokens=0,
+ awaiting_real_usage_after_compression=False,
+ ),
+ )
+ agent._touch_activity = lambda *_args, **_kwargs: None
+ agent._emit_status = agent._emit_warning = lambda _message: None
+ return agent
+
+
+ ("auto_mode", "force", "result", "name", "outcome"),
+ [
+ ("native", False, TurnResult(thread_id="t1"), "compaction.attempt", "skipped"),
+ ("hermes", True, TurnResult(thread_id="t1", turn_id="c1"), "compaction", "committed"),
+ ("hermes", True, TurnResult(thread_id="t1", error="boom"), "compaction.attempt", "failed"),
+ ],
+)
+def test_codex_route_publishes_one_provider_record_per_exit(published, auto_mode, force, result, name, outcome):
+ compress_context(_codex_agent(result, auto_mode), [{"role": "user", "content": SECRET}], "system", force=force)
+
+ [(session_id, mark, payload)] = published
+ assert (session_id, mark, payload["outcome"]) == ("codex-session", name, outcome)
+ assert (payload["kind"], payload["scope"], payload["official"]) == ("provider_native", "provider", True)
+ assert "boom" not in json.dumps(payload)
+
+
+def test_codex_native_compaction_observed_by_hermes_is_an_unofficial_provider_compaction(published):
+ from agent.codex_runtime import _record_codex_app_server_compaction
+
+ agent = _codex_agent(None, "native")
+ agent.event_callback = None
+ _record_codex_app_server_compaction(agent, TurnResult(thread_id="t1", turn_id="n1", compacted=True))
+
+ [(_sid, name, payload)] = published
+ assert name == "compaction"
+ assert (payload["kind"], payload["official"], payload["trigger"]) == ("provider_native", False, "provider")
+ assert payload["trigger_class"] == "provider" and payload["compression_count"] == 1
+
+
+ ("outcome", "name", "expected"),
+ [
+ ("absorbed", "compaction", ("committed", "llm_summary", "none")),
+ ("defrag", "compaction", ("committed", "llm_summary", "none")),
+ ("stale_generation", "compaction.attempt", ("skipped", "none", "stale_generation")),
+ ("summarize_failed", "compaction.attempt", ("failed", "none", "summarize_failed")),
+ ],
+)
+def test_micro_compaction_pass_publishes_one_record(published, outcome, name, expected):
+ compressor = _compressor()
+ compressor._session_id = "micro-session"
+ compressor._emit_micro_compaction_telemetry(
+ outcome=outcome, messages_before=12, messages_after=10, tokens_before=900, tokens_after=600, duration_ms=5,
+ )
+
+ [(session_id, mark, payload)] = published
+ assert (session_id, mark) == ("micro-session", name)
+ assert (payload["outcome"], payload["method"], payload["failure_class"]) == expected
+ assert (payload["kind"], payload["official"], payload["trigger"]) == ("micro_summarize", False, "between_turns")
+ assert payload["tokens_reclaimed"] == 300
+
+
+def test_committed_proactive_prune_publishes_one_record(published):
+ compressor = _compressor(
+ proactive_prune_tokens=48_000, proactive_prune_min_result_chars=8_000, protect_first_n=2, protect_last_n=4,
+ )
+ compressor._session_id = "prune-session"
+ msgs = [{"role": "system", "content": "sys"}]
+ for i in range(8):
+ msgs.append({"role": "assistant", "content": "", "tool_calls": [
+ {"id": f"c{i}", "type": "function", "function": {"name": "terminal", "arguments": "{}"}}
+ ]})
+ msgs.append({"role": "tool", "tool_call_id": f"c{i}", "content": (chr(65 + i) + SECRET) * 600 if i < 3 else "ok"})
+
+ _result, pruned = compressor.prune_tool_results_only(msgs, current_tokens=120_000)
+
+ [(session_id, name, payload)] = published
+ assert (session_id, name) == ("prune-session", "compaction")
+ assert (payload["kind"], payload["method"], payload["trigger"]) == (
+ "prune_tool_results", "deterministic_prune", "proactive_prune",
+ )
+ assert payload["tool_results_pruned"] == pruned and payload["tokens_reclaimed"] > 0
+ assert payload["messages_before"] == payload["messages_after"] == len(msgs)
+ assert SECRET not in json.dumps(payload)
+
+
+def test_rotation_publishes_after_the_split_with_the_attempts_own_session(published):
+ """A rotating commit re-points the agent at a child session and its memory flush resets the compressor's
+ telemetry; the record is still built from this attempt's telemetry and names the session it started in."""
+ from hermes_state import SessionDB
+ from run_agent import AIAgent
+
+ with tempfile.TemporaryDirectory() as tmpdir, patch.dict(os.environ, {"OPENROUTER_API_KEY": "test-key"}):
+ agent = AIAgent(
+ api_key="test-key", base_url="https://openrouter.ai/api/v1", model="test/model", quiet_mode=True,
+ session_db=SessionDB(db_path=Path(tmpdir) / "state.db"), session_id="rotating-session",
+ skip_context_files=True, skip_memory=True,
+ )
+ agent.compression_in_place = False
+ agent.context_compressor.tail_token_budget = 10
+ with patch.object(agent.context_compressor, "_generate_summary", return_value="SANITIZED SUMMARY"):
+ agent._compress_context(_messages(), "sys", approx_tokens=80_000, trigger="pre_api")
+ agent.close()
+
+ assert agent.session_id != "rotating-session"
+ [(session_id, name, payload)] = published
+ assert (session_id, name) == ("rotating-session", "compaction")
+ assert (payload["split_status"], payload["session_rotated"], payload["in_place"]) == (
+ "rotated_committed", True, False,
+ )
+ assert payload["tokens_after"] is not None and payload["method"] == "llm_summary"
+
+
+ ("record", "expected"),
+ [
+ ({"commit_status": "aborted", "failure_class": "lock_contended"}, ("skipped", "lock_contended")),
+ ({"commit_status": "aborted", "failure_class": "would_grow"}, ("aborted", "would_grow")),
+ ({"commit_status": "aborted", "failure_class": "exception:AcmeSecretError"}, ("failed", "exception")),
+ ({"commit_status": "aborted", "failure_class": "acme_engine_reason"}, ("failed", "other")),
+ ({"commit_status": "mystery", "failure_class": None}, ("other", "none")),
+ ],
+)
+def test_outcome_and_failure_class_stay_in_their_closed_sets(record, expected):
+ payload = compaction_events.attempt_payload(record)
+ assert (payload["outcome"], payload["failure_class"]) == expected
+ assert "Acme" not in json.dumps(payload)
+
+
+ ("trigger_source", "trigger", "trigger_class"),
+ [
+ ("manual", "manual", "manual"), ("overflow", "overflow", "overflow"), ("gateway_hygiene", "gateway_hygiene", "auto"),
+ ("auto", "unknown", "auto"), ("plugin_said_so", "other", "auto"),
+ ],
+)
+def test_trigger_maps_onto_the_closed_set(trigger_source, trigger, trigger_class):
+ payload = compaction_events.attempt_payload({"trigger_source": trigger_source, "method": "made_up"})
+ assert (payload["trigger"], payload["trigger_class"], payload["method"]) == (trigger, trigger_class, "other")
+
+
+ ("outcome", "scope", "name"),
+ [
+ ("committed", "history", "compaction"), ("committed", "provider", "compaction"),
+ ("committed", "request", "compaction.attempt"), ("skipped", "history", "compaction.attempt"),
+ ],
+)
+def test_only_a_committed_history_or_provider_rewrite_is_named_compaction(outcome, scope, name):
+ assert compaction_events.event_name({"outcome": outcome, "scope": scope}) == name
diff --git a/tests/agent/test_relay_compaction.py b/tests/agent/test_relay_compaction.py
new file mode 100644
index 00000000000..b73097f6b43
--- /dev/null
+++ b/tests/agent/test_relay_compaction.py
@@ -0,0 +1,134 @@
+"""Compaction marks land on the owning session's Relay scope stack.
+
+A mark goes under the session's live turn when there is one, else under the session scope (gateway
+hygiene runs outside any turn). Relay resets LLM-history freshness only for the agent scope that owns a
+``compaction`` mark, so a mark on the wrong stack would leave the next LLM start projected.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from agent import compaction_events, relay_runtime
+from agent.relay_compaction import COMPACTION_DATA_SCHEMA, emit_compaction_mark
+from agent.relay_runtime import RelayRuntime, RelaySessionCoordinator
+
+
+class _Handle:
+ def __init__(self, name: str) -> None:
+ self.name = name
+
+
+class _Scope:
+ def __init__(self) -> None:
+ self.events: list[dict[str, Any]] = []
+
+ def push(self, name: str, _scope_type: Any, **_kwargs: Any) -> _Handle:
+ return _Handle(name)
+
+ def pop(self, _handle: _Handle, **_kwargs: Any) -> None:
+ return None
+
+ def event(self, name: str, **kwargs: Any) -> None:
+ self.events.append({"name": name, **kwargs})
+
+
+class _Plugin:
+ def report(self) -> None:
+ return None
+
+
+class _Relay:
+ class ScopeType:
+ Function = "function"
+ Agent = "agent"
+
+ def __init__(self) -> None:
+ self.scope = _Scope()
+ self.plugin = _Plugin()
+
+ def get_scope_stack(self) -> None:
+ return None
+
+
+class _Registry:
+ def __init__(self, host: Any) -> None:
+ self.host = host
+
+ def for_profile(self, _profile_key: str | None = None, *, create: bool = True) -> Any:
+ return self.host
+
+
+def relay(monkeypatch):
+ """A Relay host for the active profile, reachable through the host registry."""
+ fake = _Relay()
+ runtime = RelayRuntime(relay=fake, profile_key=relay_runtime.current_profile_key())
+ monkeypatch.setattr(relay_runtime, "HOST_REGISTRY", _Registry(runtime))
+ coordinator = RelaySessionCoordinator(registry=_Registry(runtime))
+ coordinator._prepare_session = lambda _host, _context: None
+ yield fake, runtime, coordinator
+ runtime.shutdown()
+
+
+def _committed(session_id: str) -> dict[str, Any]:
+ return compaction_events.attempt_payload(
+ {"session_id": session_id, "commit_status": "committed", "route": "hermes", "trigger_source": "pre_api"}
+ )
+
+
+def test_mark_inside_a_turn_is_parented_to_that_turn(relay):
+ fake, runtime, coordinator = relay
+ lease = coordinator.acquire_conversation(profile_key=runtime.profile_key, session_id="s1", platform="cli")
+ turn = coordinator.begin_turn(lease, turn_id="t1", task_id="task")
+ try:
+ payload = _committed("s1")
+ assert emit_compaction_mark("s1", compaction_events.event_name(payload), payload) is True
+ finally:
+ coordinator.end_turn(turn, outcome="success")
+
+ [event] = fake.scope.events
+ assert event["name"] == "compaction"
+ assert event["handle"] is turn.handle
+ assert event["data"] == payload
+ assert event["data_schema"] == COMPACTION_DATA_SCHEMA
+ assert event["metadata"][relay_runtime.RUNTIME_INSTANCE_KEY] == runtime.runtime_id
+
+
+def test_mark_outside_a_turn_uses_the_session_scope(relay):
+ fake, runtime, coordinator = relay
+ lease = coordinator.acquire_conversation(profile_key=runtime.profile_key, session_id="hygiene", platform="telegram")
+ payload = compaction_events.attempt_payload({"session_id": "hygiene", "commit_status": "blocked"})
+
+ assert emit_compaction_mark("hygiene", compaction_events.event_name(payload), payload) is True
+
+ [event] = fake.scope.events
+ assert (event["name"], event["handle"]) == ("compaction.attempt", lease.session.handle)
+
+
+def test_mark_for_another_session_does_not_land_on_the_current_turn(relay):
+ fake, runtime, coordinator = relay
+ other = coordinator.acquire_conversation(profile_key=runtime.profile_key, session_id="other", platform="cli")
+ lease = coordinator.acquire_conversation(profile_key=runtime.profile_key, session_id="s1", platform="cli")
+ turn = coordinator.begin_turn(lease, turn_id="t1", task_id="task")
+ try:
+ emit_compaction_mark("other", "compaction", _committed("other"))
+ finally:
+ coordinator.end_turn(turn, outcome="success")
+
+ [event] = fake.scope.events
+ assert event["handle"] is other.session.handle
+
+
+def test_no_relay_session_skips_quietly(relay):
+ fake, _runtime, _coordinator = relay
+ assert emit_compaction_mark("never-opened", "compaction", _committed("never-opened")) is False
+ assert emit_compaction_mark("", "compaction", _committed("")) is False
+ assert fake.scope.events == []
+
+
+def test_no_relay_host_skips_quietly(monkeypatch):
+ monkeypatch.setattr(relay_runtime, "HOST_REGISTRY", _Registry(None))
+ assert emit_compaction_mark("s1", "compaction", _committed("s1")) is False
diff --git a/tests/agent/test_relay_compaction_atof.py b/tests/agent/test_relay_compaction_atof.py
new file mode 100644
index 00000000000..b753e3c801f
--- /dev/null
+++ b/tests/agent/test_relay_compaction_atof.py
@@ -0,0 +1,203 @@
+"""Compaction marks through the real NeMo Relay ATOF plugin, and the freshness reset they drive.
+
+Relay records an LLM start projected to the current user turn while its agent scope is not fresh. A
+``compaction`` mark on the session's own stack makes the agent fresh again, so the next LLM start
+records the full compacted history. An aborted attempt is only a ``compaction.attempt`` mark and must
+not reset anything.
+"""
+
+from __future__ import annotations
+
+import json
+from unittest.mock import patch
+
+import pytest
+
+SESSION_ID = "compaction-atof-session"
+SECRET = "TOPSECRET_TRANSCRIPT_TEXT"
+LLM_NAME = "openai.chat_completions"
+ABORT = object() # summary sentinel: fail the summary with abort_on_summary_failure set
+
+
+class _TodoStore:
+ def format_for_injection(self):
+ return ""
+
+
+class _Agent:
+ def __init__(self, compressor):
+ self.context_compressor = compressor
+ self.session_id = SESSION_ID
+ self.platform = "cli"
+ self.model = "test/main-model"
+ self.provider = "test-provider"
+ self.tools = []
+ self._compression_feasibility_checked = True
+ self.compression_in_place = True
+ self._memory_manager = None
+ self._session_db = None
+ self._todo_store = _TodoStore()
+ self._cached_system_prompt = None
+
+ def _emit_status(self, _message):
+ pass
+
+ def _emit_warning(self, _message):
+ pass
+
+ def _invalidate_system_prompt(self):
+ self._cached_system_prompt = None
+
+ def _build_system_prompt(self, system_message):
+ return system_message
+
+ def commit_memory_session(self, _messages):
+ pass
+
+
+def _transcript():
+ filler = " ".join(["context"] * 200)
+ msgs = [{"role": "system", "content": "system prompt"}]
+ for idx in range(10):
+ msgs.append({"role": "user", "content": f"user message {idx} {SECRET} {filler}"})
+ msgs.append({"role": "assistant", "content": f"assistant reply {idx} {SECRET} {filler}"})
+ return msgs
+
+
+def _chat_response(_request):
+ return {
+ "id": "r", "object": "chat.completion", "created": 0, "model": "test/main-model",
+ "choices": [{"index": 0, "finish_reason": "stop", "message": {"role": "assistant", "content": "ok"}}],
+ }
+
+
+def _llm(messages, request_id):
+ from agent import relay_llm
+
+ relay_llm.execute(
+ {"model": "test/main-model", "messages": messages}, _chat_response, name=LLM_NAME,
+ model_name="test/main-model", session_id=SESSION_ID,
+ metadata={"api_mode": "chat_completions", "api_request_id": request_id},
+ )
+
+
+def _write_plugins_toml(tmp_path, atof_dir):
+ config = tmp_path / "plugins.toml"
+ config.write_text(
+ f"""version = 1
+
+[[components]]
+kind = "observability"
+enabled = true
+
+[components.config]
+version = 4
+
+[components.config.atof]
+enabled = true
+
+[[components.config.atof.sinks]]
+type = "file"
+output_directory = {json.dumps(str(atof_dir))}
+filename = "events.jsonl"
+mode = "overwrite"
+""",
+ encoding="utf-8",
+ )
+ return config
+
+
+def _run_turn_with_compaction(tmp_path, monkeypatch, summary):
+ """One Relay turn: two LLM calls, one compression attempt, one more LLM call. Returns ATOF events
+ and the message count of the last request."""
+ relay = pytest.importorskip("nemo_relay")
+ if getattr(relay, "_native", None) is None:
+ pytest.skip("NeMo Relay native binding is unavailable on this platform")
+
+ from agent import relay_runtime
+ from agent.context_compressor import ContextCompressor
+ from agent.conversation_compression import compress_context
+
+ hermes_home, atof_dir = tmp_path / "hermes-home", tmp_path / "atof"
+ hermes_home.mkdir()
+ atof_dir.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+ monkeypatch.setenv(relay_runtime.RELAY_PLUGINS_CONFIG_ENV, str(_write_plugins_toml(tmp_path, atof_dir)))
+ relay_runtime._reset_for_tests()
+
+ with patch("agent.context_compressor.get_model_context_length", return_value=100_000):
+ compressor = ContextCompressor(
+ model="test/main-model", provider="test-provider", threshold_percent=0.50, quiet_mode=True,
+ config_context_length=100_000, abort_on_summary_failure=summary is ABORT,
+ )
+ compressor.tail_token_budget = 10
+ agent = _Agent(compressor)
+ transcript = _transcript()
+ coordinator = relay_runtime.SESSION_COORDINATOR
+ profile_key = relay_runtime.current_profile_key()
+ try:
+ lease = coordinator.acquire_conversation(profile_key=profile_key, session_id=SESSION_ID, platform="cli")
+ turn = coordinator.begin_turn(lease, turn_id="turn-1", task_id="task-1")
+ try:
+ _llm(transcript[:-2], "r1")
+ _llm(transcript, "r2")
+ with patch.object(compressor, "_generate_summary", return_value=None if summary is ABORT else summary):
+ compressed, _ = compress_context(agent, transcript, "system prompt", approx_tokens=80_000)
+ last_request = compressed + [{"role": "user", "content": "next question"}]
+ _llm(last_request, "r3")
+ finally:
+ coordinator.end_turn(turn, outcome="success")
+ coordinator.finalize_conversation(profile_key=profile_key, session_id=SESSION_ID)
+ finally:
+ relay_runtime._reset_for_tests()
+
+ events = [
+ json.loads(line)
+ for line in (atof_dir / "events.jsonl").read_text(encoding="utf-8").splitlines()
+ if line.strip()
+ ]
+ return events, len(last_request)
+
+
+
+def _llm_start_message_counts(events):
+ counts = []
+ for event in events:
+ if event.get("name") == LLM_NAME and event.get("scope_category") == "start":
+ data = event.get("data") or {}
+ counts.append(len((data.get("content") or data).get("messages") or []))
+ return counts
+
+
+def _compaction_marks(events):
+ return [e for e in events if e.get("kind") == "mark" and str(e.get("name", "")).startswith("compaction")]
+
+
+ ("summary", "method"), [("SANITIZED SUMMARY", "llm_summary"), (None, "deterministic_fallback")],
+)
+def test_committed_compaction_mark_resets_freshness_for_the_next_llm_start(tmp_path, monkeypatch, summary, method):
+ events, last_request_len = _run_turn_with_compaction(tmp_path, monkeypatch, summary)
+
+ [mark] = _compaction_marks(events)
+ assert mark["name"] == "compaction"
+ assert mark["data_schema"] == {"name": "hermes.compaction", "version": "1"}
+ assert (mark["data"]["kind"], mark["data"]["outcome"], mark["data"]["method"]) == ("summarize", "committed", method)
+ [turn_start] = [e for e in events if e.get("name") == "hermes.turn" and e.get("scope_category") == "start"]
+ assert mark["parent_uuid"] == turn_start["uuid"]
+ raw = json.dumps(mark)
+ assert SECRET not in raw and "SANITIZED SUMMARY" not in raw
+
+ first, second, after = _llm_start_message_counts(events)
+ assert second < len(_transcript()) # not fresh: projected to the current user turn
+ assert after == last_request_len # fresh again after the compaction mark: full history
+
+
+def test_aborted_attempt_is_an_attempt_mark_and_leaves_freshness_alone(tmp_path, monkeypatch):
+ events, last_request_len = _run_turn_with_compaction(tmp_path, monkeypatch, ABORT)
+
+ [mark] = _compaction_marks(events)
+ assert mark["name"] == "compaction.attempt"
+ assert (mark["data"]["outcome"], mark["data"]["failure_class"]) == ("failed", "summary_generation_aborted")
+ *_, after = _llm_start_message_counts(events)
+ assert after < last_request_len
diff --git a/website/docs/developer-guide/context-compression-and-caching.md b/website/docs/developer-guide/context-compression-and-caching.md
index 1b6b7c16625..47fe92c8af6 100644
--- a/website/docs/developer-guide/context-compression-and-caching.md
+++ b/website/docs/developer-guide/context-compression-and-caching.md
@@ -267,7 +267,10 @@ text, the focus topic or error messages.
The opt-in `hermes.compression.count` shared metric keeps coarse triggers
(`auto`, `manual`, `overflow`) and counts only attempts the local compressor
-ran; blocked and Codex-routed attempts appear in the log line only.
+ran; blocked and Codex-routed attempts appear in the log line only. When the
+NeMo Relay runtime is live, the same record, plus micro-compaction passes and
+committed proactive prunes, is also emitted as a `hermes.compaction` mark (see
+[NeMo Relay Shared Metrics](./relay-shared-metrics.md#compaction-marks)).
## Configuration
diff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.md
index 0344c7c66f0..831ed588a76 100644
--- a/website/docs/developer-guide/relay-shared-metrics.md
+++ b/website/docs/developer-guide/relay-shared-metrics.md
@@ -132,6 +132,37 @@ or mount layouts. Relay does not filter events by working directory; if a path
must not leave the host, use a trusted local collector or do not enable a remote
exporter for that process.
+## Compaction Marks
+
+Every history rewrite emits one Relay mark with
+`data_schema: {"name": "hermes.compaction", "version": "1"}`: each
+`compress_context` attempt (including blocked, Codex-routed and aborted ones),
+each micro-compaction pass, each committed proactive tool-result prune, and
+each Codex-native thread compaction Hermes observes. The mark is emitted
+whenever the Relay runtime is live; it needs no setting because Relay
+exporters are configured separately.
+
+| Mark | When | Relay effect |
+|---|---|---|
+| `compaction` | `outcome: committed` with `scope: history` or `provider` | Resets LLM-history freshness for the session's agent scope, so the next LLM start records the full compacted history |
+| `compaction.attempt` | Any other outcome (`aborted`, `failed`, `skipped`, `blocked`) | None |
+
+The mark is parented to the live `hermes.turn` of the same session, or to the
+`hermes.session` scope when compaction runs outside a turn (gateway hygiene).
+`data` is flat so OpenTelemetry flattens every field into
+`nemo_relay.mark.data.<key>`. Categorical fields come from closed sets with an
+`other` fallback: `kind` (`summarize`, `micro_summarize`,
+`prune_tool_results`, `provider_native`), `scope`, `official` (true only for
+`compress_context`), `method`, `trigger` / `trigger_class`, `outcome` and
+`failure_class`. Numeric fields carry the effect (`tokens_before`,
+`tokens_after`, `tokens_reclaimed`, `messages_before`, `messages_after`,
+`items_dropped`) and timings (`duration_ms`, `summary_generation_ms`,
+`aux_call_duration_ms`, `queue_wait_ms`, `commit_ms`). Token counts are rough
+message-only estimates (`token_count_method: estimate_rough`). The payload never
+contains message text, summary text, the focus topic (only
+`has_focus_topic`), error text or file paths. `attempt_id` and `session_id`
+are for correlation; do not use them as metric labels.
+
## Process-Wide Plugin Policy and Profile Isolation
Relay plugin configuration is a process-level deployment choice, not a Hermes