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.jsonlentries being cross-session injected, causing context pollution. - The
Consolidator.archive()writes entries without asession_keyfield. - When
ContextBuilder.build_system_prompt()reads recent history, it doesn't filter by session, so entries from all sessions get mixed into the current session's prompt.
The fix involves:
- Adding
session_keyto history entries when they're written - Filtering history reads by
session_keyinContextBuilder - Supporting unified-session mode where non-internal sessions can read each other's history
Let me start by exploring the repository structure and understanding the code.
- The bug is about
Assistant
Let me explore the memory.py and context.py files, which are the main files involved in this issue.
Assistant
Let me read the main files: memory.py and context.py.
Assistant
The output got truncated. Let me read the file in sections to get the full picture.
<tool_call> <function=bash_terminal> <parameter=command> cat /nanobot/nanobot/agent/memory.py | head -200 </tool_call>
Assistant
The user wants me to read the memory.py file in sections. Let me use the bash terminal to view the file content.
Assistant
The user wants me to read the memory.py file in sections to understand the code structure before making changes.
Assistant
Let me continue reading the memory.py file to understand the full structure.
Assistant
Let me continue reading memory.py to see more of the code, especially the read_unprocessed_history method and how it's used.
Assistant
Let me continue reading to see the Consolidator.archive() and raw_archive methods, as well as the rest of the file.
Assistant
Let me continue reading memory.py from line 800 to the end.
Assistant
Now let me read the context.py file to understand how
ContextBuilder.build_system_prompt()uses the history.Assistant
Now let me look at the existing tests to understand what's expected:
Assistant
Let me check how sessions and consolidation are called in the runner/loop files:
Assistant
Now I understand the codebase. Let me analyze what needs to change:
append_historyneeds to accept asession_keyparameter and include it in the entryraw_archiveneeds to passsession_keythrough toappend_historyConsolidator.archive()needs to accept and passsession_keyto bothappend_historyandraw_archiveread_unprocessed_historyneeds to filter bysession_keybuild_system_promptinContextBuilderneeds to filter history entries by session key- In unified-session mode, include entries from non-internal sessions but exclude internal ones (cron:, dream:, heartbeat)
- Legacy entries without session_key should be excluded
Let me trace the call paths:
Write path:
- → and
Assistant
I need to trace the call paths properly to understand how the Consolidator is invoked with session keys.
Assistant
Now I have a good understanding of the codebase. Let me trace through the key call paths and then implement the fix.
Summary of what needs to change:
append_history— addsession_keyparameter, write it into the JSON entryraw_archive— passsession_keythrough toappend_historyConsolidator.archive— accept and propagatesession_keyread_unprocessed_historyor a new method — filter bysession_key, supporting unified-session modeContextBuilder.build_system_prompt— pass session key when reading history- Update all callers of
append_history,raw_archive, andarchiveto passsession_key
Let me look at the callers more carefully:
Assistant
The user wants me to trace all the call paths to understand how session keys need to propagate through the codebase. Let me look at the callers of
append_historyandraw_archive, and the callers ofConsolidator.archivein more detail.Assistant
Let me trace the call paths more carefully. The key calls to
append_historyandraw_archiveare:-
In
Consolidator.archive():self.store.append_history(summary, max_chars=_ARCHIVE_SUMMARY_MAX_CHARS)(line 774)self.store.raw_archive(messages)(line 778)
-
In
loop.py:session.enforce_file_cap(on_archive=self.context.memory.raw_archive)(lines 1166, 1490)
-
Consolidator.archiveis called from:_consolidate_replay_overflow(line 688)maybe_consolidate_by_tokens(line 861)compact_idle_session(line 933)command/builtin.py:215—/newarchival
Let me check how
maybe_consolidate_by_tokensandcompact_idle_sessionare called to understand how to get the session key.-
Assistant
Now I have a full understanding of the codebase. Let me implement the fix step by step.
My plan:
- Modify
append_historyto accept and writesession_keyinto entries - Modify
raw_archiveto accept and passsession_key - Modify
Consolidator.archiveto accept and propagatesession_key - Add
read_recent_history_for_promptmethod to MemoryStore that filters by session - Modify
ContextBuilder.build_system_promptto use the filtered method - Update all callers to pass
session_key
Let me start implementing:
- Modify
Assistant
Now I have a clear understanding of the code. Let me implement the fix step by step.
Plan:
- Add
session_keyparameter toappend_history()and write it into the entry - Add
session_keytoraw_archive()and pass it through - Add
session_keytoConsolidator.archive()and pass it through - Add
read_recent_history_for_prompt()method to MemoryStore that filters by session_key with unified-session support - Update
ContextBuilder.build_system_prompt()to use the new method - Update all callers to propagate session_key
Let me start:
- Add
Assistant
I'll implement the fix step by step. Let me start by modifying
append_historyto accept and writesession_key:Assistant
Let me fix the grep command:
Assistant
Now I have a clear understanding of the codebase. Let me implement the fix step by step.
Step 1: Modify
append_historyto accept and writesession_keyAssistant
Let me use the correct edit syntax with proper escaping:
Assistant
The user wants me to use the
editcommand with a different syntax. Let me look at the special commands available:The
editcommand format is:edit LINE_RANGE=<start_line>:<end_line> [REPLACEMENT_TEXT]or with heredoc:
edit 1:1 << 'EOF' Line1 Line2 EOFLet me try using the heredoc syntax properly.
Assistant
Let me try a different approach - I'll use a Python script to make the edits:
Assistant
Good, the first steps were applied. Let me verify and continue with the remaining changes.
Assistant
Good, the first changes are applied. Now let me continue with updating
Consolidator.archive()and the other methods.Assistant
I need to continue with the remaining modifications. Let me update the script to handle the Consolidator.archive() method and the rest of the changes.
Assistant
Let me create a comprehensive Python script to apply all remaining changes:
Assistant
Good, now let me add the
read_recent_history_for_promptmethod and update thebuild_system_prompt:Assistant
Let me find the exact line numbers for
read_unprocessed_historyso I can add the new method near it.Assistant
Let me continue adding the
read_recent_history_for_promptmethod:Assistant
Good. Now let me update the
ContextBuilder.build_system_promptmethod to use the new filtered method:Assistant
I need to update the ContextBuilder.build_system_prompt method to use read_recent_history_for_prompt with session_key filtering. Let me find the exact lines to modify.
Assistant
The user wants me to update the
build_system_promptmethod in context.py to useread_recent_history_for_promptwith session_key filtering. I need to:- Add a
session_keyparameter tobuild_system_prompt - Change the call from
read_unprocessed_historytoread_recent_history_for_prompt - Also update
build_messagessince it callsbuild_system_prompt
Let me do this step by step.
- Add a
Assistant
Good. Now let me update
build_messagesin context.py to pass session_key through, and also update the callers.Assistant
Let me look at the build_messages method more closely to understand what parameters I need to add and update.
Assistant
Now I need to update all the callers of
build_system_promptandbuild_messagesto passsession_key. Let me find them:Assistant
Let me check the callers in loop.py to update them properly:
Assistant
I need to continue updating the callers in loop.py. Let me first check the other caller location at line 1140.
Assistant
I need to update the callers in loop.py to pass
session_key. Let me look at the broader context:Assistant
I need to update the callers in loop.py. Let me trace the full call paths to understand where
session.keyis available.Assistant
Let me trace the callers more carefully. I need to see the full call chains and update them to pass
session_key:Assistant
I need to update the callers in loop.py to pass
session_keyandunified_session. Let me trace the callers more carefully and update them.Assistant
Let me check for the
unified_sessionconcept in the codebase:Assistant
I need to update the callers in loop.py. Let me check the full context of the callers and update them:
Assistant
Now let me update the callers in loop.py:
Assistant
Let me check for remaining callers that need to be updated, especially
enforce_file_capand the/newarchival:Assistant
Let me check the
enforce_file_capcalls that passraw_archiveas a callback:Assistant
Let me continue with the remaining changes. I need to update the
enforce_file_capcalls and thesession.enforce_file_capmethod.Assistant
I need to update the
enforce_file_capmethod to passsession.keythrough toon_archive, and update the callers in loop.py. Let me also check the/newarchival call.Assistant
I need to update
enforce_file_cap, the callers in loop.py, and the/newarchival. Let me continue:Assistant
Let me check for remaining callers and verify the code compiles:
Assistant
Let me continue checking the syntax of other modified files and look for remaining callers that need to be updated.
Assistant
I need to check the syntax of the remaining modified files and look for any remaining callers that need to be updated. Let me also verify that all the changes are correct by checking the diff.
Assistant
Let me continue checking the syntax of the remaining modified files and look for any remaining callers that need to be updated. I also need to check for any remaining callers of
append_history,raw_archive,archive, andbuild_messagesthat might need updating.Assistant
The user wants me to continue checking for remaining callers and verify the changes. Let me check the syntax of builtin.py and look for any remaining callers that need to be updated.
Assistant
The user wants me to continue checking for remaining callers and verify the changes are complete. Let me search for any remaining callers that might need to be updated to pass
session_key.Assistant
Good, all files parse correctly. Now let me check for any remaining callers that need updating and run tests.
Assistant
All callers are now properly updated. The
enforce_file_capcalls in loop.py passraw_archiveas a callback, andenforce_file_capinternally passessession_key=self.keyto it. Let me verify by checking the test files and running them:Assistant
All 30 consolidator tests pass. Let me now run the context builder tests and other related tests:
Assistant
The user wants me to run more tests to verify the changes are complete. Let me run the memory store tests and other related tests. I also need to check for any remaining callers that need to be updated.
Assistant
All tests pass. Let me now run the unified session tests and other related tests to make sure the changes work correctly:
Assistant
All unified session tests pass too. Let me now write a reproduction script to verify the fix works correctly for the specific issue described:
Assistant
All my custom tests pass. Let me run the full agent test suite to make sure nothing is broken:
Assistant
Assistant
Let me search for remaining callers of build_system_prompt and build_messages to ensure I haven't missed any.
Assistant
Let me verify all callers have been properly updated:
Assistant
Line 313 is just passing the
build_messagesfunction as a reference to the Consolidator, not calling it directly. This is fine.All callers have been properly updated. Let me verify the changes are complete by looking at the git diff:
Assistant
Let me review the full diff to make sure all changes are correct before submitting.
Assistant
I have completed the implementation and verified it works correctly. Let me submit the changes.
Assistant
The user wants me to submit my changes. Let me call the submit command correctly.
Assistant
The user wants me to submit my changes. Let me use the submit tool correctly.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.