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:
- Memories already store
covers_period_start/covers_period_end(UTC timestamps) - Summaries already store
tracker_start_json/tracker_end_json(game time state) - The
IncludeTimeHeadersetting already distinguishes between"realtime"and"gametime"modes RelativeDateHelperalready formats relative real-time dates for display
What's missing is the reverse direction: parsing time expressions from user input and using them to query memories by when they happened.
Problem
Current memory search
The memory search pipeline (WebMemoryContentProvider, MemorySearchRepository) uses three methods:
- Vector search -- semantic similarity between current message embedding and memory embeddings
- Full-text search -- PostgreSQL
ts_rank_cdon stemmed words - 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:
- A memory about time passing (keyword "days" matches)
- A memory about the story's beginning (keyword "story" matches)
- Nothing relevant to what actually happened two in-world days ago
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:
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).
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:
- A memory matches if its coverage period overlaps the resolved time window
- Wider expressions ("last week") get wider fuzzy windows
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:
- Extract the current game time from the active tracker:
"Day 5, Evening" - 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."
- LLM returns:
{"from": "Day 3", "to": "Day 3"} - 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:
- "Day 3, Morning" (linear day count)
- "Third Age, Year 142, Spring" (fantasy calendar)
- "Stardate 41153.7" (sci-fi)
- "2 bells past noon" (nautical)
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, '[]')
- Pro: Precise, fast (reduces search space)
- Con: Misses memories just outside the window
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)
- Pro: Forgiving of imprecise time resolution, graceful degradation
- Con: Time-irrelevant but keyword-matching memories can still rank high
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:
- Before building the search query, scan the user message for time expressions
- If found, resolve to a time window (real or game time)
- Pass the resolved window to the search repository as an additional parameter
- The search function applies temporal scoring alongside existing vector/FTS/keyword scoring
Tracker Integration
Fuzzy time search becomes significantly more powerful with trackers:
- Game time tracker provides the "current time" reference for resolving relative expressions
- Location tracker disambiguates time references: "when we were at the tavern" can combine temporal + location search
- Story arc tracker provides narrative milestones: "before Act 2" resolves to memories before the arc transition
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:
documentDate: When content was said (maps to ourcovers_period_start)eventDate: When event occurred (maps to ourtracker_start_jsongame time)
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:
- Event time: When fact occurred
- Ingestion time: When observed/added
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
- Transparent by default: Users don't need to know fuzzy time search is happening. Memories recalled with a temporal boost just appear more relevant.
- Debug indicator (creator view): When a memory was boosted by temporal matching, show a clock icon or "matched by time" indicator alongside the memory in the debug/expanded view.
- Time-annotated recall: When time search is active, recalled memories could show their time context more prominently:
"[Day 3, Morning] The party entered Shadowkeep..."already happens with time headers, but could be emphasized when the user explicitly asked about a time period.
Creator Side
- Temporal search testing: In the evaluation testing UI, allow creators to test time resolution: input a message with a time expression, see which time window the system resolves, and which memories would match.
- Game time format guidance: Since game time resolution depends on the LLM understanding the format, creators should see guidance: "Use consistent, parseable game time formats for best temporal search results."
Implementation Phases
Phase 1: Real-Time Temporal Boost
Simplest valuable increment:
- Pattern-based detection of time expressions in user messages (Microsoft.Recognizers.Text.DateTime or equivalent)
- Resolve against UTC clock
- Temporal score boost on
covers_period_start/covers_period_end - 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:
- LLM-assisted resolution of time expressions against current game time tracker
- ILIKE/text matching on
tracker_start_json/tracker_end_json - 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:
- Parsed game time fields on summaries for precise range queries
- Named period resolution ("when we were at the tavern") combining temporal + tracker/semantic search
- LLM-assisted detection for implicit time references
- 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
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.
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.
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?
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.
Multi-tracker time resolution: If a conversation has both
gametimeandseasontrackers, and the user says "last spring", should the system resolve against theseasontracker? This generalizes fuzzy time search into "fuzzy state search" -- resolving relative state references against any tracker's history. Powerful but complex.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?