Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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
7 changes: 6 additions & 1 deletion src/basic_memory/cli/commands/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -1184,8 +1184,13 @@ def set_cloud(
config.set_project_mode(name, ProjectMode.CLOUD)
if resolved_workspace_id:
config.projects[name].workspace_id = resolved_workspace_id
# Clear local path: source-of-truth for this project is now the cloud
# Clear the local path and sync metadata: the source of truth for this
# project is now the cloud. A leftover local_sync_path would read as a local
# copy and let reconciliation recreate the row this cutover just dropped.
config.projects[name].path = ""
config.projects[name].local_sync_path = None
config.projects[name].bisync_initialized = False
config.projects[name].last_sync = None
config_manager.save_config(config)

console.print(f"[green]Project '{name}' set to cloud mode[/green]")
Expand Down
7 changes: 7 additions & 0 deletions src/basic_memory/deps/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,13 @@ async def get_engine_factory(

app_config = resolve_container().config
engine, session_maker = await db.get_or_create_db(app_config.database_path)
# Deferred import for the same reason as resolve_container above: the
# services layer is reached through api.app -> routers -> deps.
from basic_memory.services.initialization import reconcile_projects_with_config_once

# No server lifespan ran initialize_app() for this process, so seed
# config.json's projects into the database here (#1334).
await reconcile_projects_with_config_once(app_config)
Comment thread
phernandez marked this conversation as resolved.
Resolved
return engine, session_maker


Expand Down
38 changes: 36 additions & 2 deletions src/basic_memory/services/initialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,9 +146,12 @@ async def initialize_database(app_config: BasicMemoryConfig) -> None:
raise


async def reconcile_projects_with_config(app_config: BasicMemoryConfig):
async def reconcile_projects_with_config(app_config: BasicMemoryConfig) -> bool:
"""Ensure all projects in config.json exist in the projects table and vice versa.

Returns True when synchronization completed, False when it failed (the
failure is logged; startup continues either way).

This uses the ProjectService's synchronize_projects method to ensure bidirectional
synchronization between the configuration file and the database.

Expand All @@ -171,10 +174,41 @@ async def reconcile_projects_with_config(app_config: BasicMemoryConfig):
project_service = ProjectService(repository=project_repository, session_maker=session_maker)
try:
await project_service.synchronize_projects()
logger.info("Projects successfully reconciled between config and database")
except Exception as e:
logger.error(f"Error during project synchronization: {e}")
logger.info("Continuing with initialization despite synchronization error")
return False
logger.info("Projects successfully reconciled between config and database")
return True


# Database paths this process has already reconciled config projects into.
_reconciled_database_paths: set[Path] = set()


async def reconcile_projects_with_config_once(app_config: BasicMemoryConfig) -> None:
"""Reconcile config projects into the database the first time a process opens it.

Trigger: a request opens the local database outside a server lifespan — the
one-shot CLI and the MCP local flow drive the API over an in-process ASGI
transport, so nothing else seeds config.json's projects into a fresh database.
Why: initialize_app() only runs for the API/MCP servers and a few CLI
commands, so a CLI-only fresh install had `main` in config.json but no
projects row, and every default-project command failed while
`project add main` refused with "already exists" (#1334, regression of #974).
Outcome: the same reconciliation the servers run, once per process; cloud and
stateless deployments stay untouched, matching initialize_app().
"""
if app_config.skip_local_initialization:
return
database_path = Path(app_config.database_path)
if database_path in _reconciled_database_paths:
return
# Only a completed reconciliation retires this path; a transient failure
# (logged inside) leaves the next request to try again rather than pinning
# a long-lived MCP process to an unseeded database.
if await reconcile_projects_with_config(app_config):
_reconciled_database_paths.add(database_path)


# Strong references for fire-and-forget startup index tasks; the event loop
Expand Down
27 changes: 25 additions & 2 deletions src/basic_memory/services/project_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
WATCH_STATUS_JSON,
ConfigManager,
ProjectEntry,
ProjectMode,
get_project_config,
ProjectConfig,
)
Expand Down Expand Up @@ -540,6 +541,17 @@ async def synchronize_projects(self) -> None: # pragma: no cover

# Add projects that exist in config but not in DB
for name, entry in config_project_names.items():
# Trigger: a cloud-only entry — cloud mode with no local sync copy
# (`add --cloud` without --local-path, or a `set-cloud`
# cutover, which clears the sync metadata).
# Why: set-cloud deliberately deletes the local row so the project's
# configured state is purely cloud; recreating it here would
# undo that cutover on every reconciliation (#1334 review). A
# cloud project with a local sync path still needs its row for
# local-side operations (`project ls --local`, watching).
# Outcome: cloud-only entries never get a local projects row.
if entry.mode == ProjectMode.CLOUD and not entry.local_sync_path:
Comment thread
phernandez marked this conversation as resolved.
Resolved
continue
Comment thread
phernandez marked this conversation as resolved.
Resolved
if name not in db_projects_by_permalink:
logger.info(f"Adding project '{name}' to database")
project_data = {
Expand Down Expand Up @@ -572,8 +584,19 @@ async def synchronize_projects(self) -> None: # pragma: no cover
# Make sure default project is synchronized between config and database
db_default = await self.repository.get_default_project(session)
config_default = self.config_manager.default_project

if db_default and db_default.name != config_default:
config_default_entry = config_project_names.get(config_default)
Comment thread
phernandez marked this conversation as resolved.
Resolved

# Trigger: the configured default is cloud-only (no local sync copy).
# Why: it has no local row by design, so the database default is only
# the local fallback and must not overwrite the user's choice.
# Outcome: config keeps the cloud default; the DB default stays local.
if (
config_default_entry is not None
and config_default_entry.mode == ProjectMode.CLOUD
and not config_default_entry.local_sync_path
):
pass
elif db_default and db_default.name != config_default:
# Update config to match DB default
logger.info(f"Updating default project in config to '{db_default.name}'")
self.config_manager.set_default_project(db_default.name)
Expand Down
56 changes: 56 additions & 0 deletions tests/cli/test_fresh_install.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
"""Regression tests for a fresh, CLI-only install (#1334, #974)."""

import os
import subprocess
from pathlib import Path

PROJECT_ROOT = Path(__file__).parent.parent.parent


def _pristine_env(home: Path) -> dict[str, str]:
"""A profile with no Basic Memory state, and none inherited from the developer or CI."""
env = {
key: value
for key, value in os.environ.items()
if not key.startswith("BASIC_MEMORY_") and key != "PYTEST_CURRENT_TEST"
}
env.update(
HOME=str(home),
USERPROFILE=str(home),
BASIC_MEMORY_HOME=str(home / "basic-memory"),
BASIC_MEMORY_CONFIG_DIR=str(home / ".basic-memory"),
BASIC_MEMORY_NO_PROMOS="1",
)
return env


def _bm(args: list[str], env: dict[str, str]) -> subprocess.CompletedProcess[str]:
return subprocess.run(
["uv", "run", "bm", *args],
capture_output=True,
text=True,
env=env,
# Guards a wedged install, not a performance budget: first run creates
# the database and runs migrations.
timeout=90,
cwd=PROJECT_ROOT,
)


def test_fresh_cli_install_can_use_the_bootstrapped_default_project(tmp_path):
"""The auto-created `main` project must exist in the database, not just config.json.

A fresh install seeds `main` into config.json. Only the API/MCP server lifespan
used to reconcile that into the projects table, so a CLI-only flow hit
"Project not found: 'main'" on every default-project command while
`project add main` refused with "already exists" (#1334).
"""
home = tmp_path / "home"
home.mkdir()
env = _pristine_env(home)

status = _bm(["status"], env)

assert status.returncode == 0, status.stderr
assert "Project not found" not in status.stdout + status.stderr
assert "main" in status.stdout
22 changes: 22 additions & 0 deletions tests/cli/test_project_set_cloud_local.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,3 +383,25 @@ def test_set_cloud_uses_default_workspace_when_no_flag(self, runner, mock_config
config_module._CONFIG_SIZE = None
updated_data = json.loads(mock_config.read_text())
assert updated_data["projects"]["research"]["workspace_id"] == "global-default-tenant-id"


def test_set_cloud_clears_sync_metadata(runner, mock_config, tmp_path):
"""A cutover leaves no local_sync_path behind, so reconciliation cannot recreate the row.

`add --cloud --local-path` entries carry a sync path; set-cloud blanked only
`path`, and a surviving local_sync_path read as a local copy (#1334 review).
"""
config = json.loads(mock_config.read_text())
config["projects"]["research"].update(
{"local_sync_path": str(tmp_path / "research"), "bisync_initialized": True}
)
mock_config.write_text(json.dumps(config, indent=2))

result = runner.invoke(app, ["project", "set-cloud", "research"])

assert result.exit_code == 0, result.stdout
entry = json.loads(mock_config.read_text())["projects"]["research"]
assert entry["mode"] == "cloud"
assert entry["path"] == ""
assert entry["local_sync_path"] is None
assert entry["bisync_initialized"] is False
13 changes: 13 additions & 0 deletions tests/mcp/test_async_client_modes.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from basic_memory.cli.auth import CLIAuth
from basic_memory.config import ProjectMode
from basic_memory.mcp import async_client as async_client_module
from basic_memory.services import initialization
from basic_memory.mcp.async_client import (
get_client,
get_cloud_control_plane_client,
Expand Down Expand Up @@ -78,7 +79,13 @@ async def fake_get_or_create_db(db_path):
calls.append(db_path)
return engine, session_maker

async def skip_project_reconciliation(app_config):
"""The engine/session maker here are stand-ins; reconciliation needs a real database."""

monkeypatch.setattr(db, "get_or_create_db", fake_get_or_create_db)
monkeypatch.setattr(
initialization, "reconcile_projects_with_config_once", skip_project_reconciliation
)

try:
async with get_client() as client:
Expand Down Expand Up @@ -238,7 +245,13 @@ async def fake_get_or_create_db(db_path):
calls.append(db_path)
return engine, session_maker

async def skip_project_reconciliation(app_config):
"""The engine/session maker here are stand-ins; reconciliation needs a real database."""

monkeypatch.setattr(db, "get_or_create_db", fake_get_or_create_db)
monkeypatch.setattr(
initialization, "reconcile_projects_with_config_once", skip_project_reconciliation
)

first_context = get_client()
second_context = get_client()
Expand Down
19 changes: 13 additions & 6 deletions tests/mcp/test_project_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -2407,6 +2407,7 @@ class TestGetProjectClientRoutingOrder:
@pytest.mark.asyncio
async def test_local_flag_skips_workspace_resolution(self, config_manager, monkeypatch):
"""--local flag should never trigger workspace resolution, even for cloud projects."""
import basic_memory.mcp.project_context as project_context
from basic_memory.mcp.project_context import get_project_client
from basic_memory.config import ProjectEntry, ProjectMode

Expand All @@ -2422,15 +2423,21 @@ async def test_local_flag_skips_workspace_resolution(self, config_manager, monke
monkeypatch.setenv("BASIC_MEMORY_FORCE_LOCAL", "true")
monkeypatch.delenv("BASIC_MEMORY_FORCE_CLOUD", raising=False)

# Should not raise "Multiple workspaces" — it should skip workspace entirely
# It will fail at project validation (no API running), which proves routing worked
with pytest.raises(Exception) as exc_info:
# Any workspace lookup is the failure being guarded against.
async def fail_on_workspace_lookup(*args, **kwargs):
raise AssertionError("--local must not resolve workspaces")

monkeypatch.setattr(project_context, "get_available_workspaces", fail_on_workspace_lookup)

# The local ASGI client seeds config projects into the database (#1334)
# but deliberately skips cloud-mode entries, so local validation misses —
# and that miss, not a workspace error, is what proves routing stayed local.
from fastmcp.exceptions import ToolError

with pytest.raises(ToolError, match="Project not found: 'cloud-proj'"):
async with get_project_client(project="cloud-proj"):
pass

# The error should NOT be about workspaces
assert "workspace" not in str(exc_info.value).lower()

@pytest.mark.asyncio
async def test_local_route_clears_stale_cached_workspace(self, config_manager, monkeypatch):
"""A previous cloud workspace must not decorate later local memory URLs."""
Expand Down
64 changes: 64 additions & 0 deletions tests/services/test_initialization_reconcile_once.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
"""The once-per-process project reconciliation used by the CLI's API path (#1334)."""

import pytest

from basic_memory.services import initialization


@pytest.mark.asyncio
async def test_reconcile_projects_with_config_once_runs_once_per_database(app_config, monkeypatch):
"""Every local ASGI request hits the dependency; only the first may reconcile."""
calls = []

async def fake_reconcile(config):
calls.append(config)
return True

monkeypatch.setattr(initialization, "reconcile_projects_with_config", fake_reconcile)
monkeypatch.setattr(initialization, "_reconciled_database_paths", set())

await initialization.reconcile_projects_with_config_once(app_config)
await initialization.reconcile_projects_with_config_once(app_config)

assert calls == [app_config]


@pytest.mark.asyncio
async def test_reconcile_projects_with_config_once_skips_cloud_deployments(app_config, monkeypatch):
"""Cloud/stateless deployments own their project rows; reconciling would delete them."""
calls = []

async def fake_reconcile(config):
calls.append(config)
return True

monkeypatch.setattr(initialization, "reconcile_projects_with_config", fake_reconcile)
monkeypatch.setattr(initialization, "_reconciled_database_paths", set())
monkeypatch.setenv("BASIC_MEMORY_CLOUD_MODE", "true")
assert app_config.skip_local_initialization

await initialization.reconcile_projects_with_config_once(app_config)

assert calls == []


@pytest.mark.asyncio
async def test_reconcile_projects_with_config_once_retries_after_a_failed_attempt(
app_config, monkeypatch
):
"""A transient failure must not pin a long-lived process to an unseeded database."""
outcomes = iter([False, True])
calls = []

async def fake_reconcile(config):
calls.append(config)
return next(outcomes)

monkeypatch.setattr(initialization, "reconcile_projects_with_config", fake_reconcile)
monkeypatch.setattr(initialization, "_reconciled_database_paths", set())

await initialization.reconcile_projects_with_config_once(app_config)
await initialization.reconcile_projects_with_config_once(app_config)
await initialization.reconcile_projects_with_config_once(app_config)

assert calls == [app_config, app_config], "retry once after failure, then stop"
Loading
Loading