Fuzzy Time Search

Status: Planned

Overview

When a user says "remember what happened 2 days ago?" or "what did Elara say last morning?", the current memory system has no way to use these temporal references. It performs semantic/keyword search on the text content, hoping the recalled memories happen to be from the right time period. If the memory about "2 days ago" doesn't share keywords with the current message, it won't surface.

Fuzzy time search adds a temporal dimension to memory recall. The system detects relative time expressions in user messages, resolves them against either real-world time or in-world game time, and uses the resolved time window to filter or boost memory search results.

This feature builds directly on existing infrastructure:

What's missing is the reverse direction: parsing time expressions from user input and using them to query memories by when they happened.


Problem

The memory search pipeline (WebMemoryContentProvider, MemorySearchRepository) uses three methods:

  1. Vector search -- semantic similarity between current message embedding and memory embeddings
  2. Full-text search -- PostgreSQL ts_rank_cd on stemmed words
  3. Simple keyword search -- substring matching against memory keywords

All three are content-based. They answer "which memories are about similar topics?" but cannot answer "which memories are from a specific time?"

Where this fails

User: "What happened two days ago in the story?"

The search query contains "happened", "two", "days", "ago", "story" -- none of which are useful for finding memories from a specific time period. The system might return:

User: "Didn't we meet someone at the market last morning?"

"Last morning" is a clear time reference, but the search only sees "meet", "someone", "market", "morning" as keywords. It might find a market-related memory but has no way to verify it's from the right time period.

The gap

Memories have timestamps. Users reference time. Nothing connects them.


Proposed Design

Two Time Domains

The system operates in two distinct time domains, matching the existing IncludeTimeHeader setting:

Domain Source Resolution Example
Real time covers_period_start / covers_period_end on memories Parse against current UTC date "2 days ago" → UTC range
Game time tracker_start_json / tracker_end_json on memories Parse against current game time tracker value "2 days ago" → "Day 1" if current is "Day 3"

Real-time resolution is straightforward -- standard NLP date parsing against the clock. Game-time resolution is harder because game time is freeform text, not a structured timestamp.

Architecture

User message: "What happened 2 days ago?"
       │
       ▼
┌─────────────────────────┐
│  1. Time Expression      │
│     Detection            │  → Detect "2 days ago" as a temporal reference
└──────────┬──────────────┘
           │
           ▼
┌─────────────────────────┐
│  2. Time Resolution      │  → Resolve against current time domain
│     (real or game time)  │     Real: now minus 2 days → UTC range
└──────────┬──────────────┘     Game: "Day 3" minus 2 → "Day 1" window
           │
           ▼
┌─────────────────────────┐
│  3. Temporal Filter /    │  → Filter or boost memories whose time range
│     Score Boost          │     overlaps the resolved window
└──────────┬──────────────┘
           │
           ▼
┌─────────────────────────┐
│  4. Hybrid Search        │  → Existing vector + FTS + keyword search
│     (with time signal)   │     runs on filtered/boosted candidate set
└──────────────────────────┘

Step 1: Time Expression Detection

Detect relative time expressions in user messages and classify them:

Expression types:

Type Examples Resolved to
Relative past "2 days ago", "last night", "yesterday" Time point or short window
Relative range "over the past week", "in the last 3 days" Time range
Named period "during the festival", "when we were in Shadowkeep" Requires tracker/semantic matching
Ordinal "the first time we met Elara", "our second visit" Sequence-based, not time-based

The first two types are resolvable with time parsing. Named periods require combining temporal search with semantic/tracker search. Ordinal references are a stretch goal.

Detection approach:

Detection can happen at two levels:

  1. Pattern-based (fast, deterministic): Regex or NLP date parser on the user message. Catches explicit time references like "2 days ago", "last morning", "yesterday." Libraries: Microsoft.Recognizers.Text.DateTime (.NET), chrono (JS).

  2. LLM-assisted (flexible, costly): The evaluation call (shared with tracker/journal) can identify temporal intent in the user's message and extract structured time references. Catches implicit references like "back when we started" or "before the cave rescue." Only triggers when pattern-based detection finds nothing but the message seems time-referential.

For v1, pattern-based detection is sufficient. LLM-assisted detection can layer on top later.

Step 2: Time Resolution

Real-time resolution:

Straightforward. Parse the expression relative to the current UTC timestamp:

"2 days ago" + now = Feb 8, 2026 → Feb 6, 2026 ± 12h fuzzy window
"last week"  + now = Feb 8, 2026 → Feb 1-7, 2026
"yesterday"  + now = Feb 8, 2026 → Feb 7, 2026

Map to memory's covers_period_start / covers_period_end with overlap matching:

Game-time resolution:

This is the harder problem. Game time is stored as freeform text in tracker_start_json / tracker_end_json (e.g., {"gametime": "Day 3, Morning"}). Resolving "2 days ago" against freeform game time requires understanding the time format.

Approach: Evaluation LLM resolves game time expressions

When the system detects a time expression and the conversation uses game time:

  1. Extract the current game time from the active tracker: "Day 5, Evening"
  2. Send a targeted LLM call (can share with the tracker/journal evaluation call or run independently): "Current game time is 'Day 5, Evening'. The user said '2 days ago'. What game time does that refer to? Return a JSON range."
  3. LLM returns: {"from": "Day 3", "to": "Day 3"}
  4. Use this resolved range to search memory tracker_start_json / tracker_end_json

Why LLM for game time?

Game time formats are creator-defined and arbitrary:

No parser can handle all of these. The LLM understands the format because it's been reading it throughout the conversation. A targeted "resolve this time reference" call is cheap and reliable for structured formats.

Fallback for unresolvable game time:

If the LLM can't resolve the expression (ambiguous format, no clear game time progression), fall back to real-time resolution using covers_period_start. Less narratively meaningful but still better than no temporal search.

Step 3: Temporal Filter / Score Boost

Once a time window is resolved, integrate it with the existing search pipeline:

Option A: Pre-filter (strict)

Filter the memory candidate set to only include memories whose time range overlaps the resolved window, then run normal hybrid search on the filtered set.

-- Add to memory search query
WHERE daterange(covers_period_start::date, covers_period_end::date, '[]')
  && daterange(@window_start::date, @window_end::date, '[]')

Option B: Score boost (fuzzy)

Run normal hybrid search but boost scores for memories within the time window. Memories from the right time period rank higher but time-distant memories aren't excluded.

final_score = content_score + (time_overlap_score * time_boost_weight)

Recommendation: Score boost as default, pre-filter as option.

Score boost is more forgiving of the fuzzy nature of both user time expressions and game time resolution. Pre-filter can be enabled via setting for users who want strict temporal matching.

Step 4: Game-Time Search on Tracker State

For game-time resolution, memories need to be searchable by their tracker state. The tracker_start_json / tracker_end_json fields are currently opaque JSON text.

Search approach:

-- Find memories whose game time tracker overlaps a resolved range
-- This requires the LLM-resolved game time values
SELECT * FROM web_summaries
WHERE level = 0  -- memories only
  AND conversation_id = @conversation_id
  AND (
    tracker_start_json::jsonb->>'gametime' ILIKE '%Day 3%'
    OR tracker_end_json::jsonb->>'gametime' ILIKE '%Day 3%'
  )

This is a text-based approximation. For v1, ILIKE matching on the resolved game time string is sufficient. A more structured approach (parsing tracker JSON into indexed fields) can come later if needed.


Integration with Existing Systems

Memory Search Pipeline

The current search in MemorySearchRepository returns MemorySearchResult with CoversPeriodStart and CoversPeriodEnd. These timestamps are already available in the result set -- the temporal scoring layer just needs to use them.

Changes to WebMemoryContentProvider.BuildSearchQueryAsync:

  1. Before building the search query, scan the user message for time expressions
  2. If found, resolve to a time window (real or game time)
  3. Pass the resolved window to the search repository as an additional parameter
  4. The search function applies temporal scoring alongside existing vector/FTS/keyword scoring

Tracker Integration

Fuzzy time search becomes significantly more powerful with trackers:

Journal Integration

Journal character and location entries have created_at and source_message_id, which links them to specific points in the timeline. Fuzzy time search could extend to journal queries: "what did we learn about Elara in the first few days?" filters journal entries by their temporal position.

Summary Time Headers

The existing time header system (SummaryContentProviderBase:54-61) already formats memories with time context. Fuzzy time search complements this -- time headers help the AI understand when recalled memories happened, while fuzzy time search ensures the right memories are recalled in the first place.


Prior Art

Supermemory (supermemory.ai)

The closest existing implementation. Uses dual-layer timestamping:

Relative time expressions resolve against documentDate, not the system clock. Achieves 82% accuracy on temporal reasoning benchmarks. Key insight: store event time separately from ingestion time, which our system already does with tracker JSON on summaries.

Zep

Uses bitemporal modeling in a knowledge graph:

Enables retroactive corrections and temporal queries. More complex than our needs but validates the dual-timestamp approach.

SillyTavern Timeline Memory

Chapter-based chronological organization. AI agent queries chapters by narrative position. Not timestamp-based but demonstrates the value of temporal organization in roleplay contexts.


Database Changes

Minimal schema changes needed for v1. Existing fields already carry the required timestamps.

Potential index additions:

-- Index for temporal range queries on memories
CREATE INDEX idx_web_summaries_temporal
  ON web_summaries (conversation_id, covers_period_start, covers_period_end)
  WHERE level = 0 AND is_deleted = FALSE;

-- GIN index for tracker JSON querying (game time search)
CREATE INDEX idx_web_summaries_tracker_gin
  ON web_summaries USING gin (tracker_start_json::jsonb)
  WHERE level = 0 AND is_deleted = FALSE;

Future: Structured time field (Phase 2)

If game-time search becomes heavily used, consider adding a parsed/indexed time field alongside the freeform tracker JSON:

ALTER TABLE web_summaries
  ADD COLUMN gametime_start_parsed JSONB,  -- {"day": 3, "period": "morning"}
  ADD COLUMN gametime_end_parsed JSONB;

The evaluation call would populate these structured fields alongside the freeform tracker JSON. Enables precise range queries without ILIKE text matching.


Settings

New settings under Memory.*:

Key Default Description
Memory.TemporalSearch "auto" "auto" (detect time expressions), "always" (always include time scoring), "disabled"
Memory.TemporalBoostWeight 0.3 How much temporal overlap boosts search score (0-1)
Memory.TemporalFuzzyWindow "6h" Fuzzy window added to resolved time ranges to account for imprecision
Memory.TemporalSearchMode "boost" "boost" (score bonus) or "filter" (strict pre-filter)

These follow the existing settings pattern in SettingsKeys.cs and respect the source resolution chain.


UI Considerations

Chat Side

Creator Side


Implementation Phases

Phase 1: Real-Time Temporal Boost

Simplest valuable increment:

  1. Pattern-based detection of time expressions in user messages (Microsoft.Recognizers.Text.DateTime or equivalent)
  2. Resolve against UTC clock
  3. Temporal score boost on covers_period_start / covers_period_end
  4. No game time support yet

Effort: Moderate. Requires changes to WebMemoryContentProvider (detect + resolve), MemorySearchRepository (temporal scoring), and the search database function.

Phase 2: Game-Time Resolution

Adds in-world time support:

  1. LLM-assisted resolution of time expressions against current game time tracker
  2. ILIKE/text matching on tracker_start_json / tracker_end_json
  3. Requires game time tracker to be active (depends on tracker feature)

Effort: Moderate. The LLM call can piggyback on the evaluation call or run as a lightweight separate call during search.

Phase 3: Structured Game Time + Named Period Resolution

Advanced features:

  1. Parsed game time fields on summaries for precise range queries
  2. Named period resolution ("when we were at the tavern") combining temporal + tracker/semantic search
  3. LLM-assisted detection for implicit time references
  4. Ordinal resolution ("the first time we met Elara") using sequence analysis

Effort: Significant. Requires structured game time parsing, cross-referencing tracker history, and more sophisticated LLM integration.


Open Questions

  1. Time expression ambiguity: "Last night" in real time means yesterday evening. In game time, it means the previous in-world night. When both real and game time are available, which takes precedence? Probably game time for narrative-focused conversations, real time for casual chat. Could be a setting, or inferred from whether game time tracker is active.

  2. Game time format diversity: Creators invent wildly different time formats. The LLM resolution approach handles this, but how reliable is it for unusual formats? "2 bells past noon" minus "3 bells" = ??? Need to test across formats and potentially guide creators toward parseable conventions.

  3. Cost of LLM-assisted resolution: If every user message is scanned for time expressions and some trigger an LLM call for game time resolution, this adds latency and cost to the search pipeline. The LLM call runs before the search can complete, so it's on the critical path (unlike tracker evaluation which runs after the response). Should it be cached? Rate-limited?

  4. Temporal search on lorebooks: Should time expressions also affect lorebook search? If the user asks "what was in the tavern last morning?", should lorebook entries about the tavern be boosted if they have conditional entry conditions matching the resolved time? Probably not for v1 -- lorebook entries are reference data, not episodic. But for conditional entries with time conditions, this could be valuable.

  5. Multi-tracker time resolution: If a conversation has both gametime and season trackers, and the user says "last spring", should the system resolve against the season tracker? This generalizes fuzzy time search into "fuzzy state search" -- resolving relative state references against any tracker's history. Powerful but complex.

  6. Temporal search and summarization: When messages get summarized into higher-level summaries, the time granularity decreases. A Level 0 memory might cover 10 messages (1 hour of game time). A Level 2 summary might cover 100 messages (several game days). How does temporal precision degrade across summary levels? Should fuzzy windows expand for higher-level summaries?