The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): synthetic turns rehydrate pins and keep their own pending-slot identity
Tekniumd3ed7d479831
diff --git a/gateway/run_busy.py b/gateway/run_busy.pyindex 1d7d3ad6a5f..1528b62bd42 100644--- a/gateway/run_busy.py+++ b/gateway/run_busy.py@@ -456,6 +456,7 @@ class GatewayBusySessionMixin:existing = pending_slot.get(session_key) if isinstance(pending_slot, dict) else Nonesame_security_context = existing is not None and (getattr(existing, "internal", False) == getattr(event, "internal", False)+ and getattr(existing, "inherit_channel_pin", False) == getattr(event, "inherit_channel_pin", False)and getattr(existing, "allow_gateway_control", True)== getattr(event, "allow_gateway_control", True)and all(diff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex 6b00733fafd..eee8cc4ee82 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -257,12 +257,9 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gateway# Admission/typing is not execution. All routing, authorization and# turn preparation gates have passed when the agent runner is entered.event._heartbeat_execution_started = True- # Internal and pin-inheriting synthetic events reuse the last human turn's channel- # inputs (see _pinned_channel_inputs).- _turn_channel_prompt, _turn_source = self._pinned_channel_inputs(+ _turn_channel_prompt, _turn_source = self._pinned_channel_inputs( # internal/synthetic reuse pinssession_key, event.channel_prompt, source,- internal=event.internal or getattr(event, "inherit_channel_pin", False),- )+ internal=event.internal or getattr(event, "inherit_channel_pin", False))if not event.internal:# Persist the coherent context+channel pair before execution: a crash during the# human turn may be followed by an internal startup-resume on the next process.diff --git a/gateway/run_turn_prepare.py b/gateway/run_turn_prepare.pyindex 21dbec46e40..a2e2052c8de 100644--- a/gateway/run_turn_prepare.py+++ b/gateway/run_turn_prepare.py@@ -636,13 +636,13 @@ class GatewayTurnPrepareMixin:# part of the classic in-process prompt, and the TUI gateway still builds that prompt in-process.# Rendering it here would make every surface hop of one durable session a system-prompt# (and prompt-cache) break.- if source.platform != Platform.LOCAL and event.internal and session_key:+ # Synthetic goal/heartbeat/resume turns carry no prompt inputs of their own, so they reuse the+ # pins exactly like internal events do (and still pass authorization, unlike internal ones).+ _reuse_pins = event.internal or getattr(event, "inherit_channel_pin", False)+ if source.platform != Platform.LOCAL and _reuse_pins and session_key:await self._rehydrate_prompt_pins(session_key, session_entry.session_id)context_prompt = "" if source.platform == Platform.LOCAL else \- self._pinned_session_context_prompt(- context, _redact_pii, session_key,- internal=event.internal or getattr(event, "inherit_channel_pin", False),- )+ self._pinned_session_context_prompt(context, _redact_pii, session_key, internal=_reuse_pins)# Per-turn notes ride the user message via the api_content sidecar, NOT context_prompt# (appending to the ephemeral system prompt forced a full agent rebuild).diff --git a/tests/gateway/test_internal_event_pin_wiring.py b/tests/gateway/test_internal_event_pin_wiring.pyindex c10fc6225c5..d7869fb6fd1 100644--- a/tests/gateway/test_internal_event_pin_wiring.py+++ b/tests/gateway/test_internal_event_pin_wiring.py@@ -391,6 +391,67 @@ async def test_first_internal_event_after_agent_eviction_keeps_effective_prompt(assert eph[0] == eph[1] == eph[2], "wake after eviction re-rendered the session context (A->B->A)"+def _synthetic_turn(runner, source, kind: str) -> MessageEvent:+ """The event each real producer builds: goal continuation / heartbeat via+ ``_synthetic_prompt_event``, ``/goal resume`` via ``_enqueue_goal_turn``."""+ if kind == "goal-resume":+ enqueued: list[MessageEvent] = []+ runner._adapter_and_key_for = lambda _event: (object(), KEY)+ runner._enqueue_fifo = lambda _key, turn, _adapter: enqueued.append(turn)+ command = MessageEvent(text="/goal resume", source=source, channel_prompt="Channel hint.")+ runner._enqueue_goal_turn(command, "[goal] resume", label="resume", kickoff=False)+ return enqueued[0]+ if kind == "heartbeat-rebuilt-route":+ # A watch route rebuilt from a stored origin can lack the chat/user names the human turn+ # rendered; the context pin must still be reused, not re-rendered from it.+ source = _wake_thread_source()+ return runner._synthetic_prompt_event(source, "[goal] continue")++[email protected]("kind", ["goal-continuation", "goal-resume", "heartbeat-rebuilt-route"])+async def test_synthetic_goal_turn_keeps_pins_and_effective_prompt(monkeypatch, kind):+ """Goal continuation, heartbeat due-prompts and ``/goal resume`` are non-internal (they keep+ authorization and the emergency stop) but carry no channel prompt of their own; they must+ reuse the human turn's pins instead of overwriting the channel pin with None (A->B->A)."""+ config = GatewayConfig()+ config.platforms[Platform.DISCORD] = PlatformConfig(+ enabled=True,+ channel_overrides={PARENT_ID: ChannelOverride(system_prompt="Parent persona.")},+ )+ runner = _make_runner(monkeypatch, config)+ calls: list[dict] = []+ _capture(runner, calls)+ human = _human_thread_source()++ await _drive(runner, ((False, human),), channel_prompt="Channel hint.")+ synthetic = _synthetic_turn(runner, human, kind)+ assert not synthetic.internal and synthetic.channel_prompt is None+ await runner._handle_message_with_agent(synthetic, synthetic.source, KEY, 1)+ assert runner._peek_session_state(KEY).conversation.channel_pin[0] == "Channel hint."+ await _drive(runner, ((False, human),), channel_prompt="Channel hint.")++ assert [kw["channel_prompt"] for kw in calls] == ["Channel hint."] * 3+ eph = [_effective_ephemeral(runner, kw) for kw in calls]+ assert "Channel hint." in eph[0] and "Parent persona." in eph[0]+ assert eph[0] == eph[1] == eph[2], "synthetic turn toggled the effective ephemeral prompt"+++async def test_human_turn_without_channel_prompt_still_replaces_the_pin(monkeypatch):+ """Negative control: only synthetic turns inherit. A human turn whose channel prompt was+ removed must still clear it, or a deleted channel prompt would stick forever."""+ runner = _make_runner(monkeypatch)+ calls: list[dict] = []+ _capture(runner, calls)++ await _drive(runner, ((False, _human_thread_source()),), channel_prompt="Channel hint.")+ await _drive(runner, ((False, _human_thread_source()),), channel_prompt=None)++ assert [kw["channel_prompt"] for kw in calls] == ["Channel hint.", None]+ assert runner._peek_session_state(KEY).conversation.channel_pin[0] is None++@pytest.mark.asyncioasync def test_human_first_after_restart_ignores_stale_durable_prompt_pin(monkeypatch):durable = {