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 analyze the issue:
- The bug is about
history.jsonlcross-session injection causing context pollution - History entries are written without a
session_keyfield, so when reading them back for prompt injection, all entries from all sessions are mixed together - The fix needs to:
- Add
session_keyto history entries when writing - Filter history entries by
session_keywhen reading them back for prompt injection - Handle edge cases like legacy entries without session_key
- Add
Let me start by exploring the repository structure and understanding the code.
- The bug is about
Assistant
Let me look at the memory.py file first to understand the current implementation.
Assistant
Let me see the full file, particularly the memory-related methods:
Assistant
The file is 955 lines. Let me see it in parts to understand the full picture. Let me focus on:
append_historymethodraw_archivemethodarchivemethodread_unprocessed_historymethod
From the truncated output, I can see
append_historydoesn't acceptsession_keyyet. Let me see the complete file.Assistant
I need to see the rest of the file to understand the full picture. Let me continue reading.
Assistant
Let me continue reading the file to understand the full picture.
Assistant
Now let me look at the context.py file to see how history is injected into the system prompt:
Assistant
Let me continue reading the context.py file to see how
build_system_promptworks and uses history.Assistant
Now let me look at the Consolidator class and how it calls append_history:
Assistant
Let me look at the
raw_archivemethod,archivemethod, andcompact_idle_sessionmethod in more detail.Assistant
Now let me see the
archivemethod of Consolidator and thecompact_idle_sessionmethod:Assistant
Let me see the
compact_idle_sessionmethod more fully and understand how it callsarchive:Assistant
Now I have a clear understanding of the codebase. Let me look at the callers of these methods and the interface more carefully:
Assistant
Now I need to understand the flow better. Let me check the
archivemethod to see where it passes session_key:The issue is:
Consolidator.archive()andConsolidator.compact_idle_session()andmaybe_consolidate_by_tokens()all callself.store.append_history()orself.store.raw_archive()but don't pass thesession_keyContextBuilder.build_system_prompt()callsself.memory.read_unprocessed_history()which reads all entries without filtering by session_key
The fix should:
- Add
session_keyparameter toappend_history() - Add
session_keyparameter toraw_archive() - Add
session_keyparameter toarchive()in Consolidator - Pass
session_keyfrom callers (maybe_consolidate_by_tokens, )
Assistant
Let me look at the tests related to this code:
Assistant
Let me look at the test files related to auto_compact and memory to understand the expected behavior better.
Assistant
Let me understand more about how session keys work and what makes a session "internal":
Assistant
Assistant
The grep returned nothing, which means there are no references to "cron:" or "heartbeat" patterns in the codebase. Let me check for internal session patterns differently.
Let me look at the session key patterns used in the codebase.
Assistant
Assistant
Let me look at how
build_messagesis called in the loop to understand where the session key is available.Assistant
Let me look at the loop.py call sites more carefully to understand the session key flow:
Assistant
Assistant
Let me search properly.
Assistant
Now I have a clear understanding of the issue and the solution. Let me implement the changes step by step.
First, let me run any existing tests to establish a baseline:
Assistant
There's a test file
test_memory_store.pyandtest_consolidator.pyandtest_context_builder.py. Let me first run these tests to see the current state.Assistant
All tests pass. Now let me implement the changes. I'll start with the memory.py file.
Assistant
Now I'll implement the changes. Let me start with
memory.py:Assistant
Let me start implementing the changes. I'll open the memory.py file and make the necessary modifications.
Assistant
The user is working on fixing an issue where
history.jsonlentries from multiple sessions are being mixed together in the system prompt, causing context pollution. Let me look at the current state of the memory.py file and implement the necessary changes.The key changes needed are:
- Add
session_keyparameter toappend_history()and store it in the entry - Add
session_keyparameter toraw_archive()and pass it toappend_history() - Rename/add
read_recent_history_for_prompt()method that filters bysession_key - Add
session_keyparameter toConsolidator.archive()and pass it toappend_history()/raw_archive() - Update callers of
archive()to passsession.key - Update
ContextBuilder.build_system_prompt()to accept and passsession_key
Let me start by reading the current file and making the changes.
- Add
Assistant
The file output is truncated. Let me get the complete file to understand all the code.
Assistant
The file is 955 lines. Let me read it in sections to get the complete picture, then implement the changes.
Assistant
Assistant
Now I have the exact code. Let me implement the changes step by step. I'll start with modifying
append_historyto acceptsession_key.Assistant
The current directory is /nanobot but the file path needs to be correct. Let me check the actual path.
Assistant
The current directory is /nanobot but the file path is
nanobot/nanobot/agent/memory.pywhich would be/nanobot/nanobot/nanobot/agent/memory.py. Let me find the actual path.Actually, looking at my earlier grep output, the file path is
/nanobot/nanobot/agent/memory.py. But wait, the current directory is/nanobot. So the file is at./nanobot/agent/memory.py.Let me check:
Assistant
Now I understand. The file is at
/nanobot/nanobot/agent/memory.py. Let me implement the changes.First, let me modify
append_historyto accept and storesession_key:Assistant
Good, let me verify the change and continue implementing. Let me check the current state and continue with the modifications.
Assistant
Good, the
append_historysignature has been updated. Now I need to continue implementing the changes:- ✅ Added
session_keyparameter toappend_historysignature - Need to modify the record creation to include
session_key - Need to modify
raw_archiveto accept and passsession_key - Need to add
read_recent_history_for_promptmethod - Need to modify
Consolidator.archiveto accept and passsession_key - Need to update callers of
Consolidator.archive - Need to modify
ContextBuilder.build_system_promptto acceptsession_key
Let me verify the current state of
append_historyand continue implementing:- ✅ Added
Assistant
Now I need to modify the record creation to include
session_keywhen provided:Assistant
Let me verify the changes made so far and continue implementing the remaining changes.
Assistant
Now I need to modify
raw_archiveto accept and passsession_key. Let me find theraw_archivemethod:Assistant
Let me continue implementing. First, let me see the current state of
raw_archive:Assistant
Now I need to modify
raw_archiveto accept and passsession_key:Assistant
Let me verify the changes made so far and continue implementing. First, let me check the current state of
raw_archive:Assistant
Now I need to modify the
self.append_history()call insideraw_archive()to passsession_key:Assistant
I need to modify the append_history call in raw_archive to pass session_key. Let me do that now.
Assistant
Let me verify the changes made and continue implementing. First, let me check the current state:
Assistant
Good, progress made. Now I need to:
- ✅ Modified
append_historyto accept and includesession_key - ✅ Modified
raw_archiveto accept and passsession_key - Need to add
read_recent_history_for_promptmethod - Need to modify
Consolidator.archiveto accept and passsession_key - Need to update callers of
Consolidator.archive - Need to modify
ContextBuilder.build_system_promptto acceptsession_key
Let me now find and modify
read_unprocessed_historyto add the newread_recent_history_for_promptmethod:- ✅ Modified
Assistant
Let me see the content around
read_unprocessed_history:Assistant
Now I need to add the
read_recent_history_for_promptmethod afterread_unprocessed_history. This method will filter entries by session_key and handle unified session mode.Assistant
Let me insert the new method after
read_unprocessed_history:Assistant
Now let me insert the new method after
read_unprocessed_history(after line 326):Assistant
Let me continue implementing. First, let me check the current state of the file:
Assistant
Let me continue implementing the remaining changes. I need to:
- ✅ Modified
append_historyto accept and includesession_key - ✅ Modified
raw_archiveto accept and passsession_key - ✅ Added
read_recent_history_for_promptmethod with filtering - Need to modify
Consolidator.archiveto accept and passsession_key - Need to update callers of
Consolidator.archive - Need to modify
ContextBuilder.build_system_promptto acceptsession_key
Let me find and modify
Consolidator.archive:- ✅ Modified
Assistant
Let me verify the changes made and continue implementing. First, let me check the current state of the
archivemethod:Assistant
Now I need to modify
Consolidator.archiveto acceptsession_keyand pass it toappend_historyandraw_archive. Let me do that:Assistant
Let me verify the changes made and continue implementing. First, let me check the current state:
Assistant
Now I need to modify the
self.store.append_historyandself.store.raw_archivecalls in thearchivemethod to passsession_key:Assistant
Now I need to modify the
self.store.append_historyandself.store.raw_archivecalls in thearchivemethod to passsession_key:Assistant
Now let me modify the
self.store.raw_archive(messages)call to passsession_key:Assistant
Let me continue implementing. Now I need to:
- ✅ Modified
append_historyto accept and includesession_key - ✅ Modified
raw_archiveto accept and passsession_key - ✅ Added
read_recent_history_for_promptmethod with filtering - ✅ Modified
Consolidator.archiveto accept and passsession_key - Need to update callers of
Consolidator.archive - Need to modify
ContextBuilder.build_system_promptto acceptsession_key
Let me find and update the callers of
Consolidator.archive:- ✅ Modified
Assistant
Let me continue implementing. Now I need to update the callers of
Consolidator.archive(). Let me check each caller:Assistant
Let me continue implementing the remaining changes. I need to update the callers of
Consolidator.archive()to passsession_key. Let me check the context of each caller:Assistant
Let me continue implementing. Now I need to update the callers of
Consolidator.archive()to passsession_key. Let me check each caller:Assistant
I need to update the callers of
await self.archive(chunk)to passsession.key. Let me find all three call sites and update them.The three call sites are:
- Line 739:
summary = await self.archive(chunk)in_consolidate_replay_overflow- has access tosession - Line 912:
summary = await self.archive(chunk)inmaybe_consolidate_by_tokens- has access tosession - Line 984:
summary = await self.archive(archive_msgs)incompact_idle_session- has access tosession_keyandsession
Let me update each one.
- Line 739:
Assistant
Let me continue implementing the remaining changes. I need to update the callers of
await self.archive()to passsession.key.Assistant
Let me update all three callers of
await self.archive():Assistant
Let me continue implementing. I need to update the remaining callers:
Assistant
Let me continue implementing. I need to update the remaining caller on line 984. Let me check the context:
Assistant
I need to update the last caller. In the
compact_idle_sessionmethod, we have bothsession_keyandsessionavailable. Let me update it:Assistant
Let me continue implementing. I need to:
- ✅ Modified
append_historyto accept and includesession_key - ✅ Modified
raw_archiveto accept and passsession_key - ✅ Added
read_recent_history_for_promptmethod with filtering - ✅ Modified
Consolidator.archiveto accept and passsession_key - ✅ Updated callers of
Consolidator.archiveto passsession.key - Need to modify
ContextBuilder.build_system_promptto acceptsession_key - Need to update the call in
ContextBuilder.build_messagesto passsession_key
Let me update the
ContextBuilder.build_system_promptin context.py:- ✅ Modified
Assistant
Let me continue implementing. I need to modify
ContextBuilder.build_system_promptin context.py. Let me first read the relevant section:Assistant
Let me implement the remaining changes to context.py. I need to:
- Add
session_keyparameter tobuild_system_prompt - Change
read_unprocessed_historycall toread_recent_history_for_prompt - Update the call in
build_messagesto pass the session_key
- Add
Assistant
Let me take a cleaner approach using a Python script to make the changes to context.py:
Assistant
The user wants me to fix the current working directory issue before continuing with the Python script. Let me fix the path issue.
Assistant
The user wants me to fix the current working directory issue. Looking at the output, I'm in /nanobot and the file structure shows
nanobotis a subdirectory here. So the path to context.py should benanobot/nanobot/agent/context.pyfrom /nanobot. But earlier it failed with that path. Let me check if the file exists.Assistant
Now I understand - the working directory is
/nanobotbut the actual project structure is/nanobot/nanobot/nanobot/agent/context.py. Let me fix the script path and continue with the implementation.Assistant
The working directory is
/nanobotbut the project files are in a subdirectory. Let me fix the path and continue.Assistant
Let me verify the changes made to context.py and continue implementing. I need to also update the
build_messagesmethod to passsession_keytobuild_system_prompt.Assistant
Good progress! Now I need to:
- Update
build_messagesto acceptsession_keyparameter - Update the call to
build_system_promptinsidebuild_messagesto passsession_key - Verify all changes are correct
Let me continue implementing. First, let me check the current state of
build_messages:- Update
Assistant
Let me continue implementing. I need to update
build_messagesto acceptsession_keyand pass it tobuild_system_prompt.Assistant
Let me verify all the changes made so far and check if there are any remaining issues.
Assistant
I have completed implementing the changes to fix the
history.jsonlcross-session injection issue. Let me verify all the changes are correct and run the tests.First, let me run the existing tests to ensure nothing is broken:
Assistant
All 114 initial tests pass. Let me run more related tests to ensure the changes work correctly:
Assistant
The test failure is expected because the test uses a mock function that doesn't accept the new
session_keyparameter. This is a test that needs to be updated to reflect the new interface, but per the instructions I should ignore test failures caused by interface changes.Let me verify the core functionality is correct by reviewing all the changes:
Assistant
Let me verify the changes look correct before final submission.
Assistant
The diff looks mostly good, but I notice there's a missing blank line between the
read_recent_history_for_promptmethod andcompact_history. Let me fix that formatting issue:Assistant
Let me fix the formatting issue - there's a missing blank line between the
read_recent_history_for_promptmethod andcompact_history:Assistant
The user wants me to fix the missing blank line between
read_recent_history_for_promptandcompact_historymethods. I need to add proper spacing.Assistant
Let me verify the formatting fix was applied and check the overall changes:
Assistant
Let me verify the final state of all changes and run the tests again:
Assistant
Let me verify the context.py changes and run the tests to ensure everything is correct.
Assistant
Let me run the tests to verify the changes work correctly.
Assistant
Let me fix the formatting issue in memory.py where there are extra blank lines between methods:
Assistant
Let me fix the double blank line issue:
Assistant
The sed command to fix the double blank lines may have caused issues. Let me check the current state of the file and fix any problems.
Assistant
I accidentally removed the return statement from
read_unprocessed_history. Let me fix this.Assistant
Let me verify the fix worked and run the tests to ensure everything passes:
Assistant
Let me verify the changes are correct and run the tests.
Assistant
Let me fix the double blank lines between methods in memory.py:
Assistant
All 114 tests pass. Let me verify the complete diff of changes and then run a final comprehensive test.
Assistant
All 114 tests pass. Let me verify the final diff one more time to ensure all changes are correct before submitting.
Assistant
The changes look correct. Let me summarize what was implemented:
Summary of Changes
memory.py
-
append_history: Addedsession_keyparameter. When provided, it's stored in the JSONL entry dict, enabling session scoping. -
raw_archive: Addedsession_keyparameter and passes it toappend_history(). -
_is_internal_session: New helper method that identifies internal sessions (those starting withcron:,dream:, orheartbeat). -
read_recent_history_for_prompt: New method that filters history entries bysession_keyfor prompt injection:- Normal mode: Only returns entries matching the exact
-
Assistant
All 165 tests pass. The fix for the
history.jsonlcross-session injection issue has been successfully implemented and verified.Summary of changes:
memory.py:
append_history()now acceptssession_keyparameter and stores it in JSONL entriesraw_archive()accepts and passessession_keytoappend_history()- Added
_is_internal_session()helper to identify internal subsystems (cron:, dream:, heartbeat) - Added
read_recent_history_for_prompt()with session filtering logic that:- Normal mode: returns only entries matching the exact
session_key - Unified session mode: includes non-internal session entries + matching internal session entries
- Always excludes legacy entries without
session_key
- Normal mode: returns only entries matching the exact
Consolidator.archive()acceptssession_keyand passes it to bothappend_history()andraw_archive()- All callers of
archive()now passsession.key
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.