Skip to content

Bug: StaticLongTermMemoryHook injects memory at end of messages instead of beginning #1164

@Fruank4

Description

@Fruank4

Bug Description

In StaticLongTermMemoryHook, the retrieved long-term memory message is appended to the end of the message list, despite the code comment explicitly stating it should be injected at the beginning.

Affected File

agentscope-core/src/main/java/io/agentscope/core/memory/StaticLongTermMemoryHook.java, lines 157–160

Current Behavior

// Inject memory message at the beginning   // <-- comment says beginning
List<Msg> enhancedMessages = new ArrayList<>();
enhancedMessages.addAll(inputMessages);      // all messages added first
enhancedMessages.add(memoryMsg);             // memory appended at the END
event.setInputMessages(enhancedMessages);

The LLM receives messages in this order:

  1. System prompt
  2. Conversation history / user query
  3. Retrieved memory context ← appended last

Expected Behavior

The retrieved memory context should be injected at the beginning (or at least before the user query), so the LLM has the relevant context when processing the current turn:

// Inject memory message at the beginning
List<Msg> enhancedMessages = new ArrayList<>();
enhancedMessages.add(0, memoryMsg);          // insert at index 0
enhancedMessages.addAll(inputMessages);
event.setInputMessages(enhancedMessages);

Or equivalently:

enhancedMessages.addAll(inputMessages);
enhancedMessages.add(0, memoryMsg);          // insert at beginning after the fact

Impact

  • RAG (Retrieval-Augmented Generation) quality is degraded because the LLM receives the user query before the retrieved context
  • The retrieved memory has less influence on the response since it appears after the question has already been posed in the message sequence
  • The comment/code mismatch indicates this is an unintentional regression

Steps to Reproduce

  1. Configure a ReActAgent with StaticLongTermMemoryHook
  2. Send a query that triggers a long-term memory retrieval
  3. Inspect the message list passed to the LLM — the memory SYSTEM message will appear last instead of first

Suggested Fix

Change line 160 in StaticLongTermMemoryHook.java:

// Before
enhancedMessages.add(memoryMsg);

// After
enhancedMessages.add(0, memoryMsg);

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    Projects

    Status

    In progress

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions