From ff44db78a9d7def8a9dc8f913f52402d7974ed76 Mon Sep 17 00:00:00 2001 From: Fengzdadi <453788063@qq.com> Date: Thu, 5 Nov 2026 03:06:02 -0500 Subject: [PATCH 1/4] fix(bub): recall with the inbound message, not Bub's framed prompt Bub's builtin build_prompt prefixes each channel message with its context and the time, which outweighs the user's words in lexical recall. The plugin now takes the recall text from the inbound message in load_state, before that framing, and keeps the model request unchanged. --- e2e/bub/tests/test_bub_recall_query.py | 100 +++++++++++++++--- .../bub/src/powercontext_bub/plugin.py | 22 +++- 2 files changed, 105 insertions(+), 17 deletions(-) diff --git a/e2e/bub/tests/test_bub_recall_query.py b/e2e/bub/tests/test_bub_recall_query.py index 087f987f67..c18afa64c2 100644 --- a/e2e/bub/tests/test_bub_recall_query.py +++ b/e2e/bub/tests/test_bub_recall_query.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Bub recalls with the end of a long prompt, as the hook-based hosts do.""" +"""Bub recalls with what the user sent: the inbound content, or the end of a long prompt.""" from __future__ import annotations @@ -24,6 +24,8 @@ import pytest import republic +from bub.builtin.hook_impl import BuiltinImpl +from bub.channels.message import ChannelMessage from bub.hooks.interception import LLMCallRequest from powercontext_bub import plugin as plugin_module from powercontext_bub.plugin import PowerContextPlugin, PowerContextSettings @@ -57,21 +59,95 @@ async def prepare_context(self, request: Any) -> SimpleNamespace: return SimpleNamespace(content="remembered context", content_bytes=18, status=SimpleNamespace(value="ready")) -@pytest.mark.parametrize("case", FIXTURE["cases"], ids=[case["id"] for case in FIXTURE["cases"]]) -def test_recall_query_keeps_the_end_of_the_prompt(monkeypatch, tmp_path: Path, case: dict[str, Any]) -> None: +def _plugin(monkeypatch, tmp_path: Path) -> PowerContextPlugin: RecordingClient.prepared.clear() settings = PowerContextSettings(base_url="http://127.0.0.1:8000") monkeypatch.setattr(plugin_module, "ensure_config", lambda _: settings) monkeypatch.setattr(plugin_module, "PowerContextClient", RecordingClient) - plugin = PowerContextPlugin(SimpleNamespace(workspace=tmp_path)) - state = plugin.load_state(message=None, session_id="session-1") - request = LLMCallRequest( - run_id="run-1", - model="test-model", - messages=[republic.user(_expand(case["prompt"]))], - ) + return PowerContextPlugin(SimpleNamespace(workspace=tmp_path)) + + +def _prepared_queries(plugin: PowerContextPlugin, state: dict[str, Any], prompt: str) -> list[str]: + request = LLMCallRequest(run_id="run-1", model="test-model", messages=[republic.user(prompt)]) result = asyncio.run(plugin.before_llm_call(request, state)) - assert result is not None - assert [prepared.query for prepared in RecordingClient.prepared] == [_expand(case["query"])] + assert (result is not None) == bool(RecordingClient.prepared) + return [prepared.query for prepared in RecordingClient.prepared] + + +def _recall_queries( + monkeypatch, tmp_path: Path, prompt: str, *, message: ChannelMessage | None = None, session_id: str = "session-1" +) -> list[str]: + plugin = _plugin(monkeypatch, tmp_path) + # Bub's builtin load_state supplies the session id beside the plugin's state. + state = {"session_id": session_id, **plugin.load_state(message=message, session_id=session_id)} + return _prepared_queries(plugin, state, prompt) + + +def _bub_prompt(message: ChannelMessage) -> str: + agent = SimpleNamespace(command_prefix=",") + prompt = asyncio.run( + BuiltinImpl(framework=None).build_prompt(message, message.session_id, {"_runtime_agent": agent}) + ) + assert len(prompt) == 1 + assert isinstance(prompt[0], str) + return prompt[0] + + +@pytest.mark.parametrize("case", FIXTURE["cases"], ids=[case["id"] for case in FIXTURE["cases"]]) +def test_recall_query_keeps_the_end_of_the_prompt(monkeypatch, tmp_path: Path, case: dict[str, Any]) -> None: + assert _recall_queries(monkeypatch, tmp_path, _expand(case["prompt"])) == [_expand(case["query"])] + + +@pytest.mark.parametrize( + "message", + [ + ChannelMessage( + session_id="cli:local", + channel="cli", + chat_id="local", + content="How should we deploy the migrations?", + context={"sender_id": "human"}, + ), + ChannelMessage( + session_id="chat:room-7", + channel="chat", + chat_id="room-7", + content="How should we deploy the migrations?\nKeep the rollout order.", + context={"sender_id": "42", "username": "ada"}, + ), + ChannelMessage( + session_id="cli:local", + channel="cli", + chat_id="local", + content='{"message": "report", "constraint": "database migrations"}', + ), + ], + ids=["cli", "chat-channel", "json-text"], +) +def test_recall_query_is_the_inbound_content_without_the_bub_frame( + monkeypatch, tmp_path: Path, message: ChannelMessage +) -> None: + prompt = _bub_prompt(message) + assert prompt != message.content + + assert _recall_queries(monkeypatch, tmp_path, prompt, message=message, session_id=message.session_id) == [ + message.content + ] + + +def test_recall_skips_a_message_without_text(monkeypatch, tmp_path: Path) -> None: + message = ChannelMessage(session_id="cli:local", channel="cli", chat_id="local", content="") + + assert _recall_queries(monkeypatch, tmp_path, _bub_prompt(message), message=message, session_id="cli:local") == [] + + +def test_subagent_recalls_with_its_own_prompt(monkeypatch, tmp_path: Path) -> None: + message = ChannelMessage(session_id="cli:local", channel="cli", chat_id="local", content="Plan the release.") + plugin = _plugin(monkeypatch, tmp_path) + parent_state = {"session_id": "cli:local", **plugin.load_state(message=message, session_id="cli:local")} + # Bub runs a subagent with a copy of the parent's turn state under the subagent's own session. + subagent_state = {**parent_state, "session_id": "cli:local/subagent-1"} + + assert _prepared_queries(plugin, subagent_state, "Check the migration order.") == ["Check the migration order."] diff --git a/integrations/bub/src/powercontext_bub/plugin.py b/integrations/bub/src/powercontext_bub/plugin.py index 1b4dd34b3e..54fc729945 100644 --- a/integrations/bub/src/powercontext_bub/plugin.py +++ b/integrations/bub/src/powercontext_bub/plugin.py @@ -29,6 +29,7 @@ import httpx import republic from bub import Settings, config, ensure_config, hookimpl +from bub.envelope import field_of from bub.hooks.interception import LLMCallRequest, LLMCallResult, ToolCall, ToolCallResult from bub.turn import TurnState from pydantic import Field, HttpUrl, SecretStr, field_validator @@ -145,7 +146,9 @@ def __init__(self, framework: Any) -> None: @hookimpl def load_state(self, message: Any, session_id: str) -> TurnState: - del message, session_id + # Bub's prompt builder frames the content with channel metadata and the time, which would outweigh the user's + # words in lexical recall, so recall reads the inbound content before that framing. + content = field_of(message, "content") workspace_key = workspace_binding_key(getattr(self._framework, "workspace", None)) binding_keys = [workspace_key] if workspace_key is not None else [] return { @@ -165,6 +168,8 @@ def load_state(self, message: Any, session_id: str) -> TurnState: "captured_position": 0, "flushed_position": 0, "prompt_captured": False, + "recall_session_id": session_id, + "recall_text": content.strip() if isinstance(content, str) else None, } } @@ -175,8 +180,8 @@ def system_prompt(self, prompt: str | list[dict[str, Any]], state: TurnState) -> @hookimpl async def before_llm_call(self, request: LLMCallRequest, state: TurnState) -> LLMCallRequest | None: - query = _latest_user_text(request.messages) - if not query: + prompt = _latest_user_text(request.messages) + if not prompt: return None scope_id = await self._scope_id(state) @@ -184,18 +189,25 @@ async def before_llm_call(self, request: LLMCallRequest, state: TurnState) -> LL return None capture_state = state[STATE_KEY] - if self.settings.capture_events and query and not capture_state["prompt_captured"]: + if self.settings.capture_events and not capture_state["prompt_captured"]: capture_state["prompt_captured"] = True await self._capture_event( event="user_prompt", run_id=request.run_id, - payload={"text": query}, + payload={"text": prompt}, state=state, ) if any(_contains_context_marker(message) for message in request.messages): return None + query = prompt + # Subagents run with a copy of this state under their own session and recall with their own prompt. + if capture_state["recall_session_id"] == state.get("session_id") and capture_state["recall_text"] is not None: + query = capture_state["recall_text"] + if not query: + return None + prepared_content = await self._prepare_context(query, scope_id, state) if not prepared_content: return None From af111fdded3017d07a10bcd0abab333a400a9b56 Mon Sep 17 00:00:00 2001 From: Fengzdadi <453788063@qq.com> Date: Wed, 11 Nov 2026 15:24:53 -0500 Subject: [PATCH 2/4] fix(bub): map each built prompt to its inbound text for recall Bub drains steered follow-ups into a running turn through build_prompt without load_state, so the per-turn recall text went stale. The plugin now implements build_prompt at tryfirst priority, delegates to the other implementations in Bub's resolution order, and records the inbound text (ChannelMessage.text when set, else content) for each built prompt. before_llm_call recalls with the text of the latest user message. --- e2e/bub/tests/test_bub_recall_query.py | 183 ++++++++++++------ .../bub/src/powercontext_bub/plugin.py | 43 +++- 2 files changed, 161 insertions(+), 65 deletions(-) diff --git a/e2e/bub/tests/test_bub_recall_query.py b/e2e/bub/tests/test_bub_recall_query.py index c18afa64c2..670bd69a36 100644 --- a/e2e/bub/tests/test_bub_recall_query.py +++ b/e2e/bub/tests/test_bub_recall_query.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Bub recalls with what the user sent: the inbound content, or the end of a long prompt.""" +"""Bub recalls with what the user sent: each inbound message's text, or the end of a long prompt.""" from __future__ import annotations @@ -22,16 +22,19 @@ from types import SimpleNamespace from typing import Any, ClassVar +import httpx2 import pytest import republic -from bub.builtin.hook_impl import BuiltinImpl from bub.channels.message import ChannelMessage -from bub.hooks.interception import LLMCallRequest +from bub.framework import BubFramework +from bub.hooks import hookimpl +from bub.hooks.interception import LLMCallRequest, LLMCallResult from powercontext_bub import plugin as plugin_module from powercontext_bub.plugin import PowerContextPlugin, PowerContextSettings _ROOT = Path(__file__).resolve().parents[3] FIXTURE = json.loads((_ROOT / "tests/fixtures/recall_query_bound.json").read_text(encoding="utf-8")) +QUESTION = "How should we deploy the migrations?" def _expand(segments: list[dict[str, Any]]) -> str: @@ -59,95 +62,165 @@ async def prepare_context(self, request: Any) -> SimpleNamespace: return SimpleNamespace(content="remembered context", content_bytes=18, status=SimpleNamespace(value="ready")) -def _plugin(monkeypatch, tmp_path: Path) -> PowerContextPlugin: +def _cli_message(content: str, **fields: Any) -> ChannelMessage: + return ChannelMessage( + session_id="cli:local", + channel="cli", + chat_id="local", + content=content, + context={"sender_id": "human"}, + **fields, + ) + + +@pytest.fixture +def framework(monkeypatch, tmp_path: Path) -> BubFramework: + """Bub's builtin hooks with the PowerContext plugin registered after them, as Bub loads it.""" RecordingClient.prepared.clear() settings = PowerContextSettings(base_url="http://127.0.0.1:8000") monkeypatch.setattr(plugin_module, "ensure_config", lambda _: settings) monkeypatch.setattr(plugin_module, "PowerContextClient", RecordingClient) - return PowerContextPlugin(SimpleNamespace(workspace=tmp_path)) + monkeypatch.chdir(tmp_path) + framework = BubFramework(config_file=tmp_path / "bub.yml") + framework.load_builtin_hooks() + framework.plugin_manager.register(PowerContextPlugin(framework), name="powercontext") + return framework -def _prepared_queries(plugin: PowerContextPlugin, state: dict[str, Any], prompt: str) -> list[str]: - request = LLMCallRequest(run_id="run-1", model="test-model", messages=[republic.user(prompt)]) +def _plugin(framework: BubFramework) -> PowerContextPlugin: + plugin = framework.plugin_manager.get_plugin("powercontext") + assert isinstance(plugin, PowerContextPlugin) + return plugin - result = asyncio.run(plugin.before_llm_call(request, state)) - assert (result is not None) == bool(RecordingClient.prepared) - return [prepared.query for prepared in RecordingClient.prepared] +def _turn_state(framework: BubFramework, session_id: str) -> dict[str, Any]: + # The builtin load_state binds the session and its agent; this keeps the turn to the plugin's state. + state = {"session_id": session_id, **_plugin(framework).load_state(message={}, session_id=session_id)} + return {**state, "_runtime_agent": SimpleNamespace(command_prefix=",")} -def _recall_queries( - monkeypatch, tmp_path: Path, prompt: str, *, message: ChannelMessage | None = None, session_id: str = "session-1" -) -> list[str]: - plugin = _plugin(monkeypatch, tmp_path) - # Bub's builtin load_state supplies the session id beside the plugin's state. - state = {"session_id": session_id, **plugin.load_state(message=message, session_id=session_id)} - return _prepared_queries(plugin, state, prompt) +def _prepared_queries(framework: BubFramework, state: dict[str, Any], prompt: list[Any]) -> list[str]: + request = LLMCallRequest(run_id="run-1", model="test-model", messages=[republic.user(*prompt)]) + result = asyncio.run(_plugin(framework).before_llm_call(request, state)) -def _bub_prompt(message: ChannelMessage) -> str: - agent = SimpleNamespace(command_prefix=",") - prompt = asyncio.run( - BuiltinImpl(framework=None).build_prompt(message, message.session_id, {"_runtime_agent": agent}) - ) - assert len(prompt) == 1 - assert isinstance(prompt[0], str) - return prompt[0] + assert (result is not None) == bool(RecordingClient.prepared) + return [prepared.query for prepared in RecordingClient.prepared] + + +def _recall_queries(framework: BubFramework, message: Any) -> list[str]: + session_id = str(message.session_id) if isinstance(message, ChannelMessage) else "cli:local" + state = _turn_state(framework, session_id) + prompt = asyncio.run(framework.build_prompt(message, session_id, state)) + return _prepared_queries(framework, state, prompt) @pytest.mark.parametrize("case", FIXTURE["cases"], ids=[case["id"] for case in FIXTURE["cases"]]) -def test_recall_query_keeps_the_end_of_the_prompt(monkeypatch, tmp_path: Path, case: dict[str, Any]) -> None: - assert _recall_queries(monkeypatch, tmp_path, _expand(case["prompt"])) == [_expand(case["query"])] +def test_recall_query_keeps_the_end_of_the_prompt(framework: BubFramework, case: dict[str, Any]) -> None: + state = _turn_state(framework, "cli:local") + + assert _prepared_queries(framework, state, [_expand(case["prompt"])]) == [_expand(case["query"])] @pytest.mark.parametrize( "message", [ - ChannelMessage( - session_id="cli:local", - channel="cli", - chat_id="local", - content="How should we deploy the migrations?", - context={"sender_id": "human"}, - ), + _cli_message(QUESTION), ChannelMessage( session_id="chat:room-7", channel="chat", chat_id="room-7", - content="How should we deploy the migrations?\nKeep the rollout order.", + content=f"{QUESTION}\nKeep the rollout order.", context={"sender_id": "42", "username": "ada"}, ), - ChannelMessage( - session_id="cli:local", - channel="cli", - chat_id="local", - content='{"message": "report", "constraint": "database migrations"}', - ), + _cli_message('{"message": "report", "constraint": "database migrations"}'), ], ids=["cli", "chat-channel", "json-text"], ) def test_recall_query_is_the_inbound_content_without_the_bub_frame( - monkeypatch, tmp_path: Path, message: ChannelMessage + framework: BubFramework, message: ChannelMessage ) -> None: - prompt = _bub_prompt(message) - assert prompt != message.content + assert _recall_queries(framework, message) == [message.content] - assert _recall_queries(monkeypatch, tmp_path, prompt, message=message, session_id=message.session_id) == [ - message.content - ] +def test_recall_query_is_the_sender_text_when_the_content_wraps_it(framework: BubFramework) -> None: + # Bub's Telegram channel wraps the sender's words in JSON with message metadata and keeps them as ``text``. + message = { + "session_id": "telegram:42", + "channel": "telegram", + "chat_id": "42", + "content": json.dumps({"message": QUESTION, "message_id": 7, "username": "ada"}), + "text": QUESTION, + } -def test_recall_skips_a_message_without_text(monkeypatch, tmp_path: Path) -> None: - message = ChannelMessage(session_id="cli:local", channel="cli", chat_id="local", content="") + assert _recall_queries(framework, message) == [QUESTION] - assert _recall_queries(monkeypatch, tmp_path, _bub_prompt(message), message=message, session_id="cli:local") == [] +def test_recall_skips_a_message_without_text(framework: BubFramework) -> None: + assert _recall_queries(framework, _cli_message("")) == [] -def test_subagent_recalls_with_its_own_prompt(monkeypatch, tmp_path: Path) -> None: - message = ChannelMessage(session_id="cli:local", channel="cli", chat_id="local", content="Plan the release.") - plugin = _plugin(monkeypatch, tmp_path) - parent_state = {"session_id": "cli:local", **plugin.load_state(message=message, session_id="cli:local")} + +def test_recall_maps_a_prompt_another_plugin_builds(framework: BubFramework) -> None: + class SummaryPrompt: + @hookimpl + async def build_prompt(self, message: Any) -> str: + return f"Summarize for the on-call engineer:\n{message.content}" + + framework.plugin_manager.register(SummaryPrompt(), name="summary") + + assert _recall_queries(framework, _cli_message(QUESTION)) == [QUESTION] + + +def test_subagent_recalls_with_its_own_prompt(framework: BubFramework) -> None: + parent_state = _turn_state(framework, "cli:local") + asyncio.run(framework.build_prompt(_cli_message("Plan the release."), "cli:local", parent_state)) # Bub runs a subagent with a copy of the parent's turn state under the subagent's own session. subagent_state = {**parent_state, "session_id": "cli:local/subagent-1"} - assert _prepared_queries(plugin, subagent_state, "Check the migration order.") == ["Check the migration order."] + assert _prepared_queries(framework, subagent_state, ["Check the migration order."]) == [ + "Check the migration order." + ] + + +def test_steered_follow_up_recalls_with_its_own_text(monkeypatch, tmp_path: Path, framework: BubFramework) -> None: + follow_up = "What is the support escalation policy?" + + class SteerOnce: + steered = False + + @hookimpl + async def after_llm_call(self, request: LLMCallRequest, result: LLMCallResult, state: dict[str, Any]) -> None: + del request, result + if not self.steered: + self.steered = True + await framework.steer_message(message=_cli_message(follow_up), session_id="cli:local", state=state) + + replies = ["one", "two"] + + def model_reply(request: httpx2.Request) -> httpx2.Response: + del request + events = [{"choices": [{"delta": {"content": replies.pop(0)}, "finish_reason": "stop"}]}, "[DONE]"] + body = "".join(f"data: {event if isinstance(event, str) else json.dumps(event)}\n\n" for event in events) + return httpx2.Response(200, headers={"content-type": "text/event-stream"}, text=body) + + client = httpx2.AsyncClient + monkeypatch.setattr( + httpx2, "AsyncClient", lambda **options: client(**{"transport": httpx2.MockTransport(model_reply), **options}) + ) + for name, value in { + "BUB_HOME": str(tmp_path / "home"), + "BUB_MODEL": "openai:test-model", + "BUB_API_KEY": "test", + "BUB_CLIENT_ARGS": '{"api_format": "chat"}', + }.items(): + monkeypatch.setenv(name, value) + framework.plugin_manager.register(SteerOnce(), name="steer-once") + + async def run_turn() -> None: + async with framework.running(): + await framework.process_inbound(_cli_message(QUESTION)) + + asyncio.run(run_turn()) + + assert replies == [] + assert [prepared.query for prepared in RecordingClient.prepared] == [QUESTION, follow_up] diff --git a/integrations/bub/src/powercontext_bub/plugin.py b/integrations/bub/src/powercontext_bub/plugin.py index 54fc729945..27cc59bed5 100644 --- a/integrations/bub/src/powercontext_bub/plugin.py +++ b/integrations/bub/src/powercontext_bub/plugin.py @@ -18,6 +18,7 @@ import asyncio import hashlib +import inspect import json from collections.abc import AsyncIterator from contextlib import AbstractAsyncContextManager, asynccontextmanager @@ -29,8 +30,9 @@ import httpx import republic from bub import Settings, config, ensure_config, hookimpl -from bub.envelope import field_of +from bub.envelope import content_of, field_of from bub.hooks.interception import LLMCallRequest, LLMCallResult, ToolCall, ToolCallResult +from bub.prompt import UserContent, to_content from bub.turn import TurnState from pydantic import Field, HttpUrl, SecretStr, field_validator from pydantic_settings import SettingsConfigDict @@ -146,9 +148,7 @@ def __init__(self, framework: Any) -> None: @hookimpl def load_state(self, message: Any, session_id: str) -> TurnState: - # Bub's prompt builder frames the content with channel metadata and the time, which would outweigh the user's - # words in lexical recall, so recall reads the inbound content before that framing. - content = field_of(message, "content") + del message, session_id workspace_key = workspace_binding_key(getattr(self._framework, "workspace", None)) binding_keys = [workspace_key] if workspace_key is not None else [] return { @@ -168,11 +168,36 @@ def load_state(self, message: Any, session_id: str) -> TurnState: "captured_position": 0, "flushed_position": 0, "prompt_captured": False, - "recall_session_id": session_id, - "recall_text": content.strip() if isinstance(content, str) else None, + "recall_texts": {}, } } + @hookimpl(tryfirst=True) + async def build_prompt(self, message: Any, session_id: str, state: TurnState) -> list[UserContent]: + # Bub frames each inbound message with channel metadata and the time, which would outweigh the user's words in + # lexical recall. Building the prompt here, ahead of the other implementations, ties every model-facing user + # message, steered follow-ups included, to the text the user sent. + prompt = to_content(await self._build_prompt_without_self(message, session_id, state) or content_of(message)) + # ``text`` is what the sender wrote when ``content`` wraps it with channel metadata (Bub after 0.6.1). + recall_text = field_of(message, "text") or field_of(message, "content") + capture_state = state.get(STATE_KEY) + if isinstance(capture_state, dict) and isinstance(recall_text, str): + capture_state["recall_texts"][republic.user(*prompt).text.strip()] = recall_text.strip() + return prompt + + async def _build_prompt_without_self(self, message: Any, session_id: str, state: TurnState) -> Any: + # Resolve like Bub's own call: in precedence order, awaiting each implementation until one returns a result. + # Calling the subset caller instead would apply pluggy's synchronous first-result rule to coroutines. + others = self._framework.plugin_manager.subset_hook_caller("build_prompt", remove_plugins=[self]) + kwargs = {"message": message, "session_id": session_id, "state": state} + for impl in reversed(others.get_hookimpls()): + result = impl.function(**{name: kwargs[name] for name in impl.argnames if name in kwargs}) + if inspect.isawaitable(result): + result = await result + if result is not None: + return result + return None + @hookimpl def system_prompt(self, prompt: str | list[dict[str, Any]], state: TurnState) -> str: del prompt, state @@ -201,10 +226,8 @@ async def before_llm_call(self, request: LLMCallRequest, state: TurnState) -> LL if any(_contains_context_marker(message) for message in request.messages): return None - query = prompt - # Subagents run with a copy of this state under their own session and recall with their own prompt. - if capture_state["recall_session_id"] == state.get("session_id") and capture_state["recall_text"] is not None: - query = capture_state["recall_text"] + # A prompt Bub did not build from an inbound message, such as a subagent's, is recalled as the model sees it. + query = capture_state["recall_texts"].get(prompt, prompt) if not query: return None From 80eb5941db5fd1127998b1aff01258d8933891ff Mon Sep 17 00:00:00 2001 From: Fengzdadi <453788063@qq.com> Date: Wed, 11 Nov 2026 15:31:08 -0500 Subject: [PATCH 3/4] fix(bub): match multi-part prompts and guard delegated build_prompt The turn's message reaches the model through Bub's legacy prompt form, which joins text parts with newlines, so record the recall text under that form too. A plugin delegating build_prompt the same way would call back into this one without end; return None when re-entered so the delegation continues with the remaining implementations. --- e2e/bub/tests/test_bub_recall_query.py | 75 +++++++++++++++---- .../bub/src/powercontext_bub/plugin.py | 21 +++++- 2 files changed, 76 insertions(+), 20 deletions(-) diff --git a/e2e/bub/tests/test_bub_recall_query.py b/e2e/bub/tests/test_bub_recall_query.py index 670bd69a36..f23f72656f 100644 --- a/e2e/bub/tests/test_bub_recall_query.py +++ b/e2e/bub/tests/test_bub_recall_query.py @@ -17,6 +17,7 @@ from __future__ import annotations import asyncio +import inspect import json from pathlib import Path from types import SimpleNamespace @@ -182,19 +183,29 @@ def test_subagent_recalls_with_its_own_prompt(framework: BubFramework) -> None: ] -def test_steered_follow_up_recalls_with_its_own_text(monkeypatch, tmp_path: Path, framework: BubFramework) -> None: - follow_up = "What is the support escalation policy?" +def test_recall_maps_back_when_another_plugin_delegates_the_same_way(framework: BubFramework) -> None: + class DelegatingObserver: + @hookimpl(tryfirst=True) + async def build_prompt(self, message: Any, session_id: str, state: dict[str, Any]) -> Any: + # The delegation bubbuild/bub#400 suggested, without a guard against being called back. + kwargs = {"message": message, "session_id": session_id, "state": state} + others = framework.plugin_manager.subset_hook_caller("build_prompt", remove_plugins=[self]) + for impl in reversed(others.get_hookimpls()): + result = impl.function(**{name: kwargs[name] for name in impl.argnames}) + if inspect.isawaitable(result): + result = await result + if result is not None: + return result + return None - class SteerOnce: - steered = False + framework.plugin_manager.register(DelegatingObserver(), name="delegating-observer") + + assert _recall_queries(framework, _cli_message(QUESTION)) == [QUESTION] - @hookimpl - async def after_llm_call(self, request: LLMCallRequest, result: LLMCallResult, state: dict[str, Any]) -> None: - del request, result - if not self.steered: - self.steered = True - await framework.steer_message(message=_cli_message(follow_up), session_id="cli:local", state=state) +@pytest.fixture +def run_turn(monkeypatch, tmp_path: Path, framework: BubFramework): + """Run one message through ``process_inbound`` with Bub's own agent loop and a stub model that answers twice.""" replies = ["one", "two"] def model_reply(request: httpx2.Request) -> httpx2.Response: @@ -214,13 +225,45 @@ def model_reply(request: httpx2.Request) -> httpx2.Response: "BUB_CLIENT_ARGS": '{"api_format": "chat"}', }.items(): monkeypatch.setenv(name, value) - framework.plugin_manager.register(SteerOnce(), name="steer-once") - async def run_turn() -> None: - async with framework.running(): - await framework.process_inbound(_cli_message(QUESTION)) + def run(message: ChannelMessage) -> None: + async def turn() -> None: + async with framework.running(): + await framework.process_inbound(message) + + asyncio.run(turn()) + + return run + + +def test_turn_recall_maps_a_prompt_built_from_several_text_parts(framework: BubFramework, run_turn) -> None: + class BriefingPrompt: + @hookimpl + def build_prompt(self, message: Any) -> list[str]: + return ["Brief the on-call engineer.", message.content] + + framework.plugin_manager.register(BriefingPrompt(), name="briefing") + + run_turn(_cli_message(QUESTION)) + + assert [prepared.query for prepared in RecordingClient.prepared] == [QUESTION] + + +def test_steered_follow_up_recalls_with_its_own_text(framework: BubFramework, run_turn) -> None: + follow_up = "What is the support escalation policy?" + + class SteerOnce: + steered = False + + @hookimpl + async def after_llm_call(self, request: LLMCallRequest, result: LLMCallResult, state: dict[str, Any]) -> None: + del request, result + if not self.steered: + self.steered = True + await framework.steer_message(message=_cli_message(follow_up), session_id="cli:local", state=state) + + framework.plugin_manager.register(SteerOnce(), name="steer-once") - asyncio.run(run_turn()) + run_turn(_cli_message(QUESTION)) - assert replies == [] assert [prepared.query for prepared in RecordingClient.prepared] == [QUESTION, follow_up] diff --git a/integrations/bub/src/powercontext_bub/plugin.py b/integrations/bub/src/powercontext_bub/plugin.py index 27cc59bed5..9b6b0e5eb0 100644 --- a/integrations/bub/src/powercontext_bub/plugin.py +++ b/integrations/bub/src/powercontext_bub/plugin.py @@ -22,6 +22,7 @@ import json from collections.abc import AsyncIterator from contextlib import AbstractAsyncContextManager, asynccontextmanager +from contextvars import ContextVar from dataclasses import replace from datetime import UTC, datetime from pathlib import Path @@ -32,7 +33,7 @@ from bub import Settings, config, ensure_config, hookimpl from bub.envelope import content_of, field_of from bub.hooks.interception import LLMCallRequest, LLMCallResult, ToolCall, ToolCallResult -from bub.prompt import UserContent, to_content +from bub.prompt import UserContent, prompt_text, to_content from bub.turn import TurnState from pydantic import Field, HttpUrl, SecretStr, field_validator from pydantic_settings import SettingsConfigDict @@ -57,6 +58,7 @@ # shared with the hook-based hosts, so a recall also fits a server that measures bytes. MAX_QUERY_CHARACTERS = 8192 MAX_QUERY_BYTES = 8192 +_BUILDING_PROMPT: ContextVar[bool] = ContextVar("powercontext_bub_building_prompt", default=False) GUIDANCE = """\ PowerContext provides durable project memory shared across agent sessions. Relevant host-supplied context is injected automatically before each model call. @@ -173,16 +175,27 @@ def load_state(self, message: Any, session_id: str) -> TurnState: } @hookimpl(tryfirst=True) - async def build_prompt(self, message: Any, session_id: str, state: TurnState) -> list[UserContent]: + async def build_prompt(self, message: Any, session_id: str, state: TurnState) -> list[UserContent] | None: # Bub frames each inbound message with channel metadata and the time, which would outweigh the user's words in # lexical recall. Building the prompt here, ahead of the other implementations, ties every model-facing user # message, steered follow-ups included, to the text the user sent. - prompt = to_content(await self._build_prompt_without_self(message, session_id, state) or content_of(message)) + if _BUILDING_PROMPT.get(): + # Another plugin delegating the same way called back in; let it continue with the rest. + return None + token = _BUILDING_PROMPT.set(True) + try: + built = await self._build_prompt_without_self(message, session_id, state) + finally: + _BUILDING_PROMPT.reset(token) + prompt = to_content(built or content_of(message)) # ``text`` is what the sender wrote when ``content`` wraps it with channel metadata (Bub after 0.6.1). recall_text = field_of(message, "text") or field_of(message, "content") capture_state = state.get(STATE_KEY) if isinstance(capture_state, dict) and isinstance(recall_text, str): - capture_state["recall_texts"][republic.user(*prompt).text.strip()] = recall_text.strip() + # A steered message reaches the model with its text parts joined as built; the turn's message passes + # through Bub's legacy prompt form, which joins them with newlines. + for key in {republic.user(*prompt).text.strip(), prompt_text(prompt).strip()}: + capture_state["recall_texts"][key] = recall_text.strip() return prompt async def _build_prompt_without_self(self, message: Any, session_id: str, state: TurnState) -> Any: From 3a28a015e316113a673902f35eb8015c8adc6fd4 Mon Sep 17 00:00:00 2001 From: Fengzdadi <453788063@qq.com> Date: Thu, 12 Nov 2026 17:36:57 -0500 Subject: [PATCH 4/4] fix(bub): skip recall for an explicitly empty sender text Bub sets `text` to None when `content` is what the sender wrote (bubbuild/bub#399). Fall back to `content` only then, so an empty `text` skips recall instead of recalling the JSON envelope with its metadata and replied-to message. --- e2e/bub/tests/test_bub_recall_query.py | 33 ++++++++++++++++++- .../bub/src/powercontext_bub/plugin.py | 7 ++-- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/e2e/bub/tests/test_bub_recall_query.py b/e2e/bub/tests/test_bub_recall_query.py index f23f72656f..18c492b223 100644 --- a/e2e/bub/tests/test_bub_recall_query.py +++ b/e2e/bub/tests/test_bub_recall_query.py @@ -36,6 +36,10 @@ _ROOT = Path(__file__).resolve().parents[3] FIXTURE = json.loads((_ROOT / "tests/fixtures/recall_query_bound.json").read_text(encoding="utf-8")) QUESTION = "How should we deploy the migrations?" +REPLY_ENVELOPE = json.dumps({ + "message": "", + "reply_to_message": {"text": "The support escalation policy sends urgent incidents to the incident commander."}, +}) def _expand(segments: list[dict[str, Any]]) -> str: @@ -157,6 +161,21 @@ def test_recall_query_is_the_sender_text_when_the_content_wraps_it(framework: Bu assert _recall_queries(framework, message) == [QUESTION] +@pytest.mark.parametrize( + ("sender_text", "queries"), + [({"text": ""}, []), ({"text": " "}, []), ({"text": None}, [REPLY_ENVELOPE]), ({}, [REPLY_ENVELOPE])], + ids=["empty", "blank", "none", "absent"], +) +def test_recall_falls_back_to_the_content_only_without_a_sender_text( + framework: BubFramework, sender_text: dict[str, Any], queries: list[str] +) -> None: + # An empty ``text`` is still what the sender wrote; recalling the envelope would match the replied-to message. + # Without ``text``, the content is the sender's own words, even when it is JSON. + message = {"session_id": "telegram:42", "channel": "telegram", "chat_id": "42", "content": REPLY_ENVELOPE} + + assert _recall_queries(framework, {**message, **sender_text}) == queries + + def test_recall_skips_a_message_without_text(framework: BubFramework) -> None: assert _recall_queries(framework, _cli_message("")) == [] @@ -226,7 +245,7 @@ def model_reply(request: httpx2.Request) -> httpx2.Response: }.items(): monkeypatch.setenv(name, value) - def run(message: ChannelMessage) -> None: + def run(message: Any) -> None: async def turn() -> None: async with framework.running(): await framework.process_inbound(message) @@ -249,6 +268,18 @@ def build_prompt(self, message: Any) -> list[str]: assert [prepared.query for prepared in RecordingClient.prepared] == [QUESTION] +def test_turn_with_an_empty_sender_text_skips_recall(run_turn) -> None: + run_turn({ + "session_id": "telegram:42", + "channel": "telegram", + "chat_id": "42", + "content": REPLY_ENVELOPE, + "text": "", + }) + + assert RecordingClient.prepared == [] + + def test_steered_follow_up_recalls_with_its_own_text(framework: BubFramework, run_turn) -> None: follow_up = "What is the support escalation policy?" diff --git a/integrations/bub/src/powercontext_bub/plugin.py b/integrations/bub/src/powercontext_bub/plugin.py index 9b6b0e5eb0..bb914fe090 100644 --- a/integrations/bub/src/powercontext_bub/plugin.py +++ b/integrations/bub/src/powercontext_bub/plugin.py @@ -188,8 +188,11 @@ async def build_prompt(self, message: Any, session_id: str, state: TurnState) -> finally: _BUILDING_PROMPT.reset(token) prompt = to_content(built or content_of(message)) - # ``text`` is what the sender wrote when ``content`` wraps it with channel metadata (Bub after 0.6.1). - recall_text = field_of(message, "text") or field_of(message, "content") + # ``text`` is what the sender wrote when ``content`` wraps it with channel metadata (Bub after 0.6.1); only an + # absent or None ``text`` means ``content`` is that text. An empty ``text`` recalls nothing rather than the + # replied-to message and metadata in the envelope. + text = field_of(message, "text") + recall_text = field_of(message, "content") if text is None else text capture_state = state.get(STATE_KEY) if isinstance(capture_state, dict) and isinstance(recall_text, str): # A steered message reaches the model with its text parts joined as built; the turn's message passes