The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): persist the authored text, not the Discord triggering note, as the user row
teknium1c61bbc24618c
diff --git a/gateway/run_inbound.py b/gateway/run_inbound.pyindex 1c65aab39aa..0cee8372988 100644--- a/gateway/run_inbound.py+++ b/gateway/run_inbound.py@@ -39,6 +39,27 @@ if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)logger = logging.getLogger("gateway.run")+def discord_triggering_note(message_id: Any) -> str:+ """Model-facing routing note for a Discord turn (rides the API-bound user message only)."""+ return (+ f"[Triggering message id: `{message_id}` — use as `message_id` for reply/react/pin "+ f"via the discord tools.]"+ )+++def strip_discord_triggering_note(event: Any, message_text: Any) -> Any:+ """Authored text for the durable user row: peel off exactly the note+ ``_prepend_inbound_reply_context`` added for THIS event, if present. The note is a+ model instruction, not something the user wrote — persisted as ``content`` it renders+ verbatim in every transcript surface and pollutes FTS/memory (#71304, #114719). It+ keeps riding ``message_text`` (and the replay-only ``api_content`` sidecar)."""+ message_id = getattr(event, "message_id", None)+ if not message_id or not isinstance(message_text, str):+ return message_text+ prefix = f"{discord_triggering_note(message_id)}\n\n"+ return message_text[len(prefix):] if message_text.startswith(prefix) else message_text++class GatewayInboundMixin:"""Inbound message pipeline (_handle_message, text/media preparation, durable-turn markers, plugin injection) for GatewayRunner."""@@ -1553,22 +1574,7 @@ class GatewayInboundMixin:@staticmethoddef _prepend_inbound_reply_context(event: MessageEvent, source: SessionSource, message_text: str) -> str:- """Prepend the Discord triggering-message id and the reply-to pointer."""- # Discord: the triggering message id goes on the per-turn user message, never the cached- # system prompt — it changes every turn and would bust the agent-cache signature.- if (- source is not None- and getattr(source, "platform", None) == Platform.DISCORD- and getattr(event, "message_id", None)- ):- from gateway.session import _discord_tools_loaded as _disc_tools_loaded- if _disc_tools_loaded():- message_text = (- f"[Triggering message id: `{event.message_id}` — use as "- f"`message_id` for reply/react/pin via the discord tools.]\n\n"- f"{message_text}"- )-+ """Prepend the reply-to pointer, then the Discord triggering-message note (outermost)."""if getattr(event, "reply_to_text", None) and event.reply_to_message_id:# Always inject the reply-to pointer even when the quoted text is already in history:# it's disambiguation (*which* prior message), not deduplication.@@ -1577,6 +1583,19 @@ class GatewayInboundMixin:reply_text = event.reply_to_text_who = " your previous message" if getattr(event, "reply_to_is_own_message", False) else ""message_text = f'[Replying to{_who}: "{reply_text}"]\n\n{message_text}'++ # Discord: the triggering message id goes on the per-turn user message, never the cached+ # system prompt — it changes every turn and would bust the agent-cache signature. It is+ # the OUTERMOST prefix so strip_discord_triggering_note can peel exactly it off the+ # persisted transcript row without touching the reply pointer.+ if (+ source is not None+ and getattr(source, "platform", None) == Platform.DISCORD+ and getattr(event, "message_id", None)+ ):+ from gateway.session import _discord_tools_loaded as _disc_tools_loaded+ if _disc_tools_loaded():+ message_text = f"{discord_triggering_note(event.message_id)}\n\n{message_text}"return message_textasync def _inbound_model_context_length(self, source: SessionSource, session_key: str) -> int:diff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex 28d6aafde3f..86d288f1ea6 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -1393,9 +1393,11 @@ class GatewayTurnMixin:def _hmwa_apply_message_timestamp(self, event, message_text):"""Capture the platform event time as message metadata and keep the persisted transcript- clean (strip any leading timestamp prefix) regardless of the toggle; only the in-context+ clean — strip any leading timestamp prefix and the Discord triggering-message note (a+ model instruction, not authored text) — regardless of the toggle; only the in-contextRENDER is gated behind gateway.message_timestamps.enabled (default OFF)."""from gateway.run import _load_gateway_config, _message_timestamps_enabled+ from gateway.run_inbound import strip_discord_triggering_notepersist_user_message = Nonepersist_user_timestamp = Nonetry:@@ -1408,7 +1410,7 @@ class GatewayTurnMixin:_evt_tz = _get_evt_tz()if message_text and isinstance(message_text, str):_clean_message_text, _embedded_ts = _strip_msg_ts(message_text, tz=_evt_tz)- persist_user_message = _clean_message_text+ persist_user_message = strip_discord_triggering_note(event, _clean_message_text)_event_epoch = _coerce_msg_ts(getattr(event, "timestamp", None), tz=_evt_tz)persist_user_timestamp = _event_epoch if _event_epoch is not None else _embedded_tsif _message_timestamps_enabled(_load_gateway_config()):@@ -3709,6 +3711,8 @@ class GatewayTurnMixin:# distinct from the reply anchor above (None in forum topics). Carry it or two chained# topic turns with the same text would collide on one obligation id (queued-final-ledger).next_inbound_id = None+ # Queued Discord turns carry the same routing note as first turns; persist the authored text.+ next_persist_message = Nonenext_display_kind = display_kind_for_event(pending_event)# See #60671.if pending_event is not None:@@ -3733,6 +3737,8 @@ class GatewayTurnMixin:)if next_message is None:return result+ from gateway.run_inbound import strip_discord_triggering_note+ next_persist_message = strip_discord_triggering_note(pending_event, next_message)next_message_id = self._reply_anchor_for_event(pending_event)next_inbound_id = str(pending_event.message_id) if getattr(pending_event, "message_id", None) else Nonenext_channel_prompt = getattr(pending_event, "channel_prompt", None)@@ -3782,6 +3788,7 @@ class GatewayTurnMixin:run_generation=run_generation, _interrupt_depth=_interrupt_depth + 1,event_message_id=next_message_id, inbound_message_id=next_inbound_id,channel_prompt=next_channel_prompt, message_type=next_message_type,+ persist_user_message=next_persist_message,persist_user_display_kind=next_display_kind,persist_user_display_metadata=diagnostic_metadata(pending_event) or None,)diff --git a/tests/gateway/test_discord_triggering_note_persistence.py b/tests/gateway/test_discord_triggering_note_persistence.pynew file mode 100644index 00000000000..46c1b0e7f01--- /dev/null+++ b/tests/gateway/test_discord_triggering_note_persistence.py@@ -0,0 +1,88 @@+"""The Discord ``[Triggering message id: …]`` note is a model instruction: it rides the+API-bound user message but must never be persisted as the user row's ``content``+(every transcript surface rendered it as if the user typed it).+"""+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock++import pytest++from gateway.config import GatewayConfig, Platform+from gateway.platforms.event import MessageEvent+from gateway.run import GatewayRunner+from gateway.run_inbound import discord_triggering_note+from gateway.session import SessionSource+++def _runner() -> GatewayRunner:+ runner = object.__new__(GatewayRunner)+ runner.config = GatewayConfig(group_sessions_per_user=False)+ runner.adapters = {}+ runner._model = "test-model"+ runner._base_url = ""+ return runner+++def _discord_source() -> SessionSource:+ return SessionSource(platform=Platform.DISCORD, chat_id="dm1", chat_type="dm", user_id="u1", user_name="Owen")+++async def test_discord_note_rides_model_text_but_not_persisted_content(monkeypatch):+ """Real inbound prep → persist seam: the model sees the note (outermost, ahead of the reply+ pointer); the durable row keeps the reply pointer and the authored text only."""+ monkeypatch.setattr("gateway.session._discord_tools_loaded", lambda: True)+ runner = _runner()+ source = _discord_source()+ event = MessageEvent(+ text="yes do that", source=source, message_id="1550380365858865157",+ reply_to_message_id="1550380365858865156", reply_to_text="Create a project plan for Q4",+ )++ model_text = await runner._prepare_inbound_message_text(event=event, source=source, history=[])+ message_text, persist_user_message, _ts = runner._hmwa_apply_message_timestamp(event, model_text)++ note = discord_triggering_note("1550380365858865157")+ assert message_text.startswith(f"{note}\n\n[Replying to: \"Create a project plan for Q4\"]")+ assert persist_user_message == '[Replying to: "Create a project plan for Q4"]\n\nyes do that'++ # Control: a turn without a platform message id (desktop relay) persists byte-identical text.+ relay = MessageEvent(text="plain relay turn", source=source, message_id=None)+ relay_text = await runner._prepare_inbound_message_text(event=relay, source=source, history=[])+ _, relay_persist, _ = runner._hmwa_apply_message_timestamp(relay, relay_text)+ assert relay_persist == "plain relay turn" == relay_text+++async def test_queued_followup_persists_authored_text():+ """The in-band queued follow-up runs the same inbound prep; its recursive ``_run_agent`` must+ carry the clean persist text too, or a queued Discord turn re-persists the note."""+ runner = _runner()+ runner._MAX_INTERRUPT_DEPTH = 8+ runner._run_agent = AsyncMock(return_value={"final_response": "done", "messages": []})+ runner._run_agent_deliver_first_response = AsyncMock()+ runner._is_goal_continuation_event = MagicMock(return_value=False)+ runner._session_key_for_source = MagicMock(return_value="agent:main:discord:dm:dm1")+ note = discord_triggering_note("6002")+ runner._prepare_profile_scoped_inbound_message_text = AsyncMock(return_value=f"{note}\n\nthe follow-up")+ runner._reply_anchor_for_event = MagicMock(return_value=None)+ runner._adapter_for_source = MagicMock(return_value=None)+ runner._refresh_agent_cache_message_count = AsyncMock()+ source = _discord_source()+ turn_ctx = SimpleNamespace(+ source=source, session_id="sid", session_key="agent:main:discord:dm:dm1", run_generation=1,+ _interrupt_depth=0, history=[], _status_thread_metadata=None, context_prompt=None,+ result_holder=[None],+ )+ pending_event = SimpleNamespace(+ source=source, message_id="6002", channel_prompt=None, message_type=None, internal=False, metadata={},+ )++ await GatewayRunner._run_agent_queued_followup(+ runner, turn_ctx, adapter=None, pending="hi again", pending_event=pending_event,+ response="resp", result={"interrupted": True, "messages": []}, stream_task=None,+ )++ kwargs = runner._run_agent.await_args.kwargs+ assert kwargs["message"] == f"{note}\n\nthe follow-up"+ assert kwargs["persist_user_message"] == "the follow-up"diff --git a/website/docs/developer-guide/gateway-session-lifecycle.md b/website/docs/developer-guide/gateway-session-lifecycle.mdindex 0597d9e5387..21c78aa6a09 100644--- a/website/docs/developer-guide/gateway-session-lifecycle.md+++ b/website/docs/developer-guide/gateway-session-lifecycle.md@@ -48,7 +48,7 @@ incoming `MessageEvent` and used for routing, isolation, and context injection.| `is_bot` | `bool` | `False` | True when the message author is a bot or webhook (Discord bots). || `guild_id` | `Optional[str]` | `None` | Discord guild / Slack workspace / Matrix server scope identifier. || `parent_chat_id` | `Optional[str]` | `None` | Parent channel when `chat_id` refers to a thread. |-| `message_id` | `Optional[str]` | `None` | ID of the triggering message. Used for pin/reply/react operations and Discord ID injection. |+| `message_id` | `Optional[str]` | `None` | ID of the triggering message. Used for pin/reply/react operations and Discord ID injection (the injected `[Triggering message id: …]` note rides the API-bound message only; the persisted user row keeps the authored text). || `role_authorized` | `bool` | `False` | True when adapter granted access via a platform role (not individual user ID). |### Key Methods