From 63f67efb4697ed2796d1bfa334b156e1fd1e7596 Mon Sep 17 00:00:00 2001 From: ahmad-ajmal Date: Mon, 2 Nov 2026 16:59:35 +0000 Subject: [PATCH] fix: preserve MCP results and tighten prompt construction --- agent_core/core/impl/action/manager.py | 13 +- .../core/impl/event_stream/event_stream.py | 14 +- agent_core/core/impl/event_stream/manager.py | 12 +- agent_core/core/impl/mcp/server.py | 14 +- agent_core/core/prompts/reasoning.py | 45 +++-- agent_core/core/protocols/event_stream.py | 9 +- app/subagent/context_engine.py | 18 +- app/subagent/manager.py | 2 +- app/subagent/types.py | 5 + tests/test_prompt_result_fidelity.py | 189 ++++++++++++++++++ tests/test_subagent_bootstrap_prompt.py | 123 ++++++++++++ 11 files changed, 405 insertions(+), 39 deletions(-) create mode 100644 tests/test_prompt_result_fidelity.py create mode 100644 tests/test_subagent_bootstrap_prompt.py diff --git a/agent_core/core/impl/action/manager.py b/agent_core/core/impl/action/manager.py index aca5d542c..58b19e26b 100644 --- a/agent_core/core/impl/action/manager.py +++ b/agent_core/core/impl/action/manager.py @@ -132,10 +132,11 @@ async def _compat_wait_for(fut, timeout): # ============================================================================ -def _to_pretty_json(value: Any) -> str: - """Serialize a value to pretty-printed JSON for readable logs and event streams.""" +def _to_json(value: Any, *, compact: bool = False) -> str: + """Serialize event data; compact new results without changing string contents.""" try: - return json.dumps(value, indent=2, ensure_ascii=False, default=str) + layout = {"separators": (",", ":")} if compact else {"indent": 2} + return json.dumps(value, ensure_ascii=False, default=str, **layout) except (TypeError, ValueError): return str(value) @@ -354,7 +355,7 @@ async def execute_action( # Log to event stream # Only pass session_id when is_running_task=True (task stream exists) # When no task exists, use global stream by not passing task_id - pretty_input = _to_pretty_json(input_data) + pretty_input = _to_json(input_data) self._log_event_stream( is_gui_task=is_gui_task, event_kind="action_start", @@ -478,12 +479,12 @@ async def execute_action( display_status = ( "failed" if (status == "error" or output_has_error) else "completed" ) - pretty_output = _to_pretty_json(outputs) + rendered_output = _to_json(outputs, compact=True) self._log_event_stream( is_gui_task=is_gui_task, event_kind="action_end", event_type=EventType.ACTION_END, - event=f"Action {action.name} completed with output: {pretty_output}.", + event=f"Action {action.name} completed with output: {rendered_output}.", display_message=f"{action.display_name} → {display_status}", action_name=action.name, action_display_name=action.display_name, diff --git a/agent_core/core/impl/event_stream/event_stream.py b/agent_core/core/impl/event_stream/event_stream.py index 62a617f2a..e95297346 100644 --- a/agent_core/core/impl/event_stream/event_stream.py +++ b/agent_core/core/impl/event_stream/event_stream.py @@ -905,7 +905,11 @@ def _extract_keywords(message: str, top_n: int = 5) -> List[str]: # ───────────────────────── prompt accessors ────────────────────────── def to_prompt_snapshot( - self, include_summary: bool = True, up_to: Optional[int] = None + self, + include_summary: bool = True, + up_to: Optional[int] = None, + *, + message_overrides: Optional[Dict[Tuple[str, str], str]] = None, ) -> str: """ Build a compact, human-readable history for inclusion in LLM prompts. @@ -919,6 +923,8 @@ def to_prompt_snapshot( include_summary: Whether to prepend the rolled-up ``head_summary``. up_to: Only the first ``up_to`` tail events (the events a request carries, see get_event_count); None for all of them. + message_overrides: Render-only substitutions keyed by exact event + kind and message. Stored events and cached messages are untouched. Returns: A newline-delimited string ready to embed in an LLM request. @@ -931,7 +937,11 @@ def to_prompt_snapshot( recent = self.tail_events[:up_to] if recent: lines.append("Recent Event: ") - lines.extend(r.compact_line() for r in recent) + overrides = message_overrides or {} + lines.extend( + r.compact_line(overrides.get((r.event.kind, r.event.message))) + for r in recent + ) return "\n".join(lines) if lines else "(no events)" diff --git a/agent_core/core/impl/event_stream/manager.py b/agent_core/core/impl/event_stream/manager.py index f47dac2ad..daf7d8737 100644 --- a/agent_core/core/impl/event_stream/manager.py +++ b/agent_core/core/impl/event_stream/manager.py @@ -17,7 +17,7 @@ from __future__ import annotations from datetime import datetime from pathlib import Path -from typing import Callable, Dict, List, Optional +from typing import Callable, Dict, List, Optional, Tuple import threading from agent_core.core.impl.event_stream.event_stream import EventStream @@ -183,10 +183,16 @@ def snapshot_main(self, include_summary: bool = True) -> str: include_summary=include_summary ) - def snapshot_by_id(self, session_id: str, include_summary: bool = True) -> str: + def snapshot_by_id( + self, + session_id: str, + include_summary: bool = True, + *, + message_overrides: Optional[Dict[Tuple[str, str], str]] = None, + ) -> str: """Snapshot a specific session's stream.""" return self.get_stream_by_id(session_id).to_prompt_snapshot( - include_summary=include_summary + include_summary=include_summary, message_overrides=message_overrides ) def get_all_streams(self) -> list[EventStream]: diff --git a/agent_core/core/impl/mcp/server.py b/agent_core/core/impl/mcp/server.py index ba4d564b3..a35e4a7a3 100644 --- a/agent_core/core/impl/mcp/server.py +++ b/agent_core/core/impl/mcp/server.py @@ -943,6 +943,14 @@ async def call_tool( } result = response.get("result", {}) + status = "error" if result.get("isError") is True else "success" + # Presence matters: null, false, zero and empty structured values + # are still evidence. Keep the existing result/raw_content shape. + metadata = { + key: result[key] + for key in ("isError", "structuredContent", "_meta") + if key in result + } # Extract content from MCP result format content = result.get("content", []) @@ -954,14 +962,16 @@ async def call_tool( text_parts.append(item.get("text", "")) return { - "status": "success", + "status": status, "result": "\n".join(text_parts) if text_parts else result, "raw_content": content, + **metadata, } return { - "status": "success", + "status": status, "result": result, + **metadata, } except Exception as e: diff --git a/agent_core/core/prompts/reasoning.py b/agent_core/core/prompts/reasoning.py index 1173f9613..9b8e1b5a1 100644 --- a/agent_core/core/prompts/reasoning.py +++ b/agent_core/core/prompts/reasoning.py @@ -14,28 +14,32 @@ Your output feeds directly into CraftBot's task pipeline. A poorly written prompt causes wrong skill selection, wrong action sets, misrouted sessions, or the agent executing the wrong thing entirely. Your job is to eliminate -every source of ambiguity before the agent ever sees the instruction. +ambiguity that can be resolved from the supplied request without guessing missing details. RULE 1 — PRESERVE INTENT EXACTLY Never change, expand, or restrict what the user asked for. Clarify; do not invent. If uncertain, keep the original scope. +Preserve all instructions, constraints, prohibitions, account qualifiers, +approval boundaries, and exact identifiers. Make task-implied execution steps +and verification explicit only when consistent with these requirements. RULE 2 — NAME THE TARGET EXPLICITLY Vague references to apps, files, or services cause the agent to guess wrong. -- "my emails" → name the email client (Gmail, Outlook, etc.) if known; - otherwise write "the default email client or browser" -- "that file" → name the file or folder path +- "my emails" → name the email client (Gmail, Outlook, etc.) if supplied; + otherwise retain the user's description without choosing a client +- "that file" → name the file or folder path only if identified in the request - "send a message" → name the platform (Telegram, WhatsApp, Slack, Discord) - if implied by context; this prevents wrong platform routing + if identified in the supplied request; this prevents wrong platform routing - "remind me" → write "create a proactive scheduled task" RULE 3 — STATE THE DONE-CONDITION The agent verifies tasks against a done-condition. If it is missing, the agent either over-executes or loops asking for confirmation. -End every enhanced prompt with what success looks like: +Describe completion of the requested task without inventing extra deliverables +or destinations. Use done-conditions consistent with the request, such as: "...and confirm to me when complete." -"...and save the result to the workspace folder." +"...and save the requested result to the specified location." "...and send me a summary of what was found." RULE 4 — SIGNAL TASK COMPLEXITY @@ -48,14 +52,17 @@ — this signals complex_task mode RULE 5 — HONOUR SCHEDULING SIGNALS -CraftBot has a built-in proactive scheduler. If the user implies recurrence -("every day", "each week", "automatically", "whenever X happens"), write +CraftBot has a built-in proactive scheduler. If the user specifies recurrence +("every day", "each week", "whenever X happens"), write "Set up a recurring proactive task to..." — this ensures the scheduler system is invoked, not a one-off task. +Preserve supplied timing and one-time or event conditions exactly. +"Automatically" alone does not imply recurrence. Do not invent a time or repeat interval. RULE 6 — ELIMINATE PRONOUN AMBIGUITY -"it", "this", "that", "them", "there" — replace every pronoun with the -actual noun it refers to, using context from the conversation if available. +"it", "this", "that", "them", "there" — replace a pronoun with its actual +noun only when identified in the supplied request. Otherwise retain the reference +for the executing agent; do not assume unseen conversation history. RULE 7 — ONE ACTION FRAME Do not chain unrelated actions into one prompt. If the user asked for one @@ -84,9 +91,9 @@ - Do NOT produce bullet lists or numbered steps — output is one prose block - Do NOT include preamble ("Here is the improved prompt:", "Enhanced:", etc.) - Do NOT wrap the output in quotes -- Do NOT exceed 4 sentences +- Do NOT drop instructions to shorten the request; there is no sentence limit - Do NOT use passive voice — use active imperative verbs -- Do NOT leave platform names implicit when a platform is involved +- Do NOT omit supplied platform names or invent missing ones - Do NOT start using another language other than the one written in by the user initially unless asked for by the user @@ -99,14 +106,14 @@ Examples of prompt quality (these are examples only, NOT the required output format): -BAD: "check my emails" -GOOD: "Open Gmail in the browser, check for unread emails received in the last 24 hours, and send me a plain-text summary of any messages that need a reply or action." +INPUT: "review PR #514 for bugs. don't edit files or post comments" +ENHANCED: "Inspect the diff and relevant surrounding code for PR #514, trace the changes for likely bugs, and report findings with file references. Do not edit files or post comments." -BAD: "remind me about the standup" -GOOD: "Create a recurring proactive task that sends me a reminder message 5 minutes before my daily standup meeting, using the schedule defined in my calendar or a fixed daily time I confirm." +INPUT: "remind me about the standup tomorrow at 10am, just once" +ENHANCED: "Create a one-time proactive scheduled task to remind me about the standup tomorrow at 10am, and verify that the reminder is scheduled for that time without recurrence." -BAD: "clean it up" -GOOD: "Open the Downloads folder, identify duplicate files and files not accessed in the last 30 days, list them for my review, and move only the confirmed items to Trash." +INPUT: "fix the failing tests. don't commit" +ENHANCED: "Reproduce the test failures, identify their causes, make the necessary fixes, and rerun the affected tests to verify they pass. Do not commit." Required output example: { diff --git a/agent_core/core/protocols/event_stream.py b/agent_core/core/protocols/event_stream.py index 76e5100fd..4d4bb52ec 100644 --- a/agent_core/core/protocols/event_stream.py +++ b/agent_core/core/protocols/event_stream.py @@ -5,7 +5,7 @@ This module defines protocols for event stream operations. """ -from typing import List, Optional, Protocol, Tuple, TYPE_CHECKING +from typing import Dict, List, Optional, Protocol, Tuple, TYPE_CHECKING if TYPE_CHECKING: from agent_core import EventRecord @@ -48,15 +48,18 @@ def log( def to_prompt_snapshot( self, - max_events: int = 60, include_summary: bool = True, + up_to: Optional[int] = None, + *, + message_overrides: Optional[Dict[Tuple[str, str], str]] = None, ) -> str: """ Build compact history for LLM prompts. Args: - max_events: Maximum number of recent events to include. include_summary: Whether to include the head summary. + up_to: Only include events before this index. + message_overrides: Render-only substitutions by exact kind and message. Returns: Formatted string of event history. diff --git a/app/subagent/context_engine.py b/app/subagent/context_engine.py index 663c2c5c3..1e7f1aaba 100644 --- a/app/subagent/context_engine.py +++ b/app/subagent/context_engine.py @@ -158,7 +158,7 @@ def make_system_prompt(self, sub: SubAgent) -> str: def make_first_turn_user_prompt(self, sub: SubAgent) -> str: """First-turn user prompt: query + initial event log + decision nudge.""" - event_log = self._snapshot_event_log(sub.id) + event_log = self._snapshot_event_log(sub) return ( f"QUERY FROM SPAWNING AGENT:\n{sub.query}\n\n" f"YOUR EVENT LOG SO FAR (most recent last):\n{event_log}\n\n" @@ -180,9 +180,21 @@ def make_delta_user_prompt(self, delta_events: str) -> str: # Helpers # ------------------------------------------------------------------ - def _snapshot_event_log(self, sub_id: str) -> str: + def _snapshot_event_log(self, sub: SubAgent) -> str: + # The complete current query is above this snapshot, including after + # a fold or restore. Abbreviate only an exact match; never edit storage. return ( - self.event_stream_manager.snapshot_by_id(sub_id, include_summary=True) + self.event_stream_manager.snapshot_by_id( + sub.id, + include_summary=True, + message_overrides={ + ( + "subagent_start", + sub.bootstrap_message, + ): f"Sub-agent of type '{sub.agent_type}' started. " + "Query: see QUERY FROM SPAWNING AGENT above." + }, + ) or "(no events yet)" ) diff --git a/app/subagent/manager.py b/app/subagent/manager.py index 9af811b42..2deb6b089 100644 --- a/app/subagent/manager.py +++ b/app/subagent/manager.py @@ -113,7 +113,7 @@ def spawn( # The parent stream never sees it. self.event_stream_manager.log( kind="subagent_start", - message=(f"Sub-agent of type '{agent_type}' started.\nQuery: {query}"), + message=sub.bootstrap_message, display_message=f"subagent[{agent_type}] start", task_id=sub_id, ) diff --git a/app/subagent/types.py b/app/subagent/types.py index 94e6c99f9..12aabb160 100644 --- a/app/subagent/types.py +++ b/app/subagent/types.py @@ -65,6 +65,11 @@ class SubAgent: # Mode marker — always ``SUBAGENT_MODE`` so downstream code can detect it. mode: str = SUBAGENT_MODE + @property + def bootstrap_message(self) -> str: + """The full diagnostic event, also used for exact prompt deduplication.""" + return f"Sub-agent of type '{self.agent_type}' started.\nQuery: {self.query}" + def is_terminal(self) -> bool: """True once the sub-agent has reached any terminal status.""" return self.status in SUBAGENT_TERMINAL_STATUSES diff --git a/tests/test_prompt_result_fidelity.py b/tests/test_prompt_result_fidelity.py new file mode 100644 index 000000000..85b271d0b --- /dev/null +++ b/tests/test_prompt_result_fidelity.py @@ -0,0 +1,189 @@ +"""T16/T17: exercise the shared result path without a server or a model.""" + +import asyncio +import copy +import json +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import AsyncMock, Mock + +import pytest + +from agent_core.core.event_stream.event import EventRecord, EventType +from agent_core.core.impl.action.manager import ActionManager, _to_json +from agent_core.core.impl.event_stream.event_stream import EventStream +from agent_core.core.impl.event_stream.manager import EventStreamManager +from agent_core.core.impl.mcp.server import MCPServerConnection + + +def _call(response): + server = MCPServerConnection(SimpleNamespace(name="fixture")) + server._transport = SimpleNamespace( + is_connected=True, send_request=AsyncMock(return_value=response) + ) + result = asyncio.run(server.call_tool("arbitrary_tool", {"id": 42})) + server._transport.send_request.assert_awaited_once_with( + "tools/call", {"name": "arbitrary_tool", "arguments": {"id": 42}} + ) + return result + + +@pytest.mark.parametrize( + ("is_error", "content", "structured"), + [ + (True, [{"type": "text", "text": "Denied"}], {"record_id": "r-42"}), + (False, [], {"record_id": "r-42"}), + (False, [{"type": "text", "text": "Result"}], False), + (True, [], 0), + (False, None, None), + (False, [{"type": "text", "text": ""}], {}), + (False, [], []), + (False, [{"type": "text", "text": "Result"}], ""), + ], +) +def test_tool_signals_and_values_are_preserved(is_error, content, structured): + native = { + "content": content, + "isError": is_error, + "structuredContent": structured, + "_meta": {"cursor": None}, + } + before = copy.deepcopy(native) + output = _call({"result": native}) + assert output["status"] == ("error" if is_error else "success") + assert output["isError"] is is_error + assert output["structuredContent"] == structured + assert type(output["structuredContent"]) is type(structured) + assert output["_meta"] == native["_meta"] + if content: + assert output["raw_content"] == content + else: + assert "raw_content" not in output # legacy no-content contract + assert output["result"] == (content[0]["text"] if content else native) + assert native == before + + +def test_absent_fields_are_not_invented_and_text_is_not_a_status_signal(): + output = _call( + {"result": {"content": [{"type": "text", "text": "error: quoted log text"}]}} + ) + assert output["status"] == "success" + assert not {"isError", "structuredContent", "_meta"} & output.keys() + assert "raw_content" not in _call({"result": {"structuredContent": None}}) + + +def test_mixed_media_keeps_blocks_annotations_and_metadata(): + blocks = [ + {"type": "text", "text": "first", "annotations": {"audience": ["user"]}}, + {"type": "image", "data": "fixture", "mimeType": "image/png"}, + { + "type": "resource", + "resource": {"uri": "fixture://r", "text": "source\n text"}, + }, + {"type": "text", "text": "last"}, + ] + output = _call({"result": {"content": blocks, "structuredContent": {"id": "r"}}}) + assert output["result"] == "first\nlast" + assert output["raw_content"] == blocks + assert output["structuredContent"] == {"id": "r"} + + +def test_jsonrpc_error_keeps_the_existing_contract(): + assert _call({"error": {"message": "bad request", "code": -32602}}) == { + "status": "error", + "message": "bad request", + "code": -32602, + } + + +def test_nontext_only_result_retains_the_original_result_object(): + native = { + "content": [{"type": "image", "data": "fixture", "mimeType": "image/png"}], + "structuredContent": None, + "_meta": False, + } + result = _call({"result": native}) + assert result["result"] == native + assert result["raw_content"] == native["content"] + assert result["structuredContent"] is None and result["_meta"] is False + null_content = _call({"result": {"content": None}}) + absent_content = _call({"result": {}}) + assert null_content["result"] == {"content": None} + assert absent_content["result"] == {} + + +def test_compact_serializer_preserves_values_order_strings_and_fallbacks(): + value = { + "z": "def f():\r\n\treturn 0\n", + "a": '{\n "nested": true\n}', + "unicode": "日本語", + "values": [False, 0, None, [], {}], + } + rendered = _to_json(value, compact=True) + assert json.loads(rendered) == value + assert list(json.loads(rendered)) == list(value) + assert "\n" not in rendered + assert len(rendered) < len(_to_json(value)) + assert json.loads(_to_json({"path": Path("fixture")}, compact=True)) == { + "path": "fixture" + } + circular = [] + circular.append(circular) + assert _to_json(circular, compact=True) == str(circular) + + +def test_mcp_failure_reaches_action_status_and_new_compact_event(): + output = _call( + { + "result": { + "isError": True, + "content": [{"type": "text", "text": "Denied"}], + "structuredContent": {"record_id": "r-42"}, + } + } + ) + streams = EventStreamManager(llm=None) + stream = streams.create_stream("fixture") + old = 'Action old completed with output: {\n "value": 1\n}.' + stream.log("action_end", old, event_type=EventType.ACTION_END) + stream.mark_session_synced("test") + on_end = Mock() + manager = ActionManager( + action_library=Mock(), + llm_interface=Mock(), + db_interface=Mock(), + event_stream_manager=streams, + context_engine=Mock(), + state_manager=Mock(), + on_action_end=on_end, + ) + manager.execute_atomic_action = AsyncMock(return_value=output) + action = SimpleNamespace( + name="tool", + display_name="Tool", + platform_overrides={}, + code="", + irreversible=False, + action_type="atomic", + ) + returned = asyncio.run( + manager.execute_action(action, "", "", session_id="fixture", input_data={}) + ) + assert returned == output + assert on_end.call_args.args[3] == "error" + event = stream.tail_events[-1].event + assert event.action_output == output + body = event.message.removeprefix("Action tool completed with output: ")[:-1] + assert json.loads(body) == output and "\n" not in body + assert "failed" in event.display_message + assert old in stream.to_prompt_snapshot() + assert old not in stream.get_delta_events("test")[0] + # Cold restore and post-fold rendering reuse the stored representation. + restored = EventStream(llm=None) + restored.tail_events = [ + EventRecord.from_dict(json.loads(json.dumps(r.to_dict()))) + for r in stream.tail_events + ] + assert restored.to_prompt_snapshot() == stream.to_prompt_snapshot() + restored.head_summary = "Previous work" + assert event.message in restored.to_prompt_snapshot() diff --git a/tests/test_subagent_bootstrap_prompt.py b/tests/test_subagent_bootstrap_prompt.py new file mode 100644 index 000000000..7444010df --- /dev/null +++ b/tests/test_subagent_bootstrap_prompt.py @@ -0,0 +1,123 @@ +"""T18: render an exact bootstrap duplicate by reference, without mutating it.""" + +import json +from unittest.mock import Mock + +import pytest + +from agent_core.core.event_stream.event import EventRecord +from agent_core.core.impl.event_stream.manager import EventStreamManager +from app.subagent.context_engine import SubAgentContextEngine +from app.subagent.manager import SubAgentManager +from app.subagent.runner import SubAgentRunner, _SUBAGENT_CALL_TYPE + + +@pytest.fixture +def runtime(): + llm = Mock() + events = EventStreamManager(llm=llm) + manager = SubAgentManager(events, llm) + query = "\n".join( + f"Constraint {i}: preserve C:/sources/{i}.txt and /tmp/source-{i}; do not send messages." + for i in range(40) + ) + sub = manager.spawn("general_agent", query) + runner = SubAgentRunner(manager, Mock(), Mock(), events, llm) + return sub, events, runner + + +def test_initial_prompt_keeps_query_once_and_records_remain_complete(runtime): + sub, events, runner = runtime + stream = events.get_stream_by_id(sub.id) + before = [r.to_dict() for r in stream.tail_events] + prompt, first = runner._build_user_prompt(sub, stream) + assert first and prompt.count(sub.query) == 1 + assert "Query: see QUERY FROM SPAWNING AGENT above." in prompt + assert [r.to_dict() for r in stream.tail_events] == before + assert sub.bootstrap_message in events.snapshot_by_id(sub.id) + + +@pytest.mark.parametrize( + "phase", + ["restore", "fold_removed_bootstrap", "fold_retained_bootstrap", "no_delta"], +) +def test_every_fresh_context_contains_the_complete_query(runtime, phase): + sub, events, runner = runtime + stream = events.get_stream_by_id(sub.id) + stream.mark_session_synced(_SUBAGENT_CALL_TYPE) + if phase == "restore": + records = [ + EventRecord.from_dict(json.loads(json.dumps(r.to_dict()))) + for r in stream.tail_events + ] + stream.clear() + stream.tail_events = records + elif phase.startswith("fold"): + stream.head_summary = "Previous work, with open items." + if phase == "fold_removed_bootstrap": + stream.tail_events = [] + stream.reset_session_sync(_SUBAGENT_CALL_TYPE, "fold") + prompt, first = runner._build_user_prompt(sub, stream) + assert first and prompt.count(sub.query) == 1 + assert all(f"Constraint {i}:" in prompt for i in range(40)) + if phase.startswith("fold"): + assert "Previous work, with open items." in prompt + + +def test_different_bootstrap_is_never_abbreviated(runtime): + sub, events, runner = runtime + stream = events.get_stream_by_id(sub.id) + record = next(r for r in stream.tail_events if r.event.kind == "subagent_start") + record.event.message += "\nDo not modify any source files." + original = record.event.message + prompt = runner.context_engine.make_first_turn_user_prompt(sub) + assert original in prompt + assert "Query: see QUERY" not in prompt + assert sub.query in prompt + + +def test_matching_text_in_another_event_is_not_rewritten(runtime): + sub, events, runner = runtime + events.log("quotation", sub.bootstrap_message, task_id=sub.id) + prompt = runner.context_engine.make_first_turn_user_prompt(sub) + assert sub.bootstrap_message in prompt + assert "Query: see QUERY" in prompt + + +def test_delta_does_not_resend_query_or_change_the_cached_first_turn(runtime): + sub, events, runner = runtime + stream = events.get_stream_by_id(sub.id) + first, _ = runner._build_user_prompt(sub, stream) + stream.mark_session_synced(_SUBAGENT_CALL_TYPE) + events.log("progress", "Read the source", task_id=sub.id) + delta, is_first = runner._build_user_prompt(sub, stream) + assert not is_first and sub.query not in delta + assert "Read the source" in delta + assert first.count(sub.query) == 1 + + +def test_long_query_needs_no_retrieval_and_keeps_every_constraint(): + events = EventStreamManager(llm=None) + manager = SubAgentManager(events, Mock()) + query = "\n".join( + f"Constraint {i}: " + ("source evidence, " * 25) for i in range(120) + ).rstrip() + sub = manager.spawn("general_agent", query) + engine = SubAgentContextEngine(Mock(), events) + prompt = engine.make_first_turn_user_prompt(sub) + assert len(query) > 42059 + assert prompt.count(query) == 1 + assert sub.query == query + assert sub.bootstrap_message in events.snapshot_by_id(sub.id) + + +def test_query_whitespace_is_not_normalized_to_force_a_match(): + events = EventStreamManager(llm=None) + manager = SubAgentManager(events, Mock()) + sub = manager.spawn("general_agent", "Preserve this exact query.\n\n") + prompt = SubAgentContextEngine(Mock(), events).make_first_turn_user_prompt(sub) + # Event logging strips surrounding whitespace. Equality cannot be proved, + # so keep its text and the complete standalone query, including newlines. + assert sub.query in prompt + assert "Query: see QUERY" not in prompt + assert prompt.count("Preserve this exact query.") == 2