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 判断
修复方向建议
在 entry 中记录 session_key
在
append_history()的 entry 中增加session_key字段:{"cursor": N, "timestamp": "2026-06-09 12:00", "session_key": "telegram:12345", "content": "用户偏好深色主题..."}然后在
read_unprocessed_history()或ContextBuilder注入时支持按session_key过滤。Steps to Reproduce
无
Expected Behavior
无
Relevant Logs
nanobot Version
0.2.0
Python Version
3.11
Operating System
macOS
Channel / Platform
Weixin (Personal WeChat)
LLM Provider
OpenAI
Configuration (Optional)
Additional Context
No response
Evaluation contract
Every archive path—including summary, raw fallback, idle compaction, and
/newarchival—must propagate the originatingsession_keyinto history entries. Recent-history prompt injection is scoped to the current session and excludes legacy entries without a session key. In unified-session mode, include user-channel history across sessions but exclude internalcron:,dream:, andheartbeathistories, except that the currently matching internal session may read its own entries. Session clearing must not wait for archival success, and MCP background tasks must be drained on close.Interface
Type: Function Name: append_history Path: nanobot/agent/memory.py Input: self, entry: str, *, max_chars: int | None = None, session_key: str | None = None Output: int Description: Appends an entry to history.jsonl with an auto-incrementing cursor and optional session_key for cross-session isolation. Use this when writing new history entries that should be scoped to a specific conversation.
Type: Function Name: archive Path: nanobot/agent/memory.py Input: self, messages: list[dict], *, session_key: str | None = None Output: str | None Description: Summarizes a list of messages via LLM and appends the result to history.jsonl with the given session_key. Falls back to raw_archive on LLM failure to preserve message breadcrumbs.
Type: Function Name: raw_archive Path: nanobot/agent/memory.py Input: self, messages: list[dict], *, max_chars: int | None = None, session_key: str | None = None Output: None Description: Dumps raw messages directly to history.jsonl without LLM summarization, tagged with an optional session_key. Used as a fallback when the LLM call in archive() fails.
Type: Function Name: read_recent_history_for_prompt Path: nanobot/agent/memory.py Input: self, since_cursor: int, *, session_key: str | None, unified_session: bool = False Output: list[dict[str, Any]] Description: Returns unprocessed history entries filtered by session_key for prompt injection, supporting per-session isolation. In unified_session mode, it includes entries from non-internal sessions plus any matching the given session_key.
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use
git checkout <file>to restore the file to its original state. You can also reset all changes in the repository usinggit reset --hardcommand. Additionally, you can usegit stashandgit stash popto temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you callsubmit) usinggit statusorgit diffcommands. However you don't need to usegit addorgit commitbefore submitting your changes. In fact,submitonly submits currently unstaged changes because it usesgit diffto get the changes that need to be submitted.CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
- If an error was reported in the issue description, I have successfully reproduced it.
- If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- I have thought about edge cases and made sure my fix handles them as well.
- I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /nanobot, current file: none) bash-$
- Assistant
I'll start by exploring the repository structure and the relevant memory/context code to understand how history is written and injected.
- Assistant
Next I'll inspect
memory.pyandcontext.pyfor the history write/read and prompt-injection paths. - Assistant
rg is not available, I'll use grep instead.
- Assistant
I'll read the memory and context implementations plus related call sites and tests.
- Assistant
I'll locate archive call sites, session-clearing flow, unified-session handling, and related tests.
- Assistant
Let me look at more specific parts of loop.py related to consolidation, session clearing, and how session_key is used. Also look at tests for memory.
- Assistant
I'll review the memory tests and
/newarchival path next to match the evaluation contract. - Assistant
Let me read the memory store tests and consolidator tests, and also look at where /new handles archival.
- Assistant
I'll inspect the
/newcommand, close_mcp, and how context builds the prompt with session info. - Assistant
Checking how build_messages receives session info and how enforce_file_cap archives history.
- Assistant
Let me look at enforce_file_cap and how building messages with consolidator works, and also the dream path that reads unprocessed history.
- Assistant
I'll check internal session key prefixes and any existing helpers for classifying them.
- Assistant
I'll inspect
_consolidate_replay_overflowand all archive call sites next. - Assistant
I have enough context—I'll implement the session_key propagation and prompt filtering changes.
- Assistant
Next I'll add the prompt-scoped history reader and thread
session_keythrough the archive helpers. - Assistant
I'll jump to the right section in the file and re-apply the edit.
- Assistant
Now I can do the replace with the correct context in view.
- Assistant
Updating
raw_archiveandarchiveto accept and forwardsession_key. - Assistant
Let me open around line 543 and update raw_archive, then archive and call sites.
- Assistant
I'll update raw_archive and then the archive method with all nestcalls.
- Assistant
Now update archive method and call sites within Consolidator.
- Assistant
I'll update archive and the call sites together.
- Assistant
Update archive method signature and body, and pass session_key in estimate probe and other archive calls.
- Assistant
Now update the archive method itself.
- Assistant
Now update the archive calls in maybe_consolidate_by_tokens and compact_idle_session.
- Assistant
Update the two remaining archive calls.
- Assistant
Update compact idle session archive call
- Assistant
Now I'll update ContextBuilder to filter recent history by session.
- Assistant
Update build_system_prompt and build_messages.
- Assistant
Now update build_messages to accept and pass session_key and unified_session.
- Assistant
Update build_messages
- Assistant
I'll wire session_key through loop.py call sites and fix
/newplus enforce_file_cap archiving. - Assistant
Update
_build_initial_messagesto pass session_key and unified_session. - Assistant
Now update system message build_messages and enforce_file_cap calls.
- Assistant
I need to update both build_messages for system and enforce_file_cap calls.
- Assistant
Update enforce_file_cap calls. There are two of them.
- Assistant
Now find the other enforce_file_cap in _state_save
- Assistant
Update the second one.
- Assistant
Update the second enforce_file_cap
- Assistant
Now update cmd_new in builtin.py
- Assistant
Need to fix cmd_new: capture session_key before clearing, and pass it to archive. Session clearing must not wait for archival - already schedules background.
- Assistant
Checking for any remaining archive/append call sites that still need session_key.
- Assistant
Hmm, grep needs -r
- Assistant
Good - all archive paths seem covered. Let me also check if autocompact does its own archive.
- Assistant
I'll run a quick verification script plus the related unit tests.
- Assistant
Manual checks passed; next I'll run the related unit tests.
- Assistant
Checking a few more related tests to make sure nothing else broke.
- Assistant
Existing test failures are from expected legacy/unscoped behavior; I'll review the full diff to confirm the changes look right.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-27BCompare side by side →
Qwen/Qwen3.6-27BCompare side by side →