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 and understanding the codebase.
Assistant
I'll explore the repository structure first.
Assistant
The file was truncated. Let me read the full memory.py and context.py files.
Assistant
Let me view the middle and end portions of memory.py to understand the relevant functions.
Assistant
Now let me find all callers of these functions and the
/newarchival path, plus the autocompact module.Assistant
Now I have a good understanding. Let me look at the key callers:
archive()- called frommaybe_consolidate_by_tokens(line 861),_consolidate_replay_overflow(line 688),compact_idle_session(line 933), andcommand/builtin.py:215(/newarchival).raw_archive()- called fromarchive()on LLM failure.append_history()- called fromarchive()andraw_archive().read_unprocessed_history()- called fromcontext.py:99andmemory.py:414(build_dream_prompt).
Let me look at the relevant pieces:
command/builtin.py:215-/newarchival path- The
ContextBuilder.build_system_promptinjection path - The
unified_sessionconcept in loop.py
Let me look at command/builtin.py around 215.
Assistant
I'll run one command at a time. Let me look at the
/newarchival path in command/builtin.py.Assistant
Now let me look at how
build_system_promptis called from the loop and howunified_sessionandsession_keyflow into the context builder.Assistant
Now let me look at the internal session prefixes and how the loop calls
build_messageswith the session key. Let me check the loop.py around lines 1380-1460.Assistant
Now I understand the flow. Let me understand the architecture:
append_history(entry, *, max_chars=None)→ needssession_keyparamarchive(messages)→ needssession_keyparam, propagates toappend_historyraw_archive(messages, *, max_chars=None)→ needssession_keyparam, propagates toappend_historyread_recent_history_for_prompt(since_cursor, *, session_key, unified_session=False)→ new method for filtered reading
Now let me understand the callers:
-
archive()is called from:maybe_consolidate_by_tokens(line 861) - hassession.key_consolidate_replay_overflow(line 688) - hassession.keycompact_idle_session(line 933) - hassession_keyparam
Assistant
Let me check
enforce_file_capandraw_archivecallers.Assistant
Let me look at how dream is invoked and check the internal session prefixes.
Assistant
So dream uses
process_directwithephemeral=Trueandsession_key=key(a dream:... key). Whenephemeral=True,include_memory_recent_history=False(from_state_build:include_memory_recent_history=not ctx.ephemeral). So dream sessions don't include recent history in their system prompt. Good.Now let me check
process_directto understand the ephemeral flow.Assistant
Now I have a complete understanding. Let me look at the existing tests to understand the expected behavior and test patterns.
Assistant
Now let me look at the consolidator and unified_session tests.
Assistant
Let me look at the consolidator tests and how
archiveis mocked/called.Assistant
Now let me check the test for loop consolidation tokens and runner injections to understand how
build_messagesis mocked.Assistant
Let me check the runner injections test to understand how recent history injection is tested.
Assistant
Let me search for tests that exercise recent history injection in system prompt.
Assistant
Let me check
Session.clear()to ensure the key is preserved.Assistant
clear()doesn't changeself.key. Good. Now let me check the MCP background tasks draining on close, as mentioned in the contract.Assistant
close_mcpalready drains background tasks then closes MCP stacks. Now let me check tests forenforce_file_capandon_archive.Assistant
Let me look at the test_auto_compact mock to ensure changes to
compact_idle_sessiondon't break it.Assistant
I now have a thorough understanding. Let me check the
nanobot.pySDK facade and the cli/commands.py paths that might also call archive or build the prompt, to ensure I don't miss any caller.Assistant
Let me check the cli/commands.py heartbeat/cron paths to understand unified_session handling there.
Assistant
Now I have a complete understanding. Let me start making changes. First, let me open memory.py and add the internal session prefix helper and modify
append_history.Assistant
Let me add the internal session prefix constant and helper. I'll add it as a class attribute and static method on MemoryStore.
Assistant
Now let me make the edits. First, add the internal session prefix constant before the class:
Assistant
Now let me modify
append_historyto add thesession_keyparameter:Assistant
The string escaping is tricky. Let me use the
editcommand directly. First, let me find the exact line numbers.Assistant
Now let me edit the
append_historysignature and docstring:Assistant
Now let me update the
recordline to includesession_key:Assistant
Now let me add the
read_recent_history_for_promptmethod right afterread_unprocessed_history:Assistant
Now let me update
raw_archiveto add thesession_keyparameter:Assistant
The shell is interpreting the embedded syntax. Let me use the
editcommand with line range instead.Assistant
I need to add a blank line after the
raw_archivemethod. Let me fix that:Assistant
I accidentally duplicated the
logger.warningblock. Let me fix it:Assistant
There's a duplicate "Dream helpers" comment block. Let me fix it:
Assistant
Now let me update the
archivemethod to addsession_keyand propagate it. Let me find it:Assistant
There's a missing blank line between
archiveandmaybe_consolidate_by_tokens. Let me fix that:Assistant
The edit duplicated
raw_archivecall. Let me fix lines 871-875:Assistant
Now let me update the three
archivecall sites within the Consolidator to passsession_key. Let me find them:Assistant
Let me use a Python script to make these targeted replacements for the three archive call sites:
Assistant
Now let me also update
estimate_session_prompt_tokensto passsession_keytobuild_messages:Assistant
Now let me verify memory.py compiles:
Assistant
Now let me update
enforce_file_capin session/manager.py to passsession_key=self.key:Assistant
Now let me update context.py:
build_system_promptandbuild_messagesto acceptsession_keyandunified_session, and useread_recent_history_for_prompt.Assistant
Now let me update
build_messagesto accept and propagatesession_keyandunified_session:Assistant
Now let me update loop.py to pass
session_keyandunified_sessiontobuild_messages. Let me update_build_initial_messagesand its caller, and the_process_system_messagebuild_messages call.Assistant
I'll modify
_build_initial_messagesto passsession_key=session.keyandunified_session=self._unified_session:Assistant
Now let me update the
_process_system_messagebuild_messagescall (line ~1140):Assistant
Now let me update the
/newcommand in command/builtin.py to passsession_key:Assistant
I need to capture the session key before clearing, then pass it to archive. Let me update the
/newcommand. The contract says "Session clearing must not wait for archival success" - the current code already does this (clears first, schedules background archive). I just need to capture the key and pass it.Let me capture
session_key = session.keybeforesession.clear().Assistant
Now let me verify all the modified files compile:
Assistant
Now let me run the relevant tests to verify my changes don't break anything:
Assistant
All passing. Now let me run more tests:
Assistant
A test patches
consolidator.archivewith a function that doesn't acceptsession_key. Let me look at this test:Assistant
This test patches
archivewith a function that doesn't accept the newsession_keykwarg — this is an existing test that needs updating to reflect the new signature (which the contract explicitly requires). Per the instructions, I should not modify it and the evaluation won't count it. Let me run the rest of the tests to confirm no other unexpected breakage:Assistant
Only one test fails, purely because its mock of
archivedoesn't accept the newsession_keykwarg — this is the expected signature change required by the contract. Let me search broadly for any other tests that patch these functions with incompatible signatures:Assistant
Let me check the custom summarize functions in test_consolidate_offset.py:
Assistant
These custom summarize functions also don't accept
session_key. They're existing tests that need updating to reflect the new signature (which the contract requires). Let me run the broader agent test suite to confirm all failures are purely due to the mock-signature issue, not real bugs:Assistant
All 4 failures are due to test mocks not accepting the new
session_keykwarg — these are tests that need updating to reflect the new signature. Notablytest_close_mcp_drains_background_tasksis referenced by the contract. Let me examine it closely to confirm the breakage is purely the mock signature, not the MCP drain logic:Assistant
Confirmed — the breakage is purely the mock signature (
_slow_summarize(_messages)doesn't acceptsession_key); the MCP drain logic is unchanged and correct. This is a test that needs updating to reflect the new signature, which I'm not permitted to modify.Let me check whether any tests patch
build_messages/build_system_prompt/read_unprocessed_historywith incompatible signatures:Assistant
These use
MagicMock/**kwargswhich accept any kwargs, so they're fine. Now let me write a reproduction script to verify the fix works as the contract intends:Assistant
All reproduction checks pass. Now let me verify the
archiveandraw_archivepropagatesession_key, and the/newarchival path:Assistant
All archive paths propagate
session_key. Now let me verify the/newarchival path and the loop integration with a quick check ofprocess_directflow. Let me run a broader set of tests to confirm only the expected mock-signature failures occur:Assistant
6 failures. 5 are the expected mock-signature issues. Let me verify the 6th (
test_mcp_presets_api) is unrelated to my changes by checking it on the clean repo:Assistant
The
test_mcp_presets_apifailure is pre-existing (fails on the clean repo too) — unrelated to my changes. So my changes only cause the 5 expected mock-signature failures, all of which are tests that need updating to reflect the newarchive(*, session_key)signature required by the contract.Let me review the complete diff to ensure correctness:
Assistant
The diff looks complete and correct. Let me verify the
process_directpath flows the session_key correctly:Assistant
The
process_directpath flows session_key correctly. Cron/heartbeat (ephemeral=False) read their own scoped entries; dream (ephemeral=True) excludes recent history. Let me do a final check for any other callers ofraw_archive/append_history/read_unprocessed_historyI might have missed:Assistant
Line 485 is
build_dream_promptwhich correctly uses the globalread_unprocessed_history(Dream sees all entries across sessions). Line 376 is internal toread_recent_history_for_prompt. Allappend_history/raw_archivecallers now passsession_key.Let me check the webui/cli paths that might call
process_director build prompts with unified_session to ensure nothing is missed:Assistant
All callers are covered. Let me clean up temp scripts and run a final confirmation of the directly-affected unit tests:
Assistant
All 320 directly-relevant tests pass. Let me run the two test files that have the expected mock-signature failures one more time to confirm the failures are exclusively the mock-signature issue (not other bugs):
Assistant
All 5 failures are the expected mock-signature issues (the tests mock
archivewith functions that don't accept the newsession_keykwarg). These are tests that need updating to reflect the new signature required by the contract — per the instructions, the evaluation won't count them.Let me do a final import sanity check and review the full diff one more time:
Assistant
All interface signatures exactly match the contract. Let me verify the git status to ensure only the intended files are modified:
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.