Skip to content

Session context preview shows stale entries due to ascending timeline sort #1565

@singularix-maker

Description

@singularix-maker

Problem

When Claude Code starts a new session, the $CMEM context block is injected via the SessionStart hook. Claude Code displays a "Preview (first 2KB)" of the hook output to the user. Because the timeline is sorted chronologically ascending (oldest entries first), the preview gets truncated before reaching the most recent observations.

Result: The user sees observations from days ago (e.g. Mar 30) instead of the latest session's entries (e.g. Apr 2), even though the full data is correctly loaded into the LLM context.

Reproduction

  1. Have 50+ observations spanning multiple days
  2. Start a new Claude Code session
  3. The preview shows old entries from the beginning of the timeline
  4. The most recent entries are cut off by the 2KB preview limit

Root Cause

Two sort operations enforce ascending (oldest-first) order:

src/services/context/ObservationCompiler.ts line 247:

// Sort chronologically
timeline.sort((a, b) => {
  const aEpoch = a.type === 'observation' ? a.data.created_at_epoch : a.data.displayEpoch;
  const bEpoch = b.type === 'observation' ? b.data.created_at_epoch : b.data.displayEpoch;
  return aEpoch - bEpoch;  // ascending — old entries first
});

src/services/context/sections/TimelineRenderer.ts line 34-37:

const sortedEntries = Array.from(itemsByDay.entries()).sort((a, b) => {
  const aDate = new Date(a[0]).getTime();
  const bDate = new Date(b[0]).getTime();
  return aDate - bDate;  // ascending — old days first
});

Suggested Fix

Reverse both sort comparators to bEpoch - aEpoch / bDate - aDate so that the most recent observations appear first in the output. This way, the 2KB preview shown to the user contains the most relevant (recent) context.

Alternatively, a configuration option for sort order (newestFirst: true/false) would let users choose their preferred display.

Environment

  • claude-mem version: 10.6.3
  • Claude Code CLI
  • ~50 observations loaded, spanning 4 days

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions