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
I'll start by exploring the repository structure to understand the codebase and then implement the fix for the cross-session contamination issue.
Assistant
The error is about the argument format - let me try without the explicit "file" key.
Assistant
Let me see the full memory.py file and also the context.py file to understand the current implementation.
Assistant
The file is 955 lines but got truncated. Let me read it in parts.
Assistant
I need to continue reading the file to understand the full implementation. Let me read more sections.
Assistant
Now let me continue reading the rest of the memory.py file, and also check context.py.
Assistant
Now I can see the
archivemethod. Let me continue reading the rest of the file and also look at context.py.Assistant
Now let me look at the context.py file to understand how the history is used in system prompt building:
Assistant
Now I have a good understanding of the codebase. Let me also look for other files that might call
archive,raw_archive, orappend_historyto understand all the call sites:Assistant
Now let me check the loop.py to understand the
/newarchival and session clearing:Assistant
Now let me look at the auto_compact module to understand how idle sessions are compacted and the
prepare_sessionmethod:Assistant
Now let me check the session manager for how sessions are handled, especially around
/newandenforce_file_cap:Assistant
Now let me check the commands module to understand how
/newworks:Assistant
Now I have a comprehensive understanding of the codebase. Let me also check the existing tests to understand the testing patterns:
Assistant
Looking at the evaluation contract, I need to:
- Add
session_keyparameter toappend_history()inMemoryStore - Add
session_keyparameter toarchive()inConsolidator - Add
session_keyparameter toraw_archive()inMemoryStore - Create
read_recent_history_for_prompt()inMemoryStorethat filters by session_key - Update
ContextBuilder.build_system_prompt()to useread_recent_history_for_prompt()with session filtering - Update all callers of
archive(),raw_archive(), andappend_history()to pass session_key - Handle unified-session mode
- Handle internal sessions (cron:, dream:, heartbeat:)
- Handle legacy entries without session_key
Let me look at the tests to understand the testing patterns.
- Add
Assistant
Let me continue exploring the tests to understand the testing patterns, and then I'll implement the fix.
Assistant
Let me look at the existing test files for memory store and context builder to understand the testing patterns. Also, I need to check the unified session test since the evaluation contract mentions unified-session mode.
Assistant
Now I have a good understanding of the codebase and the test patterns. Let me also check the unified session test to understand the unified_session mode:
Assistant
Let me check the
enforce_file_capcall and MCP draining:Assistant
Now I have a good understanding of the codebase. Let me implement the fix according to the evaluation contract. Here's my plan:
MemoryStore.append_history()- Addsession_keyparameterMemoryStore.raw_archive()- Addsession_keyparameter, pass throughConsolidator.archive()- Addsession_keyparameter, pass throughMemoryStore.read_recent_history_for_prompt()- New method with session filteringContextBuilder.build_system_prompt()- Use new method with session filtering- Update all callers to propagate
session_key
Let me start implementing:
Assistant
Now I need to implement the changes. Let me start by modifying the
MemoryStore.append_history()method to acceptsession_key, then update all the related methods and callers.Let me create the changes step by step.
Assistant
Now let me implement all the changes. I'll start with the
memory.pyfile:Assistant
The
editcommand seems to have issues with the arguments format. Let me try a different approach - I'll use theeditcommand with the correct syntax.Assistant
I need to add the
read_recent_history_for_promptmethod toMemoryStoreclass. Let me first find whereread_unprocessed_historyis defined so I can add the new method nearby.Assistant
Now I need to add the
read_recent_history_for_promptmethod. Let me insert it right afterread_unprocessed_history:Assistant
Now let me update the
context.pyfile to use the newread_recent_history_for_promptmethod with proper session filtering. Let me check the current implementation and figure out how to pass thesession_key:Assistant
I need to update
build_system_promptto acceptsession_keyandunified_sessionparameters. Let me also check howbuild_system_promptis called:Assistant
I need to trace how
build_messagesandbuild_system_promptare called to understand what parameters are available. Let me check thebuild_messagesmethod signature and its callers:Assistant
I need to:
- Add
session_keyandunified_sessionparameters tobuild_system_promptandbuild_messages - Update the call in
build_messagesto pass those parameters - Update
context.pyto useread_recent_history_for_prompt
Let me now check how
build_messagesis called from loop.py to see if session_key is available.- Add
Assistant
I can see the
sessionobject is available in_build_initial_messages. I need to passsession.keyandself._unified_sessiontobuild_messages. Let me now update the context.py and loop.py files:Assistant
Now I need to update loop.py to pass
session_keyandunified_sessiontobuild_messagescalls:Assistant
The agent has made progress on the patching work but seems to have stopped after patching loop.py (2nd call). Let me continue with the work:
- Check what still needs to be done based on the evaluation contract
- Verify the patches are correct
- Look for other places that need session_key propagation
- Handle the /new command archival
- Handle enforce_file_cap archival
- Run tests to verify
- Create a test script to validate the fix
Let me check the current state of the files and what still needs to be done.
Assistant
I see. The
enforce_file_capmethod on the Session class takes anon_archivecallback. Currently it passesself.context.memory.raw_archive, butraw_archivenow requires asession_keyparameter. I need to look at howenforce_file_capcallson_archiveand update it to pass the session key.Let me check the Session class's
enforce_file_capmethod and update it accordingly.Assistant
I need to update the
enforce_file_capcall sites to passsession_key. I have a few options:- Update
enforce_file_capto accept and forwardsession_key - Create a wrapper/lambda at call sites
I'll go with option 1 - updating
enforce_file_capto acceptsession_key:- Update
Assistant
Now I need to update the call sites in loop.py to pass
session_key:Assistant
Now let me update the
/newcommand to passsession_keywhen callingarchive:Assistant
Let me continue checking the current state of the patches and verify everything is working correctly. I need to:
- Verify all the patches are applied correctly
- Check if there are any other places that call archive(), raw_archive(), or append_history() that need updating
- Run tests to verify the changes work
- Create a test script to validate the session isolation fix
Let me first check the current state of the patched files and look for any remaining issues.
Assistant
Good, all the calls to archive, raw_archive, and append_history have session_key propagated. Now let me run the existing tests to verify the changes work correctly.
Assistant
All memory store tests pass. Let me now run the context builder tests and other related tests to verify everything is working correctly.
Assistant
Let me continue running more tests to validate the changes.
Assistant
I see the issue. In the
_state_savemethod around line 1494, there's asessionvariable being used but it's not in scope. The code usesctx.sessioninstead. Let me fix this.Assistant
I see the issue. The patch replaced
session.enforce_file_capwith the correct signature but the variable isctx.session, notsession. Let me fix this:Assistant
The user seems to have encountered an error about not invoking a tool call. But looking at my previous response, I already ran a command. The issue is that my previous response might have been incomplete or didn't execute properly. Let me continue with verifying the fix works and run the tests again.
Assistant
All auto compact tests pass now. Let me run more comprehensive tests and then create a validation script for the session isolation fix.
Assistant
All consolidator and unified session tests pass. Let me run a broader test suite and then create a validation script for the session isolation fix.
Assistant
I see there are some test failures. Let me investigate them:
test_new_clears_session_immediately_even_if_archive_failsand related tests - likely need to check how they mock archivetest_preflight_consolidation_before_llm_call- the mocktrack_consolidate()doesn't acceptsession_key
Let me look at these failing tests to understand what's happening.
Assistant
I see the issue. The test mocks don't accept
session_key. But according to the instructions, I should NOT modify tests. The tests are failing because they mockarchive()with functions that don't accept**kwargs.The solution is to make sure the production code handles the case where
archive()might be called withsession_keybut the mock function doesn't accept it. However, I can't change the tests.Wait, let me re-read the instructions: "If existing tests break because they need to be updated to reflect the changes you made, just ignore it."
So these test failures are expected because the tests mock
archive()with a simplified signature. The tests would need to be updated to accept**kwargsor explicitly acceptsession_key, but I'm told to ignore test failures that are due to test updates needed.Let me verify that the remaining test (
test_preflight_consolidation_before_llm_call) has the same issue:Assistant
These test failures are expected - the test mocks need to be updated to accept the new
session_keyparameter. According to the instructions, I should ignore these test failures since they require test updates.Now let me create a validation script to verify the session isolation fix works correctly, and then run the existing tests that don't have mock issues.
Assistant
All 225 core tests pass. Now let me create a validation script to verify the session isolation fix works correctly.
Assistant
The test shows that in unified mode, we're getting 3 entries instead of 4. Looking at the logic, I think the issue is that the entries without session_key should be included in unified mode. Let me check my implementation:
Assistant
I see - the test expected 4 entries (3 user + 1 none) but there was no legacy entry added in the test. Let me fix the test to match what we're actually testing.
Assistant
All session isolation tests passed! Let me run the full test suite one more time to confirm the implementation is complete, then submit.
Assistant
All 225 core tests pass. Let me verify the changes I've made by reviewing the git diff:
Assistant
Let me do a final review of the implementation and verify everything is working correctly.
Assistant
I've completed implementing the session isolation fix for the
history.jsonlcross-session contamination issue. Let me submit the changes.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.