Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-sonnet-5· anthropicHugging Face ibragim-bad/swe_rebench_07_2026_trajectories

ISSUE DESCRIPTION history.jsonl 跨会话注入导致上下文污染 Bug Description history.jsonl 跨会话注入导致上下文污染…

  1. 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_cursor
    T1微信会话 A 触发 Consolidator,写入 2 条摘要 entry0
    T2Telegram 会话 B 触发 Consolidator,写入 1 条摘要 entry0
    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 /new archival—must propagate the originating session_key into 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 internal cron:, dream:, and heartbeat histories, 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 using git reset --hard command. Additionally, you can use git stash and git stash pop to temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you call submit) using git status or git diff commands. However you don't need to use git add or git commit before submitting your changes. In fact, submit only submits currently unstaged changes because it uses git diff to 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-$

  2. Claude Assistant

    Now let's look at context.py for build_system_prompt, and search for other archive() callers (e.g., /new archival).

  3. Claude Assistant

    Now let's find where build_messages is called normally (with session_key) and the "/new" archival command, and clear session logic.

  4. Claude Assistant

    Good — confirms the convention. Let's check that token_usage.py snippet for existing pattern of identifying internal sessions.

  5. Claude Assistant

    No history-related tests currently touch read_unprocessed_history/recent history directly in these tests without session_key. Good, defaults must not break. Now let's check test_context_prompt_cache.py for any recent history entries setup.

  6. Claude Assistant

    Now let's check session.enforce_file_cap(on_archive=self.context.memory.raw_archive) callers to understand the signature expected by enforce_file_cap.

  7. Claude Assistant

    Fine, it accepts **kwargs so passing extra session_key kwarg is safe. Now let's check consolidator.archive calls in tests to verify signatures used.

  8. Claude Assistant

    Good, all backward compatible. Now let's implement the changes to memory.py.

  9. Claude Assistant

    Now let's edit append_history:

  10. Claude Assistant

    Now let's add read_recent_history_for_prompt and _is_internal_session_key right after read_unprocessed_history.

  11. Claude Assistant

    Looks identical. Let me use edit command with line numbers instead.

  12. Claude Assistant

    Need a blank line before def compact_history.

  13. Claude Assistant

    Now let's update raw_archive and archive methods to add session_key.

  14. Claude Assistant

    There's a stray extra ) at line 585. Let's fix.

  15. Claude Assistant

    Need a blank line before # --- Dream helpers comment block for consistency.

  16. Claude Assistant

    Duplicate line "# Dream helpers" at 587/588. Let's fix.

  17. Claude Assistant

    Good, that's fixed now. Let's verify syntax by compiling.

  18. Claude Assistant

    Now let's update archive() method to accept session_key.

  19. Claude Assistant

    Leftover duplicate lines 866-867. Remove them.

  20. Claude Assistant

    It ate the blank line before async def maybe_consolidate_by_tokens. Let's add it back.

  21. Claude Assistant

    Now let's update line 947 summary = await self.archive(chunk) to pass session_key=session.key.

  22. Claude Assistant

    Now update line 1019.

  23. Claude Assistant

    Now let's find _consolidate_replay_overflow's call to self.archive(chunk).

  24. Claude Assistant

    Also let's add session_key=session.key to estimate_session_prompt_tokens's _build_messages call for accuracy.

  25. Claude Assistant

    Now let's update context.py.

  26. Claude Assistant

    Duplicate lines 119-122. Remove them.

  27. Claude Assistant

    Still a duplicate line 119/120. Fix.

  28. Claude Assistant

    Good. Now let's update build_messages method to accept and pass through session_key/unified_session.

  29. Claude Assistant

    Let's just use edit with line numbers directly.

  30. Claude Assistant

    I removed the ) -> list[dict[str, Any]]: closing line accidentally. Fix line 206-207.

  31. Claude Assistant

    Now let's update the build_system_prompt call within build_messages:

  32. Claude Assistant

    Oops the "role": "system", line got removed. Fix.

  33. Claude Assistant

    Now that looks correct. Let's verify with compile.

  34. Claude Assistant

    Now let's update loop.py: _build_initial_messages, _process_system_message, enforce_file_cap callbacks.

  35. Claude Assistant

    Need to fix duplicate include_memory_recent_history at line 616.

  36. Claude Assistant

    Good. Now let's fix the two enforce_file_cap(on_archive=self.context.memory.raw_archive) call sites to bind session_key. Let's find both occurrences with current line numbers.

  37. Claude Assistant

    Let's add import functools and use functools.partial.

  38. Claude Assistant

    Now update the two enforce_file_cap call sites.

  39. Claude Assistant

    Now let's check _process_system_message's build_messages call above to add session_key/unified_session there too.

  40. Claude Assistant

    Duplicate closing paren at line 1160. Remove.

  41. Claude Assistant

    Good. Now let's fix the second enforce_file_cap call site (now shifted).

  42. Claude Assistant

    Now let's verify compile.

  43. Claude Assistant

    Now let's update cmd_new in builtin.py to pass session_key.

  44. Claude Assistant

    Good, no strict key-set assertions. Now let's run the full test suite related to memory/context/consolidator to check for breakages.

  45. Claude Assistant

    All pass. Now let's run auto_compact, dream, loop_save_turn tests, and full test suite.

  46. Claude Assistant

    Let's run full test suite to catch anything unexpected.

  47. Claude Assistant

    Good, that test is pre-existing broken, unrelated to our change. Now let's check test_preflight_consolidation_before_llm_call.

  48. Claude Assistant

    All good. Let's double check dream.py doesn't also call raw_archive/archive.

  49. Claude Assistant

    These are unrelated (just file path/template references), fine. Now let's double check autocompact.py's _is_internal_session (used for skip idle-archiving) — should we extend prefixes to also include cron/heartbeat for consistency? Let's check the test file for autocompact internal session behavior.

  50. Claude Assistant

    Let's also run session/manager tests and command/builtin tests.

  51. Claude Assistant

    All expected behaviors verified. Let's clean up the temp script.

  52. Claude Assistant

    Now let's double check the close_mcp draining behavior and session-clearing-before-archive ordering are both intact (already confirmed via existing passing tests except the mock-signature ones). Let's view final diff for review.

  53. Claude Assistant

    This all looks clean and consistent. Now let's re-run the memory/context/consolidator-related tests plus the full suite once more to confirm final state.

  54. Claude Assistant

    Good, session_key is exactly "heartbeat" (no colon/suffix). Our _is_internal_session_key handles exact match and prefix match, covering this case correctly.

  55. Claude Assistant

    All good. Now let's go through the checklist explicitly.

  56. Claude Assistant

    Let's also verify subagent.py doesn't call build_messages/build_system_prompt directly bypassing session_key threading.

  57. Claude Assistant

    Good, no direct calls there (it goes through _process_message/_state_build like normal messages). Let's finally review the full diff once more for sanity, then finish.

  58. Claude Assistant

    All syntax checks pass. Let's do a final full-suite run to have the final failure count documented, then submit.

  59. Claude Assistant

    That's flaky (likely mtime-based, unrelated to our changes) — passes in isolation. Not related to our fix.

  60. Claude Assistant

    Confirmed: this test is pre-existing flaky (fails even without our changes, likely mtime-resolution related on this filesystem), unrelated to our fix.

    Now let's go through the checklist.

  61. Claude Assistant

    Now, going through the checklist explicitly:

    1. If an error was reported, I successfully reproduced it. Yes — I wrote a repro script simulating two channels (WeChat session A, Telegram session B) writing history entries and confirmed that under the old code (read_unprocessed_history with no session filter), all entries would be mixed into any session's # Recent History. I verified this understanding by inspecting context.py's build_system_prompt before the fix, which called read_unprocessed_history(since_cursor=...) unconditionally with zero session scoping.

    2. I confirmed my fix resolves the error. Yes — after implementing read_recent_history_for_prompt, my repro script (run post-fix) showed:

    • Session B's prompt does NOT contain session A's (WeChat) entries in non-unified mode.
    • Session A's prompt does NOT contain session B's entries.
    • In unified mode, session B does see session A's entries (expected: unified mode pools user-channel history).
    • Internal automation sessions (dream:...) never leak into user sessions even in unified mode, but the internal session itself can read its own entries.

    3. Edge cases considered:

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.