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 understanding the issue and the repository structure. The issue is about
history.jsonlhaving cross-session injection that causes context pollution. The fix involves:- Adding
session_keyfield to history entries - Filtering history by
session_keywhen injecting into prompts - Supporting unified-session mode
- Excluding internal sessions (cron:, dream:, heartbeat) in unified-session mode
Let me first explore the repository structure to understand the codebase.
- Adding
Assistant
Let me explore the nanobot directory structure, especially the memory.py file mentioned in the issue.
Assistant
Good, I can see memory.py and context.py. Let me first examine the memory.py file to understand the current implementation.
Assistant
Let me read the memory.py file to understand the current implementation:
Assistant
Let me continue reading more of the memory.py file to understand the append_history and related functions:
<tool_call> <function=bash_terminal> <parameter=command> sed -n '200,400p' /nanobot/nanobot/agent/memory.py </tool_call>
Assistant
Let me continue reading more of the memory.py file to understand the append_history and related functions:
Assistant
Let me continue reading the memory.py file to see the Consolidator class and the archive method:
<tool_call> <function=bash_terminal> <parameter=command> sed -n '400,600p' /nanobot/nanobot/agent/memory.py </tool_call>
Assistant
I need to continue reading more of the memory.py file to understand the Consolidator class and how entries are written to history.
Assistant
Let me continue reading the Consolidator class to see the archive method and understand how entries are being written:
Assistant
Let me continue reading the rest of the memory.py file to see how archive is being called with session_key:
<tool_call> <function=bash_terminal> <parameter=command> sed -n '800,955p' /nanobot/nanobot/agent/memory.py </tool_call>
Assistant
I need to continue reading the rest of memory.py. Let me get lines 800-955 to see the complete implementation.
Assistant
Let me continue reading to see the remaining content. I have a good understanding of the memory.py structure now. Let me now check the context.py file to see how
build_system_promptworks and how it reads history.<tool_call> <function=bash_terminal> <parameter=command> cat /nanobot/nanobot/agent/context.py </tool_call>
Assistant
Let me use the proper function call to view the context.py file.
Assistant
Now I have a clear picture of the issue. Let me check the interface specification again and understand what needs to be changed:
append_history(self, entry: str, *, max_chars: int | None = None, session_key: str | None = None)- needs to acceptsession_keyarchive(self, messages: list[dict], *, session_key: str | None = None)- needs to acceptsession_keyraw_archive(self, messages: list[dict], *, max_chars: int | None = None, session_key: str | None = None)- needs to acceptsession_keyread_recent_history_for_prompt(self, since_cursor: int, *, session_key: str | None, unified_session: bool = False)- new method
Let me now check how the archive method is called to understand what changes need to be made in other files. Let me search for calls to archive():
<tool_call> <function=bash_terminal> <parameter=command> grep -rn ".archive(" /nanobot/nanobot/agent/ --include="*.py" </tool_call>
Assistant
Let me search for calls to archive() to understand how it's being called in the codebase.
Assistant
Let me continue investigating where archive() is called. I see it's called in memory.py at lines 688, 861, and 933. Let me also check if there are calls from other files, especially in loop.py where consolidation happens.
Assistant
Let me search for where the consolidation is triggered to understand the full flow.
<tool_call> <function=bash_terminal> <parameter=command> grep -rn "maybe_consolidate|compact_idle" /nanobot/nanobot/ --include="*.py" | grep -v "test" </tool_call>
Assistant
Let me try a different approach and search for consolidation-related function calls.
Assistant
Let me check how the consolidation is triggered in loop.py and what session context is available there:
Assistant
Now let me check how the session key is available at these call sites. I need to understand how to pass the session_key to the archive function.
Assistant
I can see the session context is available. Let me now look at the autocompact.py to see how compact_idle_session is called:
Assistant
Now I have a better understanding of the codebase. Let me create a plan:
- Modify
append_history()to accept asession_keyparameter and store it in the entry - Modify
archive()to accept and passsession_keytoappend_history() - Modify
raw_archive()to accept and passsession_keytoappend_history() - Add
read_recent_history_for_prompt()method toMemoryStorethat filters entries bysession_keyand supportsunified_sessionmode - Modify
ContextBuilder.build_system_prompt()to use the new method - Update all callers of
archive()andcompact_idle_session()to passsession_key
Let me first look at the test files to understand the expected behavior better:
<tool_call> <function=bash_terminal> <parameter=command> find /nanobot/tests -name "*.py" | xargs grep -l "memory|history" 2>/dev/null | head -10 </tool_call>
- Modify
Assistant
Let me look at the tests directory structure to understand the testing approach.
Assistant
Let me check if there's a memory-specific test file:
<tool_call> <function=bash_terminal> <parameter=command> ls -la /nanobot/tests/agent/ </tool_call>
Assistant
Let me list the agent tests directory properly.
Assistant
Good, there's a test_memory_store.py file. Let me examine it to understand how the memory store is tested:
<tool_call> <function=bash_terminal> <parameter=command> cat /nanobot/tests/agent/test_memory_store.py </tool_call>
Assistant
I need to use the bash_terminal function to read the test file. Let me use the proper function call.
Assistant
Now let me look at the test_unified_session.py to understand the expected behavior for unified session mode:
<tool_call> <function=bash_terminal> <parameter=command> cat /nanobot/tests/agent/test_unified_session.py </tool_call>
Assistant
I need to use the bash_terminal tool properly. Let me use it to cat the file.
Assistant
Now I have a good understanding of the codebase. Let me now create a plan to fix the issue:
Plan:
- Modify
MemoryStore.append_history(): Addsession_keyparameter and include it in the JSON entry - Modify
MemoryStore.read_unprocessed_history()or create newread_recent_history_for_prompt(): Filter bysession_keyand supportunified_sessionmode - Modify
Consolidator.archive(): Addsession_keyparameter and pass it toappend_history() - Modify
Consolidator.raw_archive(): Addsession_keyparameter and pass it toappend_history() - Modify
ContextBuilder.build_system_prompt(): Use the new filtered method - Update all callers of
archive()andcompact_idle_session(): Pass thesession_key
Let me start by implementing these changes. First, let me read more of the memory.py file to understand the full structure better, and then I'll create the modified version.
- Modify
Assistant
I need to use bash_terminal to find the line numbers.
Assistant
Now let me read the exact signature and implementation of the archive method to understand what changes need to be made:
<tool_call> <function=bash_terminal> <parameter=command> sed -n '740,790p' /nanobot/nanobot/agent/memory.py </tool_call>
Assistant
I need to view the exact archive method implementation to understand what needs to be changed.
Assistant
Now I have a clear understanding of what needs to be changed. Let me implement the fix step by step.
First, I'll modify
MemoryStore.append_history()to accept asession_keyparameter:Assistant
Let me look at the append_history method and understand its current implementation better:
Assistant
Now I have a clear understanding. Let me start implementing the fix step by step. I'll first modify the
MemoryStore.append_history()method to accept asession_keyparameter:Assistant
Now I have a clear understanding of the code. Let me implement the fix step by step.
Step 1: Modify
MemoryStore.append_history()to acceptsession_keyparameterAssistant
Assistant
I need to run the bash_terminal command with the proper syntax. Let me do that.
Assistant
Now I need to modify the
ContextBuilder.build_system_prompt()method to use the newread_recent_history_for_prompt()method. Let me update context.py:Assistant
Let me verify the changes I've made and then check the places where
archive()is called within the Consolidator class to ensuresession_keyis passed:Assistant
Let me check the context around those calls to understand how to pass session_key:
Assistant
Let me check the context around line 688 and 861 where archive() is called:
Assistant
Let me check the exact location of archive() calls and their context:
Assistant
Let me get a different line range to find the archive() call at line 688.
Assistant
The archive call must be further down. Let me search for the exact line:
Assistant
Let me continue to find the archive call:
<tool_call> <function=bash_terminal> <parameter=command> sed -n '755,795p' /nanobot/nanobot/agent/memory.py </tool_call>
Assistant
Let me continue searching for the archive calls and their context.
Assistant
Now I can see the first archive call is at line 763 in
_consolidate_replay_overflow. This method already has access tosession.key. Let me update all archive calls in the memory.py file to pass the session_key parameter.Assistant
Let me continue viewing the archive calls and their context.
Assistant
Let me now update all the archive() calls in memory.py to pass the session_key:
Assistant
Now I need to update the
_consolidate_replay_overflowmethod to also passsession_keywhen it callsarchive(). Let me check the current state:<tool_call> <function=bash_terminal> <parameter=command> grep -n "await self.archive" /nanobot/nanobot/agent/memory.py </tool_call>
Assistant
Let me verify that all archive calls have been updated:
Assistant
Great! All archive calls have been updated. Now I need to check the context.py file to verify the history reading code is correct. Let me also check if we need to update the command/builtin.py file for the /new command that schedules archive calls.
Assistant
Let me check the context of this call in builtin.py to see if it needs to be updated:
Assistant
I see that the
/newcommand also callsarchive(). I need to update this to passsession_key:Assistant
Now let me also check for any other archive calls in the codebase:
Assistant
Now I need to check for any other places where raw_archive or append_history might be called directly:
<tool_call> <function=bash_terminal> <parameter=command> grep -rn ".raw_archive|.append_history" /nanobot/nanobot/ --include="*.py" | grep -v test | grep -v ".pyc" </tool_call>
Assistant
Let me continue searching for other calls to raw_archive and append_history to ensure they all pass session_key when needed.
Assistant
I see that
raw_archiveis called from loop.py as a callback toenforce_file_cap. Let me check the context of these calls to see if they need to be updated:Assistant
Let me continue checking more lines:
<tool_call> <function=bash_terminal> <parameter=command> sed -n '1485,1510p' /nanobot/nanobot/agent/loop.py </tool_call>
Assistant
I need to view the loop.py file to see how raw_archive is called as a callback. Let me check the context of line 1490.
Assistant
I see that
raw_archiveis passed as a callback toenforce_file_cap. Let me check how that method is defined and if it passes session_key:Assistant
Let me fix the grep command to search recursively:
Assistant
Let me check how enforce_file_cap is defined and used:
Assistant
I see that
enforce_file_capcallson_archive(archive_chunk)without passingsession_key. I need to modify this to pass the session key. Let me check the signature and update both theenforce_file_capmethod and ensure theraw_archivemethod can handle the session_key parameter:Assistant
I need to update
enforce_file_capto passsession_keywhen callingon_archive. Let me modify this file:Assistant
Now let me also verify that the raw_archive method in memory.py is properly defined. Let me also check for any other places that might call archive or raw_archive with the old signature:
Assistant
Now I see that
raw_archiveis being passed as a callback without a session_key. Theenforce_file_capmethod I just modified should now pass the session_key, but the callback signature needs to accept it. Let me verify that theraw_archivemethod has the correct signature:<tool_call> <function=bash_terminal> <parameter=command> sed -n '550,580p' /nanobot/nanobot/agent/memory.py </tool_call>
Assistant
Let me view the raw_archive method to verify its signature:
Assistant
The
raw_archivemethod now has thesession_keyparameter. However, I notice that theenforce_file_capmethod is passing the callbackon_archive(self.context.memory.raw_archive)without a wrapper that would handle the session_key parameter. Sinceraw_archiveis now defined withsession_keyas a keyword-only argument, it should work with the new signature fromenforce_file_cap.Let me verify the flow by checking how
enforce_file_capcallson_archive:Assistant
The
enforce_file_capmethod now passessession_key=self.keyto theon_archivecallback. Sinceraw_archiveacceptssession_keyas a keyword-only argument, this should work correctly.Now let me run the tests to verify my changes don't break anything. First, let me check if there are any syntax errors in the modified files:
Assistant
Good, no syntax errors in memory.py. Let me check the other files:
Assistant
Great, no syntax errors in any of the modified files. Now let me run the existing tests to ensure my changes don't break anything:
Assistant
All tests in test_memory_store.py passed. Now let me run the tests related to consolidation:
Assistant
All tests in test_consolidator.py passed. Let me now run more tests related to the context builder:
Assistant
All context builder tests passed. Now let me run the unified session tests to verify those are also working:
<tool_call> <function=bash_terminal> <parameter=command> cd /nanobot && python3 -m pytest tests/agent/test_unified_session.py -v 2>&1 | head -100 </tool_call>
Assistant
Let me run the unified session tests to verify those are also working.
Assistant
All unified session tests passed. Now let me run the auto_compact tests to ensure they pass as well since they also interact with the memory system:
<tool_call> <function=bash_terminal> <parameter=command> cd /nanobot && python3 -m pytest tests/agent/test_auto_compact.py -v 2>&1 | head -100 </tool_call>
Assistant
Let me run the auto_compact tests.
Assistant
All auto_compact tests passed. Now let me also run the command tests to ensure the /new command works properly with the session_key:
<tool_call> <function=bash_terminal> <parameter=command> cd /nanobot && python3 -m pytest tests/agent/test_onboard_logic.py -v -k new 2>&1 | head -80 </tool_call>
Assistant
Let me run the onboard logic tests to ensure the /new command works properly.
Assistant
Let me check the current state of the context.py file to ensure the changes are correct:
Assistant
Let me check the history section of the context.py file:
<tool_call> <function=bash_terminal> <parameter=command> sed -n '95,115p' /nanobot/nanobot/agent/context.py </tool_call>
Assistant
Let me check the history section of the context.py file to see if my changes were applied correctly.
Assistant
I see that my patch to context.py didn't work correctly. Let me fix this by directly editing the file:
Assistant
Let me verify the change was applied:
<tool_call> <function=bash_terminal> <parameter=command> sed -n '98,100p' /nanobot/nanobot/agent/context.py </tool_call>
Assistant
Let me verify the change was applied by checking the context.py file.
Assistant
The change was applied successfully. Now let me verify that the context.py file still works correctly:
<tool_call> <function=bash_terminal> <parameter=command> python3 -c "import ast; ast.parse(open('/nanobot/nanobot/agent/context.py').read())" </tool_call>
Assistant
Let me check if the context.py file has correct syntax.
Assistant
Now let me run the tests again to verify the context.py changes work:
<tool_call> <function=bash_terminal> <parameter=command> cd /nanobot && python3 -m pytest tests/agent/test_context_builder.py -v 2>&1 | tail -30 </tool_call>
Assistant
I need to run the tests again to verify the context.py changes work correctly.
Assistant
All tests still pass. Now let me also verify the memory.py changes are correct by checking the new
read_recent_history_for_promptmethod:<tool_call> <function=bash_terminal> <parameter=command> grep -n "def read_recent_history_for_prompt" /nanobot/nanobot/agent/memory.py </tool_call>
Assistant
Let me check if the
read_recent_history_for_promptmethod exists in memory.py.Assistant
Let me verify the
read_recent_history_for_promptmethod is correctly implemented:Assistant
The
read_recent_history_for_promptmethod is implemented correctly. Now let me write a simple test script to verify that the session isolation works correctly:Assistant
I see the issue. The
read_recent_history_for_promptmethod is not correctly filtering internal sessions when the session_key matches. The problem is that when we add cron entries, they are being included even when the session_key doesn't match. Let me fix the test to be more accurate:Assistant
I see the issue. When the
session_keyis provided in unified mode, the method is including all entries from the given session_key, not just the internal session entries. Let me fix the logic:Assistant
I see the issue. When
session_keyis provided in unified mode, the code is supposed to filter to only include entries from that specific session (either internal or external). Let me fix the logic:Assistant
Now let me run the test again:
Assistant
I see the issue. When
session_keyis provided in unified mode, we should still filter to only entries matching that specific session_key. Let me review the logic again:Assistant
Assistant
Let me check the issue more carefully. The problem is that when
session_keyis provided in unified mode, we should filter to only entries from that specific session_key. Let me fix this properly.Assistant
Now I see the issue - when
session_keyis provided in unified mode, the current logic still includes all non-internal sessions. Based on the specification, ifsession_keyis provided, we should filter to only that specific session. Let me update the logic:Assistant
Let me re-read the specification. According to 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."So in unified mode:
- Include all non-internal session entries (e.g., telegram:, wechat:, etc.)
- Exclude internal session entries (cron:, dream:, heartbeat:) UNLESS the current
session_keymatches the internal session
But when a specific
session_keyis provided in unified mode, I think we should filter to only that specific session, not all non-internal sessions. Let me re-read the issue description again to understand the expected behavior better.Actually, looking at the issue more carefully:
"In unified-session mode, include user-channel history across sessions but exclude internal
cron:,dream:, and histories, except that the currently matching internal session may read its own entries."Assistant
The test passes now. The unified session mode behavior is:
- Include all non-internal session entries (e.g., telegram:, wechat:)
- Exclude internal session entries (cron:, dream:, heartbeat:) UNLESS the current
session_keymatches the internal session
Now let me run the existing tests to verify everything still works:
Assistant
All tests pass. Let me also run a broader set of tests to make sure the changes don't break anything else:
Assistant
All tests pass. Let me now verify the changes by running a broader test to ensure the implementation is complete:
Assistant
I see some test failures. The issue is that the tests mock the
archivemethod and don't expect thesession_keyparameter. Let me check these failing tests to understand what needs to be fixed:Assistant
Let me check the test for the archive method:
Assistant
I see the issue. The tests are mocking the
archivemethod with a function that doesn't accept thesession_keyparameter. The tests need to be updated to accept this parameter, or I need to make thesession_keyparameter optional in a way that doesn't break the mocks.Actually, looking more carefully at the error:
TypeError: test_preflight_consolidation_before_llm_call.<locals>.track_consolidate() got an unexpected keyword argument 'session_key'The test's
track_consolidatefunction only acceptsmessagesas a parameter. But the actualarchivemethod signature now has*, session_key: str | None = None, which means it should accept the keyword argument.The issue is that the mock function doesn't accept
**kwargsor thesession_keykeyword argument. This is actually a test issue - the tests are mocking the archive method in a way that's incompatible with the new signature.However, according to the evaluation contract:
Assistant
I need to understand the full extent of changes and make sure the implementation is correct according to the specification. Let me review the changes and run a few more tests.
<tool_call> <function=bash_terminal> <parameter=command> cd /nanobot && git diff HEAD -- nanobot/agent/memory.py | head -150 </tool_call>
Assistant
Let me check the git diff to see the changes I made to memory.py.
Assistant
I see there's a typo in the log message. Let me fix that:
Assistant
Now let me also check the diff for context.py and command/builtin.py:
Assistant
Now let me check the diff for command/builtin.py:
Assistant
Now let me check the diff for session/manager.py:
Assistant
The changes look correct. Now let me run the failing tests to understand why they fail and verify the implementation is correct. The failing tests are mocking the
archivemethod without accepting thesession_keyparameter. According to the evaluation contract:"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 not modify the tests. But let me verify the implementation is correct by checking if the failing tests are related to my changes.
Let me run the tests that are failing to understand the issue better:
Assistant
As expected, the failing tests are due to mocking the
archivemethod without accepting thesession_keyparameter. This is a test issue, not a code issue. According to the evaluation contract:"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 these test failures are expected and acceptable.
Let me now verify the implementation is complete by checking if I've covered all the required functionality from the evaluation contract:
- ✅
append_history()acceptssession_keyparameter - ✅
archive()acceptssession_keyparameter - ✅
raw_archive()acceptssession_keyparameter - ✅
read_recent_history_for_prompt()filters bysession_keyand supportsunified_sessionmode - ✅ All callers of
archive()pass
- ✅
Assistant
Let me continue to search for other archive or raw_archive calls that might need to be updated.
Assistant
The
enforce_file_capcalls in loop.py passraw_archiveas a callback. I already updatedenforce_file_capin session/manager.py to passsession_key=self.keyto the callback. Let me verify this is correct.<tool_call> <function=bash_terminal> <parameter=command> sed -n '375,390p' /nanobot/nanobot/session/manager.py </tool_call>
Assistant
Let me verify the
enforce_file_capimplementation in session/manager.py to ensure the session_key is being passed correctly.Assistant
The implementation is correct. The
enforce_file_capmethod now passessession_key=self.keyto theon_archivecallback.Now let me verify that all the requirements from the evaluation contract are met:
-
All archive paths propagate
session_key: ✅Consolidator.archive()- now accepts and passessession_keyConsolidator.raw_archive()- now accepts and passessession_keyMemoryStore.append_history()- now accepts and storessession_keyMemoryStore.raw_archive()- now accepts and passessession_key
-
Recent-history prompt injection is scoped to the current session: ✅
-
Assistant
All the tests that don't mock
archive()pass. The failing tests are those that explicitly mock thearchivemethod without accepting thesession_keyparameter, which is expected behavior after my changes.Let me create a summary of the changes I made:
Summary of Changes
1.
nanobot/agent/memory.pyappend_history(): Added parameter. The is now stored in the JSONL entry when provided.
Assistant
All the consolidation tests pass. Let me now run the session manager tests to ensure they work correctly:
Assistant
The implementation is complete. Let me provide a final summary of the changes made:
Summary of Changes
The issue was that
history.jsonlentries were not scoped to their originating sessions, causing cross-session context pollution when injecting recent history into the system prompt.Changes Made:
-
nanobot/agent/memory.py:append_history(): Addedsession_keyparameter to store session-scoped entriesraw_archive(): Addedsession_keyparameterread_recent_history_for_prompt(): New method that filters entries bysession_keyand supportsunified_sessionmodearchive(): Addedsession_keyparameter and updated all callers to pass it
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.