ISSUE DESCRIPTION history.jsonl 跨会话注入导致上下文污染 Bug Description history.jsonl 跨会话注入导致上下文污染…
- User
ISSUE DESCRIPTION
history.jsonl跨会话注入导致上下文污染Bug Description
history.jsonl跨会话注入导致上下文污染问题描述
history.jsonl中的每条 entry 来源于 单个会话 的消息摘要(通过Consolidator.archive()生成),但ContextBuilder.build_system_prompt()在注入# Recent History时,未做会话隔离,会将所有会话尚未被 Dream 处理的 entry 全部混入当前会话的 system prompt。数据流分析
写入路径(
Consolidator)Consolidator.archive()被三个调用方触发,均传入 per-session 的消息块:# memory.py:578, 751, 824 chunk = session.messages[session.last_consolidated:end_idx] # 单会话切片 summary = await self.archive(chunk) self.store.append_history(summary, max_chars=_ARCHIVE_SUMMARY_MAX_CHARS)每条写入的 JSONL entry 格式为:
{"cursor": N, "timestamp": "2026-06-09 12:00", "content": "用户偏好深色主题..."}注意:entry 中没有
session_key或chat_id字段,无法追溯来源会话。注入路径(
ContextBuilder)# context.py:64-71 entries = self.memory.read_unprocessed_history(since_cursor=self.memory.get_last_dream_cursor()) if entries: capped = entries[-self._MAX_RECENT_HISTORY:] history_text = "\n".join( f"- [{e['timestamp']}] {e['content']}" for e in capped ) history_text = truncate_text(history_text, self._MAX_HISTORY_CHARS) parts.append("# Recent History\n\n" + history_text)read_unprocessed_history(since_cursor)读取的是 cursor > dream_cursor 的全部条目,不区分来源会话,无任何 session 隔离。问题场景
时序 事件 dream_cursorT1 微信会话 A 触发 Consolidator,写入 2 条摘要 entry 0 T2 Telegram 会话 B 触发 Consolidator,写入 1 条摘要 entry 0 T3 用户打开 Telegram 会话 B,调用 build_system_prompt读取 cursor>0 的 全部 3 条,混入会话 B 的 system prompt 此时会话 B 的
# Recent History中包含了微信会话 A 的摘要,而该摘要是从微信会话提炼的,可能包含:- 微信特定的事实或上下文
- 与 Telegram 会话完全无关的用户偏好
- 尚未被 Dream 消化/验证的原始摘要
影响评估
- 会话上下文污染 — 当前会话的 system prompt 被注入无关会话的事实,可能干扰 LLM 判断
Assistant
Let me start by exploring the repository structure to understand the codebase.
Assistant
Let me explore the agent directory structure and find the relevant files.
Assistant
Let me see the truncated portion of memory.py.
Assistant
Let me look at context.py to understand the injection path.
Assistant
Now let me look at where archive() and raw_archive() are called to understand the call sites that need to pass session_key.
Assistant
Let me look at the test directory structure for memory tests.
Assistant
Let me check the autocompact.py file to understand the full picture.
Assistant
Let me search for the place where archive is called in loop.py and command/builtin.py.
Assistant
Let me look at the session manager to understand sessions.
Assistant
Let me look at the command/builtin.py to see the /new archive call.
Assistant
Now let me look at the runner.py to understand session clearing.
Assistant
Let me look at the unified_session mode and explore further.
Assistant
Let me look at the loop.py code structure, especially around session keys.
Assistant
Let me check the heartbeat and cron session keys.
Assistant
Let me look at how the build_system_prompt callers use it.
Assistant
Let me check the existing tests for context.py to understand what's being tested.
Assistant
Let me check the test_cursor_recovery.py file to see the related history tests.
Assistant
Let me look at the existing system more carefully now to find all callers.
Assistant
Let me look at how tests are run in this repository.
Assistant
Let me write a reproduction script first.
Assistant
Now I'll plan the fix. Let me make all the changes.
First, let me update
MemoryStore.append_historyto accept and persistsession_key:Assistant
Let me use the
replacetool instead with the file path:Assistant
Let me use the
replacetool instead.Assistant
Now let me update the body of
append_historyto actually use the newsession_keyparameter:Assistant
Now let me add the new
read_recent_history_for_promptmethod. First, let me look at the existingread_unprocessed_historymethod:Assistant
Now let me add the
read_recent_history_for_promptmethod right afterread_unprocessed_history. First, let me check what an "internal session" prefix list should include:Assistant
The contract says:
- exclude internal
cron:,dream:, andheartbeathistories - the currently matching internal session may read its own entries
So the internal prefixes are:
cron:,dream:,heartbeat. There's also "heartbeat" itself which is justheartbeat(no colon).Let me check what the agent uses for heartbeat session key:
- exclude internal
Assistant
Now let me add the
read_recent_history_for_promptmethod. Let me also add helper for internal sessions:Assistant
I need to import Mapping. Let me check.
Assistant
Now let me update
raw_archiveto acceptsession_key:Assistant
Now let me update
Consolidator.archiveto acceptsession_key:Assistant
Now let me update the internal callers of
archiveto passsession_key:Assistant
Now let me update
cmd_newin builtin.py to passsession_key:Assistant
Now let me update
loop.pyto:- Wrap
raw_archivecalls inenforce_file_capso they passsession_key - Update
build_messages/_build_initial_messagesto passsession_keyandunified_sessionthrough - Make sure
close_mcpis properly defined
- Wrap
Assistant
Now let me update the
enforce_file_capcalls in loop.py to pass the session_key:Assistant
Now let me check the existing
close_mcpto verify the MCP background task draining:Assistant
The
close_mcpalready drains background tasks. Good. Let me look at the test for close_mcp or shutdown to see if there's a specific MCP background task handling that needs work.Looking at the contract:
MCP background tasks must be drained on close.
This appears to already be handled by
close_mcp. Let me make sure there isn't a separate MCP task list we need to handle.Assistant
Good. Now let me update the
ContextBuilderto use the newread_recent_history_for_prompt:Assistant
Now let me update
build_messagesincontext.pyto forward thesession_keyandunified_sessionparameters:Assistant
Now let me update
_build_initial_messagesinloop.pyto passsession_keyandunified_sessionthrough:Assistant
Now let me verify all my changes by running the reproduction script first:
Assistant
I need to re-think the unified-session logic. The contract says:
- In unified mode, include user-channel history across sessions (for user-channel callers)
- Exclude internal histories (cron/dream/heartbeat)
- The currently matching internal session may read its own entries
So in unified mode:
- If the caller is a user-channel session, they see all user-channel entries.
- If the caller is an internal session, they only see their own entries (not user-channel).
Assistant
All tests pass. Now let me run the existing tests to make sure I haven't broken anything:
Assistant
There's a test that mocks
archiveto be a simple function that doesn't acceptsession_key. Let me look at the test:Assistant
Looking at the instructions:
If existing tests break because they need to be updated to reflect the changes you made, just ignore it.
This test breaks because the test mock has the old API signature, but the new contract requires
session_keyto be passed. Let me see what other tests might be affected.Assistant
There are 5 failing tests, all due to the API change:
test_context_prompt_cache.py— likely tests for the context prompt that don't pass session_keytest_loop_consolidation_tokens.py::test_preflight_consolidation_before_llm_call— mocksarchivewith old signature
Let me check
test_context_prompt_cache.pyfirst.Assistant
These tests are testing the old behavior where
read_unprocessed_historyreturns all entries. With the new contract, whensession_key=Noneandunified_session=False, no entries are returned.Per the contract:
Recent-history prompt injection is scoped to the current session and excludes legacy entries without a session key.
So the new behavior is correct: when no session_key is provided, no entries should be returned. The tests need to be updated to pass session_key.
The instructions say:
Assistant
These tests fail because the API signature changed. Per the instructions:
If existing tests break because they need to be updated to reflect the changes you made, just ignore it. Evaluation system will not take it into account.
So I should leave these tests failing. Let me run the rest of the test suite to make sure nothing else is broken:
Assistant
Let me check the failing MCP test:
Assistant
This test failure is unrelated to my changes. Let me verify by checking the original file:
Assistant
Good —
test_test_mcp_preset_connects_and_reports_toolswas already failing before my changes (so it's unrelated). Let me also confirm the other test failures are related to my changes:Assistant
All these tests use the same pattern: they mock with a function that doesn't accept . These are the failing tests due to my API change.
Assistant
All these test failures are due to the API signature change in
archive. The test mocks have the old signature and would need to be updated.Per the instructions:
If existing tests break because they need to be updated to reflect the changes you made, just ignore it. Evaluation system will not take it into account.
These tests are checking functionality that should still work (clearing immediately, etc.) but they use the old API. The fix is correct, but the tests need updating.
Let me look at the diff of my changes to make sure everything is in order.
Assistant
Let me re-run the reproduction test to confirm the fix:
Assistant
Let me also check if there are any MCP-specific background tasks that aren't tracked in
_background_tasks:Assistant
Let me also check if
_active_tasksare drained on close.Looking at the close_mcp:
async def close_mcp(self) -> None: """Drain pending background archives, then close MCP connections.""" if self._background_tasks: await asyncio.gather(*self._background_tasks, return_exceptions=True) self._background_tasks.clear()It only drains
_background_tasks, not_active_tasks. But_active_tasksare tracked separately and should be cancelled instop()orclose_mcp().Wait — looking at the contract:
MCP background tasks must be drained on close.
The "MCP background tasks" might refer to a specific set of tasks, not just the
_background_tasks. Let me check.Assistant
Let me look at the close_mcp tests:
Assistant
The existing implementation already drains
_background_tasks(which are archive tasks) on close. The contract mentions "MCP background tasks must be drained on close." — this is about the same_background_tasksmechanism. The current code already handles this.Let me re-read the contract:
MCP background tasks must be drained on close.
This is a single sentence — it's part of the broader requirements about session closing behavior. I interpret this as: any background tasks (including MCP-related ones) that are scheduled through
_schedule_backgroundmust be drained onclose_mcp. The existing code already does this.So my implementation is correct.
Let me verify the implementation one more time by re-running the original repro:
Assistant
Let me also write a more comprehensive test to verify all the contract points:
Assistant
Let me also test the
/newcommand path:Assistant
All tests pass. Now let me also verify the existing test suite works for the parts I've modified:
Assistant
All core tests pass. Let me also verify the
enforce_file_capcallback works correctly:Assistant
Let me look at the enforce_file_cap logic more carefully:
Assistant
Now let me verify all the changes one more time:
Assistant
All
archive()andraw_archive()internal callers now passsession_key. Let me also check the_background_tasksto verify that_schedule_backgroundis properly drained on close:Assistant
Let me run a broader test suite to verify nothing else broke:
Assistant
The only remaining failing test is the pre-existing unrelated test. All 4011 other tests pass!
Let me also check for any other related code in
runner.pyor other files:Assistant
Good, only two call sites. Both have been updated.
Now let me check if there's any other place where history entries are created (e.g., Dream consolidation might write entries directly).
Assistant
The only direct writes to history.jsonl are via
_write_entrieswhich is called from internal methods (e.g.,_maybe_migrate_legacy_history,compact_history). These are fine.Now let me also look at the runner.py and any other file to see if there are any tests or behaviors I need to verify.
Assistant
The existing tests still pass because
session_keyis optional. Let me also test edge cases:Assistant
All edge cases pass. Let me also verify the build_system_prompt handles a few more scenarios:
Assistant
All system prompt tests pass. Let me also verify the integration with the agent loop is correct by running the existing unified session tests:
Assistant
All unified session tests pass. Let me also run the dream tests to make sure they still pass:
Assistant
All dream tests pass. Let me look more carefully at the raw_archive usage in non-test code to make sure all callsites are updated:
Assistant
Both
raw_archivecallsites inloop.pyare updated. Let me verify with a more comprehensive integration test:Assistant
All integration tests pass. Let me do a final review by listing all the changes:
Assistant
Let me clean up temporary test files and run a final verification:
Assistant
Let me also verify the bug is fixed with one final reproduction:
Assistant
The fix works. Let me clean up the temporary test:
Assistant
My implementation is complete. Let me verify the contract adherence one final time by looking at all the changes:
Assistant
Final Checklist
Let me run one final comprehensive test to verify all contract points are satisfied:
Assistant
All contract points are verified. Let me clean up and verify existing tests one final time:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.