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 history injection issue.
Assistant
Let me explore the repository structure to understand the codebase and find the relevant files mentioned in the issue.
Assistant
Good, I found the key files. Let me start by examining the main files mentioned in the issue:
memory.pyandcontext.py.Assistant
The user is having trouble with the tool call format. Let me use the correct format with bash_terminal to view the file.
Assistant
Now let me look at the context.py file:
Assistant
Let me see more of the memory.py file, especially the methods I need to modify:
Assistant
Now I need to understand the full scope of changes needed. Let me look at:
raw_archivemethodarchivemethod- How
read_unprocessed_historyis called incontext.py - The tests to understand expected behavior
Let me see the
raw_archivemethod and thearchivemethod.Assistant
Now I have a good understanding of the code. Let me now look at the archive method and where it's called from:
Assistant
I need to understand the full picture. Let me look at:
- Where
archiveis called with session info - Where
raw_archiveis called - Where
compact_idle_sessioncalls archive - The tests to understand expected behavior
Let me also look at the interface description more carefully:
The interface says:
append_history(self, entry: str, *, max_chars: int | None = None, session_key: str | None = None) -> intarchive(self, messages: list[dict], *, session_key: str | None = None) -> str | Noneraw_archive(self, messages: list[dict], *, max_chars: int | None = None, session_key: str | None = None) -> Noneread_recent_history_for_prompt(self, since_cursor: int, *, session_key: str | None, unified_session: bool = False) -> list[dict[str, Any]]
So I need to:
- Add
session_keyparameter toappend_historyand include it in the JSON record - Add
session_keyparameter to and pass it to and
- Where
Assistant
I need to understand the context better. Let me look at where archive is called to understand what session_key should be passed. Let me check the calls at lines 688, 861, and 933.
Assistant
Now let me look at the test files to understand the expected behavior:
Assistant
Let me continue examining the test files and the context builder to understand the full scope of changes needed.
Assistant
Let me look at the context.py more closely to understand what parameters are available when
build_system_promptis called:Assistant
Now let me understand how the
build_messagesmethod is called and if it has access tosession_keyorunified_sessionconfiguration:Assistant
Let me look at the runner.py to see how the agent gets its session_key:
Assistant
Let me understand better how build_system_prompt is called and what parameters it receives. Let me look at the actual caller:
Assistant
Let me continue exploring the codebase to understand all the archive call paths and the
/newarchival:Assistant
Let me look at the
/newarchival path and also how theenforce_file_capworks:Assistant
Let me now check what
/newcommand does related to archival:Assistant
Now let me look at the
/newcommand implementation to understand its archival path:Assistant
Let me find the cmd_new function to understand the /new archival path.
Assistant
Commenter:
Assistant
Now I have a comprehensive understanding of the codebase. Let me create a plan:
Plan
Changes needed:
MemoryStore.append_history()- Addsession_key: str | None = Noneparameter and include it in the JSON record when providedMemoryStore.raw_archive()- Addsession_key: str | None = Noneparameter and pass it toappend_history()MemoryStore.read_recent_history_for_prompt()- New method that filters bysession_keywithunified_sessionmode supportConsolidator.archive()- Addsession_key: str | None = Noneparameter and pass it to bothappend_history()andraw_archive()- - Pass to
Assistant
...
Assistant
...
Assistant
Let me understand the full context better. The
enforce_file_cappassesraw_archiveas theon_archivecallback. I need to ensuresession_keyis propagated there.Let me look at the full
enforce_file_capmethod and see how to handle this:Assistant
Now I have a solid understanding of the codebase. Let me start implementing the changes. I'll work through the files systematically.
Assistant
Now let me see the rest of
append_historyand understand the full context:Assistant
Now let me look at the
raw_archivemethod:Assistant
Now I have enough information. Let me implement all the changes. I'll start with
memory.py:Assistant
Let me create a Python script to make the changes:
Assistant
Let me make the changes to
memory.pystep by step. First, let me modify theappend_historymethod:Assistant
Now I need to update the
Consolidator.archive()method and all its callers to propagatesession_key. Let me first look at the currentarchivemethod:Assistant
I need to update the
archivemethod in the Consolidator class to accept and propagatesession_key. Let me do this step by step.Assistant
I need to verify the changes made so far and continue with the remaining updates. Let me check what I've done and what still needs to be done.
Changes completed:
- ✅
MemoryStore.append_history()- Addedsession_keyparameter - ✅
MemoryStore.raw_archive()- Addedsession_keyparameter - ✅
MemoryStore.read_recent_history_for_prompt()- New method added - ✅
Consolidator.archive()- Addedsession_keyparameter
Remaining work: 5. Update all callers of
archive()in memory.py to passsession_key6. Updateenforce_file_capcallers in loop.py to passsession_key7. Updatecmd_newin builtin.py to passsession_key8. UpdateContextBuilder.build_system_prompt()to useread_recent_history_for_prompt9. Update context.py to passsession_keyandunified_sessionto the new method- ✅
Assistant
Now I need to update the
enforce_file_capmethod and its callers to propagatesession_key. Let me continue with the remaining changes.Assistant
Now I need to update
cmd_newin builtin.py to passsession_key:Assistant
Now I need to update
context.pyto use the newread_recent_history_for_promptmethod. Let me first check the current implementation:Assistant
I need to update
ContextBuilder.build_system_prompt()to use the newread_recent_history_for_promptmethod. First, let me check how it's called frombuild_messages:Assistant
I need to update the
ContextBuilderto acceptsession_keyandunified_sessionparameters and use the newread_recent_history_for_promptmethod. Let me:- Update
build_system_promptto acceptsession_keyandunified_sessionparameters - Update
build_messagesto accept and pass these parameters - Update the callers in
loop.pyto pass these parameters
Let me look at how
build_messagesis called inloop.pyto understand what session info is available.- Update
Assistant
I need to continue implementing the changes. Let me update the context.py to:
- Add
session_keyandunified_sessionparameters tobuild_system_prompt - Update
build_messagesto accept and pass these parameters - Update loop.py callers to pass the session key and unified_session setting
Let me start by creating the fix for context.py.
- Add
Assistant
Now I need to update the callers in loop.py to pass
session_keyandunified_sessiontobuild_messages. Let me check all the call sites.Assistant
I need to update the callers in loop.py to pass
session_keyandunified_sessiontobuild_messages. Let me first see what parameters the calling function has available.Assistant
I need to update loop.py to pass
session_keyandunified_sessiontobuild_messages. The method_build_initial_messageshas access tosession, so I can usesession.keyandself._unified_session.Assistant
I need to continue updating the other
build_messagescall sites in loop.py. Let me check the remaining calls.Assistant
I need to update this second call to
build_messagesat line ~1142. Let me update it:Assistant
Let me verify all the changes and check for any remaining call sites that need updating.
Assistant
Let me verify all changes are in place. Let me check what's at line 313 in loop.py - that's a reference that passes
build_messagesas a callback.Assistant
This is where
Consolidatorgets thebuild_messagescallback. Let me check how theConsolidatoruses this callback:Assistant
I see that
Consolidatoralso usesbuild_messagesfor token estimation. This call should also passsession_keyandunified_sessionfor consistency. Let me update it:Assistant
Now I need to update the caller in loop.py that creates the Consolidator to pass
unified_session:Assistant
I need to add
unified_session=self._unified_sessionto the Consolidator constructor call in loop.py:Assistant
Now let me verify the changes by running the tests to make sure everything works correctly.
Assistant
All 38 tests pass. Let me continue running the context builder tests to verify the changes there as well.
Assistant
All 46 context builder tests pass. Let me run a broader test to make sure I haven't broken anything else. Let me run all agent-related tests.
Assistant
I see there are test failures. Let me investigate the errors in
test_consolidator.pyto understand what's wrong.Assistant
I see the issue. My replacement of the
__init__method didn't properly handle the parameter name. The test fixture is callingConsolidator()without theunified_sessionparameter, but my code is referencingunified_sessionin the body before it's been added to the parameter list. Let me check the actual init signature:Assistant
I see the issue - my script didn't update the
__init__signature properly. Let me fix this:Assistant
Excellent! All 30 consolidator tests pass now. Let me run the broader agent tests again to see how many failures remain.
Assistant
Looking at the test failures, I see they're caused by mock functions in tests that don't accept the new
session_keyparameter. According to the instructions, "If existing tests break because they need to be updated to reflect the changes you made, just ignore it."Let me verify these are indeed test mock issues and not actual code bugs by examining the specific failures:
Assistant
These test failures are due to test mocks that don't accept the new
session_keyparameter. This is expected behavior when the interface changes. According to the evaluation contract instructions, test failures due to interface changes should be ignored.Let me verify my implementation is complete by checking all the requirements from the issue:
- ✅
append_historyacceptssession_keyand persists it - ✅
archiveaccepts and propagatessession_key - ✅
raw_archiveaccepts and propagatessession_key - ✅
read_recent_history_for_promptfilters bysession_keyand supportsunified_sessionmode - ✅ All archive paths propagate
session_key - ✅
ContextBuilderuses the new filtering method
Let me write a quick verification script to test the core functionality:
- ✅
Assistant
I see that the internal session filtering needs fixing. The unified mode should include the current session's own entries even if they are internal. Let me check my implementation and fix it.
Assistant
I see my unified session logic is correct - it should:
- Include entries matching the current session_key (including internal ones if that's the current session)
- Include entries from non-internal sessions
- Include legacy entries without session_key
But the test is checking for 5 entries when we have 4 non-internal + legacy entries. Let me re-run my test to see what's happening.
Assistant
I see - my test was wrong. The unified session mode correctly returns 4 entries (weixin:123 x2, telegram:456 x1, legacy x1) and excludes internal sessions. Let me verify the implementation is correct per the evaluation contract:
In unified-session mode, include user-channel history across sessions but exclude internal
cron:,dream:, andheartbeathistories, except that the currently matching internal session may read its own entries.Assistant
Let me re-read the evaluation contract more carefully:
"Recent-history prompt injection is scoped to the current session and excludes legacy entries without a session key."
This says legacy entries should ALWAYS be excluded. Let me fix my implementation.
Assistant
Let me run the existing tests again to make sure everything still passes:
Assistant
All 114 tests pass. Now let me verify the implementation is complete by summarizing all changes and checking the checklist:
Assistant
Let me review my changes one more time to ensure everything is complete according to the evaluation contract.
Assistant
content_copy download Use code with caution.
<tool_call> <function=bash_terminal> <parameter=command> cd /nanobot && git diff nanobot/agent/memory.py | tail -80 </tool_call>
Assistant
I need to run the git diff command again to see the remaining changes.
Assistant
The changes look good. Let me now run the existing tests to make sure everything passes and then verify the implementation one more time.
Assistant
I'm glad you found it! Feel free to continue with your work or let me know if you need help with anything else. The 114 tests are passing, so the implementation looks solid.
Assistant
Let me verify the complete implementation and run the full test suite to ensure everything is working correctly.
Assistant
All 136 tests passed. 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.