Skip to content
TheChatArchiveThe Chat Archive
x-ai/grok-4.5· unknownHugging 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. Assistant

    I'll start by exploring the repository structure and the relevant memory/context code to understand how history is written and injected.

  3. Assistant

    I'll inspect the memory and context modules plus related tests next.

  4. Assistant

    Let me read the memory.py file, especially append_history, archive, raw_archive, and read related functions.

  5. Assistant

    rg is not available, let me use grep.

  6. Assistant

    I'll open the key sections of memory.py and context.py around those call sites.

  7. Assistant

    Let me read the append_history and related methods.

  8. Assistant

    Let me continue reading more of the memory.py file.

  9. Assistant

    Next I'll inspect archive, raw_archive, and the consolidator call path.

  10. Assistant

    Let me read the Consolidator class methods more carefully.

  11. Assistant

    I'll keep reading the rest of Consolidator, focusing on archive call sites.

  12. Assistant

    Let me finish reading the rest of the file.

  13. Assistant

    I'll also check context.py and every caller of archive/append_history/raw_archive.

  14. Assistant

    I'll inspect _consolidate_replay_overflow, build_system_prompt callers, and session-clearingenforce_file_cap.

  15. Assistant

    I'll examine cmd_new, close_mcp, message building around session keys, and related tests.

  16. Assistant

    I'll look over the relevant tests and more call sites to understand the expected API.

  17. Assistant

    I'll inspect enforce_file_cap, autocompact, and how session keys are structured for internal sessions.

  18. Assistant

    I'll check remaining archive call sites and how dream consumes history.

  19. Assistant

    I'll check how initial messages are built and how Consolidator is wired for _build_messages.

  20. Assistant

    I'll check the case folder and docs for any extra implementation notes.

  21. Assistant

    I'll check dream-related history processing and any helper for internal session prefixes.

  22. Assistant

    I'll scan remaining force-file-cap usages and dream's history readings, then implement.

  23. Assistant

    I have a clear plan: tag history entries with session_key, filter Recent History by session (with unified-mode rules), and thread session_key through every archive path.

  24. Assistant

    Next I'll add read_recent_history_for_prompt and update raw_archive.

  25. Assistant

    I'll fix the missing newline before compact_history and update raw_archive/archive.

  26. Assistant

    Updating raw_archive and archive to accept and forward session_key.

  27. Assistant

    Let me update raw_archive and archive.

  28. Assistant

    Note that _RAW_ARCHIVE_MAX_CHARS is defined after raw_archive uses it - but it was already like that before. That's fine at runtime since the method isowness called after module loadelle.

  29. Assistant

    Updating Consolidator.archive and its call sites next.

  30. Assistant

    Let me update archive method and all archive calls.

  31. Assistant

    Continue updating archive method and remaining calls.

  32. Assistant

    Now update the archive method body.

  33. Assistant

    Now update the maybe_consolidate and compact_idle_session archive calls.

  34. Assistant

    Update the remaining two.

  35. Assistant

    Update both archive calls.

  36. Assistant

    Update the compact_idle_session archive call.

  37. Assistant

    Updating context.py next so recent-history injection is session-scoped.

  38. Assistant

    I'll thread session_key/unified_session through build_messages into build_system_prompt.

  39. Assistant

    Update build_messages signature and call.

  40. Assistant

    Next I'll update loop.py and cmd_new call sites.

  41. Assistant

    I'll update _process_system_message and the enforce_file_cap wrappers.

  42. Assistant

    I'll update both call sites.

  43. Assistant

    Now I'll update _state_save's enforce_file_cap call.

  44. Assistant

    Update line 1499.

  45. Assistant

    Update enforce_file_cap in _state_save

  46. Assistant

    Updating /new archival in builtin.py to pass session_key.

  47. Assistant

    I'll check remaining call paths: dream, direct append_history, and other build_messages sites.

  48. Assistant

    I'll verify how Dream builds messages and which session keys it uses.

  49. Assistant

    I'll write a temporary script to verify session isolation and the other edge cases.

  50. Assistant

    Temporary checks passed. I'll run the related existing test suites next.

  51. Assistant

    Existing failures are expected without session_key. I'll sanity-check cmd_new archival and that close_mcp still drains background work.

  52. Assistant

    I'll run a quick ruff check on the edited files.

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