Skip to content

The agent that grows with you

fix(gateway): a wake after an agent eviction reuses the session-context pin

John Paul Soliva9e48e33348e9
diff --git a/gateway/run_agent_cache.py b/gateway/run_agent_cache.py
index 1d8aaacd002..aa8fc266700 100644
--- a/gateway/run_agent_cache.py
+++ b/gateway/run_agent_cache.py
@@ -667,13 +667,13 @@ class GatewayAgentCacheMixin:
return f"[Voice channel now: {vc_now or 'not connected to a voice channel'}]"
async def _rehydrate_prompt_pins(self, session_key: str, expected_session_id: Optional[str]) -> None:
- """Adopt the durable pin snapshot for an internal turn when this process holds no pins for
- *session_key* (a restart). Eviction clears only ``ephemeral_pin`` and keeps ``channel_pin``,
- so an evicted agent still re-renders instead of reviving the snapshot."""
+ """Adopt the durable pin snapshot for an internal turn when this process holds no context pin
+ for *session_key*: a restart, or an eviction (/stop, /undo, /model), which clears only
+ ``ephemeral_pin``. Without it the wake renders from its origin-only source (no chat or user
+ names) and the next human turn re-keys back, rewriting the system bytes twice. Human turns
+ never call this, so an evicted agent's next human turn still re-renders."""
state = self._peek_session_state(session_key)
- if state is not None and (
- state.conversation.ephemeral_pin is not None or state.conversation.channel_pin is not None
- ):
+ if state is not None and state.conversation.ephemeral_pin is not None:
return
try:
pin = sanitize_prompt_pin(await self.async_session_store.get_prompt_pin(
@@ -686,7 +686,8 @@ class GatewayAgentCacheMixin:
return
conversation = self._session_state(session_key).conversation
conversation.ephemeral_pin = (pin["context_key"], pin["context_prompt"], pin["redact_pii"])
- conversation.channel_pin = (pin["channel_prompt"], pin["parent_chat_id"])
+ if conversation.channel_pin is None:
+ conversation.channel_pin = (pin["channel_prompt"], pin["parent_chat_id"])
async def _persist_prompt_pins(self, session_key: Optional[str], expected_session_id: Optional[str]) -> None:
"""Persist this conversation's pins before the agent runs; the store no-ops an unchanged
@@ -719,7 +720,7 @@ class GatewayAgentCacheMixin:
source rebuilt from the persisted origin, without chat_name/user_name/message_id. Rendering
from it re-keyed the pin, and the next human turn re-keyed it back (A→B→A), rewriting
already-sent system bytes each time. An internal event is never a real metadata change, so
- it reuses an existing pin verbatim (restored by ``_rehydrate_prompt_pins`` after a restart); with
+ it reuses an existing pin verbatim (restored by ``_rehydrate_prompt_pins`` after a restart or an eviction); with
no pin yet it renders and pins as usual. The pin records the ``privacy.redact_pii`` it was
rendered under: bytes from another privacy policy are never reused, even by an internal
event."""
diff --git a/tests/gateway/test_internal_event_pin_wiring.py b/tests/gateway/test_internal_event_pin_wiring.py
index ad3d8ec2388..c10fc6225c5 100644
--- a/tests/gateway/test_internal_event_pin_wiring.py
+++ b/tests/gateway/test_internal_event_pin_wiring.py
@@ -364,6 +364,33 @@ async def test_first_internal_event_after_restart_rehydrates_durable_prompt_pins
assert _effective_ephemeral(after, first_internal) == _effective_ephemeral(before, human)
+async def test_first_internal_event_after_agent_eviction_keeps_effective_prompt(monkeypatch):
+ """/stop, /undo and /model evict the cached agent mid-conversation and clear the context pin
+ while the channel pin survives; a wake arriving next must still send the human turn's bytes."""
+ config = GatewayConfig()
+ config.platforms[Platform.DISCORD] = PlatformConfig(
+ enabled=True,
+ channel_overrides={PARENT_ID: ChannelOverride(system_prompt="Parent persona.")},
+ )
+ runner = _make_runner(monkeypatch, config, durable_prompt_pin={})
+ calls: list[dict] = []
+ _capture(runner, calls)
+
+ await _drive(runner, ((False, _human_thread_source()),), channel_prompt="Channel hint.")
+ runner._evict_cached_agent(KEY)
+ await _drive(
+ runner,
+ ((True, _wake_thread_source()), (False, _human_thread_source())),
+ channel_prompt="Channel hint.",
+ )
+
+ assert len(calls) == 3
+ eph = [_effective_ephemeral(runner, kw) for kw in calls]
+ assert "Guild / #dev / build thread" in eph[0]
+ assert eph[0] == eph[1] == eph[2], "wake after eviction re-rendered the session context (A->B->A)"
+
+
@pytest.mark.asyncio
async def test_human_first_after_restart_ignores_stale_durable_prompt_pin(monkeypatch):
durable = {