From ae86295da85acc36b1bed1c5ba6ee5c7dc960fff Mon Sep 17 00:00:00 2001 From: matrix9neonebuchadnezzar2199-sketch Date: Thu, 9 Apr 2026 15:15:43 +0900 Subject: [PATCH 1/2] =?UTF-8?q?feat:=20time-decay=20scoring=20for=20search?= =?UTF-8?q?=20results=20=E2=80=94=20prioritize=20recent=20memories=20(#331?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- mempalace/config.py | 5 ++ mempalace/mcp_server.py | 4 +- mempalace/searcher.py | 58 +++++++++++++++++++- tests/test_time_decay.py | 111 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 176 insertions(+), 2 deletions(-) create mode 100644 tests/test_time_decay.py diff --git a/mempalace/config.py b/mempalace/config.py index 5a736509f9..3853d99737 100644 --- a/mempalace/config.py +++ b/mempalace/config.py @@ -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) diff --git a/mempalace/mcp_server.py b/mempalace/mcp_server.py index 2169255525..89e8a7b367 100644 --- a/mempalace/mcp_server.py +++ b/mempalace/mcp_server.py @@ -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, ) @@ -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"], }, diff --git a/mempalace/searcher.py b/mempalace/searcher.py index 163abd88c5..c8309060d5 100644 --- a/mempalace/searcher.py +++ b/mempalace/searcher.py @@ -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).""" @@ -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. @@ -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, } diff --git a/tests/test_time_decay.py b/tests/test_time_decay.py new file mode 100644 index 0000000000..8646fccfcf --- /dev/null +++ b/tests/test_time_decay.py @@ -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 == [] From dd4aa38953297fb159ab7bc4b348bda6b4219b70 Mon Sep 17 00:00:00 2001 From: matrix9neonebuchadnezzar2199-sketch <あなたのメールアドレス> Date: Thu, 9 Apr 2026 20:09:15 +0900 Subject: [PATCH 2/2] feat: include half_life_days in search response metadata (#337) - Addresses @web3guru888 suggestion to expose the applied half-life - Response now includes half_life_days (int) when time_decay is true, None when false Made-with: Cursor --- mempalace/searcher.py | 8 +++--- tests/test_time_decay.py | 57 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 61 insertions(+), 4 deletions(-) diff --git a/mempalace/searcher.py b/mempalace/searcher.py index c8309060d5..68253914a6 100644 --- a/mempalace/searcher.py +++ b/mempalace/searcher.py @@ -193,16 +193,18 @@ def search_memories( ) # Apply time-decay scoring + half_life_days = None if time_decay: try: - half_life = MempalaceConfig().time_decay_half_life_days + half_life_days = MempalaceConfig().time_decay_half_life_days except Exception: - half_life = 90 - hits = _apply_time_decay(hits, half_life) + half_life_days = 90 + hits = _apply_time_decay(hits, half_life_days) return { "query": query, "filters": {"wing": wing, "room": room}, "time_decay": time_decay, + "half_life_days": half_life_days if time_decay else None, "results": hits, } diff --git a/tests/test_time_decay.py b/tests/test_time_decay.py index 8646fccfcf..b6d10eef3a 100644 --- a/tests/test_time_decay.py +++ b/tests/test_time_decay.py @@ -1,10 +1,11 @@ """Tests for time-decay scoring feature (#331).""" from datetime import datetime, timezone, timedelta +from unittest.mock import MagicMock import pytest -from mempalace.searcher import _apply_time_decay +from mempalace.searcher import _apply_time_decay, search_memories class TestApplyTimeDecay: @@ -109,3 +110,57 @@ def test_empty_hits(self): """Empty list should return empty list.""" result = _apply_time_decay([], half_life_days=90) assert result == [] + + +class TestSearchMemoriesResponse: + """search_memories() response metadata for time decay.""" + + def test_response_includes_half_life_days_when_decay_enabled(self, monkeypatch): + """When time_decay is True, response includes half_life_days as the configured value.""" + mock_col = MagicMock() + mock_col.query.return_value = { + "documents": [["hello"]], + "metadatas": [ + [ + { + "wing": "w", + "room": "r", + "source_file": "test.md", + "filed_at": datetime.now(timezone.utc).isoformat(), + } + ] + ], + "distances": [[0.1]], + } + mock_client = MagicMock() + mock_client.get_collection.return_value = mock_col + monkeypatch.setattr( + "mempalace.searcher.chromadb.PersistentClient", lambda path: mock_client + ) + + cfg = MagicMock() + cfg.time_decay_half_life_days = 90 + monkeypatch.setattr("mempalace.searcher.MempalaceConfig", lambda: cfg) + + result = search_memories("q", "/fake/path", time_decay=True) + assert "half_life_days" in result + assert result["time_decay"] is True + assert result["half_life_days"] == 90 + + def test_half_life_days_none_when_decay_disabled(self, monkeypatch): + """When time_decay is False, half_life_days is None.""" + mock_col = MagicMock() + mock_col.query.return_value = { + "documents": [["hello"]], + "metadatas": [[{"wing": "w", "room": "r", "source_file": "test.md"}]], + "distances": [[0.1]], + } + mock_client = MagicMock() + mock_client.get_collection.return_value = mock_col + monkeypatch.setattr( + "mempalace.searcher.chromadb.PersistentClient", lambda path: mock_client + ) + + result = search_memories("q", "/fake/path", time_decay=False) + assert result["time_decay"] is False + assert result["half_life_days"] is None