The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor: offset the salvage's growth (checkpoint gate, leftover-steer merge)
Tekniumf974134f367b
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.pyindex 66a978656d6..922bc1d82d8 100644--- a/agent/conversation_compression.py+++ b/agent/conversation_compression.py@@ -1397,84 +1397,16 @@ def run_compress_context_with_progress_timeout(fence.revoke_commit_admission()-class CompressionCheckpointUnavailable(RuntimeError):- """Raised when required durable pre-compress checkpointing is unavailable."""---# Shared by the startup warning and compress-time block so operators see the-# same recovery path: disable the fail-closed flag, or switch providers.-_CHECKPOINT_REQUIRED_REMEDIATION = (- "set compression.checkpoint_required: false, or switch to a memory "- "provider that implements checkpoint API v2"+from agent.conversation_compression_checkpoint import (+ _CHECKPOINT_REQUIRED_REMEDIATION,+ CompressionCheckpointUnavailable,+ _active_memory_provider_label,+ _checkpoint_blocked,+ _checkpoint_incapable,+ _warn_checkpoint_required_without_capable_provider,)-def _active_memory_provider_label(agent: Any) -> str:- """Human-readable active provider name, or an explicit none sentinel."""- memory_manager = getattr(agent, "_memory_manager", None)- if memory_manager is None:- return "no active provider"- providers = getattr(memory_manager, "providers", None)- names: list[str] = []- if providers is not None:- try:- iterable = list(providers)- except TypeError:- iterable = []- for provider in iterable:- name = getattr(provider, "name", None)- if isinstance(name, str) and name.strip():- names.append(name.strip())- return ", ".join(names) if names else "no active provider"---def _checkpoint_blocked(reason: str) -> CompressionCheckpointUnavailable:- return CompressionCheckpointUnavailable(- f"BLOCKED_MISSING_PREREQUISITE: required pre-compress checkpoint unavailable: {reason}"- )---def _checkpoint_incapable(reason: str) -> CompressionCheckpointUnavailable:- """Capability refusal: the gate can never pass with this provider set, so the- message carries the config-level way out. Transient checkpoint failures keep- the plain form — there the provider is capable and the right move is a retry."""- return _checkpoint_blocked(f"{reason}. Recover by {_CHECKPOINT_REQUIRED_REMEDIATION}")---def _warn_checkpoint_required_without_capable_provider(agent: Any) -> None:- """Startup warning when fail-closed compress will block (init itself must not refuse).-- Capability-probe exceptions are suppressed so a broken provider cannot crash- agent construction — same fail-open style as the micro-compact warning.- Probe failures log at DEBUG so a flaky probe can be diagnosed without- refusing init or emitting the incapable-provider WARNING.- """- if getattr(agent, "compression_checkpoint_required", False) is not True:- return- memory_manager = getattr(agent, "_memory_manager", None)- if memory_manager is not None:- supports_checkpoint = getattr(memory_manager, "supports_pre_compress_checkpoint", None)- if callable(supports_checkpoint):- try:- if bool(supports_checkpoint(PRE_COMPRESS_CHECKPOINT_API_VERSION)):- return- except Exception as exc:- logger.debug(- "checkpoint-required capability probe failed; init continues: %s",- exc,- exc_info=True,- )- return- logger.warning(- "compression.checkpoint_required is enabled but the active memory "- "provider (%s) does not implement checkpoint API v%s. Compress will "- "fail closed. Recover by %s.",- _active_memory_provider_label(agent),- PRE_COMPRESS_CHECKPOINT_API_VERSION,- _CHECKPOINT_REQUIRED_REMEDIATION,- )--def _lock_api_is_absent_on_session_db(lock_db: Any) -> bool:"""Whether the live in-memory SessionDB class structurally predates locks.Only the exact old ``hermes_state.SessionDB`` class (hot-reload skew) may fail open; proxies, lookalikes,diff --git a/agent/conversation_compression_checkpoint.py b/agent/conversation_compression_checkpoint.pynew file mode 100644index 00000000000..49c508b3fd9--- /dev/null+++ b/agent/conversation_compression_checkpoint.py@@ -0,0 +1,93 @@+"""Fail-closed pre-compress checkpoint gate for ``agent.conversation_compression``.++The refusal type, its remediation text and the startup warning for+``compression.checkpoint_required``; ``conversation_compression`` re-exports every name.+"""++from __future__ import annotations++import logging+from typing import Any++from agent.memory_provider import PRE_COMPRESS_CHECKPOINT_API_VERSION++# Log-record parity with the origin module.+logger = logging.getLogger("agent.conversation_compression")+++class CompressionCheckpointUnavailable(RuntimeError):+ """Raised when required durable pre-compress checkpointing is unavailable."""+++# Shared by the startup warning and compress-time block so operators see the+# same recovery path: disable the fail-closed flag, or switch providers.+_CHECKPOINT_REQUIRED_REMEDIATION = (+ "set compression.checkpoint_required: false, or switch to a memory "+ "provider that implements checkpoint API v2"+)+++def _active_memory_provider_label(agent: Any) -> str:+ """Human-readable active provider name, or an explicit none sentinel."""+ memory_manager = getattr(agent, "_memory_manager", None)+ if memory_manager is None:+ return "no active provider"+ providers = getattr(memory_manager, "providers", None)+ names: list[str] = []+ if providers is not None:+ try:+ iterable = list(providers)+ except TypeError:+ iterable = []+ for provider in iterable:+ name = getattr(provider, "name", None)+ if isinstance(name, str) and name.strip():+ names.append(name.strip())+ return ", ".join(names) if names else "no active provider"+++def _checkpoint_blocked(reason: str) -> CompressionCheckpointUnavailable:+ return CompressionCheckpointUnavailable(+ f"BLOCKED_MISSING_PREREQUISITE: required pre-compress checkpoint unavailable: {reason}"+ )+++def _checkpoint_incapable(reason: str) -> CompressionCheckpointUnavailable:+ """Capability refusal: the gate can never pass with this provider set, so the+ message carries the config-level way out. Transient checkpoint failures keep+ the plain form — there the provider is capable and the right move is a retry."""+ return _checkpoint_blocked(f"{reason}. Recover by {_CHECKPOINT_REQUIRED_REMEDIATION}")+++def _warn_checkpoint_required_without_capable_provider(agent: Any) -> None:+ """Startup warning when fail-closed compress will block (init itself must not refuse).++ Capability-probe exceptions are suppressed so a broken provider cannot crash+ agent construction — same fail-open style as the micro-compact warning.+ Probe failures log at DEBUG so a flaky probe can be diagnosed without+ refusing init or emitting the incapable-provider WARNING.+ """+ if getattr(agent, "compression_checkpoint_required", False) is not True:+ return+ memory_manager = getattr(agent, "_memory_manager", None)+ if memory_manager is not None:+ supports_checkpoint = getattr(memory_manager, "supports_pre_compress_checkpoint", None)+ if callable(supports_checkpoint):+ try:+ if bool(supports_checkpoint(PRE_COMPRESS_CHECKPOINT_API_VERSION)):+ return+ except Exception as exc:+ logger.debug(+ "checkpoint-required capability probe failed; init continues: %s",+ exc,+ exc_info=True,+ )+ return+ logger.warning(+ "compression.checkpoint_required is enabled but the active memory "+ "provider (%s) does not implement checkpoint API v%s. Compress will "+ "fail closed. Recover by %s.",+ _active_memory_provider_label(agent),+ PRE_COMPRESS_CHECKPOINT_API_VERSION,+ _CHECKPOINT_REQUIRED_REMEDIATION,+ )diff --git a/gateway/run_busy.py b/gateway/run_busy.pyindex bbf9a12a29b..8dd9901ec6c 100644--- a/gateway/run_busy.py+++ b/gateway/run_busy.py@@ -131,6 +131,58 @@ class GatewayBusySessionMixin:# else: no adapter — leave the head in place so we don't silently drop it.return pending_event+ def _merge_leftover_steer(+ self, result: Any, adapter: Any, source: SessionSource, session_key: Optional[str],+ pending_event: Optional[MessageEvent], pending: Optional[str],+ ) -> tuple[Optional[MessageEvent], Optional[str]]:+ """Fold a leftover /steer (arrived after the last tool batch) into the post-turn drain:+ the next user turn when nothing else is pending, otherwise ahead of / behind it in the FIFO."""+ leftover_steer = (result.get("pending_steer") or "").strip() if result else None+ if leftover_steer:+ if not pending and not pending_event:+ pending = leftover_steer+ logger.debug("Delivering leftover /steer as next turn: '%s...'", pending[:40])+ elif pending_event and adapter and session_key:+ # User steered during the turn, but a background event or queued message arrived.+ # Deliver the user's steer first and restore the pending event to the head of the queue.+ overflow = self._overflow_queue(session_key)+ if hasattr(adapter, "_pending_messages") and isinstance(adapter._pending_messages, dict):+ promoted = adapter._pending_messages.get(session_key)+ if promoted is not None:+ if overflow is not None:+ overflow.insert(0, promoted)+ else:+ self._session_state(session_key).conversation.queued_events.insert(0, promoted)+ adapter._pending_messages[session_key] = pending_event+ else:+ if overflow is not None:+ overflow.insert(0, pending_event)+ else:+ self._session_state(session_key).conversation.queued_events.insert(0, pending_event)+ pending_event = None+ pending = leftover_steer+ logger.debug(+ "Delivering leftover /steer before queued event for session %s: '%s...'",+ session_key, pending[:40],+ )+ elif pending and not pending_event:+ from gateway.platforms.base import MessageEvent+ # A deferred steer continues the active channel context, just like an+ # eventless follow-up. Reuse its pins without marking the user as internal.+ steer_prompt, steer_source = self._pinned_channel_inputs(+ session_key, None, source, internal=True,+ )+ steer_event = MessageEvent(+ text=leftover_steer, source=steer_source, channel_prompt=steer_prompt,+ )+ if session_key:+ self._enqueue_fifo(session_key, steer_event, adapter)+ logger.debug(+ "Enqueued leftover /steer behind pending message for session %s: '%s...'",+ session_key or "?", leftover_steer[:40],+ )+ return pending_event, pending+def _queue_depth(self, session_key: str, *, adapter: Any = None) -> int:"""Total pending /queue items for a session — slot + overflow."""depth = len(self._overflow_queue(session_key) or ())diff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex b10e72dc30c..6bba5446291 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -1753,50 +1753,7 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gatewaylogger.debug("Processing queued message after agent completion: '%s...'", pending[:40])# Leftover /steer (arrived after the last tool batch): deliver as the next user turn.- leftover_steer = (result.get("pending_steer") or "").strip() if result else None- if leftover_steer:- if not pending and not pending_event:- pending = leftover_steer- logger.debug("Delivering leftover /steer as next turn: '%s...'", pending[:40])- elif pending_event and adapter and session_key:- # User steered during the turn, but a background event or queued message arrived.- # Deliver the user's steer first and restore the pending event to the head of the queue.- overflow = self._overflow_queue(session_key)- if hasattr(adapter, "_pending_messages") and isinstance(adapter._pending_messages, dict):- promoted = adapter._pending_messages.get(session_key)- if promoted is not None:- if overflow is not None:- overflow.insert(0, promoted)- else:- self._session_state(session_key).conversation.queued_events.insert(0, promoted)- adapter._pending_messages[session_key] = pending_event- else:- if overflow is not None:- overflow.insert(0, pending_event)- else:- self._session_state(session_key).conversation.queued_events.insert(0, pending_event)- pending_event = None- pending = leftover_steer- logger.debug(- "Delivering leftover /steer before queued event for session %s: '%s...'",- session_key, pending[:40],- )- elif pending and not pending_event:- from gateway.platforms.base import MessageEvent- # A deferred steer continues the active channel context, just like an- # eventless follow-up. Reuse its pins without marking the user as internal.- steer_prompt, steer_source = self._pinned_channel_inputs(- session_key, None, source, internal=True,- )- steer_event = MessageEvent(- text=leftover_steer, source=steer_source, channel_prompt=steer_prompt,- )- if session_key:- self._enqueue_fifo(session_key, steer_event, adapter)- logger.debug(- "Enqueued leftover /steer behind pending message for session %s: '%s...'",- session_key or "?", leftover_steer[:40],- )+ pending_event, pending = self._merge_leftover_steer(result, adapter, source, session_key, pending_event, pending)# Safety net: a pending slash command is never passed to the agent as user input.if pending and pending.strip().startswith("/"):