diff --git a/src/basic_memory/mcp/index_readiness.py b/src/basic_memory/mcp/index_readiness.py index 7eebc4c01..3fd7bb3e8 100644 --- a/src/basic_memory/mcp/index_readiness.py +++ b/src/basic_memory/mcp/index_readiness.py @@ -3,21 +3,36 @@ from httpx import AsyncClient from basic_memory.schemas.project_info import ProjectItem +from basic_memory.schemas import ProjectIndexStatusResponse from basic_memory.schemas.project_readiness import ProjectIndexPhase from basic_memory.utils import shell_command -async def project_index_required(client: AsyncClient, project: ProjectItem) -> str | None: +async def project_index_status( + client: AsyncClient, project: ProjectItem +) -> ProjectIndexStatusResponse: + """Fetch the project's index status, for callers that need more than the guidance.""" + # Match the tools' deferred client imports to keep CLI startup lightweight. + from basic_memory.mcp.clients.project import ProjectClient + + return await ProjectClient(client).get_status(project.external_id) + + +async def project_index_required( + client: AsyncClient, + project: ProjectItem, + *, + status: ProjectIndexStatusResponse | None = None, +) -> str | None: """Distinguish an unsearched project from an honest empty result. Call only after an empty read: the status endpoint observes project files, so successful reads should not pay for an extra directory scan. Let status failures propagate rather than interpreting unknown readiness as an empty index. + A caller that already fetched the status passes it to avoid a second request. """ - # Match the tools' deferred client imports to keep CLI startup lightweight. - from basic_memory.mcp.clients.project import ProjectClient - - status = await ProjectClient(client).get_status(project.external_id) + if status is None: + status = await project_index_status(client, project) readiness = status.readiness if readiness.phase is not ProjectIndexPhase.NEVER_INDEXED: return None diff --git a/src/basic_memory/mcp/tools/recent_activity.py b/src/basic_memory/mcp/tools/recent_activity.py index 451446b17..81f866642 100644 --- a/src/basic_memory/mcp/tools/recent_activity.py +++ b/src/basic_memory/mcp/tools/recent_activity.py @@ -11,7 +11,7 @@ from fastmcp import Context from loguru import logger -from basic_memory.mcp.index_readiness import project_index_required +from basic_memory.mcp.index_readiness import project_index_required, project_index_status from basic_memory.mcp.project_context import get_project_client from basic_memory.mcp.tool_params import ItemKind, search_item_types from basic_memory.mcp.tools.utils import call_get @@ -74,9 +74,14 @@ async def recent_activity_page( ) activity_data = GraphContext.model_validate(response.json()) - # Do not offer first-note onboarding before the project was indexed. + # Do not offer first-note onboarding before the project was indexed. The same + # status response says whether the project holds any notes, so one request + # answers both questions. + project_has_notes = True if not activity_data.results: - guidance = await project_index_required(client, active_project) + status = await project_index_status(client, active_project) + project_has_notes = status.readiness.indexed_entities > 0 + guidance = await project_index_required(client, active_project, status=status) if guidance is not None: return guidance @@ -97,6 +102,7 @@ async def recent_activity_page( page=page, project_id=active_project.external_id, type_filter_applied=bool(items), + project_has_notes=project_has_notes, ) @@ -125,12 +131,14 @@ def _format_project_output( page: int, project_id: str, type_filter_applied: bool, + project_has_notes: bool, ) -> str: """Format one project's recent activity as human-readable text. `project_id` is the project's route-safe external id. Onboarding examples use it instead of the display name so a model following them cannot land in a different - same-named project in another cloud workspace. + same-named project in another cloud workspace. `project_has_notes` is only + consulted for an empty unfiltered first page; it gates first-note onboarding. """ lines = [f"## Recent Activity: {project_name} ({timeframe})"] @@ -156,22 +164,27 @@ def _format_project_output( lines.append(f"\nNo recent activity in '{project_name}' within {timeframe}.") # Recent activity is the orientation call a model makes at session start, so an empty - # result is the natural moment to help. Stay offer-not-act, and cover both a brand-new - # (empty) knowledge base and an established one that is merely quiet in this window. + # result is the natural moment to help. Stay offer-not-act. Onboarding is for a project + # with no notes; an established project that is merely quiet in this window only gets + # the widen-or-search hint, so the model does not offer its user a "first note". # Examples name the external id: names collide across cloud workspaces, ids do not. route = f'project="{project_id}"' lines.append("") + if not project_has_notes: + lines.append( + "If the user is just getting started and has no notes yet, briefly explain that " + "Basic Memory keeps notes that persist across conversations and are shared between " + "the user and their AI, then offer to save something useful from this conversation " + "as their first note — wait for them to agree before writing:" + ) + lines.append("```") + lines.append(f'bm_write({route}, title="...", content="...", directory="notes")') + lines.append("```") + lead = "Otherwise, widen" + else: + lead = "Widen" lines.append( - "If the user is just getting started and has no notes yet, briefly explain that " - "Basic Memory keeps notes that persist across conversations and are shared between " - "the user and their AI, then offer to save something useful from this conversation " - "as their first note — wait for them to agree before writing:" - ) - lines.append("```") - lines.append(f'bm_write({route}, title="...", content="...", directory="notes")') - lines.append("```") - lines.append( - f"Otherwise, widen the window with " + f"{lead} the window with " f'bm_project(command="recent", {route}, since="30d") or find a topic ' f'with bm_search({route}, query="...").' ) diff --git a/tests/mcp/test_first_connect_onboarding.py b/tests/mcp/test_first_connect_onboarding.py index 4c2d6718f..201a95b2b 100644 --- a/tests/mcp/test_first_connect_onboarding.py +++ b/tests/mcp/test_first_connect_onboarding.py @@ -8,7 +8,10 @@ - the `getting_started` prompt. """ +from datetime import datetime, timezone + import pytest +from sqlalchemy import text from basic_memory.mcp.prompts.getting_started import getting_started from basic_memory.mcp.server import mcp @@ -57,6 +60,62 @@ async def test_recent_activity_empty_project_offers_first_note( assert 'since="30d"' in result +@pytest.mark.asyncio +async def test_recent_activity_quiet_populated_project_has_no_first_note_offer( + client, test_project, indexed_project, session_maker +): + """A project with notes, none changed in the window, gets the hint but no onboarding.""" + await bm_write( + project=test_project.name, + title="Old note", + content="This project already contains useful context.", + directory="notes", + ) + # Move the note out of the 7d window in both the entity table and the search index. + old = datetime(2020, 1, 1, tzinfo=timezone.utc) + async with session_maker() as session: + await session.execute( + text("UPDATE entity SET created_at = :old, updated_at = :old"), {"old": old} + ) + await session.execute( + text("UPDATE search_index SET created_at = :old, updated_at = :old"), {"old": old} + ) + await session.commit() + + result = await bm_project(command="recent", project=test_project.name, since="7d") # pyright: ignore[reportGeneralTypeIssues] + + assert isinstance(result, str) + assert "No recent activity" in result + assert "If the user is just getting started" not in result + assert "first note" not in result + assert "bm_write(" not in result + assert f'bm_project(command="recent", project="{test_project.external_id}"' in result + assert 'since="30d"' in result + assert f'bm_search(project="{test_project.external_id}"' in result + + +@pytest.mark.asyncio +async def test_recent_activity_empty_path_makes_one_status_request( + client, test_project, indexed_project, monkeypatch +): + """The note count comes from the status call the empty path already made.""" + from basic_memory.mcp.clients.project import ProjectClient + + calls = 0 + original = ProjectClient.get_status + + async def counting(self, project_external_id): + nonlocal calls + calls += 1 + return await original(self, project_external_id) + + monkeypatch.setattr(ProjectClient, "get_status", counting) + + await bm_project(command="recent", project=test_project.name, since="7d") # pyright: ignore[reportGeneralTypeIssues] + + assert calls == 1 + + @pytest.mark.asyncio async def test_recent_activity_populated_project_has_no_first_note_offer( client, test_project, test_graph diff --git a/tests/mcp/test_tool_bm_project_recent.py b/tests/mcp/test_tool_bm_project_recent.py index 6b35cffea..840d26784 100644 --- a/tests/mcp/test_tool_bm_project_recent.py +++ b/tests/mcp/test_tool_bm_project_recent.py @@ -194,7 +194,13 @@ def _entity_result(index: int, title: str) -> ContextResult: ) -def _format(activity: GraphContext, *, page: int = 1, type_filter_applied: bool = False) -> str: +def _format( + activity: GraphContext, + *, + page: int = 1, + type_filter_applied: bool = False, + project_has_notes: bool = False, +) -> str: return _format_project_output( "proj", activity, @@ -202,9 +208,30 @@ def _format(activity: GraphContext, *, page: int = 1, type_filter_applied: bool page=page, project_id="ext-123", type_filter_applied=type_filter_applied, + project_has_notes=project_has_notes, ) +def test_empty_project_offers_first_note(): + out = _format(_empty_graph(), project_has_notes=False) + + assert "No recent activity in 'proj' within 7d." in out + assert "wait for them to agree" in out + assert 'bm_write(project="ext-123"' in out + assert "Otherwise, widen the window" in out + + +def test_quiet_populated_project_has_hint_only(): + out = _format(_empty_graph(), project_has_notes=True) + + assert "No recent activity in 'proj' within 7d." in out + assert "If the user is just getting started" not in out + assert "first note" not in out + assert "bm_write(" not in out + assert 'bm_project(command="recent", project="ext-123", since="30d")' in out + assert 'bm_search(project="ext-123", query="...")' in out + + def test_filtered_empty_page_has_no_first_note_offer(): out = _format(_empty_graph(), type_filter_applied=True)