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 exploring the repository structure and understanding the codebase.
Assistant
The file is truncated. Let me see the full file, especially the parts around append_history, raw_archive, read_unprocessed_history, and the Consolidator class.
Assistant
Now let me look at context.py:
Assistant
Now let me find all callers of
archive,raw_archive,append_history, andbuild_system_prompt:Assistant
Let me look at the relevant callers in detail:
/nanobot/nanobot/agent/loop.py:1166-session.enforce_file_cap(on_archive=self.context.memory.raw_archive)/nanobot/nanobot/agent/loop.py:1490-ctx.session.enforce_file_cap(on_archive=self.context.memory.raw_archive)/nanobot/nanobot/command/builtin.py:215-loop._schedule_background(loop.consolidator.archive(snapshot))- this is the/newarchival/nanobot/nanobot/agent/autocompact.py:57-schedule_background(self._archive(key))/nanobot/nanobot/session/manager.py:368-enforce_file_cap(on_archive=...)
Let me look at these in detail.
Assistant
Now let me look at the
enforce_file_capin session/manager.py and the/newarchival in command/builtin.py and the autocompact.py.Assistant
Let me look at how
build_messagesis called and the session key flow in loop.py:Assistant
Let me look at the UNIFIED_SESSION_KEY constant and unified_session handling:
Assistant
Let me search for internal session prefixes (cron, dream, heartbeat):
Assistant
So the internal session prefixes are
cron:,dream:, andheartbeat. The heartbeat session key is exactly "heartbeat" (not "heartbeat:..."). Let me confirm: in cli/commands.py:1164session_key="heartbeat"and 1175get_or_create("heartbeat"). And cron:session_key=f"cron:{job.id}". And dream:f"dream:{datetime...}".So internal sessions: keys starting with
cron:,dream:, or equal toheartbeat(or starting withheartbeat). Let me check token_usage.py:80-82:if key.startswith("dream:"): ... if key == "heartbeat" or key.startswith("cron:"): ...So the internal session detection:
key == "heartbeat" or key.startswith("cron:") or key.startswith("dream:"). Let me check if heartbeat could beheartbeat:...too. Let me search.Assistant
Let me look at
process_directand the secondbuild_messagescall site:Assistant
Let me look at the close/drain logic in loop.py around 1072:
Assistant
The MCP draining on close is already implemented. Now let me look at the existing tests for memory and context:
Assistant
Let me look at the rest of test_consolidator.py and the auto_compact/unified_session tests:
Assistant
Let me check the context prompt cache test and search for tests that test recent history injection:
Assistant
Now I have a thorough understanding. Let me implement the changes. First, let me modify
append_historyto addsession_key:Assistant
Now let me make the edits. First,
append_history:Assistant
Now let me edit
append_history:Assistant
Now update the docstring and the record creation to include
session_key:Assistant
The docstring got mangled. Let me fix it:
Assistant
The docstring still has a stray line. Let me rewrite the whole docstring cleanly:
Assistant
Now update the record creation to include
session_key:Assistant
Now let me add the
read_recent_history_for_promptmethod and the internal session key helper. Let me add it right afterread_unprocessed_history:Assistant
Now let me add the
_is_internal_session_keymodule-level helper. Let me add it near the constants block:Assistant
My edit broke the comment block. Let me fix the whole section:
Assistant
Now let me update
archiveandraw_archive. Let me view them:Assistant
The replace command needs the file to be open. Let me open the file first. Actually it says "file not modified" but found occurrences. Let me open the file at line 549 and try again.
Assistant
Now update
archive:Assistant
There's a duplicate
return Noneon line 862. Let me remove it:Assistant
Now let me update the
archivecalls within the Consolidator to passsession_key. Let me find them:Assistant
The replace needs the file to be open. Let me open the file at line 762 and run replace.
Assistant
Now the
maybe_consolidate_by_tokensarchive call (line ~944) and thecompact_idle_sessionarchive call (line ~1016):Assistant
The replace tool requires the matching lines to be in the displayed window. Let me open the file at that line first.
Assistant
Now update the
compact_idle_sessionarchive call (line 1015). The session key here issession.key(which equalssession_key):Assistant
Now let me verify the memory.py syntax compiles:
Assistant
Now let me update
context.py. First,build_system_promptto acceptsession_keyandunified_session, and useread_recent_history_for_prompt:Assistant
There are leftover duplicate lines 125-128. Let me remove them:
Assistant
There's a duplicate
def _get_identityon lines 125 and 127. Let me fix:Assistant
Now there's a duplicate docstring line 126-127. Let me fix:
Assistant
Now there's a duplicate
root = workspace or self.workspaceon lines 127 and 128. Let me remove the duplicate:Assistant
Now let me update
build_messagesto accept and forwardsession_keyandunified_session:Assistant
There's a duplicate
skip_runtime_linesline. Let me remove it and update thebuild_system_promptcall:Assistant
Let me verify context.py compiles:
Assistant
Now let me update the callers in
loop.py. The twobuild_messagescall sites (_build_initial_messagesand_process_system_message) need to passsession_keyandunified_session. Alsoenforce_file_capcallers need to pass session_key toraw_archive. Let me update_build_initial_messages:Assistant
Now the
_process_system_messagebuild_messages call (line ~1142):Assistant
Now update the
enforce_file_capcalls to pass session_key to raw_archive via partial. Let me check if functools is imported in loop.py:Assistant
Let me check
enforce_file_capusages in tests:Assistant
Let me add
import functoolsand usefunctools.partialat the call sites:Assistant
Now update the two
enforce_file_capcall sites to use a partial withsession_key:Assistant
Now the second
enforce_file_capcall (line ~1495):Assistant
Now update the
/newarchival inbuiltin.pyto passsession_key:Assistant
Let me verify all modified files compile:
Assistant
Now let me run the existing affected tests:
Assistant
All passing. Now let me run the autocompact and session manager history tests:
Assistant
Now let me create a temporary test script to verify the cross-session isolation behavior works as intended:
Assistant
Now let me verify the ContextBuilder correctly scopes the Recent History section:
Assistant
Let me run a broader set of agent tests to ensure nothing breaks:
Assistant
Let me look at the failing tests to understand them:
Assistant
Let me look at the
test_preflight_consolidation_before_llm_calltest:Assistant
The 5 failures are all due to tests mocking
archivewith a single-argument function (async def _failing_summarize(_messages)) that doesn't accept the newsession_keykeyword. This is exactly the "tests need updating to reflect the change" scenario described in the instructions. The fix itself is correct per the contract. Let me confirm all 5 are this mock-signature pattern and not logic errors:Assistant
All 5 failures are confirmed to be the mock-signature pattern (
got an unexpected keyword argument 'session_key'), caused by tests mockingarchivewith a plain single-argument function. These tests need updating to the new contract signature, which is the documented "tests need updating" scenario. My fix is correct per the contract.Let me run the rest of the test suite to confirm no other breakage:
Assistant
Let me check the 2 additional failures to see if they're related to my changes or pre-existing:
Assistant
The dream_session test passed this run (flaky/order-dependent). The mcp_presets_api failure is about MCP preset connection (network), unrelated to my changes. Let me confirm these 2 are pre-existing by stashing my changes:
Assistant
Confirmed: the
mcp_presets_apifailure is pre-existing (fails on original code too), anddream_sessionpassed (flaky). My changes introduce exactly 5 failures, all the "mock doesn't acceptsession_key" pattern — i.e., tests that need updating to the new contract signature, which the instructions say to ignore.Let me verify I haven't missed any caller of
archive/raw_archive/append_historythat should propagatesession_key:Assistant
Let me confirm the
enforce_file_cappartials and verify there are no remaining directraw_archivereferences without session_key:Assistant
Let me verify the session key flow in unified mode to ensure
session.keyis the effective key:Assistant
Let me check
process_directto ensure cron/heartbeat sessions also get session_key passed through:Assistant
Let me check for any other direct
build_system_promptorbuild_messagescalls I might have missed:Assistant
Only the two I've already updated. Now let me clean up temp files and do a final review of the diff:
Assistant
The memory.py diff looks good. Let me review context.py and loop.py and builtin.py diffs.
Assistant
All changes look good. Let me do a final import check and re-run the directly-affected tests:
Assistant
All directly-related tests pass. Let me re-create a quick test mirroring the exact issue scenario (T1/T2/T3) to be thorough:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.