The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(honcho): omit reasoning-contaminated session summaries
686f6c612614b900b8db
diff --git a/plugins/memory/honcho/__init__.py b/plugins/memory/honcho/__init__.pyindex 5b6df77575c..4c480cfd54a 100644--- a/plugins/memory/honcho/__init__.py+++ b/plugins/memory/honcho/__init__.py@@ -24,6 +24,7 @@ from plugins.memory.honcho.client import HonchoClientConfig, resolve_config_pathfrom plugins.memory.honcho.client import _host_block, _HostLookupfrom plugins.memory.honcho.dialectic import DialecticMixinfrom plugins.memory.honcho.session_peers import assistant_peer_id_for, sanitize_peer_id+from plugins.memory.honcho.session_context import usable_honcho_summaryfrom plugins.memory.honcho.tool_schemas import ALL_TOOL_SCHEMASfrom tools.registry import tool_error@@ -399,7 +400,9 @@ class HonchoMemoryProvider(DialecticMixin, MemoryProvider):return frozenset(str(x) for x in listed)def _format_first_turn_context(self, ctx: dict) -> str:- """Render the prefetch context, keeping only the ``injection.sessionStart`` components when pinned."""+ """Render the prefetch context, keeping only the ``injection.sessionStart`` components when pinned.+ The summary passes usable_honcho_summary here, so a contaminated one never reaches _base_context_cache."""+ ctx = {**ctx, "summary": usable_honcho_summary(ctx.get("summary")) or ""}allowed = self._session_start_componentsparts, suppressed = [], []for name, key, header in _CONTEXT_SECTIONS:@@ -916,9 +919,9 @@ class HonchoMemoryProvider(DialecticMixin, MemoryProvider):ctx = self._manager.get_session_context(self._session_key, peer=args.get("peer", "user"))if not ctx:return json.dumps({"result": "No context available yet."})- parts = [f"## {header}\n{ctx[key]}"- for key, header in (("summary", "Summary"), ("representation", "Representation"), ("card", "Card"))- if ctx.get(key)]+ sections = (("Summary", usable_honcho_summary(ctx.get("summary"))),+ ("Representation", ctx.get("representation")), ("Card", ctx.get("card")))+ parts = [f"## {header}\n{value}" for header, value in sections if value]if recent := ctx.get("recent_messages"):parts.append("## Recent messages\n" + "\n".join(f" [{m['role']}] {m['content'][:200]}" for m in recent[-5:]))return json.dumps({"result": "\n\n".join(parts) or "No context available."})diff --git a/plugins/memory/honcho/session_context.py b/plugins/memory/honcho/session_context.pyindex cb0b0615159..824cc83442b 100644--- a/plugins/memory/honcho/session_context.py+++ b/plugins/memory/honcho/session_context.py@@ -3,6 +3,7 @@from __future__ import annotationsimport logging+import refrom typing import Any, Callablefrom plugins.memory.honcho.session_auth import HonchoAuthError@@ -11,6 +12,36 @@ logger = logging.getLogger("plugins.memory.honcho.session")_FAILED = object() # sentinel: a guarded call raised (distinct from a legitimately empty/None result)+# Reasoning-channel markers a summarizer model can leave inside a persisted session summary (#97639).+_THINK_BLOCK_RE = re.compile(+ r"<\s*(?:think|thinking|reasoning|thought|reasoning_scratchpad)\s*>.*?"+ r"<\s*/\s*(?:think|thinking|reasoning|thought|reasoning_scratchpad)\s*>",+ re.IGNORECASE | re.DOTALL,+)+_THINK_CLOSE_RE = re.compile(r"</\s*think\s*>", re.IGNORECASE)+_PLANNING_HEAD_RE = re.compile(+ r"^(?:i need to create a thorough|the instruction says to focus on capturing key facts|first, let me review)",+ re.IGNORECASE,+)+++def usable_honcho_summary(text: object) -> str | None:+ """A session summary safe to inject, or None to omit it. Honcho summarizers can persist the+ model's planning text and a trailing ``</think>`` as the summary body; the text after that+ close survives, planning-only or still-tagged text is dropped."""+ raw = "" if text is None else str(text)+ if not raw.strip():+ return None+ # The observed payload has no opening tag: planning prose, then ``</think>``, then the summary.+ close = _THINK_CLOSE_RE.search(raw)+ if close:+ raw = raw[close.end():]+ cleaned = _THINK_BLOCK_RE.sub("", raw).strip()+ lowered = cleaned.lower()+ if not cleaned or "<think" in lowered or "</think" in lowered or _PLANNING_HEAD_RE.search(cleaned):+ return None+ return cleaned+class SessionContextMixin:"""Peer context / card / search / conclusion / dialectic operations against Honcho."""@@ -107,8 +138,8 @@ class SessionContextMixin:"session summary fetch",lambda: self._sdk_session(session.honcho_session_id).context(summary=True, tokens=self._context_tokens),)- if ctx.summary and getattr(ctx.summary, "content", None):- result["summary"] = ctx.summary.content+ if ctx.summary and (summary := usable_honcho_summary(getattr(ctx.summary, "content", None))):+ result["summary"] = summarydef _user() -> None:observer_peer_id, target_peer_id = self._resolve_observer_target(session, "user")@@ -167,8 +198,8 @@ class SessionContextMixin:),)result: dict[str, Any] = {}- if ctx.summary:- result["summary"] = ctx.summary.content+ if ctx.summary and (summary := usable_honcho_summary(getattr(ctx.summary, "content", ctx.summary))):+ result["summary"] = summaryif ctx.peer_representation:result["representation"] = ctx.peer_representationif ctx.peer_card:diff --git a/tests/test_honcho_summary_sanitize.py b/tests/test_honcho_summary_sanitize.pynew file mode 100644index 00000000000..105566ee857--- /dev/null+++ b/tests/test_honcho_summary_sanitize.py@@ -0,0 +1,134 @@+"""Honcho session summaries must not inject model reasoning (#97639)."""++from types import SimpleNamespace++from plugins.memory.honcho.session import HonchoSession, HonchoSessionManager+from plugins.memory.honcho.session_context import usable_honcho_summary+++CONTAMINATED = """I need to create a thorough, comprehensive summary of this conversation.+The instruction says to focus on capturing key facts...+First, let me review what I have in the previous summary...+</think>+Alice prefers dark roast coffee.+"""++PLANNING_ONLY = """I need to create a thorough, comprehensive summary of this conversation.+The instruction says to focus on capturing key facts...+First, let me review what I have in the previous summary...+"""+++def test_usable_summary_keeps_text_after_think_close() -> None:+ out = usable_honcho_summary(CONTAMINATED)+ assert out is not None+ assert "Alice prefers dark roast coffee." in out+ assert "</think>" not in out.lower()+ assert "I need to create a thorough" not in out+++def test_usable_summary_drops_planning_preamble_without_body() -> None:+ assert usable_honcho_summary(PLANNING_ONLY) is None+++def test_usable_summary_drops_closed_think_block() -> None:+ raw = "<think>plan the summary</think>\nBob uses vim."+ out = usable_honcho_summary(raw)+ assert out == "Bob uses vim."+++def test_usable_summary_keeps_clean_text() -> None:+ assert usable_honcho_summary("Uses Python 3.11.") == "Uses Python 3.11."+++class _FakeSummary:+ def __init__(self, content: str) -> None:+ self.content = content+++class _FakeContext:+ def __init__(self, content: str) -> None:+ self.summary = _FakeSummary(content)+ self.peer_representation = "representation"+ self.peer_card = ["fact"]+ self.messages = []+++class _RecordingHonchoSession:+ def __init__(self, content: str) -> None:+ self.content = content++ def context(self, **kwargs):+ return _FakeContext(self.content)+++def _manager_with_summary(content: str):+ cfg = SimpleNamespace(+ write_frequency="turn",+ dialectic_reasoning_level="low",+ dialectic_dynamic=True,+ dialectic_max_chars=600,+ observation_mode="directional",+ user_observe_me=True,+ user_observe_others=True,+ ai_observe_me=True,+ ai_observe_others=True,+ message_max_chars=25000,+ dialectic_max_input_chars=10000,+ )+ mgr = HonchoSessionManager(honcho=SimpleNamespace(), config=cfg)+ session = HonchoSession(+ key="test-session",+ user_peer_id="chris",+ assistant_peer_id="hermes",+ honcho_session_id="test-session",+ )+ fake = _RecordingHonchoSession(content)+ mgr._cache[session.key] = session+ mgr._sessions_cache[session.honcho_session_id] = fake+ return mgr+++def test_prefetch_omits_planning_only_summary() -> None:+ mgr = _manager_with_summary(PLANNING_ONLY)+ mgr._fetch_peer_context = lambda *a, **k: {+ "representation": "representation",+ "card": ["fact"],+ }+ mgr._resolve_observer_target = lambda *a, **k: ("hermes", "chris")+ result = mgr.get_prefetch_context("test-session")+ assert "summary" not in result+ assert result.get("representation") == "representation"+++def test_prefetch_keeps_body_after_think_close() -> None:+ mgr = _manager_with_summary(CONTAMINATED)+ mgr._fetch_peer_context = lambda *a, **k: {+ "representation": "representation",+ "card": ["fact"],+ }+ mgr._resolve_observer_target = lambda *a, **k: ("hermes", "chris")+ result = mgr.get_prefetch_context("test-session")+ assert result["summary"] == "Alice prefers dark roast coffee."+++def test_session_context_omits_planning_only_summary() -> None:+ mgr = _manager_with_summary(PLANNING_ONLY)+ result = mgr.get_session_context("test-session")+ assert "summary" not in result+ assert result.get("representation") == "representation"+++def test_format_first_turn_omits_contaminated_summary() -> None:+ from plugins.memory.honcho import HonchoMemoryProvider++ plugin = HonchoMemoryProvider.__new__(HonchoMemoryProvider)+ out = plugin._format_first_turn_context(+ {+ "summary": PLANNING_ONLY,+ "card": "Likes espresso.",+ }+ )+ assert "Likes espresso." in out+ assert "Session Summary" not in out+ assert "I need to create a thorough" not in out