The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(memory): renumber checkpoint API — v1 is the implicit historical contract, v2 opts into fail-closed checkpoints
Teknium9e551d293133
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.pyindex 660e375d754..012600bca82 100644--- a/agent/conversation_compression.py+++ b/agent/conversation_compression.py@@ -3014,7 +3014,10 @@ def compress_context(# instead of silently discarding the provider's return value.memory_context = ""memory_manager = getattr(agent, "_memory_manager", None)- direct_messages = _direct_messages_for_pre_compress_memory(messages)+ # Raw messages remain the historical (API v1) provider contract; the+ # normalized evidence list is handed only to API v2+ checkpoint+ # providers inside MemoryManager.on_pre_compress().+ evidence_messages = _direct_messages_for_pre_compress_memory(messages)if checkpoint_required:supports_checkpoint = getattr(memory_manager, "supports_pre_compress_checkpoint", None@@ -3037,7 +3040,8 @@ def compress_context()try:_maybe_ctx = memory_manager.on_pre_compress(- direct_messages,+ messages,+ evidence_messages=evidence_messages,require_checkpoint=True,checkpoint_api_version=PRE_COMPRESS_CHECKPOINT_API_VERSION,)@@ -3053,7 +3057,9 @@ def compress_context(memory_context = sanitize_memory_context(_maybe_ctx)elif memory_manager:try:- _maybe_ctx = memory_manager.on_pre_compress(direct_messages)+ _maybe_ctx = memory_manager.on_pre_compress(+ messages, evidence_messages=evidence_messages+ )if isinstance(_maybe_ctx, str):memory_context = sanitize_memory_context(_maybe_ctx)except Exception:diff --git a/agent/memory_manager.py b/agent/memory_manager.pyindex d373660ce48..818320ca723 100644--- a/agent/memory_manager.py+++ b/agent/memory_manager.py@@ -37,6 +37,10 @@ from agent.memory_provider import MemoryProvider, PRE_COMPRESS_CHECKPOINT_API_VEfrom agent.skill_commands import extract_user_instruction_from_skill_messagefrom tools.registry import tool_error+# Providers that predate the checkpoint-API attribute are implicitly on the+# historical best-effort contract (API v1).+_LEGACY_PRE_COMPRESS_API_VERSION = 1+logger = logging.getLogger(__name__)# How long shutdown_all() waits for in-flight background sync/prefetch work@@ -1064,7 +1068,11 @@ class MemoryManager:for provider in self._providers:try:provider_version = int(- getattr(provider, "pre_compress_checkpoint_api_version", 0)+ getattr(+ provider,+ "pre_compress_checkpoint_api_version",+ _LEGACY_PRE_COMPRESS_API_VERSION,+ ))except (TypeError, ValueError):continue@@ -1076,29 +1084,45 @@ class MemoryManager:self,messages: List[Dict[str, Any]],*,+ evidence_messages: Optional[List[Dict[str, Any]]] = None,require_checkpoint: bool = False,checkpoint_api_version: int = PRE_COMPRESS_CHECKPOINT_API_VERSION,) -> str:"""Notify all providers before context compression.Returns combined text from providers to include in the compression- summary prompt. Empty string if no provider contributes. When- ``require_checkpoint`` is true, at least one provider advertising the- requested checkpoint API must return successfully; its exception is- propagated so the caller can preserve the uncompressed transcript.+ summary prompt. Empty string if no provider contributes.++ ``messages`` is the raw transcript — the historical (API v1)+ contract every existing provider receives unchanged.+ ``evidence_messages`` is the host-normalized direct-evidence list+ handed only to providers that opted into checkpoint API v2+; when+ omitted, v2 providers receive the raw list too.++ When ``require_checkpoint`` is true, at least one provider+ advertising the requested checkpoint API must return successfully;+ its exception is propagated so the caller can preserve the+ uncompressed transcript."""parts = []checkpoint_succeeded = Falsefor provider in self._providers:try:provider_version = int(- getattr(provider, "pre_compress_checkpoint_api_version", 0)+ getattr(+ provider,+ "pre_compress_checkpoint_api_version",+ _LEGACY_PRE_COMPRESS_API_VERSION,+ ))except (TypeError, ValueError):- provider_version = 0+ provider_version = _LEGACY_PRE_COMPRESS_API_VERSIONis_checkpoint_provider = provider_version >= checkpoint_api_version+ provider_messages = messages+ if is_checkpoint_provider and evidence_messages is not None:+ provider_messages = evidence_messagestry:- result = provider.on_pre_compress(messages)+ result = provider.on_pre_compress(provider_messages)if result and result.strip():parts.append(result)except Exception as e:diff --git a/agent/memory_provider.py b/agent/memory_provider.pyindex 5f6fdd0b9bc..014f8955032 100644--- a/agent/memory_provider.py+++ b/agent/memory_provider.py@@ -41,7 +41,11 @@ from typing import Any, Dict, List, Optionallogger = logging.getLogger(__name__)-PRE_COMPRESS_CHECKPOINT_API_VERSION = 1+# Version 1 is the historical, implicit contract every provider is already+# on: best-effort on_pre_compress() with the raw message list. Version 2 is+# the opt-in fail-closed checkpoint contract (normalized evidence handoff ++# strict-mode failure propagation).+PRE_COMPRESS_CHECKPOINT_API_VERSION = 2# Default glyph for the deterministic memory indicators. Providers override# per-status with their own brand mark (e.g. Hindsight uses "👁️").@@ -107,9 +111,10 @@ class MemoryProvider(ABC):"""Abstract base class for memory providers."""# Providers that durably checkpoint every successful on_pre_compress()- # call may opt into this host contract by setting the current version.- # Version 0 preserves the historical best-effort hook semantics.- pre_compress_checkpoint_api_version = 0+ # call may opt into that host contract by setting the current version+ # (PRE_COMPRESS_CHECKPOINT_API_VERSION). Version 1 is the implicit+ # historical contract: best-effort semantics, raw message list.+ pre_compress_checkpoint_api_version = 1@property@abstractmethoddiff --git a/cli-config.yaml.example b/cli-config.yaml.exampleindex 69f322bbffd..1da48f14154 100644--- a/cli-config.yaml.example+++ b/cli-config.yaml.example@@ -543,7 +543,7 @@ compression:enabled: true# Fail closed before lossy compaction unless an active memory provider that- # implements the pre-compress checkpoint contract (API v1) confirms its+ # implements the pre-compress checkpoint contract (API v2) confirms its# durable checkpoint (default: false). With this on and no checkpoint, the# compaction attempt errors with BLOCKED_MISSING_PREREQUISITE and the# uncompressed transcript is preserved for a later retry. The gate binds todiff --git a/tests/agent/test_pre_compress_checkpoint_contract.py b/tests/agent/test_pre_compress_checkpoint_contract.pyindex 01037cfa4fa..fe121c23417 100644--- a/tests/agent/test_pre_compress_checkpoint_contract.py+++ b/tests/agent/test_pre_compress_checkpoint_contract.py@@ -60,8 +60,34 @@ class _FailingLegacyProvider(_BaseStubProvider):raise RuntimeError("legacy best-effort failure")-def test_provider_base_class_defaults_to_best_effort_api_version_zero():- assert MemoryProvider.pre_compress_checkpoint_api_version == 0+def test_provider_base_class_defaults_to_implicit_historical_api_version_one():+ assert MemoryProvider.pre_compress_checkpoint_api_version == 1+ assert PRE_COMPRESS_CHECKPOINT_API_VERSION == 2+++def test_v1_providers_receive_raw_messages_and_v2_receive_evidence():+ """The historical (v1) contract is untouched: raw message list.++ Only providers that opted into checkpoint API v2 receive the+ host-normalized evidence handoff.+ """+ manager = MemoryManager()+ legacy = _BaseStubProvider("legacy")+ manager.add_provider(legacy)+ raw = [+ {"role": "user", "content": "evidence"},+ {"role": "tool", "content": "tool output", "tool_call_id": "t1"},+ ]+ evidence = [{"role": "user", "content": "evidence"}]++ manager.on_pre_compress(raw, evidence_messages=evidence)+ assert legacy.pre_compress_calls == [raw]++ durable_manager = MemoryManager()+ durable = _CheckpointProvider("durable")+ durable_manager.add_provider(durable)+ durable_manager.on_pre_compress(raw, evidence_messages=evidence)+ assert durable.pre_compress_calls == [evidence]def test_direct_messages_filter_keeps_only_direct_source_evidence():diff --git a/tests/run_agent/test_pre_compress_memory_context.py b/tests/run_agent/test_pre_compress_memory_context.pyindex b5a33fa8c27..5877f90a949 100644--- a/tests/run_agent/test_pre_compress_memory_context.py+++ b/tests/run_agent/test_pre_compress_memory_context.py@@ -77,7 +77,12 @@ def test_on_pre_compress_result_reaches_compressor_with_existing_options():force=True,)- manager.on_pre_compress.assert_called_once_with(messages)+ # Positional arg is the raw transcript (the historical v1 provider+ # contract); evidence_messages carries the normalized handoff for+ # checkpoint API v2+ providers. All-user messages normalize to themselves.+ manager.on_pre_compress.assert_called_once_with(+ messages, evidence_messages=messages+ )assert received == {"current_tokens": 100_000,"focus_topic": "checkpoint continuity",diff --git a/website/docs/developer-guide/memory-provider-plugin.md b/website/docs/developer-guide/memory-provider-plugin.mdindex 93b2939247c..d5fd99d15d7 100644--- a/website/docs/developer-guide/memory-provider-plugin.md+++ b/website/docs/developer-guide/memory-provider-plugin.md@@ -136,7 +136,7 @@ class MyMemoryProvider(MemoryProvider):host logs the failure and compression proceeds. That is the right default forinsight extraction — and the wrong one for a provider whose job is to archivetranscript evidence to a durable store *before* the lossy rewrite. For that-case the host offers an opt-in checkpoint contract (API v1):+case the host offers an opt-in checkpoint contract (API v2):```pythonfrom agent.memory_provider import MemoryProvider@@ -144,8 +144,9 @@ from agent.memory_provider import MemoryProviderclass MyArchivingProvider(MemoryProvider):# Opt in: every successful on_pre_compress() return means the durable# checkpoint is committed. Raise on any failure — do not return partial- # success. Version 0 (the inherited default) keeps best-effort semantics.- pre_compress_checkpoint_api_version = 1+ # success. Version 1 (the inherited default) is the implicit historical+ # contract: best-effort semantics, raw message list.+ pre_compress_checkpoint_api_version = 2def on_pre_compress(self, messages):ids = self._archive(messages) # must be durable before returning@@ -173,7 +174,10 @@ refused at agent init — the codex agent compacts its own thread with notruthful pre-compaction boundary, so a required checkpoint cannot beguaranteed there.-What your provider receives in both modes is normalized direct evidence:+What your provider receives depends on its declared API version. Version 1+providers (the implicit default — every pre-existing provider) keep the+historical contract: the raw message list, exactly as before. Version 2+checkpoint providers receive normalized direct evidence instead:user/assistant text rows only — tool results, system messages, the`tool_calls` payload of assistant messages (their prose is kept), and priorcompaction summaries are filtered host-side. Prior summaries are recognized