Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions mempalace/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,11 @@ def hall_keywords(self):
"""Mapping of hall names to keyword lists."""
return self._file_config.get("hall_keywords", DEFAULT_HALL_KEYWORDS)

@property
def time_decay_half_life_days(self):
"""Half-life in days for time-decay scoring. 0 = disabled."""
return self._file_config.get("time_decay_half_life_days", 90)

def init(self):
"""Create config directory and write default config.json if it doesn't exist."""
self._config_dir.mkdir(parents=True, exist_ok=True)
Expand Down
4 changes: 3 additions & 1 deletion mempalace/mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,13 +170,14 @@ def tool_get_taxonomy():
return {"taxonomy": taxonomy}


def tool_search(query: str, limit: int = 5, wing: str = None, room: str = None):
def tool_search(query: str, limit: int = 5, wing: str = None, room: str = None, time_decay: bool = True):
return search_memories(
query,
palace_path=_config.palace_path,
wing=wing,
room=room,
n_results=limit,
time_decay=time_decay,
)


Expand Down Expand Up @@ -594,6 +595,7 @@ def tool_diary_read(agent_name: str, last_n: int = 10):
"limit": {"type": "integer", "description": "Max results (default 5)"},
"wing": {"type": "string", "description": "Filter by wing (optional)"},
"room": {"type": "string", "description": "Filter by room (optional)"},
"time_decay": {"type": "boolean", "description": "Apply time-decay to rank recent memories higher (default true)"},
},
"required": ["query"],
},
Expand Down
58 changes: 57 additions & 1 deletion mempalace/searcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,53 @@
"""

import logging
from datetime import datetime, timezone
import math
from pathlib import Path

import chromadb

logger = logging.getLogger("mempalace_mcp")

from mempalace.config import MempalaceConfig


def _apply_time_decay(hits, half_life_days):
"""Re-rank hits by applying exponential time-decay to similarity scores.

Args:
hits: list of dicts with 'similarity' and 'filed_at' keys.
half_life_days: half-life in days. If 0 or negative, no decay applied.

Returns:
Sorted list of hits with 'decay', 'original_similarity', and updated 'similarity'.
"""
if not half_life_days or half_life_days <= 0:
return hits

now = datetime.now(timezone.utc)

for hit in hits:
filed_at_str = hit.get("filed_at", "")
if filed_at_str:
try:
filed_at = datetime.fromisoformat(filed_at_str)
if filed_at.tzinfo is None:
filed_at = filed_at.replace(tzinfo=timezone.utc)
age_days = max((now - filed_at).total_seconds() / 86400, 0)
except (ValueError, TypeError):
age_days = 0
else:
age_days = 0

decay = math.pow(0.5, age_days / half_life_days)
hit["original_similarity"] = hit["similarity"]
hit["decay"] = round(decay, 4)
hit["similarity"] = round(hit["similarity"] * decay, 4)

hits.sort(key=lambda h: h["similarity"], reverse=True)
return hits


class SearchError(Exception):
"""Raised when search cannot proceed (e.g. no palace found)."""
Expand Down Expand Up @@ -91,7 +132,12 @@ def search(query: str, palace_path: str, wing: str = None, room: str = None, n_r


def search_memories(
query: str, palace_path: str, wing: str = None, room: str = None, n_results: int = 5
query: str,
palace_path: str,
wing: str = None,
room: str = None,
n_results: int = 5,
time_decay: bool = True,
) -> dict:
"""
Programmatic search — returns a dict instead of printing.
Expand Down Expand Up @@ -142,11 +188,21 @@ def search_memories(
"room": meta.get("room", "unknown"),
"source_file": Path(meta.get("source_file", "?")).name,
"similarity": round(1 - dist, 3),
"filed_at": meta.get("filed_at", ""),
}
)

# Apply time-decay scoring
if time_decay:
try:
half_life = MempalaceConfig().time_decay_half_life_days
except Exception:
half_life = 90
hits = _apply_time_decay(hits, half_life)

return {
"query": query,
"filters": {"wing": wing, "room": room},
"time_decay": time_decay,
"results": hits,
}
111 changes: 111 additions & 0 deletions tests/test_time_decay.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
"""Tests for time-decay scoring feature (#331)."""

from datetime import datetime, timezone, timedelta

import pytest

from mempalace.searcher import _apply_time_decay


class TestApplyTimeDecay:
"""Test the _apply_time_decay helper function."""

def _make_hit(self, similarity, days_ago):
"""Create a hit dict with filed_at set to days_ago days in the past."""
filed_at = datetime.now(timezone.utc) - timedelta(days=days_ago)
return {
"text": f"content from {days_ago} days ago",
"wing": "test",
"room": "test",
"source_file": "test.md",
"similarity": similarity,
"filed_at": filed_at.isoformat(),
}

def test_recent_beats_old_when_similarity_close(self):
"""A recent hit with slightly lower similarity should outrank an older hit."""
hits = [
self._make_hit(0.85, days_ago=180), # old, higher similarity
self._make_hit(0.82, days_ago=1), # recent, lower similarity
]
result = _apply_time_decay(hits, half_life_days=90)
assert result[0]["text"] == "content from 1 days ago"

def test_half_life_halves_score_at_exact_half_life(self):
"""At exactly half_life_days, decay should be ~0.5."""
hits = [self._make_hit(1.0, days_ago=90)]
result = _apply_time_decay(hits, half_life_days=90)
assert abs(result[0]["decay"] - 0.5) < 0.01

def test_zero_age_no_decay(self):
"""A hit from today should have decay ~1.0."""
hits = [self._make_hit(0.9, days_ago=0)]
result = _apply_time_decay(hits, half_life_days=90)
assert result[0]["decay"] >= 0.99

def test_disabled_when_half_life_zero(self):
"""half_life_days=0 should skip decay entirely."""
hits = [
self._make_hit(0.85, days_ago=180),
self._make_hit(0.82, days_ago=1),
]
result = _apply_time_decay(hits, half_life_days=0)
# Original order preserved, no decay field added
assert result[0]["similarity"] == 0.85
assert "decay" not in result[0]

def test_disabled_when_half_life_negative(self):
"""Negative half_life_days should skip decay."""
hits = [self._make_hit(0.9, days_ago=30)]
result = _apply_time_decay(hits, half_life_days=-1)
assert result[0]["similarity"] == 0.9
assert "decay" not in result[0]

def test_preserves_original_similarity(self):
"""Original similarity should be saved in original_similarity field."""
hits = [self._make_hit(0.9, days_ago=90)]
result = _apply_time_decay(hits, half_life_days=90)
assert result[0]["original_similarity"] == 0.9
assert result[0]["similarity"] < 0.9

def test_missing_filed_at_gets_zero_decay(self):
"""Hits without filed_at should get age=0 (no penalty)."""
hits = [{
"text": "no timestamp",
"wing": "test",
"room": "test",
"source_file": "test.md",
"similarity": 0.8,
"filed_at": "",
}]
result = _apply_time_decay(hits, half_life_days=90)
assert result[0]["decay"] >= 0.99

def test_invalid_filed_at_gets_zero_decay(self):
"""Hits with invalid filed_at should get age=0 (no penalty)."""
hits = [{
"text": "bad timestamp",
"wing": "test",
"room": "test",
"source_file": "test.md",
"similarity": 0.8,
"filed_at": "not-a-date",
}]
result = _apply_time_decay(hits, half_life_days=90)
assert result[0]["decay"] >= 0.99

def test_sort_order_after_decay(self):
"""Results should be sorted by decayed similarity, descending."""
hits = [
self._make_hit(0.95, days_ago=365), # very old
self._make_hit(0.70, days_ago=1), # recent but low similarity
self._make_hit(0.85, days_ago=30), # middle
]
result = _apply_time_decay(hits, half_life_days=90)
scores = [h["similarity"] for h in result]
assert scores == sorted(scores, reverse=True)

def test_empty_hits(self):
"""Empty list should return empty list."""
result = _apply_time_decay([], half_life_days=90)
assert result == []