Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
6 changes: 6 additions & 0 deletions src/basic_memory/api/v2/routers/search_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
SemanticSearchDisabledError,
)
from basic_memory.schemas.search import SearchQuery, SearchResponse, SearchRetrievalMode
from basic_memory.services.search_guidance import unspaced_script_query_hint

# App registration mounts this router at /v2/projects/{project_id}.
router = APIRouter(tags=["search"])
Expand Down Expand Up @@ -243,6 +244,11 @@ async def search(
total=total,
total_is_exact=exact_count_available,
has_more=has_more,
# A later empty page is pagination, not evidence of a compound miss.
# Guidance adds no retrieval pass and makes no index-completeness claim.
query_hint=unspaced_script_query_hint(query)
if page == 1 and not search_results and total == 0
else None,
# None, not False, when nothing was asked: an ordinary search
# payload stays exactly what it was before valid time existed.
temporal_applied=True if temporal_requested else None,
Expand Down
9 changes: 9 additions & 0 deletions src/basic_memory/mcp/tools/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,7 @@ def _format_search_markdown(
return (
f"No results found for '{query or ''}' in project '{project}'. "
f"Try broader or different terms, or {suggestion}."
+ (f"\n\n{result.query_hint}" if result.query_hint else "")
)

parts = []
Expand Down Expand Up @@ -663,6 +664,7 @@ async def _search_all_projects(
# How many projects actually answered. A leg that fails is skipped with a warning,
# so without this the caller cannot tell "no note matched" from "nothing ran".
projects_answered = 0
query_hint: str | None = None

# Trigger: caller asked for an account-wide search.
# Why: project_id (external UUID) routes through the cloud v2 API path,
Expand Down Expand Up @@ -729,6 +731,8 @@ async def _search_all_projects(
continue

projects_answered += 1
if isinstance(results.get("query_hint"), str):
query_hint = results["query_hint"]
raw_results = _raw_results_from_search_payload(results)
total += _result_total(results, raw_results)
total_is_exact = total_is_exact and _result_total_is_exact(results)
Expand Down Expand Up @@ -763,6 +767,11 @@ async def _search_all_projects(
response = SearchResponse.model_validate(
{
"results": paged_results,
# Only propagate query guidance when every project answered and the
# aggregate is empty; one empty leg must not label a successful search.
"query_hint": query_hint
if requested_page == 1 and not merged_results and projects_answered == len(project_refs)
else None,
"current_page": requested_page,
"page_size": requested_page_size,
"total": total,
Expand Down
4 changes: 4 additions & 0 deletions src/basic_memory/schemas/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,10 @@ class SearchResponse(BaseModel):
description="Whether total is an exact count that clients can use for pagination",
)
has_more: bool = False
query_hint: str | None = Field(
default=None,
description="Actionable guidance for an empty query, not an index health status",
)
# Version-skew guard. SearchQuery ignores unknown fields, so a client that sends a
# valid-time filter to a server predating SPEC-82 would receive unfiltered results
# that look filtered -- silently including the undated sources the filter excludes.
Expand Down
36 changes: 36 additions & 0 deletions src/basic_memory/services/search_guidance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
"""Actionable query guidance without changing retrieval or claiming index completeness."""

import unicodedata

from basic_memory.repository.script_ngrams import script_runs
from basic_memory.schemas.search import SearchQuery, SearchRetrievalMode


def unspaced_script_query_hint(query: SearchQuery) -> str | None:
"""Explain a plain compound's lexical semantics after an empty first page."""
if query.retrieval_mode not in (SearchRetrievalMode.FTS, SearchRetrievalMode.HYBRID):
return None
if not query.text or query.title or query.permalink or query.permalink_match:
return None
text = (
unicodedata.normalize("NFKC", query.text.strip())
.replace("\u200c", "")
.replace("\u200d", "")
)
runs = script_runs(text)
# One run must consume the entire query, so quotes, operators and mixed words
# cannot masquerade as a compound. Count retrieval's units: attached marks and
# join controls must neither veto a word nor pad it past the four-unit guard.
if (
len(runs) != 1
or len(runs[0]) < 4
or "".join(runs[0]) != text
or any(unicodedata.category(char).startswith("N") for char in text)
):
return None
return (
"Unspaced text in this script is searched as a continuous sequence, not automatically split "
"into words. Try a shorter word from your query on its own, or add spaces between "
"the words you intend to search. An empty result does not rule out notes containing "
"only part of the compound."
)
101 changes: 101 additions & 0 deletions tests/api/v2/test_cjk_search_guidance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
"""CJK misses remain exact, but expose an actionable recovery path (#1533)."""

from typing import Literal

import pytest
from sqlalchemy import text
from httpx import AsyncClient

from basic_memory import db


@pytest.mark.asyncio
async def test_unspaced_compound_miss_has_actionable_hint(
client: AsyncClient, v2_project_url: str, entity_repository, search_service
):
async with db.scoped_session(search_service.session_maker) as session:
entity = await entity_repository.create(
session,
{
"title": "Deployment diary",
"note_type": "note",
"content_type": "text/markdown",
"file_path": "notes/rime.md",
"permalink": "notes/rime",
},
)
await search_service.index_entity_data(entity, content="09-07 雾凇词库部署时实测")

# This pins the actual backend behavior, rather than assuming the issue's
# older unicode61-only index is still the current implementation.
for query in ("雾凇", "词库", "雾凇词库部署"):
response = await client.post(f"{v2_project_url}/search/", json={"text": query})
assert response.status_code == 200
assert len(response.json()["results"]) == 1
assert response.json().get("query_hint") is None

response = await client.post(f"{v2_project_url}/search/", json={"text": "雾凇拼音"})
assert response.status_code == 200
payload = response.json()
assert payload["results"] == []
assert payload["total"] == 0
assert payload["total_is_exact"] is True
assert payload["has_more"] is False
assert "shorter word" in payload["query_hint"]
assert "spaces" in payload["query_hint"]

later_page = await client.post(
f"{v2_project_url}/search/", json={"text": "雾凇拼音"}, params={"page": 2}
)
assert later_page.json().get("query_hint") is None

# The typed MCP client and formatter must preserve the API's guidance in
# both output formats, including compact discovery responses.
from basic_memory.mcp.tools.search import search_notes

async with db.scoped_session(search_service.session_maker) as session:
await session.execute(
text("UPDATE project SET last_indexed_at = CURRENT_TIMESTAMP WHERE id = :id"),
{"id": entity.project_id},
)
formats: tuple[Literal["text", "json"], ...] = ("text", "json")
for output_format in formats:
result = await search_notes(
query="雾凇拼音", search_type="text", output_format=output_format, compact=True
)
if isinstance(result, str):
assert "shorter word" in result
else:
assert "shorter word" in result["query_hint"]


@pytest.mark.asyncio
@pytest.mark.parametrize("output_format", ["text", "json"])
async def test_unindexed_cjk_miss_keeps_index_guidance(
client, test_project, session_maker, config_home, output_format
):
from basic_memory.mcp.tools.search import search_notes

notes_dir = config_home / "notes"
notes_dir.mkdir(exist_ok=True)
(notes_dir / "unindexed.md").write_text("# Diary\n\n雾凇词库部署\n", encoding="utf-8")
async with db.scoped_session(session_maker) as session:
await session.execute(
text("UPDATE project SET last_indexed_at = NULL WHERE id = :id"),
{"id": test_project.id},
)
result = await search_notes(
project=test_project.name, query="雾凇拼音", search_type="text", output_format=output_format
)
assert isinstance(result, str)
assert result.startswith("# Project Index Required")
assert "shorter word" not in result


@pytest.mark.asyncio
@pytest.mark.parametrize("query", ["𠮷野家情報", "漢\ufe00字情報", "น้ำแข็ง", "မြန်မာစာ"])
async def test_script_unit_miss_has_guidance(client: AsyncClient, v2_project_url: str, query: str):
response = await client.post(f"{v2_project_url}/search/", json={"text": query})
assert response.status_code == 200
assert response.json()["results"] == []
assert "shorter word" in response.json()["query_hint"]
71 changes: 71 additions & 0 deletions tests/mcp/tools/test_cjk_search_guidance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
"""Account search carries query guidance only for a complete, empty first page."""

import importlib
from typing import Literal
from unittest.mock import AsyncMock

import pytest


@pytest.mark.asyncio
@pytest.mark.parametrize("case", ["empty", "hit", "failed", "later"])
@pytest.mark.parametrize("output_format", ["text", "json"])
async def test_fanout_query_hint(monkeypatch, case: str, output_format: Literal["text", "json"]):
search = importlib.import_module("basic_memory.mcp.tools.search")
monkeypatch.setattr(
search,
"_load_search_project_refs",
AsyncMock(
return_value=[
{"project": "one", "project_id": None},
{"project": "two", "project_id": None},
]
),
)
empty = {
"results": [],
"total": 0,
"total_is_exact": True,
"query_hint": "Try a shorter word from your query.",
}
second: dict[str, object] | str = empty
if case == "hit":
second = {
"results": [
{
"title": "Match",
"type": "entity",
"score": 1.0,
"file_path": "note.md",
"permalink": "note",
}
],
"total": 1,
"total_is_exact": True,
}
elif case == "failed":
second = "# Search Failed - Access Error"
monkeypatch.setattr(search, "search_notes", AsyncMock(side_effect=[empty, second]))
result = await search._search_all_projects(
query="雾凇拼音",
page=2 if case == "later" else 1,
page_size=10,
search_type="text",
output_format=output_format,
note_types=[],
entity_types=[],
categories=[],
after_date=None,
metadata_filters=None,
tags=None,
status=None,
min_similarity=None,
valid_at=None,
valid_overlaps=None,
time_kind=None,
context=None,
)
if isinstance(result, str):
assert ("shorter word" in result) == (case == "empty")
else:
assert (result.get("query_hint") is not None) == (case == "empty")
56 changes: 56 additions & 0 deletions tests/services/test_search_guidance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
"""Query guidance preserves explicit intent and never runs another retrieval."""

import pytest

from basic_memory.schemas.search import SearchQuery, SearchRetrievalMode
from basic_memory.services.search_guidance import unspaced_script_query_hint


@pytest.mark.parametrize(
"text",
[
"雾凇拼音",
" 雾凇拼音 ",
"日本語検索",
"한국어검색",
"𠮷野家情報",
"人々生活",
"ㄅㄆㄇㄈ",
"ㇰㇱㇲㇳ",
"น้ำแข็ง",
"မြန်မာစာ",
"漢\ufe00字情報",
"雾凇\u200d拼音",
"雾凇\u200c拼音",
],
)
@pytest.mark.parametrize("mode", [SearchRetrievalMode.FTS, SearchRetrievalMode.HYBRID])
def test_plain_compounds_receive_guidance(text: str, mode: SearchRetrievalMode):
assert unspaced_script_query_hint(SearchQuery(text=text, retrieval_mode=mode))


@pytest.mark.parametrize(
"query",
[
SearchQuery(),
SearchQuery(text="雾凇"),
SearchQuery(text="漢\ufe00字\ufe00情"),
SearchQuery(text="漢\u200d字情"),
SearchQuery(text="๑๒๓๔"),
SearchQuery(text="雾凇,拼音"),
SearchQuery(text="雾凇 拼音"),
SearchQuery(text='"雾凇拼音"'),
SearchQuery(text="雾凇 AND 拼音"),
SearchQuery(text="雾凇拼音*"),
SearchQuery(text="雾凇拼音1"),
SearchQuery(text="rime雾凇拼音"),
SearchQuery(text="plainword"),
SearchQuery(text="雾凇拼音", retrieval_mode=SearchRetrievalMode.VECTOR),
SearchQuery(title="雾凇拼音"),
SearchQuery(text="雾凇拼音", title="title"),
SearchQuery(text="雾凇拼音", permalink="note"),
SearchQuery(text="雾凇拼音", permalink_match="note*"),
],
)
def test_other_query_contracts_do_not_receive_compound_guidance(query: SearchQuery):
assert unspaced_script_query_hint(query) is None
Loading